{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \");\n\t\tCommunityBoardHandler.separateAndSend(html.toString(), activeChar);\n\t}"},"code_wo_comment":{"kind":"string","value":"private void clanList(L2PcInstance activeChar, int index)\n\t{\n\t\tif (index < 1)\n\t\t{\n\t\t\tindex = 1;\n\t\t}\n\t\n\t\tfinal StringBuilder html = StringUtil.startAppend(2000, \"

&nbsp; CLAN COMMUNITY
[GO TO MY CLAN]&nbsp;&nbsp;

CLAN NAMECLAN LEADERCLAN LEVELCLAN MEMBERS
\");\n\t\tint i = 0;\n\t\tfor (L2Clan cl : ClanTable.getInstance().getClans())\n\t\t{\n\t\t\tif (i > ((index + 1) * 7))\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (i++ >= ((index - 1) * 7))\n\t\t\t{\n\t\t\t\tStringUtil.append(html, \"
\", cl.getName(), \"\", cl.getLeaderName(), \"\", String.valueOf(cl.getLevel()), \"\", String.valueOf(cl.getMembersCount()), \"
\");\n\t\t\t}\n\t\t}\n\t\thtml.append(\"\");\n\t\tif (index == 1)\n\t\t{\n\t\t\thtml.append(\"\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tStringUtil.append(html, \"\");\n\t\t}\n\t\ti = 0;\n\t\tint nbp = ClanTable.getInstance().getClanCount() / 8;\n\t\tif ((nbp * 8) != ClanTable.getInstance().getClanCount())\n\t\t{\n\t\t\tnbp++;\n\t\t}\n\t\tfor (i = 1; i <= nbp; i++)\n\t\t{\n\t\t\tif (i == index)\n\t\t\t{\n\t\t\t\tStringUtil.append(html, \"\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tStringUtil.append(html, \"\");\n\t\t\t}\n\t\t}\n\t\tif (index == nbp)\n\t\t{\n\t\t\thtml.append(\"\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tStringUtil.append(html, \"\");\n\t\t}\n\t\thtml.append(\"
\", String.valueOf(i), \" \", String.valueOf(i), \"
\" +\n\t\n\t\t\"


\");\n\t\tCommunityBoardHandler.separateAndSend(html.toString(), activeChar);\n\t}"},"cleancode":{"kind":"string","value":"private void clanlist(l2pcinstance activechar, int index) { if (index < 1) { index = 1; } final stringbuilder html = stringutil.startappend(2000, \"

&nbsp; clan community
[go to my clan]&nbsp;&nbsp;

clan nameclan leaderclan levelclan members
\"); int i = 0; for (l2clan cl : clantable.getinstance().getclans()) { if (i > ((index + 1) * 7)) { break; } if (i++ >= ((index - 1) * 7)) { stringutil.append(html, \"
\", cl.getname(), \"\", cl.getleadername(), \"\", string.valueof(cl.getlevel()), \"\", string.valueof(cl.getmemberscount()), \"
\"); } } html.append(\"\"); if (index == 1) { html.append(\"\"); } else { stringutil.append(html, \"\"); } i = 0; int nbp = clantable.getinstance().getclancount() / 8; if ((nbp * 8) != clantable.getinstance().getclancount()) { nbp++; } for (i = 1; i <= nbp; i++) { if (i == index) { stringutil.append(html, \"\"); } else { stringutil.append(html, \"\"); } } if (index == nbp) { html.append(\"\"); } else { stringutil.append(html, \"\"); } html.append(\"
\", string.valueof(i), \" \", string.valueof(i), \"
\" + \"


\"); communityboardhandler.separateandsend(html.tostring(), activechar); }"},"repo":{"kind":"string","value":"RollingSoftware/L2J_HighFive_Hardcore"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":208,"cells":{"id":{"kind":"number","value":23375,"string":"23,375"},"original_code":{"kind":"string","value":"public void sendErrorEmail(RequestCycle cycle, Exception ex, IRequestLogger logger) {\n try {\n String customer = Utils.getCustomer();\n Url url = cycle.getRequest().getUrl();\n Url clientUrl = cycle.getRequest().getClientUrl();\n String exStr = ExceptionUtils.getStackTrace(ex);\n String fullUrl = cycle.getUrlRenderer().renderFullUrl(url);\n int currUserId = 0;\n RequestData currRd = logger.getCurrentRequest();\n String currSessId = Session.get().getId();\n SessionData sd = null;\n if(currSessId != null) {\n SessionData[] sessions = logger.getLiveSessions();\n for(SessionData s : sessions) {\n if(s.getSessionId().equals(currSessId)) {\n sd = s;\n break;\n }\n }\n }\n String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd);\n StringBuilder currSessStr = new StringBuilder();\n if(sd != null) {\n currSessStr.append(\"id:\").append(sd.getSessionId()).append('\\n');\n currSessStr.append(\"requestCount:\").append(sd.getNumberOfRequests()).append('\\n');\n currSessStr.append(\"requestsTime:\").append(sd.getTotalTimeTaken()).append('\\n');\n currSessStr.append(\"sessionSize:\").append(Bytes.bytes(sd.getSessionSize())).append('\\n');\n currSessStr.append(\"sessionInfo:\").append(sd.getSessionInfo()).append('\\n');\n currSessStr.append(\"startDate:\").append(sd.getStartDate()).append('\\n');\n currSessStr.append(\"lastRequestTime:\").append(sd.getLastActive()).append('\\n');\n currSessStr.append(\"numberOfRequests:\").append(sd.getNumberOfRequests()).append('\\n');\n currSessStr.append(\"totalTimeTaken:\").append(sd.getTotalTimeTaken()).append(\"\\n\\n\\n\");\n }\n currSessStr.append(\"Requests: \\n\");\n ((CustomRequestLogger)logger).getRequests(currSessStr);\n String template = \"param1: %s \\n url: %s \\n client url: %s \\n user: %s \\n\\n \"\n + \"curr req: %s \\n\\n\\n curr session: %s \\n\\n\\n stack trace: %s\";\n String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);\n String subject = customer + \" error\";\n //TODO send email here\n } catch (Exception e) {\n //ignore\n }\n }"},"code_wo_comment":{"kind":"string","value":"public void sendErrorEmail(RequestCycle cycle, Exception ex, IRequestLogger logger) {\n try {\n String customer = Utils.getCustomer();\n Url url = cycle.getRequest().getUrl();\n Url clientUrl = cycle.getRequest().getClientUrl();\n String exStr = ExceptionUtils.getStackTrace(ex);\n String fullUrl = cycle.getUrlRenderer().renderFullUrl(url);\n int currUserId = 0;\n RequestData currRd = logger.getCurrentRequest();\n String currSessId = Session.get().getId();\n SessionData sd = null;\n if(currSessId != null) {\n SessionData[] sessions = logger.getLiveSessions();\n for(SessionData s : sessions) {\n if(s.getSessionId().equals(currSessId)) {\n sd = s;\n break;\n }\n }\n }\n String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd);\n StringBuilder currSessStr = new StringBuilder();\n if(sd != null) {\n currSessStr.append(\"id:\").append(sd.getSessionId()).append('\\n');\n currSessStr.append(\"requestCount:\").append(sd.getNumberOfRequests()).append('\\n');\n currSessStr.append(\"requestsTime:\").append(sd.getTotalTimeTaken()).append('\\n');\n currSessStr.append(\"sessionSize:\").append(Bytes.bytes(sd.getSessionSize())).append('\\n');\n currSessStr.append(\"sessionInfo:\").append(sd.getSessionInfo()).append('\\n');\n currSessStr.append(\"startDate:\").append(sd.getStartDate()).append('\\n');\n currSessStr.append(\"lastRequestTime:\").append(sd.getLastActive()).append('\\n');\n currSessStr.append(\"numberOfRequests:\").append(sd.getNumberOfRequests()).append('\\n');\n currSessStr.append(\"totalTimeTaken:\").append(sd.getTotalTimeTaken()).append(\"\\n\\n\\n\");\n }\n currSessStr.append(\"Requests: \\n\");\n ((CustomRequestLogger)logger).getRequests(currSessStr);\n String template = \"param1: %s \\n url: %s \\n client url: %s \\n user: %s \\n\\n \"\n + \"curr req: %s \\n\\n\\n curr session: %s \\n\\n\\n stack trace: %s\";\n String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);\n String subject = customer + \" error\";\n \n } catch (Exception e) {\n \n }\n }"},"cleancode":{"kind":"string","value":"public void senderroremail(requestcycle cycle, exception ex, irequestlogger logger) { try { string customer = utils.getcustomer(); url url = cycle.getrequest().geturl(); url clienturl = cycle.getrequest().getclienturl(); string exstr = exceptionutils.getstacktrace(ex); string fullurl = cycle.geturlrenderer().renderfullurl(url); int curruserid = 0; requestdata currrd = logger.getcurrentrequest(); string currsessid = session.get().getid(); sessiondata sd = null; if(currsessid != null) { sessiondata[] sessions = logger.getlivesessions(); for(sessiondata s : sessions) { if(s.getsessionid().equals(currsessid)) { sd = s; break; } } } string currreq = ((customrequestlogger)logger).createrequestdata(currrd, sd); stringbuilder currsessstr = new stringbuilder(); if(sd != null) { currsessstr.append(\"id:\").append(sd.getsessionid()).append('\\n'); currsessstr.append(\"requestcount:\").append(sd.getnumberofrequests()).append('\\n'); currsessstr.append(\"requeststime:\").append(sd.gettotaltimetaken()).append('\\n'); currsessstr.append(\"sessionsize:\").append(bytes.bytes(sd.getsessionsize())).append('\\n'); currsessstr.append(\"sessioninfo:\").append(sd.getsessioninfo()).append('\\n'); currsessstr.append(\"startdate:\").append(sd.getstartdate()).append('\\n'); currsessstr.append(\"lastrequesttime:\").append(sd.getlastactive()).append('\\n'); currsessstr.append(\"numberofrequests:\").append(sd.getnumberofrequests()).append('\\n'); currsessstr.append(\"totaltimetaken:\").append(sd.gettotaltimetaken()).append(\"\\n\\n\\n\"); } currsessstr.append(\"requests: \\n\"); ((customrequestlogger)logger).getrequests(currsessstr); string template = \"param1: %s \\n url: %s \\n client url: %s \\n user: %s \\n\\n \" + \"curr req: %s \\n\\n\\n curr session: %s \\n\\n\\n stack trace: %s\"; string body = string.format(template, customer, fullurl, clienturl.tostring(), curruserid, currreq, currsessstr.tostring(), exstr); string subject = customer + \" error\"; } catch (exception e) { } }"},"repo":{"kind":"string","value":"RomanSery/codesnippets"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":209,"cells":{"id":{"kind":"number","value":23575,"string":"23,575"},"original_code":{"kind":"string","value":"public static void main(String[] args) {\n\t\t// TODO Auto-generated method stub\n\t\t//Assuming stock of each sport is 2\n\t\tSports sp1=new IndoorSports();\n\t\tSystem.out.println(\"Total Indoor Sports Stock:\"+sp1.getCurrentStock());\n\t\tsp1=new Billiards(sp1);\n\t\tSystem.out.println(\"Total Indoor Sports Stock:\"+sp1.getCurrentStock());\n\t\tsp1=new Carrom(sp1);\n\t\tSystem.out.println(\"Total Indoor Sports Stock:\"+sp1.getCurrentStock());\n\t\tsp1=new Badminton(sp1);\n\t\tSystem.out.println(\"Total Indoor Sports Stock:\"+sp1.getCurrentStock());\n\t\tSports sp2=new OutdoorSports();\n\t\tSystem.out.println(\"\\nTotal Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t\tsp2=new Trekking(sp2);\n\t\tSystem.out.println(\"Total Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t\tsp2=new Cricket(sp2);\n\t\tSystem.out.println(\"Total Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t\tsp2=new HighJump(sp2);\n\t\tSystem.out.println(\"Total Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t\tsp2=new LongJump(sp2);\n\t\tSystem.out.println(\"Total Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t}"},"code_wo_comment":{"kind":"string","value":"public static void main(String[] args) {\n\t\n\t\n\t\tSports sp1=new IndoorSports();\n\t\tSystem.out.println(\"Total Indoor Sports Stock:\"+sp1.getCurrentStock());\n\t\tsp1=new Billiards(sp1);\n\t\tSystem.out.println(\"Total Indoor Sports Stock:\"+sp1.getCurrentStock());\n\t\tsp1=new Carrom(sp1);\n\t\tSystem.out.println(\"Total Indoor Sports Stock:\"+sp1.getCurrentStock());\n\t\tsp1=new Badminton(sp1);\n\t\tSystem.out.println(\"Total Indoor Sports Stock:\"+sp1.getCurrentStock());\n\t\tSports sp2=new OutdoorSports();\n\t\tSystem.out.println(\"\\nTotal Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t\tsp2=new Trekking(sp2);\n\t\tSystem.out.println(\"Total Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t\tsp2=new Cricket(sp2);\n\t\tSystem.out.println(\"Total Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t\tsp2=new HighJump(sp2);\n\t\tSystem.out.println(\"Total Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t\tsp2=new LongJump(sp2);\n\t\tSystem.out.println(\"Total Outdoor Sports Stock:\"+sp2.getCurrentStock());\n\t}"},"cleancode":{"kind":"string","value":"public static void main(string[] args) { sports sp1=new indoorsports(); system.out.println(\"total indoor sports stock:\"+sp1.getcurrentstock()); sp1=new billiards(sp1); system.out.println(\"total indoor sports stock:\"+sp1.getcurrentstock()); sp1=new carrom(sp1); system.out.println(\"total indoor sports stock:\"+sp1.getcurrentstock()); sp1=new badminton(sp1); system.out.println(\"total indoor sports stock:\"+sp1.getcurrentstock()); sports sp2=new outdoorsports(); system.out.println(\"\\ntotal outdoor sports stock:\"+sp2.getcurrentstock()); sp2=new trekking(sp2); system.out.println(\"total outdoor sports stock:\"+sp2.getcurrentstock()); sp2=new cricket(sp2); system.out.println(\"total outdoor sports stock:\"+sp2.getcurrentstock()); sp2=new highjump(sp2); system.out.println(\"total outdoor sports stock:\"+sp2.getcurrentstock()); sp2=new longjump(sp2); system.out.println(\"total outdoor sports stock:\"+sp2.getcurrentstock()); }"},"repo":{"kind":"string","value":"Saba-d-coder/6thSemIse"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":210,"cells":{"id":{"kind":"number","value":15413,"string":"15,413"},"original_code":{"kind":"string","value":"public void put(String name, Scriptable start, Object value) {\n\t try {\n\t\tObjectLocation variable = this.extractFieldVariable(name);\n\t\tif (value instanceof NativeArray) {\n\t\t // FIXME this breaks referential equality, but maybe it's OK\n\t\t variable.set(this.sequenceFromArray((NativeArray)value, start));\n\t\t return;\n\t\t}\n\t\t//System.err.println(\"variable \" + variable + \" new value \" + value + \" type \" + variable.getClass().getName());\n\t\tif (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc\n\t\t value = Context.jsToJava(value, Float.class);\n\t\t} else if (value instanceof ObjectLocation) {\n\t\t // here's a place where two locations could be bound to each other?\n\t\t value = ((ObjectLocation)value).get();\n\t\t} else if (value instanceof Wrapper) {\n\t\t // FIXME is there a better way???\n\t\t value = ((Wrapper)value).unwrap();\n\t\t if (value instanceof ObjectLocation) {\n\t\t\tvalue = ((ObjectLocation)value).get();\n\t\t }\n\t\t}\n\t\tvariable.set(value); \n\t\treturn;\n\t } catch (Exception e) { \n\t\te.printStackTrace(System.err);\n\t }\n\t}"},"code_wo_comment":{"kind":"string","value":"public void put(String name, Scriptable start, Object value) {\n\t try {\n\t\tObjectLocation variable = this.extractFieldVariable(name);\n\t\tif (value instanceof NativeArray) {\n\t\t \n\t\t variable.set(this.sequenceFromArray((NativeArray)value, start));\n\t\t return;\n\t\t}\n\t\n\t\tif (variable instanceof FloatLocation) {\n\t\t value = Context.jsToJava(value, Float.class);\n\t\t} else if (value instanceof ObjectLocation) {\n\t\t \n\t\t value = ((ObjectLocation)value).get();\n\t\t} else if (value instanceof Wrapper) {\n\t\t \n\t\t value = ((Wrapper)value).unwrap();\n\t\t if (value instanceof ObjectLocation) {\n\t\t\tvalue = ((ObjectLocation)value).get();\n\t\t }\n\t\t}\n\t\tvariable.set(value); \n\t\treturn;\n\t } catch (Exception e) { \n\t\te.printStackTrace(System.err);\n\t }\n\t}"},"cleancode":{"kind":"string","value":"public void put(string name, scriptable start, object value) { try { objectlocation variable = this.extractfieldvariable(name); if (value instanceof nativearray) { variable.set(this.sequencefromarray((nativearray)value, start)); return; } if (variable instanceof floatlocation) { value = context.jstojava(value, float.class); } else if (value instanceof objectlocation) { value = ((objectlocation)value).get(); } else if (value instanceof wrapper) { value = ((wrapper)value).unwrap(); if (value instanceof objectlocation) { value = ((objectlocation)value).get(); } } variable.set(value); return; } catch (exception e) { e.printstacktrace(system.err); } }"},"repo":{"kind":"string","value":"LivelyKernel/sunlabs-kernel"},"label":{"kind":"list like","value":[1,0,1,0],"string":"[\n 1,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":211,"cells":{"id":{"kind":"number","value":15430,"string":"15,430"},"original_code":{"kind":"string","value":"private static Method getMethod() {\n\t\treturn method.get(0);\n\t}"},"code_wo_comment":{"kind":"string","value":"private static Method getMethod() {\n\t\treturn method.get(0);\n\t}"},"cleancode":{"kind":"string","value":"private static method getmethod() { return method.get(0); }"},"repo":{"kind":"string","value":"Modify24x7/ApkStringDecryptor"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":212,"cells":{"id":{"kind":"number","value":15621,"string":"15,621"},"original_code":{"kind":"string","value":"private boolean initCipher() {\n try {\n //Obtain a cipher instance and configure it with the properties required for fingerprint authentication//\n if(this.cipher == null) {\n this.cipher = Cipher.getInstance(\n KeyProperties.KEY_ALGORITHM_AES + \"/\"\n + KeyProperties.BLOCK_MODE_CBC + \"/\"\n + KeyProperties.ENCRYPTION_PADDING_PKCS7);\n }\n } catch (NoSuchAlgorithmException |\n NoSuchPaddingException e) {\n e.printStackTrace();\n return false;\n }\n try {\n if(this.secretKey == null) {\n this.secretKey = generateKey();\n }\n if(this.keyStore != null) {\n if(!this.keystoreInitialized) {\n this.keyStore.load(null);\n this.keystoreInitialized = true;\n }\n }\n// key = (SecretKey) this.keyStore.getKey(keyName, null); todo needed?\n if(this.cipher != null) {\n if (!this.cipherInitialized) {\n this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);\n this.cipherInitialized = true;\n }\n }\n //Return true if the cipher has been initialized successfully//\n return true;\n } catch (KeyPermanentlyInvalidatedException e) {\n //Return false if cipher initialization failed//\n return false;\n } catch (CertificateException //KeyStoreException\n | IOException //UnrecoverableKeyException\n | NullPointerException\n | NoSuchAlgorithmException | InvalidKeyException e) {\n e.printStackTrace();\n return false;\n }\n }"},"code_wo_comment":{"kind":"string","value":"private boolean initCipher() {\n try {\n \n if(this.cipher == null) {\n this.cipher = Cipher.getInstance(\n KeyProperties.KEY_ALGORITHM_AES + \"/\"\n + KeyProperties.BLOCK_MODE_CBC + \"/\"\n + KeyProperties.ENCRYPTION_PADDING_PKCS7);\n }\n } catch (NoSuchAlgorithmException |\n NoSuchPaddingException e) {\n e.printStackTrace();\n return false;\n }\n try {\n if(this.secretKey == null) {\n this.secretKey = generateKey();\n }\n if(this.keyStore != null) {\n if(!this.keystoreInitialized) {\n this.keyStore.load(null);\n this.keystoreInitialized = true;\n }\n }\n if(this.cipher != null) {\n if (!this.cipherInitialized) {\n this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);\n this.cipherInitialized = true;\n }\n }\n \n return true;\n } catch (KeyPermanentlyInvalidatedException e) {\n \n return false;\n } catch (CertificateException\n | IOException\n | NullPointerException\n | NoSuchAlgorithmException | InvalidKeyException e) {\n e.printStackTrace();\n return false;\n }\n }"},"cleancode":{"kind":"string","value":"private boolean initcipher() { try { if(this.cipher == null) { this.cipher = cipher.getinstance( keyproperties.key_algorithm_aes + \"/\" + keyproperties.block_mode_cbc + \"/\" + keyproperties.encryption_padding_pkcs7); } } catch (nosuchalgorithmexception | nosuchpaddingexception e) { e.printstacktrace(); return false; } try { if(this.secretkey == null) { this.secretkey = generatekey(); } if(this.keystore != null) { if(!this.keystoreinitialized) { this.keystore.load(null); this.keystoreinitialized = true; } } if(this.cipher != null) { if (!this.cipherinitialized) { this.cipher.init(cipher.encrypt_mode, this.secretkey); this.cipherinitialized = true; } } return true; } catch (keypermanentlyinvalidatedexception e) { return false; } catch (certificateexception | ioexception | nullpointerexception | nosuchalgorithmexception | invalidkeyexception e) { e.printstacktrace(); return false; } }"},"repo":{"kind":"string","value":"PGMacDesign/PGMacTips"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":213,"cells":{"id":{"kind":"number","value":23837,"string":"23,837"},"original_code":{"kind":"string","value":"private void writeRunnerProject() throws IOException, XmlException, ParseException {\n // TODO revise whole method\n // TODO now using a newer JAPA (suuports java 8), -> maybe ANTLR supports better\n PathUtils.createDir(getRunnerProjectSettings().getBaseDir().toPath());\n // copy snippets\n PathUtils.copy(getSnippetProject().getSourceDir(),\n getRunnerProjectSettings().getSnippetSourceDirectory().toPath());\n // create INFO file\n writeInfoFile();\n // remove SETTE annotations and imports from file\n Collection filesWritten = Files\n .walk(getRunnerProjectSettings().getSnippetSourceDirectory().toPath())\n .filter(Files::isRegularFile).map(Path::toFile).sorted()\n .collect(Collectors.toList());\n for (File file : filesWritten) {\n // parse source with JavaParser\n log.debug(\"Parsing with JavaParser: {}\", file);\n CompilationUnit compilationUnit = JavaParser.parse(file);\n log.debug(\"Parsed with JavaParser: {}\", file);\n // extract type\n List types = compilationUnit.getTypes();\n if (types.size() != 1) {\n // NOTE better exception type\n throw new RuntimeException(\n \"Java source files containing more that one types are not supported\");\n }\n TypeDeclaration type = types.get(0);\n // skip file if Java version is not supported by the tool (@SetteSnippetContainer)\n // NOTE it can be also done with snippet containers... (and also done in CATG\n // generator!)\n List classAnnotations = type.getAnnotations();\n JavaVersion reqJavaVer = getRequiredJavaVersion(classAnnotations);\n if (reqJavaVer != null && !getTool().supportsJavaVersion(reqJavaVer)) {\n System.err.println(\n \"Skipping file: \" + file + \" (required Java version: \" + reqJavaVer + \")\");\n PathUtils.delete(file.toPath());\n } else {\n // remove SETTE annotations from the class\n Predicate isSetteAnnotation = (a -> a.getName().getName()\n .startsWith(\"Sette\"));\n classAnnotations.removeIf(isSetteAnnotation);\n // remove SETTE annotations from the members\n for (BodyDeclaration member : type.getMembers()) {\n member.getAnnotations().removeIf(isSetteAnnotation);\n }\n // TODO enhance\n List toRemovePrefixes = new ArrayList<>();\n toRemovePrefixes.add(\"hu.bme.mit.sette.snippets.inputs\");\n toRemovePrefixes.add(\"hu.bme.mit.sette.common\");\n // remove SETTE imports\n compilationUnit.getImports().removeIf(importDeclaration -> {\n String impDecl = importDeclaration.getName().toString();\n for (String prefix : toRemovePrefixes) {\n if (impDecl.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n });\n // save edited source code\n String source = compilationUnit.toString();\n if (type instanceof EnumDeclaration) {\n // FIXME remove after javaparser bug is fixed\n source = source.replaceFirst(type.getName() + \"\\\\s+implements\\\\s*\\\\{\",\n type.getName() + \" {\");\n }\n PathUtils.write(file.toPath(), source.getBytes());\n }\n }\n // copy libraries\n if (getSnippetProject().getLibDir().toFile().exists()) {\n PathUtils.copy(getSnippetProject().getLibDir(),\n getRunnerProjectSettings().getSnippetLibraryDirectory().toPath());\n }\n // create project\n this.eclipseProject.save(getRunnerProjectSettings().getBaseDir().toPath());\n }"},"code_wo_comment":{"kind":"string","value":"private void writeRunnerProject() throws IOException, XmlException, ParseException {\n \n \n PathUtils.createDir(getRunnerProjectSettings().getBaseDir().toPath());\n \n PathUtils.copy(getSnippetProject().getSourceDir(),\n getRunnerProjectSettings().getSnippetSourceDirectory().toPath());\n \n writeInfoFile();\n \n Collection filesWritten = Files\n .walk(getRunnerProjectSettings().getSnippetSourceDirectory().toPath())\n .filter(Files::isRegularFile).map(Path::toFile).sorted()\n .collect(Collectors.toList());\n for (File file : filesWritten) {\n \n log.debug(\"Parsing with JavaParser: {}\", file);\n CompilationUnit compilationUnit = JavaParser.parse(file);\n log.debug(\"Parsed with JavaParser: {}\", file);\n \n List types = compilationUnit.getTypes();\n if (types.size() != 1) {\n \n throw new RuntimeException(\n \"Java source files containing more that one types are not supported\");\n }\n TypeDeclaration type = types.get(0);\n \n \n \n List classAnnotations = type.getAnnotations();\n JavaVersion reqJavaVer = getRequiredJavaVersion(classAnnotations);\n if (reqJavaVer != null && !getTool().supportsJavaVersion(reqJavaVer)) {\n System.err.println(\n \"Skipping file: \" + file + \" (required Java version: \" + reqJavaVer + \")\");\n PathUtils.delete(file.toPath());\n } else {\n \n Predicate isSetteAnnotation = (a -> a.getName().getName()\n .startsWith(\"Sette\"));\n classAnnotations.removeIf(isSetteAnnotation);\n \n for (BodyDeclaration member : type.getMembers()) {\n member.getAnnotations().removeIf(isSetteAnnotation);\n }\n \n List toRemovePrefixes = new ArrayList<>();\n toRemovePrefixes.add(\"hu.bme.mit.sette.snippets.inputs\");\n toRemovePrefixes.add(\"hu.bme.mit.sette.common\");\n \n compilationUnit.getImports().removeIf(importDeclaration -> {\n String impDecl = importDeclaration.getName().toString();\n for (String prefix : toRemovePrefixes) {\n if (impDecl.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n });\n \n String source = compilationUnit.toString();\n if (type instanceof EnumDeclaration) {\n \n source = source.replaceFirst(type.getName() + \"\\\\s+implements\\\\s*\\\\{\",\n type.getName() + \" {\");\n }\n PathUtils.write(file.toPath(), source.getBytes());\n }\n }\n \n if (getSnippetProject().getLibDir().toFile().exists()) {\n PathUtils.copy(getSnippetProject().getLibDir(),\n getRunnerProjectSettings().getSnippetLibraryDirectory().toPath());\n }\n \n this.eclipseProject.save(getRunnerProjectSettings().getBaseDir().toPath());\n }"},"cleancode":{"kind":"string","value":"private void writerunnerproject() throws ioexception, xmlexception, parseexception { pathutils.createdir(getrunnerprojectsettings().getbasedir().topath()); pathutils.copy(getsnippetproject().getsourcedir(), getrunnerprojectsettings().getsnippetsourcedirectory().topath()); writeinfofile(); collection fileswritten = files .walk(getrunnerprojectsettings().getsnippetsourcedirectory().topath()) .filter(files::isregularfile).map(path::tofile).sorted() .collect(collectors.tolist()); for (file file : fileswritten) { log.debug(\"parsing with javaparser: {}\", file); compilationunit compilationunit = javaparser.parse(file); log.debug(\"parsed with javaparser: {}\", file); list types = compilationunit.gettypes(); if (types.size() != 1) { throw new runtimeexception( \"java source files containing more that one types are not supported\"); } typedeclaration type = types.get(0); list classannotations = type.getannotations(); javaversion reqjavaver = getrequiredjavaversion(classannotations); if (reqjavaver != null && !gettool().supportsjavaversion(reqjavaver)) { system.err.println( \"skipping file: \" + file + \" (required java version: \" + reqjavaver + \")\"); pathutils.delete(file.topath()); } else { predicate issetteannotation = (a -> a.getname().getname() .startswith(\"sette\")); classannotations.removeif(issetteannotation); for (bodydeclaration member : type.getmembers()) { member.getannotations().removeif(issetteannotation); } list toremoveprefixes = new arraylist<>(); toremoveprefixes.add(\"hu.bme.mit.sette.snippets.inputs\"); toremoveprefixes.add(\"hu.bme.mit.sette.common\"); compilationunit.getimports().removeif(importdeclaration -> { string impdecl = importdeclaration.getname().tostring(); for (string prefix : toremoveprefixes) { if (impdecl.startswith(prefix)) { return true; } } return false; }); string source = compilationunit.tostring(); if (type instanceof enumdeclaration) { source = source.replacefirst(type.getname() + \"\\\\s+implements\\\\s*\\\\{\", type.getname() + \" {\"); } pathutils.write(file.topath(), source.getbytes()); } } if (getsnippetproject().getlibdir().tofile().exists()) { pathutils.copy(getsnippetproject().getlibdir(), getrunnerprojectsettings().getsnippetlibrarydirectory().topath()); } this.eclipseproject.save(getrunnerprojectsettings().getbasedir().topath()); }"},"repo":{"kind":"string","value":"SETTE-Testing/sette-tool"},"label":{"kind":"list like","value":[1,0,1,0],"string":"[\n 1,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":214,"cells":{"id":{"kind":"number","value":15691,"string":"15,691"},"original_code":{"kind":"string","value":"public boolean isSubjectEmpty() {\n return TextUtils.getTrimmedLength(mSubject.getText()) == 0;\n }"},"code_wo_comment":{"kind":"string","value":"public boolean isSubjectEmpty() {\n return TextUtils.getTrimmedLength(mSubject.getText()) == 0;\n }"},"cleancode":{"kind":"string","value":"public boolean issubjectempty() { return textutils.gettrimmedlength(msubject.gettext()) == 0; }"},"repo":{"kind":"string","value":"Keneral/apackages"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":215,"cells":{"id":{"kind":"number","value":23891,"string":"23,891"},"original_code":{"kind":"string","value":"public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) {\n String sql2PlName = call.getPl2SQLName(this);\n if (sql2PlName == null) {\n // TODO: Error.\n throw new NullPointerException(\"no Pl2SQL conversion routine for \" + typeName);\n }\n String target = databaseTypeHelper.buildTarget(outArg);\n sb.append(\" :\");\n sb.append(outArg.outIndex);\n sb.append(\" := \");\n sb.append(sql2PlName);\n sb.append(\"(\");\n sb.append(target);\n sb.append(\");\");\n sb.append(NL);\n }"},"code_wo_comment":{"kind":"string","value":"public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) {\n String sql2PlName = call.getPl2SQLName(this);\n if (sql2PlName == null) {\n \n throw new NullPointerException(\"no Pl2SQL conversion routine for \" + typeName);\n }\n String target = databaseTypeHelper.buildTarget(outArg);\n sb.append(\" :\");\n sb.append(outArg.outIndex);\n sb.append(\" := \");\n sb.append(sql2PlName);\n sb.append(\"(\");\n sb.append(target);\n sb.append(\");\");\n sb.append(NL);\n }"},"cleancode":{"kind":"string","value":"public void buildoutassignment(stringbuilder sb, plsqlargument outarg, plsqlstoredprocedurecall call) { string sql2plname = call.getpl2sqlname(this); if (sql2plname == null) { throw new nullpointerexception(\"no pl2sql conversion routine for \" + typename); } string target = databasetypehelper.buildtarget(outarg); sb.append(\" :\"); sb.append(outarg.outindex); sb.append(\" := \"); sb.append(sql2plname); sb.append(\"(\"); sb.append(target); sb.append(\");\"); sb.append(nl); }"},"repo":{"kind":"string","value":"Pandrex247/patched-src-eclipselink"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":216,"cells":{"id":{"kind":"number","value":23901,"string":"23,901"},"original_code":{"kind":"string","value":"private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed\n // TODO add your handling code here:\n //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email);\n //jFrameInstance.changePanelToSpecific(guestsearch);\n }"},"code_wo_comment":{"kind":"string","value":"private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) { \n \n \n }"},"cleancode":{"kind":"string","value":"private void guestsearchactionperformed(java.awt.event.actionevent evt) { }"},"repo":{"kind":"string","value":"Jed-g/property-booking-system"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":217,"cells":{"id":{"kind":"number","value":32148,"string":"32,148"},"original_code":{"kind":"string","value":"@Override\n protected void setUp() throws Exception {\n super.setUp();\n // TODO: This test will actually mess with contacts on your phone.\n // Ideally we would use a fake content provider to give us contact data...\n FakeFactory.registerWithoutFakeContext(getTestContext());\n // add test contacts.\n addTestContact(\"John\", \"650-123-1233\", \"john@gmail.com\", false);\n addTestContact(\"Joe\", \"(650)123-1233\", \"joe@gmail.com\", false);\n addTestContact(\"Jim\", \"650 123 1233\", \"jim@gmail.com\", false);\n addTestContact(\"Samantha\", \"650-123-1235\", \"samantha@gmail.com\", true);\n addTestContact(\"Adrienne\", \"650-123-1236\", \"adrienne@gmail.com\", true);\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n protected void setUp() throws Exception {\n super.setUp();\n \n \n FakeFactory.registerWithoutFakeContext(getTestContext());\n \n addTestContact(\"John\", \"650-123-1233\", \"john@gmail.com\", false);\n addTestContact(\"Joe\", \"(650)123-1233\", \"joe@gmail.com\", false);\n addTestContact(\"Jim\", \"650 123 1233\", \"jim@gmail.com\", false);\n addTestContact(\"Samantha\", \"650-123-1235\", \"samantha@gmail.com\", true);\n addTestContact(\"Adrienne\", \"650-123-1236\", \"adrienne@gmail.com\", true);\n }"},"cleancode":{"kind":"string","value":"@override protected void setup() throws exception { super.setup(); fakefactory.registerwithoutfakecontext(gettestcontext()); addtestcontact(\"john\", \"650-123-1233\", \"john@gmail.com\", false); addtestcontact(\"joe\", \"(650)123-1233\", \"joe@gmail.com\", false); addtestcontact(\"jim\", \"650 123 1233\", \"jim@gmail.com\", false); addtestcontact(\"samantha\", \"650-123-1235\", \"samantha@gmail.com\", true); addtestcontact(\"adrienne\", \"650-123-1236\", \"adrienne@gmail.com\", true); }"},"repo":{"kind":"string","value":"Keneral/apackages"},"label":{"kind":"list like","value":[0,0,0,1],"string":"[\n 0,\n 0,\n 0,\n 1\n]"}}},{"rowIdx":218,"cells":{"id":{"kind":"number","value":15785,"string":"15,785"},"original_code":{"kind":"string","value":"@Override\n\tpublic ItemStack transferStackInSlot(EntityPlayer player, int slot) {\n\t\t// TODO: Try to come up with a generic way of implementing this\n\t\treturn null;\n\t}"},"code_wo_comment":{"kind":"string","value":"@Override\n\tpublic ItemStack transferStackInSlot(EntityPlayer player, int slot) {\n\t\n\t\treturn null;\n\t}"},"cleancode":{"kind":"string","value":"@override public itemstack transferstackinslot(entityplayer player, int slot) { return null; }"},"repo":{"kind":"string","value":"PC-Logix/GregsLighting-Reloaded"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":219,"cells":{"id":{"kind":"number","value":7631,"string":"7,631"},"original_code":{"kind":"string","value":"public JSONArray getProjectRevisions(ProjectEndpoint endpoint) {\n\t\t//TODO need to add paging somewhere (page, items) to handle long commit histories\n\t\tString json = restInterface.get(TeamworkCloudEndpoints.GET_PROJECT_REVISIONS.buildUrl(endpoint.getHost(),\n\t\t\t\tendpoint.getCollection(), endpoint.getProject(), \"true\"), endpoint.getToken(), String.class);\n\t\treturn new JSONArray(json);\n\t}"},"code_wo_comment":{"kind":"string","value":"public JSONArray getProjectRevisions(ProjectEndpoint endpoint) {\n\t\n\t\tString json = restInterface.get(TeamworkCloudEndpoints.GET_PROJECT_REVISIONS.buildUrl(endpoint.getHost(),\n\t\t\t\tendpoint.getCollection(), endpoint.getProject(), \"true\"), endpoint.getToken(), String.class);\n\t\treturn new JSONArray(json);\n\t}"},"cleancode":{"kind":"string","value":"public jsonarray getprojectrevisions(projectendpoint endpoint) { string json = restinterface.get(teamworkcloudendpoints.get_project_revisions.buildurl(endpoint.gethost(), endpoint.getcollection(), endpoint.getproject(), \"true\"), endpoint.gettoken(), string.class); return new jsonarray(json); }"},"repo":{"kind":"string","value":"Open-MBEE/sync-service"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":220,"cells":{"id":{"kind":"number","value":24107,"string":"24,107"},"original_code":{"kind":"string","value":"public void ClearScreenTest(){\n press(R.id.btn_1);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.binary_number_2);\n press(R.id.btn_1);\n press(R.id.btn_0);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_divide);\n press(R.id.btn_all_clear);\n checkResult(\"\");\n checkBinary1(\"\");\n checkBinary2(\"\");\n }"},"code_wo_comment":{"kind":"string","value":"public void ClearScreenTest(){\n press(R.id.btn_1);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.binary_number_2);\n press(R.id.btn_1);\n press(R.id.btn_0);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_divide);\n press(R.id.btn_all_clear);\n checkResult(\"\");\n checkBinary1(\"\");\n checkBinary2(\"\");\n }"},"cleancode":{"kind":"string","value":"public void clearscreentest(){ press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.binary_number_2); press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_divide); press(r.id.btn_all_clear); checkresult(\"\"); checkbinary1(\"\"); checkbinary2(\"\"); }"},"repo":{"kind":"string","value":"ModestosV/Simple-Calculator"},"label":{"kind":"list like","value":[0,0,0,1],"string":"[\n 0,\n 0,\n 0,\n 1\n]"}}},{"rowIdx":221,"cells":{"id":{"kind":"number","value":24108,"string":"24,108"},"original_code":{"kind":"string","value":"public void DeleteTest(){\n press(R.id.btn_1);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_del);\n checkBinary1(\"1000011111\");\n press(R.id.binary_number_2);\n press(R.id.btn_1);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_del);\n checkBinary2(\"10\");\n }"},"code_wo_comment":{"kind":"string","value":"public void DeleteTest(){\n press(R.id.btn_1);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_1);\n press(R.id.btn_del);\n checkBinary1(\"1000011111\");\n press(R.id.binary_number_2);\n press(R.id.btn_1);\n press(R.id.btn_0);\n press(R.id.btn_0);\n press(R.id.btn_del);\n checkBinary2(\"10\");\n }"},"cleancode":{"kind":"string","value":"public void deletetest(){ press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_del); checkbinary1(\"1000011111\"); press(r.id.binary_number_2); press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_del); checkbinary2(\"10\"); }"},"repo":{"kind":"string","value":"ModestosV/Simple-Calculator"},"label":{"kind":"list like","value":[0,0,0,1],"string":"[\n 0,\n 0,\n 0,\n 1\n]"}}},{"rowIdx":222,"cells":{"id":{"kind":"number","value":15927,"string":"15,927"},"original_code":{"kind":"string","value":"public int ExecuteGFXCommand(int cmd, int len, byte[] cmddata, int[] hasret)\n\t{\n\t\tlen -= 4; // for the 4 byte header\n\t hasret[0] = 0; // Nothing to return by default\n//\t\tSystem.out.println(\"GFXCMD=\" + cmd);\n\t\t// make sure the frame is still valid or we could crash on fullscreen mode switches\n\t\tif((cmd != GFXCMD_INIT) && (cmd != GFXCMD_DEINIT))\n\t\t{\n\t\t\tif((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) {\n//\t\t\t\tSystem.out.println(\"GFXCMD while frame not displayable\");\n\t\t\t\t// spin until the frame is valid and displayable, if we don't we'll lose parts of the UI or crash\n\t\t\t\twhile((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.sleep(10);\n\t\t\t\t\t} catch(InterruptedException ex) {}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (c != null)\n\t\t{\n\t\t\tswitch(cmd)\n\t\t\t{\n\t\t\t\tcase GFXCMD_INIT:\n\t\t\t\tcase GFXCMD_DEINIT:\n\t\t\t\tcase GFXCMD_STARTFRAME:\n\t\t\t\tcase GFXCMD_FLIPBUFFER:\n\t\t\t\t\tc.setCursor(null);\n\t\t\t\t\tbreak;\n\t\t\t\tcase GFXCMD_DRAWRECT:\n\t\t\t\tcase GFXCMD_FILLRECT:\n\t\t\t\tcase GFXCMD_CLEARRECT:\n\t\t\t\tcase GFXCMD_DRAWOVAL:\n\t\t\t\tcase GFXCMD_FILLOVAL:\n\t\t\t\tcase GFXCMD_DRAWROUNDRECT:\n\t\t\t\tcase GFXCMD_FILLROUNDRECT:\n\t\t\t\tcase GFXCMD_DRAWTEXT:\n\t\t\t\tcase GFXCMD_DRAWTEXTURED:\n\t\t\t\tcase GFXCMD_DRAWLINE:\n\t\t\t\tcase GFXCMD_LOADIMAGE:\n\t\t\t\tcase GFXCMD_LOADIMAGETARGETED:\n\t\t\t\tcase GFXCMD_UNLOADIMAGE:\n\t\t\t\tcase GFXCMD_LOADFONT:\n\t\t\t\tcase GFXCMD_UNLOADFONT:\n\t\t\t\tcase GFXCMD_SETTARGETSURFACE:\n\t\t\t\tcase GFXCMD_CREATESURFACE:\n\t\t\t\t\tbreak;\n\t\t\t\tcase GFXCMD_PREPIMAGE:\n\t\t\t\tcase GFXCMD_LOADIMAGELINE:\n\t\t\t\tcase GFXCMD_LOADIMAGECOMPRESSED:\n\t\t\t\tcase GFXCMD_XFMIMAGE:\n\t\t\t\tcase GFXCMD_LOADCACHEDIMAGE:\n\t\t\t\tcase GFXCMD_PREPIMAGETARGETED:\n\t\t\t\t\tif (!cursorHidden)\n\t\t\t\t\t\tc.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tswitch(cmd)\n\t\t{\n\t\t\tcase GFXCMD_INIT:\n\t\t\t\thasret[0] = 1;\n//\t\t\t\tSystem.out.println(\"INIT\");\n\t\t\t\t// start up native renderer\n\t\t\t\tinit0();\n\t\t\t\tint windowTitleStyle = 0;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\twindowTitleStyle = Integer.parseInt(MiniClient.myProperties.getProperty(\"window_title_style\", \"0\"));\n\t\t\t\t}\n\t\t\t\tcatch (NumberFormatException e){}\n\t\t\t\tif (!\"true\".equals(MiniClient.myProperties.getProperty(\"enable_custom_title_bar\", MiniClient.MAC_OS_X ? \"false\" : \"true\")))\n\t\t\t\t\twindowTitleStyle = 10; // platform default\n\t\t\t\tf = new MiniClientWindow(myConn.getWindowTitle(), windowTitleStyle);\n\t\t\t\tjava.awt.LayoutManager layer = new java.awt.LayoutManager()\n\t\t\t\t\t{\n\t\t\t\t\t\tpublic void addLayoutComponent(String name, java.awt.Component comp)\n\t\t\t\t\t\t{}\n\t\t\t\t\t\tpublic java.awt.Dimension minimumLayoutSize(java.awt.Container parent)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn preferredLayoutSize(parent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpublic java.awt.Dimension preferredLayoutSize(java.awt.Container parent)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn parent.getPreferredSize();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpublic void removeLayoutComponent(java.awt.Component comp)\n\t\t\t\t\t\t{}\n\t\t\t\t\t\tpublic void layoutContainer(java.awt.Container parent)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tc.setBounds(parent.getInsets().left, parent.getInsets().top, parent.getWidth() - parent.getInsets().left - parent.getInsets().right,\n\t\t\t\t\t\t\t\tparent.getHeight() - parent.getInsets().top - parent.getInsets().bottom);\n//System.out.println(\"LAYOUT frame bounds=\" + f.getBounds() + \" videoBounds=\" + videoBounds + \" parentBounds=\" + parent.getBounds());\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\tf.getContentPane().setLayout(layer);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tbgImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource(\"images/Background.jpg\"));\n\t\t\t\t\tensureImageIsLoaded(bgImage);\n\t\t\t\t\tlogoImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource(\"images/SageLogo256.png\"));\n\t\t\t\t\tensureImageIsLoaded(logoImage);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"ERROR:\" + e);\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tf.setFocusTraversalKeysEnabled(false);\n\t\t\t\t/*\n\t\t\t\t\tif not connecting to localhost:\n\t\t\t\t\t\t- draw background to bounds (scaled)\n\t\t\t\t\t\t- draw logo to {{2% from left, 15% from top}{20% view width, 7% view height}}, no clipping, alpha = 0.85, adjust size to keep aspect ratio\n\t\t\t\t\t\t- load Arial 32 bold\n\t\t\t\t\t\t- draw the following text, double spaced using Arial 32 bold, white with black shadow (offset by (+2,+2))\n\t\t\t\t\t\t\t\"SageTV Placeshifter is connecting to\"\n\t\t\t\t\t\t\t\"the server: \"+myConn.getServerName()\n\t\t\t\t\t\t\t\"Please Wait...\"\n\t\t\t\t\t\ttext is centered in the view on the middle line, use font metrics to determine proper location\n\t\t\t\t\t\t g.setFont(pleaseWaitFont);\n\t\t\t\t\t\t g.setColor(java.awt.Color.black);\n\t\t\t\t\t\t y += 2;\n\t\t\t\t\t\t g.drawString(str1, 2 + (getWidth()/2) - (fm.stringWidth(str1)/2), y + fm.getAscent());\n\t\t\t\t\t\t y += fm.getHeight();\n\t\t\t\t\t\t g.drawString(str2, 2 + (getWidth()/2) - (fm.stringWidth(str2)/2), y + fm.getAscent());\n\t\t\t\t\t\t y += 2*fm.getHeight();\n\t\t\t\t\t\t g.drawString(str3, 2 + (getWidth()/2) - (fm.stringWidth(str3)/2), y + fm.getAscent());\n\t\t\t\t\t\t g.setColor(java.awt.Color.white);\n\t\t\t\t\t\t y = (getHeight() / 2) - fh/2;\n\t\t\t\t\t\t g.drawString(str1, (getWidth()/2) - (fm.stringWidth(str1)/2), y + fm.getAscent());\n\t\t\t\t\t\t y += fm.getHeight();\n\t\t\t\t\t\t g.drawString(str2, (getWidth()/2) - (fm.stringWidth(str2)/2), y + fm.getAscent());\n\t\t\t\t\t\t y += 2*fm.getHeight();\n\t\t\t\t\t\t g.drawString(str3, (getWidth()/2) - (fm.stringWidth(str3)/2), y + fm.getAscent());\n\t\t\t\t */\n\t\t\t\tjava.awt.Dimension panelSize = f.getContentPane().getSize();\n\t\t\t\tc = new QuartzRendererView();\n\t\t\t\tc.setSize(panelSize);\n\t\t\t\tc.setFocusTraversalKeysEnabled(false);\n\t\t\t\tf.getContentPane().add(c);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tjava.awt.Image frameIcon = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource(\"images/tvicon.gif\"));\n\t\t\t\t\tensureImageIsLoaded(frameIcon);\n\t\t\t\t\tf.setIconImage(frameIcon);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"ERROR:\" + e);\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tf.addWindowListener(new java.awt.event.WindowAdapter()\n\t\t\t\t{\n\t\t\t\t\tpublic void windowClosing(java.awt.event.WindowEvent evt)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!f.isFullScreen() || System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") != -1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMiniClient.myProperties.setProperty(\"main_window_width\", Integer.toString(f.getWidth()));\n\t\t\t\t\t\t\tMiniClient.myProperties.setProperty(\"main_window_height\", Integer.toString(f.getHeight()));\n\t\t\t\t\t\t\tMiniClient.myProperties.setProperty(\"main_window_x\", Integer.toString(f.getX()));\n\t\t\t\t\t\t\tMiniClient.myProperties.setProperty(\"main_window_y\", Integer.toString(f.getY()));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmyConn.close();\n/*\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (myConn.getMediaCmd().getPlaya() != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmyConn.getMediaCmd().getPlaya().stop();\n\t\t\t\t\t\t\t\tmyConn.getMediaCmd().getPlaya().free();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}catch (Exception e){}\n\t\t\t\t\t\tSystem.exit(0);*/\n\t\t\t\t\t\tclose();\n//\t\t\t\t\t\tf.dispose();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tc.addComponentListener(new java.awt.event.ComponentAdapter()\n\t\t\t\t{\n\t\t\t\t\tpublic void componentResized(java.awt.event.ComponentEvent evt)\n\t\t\t\t\t{\n\t\t\t\t\t\tmyConn.postResizeEvent(new java.awt.Dimension(c.getWidth(), c.getHeight()));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tf.addKeyListener(this);\n\t\t\t\tc.addKeyListener(this);\n\t\t\t\t//f.addMouseListener(this);\n\t\t\t\tf.addMouseWheelListener(this);\n\t\t\t\tc.addMouseListener(this);\n\t\t\t\tif (ENABLE_MOUSE_MOTION_EVENTS)\n\t\t\t\t{\n\t\t\t\t\t//f.addMouseMotionListener(this);\n\t\t\t\t\tc.addMouseMotionListener(this);\n\t\t\t\t}\n\t\t\t\tint frameX = 100;\n\t\t\t\tint frameY = 100;\n\t\t\t\tint frameW = 720;\n\t\t\t\tint frameH = 480;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tframeW = Integer.parseInt(MiniClient.myProperties.getProperty(\"main_window_width\", \"720\"));\n\t\t\t\t\tframeH = Integer.parseInt(MiniClient.myProperties.getProperty(\"main_window_height\", \"480\"));\n\t\t\t\t\tframeX = Integer.parseInt(MiniClient.myProperties.getProperty(\"main_window_x\", \"100\"));\n\t\t\t\t\tframeY = Integer.parseInt(MiniClient.myProperties.getProperty(\"main_window_y\", \"100\"));\n\t\t\t\t}\n\t\t\t\tcatch (NumberFormatException e){}\n\t\t\t\tjava.awt.Point newPos = new java.awt.Point(frameX, frameY);\n\t\t\t\tboolean foundScreen = sage.UIUtils.isPointOnAScreen(newPos);\n\t\t\t\tif (!foundScreen)\n\t\t\t\t{\n\t\t\t\t\tnewPos.x = 150;\n\t\t\t\t\tnewPos.y = 150;\n\t\t\t\t}\n\t\t\t\tf.setVisible(true);\n\t\t\t\tf.setSize(1,1);\n\t\t\t\tf.setSize(Math.max(frameW, 320), Math.max(frameH, 240));\n\t\t\t\tf.setLocation(newPos);\n\t\t\t\tif (MiniClient.fsStartup)\n\t\t\t\t\tf.setFullScreen(true);\n\t\t\t\tMiniClient.hideSplash();\n//\t\t\t\tf.setVisible(true);\n\t\t\t\treturn 1;\n\t\t\tcase GFXCMD_DEINIT:\n//\t\t\t\tSystem.out.println(\"DEINIT\");\n\t\t\t\tclose();\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWRECT:\n\t\t\t\tif(len==36)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height;\n\t\t\t\t\tint thickness, argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\tthickness=readInt(16, cmddata);\n\t\t\t\t\targbTL=readInt(20, cmddata);\n\t\t\t\t\targbTR=readInt(24, cmddata);\n\t\t\t\t\targbBR=readInt(28, cmddata);\n\t\t\t\t\targbBL=readInt(32, cmddata);\n//\t\t\t\t\tSystem.out.println(\"DRAWRECT: dest=(\"+x+\",\"+y+\" \"+width+\"x\"+height+\") thickness=\"+thickness+\" argbTL=\"+Integer.toHexString(argbTL)+\" argbTR=\"+Integer.toHexString(argbTR)+\" argbBL=\"+Integer.toHexString(argbBL)+\" argbBR=\"+Integer.toHexString(argbBR));\n\t\t\t\t\t// FIXME: no gradients on framed rects yet...\n\t\t\t\t\tdrawRect0(new java.awt.geom.Rectangle2D.Float(x, y, width, height), null,\n\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), thickness,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_FILLRECT:\n\t\t\t\t// x, y, width, height, argbTL, argbTR, argbBR, argbBL\n\t\t\t\tif(len==32)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height;\n\t\t\t\t\tint argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\targbTL=readInt(16, cmddata);\n\t\t\t\t\targbTR=readInt(20, cmddata);\n\t\t\t\t\targbBR=readInt(24, cmddata);\n\t\t\t\t\targbBL=readInt(28, cmddata);\n//\t\t\t\t\tSystem.out.println(\"FILLRECT: dest=(\"+x+\",\"+y+\" \"+width+\"x\"+height+\") argbTL=\"+Integer.toHexString(argbTL)+\" argbTR=\"+Integer.toHexString(argbTR)+\" argbBL=\"+Integer.toHexString(argbBL)+\" argbBR=\"+Integer.toHexString(argbBR));\n\t\t\t\t\tjava.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tif(gp != null) {\n\t\t\t\t\t\tdrawRect0(bounds, null,\n\t\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(),\n\t\t\t\t\t\t\t\t gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(),\n\t\t\t\t\t\t\t\t //(float)((argbTL>>24)&0xff)/255.0f);\n\t\t\t\t\t\t\t\t 1.0f); // alpha already supplied\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdrawRect0(bounds, null,\n\t\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_FILLRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_CLEARRECT:\n\t\t\t\t// x, y, width, height, argbTL, argbTR, argbBR, argbBL\n\t\t\t\tif(len==32)\n\t\t\t\t{\n\t\t\t\t\tint x, y, width, height,\n\t\t\t\t\t\targbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=readInt(0, cmddata);\n\t\t\t\t\ty=readInt(4, cmddata);\n\t\t\t\t\twidth=readInt(8, cmddata);\n\t\t\t\t\theight=readInt(12, cmddata);\n\t\t\t\t\targbTL=readInt(16, cmddata);\n\t\t\t\t\targbTR=readInt(20, cmddata);\n\t\t\t\t\targbBR=readInt(24, cmddata);\n\t\t\t\t\targbBL=readInt(28, cmddata);\n//\t\t\t\t\tSystem.out.println(\"CLEARRECT: dest=(\"+x+\",\"+y+\" \"+width+\"x\"+height+\") argbTL=\"+Integer.toHexString(argbTL)+\" argbTR=\"+Integer.toHexString(argbTR)+\" argbBL=\"+Integer.toHexString(argbBL)+\" argbBR=\"+Integer.toHexString(argbBR));\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tclearRect0(destRect);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_CLEARRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWOVAL:\n\t\t\t\t// x, y, width, height, thickness, argbTL, argbTR, argbBR, argbBL,\n\t\t\t\t// clipX, clipY, clipW, clipH\n\t\t\t\tif(len==52)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height, clipX, clipY, clipW, clipH;\n\t\t\t\t\tint thickness, argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\tthickness=readInt(16, cmddata);\n\t\t\t\t\targbTL=readInt(20, cmddata);\n\t\t\t\t\targbTR=readInt(24, cmddata);\n\t\t\t\t\targbBR=readInt(28, cmddata);\n\t\t\t\t\targbBL=readInt(32, cmddata);\n\t\t\t\t\tclipX=(float)readInt(36, cmddata);\n\t\t\t\t\tclipY=(float)readInt(40, cmddata);\n\t\t\t\t\tclipW=(float)readInt(44, cmddata);\n\t\t\t\t\tclipH=(float)readInt(48, cmddata);\n//\t\t\t\t\tSystem.out.println(\"DRAWOVAL: dest=(\"+x+\",\"+y+\" \"+width+\"x\"+height+\") clip=(\"+clipX+\",\"+clipY+\" \"+clipW+\"x\"+clipH+\") thickness=\"+thickness+\" argbTL=\"+Integer.toHexString(argbTL)+\" argbTR=\"+Integer.toHexString(argbTR)+\" argbBL=\"+Integer.toHexString(argbBL)+\" argbBR=\"+Integer.toHexString(argbBR));\n\t\t\t\t\t// FIXME: no gradient for framed ovals\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH);\n\t\t\t\t\tdrawOval0(bounds, clipRect,\n\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), thickness,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWOVAL : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_FILLOVAL:\n\t\t\t\t// x, y, width, height, argbTL, argbTR, argbBR, argbBL,\n\t\t\t\t// clipX, clipY, clipW, clipH\n\t\t\t\tif(len==48)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height,\n\t\t\t\t\t\tclipX, clipY, clipW, clipH;\n\t\t\t\t\tint argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\targbTL=readInt(16, cmddata);\n\t\t\t\t\targbTR=readInt(20, cmddata);\n\t\t\t\t\targbBR=readInt(24, cmddata);\n\t\t\t\t\targbBL=readInt(28, cmddata);\n\t\t\t\t\tclipX=(float)readInt(32, cmddata);\n\t\t\t\t\tclipY=(float)readInt(36, cmddata);\n\t\t\t\t\tclipW=(float)readInt(40, cmddata);\n\t\t\t\t\tclipH=(float)readInt(44, cmddata);\n//\t\t\t\t\tSystem.out.println(\"FILLOVAL: dest=(\"+x+\",\"+y+\" \"+width+\"x\"+height+\") clip=(\"+clipX+\",\"+clipY+\" \"+clipW+\"x\"+clipH+\") argbTL=\"+Integer.toHexString(argbTL)+\" argbTR=\"+Integer.toHexString(argbTR)+\" argbBL=\"+Integer.toHexString(argbBL)+\" argbBR=\"+Integer.toHexString(argbBR));\n\t\t\t\t\tjava.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH);\n\t\t\t\t\tif(gp != null) {\n\t\t\t\t\t\tdrawOval0(bounds, clipRect,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(),\n\t\t\t\t\t\t\t\t gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(),\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdrawOval0(bounds, clipRect,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_FILLOVAL : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWROUNDRECT:\n\t\t\t\t// x, y, width, height, thickness, arcRadius, argbTL, argbTR, argbBR, argbBL,\n\t\t\t\t// clipX, clipY, clipW, clipH\n\t\t\t\tif(len==56)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height,\n\t\t\t\t\t\tclipX, clipY, clipW, clipH;\n\t\t\t\t\tint thickness, arcRadius,\n\t\t\t\t\t\targbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\tthickness=readInt(16, cmddata);\n\t\t\t\t\tarcRadius=readInt(20, cmddata);\n\t\t\t\t\targbTL=readInt(24, cmddata);\n\t\t\t\t\targbTR=readInt(28, cmddata);\n\t\t\t\t\targbBR=readInt(32, cmddata);\n\t\t\t\t\targbBL=readInt(36, cmddata);\n\t\t\t\t\tclipX=(float)readInt(40, cmddata);\n\t\t\t\t\tclipY=(float)readInt(44, cmddata);\n\t\t\t\t\tclipW=(float)readInt(48, cmddata);\n\t\t\t\t\tclipH=(float)readInt(52, cmddata);\n//\t\t\t\t\tSystem.out.println(\"DRAWROUNDRECT: dest=(\"+x+\",\"+y+\" \"+width+\"x\"+height+\") clip=(\"+clipX+\",\"+clipY+\" \"+clipW+\"x\"+clipH+\") thickness=\"+thickness+\" arcRadius=\"+arcRadius+\" argbTL=\"+Integer.toHexString(argbTL)+\" argbTR=\"+Integer.toHexString(argbTR)+\" argbBL=\"+Integer.toHexString(argbBL)+\" argbBR=\"+Integer.toHexString(argbBR));\n\t\t\t\t\t// FIXME: no gradients on stroked shapes\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH);\n\t\t\t\t\tdrawRect0(bounds, clipRect,\n\t\t\t\t\t\t\t arcRadius,\n\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), thickness,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWROUNDRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_FILLROUNDRECT:\n\t\t\t\t// x, y, width, height, arcRadius, argbTL, argbTR, argbBR, argbBL,\n\t\t\t\t// clipX, clipY, clipW, clipH\n\t\t\t\tif(len==52)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height,\n\t\t\t\t\t\tclipX, clipY, clipW, clipH;\n\t\t\t\t\tint arcRadius, argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\tarcRadius=readInt(16, cmddata);\n\t\t\t\t\targbTL=readInt(20, cmddata);\n\t\t\t\t\targbTR=readInt(24, cmddata);\n\t\t\t\t\targbBR=readInt(28, cmddata);\n\t\t\t\t\targbBL=readInt(32, cmddata);\n\t\t\t\t\tclipX=(float)readInt(36, cmddata);\n\t\t\t\t\tclipY=(float)readInt(40, cmddata);\n\t\t\t\t\tclipW=(float)readInt(44, cmddata);\n\t\t\t\t\tclipH=(float)readInt(48, cmddata);\n//\t\t\t\t\tSystem.out.println(\"FILLROUNDRECT: dest=(\"+x+\",\"+y+\" \"+width+\"x\"+height+\") clip=(\"+clipX+\",\"+clipY+\" \"+clipW+\"x\"+clipH+\") arcRadius=\"+arcRadius+\" argbTL=\"+Integer.toHexString(argbTL)+\" argbTR=\"+Integer.toHexString(argbTR)+\" argbBL=\"+Integer.toHexString(argbBL)+\" argbBR=\"+Integer.toHexString(argbBR));\n\t\t\t\t\tjava.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH);\n\t\t\t\t\tif(gp != null) {\n\t\t\t\t\t\tdrawRect0(bounds, clipRect,\n\t\t\t\t\t\t\t\t arcRadius,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(),\n\t\t\t\t\t\t\t\t gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(),\n\t\t\t\t\t\t\t\t //(float)((argbTL>>24)&0xff)/255.0f);\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdrawRect0(bounds, clipRect,\n\t\t\t\t\t\t\t\t arcRadius,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_FILLROUNDRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWTEXT:\n\t\t\t\t// x, y, len, text, handle, argb, clipX, clipY, clipW, clipH\n\t\t\t\tif(len>=36 && len>=(36+readInt(8, cmddata)*2))\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, clipX, clipY, clipW, clipH;\n\t\t\t\t\tint textlen, fontHandle, argb;\n\t\t\t\t\tStringBuffer text = new StringBuffer();\n\t\t\t\t\tint i;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\ttextlen=readInt(8, cmddata);\n\t\t\t\t\tfor(i=0;i> 24)&0xff))/255.0f : 1.0f);\n\t\t\t\t\t\t\tcomposite0(imagePtr.longValue(), currentLayer, srcRect, destRect, alpha, doBlend);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR invalid handle passed for texture rendering of: \" + handle);\n\t\t\t\t\t\t\tabortRenderCycle = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWTEXTURED : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWLINE:\n\t\t\t\t// x1, y1, x2, y2, argb1, argb2\n\t\t\t\tif(len==24)\n\t\t\t\t{\n\t\t\t\t\tfloat x1, y1, x2, y2;\n\t\t\t\t\tint argb1, argb2;\n\t\t\t\t\tx1=readInt(0, cmddata);\n\t\t\t\t\ty1=readInt(4, cmddata);\n\t\t\t\t\tx2=readInt(8, cmddata);\n\t\t\t\t\ty2=readInt(12, cmddata);\n\t\t\t\t\targb1=readInt(16, cmddata);\n\t\t\t\t\targb2=readInt(20, cmddata);\n//\t\t\t\t\tSystem.out.println(\"DRAWLINE: start=(\"+x1+\",\"+y1+\") end=(\"+x2+\",\"+y2+\") argb1=\"+Integer.toHexString(argb1)+\" argb2=\"+Integer.toHexString(argb2));\n\t\t\t\t\tdrawLine0(x1, y1, x2, y2, 1, new java.awt.Color(argb1, true));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWLINE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADIMAGE:\n\t\t\t\t// width, height\n\t\t\t\tif(len>=8)\n\t\t\t\t{\n\t\t\t\t\tint width, height;\n\t\t\t\t\tint imghandle = 0;\n\t\t\t\t\twidth=readInt(0, cmddata);\n\t\t\t\t\theight=readInt(4, cmddata);\n//\t\t\t\t\tSystem.out.println(\"LOADIMAGE: size=(\"+width+\"x\"+height+\")\");\n\t\t\t\t\tif (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t{\n\t\t\t\t\t\timghandle = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// creating a new image from bitmap data being sent over myConn, create a new empty image\n\t\t\t\t\t\tlong imagePtr = createNewImage0(width, height);\n\t\t\t\t\t\timghandle = handleCount++;\n//\t\t\t\t\t\tSystem.out.println(\" imghandle=\"+imghandle+\" imagePtr=\"+imagePtr);\n\t\t\t\t\t\timageMap.put(new Integer(imghandle), new Long(imagePtr));\t// actual value is filled in later when it's prepared\n\t\t\t\t\t\timageCacheSize += width * height * 4;\n\t\t\t\t\t}\n\t\t\t\t\thasret[0]=1;\n\t\t\t\t\treturn imghandle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADIMAGETARGETED:\n\t\t\t\t// handle, width, height // Not used unless we do uncompressed images\n\t\t\t\tif(len>=12)\n\t\t\t\t{\n\t\t\t\t\tint width, height;\n\t\t\t\t\tint imghandle = readInt(0, cmddata);\n\t\t\t\t\twidth=readInt(4, cmddata);\n\t\t\t\t\theight=readInt(8, cmddata);\n\t\t\t\t\twhile (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Keep freeing the oldest image until we have enough memory to do this\n\t\t\t\t\t\tint oldestImage = myConn.getOldestImage();\n\t\t\t\t\t\tif (oldestImage != 0)\n\t\t\t\t\t\t{\nSystem.out.println(\"Freeing image to make room in cache\");\n\t\t\t\t\t\t\tunloadImage(oldestImage);\n\t\t\t\t\t\t\tmyConn.postImageUnload(oldestImage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR cannot free enough from the cache to support loading a new image!!!\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlong imagePtr = createNewImage0(width, height);\n//\t\t\t\t\t\tSystem.out.println(\" imghandle=\"+imghandle+\" imagePtr=\"+imagePtr);\n\t\t\t\t\timageMap.put(new Integer(imghandle), new Long(imagePtr));\t// actual value is filled in later when it's prepared\n\t\t\t\t\timageCacheSize += width * height * 4;\n\t\t\t\t\tmyConn.registerImageAccess(imghandle);\n\t\t\t\t\thasret[0]=0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADIMAGETARGETED : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_CREATESURFACE:\n\t\t\t\t// width, height\n\t\t\t\tif(len>=8)\n\t\t\t\t{\n\t\t\t\t\tint width, height;\n\t\t\t\t\tint handle = handleCount++;;\n\t\t\t\t\twidth=readInt(0, cmddata);\n\t\t\t\t\theight=readInt(4, cmddata);\n\t\t\t\t\t// width/height is managed here\n\t\t\t\t\tlong layerPtr = createLayer0(c.getSize());\n\t\t\t\t\tlayerMap.put(new Integer(handle), new Long(layerPtr));\n//\t\t\t\t\tSystem.out.println(\"CREATESURFACE: (\"+width+\",\"+height+\") handle=\"+handle+\" layerPtr=\"+layerPtr);\n\t\t\t\t\thasret[0]=1;\n\t\t\t\t\treturn handle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_CREATESURFACE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_PREPIMAGE:\n\t\t\t\t// width, height\n\t\t\t\tif(len>=8)\n\t\t\t\t{\n\t\t\t\t\tint width, height;\n\t\t\t\t\t//int imghandle = handleCount++;;\n\t\t\t\t\twidth=readInt(0, cmddata);\n\t\t\t\t\theight=readInt(4, cmddata);\n\t\t\t\t\tint imghandle = 1;\n//\t\t\t\t\tSystem.out.println(\"PREPIMAGE: size=(\"+width+\"x\"+height+\")\");\n\t\t\t\t\tif (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t\timghandle = 0;\n\t\t\t\t\telse if (len >= 12)\n\t\t\t\t\t{\n\t\t\t\t\t\t// We've got enough room for it and there's a cache ID, check if we've got it cached locally\n\t\t\t\t\t\tint strlen = readInt(8, cmddata);\n\t\t\t\t\t\tif (strlen > 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tString rezName = new String(cmddata, 16, strlen - 1);\n//\t\t\t\t\t\t\tSystem.out.println(\" rezName=\"+rezName);\n\t\t\t\t\t\t\tlastImageResourceID = rezName;\n\t\t\t\t\t\t\t// We use this hashcode to match it up on the loadCompressedImage call so we know we're caching the right thing\n\t\t\t\t\t\t\tlastImageResourceIDHandle = imghandle = Math.abs(lastImageResourceID.hashCode());\n\t\t\t\t\t\t\tjava.io.File cachedFile = myConn.getCachedImageFile(rezName);\n\t\t\t\t\t\t\tif (cachedFile != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// We've got it locally in our cache! Read it from there.\n\t\t\t\t\t\t\t\tlong imagePtr = createImageFromPath0(cachedFile.getAbsolutePath());\n\t\t\t\t\t\t\t\tif(imagePtr != 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tjava.awt.Dimension imgSize = getImageDimensions0(imagePtr);\n\t\t\t\t\t\t\t\t\tif(imgSize != null)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif(imgSize.getWidth() == width && imgSize.getHeight() == height)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t// valid image in cache, use it\n\t\t\t\t\t\t\t\t\t\t\timghandle = handleCount++;\n//\t\t\t\t\t\t\t\t\t\t\tSystem.out.println(\" loaded from cache, imagePtr=\"+imagePtr+\" handle=\"+imghandle);\n\t\t\t\t\t\t\t\t\t\t\timageMap.put(new Integer(imghandle), new Long(imagePtr));\n\t\t\t\t\t\t\t\t\t\t\timageCacheSize += getImageSize0(imagePtr);\n\t\t\t\t\t\t\t\t\t\t\thasret[0] = 1;\n\t\t\t\t\t\t\t\t\t\t\treturn -1 * imghandle;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tfreeNativeImage0(imagePtr);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tfreeNativeImage0(imagePtr);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//imghandle=STBGFX.GFX_loadImage(width, height);\n\t\t\t\t\thasret[0]=1;\n\t\t\t\t\treturn imghandle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_PREPIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_PREPIMAGETARGETED:\n\t\t\t\t// handle, width, height, [rezID]\n\t\t\t\tif(len>=12)\n\t\t\t\t{\n\t\t\t\t\tint imghandle, width, height;\n\t\t\t\t\timghandle = readInt(0, cmddata);\n\t\t\t\t\twidth=readInt(4, cmddata);\n\t\t\t\t\theight=readInt(8, cmddata);\n\t\t\t\t\tint strlen = readInt(12, cmddata);\n\t\t\t\t\twhile (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Keep freeing the oldest image until we have enough memory to do this\n\t\t\t\t\t\tint oldestImage = myConn.getOldestImage();\n\t\t\t\t\t\tif (oldestImage != 0)\n\t\t\t\t\t\t{\nSystem.out.println(\"Freeing image to make room in cache\");\n\t\t\t\t\t\t\tunloadImage(oldestImage);\n\t\t\t\t\t\t\tmyConn.postImageUnload(oldestImage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR cannot free enough from the cache to support loading a new image!!!\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (len >= 16)\n\t\t\t\t\t{\n\t\t\t\t\t\t// We will not have this cached locally...but setup our vars to track it\n\t\t\t\t\t\tString rezName = new String(cmddata, 20, strlen - 1);\n\t\t\t\t\t\tlastImageResourceID = rezName;\n\t\t\t\t\t\tlastImageResourceIDHandle = imghandle;\nSystem.out.println(\"Prepped targeted image with handle \" + imghandle + \" resource=\" + rezName);\n\t\t\t\t\t}\n\t\t\t\t\tmyConn.registerImageAccess(imghandle);\n\t\t\t\t\thasret[0]=0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_PREPIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADCACHEDIMAGE:\n\t\t\t\t// width, height\n\t\t\t\tif(len>=18)\n\t\t\t\t{\n\t\t\t\t\tint width, height, imghandle;\n\t\t\t\t\timghandle = readInt(0, cmddata);\n\t\t\t\t\twidth = readInt(4, cmddata);\n\t\t\t\t\theight = readInt(8, cmddata);\n\t\t\t\t\tint strlen = readInt(12, cmddata);\n\t\t\t\t\tString rezName = new String(cmddata, 20, strlen - 1);\nSystem.out.println(\"imghandle=\" + imghandle + \" width=\" + width + \" height=\" + height + \" strlen=\" + strlen + \" rezName=\" + rezName);\n\t\t\t\t\twhile (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Keep freeing the oldest image until we have enough memory to do this\n\t\t\t\t\t\tint oldestImage = myConn.getOldestImage();\n\t\t\t\t\t\tif (oldestImage != 0)\n\t\t\t\t\t\t{\nSystem.out.println(\"Freeing image to make room in cache\");\n\t\t\t\t\t\t\tunloadImage(oldestImage);\n\t\t\t\t\t\t\tmyConn.postImageUnload(oldestImage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR cannot free enough from the cache to support loading a new image!!!\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tmyConn.registerImageAccess(imghandle);\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tSystem.out.println(\"Loading resource from cache: \" + rezName);\n\t\t\t\t\t\tjava.io.File cachedFile = myConn.getCachedImageFile(rezName);\n\t\t\t\t\t\tif (cachedFile != null)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// We've got it locally in our cache! Read it from there.\n\t\t\t\t\t\t\tSystem.out.println(\"Image found in cache!\");\n\t\t\t\t\t\t\t// We've got it locally in our cache! Read it from there.\n\t\t\t\t\t\t\tlong imagePtr = createImageFromPath0(cachedFile.getAbsolutePath());\n\t\t\t\t\t\t\tif(imagePtr != 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tjava.awt.Dimension imgSize = getImageDimensions0(imagePtr);\n\t\t\t\t\t\t\t\tif(imgSize != null && imgSize.getWidth() == width && imgSize.getHeight() == height)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t// valid image in cache, use it\n//\t\t\t\t\t\t\t\t\t\t\tSystem.out.println(\" loaded from cache, imagePtr=\"+imagePtr+\" handle=\"+imghandle);\n\t\t\t\t\t\t\t\t\timageMap.put(new Integer(imghandle), new Long(imagePtr));\n\t\t\t\t\t\t\t\t\timageCacheSize += getImageSize0(imagePtr);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (imgSize != null)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t// It doesn't match the cache\n\t\t\t\t\t\t\t\t\t\tSystem.out.println(\"CACHE ID verification failed for rezName=\" + rezName + \" target=\" + width + \"x\" + height + \" actual=\" + imgSize.getWidth() + \"x\" + imgSize.getHeight());\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tSystem.out.println(\"CACHE Load failed for rezName=\" + rezName);\n\t\t\t\t\t\t\t\t\tcachedFile.delete();\n\t\t\t\t\t\t\t\t\tfreeNativeImage0(imagePtr);\n\t\t\t\t\t\t\t\t\t// This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded.\n\t\t\t\t\t\t\t\t\tmyConn.postImageUnload(imghandle);\n\t\t\t\t\t\t\t\t\tmyConn.postOfflineCacheChange(false, rezName);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcachedFile.delete();\n\t\t\t\t\t\t\t\t// This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded.\n\t\t\t\t\t\t\t\tmyConn.postImageUnload(imghandle);\n\t\t\t\t\t\t\t\tmyConn.postOfflineCacheChange(false, rezName);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR Image not found in cache that should be there! rezName=\" + rezName);\n\t\t\t\t\t\t\t// This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded.\n\t\t\t\t\t\t\tmyConn.postImageUnload(imghandle);\n\t\t\t\t\t\t\tmyConn.postOfflineCacheChange(false, rezName);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (java.io.IOException e)\n\t\t\t\t\t{\n\t\t\t\t\t\tSystem.out.println(\"ERROR loading compressed image: \" + e);\n\t\t\t\t\t}\n\t\t\t\t\thasret[0]=0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_PREPIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_UNLOADIMAGE:\n\t\t\t\t// handle\n\t\t\t\tif(len==4)\n\t\t\t\t{\n\t\t\t\t\tint handle;\n\t\t\t\t\thandle=readInt(0, cmddata);\n\t\t\t\t\tunloadImage(handle);\n\t\t\t\t\tmyConn.clearImageAccess(handle);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_UNLOADIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_SETTARGETSURFACE:\n\t\t\t\t// handle\n\t\t\t\tif(len==4)\n\t\t\t\t{\n\t\t\t\t\tint handle;\n\t\t\t\t\thandle=readInt(0, cmddata);\n\t\t\t\t\t//STBGFX.GFX_unloadImage(handle);\n\t\t\t\t\tLong layerPtr = (Long)layerMap.get(new Integer(handle));\n//\t\t\t\t\tSystem.out.println(\"SETTARGETSURFACE: handle=\"+handle+\" layerPtr=\"+ (layerPtr == null ? \"0\" : Long.toHexString(layerPtr.longValue())));\n\t\t\t\t\tcurrentLayer = (layerPtr != null) ? layerPtr.longValue() : 0;\n\t\t\t\t\tjava.awt.Rectangle clipRect = new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight());\n\t\t\t\t\tsetLayer0(currentLayer, c.getSize(), clipRect);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_SETTARGETSURFACE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADFONT:\n\t\t\t\t// namelen, name, style, size\n\t\t\t\tif(len>=12 && len>=(12+readInt(0, cmddata)))\n\t\t\t\t{\n\t\t\t\t\tint namelen, style, size;\n\t\t\t\t\tStringBuffer name = new StringBuffer();\n\t\t\t\t\tint i;\n\t\t\t\t\tint fonthandle = handleCount++;\n\t\t\t\t\tnamelen=readInt(0, cmddata);\n\t\t\t\t\tfor(i=0;i=8)\n\t\t\t\t{\n\t\t\t\t\tStringBuffer name = new StringBuffer();\n\t\t\t\t\tint namelen = readInt(0, cmddata);\n\t\t\t\t\tfor(int i=0;i= datalen + 8 + namelen)\n\t\t\t\t\t{\n//\t\t\t\t\t\tSystem.out.println(\"Saving font \" + name.toString() + \" to cache\");\n\t\t\t\t\t\tmyConn.saveCacheData(name.toString() + \"-\" + myConn.getServerName(), cmddata, 12 + namelen, datalen);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADFONTSTREAM : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_FLIPBUFFER:\n//\t\t\t\tSystem.out.println(\"FLIPBUFFER\");\n\t\t\t\tif (abortRenderCycle)\n\t\t\t\t{\nSystem.out.println(\"ERROR in painting cycle, ABORT was set...send full repaint command\");\n\t\t\t\t\tmyConn.postRepaintEvent(0, 0, c.getWidth(), c.getHeight());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpresent0(c.nativeView, new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight()));\n\t\t\t\t}\n\t\t\t\thasret[0] = 1;\n\t\t\t\t//STBGFX.GFX_flipBuffer();\n\t\t\t\tfirstFrameDone = true;\n\t\t\t\treturn 0;\n\t\t\tcase GFXCMD_STARTFRAME:\n//\t\t\t\tSystem.out.println(\"STARTFRAME\");\n\t\t\t\t// prepare for a new frame to be rendered\n\t\t\t\tsetTargetView0(c.nativeView);\n\t\t\t\tsetLayer0(0, c.getSize(), null); // this makes sure the drawing surface gets resized properly\n\t\t\t\tabortRenderCycle = false;\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADIMAGELINE:\n\t\t\t\t// handle, line, len, data\n\t\t\t\tif(len>=12 && len>=(12+readInt(8, cmddata)))\n\t\t\t\t{\n\t\t\t\t\tint handle, line, len2;\n\t\t\t\t\t//unsigned char *data=&cmddata[12];\n\t\t\t\t\thandle=readInt(0, cmddata);\n\t\t\t\t\tline=readInt(4, cmddata);\n\t\t\t\t\tlen2=readInt(8, cmddata);\n\t\t\t\t\t// the last number is the offset into the data array to start reading from\n\t\t\t\t\t//STBGFX.GFX_loadImageLine(handle, line, len, data, 12);\n\t\t\t\t\t//int dataPos = 12;\n\t\t\t\t\tLong imagePtr = (Long)imageMap.get(new Integer(handle));\n//\t\t\t\t\tSystem.out.println(\"LOADIMAGELINE: handle=\"+handle+\" imagePtr=\"+imagePtr+\" line=\"+line+\" len2=\"+len2);\n\t\t\t\t\tif(imagePtr != null)\n\t\t\t\t\t\tloadImageLine0(imagePtr.longValue(), line, cmddata, 16/*12*/, len2);\n\t\t\t\t\tmyConn.registerImageAccess(handle);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADIMAGELINE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADIMAGECOMPRESSED:\n\t\t\t\t// handle, line, len, data\n\t\t\t\tif(len>=8 && len>=(8+readInt(4, cmddata)))\n\t\t\t\t{\n\t\t\t\t\tint handle, len2;\n\t\t\t\t\thandle=readInt(0, cmddata);\n\t\t\t\t\tlen2=readInt(4, cmddata);\n\t\t\t\t\tif (lastImageResourceID != null && lastImageResourceIDHandle == handle)\n\t\t\t\t\t{\n\t\t\t\t\t\tmyConn.saveCacheData(lastImageResourceID, cmddata, 12, len2);\n\t\t\t\t\t\tmyConn.postOfflineCacheChange(true, lastImageResourceID);\n\t\t\t\t\t}\n\t\t\t\t\tif (!myConn.doesUseAdvancedImageCaching())\n\t\t\t\t\t{\n\t\t\t\t\t\thandle = handleCount++;\n\t\t\t\t\t\thasret[0] = 1;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\thasret[0] = 0;\n\t\t\t\t\tmyConn.registerImageAccess(handle);\n\t\t\t\t\tlong imagePtr = createImageFromBytes0(cmddata, 12, len2, null); // FIXME: grab extension if possible\n//\t\t\t\t\tSystem.out.println(\"LOADIMAGECOMPRESSED: handle=\"+handle+\" imagePtr=\"+imagePtr+\" len2=\"+len2);\n\t\t\t\t\timageMap.put(new Integer(handle), new Long(imagePtr));\n\t\t\t\t\timageCacheSize += getImageSize0(imagePtr);\n\t\t\t\t\treturn handle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADIMAGECOMPRESSED : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_XFMIMAGE:\n\t\t\t\t// srcHandle, destHandle, destWidth, destHeight, maskCornerArc\n\t\t\t\tif (len >= 20)\n\t\t\t\t{\n\t\t\t\t\tint srcHandle, destHandle, destWidth, destHeight, maskCornerArc;\n\t\t\t\t\tsrcHandle = readInt(0, cmddata);\n\t\t\t\t\tdestHandle = readInt(4, cmddata);\t\t// seems to be unused\n\t\t\t\t\tdestWidth = readInt(8, cmddata);\t\t// scaled size (ignore?)\n\t\t\t\t\tdestHeight = readInt(12, cmddata);\n\t\t\t\t\tmaskCornerArc = readInt(16, cmddata);\n\t\t\t\t\tint rvHandle = destHandle;\n\t\t\t\t\tif (!myConn.doesUseAdvancedImageCaching())\n\t\t\t\t\t{\n\t\t\t\t\t\trvHandle = handleCount++;\n\t\t\t\t\t\thasret[0] = 1;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\thasret[0] = 0;\n\t\t\t\t\t// we cheat and apply the transforms to a metaimage object without actually creating a new image (saves oodles of memory)\n\t\t\t\t\tLong srcImg = (Long)imageMap.get(new Integer(srcHandle));\n//\t\t\t\t\tSystem.out.println(\"XFMIMAGE: srcHandle=\"+srcHandle+\" srcImg=\"+srcImg+\" destHandle=\"+destHandle+\" destWidth=\"+destWidth+\" destHeight=\"+destHeight+\" maskCornerArc=\"+maskCornerArc);\n\t\t\t\t\tif(srcImg != null) {\n\t\t\t\t\t\tlong newImage = transformImage0(srcImg.longValue(), destWidth, destHeight, maskCornerArc);\n\t\t\t\t\t\tif(newImage != 0) {\n//\t\t\t\t\t\t\tSystem.out.println(\" newImage=\"+newImage);\n\t\t\t\t\t\t\timageMap.put(new Integer(rvHandle), new Long(newImage));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn rvHandle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_XFMIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_SETVIDEOPROP:\n\t\t\t\tif (len >= 40)\n\t\t\t\t{\n\t\t\t\t\tjava.awt.Rectangle srcRect = new java.awt.Rectangle(readInt(4, cmddata), readInt(8, cmddata),\n\t\t\t\t\t\treadInt(12, cmddata), readInt(16, cmddata));\n\t\t\t\t\tjava.awt.Rectangle destRect = new java.awt.Rectangle(readInt(20, cmddata), readInt(24, cmddata),\n\t\t\t\t\t\treadInt(28, cmddata), readInt(32, cmddata));\n\t\t\t\t\tSystem.out.println(\"SETVIDEOPROP: srcRect=\"+srcRect+\" dstRect=\"+destRect);\n\t\t\t\t\tsetVideoBounds(srcRect, destRect);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_SETVIDEOPROP: \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn -1;\n\t\t}\n\t\treturn 0;\n\t}"},"code_wo_comment":{"kind":"string","value":"public int ExecuteGFXCommand(int cmd, int len, byte[] cmddata, int[] hasret)\n\t{\n\t\tlen -= 4;\n\t hasret[0] = 0;\n\t\n\t\tif((cmd != GFXCMD_INIT) && (cmd != GFXCMD_DEINIT))\n\t\t{\n\t\t\tif((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) {\n\t\t\t\n\t\t\t\twhile((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.sleep(10);\n\t\t\t\t\t} catch(InterruptedException ex) {}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (c != null)\n\t\t{\n\t\t\tswitch(cmd)\n\t\t\t{\n\t\t\t\tcase GFXCMD_INIT:\n\t\t\t\tcase GFXCMD_DEINIT:\n\t\t\t\tcase GFXCMD_STARTFRAME:\n\t\t\t\tcase GFXCMD_FLIPBUFFER:\n\t\t\t\t\tc.setCursor(null);\n\t\t\t\t\tbreak;\n\t\t\t\tcase GFXCMD_DRAWRECT:\n\t\t\t\tcase GFXCMD_FILLRECT:\n\t\t\t\tcase GFXCMD_CLEARRECT:\n\t\t\t\tcase GFXCMD_DRAWOVAL:\n\t\t\t\tcase GFXCMD_FILLOVAL:\n\t\t\t\tcase GFXCMD_DRAWROUNDRECT:\n\t\t\t\tcase GFXCMD_FILLROUNDRECT:\n\t\t\t\tcase GFXCMD_DRAWTEXT:\n\t\t\t\tcase GFXCMD_DRAWTEXTURED:\n\t\t\t\tcase GFXCMD_DRAWLINE:\n\t\t\t\tcase GFXCMD_LOADIMAGE:\n\t\t\t\tcase GFXCMD_LOADIMAGETARGETED:\n\t\t\t\tcase GFXCMD_UNLOADIMAGE:\n\t\t\t\tcase GFXCMD_LOADFONT:\n\t\t\t\tcase GFXCMD_UNLOADFONT:\n\t\t\t\tcase GFXCMD_SETTARGETSURFACE:\n\t\t\t\tcase GFXCMD_CREATESURFACE:\n\t\t\t\t\tbreak;\n\t\t\t\tcase GFXCMD_PREPIMAGE:\n\t\t\t\tcase GFXCMD_LOADIMAGELINE:\n\t\t\t\tcase GFXCMD_LOADIMAGECOMPRESSED:\n\t\t\t\tcase GFXCMD_XFMIMAGE:\n\t\t\t\tcase GFXCMD_LOADCACHEDIMAGE:\n\t\t\t\tcase GFXCMD_PREPIMAGETARGETED:\n\t\t\t\t\tif (!cursorHidden)\n\t\t\t\t\t\tc.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tswitch(cmd)\n\t\t{\n\t\t\tcase GFXCMD_INIT:\n\t\t\t\thasret[0] = 1;\n\t\t\t\n\t\t\t\tinit0();\n\t\t\t\tint windowTitleStyle = 0;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\twindowTitleStyle = Integer.parseInt(MiniClient.myProperties.getProperty(\"window_title_style\", \"0\"));\n\t\t\t\t}\n\t\t\t\tcatch (NumberFormatException e){}\n\t\t\t\tif (!\"true\".equals(MiniClient.myProperties.getProperty(\"enable_custom_title_bar\", MiniClient.MAC_OS_X ? \"false\" : \"true\")))\n\t\t\t\t\twindowTitleStyle = 10;\n\t\t\t\tf = new MiniClientWindow(myConn.getWindowTitle(), windowTitleStyle);\n\t\t\t\tjava.awt.LayoutManager layer = new java.awt.LayoutManager()\n\t\t\t\t\t{\n\t\t\t\t\t\tpublic void addLayoutComponent(String name, java.awt.Component comp)\n\t\t\t\t\t\t{}\n\t\t\t\t\t\tpublic java.awt.Dimension minimumLayoutSize(java.awt.Container parent)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn preferredLayoutSize(parent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpublic java.awt.Dimension preferredLayoutSize(java.awt.Container parent)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn parent.getPreferredSize();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpublic void removeLayoutComponent(java.awt.Component comp)\n\t\t\t\t\t\t{}\n\t\t\t\t\t\tpublic void layoutContainer(java.awt.Container parent)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tc.setBounds(parent.getInsets().left, parent.getInsets().top, parent.getWidth() - parent.getInsets().left - parent.getInsets().right,\n\t\t\t\t\t\t\t\tparent.getHeight() - parent.getInsets().top - parent.getInsets().bottom);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\tf.getContentPane().setLayout(layer);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tbgImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource(\"images/Background.jpg\"));\n\t\t\t\t\tensureImageIsLoaded(bgImage);\n\t\t\t\t\tlogoImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource(\"images/SageLogo256.png\"));\n\t\t\t\t\tensureImageIsLoaded(logoImage);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"ERROR:\" + e);\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tf.setFocusTraversalKeysEnabled(false);\n\t\t\t\n\t\t\t\tjava.awt.Dimension panelSize = f.getContentPane().getSize();\n\t\t\t\tc = new QuartzRendererView();\n\t\t\t\tc.setSize(panelSize);\n\t\t\t\tc.setFocusTraversalKeysEnabled(false);\n\t\t\t\tf.getContentPane().add(c);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tjava.awt.Image frameIcon = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource(\"images/tvicon.gif\"));\n\t\t\t\t\tensureImageIsLoaded(frameIcon);\n\t\t\t\t\tf.setIconImage(frameIcon);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"ERROR:\" + e);\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tf.addWindowListener(new java.awt.event.WindowAdapter()\n\t\t\t\t{\n\t\t\t\t\tpublic void windowClosing(java.awt.event.WindowEvent evt)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!f.isFullScreen() || System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") != -1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMiniClient.myProperties.setProperty(\"main_window_width\", Integer.toString(f.getWidth()));\n\t\t\t\t\t\t\tMiniClient.myProperties.setProperty(\"main_window_height\", Integer.toString(f.getHeight()));\n\t\t\t\t\t\t\tMiniClient.myProperties.setProperty(\"main_window_x\", Integer.toString(f.getX()));\n\t\t\t\t\t\t\tMiniClient.myProperties.setProperty(\"main_window_y\", Integer.toString(f.getY()));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmyConn.close();\n\t\t\t\t\t\tclose();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tc.addComponentListener(new java.awt.event.ComponentAdapter()\n\t\t\t\t{\n\t\t\t\t\tpublic void componentResized(java.awt.event.ComponentEvent evt)\n\t\t\t\t\t{\n\t\t\t\t\t\tmyConn.postResizeEvent(new java.awt.Dimension(c.getWidth(), c.getHeight()));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tf.addKeyListener(this);\n\t\t\t\tc.addKeyListener(this);\n\t\t\t\n\t\t\t\tf.addMouseWheelListener(this);\n\t\t\t\tc.addMouseListener(this);\n\t\t\t\tif (ENABLE_MOUSE_MOTION_EVENTS)\n\t\t\t\t{\n\t\t\t\t\n\t\t\t\t\tc.addMouseMotionListener(this);\n\t\t\t\t}\n\t\t\t\tint frameX = 100;\n\t\t\t\tint frameY = 100;\n\t\t\t\tint frameW = 720;\n\t\t\t\tint frameH = 480;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tframeW = Integer.parseInt(MiniClient.myProperties.getProperty(\"main_window_width\", \"720\"));\n\t\t\t\t\tframeH = Integer.parseInt(MiniClient.myProperties.getProperty(\"main_window_height\", \"480\"));\n\t\t\t\t\tframeX = Integer.parseInt(MiniClient.myProperties.getProperty(\"main_window_x\", \"100\"));\n\t\t\t\t\tframeY = Integer.parseInt(MiniClient.myProperties.getProperty(\"main_window_y\", \"100\"));\n\t\t\t\t}\n\t\t\t\tcatch (NumberFormatException e){}\n\t\t\t\tjava.awt.Point newPos = new java.awt.Point(frameX, frameY);\n\t\t\t\tboolean foundScreen = sage.UIUtils.isPointOnAScreen(newPos);\n\t\t\t\tif (!foundScreen)\n\t\t\t\t{\n\t\t\t\t\tnewPos.x = 150;\n\t\t\t\t\tnewPos.y = 150;\n\t\t\t\t}\n\t\t\t\tf.setVisible(true);\n\t\t\t\tf.setSize(1,1);\n\t\t\t\tf.setSize(Math.max(frameW, 320), Math.max(frameH, 240));\n\t\t\t\tf.setLocation(newPos);\n\t\t\t\tif (MiniClient.fsStartup)\n\t\t\t\t\tf.setFullScreen(true);\n\t\t\t\tMiniClient.hideSplash();\n\t\t\t\treturn 1;\n\t\t\tcase GFXCMD_DEINIT:\n\t\t\t\tclose();\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWRECT:\n\t\t\t\tif(len==36)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height;\n\t\t\t\t\tint thickness, argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\tthickness=readInt(16, cmddata);\n\t\t\t\t\targbTL=readInt(20, cmddata);\n\t\t\t\t\targbTR=readInt(24, cmddata);\n\t\t\t\t\targbBR=readInt(28, cmddata);\n\t\t\t\t\targbBL=readInt(32, cmddata);\n\t\t\t\t\n\t\t\t\t\tdrawRect0(new java.awt.geom.Rectangle2D.Float(x, y, width, height), null,\n\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), thickness,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_FILLRECT:\n\t\t\t\n\t\t\t\tif(len==32)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height;\n\t\t\t\t\tint argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\targbTL=readInt(16, cmddata);\n\t\t\t\t\targbTR=readInt(20, cmddata);\n\t\t\t\t\targbBR=readInt(24, cmddata);\n\t\t\t\t\targbBL=readInt(28, cmddata);\n\t\t\t\t\tjava.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tif(gp != null) {\n\t\t\t\t\t\tdrawRect0(bounds, null,\n\t\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(),\n\t\t\t\t\t\t\t\t gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(),\n\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdrawRect0(bounds, null,\n\t\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_FILLRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_CLEARRECT:\n\t\t\t\n\t\t\t\tif(len==32)\n\t\t\t\t{\n\t\t\t\t\tint x, y, width, height,\n\t\t\t\t\t\targbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=readInt(0, cmddata);\n\t\t\t\t\ty=readInt(4, cmddata);\n\t\t\t\t\twidth=readInt(8, cmddata);\n\t\t\t\t\theight=readInt(12, cmddata);\n\t\t\t\t\targbTL=readInt(16, cmddata);\n\t\t\t\t\targbTR=readInt(20, cmddata);\n\t\t\t\t\targbBR=readInt(24, cmddata);\n\t\t\t\t\targbBL=readInt(28, cmddata);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tclearRect0(destRect);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_CLEARRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWOVAL:\n\t\t\t\n\t\t\t\n\t\t\t\tif(len==52)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height, clipX, clipY, clipW, clipH;\n\t\t\t\t\tint thickness, argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\tthickness=readInt(16, cmddata);\n\t\t\t\t\targbTL=readInt(20, cmddata);\n\t\t\t\t\targbTR=readInt(24, cmddata);\n\t\t\t\t\targbBR=readInt(28, cmddata);\n\t\t\t\t\targbBL=readInt(32, cmddata);\n\t\t\t\t\tclipX=(float)readInt(36, cmddata);\n\t\t\t\t\tclipY=(float)readInt(40, cmddata);\n\t\t\t\t\tclipW=(float)readInt(44, cmddata);\n\t\t\t\t\tclipH=(float)readInt(48, cmddata);\n\t\t\t\t\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH);\n\t\t\t\t\tdrawOval0(bounds, clipRect,\n\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), thickness,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWOVAL : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_FILLOVAL:\n\t\t\t\n\t\t\t\n\t\t\t\tif(len==48)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height,\n\t\t\t\t\t\tclipX, clipY, clipW, clipH;\n\t\t\t\t\tint argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\targbTL=readInt(16, cmddata);\n\t\t\t\t\targbTR=readInt(20, cmddata);\n\t\t\t\t\targbBR=readInt(24, cmddata);\n\t\t\t\t\targbBL=readInt(28, cmddata);\n\t\t\t\t\tclipX=(float)readInt(32, cmddata);\n\t\t\t\t\tclipY=(float)readInt(36, cmddata);\n\t\t\t\t\tclipW=(float)readInt(40, cmddata);\n\t\t\t\t\tclipH=(float)readInt(44, cmddata);\n\t\t\t\t\tjava.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH);\n\t\t\t\t\tif(gp != null) {\n\t\t\t\t\t\tdrawOval0(bounds, clipRect,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(),\n\t\t\t\t\t\t\t\t gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(),\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdrawOval0(bounds, clipRect,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_FILLOVAL : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWROUNDRECT:\n\t\t\t\n\t\t\t\n\t\t\t\tif(len==56)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height,\n\t\t\t\t\t\tclipX, clipY, clipW, clipH;\n\t\t\t\t\tint thickness, arcRadius,\n\t\t\t\t\t\targbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\tthickness=readInt(16, cmddata);\n\t\t\t\t\tarcRadius=readInt(20, cmddata);\n\t\t\t\t\targbTL=readInt(24, cmddata);\n\t\t\t\t\targbTR=readInt(28, cmddata);\n\t\t\t\t\targbBR=readInt(32, cmddata);\n\t\t\t\t\targbBL=readInt(36, cmddata);\n\t\t\t\t\tclipX=(float)readInt(40, cmddata);\n\t\t\t\t\tclipY=(float)readInt(44, cmddata);\n\t\t\t\t\tclipW=(float)readInt(48, cmddata);\n\t\t\t\t\tclipH=(float)readInt(52, cmddata);\n\t\t\t\t\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH);\n\t\t\t\t\tdrawRect0(bounds, clipRect,\n\t\t\t\t\t\t\t arcRadius,\n\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), thickness,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWROUNDRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_FILLROUNDRECT:\n\t\t\t\n\t\t\t\n\t\t\t\tif(len==52)\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, width, height,\n\t\t\t\t\t\tclipX, clipY, clipW, clipH;\n\t\t\t\t\tint arcRadius, argbTL, argbTR, argbBR, argbBL;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\twidth=(float)readInt(8, cmddata);\n\t\t\t\t\theight=(float)readInt(12, cmddata);\n\t\t\t\t\tarcRadius=readInt(16, cmddata);\n\t\t\t\t\targbTL=readInt(20, cmddata);\n\t\t\t\t\targbTR=readInt(24, cmddata);\n\t\t\t\t\targbBR=readInt(28, cmddata);\n\t\t\t\t\targbBL=readInt(32, cmddata);\n\t\t\t\t\tclipX=(float)readInt(36, cmddata);\n\t\t\t\t\tclipY=(float)readInt(40, cmddata);\n\t\t\t\t\tclipW=(float)readInt(44, cmddata);\n\t\t\t\t\tclipH=(float)readInt(48, cmddata);\n\t\t\t\t\tjava.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height);\n\t\t\t\t\tjava.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH);\n\t\t\t\t\tif(gp != null) {\n\t\t\t\t\t\tdrawRect0(bounds, clipRect,\n\t\t\t\t\t\t\t\t arcRadius,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(),\n\t\t\t\t\t\t\t\t gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(),\n\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdrawRect0(bounds, clipRect,\n\t\t\t\t\t\t\t\t arcRadius,\n\t\t\t\t\t\t\t\t null, 0,\n\t\t\t\t\t\t\t\t new java.awt.Color(argbTL, true), 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t null, 0.0f, 0.0f,\n\t\t\t\t\t\t\t\t 1.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_FILLROUNDRECT : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWTEXT:\n\t\t\t\n\t\t\t\tif(len>=36 && len>=(36+readInt(8, cmddata)*2))\n\t\t\t\t{\n\t\t\t\t\tfloat x, y, clipX, clipY, clipW, clipH;\n\t\t\t\t\tint textlen, fontHandle, argb;\n\t\t\t\t\tStringBuffer text = new StringBuffer();\n\t\t\t\t\tint i;\n\t\t\t\t\tx=(float)readInt(0, cmddata);\n\t\t\t\t\ty=(float)readInt(4, cmddata);\n\t\t\t\t\ttextlen=readInt(8, cmddata);\n\t\t\t\t\tfor(i=0;i> 24)&0xff))/255.0f : 1.0f);\n\t\t\t\t\t\t\tcomposite0(imagePtr.longValue(), currentLayer, srcRect, destRect, alpha, doBlend);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR invalid handle passed for texture rendering of: \" + handle);\n\t\t\t\t\t\t\tabortRenderCycle = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWTEXTURED : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_DRAWLINE:\n\t\t\t\n\t\t\t\tif(len==24)\n\t\t\t\t{\n\t\t\t\t\tfloat x1, y1, x2, y2;\n\t\t\t\t\tint argb1, argb2;\n\t\t\t\t\tx1=readInt(0, cmddata);\n\t\t\t\t\ty1=readInt(4, cmddata);\n\t\t\t\t\tx2=readInt(8, cmddata);\n\t\t\t\t\ty2=readInt(12, cmddata);\n\t\t\t\t\targb1=readInt(16, cmddata);\n\t\t\t\t\targb2=readInt(20, cmddata);\n\t\t\t\t\tdrawLine0(x1, y1, x2, y2, 1, new java.awt.Color(argb1, true));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_DRAWLINE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADIMAGE:\n\t\t\t\n\t\t\t\tif(len>=8)\n\t\t\t\t{\n\t\t\t\t\tint width, height;\n\t\t\t\t\tint imghandle = 0;\n\t\t\t\t\twidth=readInt(0, cmddata);\n\t\t\t\t\theight=readInt(4, cmddata);\n\t\t\t\t\tif (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t{\n\t\t\t\t\t\timghandle = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\tlong imagePtr = createNewImage0(width, height);\n\t\t\t\t\t\timghandle = handleCount++;\n\t\t\t\t\t\timageMap.put(new Integer(imghandle), new Long(imagePtr));\n\t\t\t\t\t\timageCacheSize += width * height * 4;\n\t\t\t\t\t}\n\t\t\t\t\thasret[0]=1;\n\t\t\t\t\treturn imghandle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADIMAGETARGETED:\n\t\t\t\n\t\t\t\tif(len>=12)\n\t\t\t\t{\n\t\t\t\t\tint width, height;\n\t\t\t\t\tint imghandle = readInt(0, cmddata);\n\t\t\t\t\twidth=readInt(4, cmddata);\n\t\t\t\t\theight=readInt(8, cmddata);\n\t\t\t\t\twhile (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\tint oldestImage = myConn.getOldestImage();\n\t\t\t\t\t\tif (oldestImage != 0)\n\t\t\t\t\t\t{\nSystem.out.println(\"Freeing image to make room in cache\");\n\t\t\t\t\t\t\tunloadImage(oldestImage);\n\t\t\t\t\t\t\tmyConn.postImageUnload(oldestImage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR cannot free enough from the cache to support loading a new image!!!\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlong imagePtr = createNewImage0(width, height);\n\t\t\t\t\timageMap.put(new Integer(imghandle), new Long(imagePtr));\n\t\t\t\t\timageCacheSize += width * height * 4;\n\t\t\t\t\tmyConn.registerImageAccess(imghandle);\n\t\t\t\t\thasret[0]=0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADIMAGETARGETED : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_CREATESURFACE:\n\t\t\t\n\t\t\t\tif(len>=8)\n\t\t\t\t{\n\t\t\t\t\tint width, height;\n\t\t\t\t\tint handle = handleCount++;;\n\t\t\t\t\twidth=readInt(0, cmddata);\n\t\t\t\t\theight=readInt(4, cmddata);\n\t\t\t\t\n\t\t\t\t\tlong layerPtr = createLayer0(c.getSize());\n\t\t\t\t\tlayerMap.put(new Integer(handle), new Long(layerPtr));\n\t\t\t\t\thasret[0]=1;\n\t\t\t\t\treturn handle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_CREATESURFACE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_PREPIMAGE:\n\t\t\t\n\t\t\t\tif(len>=8)\n\t\t\t\t{\n\t\t\t\t\tint width, height;\n\t\t\t\t\n\t\t\t\t\twidth=readInt(0, cmddata);\n\t\t\t\t\theight=readInt(4, cmddata);\n\t\t\t\t\tint imghandle = 1;\n\t\t\t\t\tif (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t\timghandle = 0;\n\t\t\t\t\telse if (len >= 12)\n\t\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\tint strlen = readInt(8, cmddata);\n\t\t\t\t\t\tif (strlen > 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tString rezName = new String(cmddata, 16, strlen - 1);\n\t\t\t\t\t\t\tlastImageResourceID = rezName;\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tlastImageResourceIDHandle = imghandle = Math.abs(lastImageResourceID.hashCode());\n\t\t\t\t\t\t\tjava.io.File cachedFile = myConn.getCachedImageFile(rezName);\n\t\t\t\t\t\t\tif (cachedFile != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tlong imagePtr = createImageFromPath0(cachedFile.getAbsolutePath());\n\t\t\t\t\t\t\t\tif(imagePtr != 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tjava.awt.Dimension imgSize = getImageDimensions0(imagePtr);\n\t\t\t\t\t\t\t\t\tif(imgSize != null)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif(imgSize.getWidth() == width && imgSize.getHeight() == height)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\timghandle = handleCount++;\n\t\t\t\t\t\t\t\t\t\t\timageMap.put(new Integer(imghandle), new Long(imagePtr));\n\t\t\t\t\t\t\t\t\t\t\timageCacheSize += getImageSize0(imagePtr);\n\t\t\t\t\t\t\t\t\t\t\thasret[0] = 1;\n\t\t\t\t\t\t\t\t\t\t\treturn -1 * imghandle;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tfreeNativeImage0(imagePtr);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tfreeNativeImage0(imagePtr);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\thasret[0]=1;\n\t\t\t\t\treturn imghandle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_PREPIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_PREPIMAGETARGETED:\n\t\t\t\n\t\t\t\tif(len>=12)\n\t\t\t\t{\n\t\t\t\t\tint imghandle, width, height;\n\t\t\t\t\timghandle = readInt(0, cmddata);\n\t\t\t\t\twidth=readInt(4, cmddata);\n\t\t\t\t\theight=readInt(8, cmddata);\n\t\t\t\t\tint strlen = readInt(12, cmddata);\n\t\t\t\t\twhile (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\tint oldestImage = myConn.getOldestImage();\n\t\t\t\t\t\tif (oldestImage != 0)\n\t\t\t\t\t\t{\nSystem.out.println(\"Freeing image to make room in cache\");\n\t\t\t\t\t\t\tunloadImage(oldestImage);\n\t\t\t\t\t\t\tmyConn.postImageUnload(oldestImage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR cannot free enough from the cache to support loading a new image!!!\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (len >= 16)\n\t\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\tString rezName = new String(cmddata, 20, strlen - 1);\n\t\t\t\t\t\tlastImageResourceID = rezName;\n\t\t\t\t\t\tlastImageResourceIDHandle = imghandle;\nSystem.out.println(\"Prepped targeted image with handle \" + imghandle + \" resource=\" + rezName);\n\t\t\t\t\t}\n\t\t\t\t\tmyConn.registerImageAccess(imghandle);\n\t\t\t\t\thasret[0]=0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_PREPIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADCACHEDIMAGE:\n\t\t\t\n\t\t\t\tif(len>=18)\n\t\t\t\t{\n\t\t\t\t\tint width, height, imghandle;\n\t\t\t\t\timghandle = readInt(0, cmddata);\n\t\t\t\t\twidth = readInt(4, cmddata);\n\t\t\t\t\theight = readInt(8, cmddata);\n\t\t\t\t\tint strlen = readInt(12, cmddata);\n\t\t\t\t\tString rezName = new String(cmddata, 20, strlen - 1);\nSystem.out.println(\"imghandle=\" + imghandle + \" width=\" + width + \" height=\" + height + \" strlen=\" + strlen + \" rezName=\" + rezName);\n\t\t\t\t\twhile (width * height * 4 + imageCacheSize > imageCacheLimit)\n\t\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\t\tint oldestImage = myConn.getOldestImage();\n\t\t\t\t\t\tif (oldestImage != 0)\n\t\t\t\t\t\t{\nSystem.out.println(\"Freeing image to make room in cache\");\n\t\t\t\t\t\t\tunloadImage(oldestImage);\n\t\t\t\t\t\t\tmyConn.postImageUnload(oldestImage);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR cannot free enough from the cache to support loading a new image!!!\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tmyConn.registerImageAccess(imghandle);\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tSystem.out.println(\"Loading resource from cache: \" + rezName);\n\t\t\t\t\t\tjava.io.File cachedFile = myConn.getCachedImageFile(rezName);\n\t\t\t\t\t\tif (cachedFile != null)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tSystem.out.println(\"Image found in cache!\");\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tlong imagePtr = createImageFromPath0(cachedFile.getAbsolutePath());\n\t\t\t\t\t\t\tif(imagePtr != 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tjava.awt.Dimension imgSize = getImageDimensions0(imagePtr);\n\t\t\t\t\t\t\t\tif(imgSize != null && imgSize.getWidth() == width && imgSize.getHeight() == height)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\timageMap.put(new Integer(imghandle), new Long(imagePtr));\n\t\t\t\t\t\t\t\t\timageCacheSize += getImageSize0(imagePtr);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (imgSize != null)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tSystem.out.println(\"CACHE ID verification failed for rezName=\" + rezName + \" target=\" + width + \"x\" + height + \" actual=\" + imgSize.getWidth() + \"x\" + imgSize.getHeight());\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tSystem.out.println(\"CACHE Load failed for rezName=\" + rezName);\n\t\t\t\t\t\t\t\t\tcachedFile.delete();\n\t\t\t\t\t\t\t\t\tfreeNativeImage0(imagePtr);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tmyConn.postImageUnload(imghandle);\n\t\t\t\t\t\t\t\t\tmyConn.postOfflineCacheChange(false, rezName);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcachedFile.delete();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tmyConn.postImageUnload(imghandle);\n\t\t\t\t\t\t\t\tmyConn.postOfflineCacheChange(false, rezName);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSystem.out.println(\"ERROR Image not found in cache that should be there! rezName=\" + rezName);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tmyConn.postImageUnload(imghandle);\n\t\t\t\t\t\t\tmyConn.postOfflineCacheChange(false, rezName);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (java.io.IOException e)\n\t\t\t\t\t{\n\t\t\t\t\t\tSystem.out.println(\"ERROR loading compressed image: \" + e);\n\t\t\t\t\t}\n\t\t\t\t\thasret[0]=0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_PREPIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_UNLOADIMAGE:\n\t\t\t\n\t\t\t\tif(len==4)\n\t\t\t\t{\n\t\t\t\t\tint handle;\n\t\t\t\t\thandle=readInt(0, cmddata);\n\t\t\t\t\tunloadImage(handle);\n\t\t\t\t\tmyConn.clearImageAccess(handle);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_UNLOADIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_SETTARGETSURFACE:\n\t\t\t\n\t\t\t\tif(len==4)\n\t\t\t\t{\n\t\t\t\t\tint handle;\n\t\t\t\t\thandle=readInt(0, cmddata);\n\t\t\t\t\n\t\t\t\t\tLong layerPtr = (Long)layerMap.get(new Integer(handle));\n\t\t\t\t\tcurrentLayer = (layerPtr != null) ? layerPtr.longValue() : 0;\n\t\t\t\t\tjava.awt.Rectangle clipRect = new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight());\n\t\t\t\t\tsetLayer0(currentLayer, c.getSize(), clipRect);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_SETTARGETSURFACE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADFONT:\n\t\t\t\n\t\t\t\tif(len>=12 && len>=(12+readInt(0, cmddata)))\n\t\t\t\t{\n\t\t\t\t\tint namelen, style, size;\n\t\t\t\t\tStringBuffer name = new StringBuffer();\n\t\t\t\t\tint i;\n\t\t\t\t\tint fonthandle = handleCount++;\n\t\t\t\t\tnamelen=readInt(0, cmddata);\n\t\t\t\t\tfor(i=0;i=8)\n\t\t\t\t{\n\t\t\t\t\tStringBuffer name = new StringBuffer();\n\t\t\t\t\tint namelen = readInt(0, cmddata);\n\t\t\t\t\tfor(int i=0;i= datalen + 8 + namelen)\n\t\t\t\t\t{\n\t\t\t\t\t\tmyConn.saveCacheData(name.toString() + \"-\" + myConn.getServerName(), cmddata, 12 + namelen, datalen);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADFONTSTREAM : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_FLIPBUFFER:\n\t\t\t\tif (abortRenderCycle)\n\t\t\t\t{\nSystem.out.println(\"ERROR in painting cycle, ABORT was set...send full repaint command\");\n\t\t\t\t\tmyConn.postRepaintEvent(0, 0, c.getWidth(), c.getHeight());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpresent0(c.nativeView, new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight()));\n\t\t\t\t}\n\t\t\t\thasret[0] = 1;\n\t\t\t\n\t\t\t\tfirstFrameDone = true;\n\t\t\t\treturn 0;\n\t\t\tcase GFXCMD_STARTFRAME:\n\t\t\t\n\t\t\t\tsetTargetView0(c.nativeView);\n\t\t\t\tsetLayer0(0, c.getSize(), null);\n\t\t\t\tabortRenderCycle = false;\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADIMAGELINE:\n\t\t\t\n\t\t\t\tif(len>=12 && len>=(12+readInt(8, cmddata)))\n\t\t\t\t{\n\t\t\t\t\tint handle, line, len2;\n\t\t\t\t\n\t\t\t\t\thandle=readInt(0, cmddata);\n\t\t\t\t\tline=readInt(4, cmddata);\n\t\t\t\t\tlen2=readInt(8, cmddata);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\tLong imagePtr = (Long)imageMap.get(new Integer(handle));\n\t\t\t\t\tif(imagePtr != null)\n\t\t\t\t\t\tloadImageLine0(imagePtr.longValue(), line, cmddata, 1, len2);\n\t\t\t\t\tmyConn.registerImageAccess(handle);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADIMAGELINE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_LOADIMAGECOMPRESSED:\n\t\t\t\n\t\t\t\tif(len>=8 && len>=(8+readInt(4, cmddata)))\n\t\t\t\t{\n\t\t\t\t\tint handle, len2;\n\t\t\t\t\thandle=readInt(0, cmddata);\n\t\t\t\t\tlen2=readInt(4, cmddata);\n\t\t\t\t\tif (lastImageResourceID != null && lastImageResourceIDHandle == handle)\n\t\t\t\t\t{\n\t\t\t\t\t\tmyConn.saveCacheData(lastImageResourceID, cmddata, 12, len2);\n\t\t\t\t\t\tmyConn.postOfflineCacheChange(true, lastImageResourceID);\n\t\t\t\t\t}\n\t\t\t\t\tif (!myConn.doesUseAdvancedImageCaching())\n\t\t\t\t\t{\n\t\t\t\t\t\thandle = handleCount++;\n\t\t\t\t\t\thasret[0] = 1;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\thasret[0] = 0;\n\t\t\t\t\tmyConn.registerImageAccess(handle);\n\t\t\t\t\tlong imagePtr = createImageFromBytes0(cmddata, 12, len2, null);\n\t\t\t\t\timageMap.put(new Integer(handle), new Long(imagePtr));\n\t\t\t\t\timageCacheSize += getImageSize0(imagePtr);\n\t\t\t\t\treturn handle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_LOADIMAGECOMPRESSED : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_XFMIMAGE:\n\t\t\t\n\t\t\t\tif (len >= 20)\n\t\t\t\t{\n\t\t\t\t\tint srcHandle, destHandle, destWidth, destHeight, maskCornerArc;\n\t\t\t\t\tsrcHandle = readInt(0, cmddata);\n\t\t\t\t\tdestHandle = readInt(4, cmddata);\t\n\t\t\t\t\tdestWidth = readInt(8, cmddata);\t\n\t\t\t\t\tdestHeight = readInt(12, cmddata);\n\t\t\t\t\tmaskCornerArc = readInt(16, cmddata);\n\t\t\t\t\tint rvHandle = destHandle;\n\t\t\t\t\tif (!myConn.doesUseAdvancedImageCaching())\n\t\t\t\t\t{\n\t\t\t\t\t\trvHandle = handleCount++;\n\t\t\t\t\t\thasret[0] = 1;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\thasret[0] = 0;\n\t\t\t\t\n\t\t\t\t\tLong srcImg = (Long)imageMap.get(new Integer(srcHandle));\n\t\t\t\t\tif(srcImg != null) {\n\t\t\t\t\t\tlong newImage = transformImage0(srcImg.longValue(), destWidth, destHeight, maskCornerArc);\n\t\t\t\t\t\tif(newImage != 0) {\n\t\t\t\t\t\t\timageMap.put(new Integer(rvHandle), new Long(newImage));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn rvHandle;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_XFMIMAGE : \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase GFXCMD_SETVIDEOPROP:\n\t\t\t\tif (len >= 40)\n\t\t\t\t{\n\t\t\t\t\tjava.awt.Rectangle srcRect = new java.awt.Rectangle(readInt(4, cmddata), readInt(8, cmddata),\n\t\t\t\t\t\treadInt(12, cmddata), readInt(16, cmddata));\n\t\t\t\t\tjava.awt.Rectangle destRect = new java.awt.Rectangle(readInt(20, cmddata), readInt(24, cmddata),\n\t\t\t\t\t\treadInt(28, cmddata), readInt(32, cmddata));\n\t\t\t\t\tSystem.out.println(\"SETVIDEOPROP: srcRect=\"+srcRect+\" dstRect=\"+destRect);\n\t\t\t\t\tsetVideoBounds(srcRect, destRect);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSystem.out.println(\"Invalid len for GFXCMD_SETVIDEOPROP: \" + len);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn -1;\n\t\t}\n\t\treturn 0;\n\t}"},"cleancode":{"kind":"string","value":"public int executegfxcommand(int cmd, int len, byte[] cmddata, int[] hasret) { len -= 4; hasret[0] = 0; if((cmd != gfxcmd_init) && (cmd != gfxcmd_deinit)) { if((f != null) ? (!f.isdisplayable() || !f.isvalid() || !f.isshowing()) : true) { while((f != null) ? (!f.isdisplayable() || !f.isvalid() || !f.isshowing()) : true) { try { thread.sleep(10); } catch(interruptedexception ex) {} } } } if (c != null) { switch(cmd) { case gfxcmd_init: case gfxcmd_deinit: case gfxcmd_startframe: case gfxcmd_flipbuffer: c.setcursor(null); break; case gfxcmd_drawrect: case gfxcmd_fillrect: case gfxcmd_clearrect: case gfxcmd_drawoval: case gfxcmd_filloval: case gfxcmd_drawroundrect: case gfxcmd_fillroundrect: case gfxcmd_drawtext: case gfxcmd_drawtextured: case gfxcmd_drawline: case gfxcmd_loadimage: case gfxcmd_loadimagetargeted: case gfxcmd_unloadimage: case gfxcmd_loadfont: case gfxcmd_unloadfont: case gfxcmd_settargetsurface: case gfxcmd_createsurface: break; case gfxcmd_prepimage: case gfxcmd_loadimageline: case gfxcmd_loadimagecompressed: case gfxcmd_xfmimage: case gfxcmd_loadcachedimage: case gfxcmd_prepimagetargeted: if (!cursorhidden) c.setcursor(java.awt.cursor.getpredefinedcursor(java.awt.cursor.wait_cursor)); break; } } switch(cmd) { case gfxcmd_init: hasret[0] = 1; init0(); int windowtitlestyle = 0; try { windowtitlestyle = integer.parseint(miniclient.myproperties.getproperty(\"window_title_style\", \"0\")); } catch (numberformatexception e){} if (!\"true\".equals(miniclient.myproperties.getproperty(\"enable_custom_title_bar\", miniclient.mac_os_x ? \"false\" : \"true\"))) windowtitlestyle = 10; f = new miniclientwindow(myconn.getwindowtitle(), windowtitlestyle); java.awt.layoutmanager layer = new java.awt.layoutmanager() { public void addlayoutcomponent(string name, java.awt.component comp) {} public java.awt.dimension minimumlayoutsize(java.awt.container parent) { return preferredlayoutsize(parent); } public java.awt.dimension preferredlayoutsize(java.awt.container parent) { return parent.getpreferredsize(); } public void removelayoutcomponent(java.awt.component comp) {} public void layoutcontainer(java.awt.container parent) { c.setbounds(parent.getinsets().left, parent.getinsets().top, parent.getwidth() - parent.getinsets().left - parent.getinsets().right, parent.getheight() - parent.getinsets().top - parent.getinsets().bottom); } }; f.getcontentpane().setlayout(layer); try { bgimage = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource(\"images/background.jpg\")); ensureimageisloaded(bgimage); logoimage = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource(\"images/sagelogo256.png\")); ensureimageisloaded(logoimage); } catch (exception e) { system.out.println(\"error:\" + e); e.printstacktrace(); } f.setfocustraversalkeysenabled(false); java.awt.dimension panelsize = f.getcontentpane().getsize(); c = new quartzrendererview(); c.setsize(panelsize); c.setfocustraversalkeysenabled(false); f.getcontentpane().add(c); try { java.awt.image frameicon = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource(\"images/tvicon.gif\")); ensureimageisloaded(frameicon); f.seticonimage(frameicon); } catch (exception e) { system.out.println(\"error:\" + e); e.printstacktrace(); } f.addwindowlistener(new java.awt.event.windowadapter() { public void windowclosing(java.awt.event.windowevent evt) { if (!f.isfullscreen() || system.getproperty(\"os.name\").tolowercase().indexof(\"windows\") != -1) { miniclient.myproperties.setproperty(\"main_window_width\", integer.tostring(f.getwidth())); miniclient.myproperties.setproperty(\"main_window_height\", integer.tostring(f.getheight())); miniclient.myproperties.setproperty(\"main_window_x\", integer.tostring(f.getx())); miniclient.myproperties.setproperty(\"main_window_y\", integer.tostring(f.gety())); } myconn.close(); close(); } }); c.addcomponentlistener(new java.awt.event.componentadapter() { public void componentresized(java.awt.event.componentevent evt) { myconn.postresizeevent(new java.awt.dimension(c.getwidth(), c.getheight())); } }); f.addkeylistener(this); c.addkeylistener(this); f.addmousewheellistener(this); c.addmouselistener(this); if (enable_mouse_motion_events) { c.addmousemotionlistener(this); } int framex = 100; int framey = 100; int framew = 720; int frameh = 480; try { framew = integer.parseint(miniclient.myproperties.getproperty(\"main_window_width\", \"720\")); frameh = integer.parseint(miniclient.myproperties.getproperty(\"main_window_height\", \"480\")); framex = integer.parseint(miniclient.myproperties.getproperty(\"main_window_x\", \"100\")); framey = integer.parseint(miniclient.myproperties.getproperty(\"main_window_y\", \"100\")); } catch (numberformatexception e){} java.awt.point newpos = new java.awt.point(framex, framey); boolean foundscreen = sage.uiutils.ispointonascreen(newpos); if (!foundscreen) { newpos.x = 150; newpos.y = 150; } f.setvisible(true); f.setsize(1,1); f.setsize(math.max(framew, 320), math.max(frameh, 240)); f.setlocation(newpos); if (miniclient.fsstartup) f.setfullscreen(true); miniclient.hidesplash(); return 1; case gfxcmd_deinit: close(); break; case gfxcmd_drawrect: if(len==36) { float x, y, width, height; int thickness, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); drawrect0(new java.awt.geom.rectangle2d.float(x, y, width, height), null, 0, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println(\"invalid len for gfxcmd_drawrect : \" + len); } break; case gfxcmd_fillrect: if(len==32) { float x, y, width, height; int argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); if(gp != null) { drawrect0(bounds, null, 0, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawrect0(bounds, null, 0, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println(\"invalid len for gfxcmd_fillrect : \" + len); } break; case gfxcmd_clearrect: if(len==32) { int x, y, width, height, argbtl, argbtr, argbbr, argbbl; x=readint(0, cmddata); y=readint(4, cmddata); width=readint(8, cmddata); height=readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); java.awt.geom.rectangle2d.float destrect = new java.awt.geom.rectangle2d.float(x, y, width, height); clearrect0(destrect); } else { system.out.println(\"invalid len for gfxcmd_clearrect : \" + len); } break; case gfxcmd_drawoval: if(len==52) { float x, y, width, height, clipx, clipy, clipw, cliph; int thickness, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); clipx=(float)readint(36, cmddata); clipy=(float)readint(40, cmddata); clipw=(float)readint(44, cmddata); cliph=(float)readint(48, cmddata); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); drawoval0(bounds, cliprect, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println(\"invalid len for gfxcmd_drawoval : \" + len); } break; case gfxcmd_filloval: if(len==48) { float x, y, width, height, clipx, clipy, clipw, cliph; int argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); clipx=(float)readint(32, cmddata); clipy=(float)readint(36, cmddata); clipw=(float)readint(40, cmddata); cliph=(float)readint(44, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); if(gp != null) { drawoval0(bounds, cliprect, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawoval0(bounds, cliprect, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println(\"invalid len for gfxcmd_filloval : \" + len); } break; case gfxcmd_drawroundrect: if(len==56) { float x, y, width, height, clipx, clipy, clipw, cliph; int thickness, arcradius, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); arcradius=readint(20, cmddata); argbtl=readint(24, cmddata); argbtr=readint(28, cmddata); argbbr=readint(32, cmddata); argbbl=readint(36, cmddata); clipx=(float)readint(40, cmddata); clipy=(float)readint(44, cmddata); clipw=(float)readint(48, cmddata); cliph=(float)readint(52, cmddata); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); drawrect0(bounds, cliprect, arcradius, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println(\"invalid len for gfxcmd_drawroundrect : \" + len); } break; case gfxcmd_fillroundrect: if(len==52) { float x, y, width, height, clipx, clipy, clipw, cliph; int arcradius, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); arcradius=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); clipx=(float)readint(36, cmddata); clipy=(float)readint(40, cmddata); clipw=(float)readint(44, cmddata); cliph=(float)readint(48, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); if(gp != null) { drawrect0(bounds, cliprect, arcradius, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawrect0(bounds, cliprect, arcradius, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println(\"invalid len for gfxcmd_fillroundrect : \" + len); } break; case gfxcmd_drawtext: if(len>=36 && len>=(36+readint(8, cmddata)*2)) { float x, y, clipx, clipy, clipw, cliph; int textlen, fonthandle, argb; stringbuffer text = new stringbuffer(); int i; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); textlen=readint(8, cmddata); for(i=0;i> 24)&0xff))/255.0f : 1.0f); composite0(imageptr.longvalue(), currentlayer, srcrect, destrect, alpha, doblend); } else { system.out.println(\"error invalid handle passed for texture rendering of: \" + handle); abortrendercycle = true; } } } else { system.out.println(\"invalid len for gfxcmd_drawtextured : \" + len); } break; case gfxcmd_drawline: if(len==24) { float x1, y1, x2, y2; int argb1, argb2; x1=readint(0, cmddata); y1=readint(4, cmddata); x2=readint(8, cmddata); y2=readint(12, cmddata); argb1=readint(16, cmddata); argb2=readint(20, cmddata); drawline0(x1, y1, x2, y2, 1, new java.awt.color(argb1, true)); } else { system.out.println(\"invalid len for gfxcmd_drawline : \" + len); } break; case gfxcmd_loadimage: if(len>=8) { int width, height; int imghandle = 0; width=readint(0, cmddata); height=readint(4, cmddata); if (width * height * 4 + imagecachesize > imagecachelimit) { imghandle = 0; } else { long imageptr = createnewimage0(width, height); imghandle = handlecount++; imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += width * height * 4; } hasret[0]=1; return imghandle; } else { system.out.println(\"invalid len for gfxcmd_loadimage : \" + len); } break; case gfxcmd_loadimagetargeted: if(len>=12) { int width, height; int imghandle = readint(0, cmddata); width=readint(4, cmddata); height=readint(8, cmddata); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println(\"freeing image to make room in cache\"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println(\"error cannot free enough from the cache to support loading a new image!!!\"); break; } } long imageptr = createnewimage0(width, height); imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += width * height * 4; myconn.registerimageaccess(imghandle); hasret[0]=0; } else { system.out.println(\"invalid len for gfxcmd_loadimagetargeted : \" + len); } break; case gfxcmd_createsurface: if(len>=8) { int width, height; int handle = handlecount++;; width=readint(0, cmddata); height=readint(4, cmddata); long layerptr = createlayer0(c.getsize()); layermap.put(new integer(handle), new long(layerptr)); hasret[0]=1; return handle; } else { system.out.println(\"invalid len for gfxcmd_createsurface : \" + len); } break; case gfxcmd_prepimage: if(len>=8) { int width, height; width=readint(0, cmddata); height=readint(4, cmddata); int imghandle = 1; if (width * height * 4 + imagecachesize > imagecachelimit) imghandle = 0; else if (len >= 12) { int strlen = readint(8, cmddata); if (strlen > 1) { string rezname = new string(cmddata, 16, strlen - 1); lastimageresourceid = rezname; lastimageresourceidhandle = imghandle = math.abs(lastimageresourceid.hashcode()); java.io.file cachedfile = myconn.getcachedimagefile(rezname); if (cachedfile != null) { long imageptr = createimagefrompath0(cachedfile.getabsolutepath()); if(imageptr != 0) { java.awt.dimension imgsize = getimagedimensions0(imageptr); if(imgsize != null) { if(imgsize.getwidth() == width && imgsize.getheight() == height) { imghandle = handlecount++; imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); hasret[0] = 1; return -1 * imghandle; } else freenativeimage0(imageptr); } else freenativeimage0(imageptr); } } } } hasret[0]=1; return imghandle; } else { system.out.println(\"invalid len for gfxcmd_prepimage : \" + len); } break; case gfxcmd_prepimagetargeted: if(len>=12) { int imghandle, width, height; imghandle = readint(0, cmddata); width=readint(4, cmddata); height=readint(8, cmddata); int strlen = readint(12, cmddata); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println(\"freeing image to make room in cache\"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println(\"error cannot free enough from the cache to support loading a new image!!!\"); break; } } if (len >= 16) { string rezname = new string(cmddata, 20, strlen - 1); lastimageresourceid = rezname; lastimageresourceidhandle = imghandle; system.out.println(\"prepped targeted image with handle \" + imghandle + \" resource=\" + rezname); } myconn.registerimageaccess(imghandle); hasret[0]=0; } else { system.out.println(\"invalid len for gfxcmd_prepimage : \" + len); } break; case gfxcmd_loadcachedimage: if(len>=18) { int width, height, imghandle; imghandle = readint(0, cmddata); width = readint(4, cmddata); height = readint(8, cmddata); int strlen = readint(12, cmddata); string rezname = new string(cmddata, 20, strlen - 1); system.out.println(\"imghandle=\" + imghandle + \" width=\" + width + \" height=\" + height + \" strlen=\" + strlen + \" rezname=\" + rezname); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println(\"freeing image to make room in cache\"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println(\"error cannot free enough from the cache to support loading a new image!!!\"); break; } } myconn.registerimageaccess(imghandle); try { system.out.println(\"loading resource from cache: \" + rezname); java.io.file cachedfile = myconn.getcachedimagefile(rezname); if (cachedfile != null) { system.out.println(\"image found in cache!\"); long imageptr = createimagefrompath0(cachedfile.getabsolutepath()); if(imageptr != 0) { java.awt.dimension imgsize = getimagedimensions0(imageptr); if(imgsize != null && imgsize.getwidth() == width && imgsize.getheight() == height) { imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); } else { if (imgsize != null) { system.out.println(\"cache id verification failed for rezname=\" + rezname + \" target=\" + width + \"x\" + height + \" actual=\" + imgsize.getwidth() + \"x\" + imgsize.getheight()); } else system.out.println(\"cache load failed for rezname=\" + rezname); cachedfile.delete(); freenativeimage0(imageptr); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } else { cachedfile.delete(); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } else { system.out.println(\"error image not found in cache that should be there! rezname=\" + rezname); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } catch (java.io.ioexception e) { system.out.println(\"error loading compressed image: \" + e); } hasret[0]=0; } else { system.out.println(\"invalid len for gfxcmd_prepimage : \" + len); } break; case gfxcmd_unloadimage: if(len==4) { int handle; handle=readint(0, cmddata); unloadimage(handle); myconn.clearimageaccess(handle); } else { system.out.println(\"invalid len for gfxcmd_unloadimage : \" + len); } break; case gfxcmd_settargetsurface: if(len==4) { int handle; handle=readint(0, cmddata); long layerptr = (long)layermap.get(new integer(handle)); currentlayer = (layerptr != null) ? layerptr.longvalue() : 0; java.awt.rectangle cliprect = new java.awt.rectangle(0, 0, c.getwidth(), c.getheight()); setlayer0(currentlayer, c.getsize(), cliprect); } else { system.out.println(\"invalid len for gfxcmd_settargetsurface : \" + len); } break; case gfxcmd_loadfont: if(len>=12 && len>=(12+readint(0, cmddata))) { int namelen, style, size; stringbuffer name = new stringbuffer(); int i; int fonthandle = handlecount++; namelen=readint(0, cmddata); for(i=0;i=8) { stringbuffer name = new stringbuffer(); int namelen = readint(0, cmddata); for(int i=0;i= datalen + 8 + namelen) { myconn.savecachedata(name.tostring() + \"-\" + myconn.getservername(), cmddata, 12 + namelen, datalen); } } else { system.out.println(\"invalid len for gfxcmd_loadfontstream : \" + len); } break; case gfxcmd_flipbuffer: if (abortrendercycle) { system.out.println(\"error in painting cycle, abort was set...send full repaint command\"); myconn.postrepaintevent(0, 0, c.getwidth(), c.getheight()); } else { present0(c.nativeview, new java.awt.rectangle(0, 0, c.getwidth(), c.getheight())); } hasret[0] = 1; firstframedone = true; return 0; case gfxcmd_startframe: settargetview0(c.nativeview); setlayer0(0, c.getsize(), null); abortrendercycle = false; break; case gfxcmd_loadimageline: if(len>=12 && len>=(12+readint(8, cmddata))) { int handle, line, len2; handle=readint(0, cmddata); line=readint(4, cmddata); len2=readint(8, cmddata); long imageptr = (long)imagemap.get(new integer(handle)); if(imageptr != null) loadimageline0(imageptr.longvalue(), line, cmddata, 1, len2); myconn.registerimageaccess(handle); } else { system.out.println(\"invalid len for gfxcmd_loadimageline : \" + len); } break; case gfxcmd_loadimagecompressed: if(len>=8 && len>=(8+readint(4, cmddata))) { int handle, len2; handle=readint(0, cmddata); len2=readint(4, cmddata); if (lastimageresourceid != null && lastimageresourceidhandle == handle) { myconn.savecachedata(lastimageresourceid, cmddata, 12, len2); myconn.postofflinecachechange(true, lastimageresourceid); } if (!myconn.doesuseadvancedimagecaching()) { handle = handlecount++; hasret[0] = 1; } else hasret[0] = 0; myconn.registerimageaccess(handle); long imageptr = createimagefrombytes0(cmddata, 12, len2, null); imagemap.put(new integer(handle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); return handle; } else { system.out.println(\"invalid len for gfxcmd_loadimagecompressed : \" + len); } break; case gfxcmd_xfmimage: if (len >= 20) { int srchandle, desthandle, destwidth, destheight, maskcornerarc; srchandle = readint(0, cmddata); desthandle = readint(4, cmddata); destwidth = readint(8, cmddata); destheight = readint(12, cmddata); maskcornerarc = readint(16, cmddata); int rvhandle = desthandle; if (!myconn.doesuseadvancedimagecaching()) { rvhandle = handlecount++; hasret[0] = 1; } else hasret[0] = 0; long srcimg = (long)imagemap.get(new integer(srchandle)); if(srcimg != null) { long newimage = transformimage0(srcimg.longvalue(), destwidth, destheight, maskcornerarc); if(newimage != 0) { imagemap.put(new integer(rvhandle), new long(newimage)); } } return rvhandle; } else { system.out.println(\"invalid len for gfxcmd_xfmimage : \" + len); } break; case gfxcmd_setvideoprop: if (len >= 40) { java.awt.rectangle srcrect = new java.awt.rectangle(readint(4, cmddata), readint(8, cmddata), readint(12, cmddata), readint(16, cmddata)); java.awt.rectangle destrect = new java.awt.rectangle(readint(20, cmddata), readint(24, cmddata), readint(28, cmddata), readint(32, cmddata)); system.out.println(\"setvideoprop: srcrect=\"+srcrect+\" dstrect=\"+destrect); setvideobounds(srcrect, destrect); } else { system.out.println(\"invalid len for gfxcmd_setvideoprop: \" + len); } break; default: return -1; } return 0; }"},"repo":{"kind":"string","value":"Narflex/sagetv"},"label":{"kind":"list like","value":[1,0,1,0],"string":"[\n 1,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":223,"cells":{"id":{"kind":"number","value":7810,"string":"7,810"},"original_code":{"kind":"string","value":"public boolean isOvertaking() {\n\t\tif (overtakeStage != OvertakeStage.NOT_OVERTAKING) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}"},"code_wo_comment":{"kind":"string","value":"public boolean isOvertaking() {\n\t\tif (overtakeStage != OvertakeStage.NOT_OVERTAKING) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}"},"cleancode":{"kind":"string","value":"public boolean isovertaking() { if (overtakestage != overtakestage.not_overtaking) { return true; } else { return false; } }"},"repo":{"kind":"string","value":"RobAlexander/SCovSGen"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":224,"cells":{"id":{"kind":"number","value":16039,"string":"16,039"},"original_code":{"kind":"string","value":"public static List generateParenthesis1(int n) {\n Set[] dp = new Set[n + 1];\n Set first = new HashSet<>();\n first.add(\"\");\n dp[0] = first;\n for (int i = 1; i <= n; i++) {\n Set set = new HashSet<>();\n for (String pre : dp[i - 1]) {\n set.add(\"(\" + pre + \")\");\n }\n for (int m = 1; m < i; m++) {\n for (String p1 : dp[m]) {\n for (String p2 : dp[i - m]) {\n set.add(p1 + p2);\n set.add(p2 + p1);\n }\n }\n }\n dp[i] = set;\n }\n return new ArrayList<>(dp[n]);\n }"},"code_wo_comment":{"kind":"string","value":"public static List generateParenthesis1(int n) {\n Set[] dp = new Set[n + 1];\n Set first = new HashSet<>();\n first.add(\"\");\n dp[0] = first;\n for (int i = 1; i <= n; i++) {\n Set set = new HashSet<>();\n for (String pre : dp[i - 1]) {\n set.add(\"(\" + pre + \")\");\n }\n for (int m = 1; m < i; m++) {\n for (String p1 : dp[m]) {\n for (String p2 : dp[i - m]) {\n set.add(p1 + p2);\n set.add(p2 + p1);\n }\n }\n }\n dp[i] = set;\n }\n return new ArrayList<>(dp[n]);\n }"},"cleancode":{"kind":"string","value":"public static list generateparenthesis1(int n) { set[] dp = new set[n + 1]; set first = new hashset<>(); first.add(\"\"); dp[0] = first; for (int i = 1; i <= n; i++) { set set = new hashset<>(); for (string pre : dp[i - 1]) { set.add(\"(\" + pre + \")\"); } for (int m = 1; m < i; m++) { for (string p1 : dp[m]) { for (string p2 : dp[i - m]) { set.add(p1 + p2); set.add(p2 + p1); } } } dp[i] = set; } return new arraylist<>(dp[n]); }"},"repo":{"kind":"string","value":"Joybeanx/leetcode"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":225,"cells":{"id":{"kind":"number","value":24717,"string":"24,717"},"original_code":{"kind":"string","value":"public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows Exception {\n\t\tStudy study = ControllerUtil.findStudy(request, mStudyService);\n\t\tSubmission submission = (Submission) study.getSubmission();\n\t\tStudyCommand studyCommand = new StudyCommand();\n\t\t// copy study information\n\t\tstudyCommand.setStudy(study);\n\t\t// study from TBI do not contain submission_id\n\t\tif (submission != null) {\n\t\t\tstudyCommand.setSubmission_id(submission.getId());\n\t\t}\n\t\tList analysisList = study.getAnalyses();\n\t\tList analysisCommandList = new ArrayList();\n\t\tList changedAnalyses = new ArrayList();\n\t\tStringBuilder errBuilder = new StringBuilder();\n\t\tfor (Analysis analysis : analysisList) {\n\t\t\t// FIXME: next if block needs to me moved to the onSumbit method when\n\t\t\t// we this controller will extend BaseFormController.\n\t\t\tif (!analysis.getValidated()) {\n\t\t\t\tExecutionResult result = analysis.validate();\n\t\t\t\tif (!result.isSuccessful()) {\n\t\t\t\t\terrBuilder.append(result.getErrorMessage());\n\t\t\t\t}\n\t\t\t\tif (analysis.getValidated()) {\n\t\t\t\t\t// save to db if the validated flag is updated:\n\t\t\t\t\tchangedAnalyses.add(analysis);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//FIXME: display err message in GUI\n\t\t\tif (LOGGER.isDebugEnabled()) {\n\t\t\t\tLOGGER.debug(errBuilder.toString()); //$NON-NLS-1$\n\t\t\t}\n\t\t\t//\n\t\t\t// Analysis\n\t\t\tAnalysisCommand analysisCommand = new AnalysisCommand();\n\t\t\tBeanUtils.copyProperties(analysisCommand, analysis);\n\t\t\t// Analysis Steps for Analysis and add algorithm type\n\t\t\tList analysisStepList = analysis.getAnalysisStepsReadOnly();\n\t\t\tList analysisStepCommandList = new ArrayList();\n\t\t\tfor (AnalysisStep analysisStep : analysisStepList) {\n\t\t\t\tAnalysisStepCommand analysisStepCommand = new AnalysisStepCommand();\n\t\t\t\tBeanUtils.copyProperties(analysisStepCommand, analysisStep);\n\t\t\t\t// analysisStepCommand.setId(analysisStep.getId());\n\t\t\t\t// analysisStepCommand.setSoftwareInfo(analysisStep.getSoftwareInfo());\n\t\t\t\tAlgorithm algorithm = analysisStep.getAlgorithmInfo();\n\t\t\t\tString algorithmType = new String();\n\t\t\t\tif (algorithm instanceof LikelihoodAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_LIKELIHOOD;\n\t\t\t\t} else if (algorithm instanceof ParsimonyAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_PARSIMONY;\n\t\t\t\t} else if (algorithm instanceof OtherAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_OTHER;\n\t\t\t\t}else if (algorithm instanceof BayesianAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_Bayesian;\n\t\t\t\t} else if (algorithm instanceof EvolutionAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_Evolution;\n\t\t\t\t} else if (algorithm instanceof JoiningAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_Joining;\n\t\t\t} else if (algorithm instanceof UPGMAAlgorithm) {\n\t\t\t\talgorithmType = Constants.ALGORITHM_UPGMA;\t\n\t\t\t}\n\t\t\t\t// add algorithm type for analysisStepCommand\n\t\t\t\tanalysisStepCommand.setAlgorithmType(algorithmType);\n\t\t\t\t// analyzed data for each analysis step\n\t\t\t\tList analyzedDataSet = analysisStep.getDataSetReadOnly();\n\t\t\t\tList analyzedDataCommandList = new ArrayList();\n\t\t\t\t// Matrix or Tree?\n\t\t\t\tfor (AnalyzedData analyzedData : analyzedDataSet) {\n\t\t\t\t\tAnalyzedDataCommand analyzedDataCommand = new AnalyzedDataCommand();\n\t\t\t\t\tBeanUtils.copyProperties(analyzedDataCommand, analyzedData);\n\t\t\t\t\tString inputOutput = (analyzedData.isInputData()) ? (\"Input\") : (\"Output\");\n\t\t\t\t\tanalyzedDataCommand.setInputOutputType(inputOutput);\n\t\t\t\t\tif (analyzedData instanceof AnalyzedMatrix) {\n\t\t\t\t\t\tAnalyzedMatrix analyzedMatrix = (AnalyzedMatrix) analyzedData;\n\t\t\t\t\t\tanalyzedDataCommand.setDataType(Constants.MATRIX_KEY);\n\t\t\t\t\t\tanalyzedDataCommand.setDisplayName(analyzedMatrix.getMatrix().getTitle());\n\t\t\t\t\t\tanalyzedDataCommand.setId(analyzedMatrix.getId());\n\t\t\t\t\t\tanalyzedDataCommand.setDataId(analyzedMatrix.getMatrix().getId());\n\t\t\t\t\t} else if (analyzedData instanceof AnalyzedTree) {\n\t\t\t\t\t\tAnalyzedTree analyzedTree = (AnalyzedTree) analyzedData;\n\t\t\t\t\t\tanalyzedDataCommand.setDataType(Constants.TREE_KEY);\n\t\t\t\t\t\tanalyzedDataCommand.setDisplayName(analyzedTree.getTree().getLabel());\n\t\t\t\t\t\tanalyzedDataCommand.setId(analyzedTree.getId());\n\t\t\t\t\t\tanalyzedDataCommand.setDataId(analyzedTree.getTree().getId());\n\t\t\t\t\t}\n\t\t\t\t\tanalyzedDataCommandList.add(analyzedDataCommand);\n\t\t\t\t} // end for\n\t\t\t\t// add analyzedData for analysisStepCommand\n\t\t\t\tCollections.sort(analyzedDataCommandList, new AnalyzedDataComparator());\n\t\t\t\tanalysisStepCommand.setAnalyzedDataCommandList(analyzedDataCommandList);\n\t\t\t\tanalysisStepCommandList.add(analysisStepCommand);\n\t\t\t}\n\t\t\tanalysisCommand.setAnalysisStepCommandList(analysisStepCommandList);\n\t\t\tanalysisCommandList.add(analysisCommand);\n\t\t}\n\t\tgetStudyService().updateCollection(changedAnalyses);\n\t\tstudyCommand.setAnalysisCommandList(analysisCommandList);\n\t\treturn new ModelAndView(\"analysisSection\", Constants.STUDY_COMMAND_KEY, studyCommand);\n\t}"},"code_wo_comment":{"kind":"string","value":"public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)\n\t\tthrows Exception {\n\t\tStudy study = ControllerUtil.findStudy(request, mStudyService);\n\t\tSubmission submission = (Submission) study.getSubmission();\n\t\tStudyCommand studyCommand = new StudyCommand();\n\t\n\t\tstudyCommand.setStudy(study);\n\t\n\t\tif (submission != null) {\n\t\t\tstudyCommand.setSubmission_id(submission.getId());\n\t\t}\n\t\tList analysisList = study.getAnalyses();\n\t\tList analysisCommandList = new ArrayList();\n\t\tList changedAnalyses = new ArrayList();\n\t\tStringBuilder errBuilder = new StringBuilder();\n\t\tfor (Analysis analysis : analysisList) {\n\t\t\n\t\t\n\t\t\tif (!analysis.getValidated()) {\n\t\t\t\tExecutionResult result = analysis.validate();\n\t\t\t\tif (!result.isSuccessful()) {\n\t\t\t\t\terrBuilder.append(result.getErrorMessage());\n\t\t\t\t}\n\t\t\t\tif (analysis.getValidated()) {\n\t\t\t\t\n\t\t\t\t\tchangedAnalyses.add(analysis);\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t\tif (LOGGER.isDebugEnabled()) {\n\t\t\t\tLOGGER.debug(errBuilder.toString());\n\t\t\t}\n\t\t\n\t\t\n\t\t\tAnalysisCommand analysisCommand = new AnalysisCommand();\n\t\t\tBeanUtils.copyProperties(analysisCommand, analysis);\n\t\t\n\t\t\tList analysisStepList = analysis.getAnalysisStepsReadOnly();\n\t\t\tList analysisStepCommandList = new ArrayList();\n\t\t\tfor (AnalysisStep analysisStep : analysisStepList) {\n\t\t\t\tAnalysisStepCommand analysisStepCommand = new AnalysisStepCommand();\n\t\t\t\tBeanUtils.copyProperties(analysisStepCommand, analysisStep);\n\t\t\t\n\t\t\t\n\t\t\t\tAlgorithm algorithm = analysisStep.getAlgorithmInfo();\n\t\t\t\tString algorithmType = new String();\n\t\t\t\tif (algorithm instanceof LikelihoodAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_LIKELIHOOD;\n\t\t\t\t} else if (algorithm instanceof ParsimonyAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_PARSIMONY;\n\t\t\t\t} else if (algorithm instanceof OtherAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_OTHER;\n\t\t\t\t}else if (algorithm instanceof BayesianAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_Bayesian;\n\t\t\t\t} else if (algorithm instanceof EvolutionAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_Evolution;\n\t\t\t\t} else if (algorithm instanceof JoiningAlgorithm) {\n\t\t\t\t\talgorithmType = Constants.ALGORITHM_Joining;\n\t\t\t} else if (algorithm instanceof UPGMAAlgorithm) {\n\t\t\t\talgorithmType = Constants.ALGORITHM_UPGMA;\t\n\t\t\t}\n\t\t\t\n\t\t\t\tanalysisStepCommand.setAlgorithmType(algorithmType);\n\t\t\t\n\t\t\t\tList analyzedDataSet = analysisStep.getDataSetReadOnly();\n\t\t\t\tList analyzedDataCommandList = new ArrayList();\n\t\t\t\n\t\t\t\tfor (AnalyzedData analyzedData : analyzedDataSet) {\n\t\t\t\t\tAnalyzedDataCommand analyzedDataCommand = new AnalyzedDataCommand();\n\t\t\t\t\tBeanUtils.copyProperties(analyzedDataCommand, analyzedData);\n\t\t\t\t\tString inputOutput = (analyzedData.isInputData()) ? (\"Input\") : (\"Output\");\n\t\t\t\t\tanalyzedDataCommand.setInputOutputType(inputOutput);\n\t\t\t\t\tif (analyzedData instanceof AnalyzedMatrix) {\n\t\t\t\t\t\tAnalyzedMatrix analyzedMatrix = (AnalyzedMatrix) analyzedData;\n\t\t\t\t\t\tanalyzedDataCommand.setDataType(Constants.MATRIX_KEY);\n\t\t\t\t\t\tanalyzedDataCommand.setDisplayName(analyzedMatrix.getMatrix().getTitle());\n\t\t\t\t\t\tanalyzedDataCommand.setId(analyzedMatrix.getId());\n\t\t\t\t\t\tanalyzedDataCommand.setDataId(analyzedMatrix.getMatrix().getId());\n\t\t\t\t\t} else if (analyzedData instanceof AnalyzedTree) {\n\t\t\t\t\t\tAnalyzedTree analyzedTree = (AnalyzedTree) analyzedData;\n\t\t\t\t\t\tanalyzedDataCommand.setDataType(Constants.TREE_KEY);\n\t\t\t\t\t\tanalyzedDataCommand.setDisplayName(analyzedTree.getTree().getLabel());\n\t\t\t\t\t\tanalyzedDataCommand.setId(analyzedTree.getId());\n\t\t\t\t\t\tanalyzedDataCommand.setDataId(analyzedTree.getTree().getId());\n\t\t\t\t\t}\n\t\t\t\t\tanalyzedDataCommandList.add(analyzedDataCommand);\n\t\t\t\t}\n\t\t\t\n\t\t\t\tCollections.sort(analyzedDataCommandList, new AnalyzedDataComparator());\n\t\t\t\tanalysisStepCommand.setAnalyzedDataCommandList(analyzedDataCommandList);\n\t\t\t\tanalysisStepCommandList.add(analysisStepCommand);\n\t\t\t}\n\t\t\tanalysisCommand.setAnalysisStepCommandList(analysisStepCommandList);\n\t\t\tanalysisCommandList.add(analysisCommand);\n\t\t}\n\t\tgetStudyService().updateCollection(changedAnalyses);\n\t\tstudyCommand.setAnalysisCommandList(analysisCommandList);\n\t\treturn new ModelAndView(\"analysisSection\", Constants.STUDY_COMMAND_KEY, studyCommand);\n\t}"},"cleancode":{"kind":"string","value":"public modelandview handlerequest(httpservletrequest request, httpservletresponse response) throws exception { study study = controllerutil.findstudy(request, mstudyservice); submission submission = (submission) study.getsubmission(); studycommand studycommand = new studycommand(); studycommand.setstudy(study); if (submission != null) { studycommand.setsubmission_id(submission.getid()); } list analysislist = study.getanalyses(); list analysiscommandlist = new arraylist(); list changedanalyses = new arraylist(); stringbuilder errbuilder = new stringbuilder(); for (analysis analysis : analysislist) { if (!analysis.getvalidated()) { executionresult result = analysis.validate(); if (!result.issuccessful()) { errbuilder.append(result.geterrormessage()); } if (analysis.getvalidated()) { changedanalyses.add(analysis); } } if (logger.isdebugenabled()) { logger.debug(errbuilder.tostring()); } analysiscommand analysiscommand = new analysiscommand(); beanutils.copyproperties(analysiscommand, analysis); list analysissteplist = analysis.getanalysisstepsreadonly(); list analysisstepcommandlist = new arraylist(); for (analysisstep analysisstep : analysissteplist) { analysisstepcommand analysisstepcommand = new analysisstepcommand(); beanutils.copyproperties(analysisstepcommand, analysisstep); algorithm algorithm = analysisstep.getalgorithminfo(); string algorithmtype = new string(); if (algorithm instanceof likelihoodalgorithm) { algorithmtype = constants.algorithm_likelihood; } else if (algorithm instanceof parsimonyalgorithm) { algorithmtype = constants.algorithm_parsimony; } else if (algorithm instanceof otheralgorithm) { algorithmtype = constants.algorithm_other; }else if (algorithm instanceof bayesianalgorithm) { algorithmtype = constants.algorithm_bayesian; } else if (algorithm instanceof evolutionalgorithm) { algorithmtype = constants.algorithm_evolution; } else if (algorithm instanceof joiningalgorithm) { algorithmtype = constants.algorithm_joining; } else if (algorithm instanceof upgmaalgorithm) { algorithmtype = constants.algorithm_upgma; } analysisstepcommand.setalgorithmtype(algorithmtype); list analyzeddataset = analysisstep.getdatasetreadonly(); list analyzeddatacommandlist = new arraylist(); for (analyzeddata analyzeddata : analyzeddataset) { analyzeddatacommand analyzeddatacommand = new analyzeddatacommand(); beanutils.copyproperties(analyzeddatacommand, analyzeddata); string inputoutput = (analyzeddata.isinputdata()) ? (\"input\") : (\"output\"); analyzeddatacommand.setinputoutputtype(inputoutput); if (analyzeddata instanceof analyzedmatrix) { analyzedmatrix analyzedmatrix = (analyzedmatrix) analyzeddata; analyzeddatacommand.setdatatype(constants.matrix_key); analyzeddatacommand.setdisplayname(analyzedmatrix.getmatrix().gettitle()); analyzeddatacommand.setid(analyzedmatrix.getid()); analyzeddatacommand.setdataid(analyzedmatrix.getmatrix().getid()); } else if (analyzeddata instanceof analyzedtree) { analyzedtree analyzedtree = (analyzedtree) analyzeddata; analyzeddatacommand.setdatatype(constants.tree_key); analyzeddatacommand.setdisplayname(analyzedtree.gettree().getlabel()); analyzeddatacommand.setid(analyzedtree.getid()); analyzeddatacommand.setdataid(analyzedtree.gettree().getid()); } analyzeddatacommandlist.add(analyzeddatacommand); } collections.sort(analyzeddatacommandlist, new analyzeddatacomparator()); analysisstepcommand.setanalyzeddatacommandlist(analyzeddatacommandlist); analysisstepcommandlist.add(analysisstepcommand); } analysiscommand.setanalysisstepcommandlist(analysisstepcommandlist); analysiscommandlist.add(analysiscommand); } getstudyservice().updatecollection(changedanalyses); studycommand.setanalysiscommandlist(analysiscommandlist); return new modelandview(\"analysissection\", constants.study_command_key, studycommand); }"},"repo":{"kind":"string","value":"TreeBASE/treebasetest"},"label":{"kind":"list like","value":[0,1,1,0],"string":"[\n 0,\n 1,\n 1,\n 0\n]"}}},{"rowIdx":226,"cells":{"id":{"kind":"number","value":148,"string":"148"},"original_code":{"kind":"string","value":"private void addVar(Varlet v){\n\t\t\tlong key=key(v.chromosome, v.beginLoc);\n\t\t\tArrayList list=keymap.get(key);\n\t\t\tassert(list!=null) : \"\\nCan't find \"+key+\" in \"+keymap.keySet()+\"\\n\";\n\t\t\tsynchronized(list){\n\t\t\t\tlist.add(v);\n\t\t\t\tif(list.size()>=WRITE_BUFFER){\n\t\t\t\t\tif(MERGE_EQUAL_VARLETS){\n\t\t\t\t\t\tmergeEqualVarlets(list);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tCollections.sort(list);\n\t\t\t\t\t}\n\t\t\t\t\twriteList(list);\n\t\t\t\t\tlist.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t}"},"code_wo_comment":{"kind":"string","value":"private void addVar(Varlet v){\n\t\t\tlong key=key(v.chromosome, v.beginLoc);\n\t\t\tArrayList list=keymap.get(key);\n\t\t\tassert(list!=null) : \"\\nCan't find \"+key+\" in \"+keymap.keySet()+\"\\n\";\n\t\t\tsynchronized(list){\n\t\t\t\tlist.add(v);\n\t\t\t\tif(list.size()>=WRITE_BUFFER){\n\t\t\t\t\tif(MERGE_EQUAL_VARLETS){\n\t\t\t\t\t\tmergeEqualVarlets(list);\n\t\t\t\t\t}else{\n\t\t\t\t\t\tCollections.sort(list);\n\t\t\t\t\t}\n\t\t\t\t\twriteList(list);\n\t\t\t\t\tlist.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t}"},"cleancode":{"kind":"string","value":"private void addvar(varlet v){ long key=key(v.chromosome, v.beginloc); arraylist list=keymap.get(key); assert(list!=null) : \"\\ncan't find \"+key+\" in \"+keymap.keyset()+\"\\n\"; synchronized(list){ list.add(v); if(list.size()>=write_buffer){ if(merge_equal_varlets){ mergeequalvarlets(list); }else{ collections.sort(list); } writelist(list); list.clear(); } } }"},"repo":{"kind":"string","value":"SilasK/BBMap"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":227,"cells":{"id":{"kind":"number","value":16664,"string":"16,664"},"original_code":{"kind":"string","value":"private NiceWebDriver getNiceWebDriverInstance(DriverType driverType, Object[] oArgs){\n\t\tswitch(driverType) {\n\t\t\tcase Chrome:\n\t\t\t\treturn new NiceChrome().UnderloadedNiceWebDriverConstructor(oArgs).getThisWithVerbositySetTo(outputIsVerbose);\n\t\t\tcase Firefox:\n\t\t\t\treturn null; //TODO: Make Firefox subclass\n\t\t\tcase IE:\n\t\t\t\treturn null; //TODO: Make IE subclass\n\t\t\tcase Edge:\n\t\t\t\treturn null; //TODO: Make Edge subclass\n\t\t\tcase Opera:\n\t\t\t\treturn null; //TODO: Make Opera subclass\n\t\t\tcase Safari:\n\t\t\t\treturn null; //TODO: Make Safari subclass\n\t\t\tcase iOS_iPhone:\n\t\t\t\treturn null; //TODO: Make iOS_iPhone subclass\n\t\t\tcase iOS_iPad:\n\t\t\t\treturn null; //TODO: Make iOS_iPad subclass\n\t\t\tcase Android:\n\t\t\t\treturn null; //TODO: Make Android subclass\n\t\t\tcase HtmlUnit:\n\t\t\t\treturn null; //TODO: Make HtmlUnit subclass\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}"},"code_wo_comment":{"kind":"string","value":"private NiceWebDriver getNiceWebDriverInstance(DriverType driverType, Object[] oArgs){\n\t\tswitch(driverType) {\n\t\t\tcase Chrome:\n\t\t\t\treturn new NiceChrome().UnderloadedNiceWebDriverConstructor(oArgs).getThisWithVerbositySetTo(outputIsVerbose);\n\t\t\tcase Firefox:\n\t\t\t\treturn null;\n\t\t\tcase IE:\n\t\t\t\treturn null;\n\t\t\tcase Edge:\n\t\t\t\treturn null;\n\t\t\tcase Opera:\n\t\t\t\treturn null;\n\t\t\tcase Safari:\n\t\t\t\treturn null;\n\t\t\tcase iOS_iPhone:\n\t\t\t\treturn null;\n\t\t\tcase iOS_iPad:\n\t\t\t\treturn null;\n\t\t\tcase Android:\n\t\t\t\treturn null;\n\t\t\tcase HtmlUnit:\n\t\t\t\treturn null;\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}"},"cleancode":{"kind":"string","value":"private nicewebdriver getnicewebdriverinstance(drivertype drivertype, object[] oargs){ switch(drivertype) { case chrome: return new nicechrome().underloadednicewebdriverconstructor(oargs).getthiswithverbositysetto(outputisverbose); case firefox: return null; case ie: return null; case edge: return null; case opera: return null; case safari: return null; case ios_iphone: return null; case ios_ipad: return null; case android: return null; case htmlunit: return null; default: return null; } }"},"repo":{"kind":"string","value":"Skenvy/SeleniumNG"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":228,"cells":{"id":{"kind":"number","value":33149,"string":"33,149"},"original_code":{"kind":"string","value":"private void tag()\n throws Exception\n {\n String[] asFilename = (String[])m_oCmdLineMap.get(\"filenames\");\n for (int i=0; i < asFilename.length; i++)\n {\n File oSourceFile = new File(asFilename[i]);\n MP3File oMP3File = new MP3File(oSourceFile);\n if (m_oCmdLineMap.containsKey(\"1\"))\n {\n ID3V1_1Tag oID3V1_1Tag = new ID3V1_1Tag();\n if (m_oCmdLineMap.containsKey(\"album\"))\n {\n oID3V1_1Tag.setAlbum((String)m_oCmdLineMap.get(\"album\"));\n }\n if (m_oCmdLineMap.containsKey(\"artist\"))\n {\n oID3V1_1Tag.setArtist((String)m_oCmdLineMap.get(\"artist\"));\n }\n if (m_oCmdLineMap.containsKey(\"comment\"))\n {\n oID3V1_1Tag.setComment((String)m_oCmdLineMap.get(\"comment\"));\n }\n if (m_oCmdLineMap.containsKey(\"genre\"))\n {\n String sGenre = (String)m_oCmdLineMap.get(\"genre\");\n oID3V1_1Tag.setGenre(ID3V1Tag.Genre.lookupGenre(sGenre));\n }\n if (m_oCmdLineMap.containsKey(\"title\"))\n {\n oID3V1_1Tag.setTitle((String)m_oCmdLineMap.get(\"title\"));\n }\n if (m_oCmdLineMap.containsKey(\"year\"))\n {\n oID3V1_1Tag.setYear(((Integer)m_oCmdLineMap.get(\"year\")).toString());\n }\n if (m_oCmdLineMap.containsKey(\"track\"))\n {\n oID3V1_1Tag.setAlbumTrack(((Integer)m_oCmdLineMap.get(\"track\")).intValue());\n }\n oMP3File.setID3Tag(oID3V1_1Tag);\n }\n if (m_oCmdLineMap.containsKey(\"2\"))\n {\n ID3V2_3_0Tag oID3V2_3_0Tag = new ID3V2_3_0Tag();\n //HACK: Need to have padding at the end of the tag, or Winamp won't see the last frame (at least 6 bytes seem to be required).\n oID3V2_3_0Tag.setPaddingLength(16);\n if (m_oCmdLineMap.containsKey(\"album\"))\n {\n oID3V2_3_0Tag.setAlbum((String)m_oCmdLineMap.get(\"album\"));\n }\n if (m_oCmdLineMap.containsKey(\"artist\"))\n {\n oID3V2_3_0Tag.setArtist((String)m_oCmdLineMap.get(\"artist\"));\n }\n if (m_oCmdLineMap.containsKey(\"comment\"))\n {\n oID3V2_3_0Tag.setComment((String)m_oCmdLineMap.get(\"comment\"));\n }\n if (m_oCmdLineMap.containsKey(\"genre\"))\n {\n oID3V2_3_0Tag.setGenre((String)m_oCmdLineMap.get(\"genre\"));\n }\n oMP3File.setID3Tag(oID3V2_3_0Tag);\n if (m_oCmdLineMap.containsKey(\"title\"))\n {\n oID3V2_3_0Tag.setTitle((String)m_oCmdLineMap.get(\"title\"));\n }\n if (m_oCmdLineMap.containsKey(\"year\"))\n {\n oID3V2_3_0Tag.setYear(((Integer)m_oCmdLineMap.get(\"year\")).intValue());\n }\n if (m_oCmdLineMap.containsKey(\"track\"))\n {\n if (m_oCmdLineMap.containsKey(\"total\"))\n {\n oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get(\"track\")).intValue(),\n ((Integer)m_oCmdLineMap.get(\"total\")).intValue());\n }\n else\n {\n oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get(\"track\")).intValue());\n }\n }\n }\n oMP3File.sync();\n }\n }"},"code_wo_comment":{"kind":"string","value":"private void tag()\n throws Exception\n {\n String[] asFilename = (String[])m_oCmdLineMap.get(\"filenames\");\n for (int i=0; i < asFilename.length; i++)\n {\n File oSourceFile = new File(asFilename[i]);\n MP3File oMP3File = new MP3File(oSourceFile);\n if (m_oCmdLineMap.containsKey(\"1\"))\n {\n ID3V1_1Tag oID3V1_1Tag = new ID3V1_1Tag();\n if (m_oCmdLineMap.containsKey(\"album\"))\n {\n oID3V1_1Tag.setAlbum((String)m_oCmdLineMap.get(\"album\"));\n }\n if (m_oCmdLineMap.containsKey(\"artist\"))\n {\n oID3V1_1Tag.setArtist((String)m_oCmdLineMap.get(\"artist\"));\n }\n if (m_oCmdLineMap.containsKey(\"comment\"))\n {\n oID3V1_1Tag.setComment((String)m_oCmdLineMap.get(\"comment\"));\n }\n if (m_oCmdLineMap.containsKey(\"genre\"))\n {\n String sGenre = (String)m_oCmdLineMap.get(\"genre\");\n oID3V1_1Tag.setGenre(ID3V1Tag.Genre.lookupGenre(sGenre));\n }\n if (m_oCmdLineMap.containsKey(\"title\"))\n {\n oID3V1_1Tag.setTitle((String)m_oCmdLineMap.get(\"title\"));\n }\n if (m_oCmdLineMap.containsKey(\"year\"))\n {\n oID3V1_1Tag.setYear(((Integer)m_oCmdLineMap.get(\"year\")).toString());\n }\n if (m_oCmdLineMap.containsKey(\"track\"))\n {\n oID3V1_1Tag.setAlbumTrack(((Integer)m_oCmdLineMap.get(\"track\")).intValue());\n }\n oMP3File.setID3Tag(oID3V1_1Tag);\n }\n if (m_oCmdLineMap.containsKey(\"2\"))\n {\n ID3V2_3_0Tag oID3V2_3_0Tag = new ID3V2_3_0Tag();\n \n oID3V2_3_0Tag.setPaddingLength(16);\n if (m_oCmdLineMap.containsKey(\"album\"))\n {\n oID3V2_3_0Tag.setAlbum((String)m_oCmdLineMap.get(\"album\"));\n }\n if (m_oCmdLineMap.containsKey(\"artist\"))\n {\n oID3V2_3_0Tag.setArtist((String)m_oCmdLineMap.get(\"artist\"));\n }\n if (m_oCmdLineMap.containsKey(\"comment\"))\n {\n oID3V2_3_0Tag.setComment((String)m_oCmdLineMap.get(\"comment\"));\n }\n if (m_oCmdLineMap.containsKey(\"genre\"))\n {\n oID3V2_3_0Tag.setGenre((String)m_oCmdLineMap.get(\"genre\"));\n }\n oMP3File.setID3Tag(oID3V2_3_0Tag);\n if (m_oCmdLineMap.containsKey(\"title\"))\n {\n oID3V2_3_0Tag.setTitle((String)m_oCmdLineMap.get(\"title\"));\n }\n if (m_oCmdLineMap.containsKey(\"year\"))\n {\n oID3V2_3_0Tag.setYear(((Integer)m_oCmdLineMap.get(\"year\")).intValue());\n }\n if (m_oCmdLineMap.containsKey(\"track\"))\n {\n if (m_oCmdLineMap.containsKey(\"total\"))\n {\n oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get(\"track\")).intValue(),\n ((Integer)m_oCmdLineMap.get(\"total\")).intValue());\n }\n else\n {\n oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get(\"track\")).intValue());\n }\n }\n }\n oMP3File.sync();\n }\n }"},"cleancode":{"kind":"string","value":"private void tag() throws exception { string[] asfilename = (string[])m_ocmdlinemap.get(\"filenames\"); for (int i=0; i < asfilename.length; i++) { file osourcefile = new file(asfilename[i]); mp3file omp3file = new mp3file(osourcefile); if (m_ocmdlinemap.containskey(\"1\")) { id3v1_1tag oid3v1_1tag = new id3v1_1tag(); if (m_ocmdlinemap.containskey(\"album\")) { oid3v1_1tag.setalbum((string)m_ocmdlinemap.get(\"album\")); } if (m_ocmdlinemap.containskey(\"artist\")) { oid3v1_1tag.setartist((string)m_ocmdlinemap.get(\"artist\")); } if (m_ocmdlinemap.containskey(\"comment\")) { oid3v1_1tag.setcomment((string)m_ocmdlinemap.get(\"comment\")); } if (m_ocmdlinemap.containskey(\"genre\")) { string sgenre = (string)m_ocmdlinemap.get(\"genre\"); oid3v1_1tag.setgenre(id3v1tag.genre.lookupgenre(sgenre)); } if (m_ocmdlinemap.containskey(\"title\")) { oid3v1_1tag.settitle((string)m_ocmdlinemap.get(\"title\")); } if (m_ocmdlinemap.containskey(\"year\")) { oid3v1_1tag.setyear(((integer)m_ocmdlinemap.get(\"year\")).tostring()); } if (m_ocmdlinemap.containskey(\"track\")) { oid3v1_1tag.setalbumtrack(((integer)m_ocmdlinemap.get(\"track\")).intvalue()); } omp3file.setid3tag(oid3v1_1tag); } if (m_ocmdlinemap.containskey(\"2\")) { id3v2_3_0tag oid3v2_3_0tag = new id3v2_3_0tag(); oid3v2_3_0tag.setpaddinglength(16); if (m_ocmdlinemap.containskey(\"album\")) { oid3v2_3_0tag.setalbum((string)m_ocmdlinemap.get(\"album\")); } if (m_ocmdlinemap.containskey(\"artist\")) { oid3v2_3_0tag.setartist((string)m_ocmdlinemap.get(\"artist\")); } if (m_ocmdlinemap.containskey(\"comment\")) { oid3v2_3_0tag.setcomment((string)m_ocmdlinemap.get(\"comment\")); } if (m_ocmdlinemap.containskey(\"genre\")) { oid3v2_3_0tag.setgenre((string)m_ocmdlinemap.get(\"genre\")); } omp3file.setid3tag(oid3v2_3_0tag); if (m_ocmdlinemap.containskey(\"title\")) { oid3v2_3_0tag.settitle((string)m_ocmdlinemap.get(\"title\")); } if (m_ocmdlinemap.containskey(\"year\")) { oid3v2_3_0tag.setyear(((integer)m_ocmdlinemap.get(\"year\")).intvalue()); } if (m_ocmdlinemap.containskey(\"track\")) { if (m_ocmdlinemap.containskey(\"total\")) { oid3v2_3_0tag.settracknumber(((integer)m_ocmdlinemap.get(\"track\")).intvalue(), ((integer)m_ocmdlinemap.get(\"total\")).intvalue()); } else { oid3v2_3_0tag.settracknumber(((integer)m_ocmdlinemap.get(\"track\")).intvalue()); } } } omp3file.sync(); } }"},"repo":{"kind":"string","value":"ShahzaibAyyub/Music-Player-Library-Java-SQL"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":229,"cells":{"id":{"kind":"number","value":8611,"string":"8,611"},"original_code":{"kind":"string","value":"@Override\n\t\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\tif(currSel!= null && currSel instanceof GroupTreeNode){\n\t\t\t\t\t\t// differentiate clones in this group\n\t\t\t\t\t\tGroupTreeNode gtn = (GroupTreeNode)currSel;\n//\t\t\t\t\t\tif(gtn.getChildCount() == 2){\n\t\t\t\t\t\t\t// TODO: currently we only support two way comparison\n\t\t\t\t\t\t\tCloneTreeNode ctn1 = (CloneTreeNode)gtn.getChildAt(0);\n\t\t\t\t\t\t\tCloneTreeNode ctn2 = (CloneTreeNode)gtn.getChildAt(1);\n\t\t\t\t\t\t\tString file1 = ctn1.getFile();\n\t\t\t\t\t\t\tString file2 = ctn2.getFile();\n\t\t\t\t\t\t\tCloneComparison comparison = new CloneComparison(panel, new File(file1), new File(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end);\n\t\t\t\t\t\t\tcomparison.setOpenInBackground(false);\n\t\t\t\t\t\t\tcomparison.execute();\n//\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}"},"code_wo_comment":{"kind":"string","value":"@Override\n\t\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\tif(currSel!= null && currSel instanceof GroupTreeNode){\n\t\t\t\t\t\n\t\t\t\t\t\tGroupTreeNode gtn = (GroupTreeNode)currSel;\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tCloneTreeNode ctn1 = (CloneTreeNode)gtn.getChildAt(0);\n\t\t\t\t\t\t\tCloneTreeNode ctn2 = (CloneTreeNode)gtn.getChildAt(1);\n\t\t\t\t\t\t\tString file1 = ctn1.getFile();\n\t\t\t\t\t\t\tString file2 = ctn2.getFile();\n\t\t\t\t\t\t\tCloneComparison comparison = new CloneComparison(panel, new File(file1), new File(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end);\n\t\t\t\t\t\t\tcomparison.setOpenInBackground(false);\n\t\t\t\t\t\t\tcomparison.execute();\n\t\t\t\t\t}\n\t\t\t\t}"},"cleancode":{"kind":"string","value":"@override public void actionperformed(actionevent e) { if(currsel!= null && currsel instanceof grouptreenode){ grouptreenode gtn = (grouptreenode)currsel; clonetreenode ctn1 = (clonetreenode)gtn.getchildat(0); clonetreenode ctn2 = (clonetreenode)gtn.getchildat(1); string file1 = ctn1.getfile(); string file2 = ctn2.getfile(); clonecomparison comparison = new clonecomparison(panel, new file(file1), new file(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end); comparison.setopeninbackground(false); comparison.execute(); } }"},"repo":{"kind":"string","value":"UCLA-SEAL/Grafter"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":230,"cells":{"id":{"kind":"number","value":25018,"string":"25,018"},"original_code":{"kind":"string","value":"private BaseQuery buildQueryNoAggregations(QueryFactory queryFactory, String queryString, Map namedParameters,\n long startOffset, int maxResults, IckleParsingResult parsingResult) {\n if (parsingResult.hasGroupingOrAggregations()) {\n throw log.queryMustNotUseGroupingOrAggregation(); // may happen only due to internal programming error\n }\n boolean isFullTextQuery;\n if (parsingResult.getWhereClause() != null) {\n isFullTextQuery = parsingResult.getWhereClause().acceptVisitor(FullTextVisitor.INSTANCE);\n if (!isIndexed && isFullTextQuery) {\n throw new IllegalStateException(\"The cache must be indexed in order to use full-text queries.\");\n }\n }\n if (parsingResult.getSortFields() != null) {\n for (SortField sortField : parsingResult.getSortFields()) {\n PropertyPath p = sortField.getPath();\n if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) {\n throw log.multivaluedPropertyCannotBeUsedInOrderBy(p.toString());\n }\n }\n }\n if (parsingResult.getProjectedPaths() != null) {\n for (PropertyPath p : parsingResult.getProjectedPaths()) {\n if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) {\n throw log.multivaluedPropertyCannotBeProjected(p.asStringPath());\n }\n }\n }\n BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause());\n if (normalizedWhereClause == ConstantBooleanExpr.FALSE) {\n // the query is a contradiction, there are no matches\n return new EmptyResultQuery(queryFactory, cache, queryString, namedParameters, startOffset, maxResults);\n }\n // if cache is indexed but there is no actual 'where' filter clause and we do have sorting or projections we should still use the index, otherwise just go for a non-indexed fetch-all\n if (!isIndexed || (normalizedWhereClause == null || normalizedWhereClause == ConstantBooleanExpr.TRUE) && parsingResult.getProjections() == null && parsingResult.getSortFields() == null) {\n // fully non-indexed execution because the filter matches everything or there is no indexing at all\n return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults);\n }\n IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata = propertyHelper.getIndexedFieldProvider().get(parsingResult.getTargetEntityMetadata());\n boolean allProjectionsAreStored = true;\n LinkedHashMap> projectionsMap = null;\n if (parsingResult.getProjectedPaths() != null) {\n projectionsMap = new LinkedHashMap<>();\n for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) {\n PropertyPath p = parsingResult.getProjectedPaths()[i];\n List idx = projectionsMap.get(p);\n if (idx == null) {\n idx = new ArrayList<>();\n projectionsMap.put(p, idx);\n if (!fieldIndexingMetadata.isStored(p.asArrayPath())) {\n allProjectionsAreStored = false;\n }\n }\n idx.add(i);\n }\n }\n boolean allSortFieldsAreStored = true;\n SortField[] sortFields = parsingResult.getSortFields();\n if (sortFields != null) {\n // deduplicate sort fields\n LinkedHashMap sortFieldMap = new LinkedHashMap<>();\n for (SortField sf : sortFields) {\n PropertyPath p = sf.getPath();\n String asStringPath = p.asStringPath();\n if (!sortFieldMap.containsKey(asStringPath)) {\n sortFieldMap.put(asStringPath, sf);\n if (!fieldIndexingMetadata.isStored(p.asArrayPath())) {\n allSortFieldsAreStored = false;\n }\n }\n }\n sortFields = sortFieldMap.values().toArray(new SortField[sortFieldMap.size()]);\n }\n //todo [anistor] do not allow hybrid queries with fulltext. exception, allow a fully indexed query followed by in-memory aggregation. the aggregated or 'having' field should not be analyzed\n //todo [anistor] do we allow aggregation in fulltext queries?\n //todo [anistor] do not allow hybrid fulltext queries. all 'where' fields must be indexed. all projections must be stored.\n BooleShannonExpansion bse = new BooleShannonExpansion(MAX_EXPANSION_COFACTORS, fieldIndexingMetadata);\n BooleanExpr expansion = bse.expand(normalizedWhereClause);\n if (expansion == normalizedWhereClause) { // identity comparison is intended here!\n // all involved fields are indexed, so go the Lucene way\n if (allSortFieldsAreStored) {\n if (allProjectionsAreStored) {\n // all projections are stored, so we can execute the query entirely against the index, and we can also sort using the index\n RowProcessor rowProcessor = null;\n if (parsingResult.getProjectedPaths() != null) {\n if (projectionsMap.size() != parsingResult.getProjectedPaths().length) {\n // but some projections are duplicated ...\n final Class[] projectedTypes = new Class[projectionsMap.size()];\n final int[] map = new int[parsingResult.getProjectedPaths().length];\n int j = 0;\n for (List idx : projectionsMap.values()) {\n int i = idx.get(0);\n projectedTypes[j] = parsingResult.getProjectedTypes()[i];\n for (int k : idx) {\n map[k] = j;\n }\n j++;\n }\n RowProcessor projectionProcessor = makeProjectionProcessor(projectedTypes);\n rowProcessor = inRow -> {\n if (projectionProcessor != null) {\n inRow = projectionProcessor.process(inRow);\n }\n Object[] outRow = new Object[map.length];\n for (int i = 0; i < map.length; i++) {\n outRow[i] = inRow[map[i]];\n }\n return outRow;\n };\n PropertyPath[] deduplicatedProjection = projectionsMap.keySet().toArray(new PropertyPath[projectionsMap.size()]);\n IckleParsingResult fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, deduplicatedProjection, projectedTypes, sortFields);\n return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults);\n } else {\n rowProcessor = makeProjectionProcessor(parsingResult.getProjectedTypes());\n }\n }\n return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, parsingResult, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults);\n } else {\n IckleParsingResult fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, sortFields);\n Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), startOffset, maxResults);\n String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, null);\n return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), -1, -1, indexQuery);\n }\n } else {\n // projections may be stored but some sort fields are not so we need to query the index and then execute in-memory sorting and projecting in a second phase\n IckleParsingResult fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, null);\n Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1);\n String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, sortFields);\n return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), startOffset, maxResults, indexQuery);\n }\n }\n if (expansion == ConstantBooleanExpr.TRUE) {\n // expansion leads to a full non-indexed query or the expansion is too long/complex\n return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults);\n }\n // some fields are indexed, run a hybrid query\n IckleParsingResult fpr = makeFilterParsingResult(parsingResult, expansion, null, null, null);\n Query expandedQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1);\n return new HybridQuery(queryFactory, cache, queryString, namedParameters, getObjectFilter(matcher, queryString, namedParameters, null), startOffset, maxResults, expandedQuery);\n }"},"code_wo_comment":{"kind":"string","value":"private BaseQuery buildQueryNoAggregations(QueryFactory queryFactory, String queryString, Map namedParameters,\n long startOffset, int maxResults, IckleParsingResult parsingResult) {\n if (parsingResult.hasGroupingOrAggregations()) {\n throw log.queryMustNotUseGroupingOrAggregation();\n }\n boolean isFullTextQuery;\n if (parsingResult.getWhereClause() != null) {\n isFullTextQuery = parsingResult.getWhereClause().acceptVisitor(FullTextVisitor.INSTANCE);\n if (!isIndexed && isFullTextQuery) {\n throw new IllegalStateException(\"The cache must be indexed in order to use full-text queries.\");\n }\n }\n if (parsingResult.getSortFields() != null) {\n for (SortField sortField : parsingResult.getSortFields()) {\n PropertyPath p = sortField.getPath();\n if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) {\n throw log.multivaluedPropertyCannotBeUsedInOrderBy(p.toString());\n }\n }\n }\n if (parsingResult.getProjectedPaths() != null) {\n for (PropertyPath p : parsingResult.getProjectedPaths()) {\n if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) {\n throw log.multivaluedPropertyCannotBeProjected(p.asStringPath());\n }\n }\n }\n BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause());\n if (normalizedWhereClause == ConstantBooleanExpr.FALSE) {\n \n return new EmptyResultQuery(queryFactory, cache, queryString, namedParameters, startOffset, maxResults);\n }\n \n if (!isIndexed || (normalizedWhereClause == null || normalizedWhereClause == ConstantBooleanExpr.TRUE) && parsingResult.getProjections() == null && parsingResult.getSortFields() == null) {\n \n return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults);\n }\n IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata = propertyHelper.getIndexedFieldProvider().get(parsingResult.getTargetEntityMetadata());\n boolean allProjectionsAreStored = true;\n LinkedHashMap> projectionsMap = null;\n if (parsingResult.getProjectedPaths() != null) {\n projectionsMap = new LinkedHashMap<>();\n for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) {\n PropertyPath p = parsingResult.getProjectedPaths()[i];\n List idx = projectionsMap.get(p);\n if (idx == null) {\n idx = new ArrayList<>();\n projectionsMap.put(p, idx);\n if (!fieldIndexingMetadata.isStored(p.asArrayPath())) {\n allProjectionsAreStored = false;\n }\n }\n idx.add(i);\n }\n }\n boolean allSortFieldsAreStored = true;\n SortField[] sortFields = parsingResult.getSortFields();\n if (sortFields != null) {\n \n LinkedHashMap sortFieldMap = new LinkedHashMap<>();\n for (SortField sf : sortFields) {\n PropertyPath p = sf.getPath();\n String asStringPath = p.asStringPath();\n if (!sortFieldMap.containsKey(asStringPath)) {\n sortFieldMap.put(asStringPath, sf);\n if (!fieldIndexingMetadata.isStored(p.asArrayPath())) {\n allSortFieldsAreStored = false;\n }\n }\n }\n sortFields = sortFieldMap.values().toArray(new SortField[sortFieldMap.size()]);\n }\n \n \n \n BooleShannonExpansion bse = new BooleShannonExpansion(MAX_EXPANSION_COFACTORS, fieldIndexingMetadata);\n BooleanExpr expansion = bse.expand(normalizedWhereClause);\n if (expansion == normalizedWhereClause) { \n \n if (allSortFieldsAreStored) {\n if (allProjectionsAreStored) {\n \n RowProcessor rowProcessor = null;\n if (parsingResult.getProjectedPaths() != null) {\n if (projectionsMap.size() != parsingResult.getProjectedPaths().length) {\n \n final Class[] projectedTypes = new Class[projectionsMap.size()];\n final int[] map = new int[parsingResult.getProjectedPaths().length];\n int j = 0;\n for (List idx : projectionsMap.values()) {\n int i = idx.get(0);\n projectedTypes[j] = parsingResult.getProjectedTypes()[i];\n for (int k : idx) {\n map[k] = j;\n }\n j++;\n }\n RowProcessor projectionProcessor = makeProjectionProcessor(projectedTypes);\n rowProcessor = inRow -> {\n if (projectionProcessor != null) {\n inRow = projectionProcessor.process(inRow);\n }\n Object[] outRow = new Object[map.length];\n for (int i = 0; i < map.length; i++) {\n outRow[i] = inRow[map[i]];\n }\n return outRow;\n };\n PropertyPath[] deduplicatedProjection = projectionsMap.keySet().toArray(new PropertyPath[projectionsMap.size()]);\n IckleParsingResult fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, deduplicatedProjection, projectedTypes, sortFields);\n return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults);\n } else {\n rowProcessor = makeProjectionProcessor(parsingResult.getProjectedTypes());\n }\n }\n return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, parsingResult, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults);\n } else {\n IckleParsingResult fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, sortFields);\n Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), startOffset, maxResults);\n String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, null);\n return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), -1, -1, indexQuery);\n }\n } else {\n \n IckleParsingResult fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, null);\n Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1);\n String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, sortFields);\n return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), startOffset, maxResults, indexQuery);\n }\n }\n if (expansion == ConstantBooleanExpr.TRUE) {\n \n return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults);\n }\n \n IckleParsingResult fpr = makeFilterParsingResult(parsingResult, expansion, null, null, null);\n Query expandedQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1);\n return new HybridQuery(queryFactory, cache, queryString, namedParameters, getObjectFilter(matcher, queryString, namedParameters, null), startOffset, maxResults, expandedQuery);\n }"},"cleancode":{"kind":"string","value":"private basequery buildquerynoaggregations(queryfactory queryfactory, string querystring, map namedparameters, long startoffset, int maxresults, ickleparsingresult parsingresult) { if (parsingresult.hasgroupingoraggregations()) { throw log.querymustnotusegroupingoraggregation(); } boolean isfulltextquery; if (parsingresult.getwhereclause() != null) { isfulltextquery = parsingresult.getwhereclause().acceptvisitor(fulltextvisitor.instance); if (!isindexed && isfulltextquery) { throw new illegalstateexception(\"the cache must be indexed in order to use full-text queries.\"); } } if (parsingresult.getsortfields() != null) { for (sortfield sortfield : parsingresult.getsortfields()) { propertypath p = sortfield.getpath(); if (propertyhelper.isrepeatedproperty(parsingresult.gettargetentitymetadata(), p.asarraypath())) { throw log.multivaluedpropertycannotbeusedinorderby(p.tostring()); } } } if (parsingresult.getprojectedpaths() != null) { for (propertypath p : parsingresult.getprojectedpaths()) { if (propertyhelper.isrepeatedproperty(parsingresult.gettargetentitymetadata(), p.asarraypath())) { throw log.multivaluedpropertycannotbeprojected(p.asstringpath()); } } } booleanexpr normalizedwhereclause = booleanfilternormalizer.normalize(parsingresult.getwhereclause()); if (normalizedwhereclause == constantbooleanexpr.false) { return new emptyresultquery(queryfactory, cache, querystring, namedparameters, startoffset, maxresults); } if (!isindexed || (normalizedwhereclause == null || normalizedwhereclause == constantbooleanexpr.true) && parsingresult.getprojections() == null && parsingresult.getsortfields() == null) { return new embeddedquery(this, queryfactory, cache, querystring, namedparameters, parsingresult.getprojections(), startoffset, maxresults); } indexedfieldprovider.fieldindexingmetadata fieldindexingmetadata = propertyhelper.getindexedfieldprovider().get(parsingresult.gettargetentitymetadata()); boolean allprojectionsarestored = true; linkedhashmap> projectionsmap = null; if (parsingresult.getprojectedpaths() != null) { projectionsmap = new linkedhashmap<>(); for (int i = 0; i < parsingresult.getprojectedpaths().length; i++) { propertypath p = parsingresult.getprojectedpaths()[i]; list idx = projectionsmap.get(p); if (idx == null) { idx = new arraylist<>(); projectionsmap.put(p, idx); if (!fieldindexingmetadata.isstored(p.asarraypath())) { allprojectionsarestored = false; } } idx.add(i); } } boolean allsortfieldsarestored = true; sortfield[] sortfields = parsingresult.getsortfields(); if (sortfields != null) { linkedhashmap sortfieldmap = new linkedhashmap<>(); for (sortfield sf : sortfields) { propertypath p = sf.getpath(); string asstringpath = p.asstringpath(); if (!sortfieldmap.containskey(asstringpath)) { sortfieldmap.put(asstringpath, sf); if (!fieldindexingmetadata.isstored(p.asarraypath())) { allsortfieldsarestored = false; } } } sortfields = sortfieldmap.values().toarray(new sortfield[sortfieldmap.size()]); } booleshannonexpansion bse = new booleshannonexpansion(max_expansion_cofactors, fieldindexingmetadata); booleanexpr expansion = bse.expand(normalizedwhereclause); if (expansion == normalizedwhereclause) { if (allsortfieldsarestored) { if (allprojectionsarestored) { rowprocessor rowprocessor = null; if (parsingresult.getprojectedpaths() != null) { if (projectionsmap.size() != parsingresult.getprojectedpaths().length) { final class[] projectedtypes = new class[projectionsmap.size()]; final int[] map = new int[parsingresult.getprojectedpaths().length]; int j = 0; for (list idx : projectionsmap.values()) { int i = idx.get(0); projectedtypes[j] = parsingresult.getprojectedtypes()[i]; for (int k : idx) { map[k] = j; } j++; } rowprocessor projectionprocessor = makeprojectionprocessor(projectedtypes); rowprocessor = inrow -> { if (projectionprocessor != null) { inrow = projectionprocessor.process(inrow); } object[] outrow = new object[map.length]; for (int i = 0; i < map.length; i++) { outrow[i] = inrow[map[i]]; } return outrow; }; propertypath[] deduplicatedprojection = projectionsmap.keyset().toarray(new propertypath[projectionsmap.size()]); ickleparsingresult fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, deduplicatedprojection, projectedtypes, sortfields); return new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, parsingresult.getprojections(), makeresultprocessor(rowprocessor), startoffset, maxresults); } else { rowprocessor = makeprojectionprocessor(parsingresult.getprojectedtypes()); } } return new embeddedlucenequery<>(this, queryfactory, namedparameters, parsingresult, parsingresult.getprojections(), makeresultprocessor(rowprocessor), startoffset, maxresults); } else { ickleparsingresult fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, null, null, sortfields); query indexquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), startoffset, maxresults); string projectionquerystr = syntaxtreeprinter.printtree(parsingresult.gettargetentityname(), parsingresult.getprojectedpaths(), null, null); return new hybridquery(queryfactory, cache, projectionquerystr, null, getobjectfilter(matcher, projectionquerystr, null, null), -1, -1, indexquery); } } else { ickleparsingresult fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, null, null, null); query indexquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), -1, -1); string projectionquerystr = syntaxtreeprinter.printtree(parsingresult.gettargetentityname(), parsingresult.getprojectedpaths(), null, sortfields); return new hybridquery(queryfactory, cache, projectionquerystr, null, getobjectfilter(matcher, projectionquerystr, null, null), startoffset, maxresults, indexquery); } } if (expansion == constantbooleanexpr.true) { return new embeddedquery(this, queryfactory, cache, querystring, namedparameters, parsingresult.getprojections(), startoffset, maxresults); } ickleparsingresult fpr = makefilterparsingresult(parsingresult, expansion, null, null, null); query expandedquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), -1, -1); return new hybridquery(queryfactory, cache, querystring, namedparameters, getobjectfilter(matcher, querystring, namedparameters, null), startoffset, maxresults, expandedquery); }"},"repo":{"kind":"string","value":"TomasHofman/infinispan"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":231,"cells":{"id":{"kind":"number","value":448,"string":"448"},"original_code":{"kind":"string","value":"public static char[][] fill(char contents, int width, int height) {\n char[][] next = new char[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"code_wo_comment":{"kind":"string","value":"public static char[][] fill(char contents, int width, int height) {\n char[][] next = new char[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"cleancode":{"kind":"string","value":"public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }"},"repo":{"kind":"string","value":"SquidPony/SquidLib"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":232,"cells":{"id":{"kind":"number","value":449,"string":"449"},"original_code":{"kind":"string","value":"public static float[][] fill(float contents, int width, int height) {\n float[][] next = new float[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"code_wo_comment":{"kind":"string","value":"public static float[][] fill(float contents, int width, int height) {\n float[][] next = new float[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"cleancode":{"kind":"string","value":"public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }"},"repo":{"kind":"string","value":"SquidPony/SquidLib"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":233,"cells":{"id":{"kind":"number","value":450,"string":"450"},"original_code":{"kind":"string","value":"public static double[][] fill(double contents, int width, int height) {\n double[][] next = new double[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"code_wo_comment":{"kind":"string","value":"public static double[][] fill(double contents, int width, int height) {\n double[][] next = new double[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"cleancode":{"kind":"string","value":"public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }"},"repo":{"kind":"string","value":"SquidPony/SquidLib"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":234,"cells":{"id":{"kind":"number","value":451,"string":"451"},"original_code":{"kind":"string","value":"public static int[][] fill(int contents, int width, int height) {\n int[][] next = new int[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"code_wo_comment":{"kind":"string","value":"public static int[][] fill(int contents, int width, int height) {\n int[][] next = new int[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"cleancode":{"kind":"string","value":"public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }"},"repo":{"kind":"string","value":"SquidPony/SquidLib"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":235,"cells":{"id":{"kind":"number","value":452,"string":"452"},"original_code":{"kind":"string","value":"public static byte[][] fill(byte contents, int width, int height) {\n byte[][] next = new byte[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"code_wo_comment":{"kind":"string","value":"public static byte[][] fill(byte contents, int width, int height) {\n byte[][] next = new byte[width][height];\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], contents);\n }\n return next;\n }"},"cleancode":{"kind":"string","value":"public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }"},"repo":{"kind":"string","value":"SquidPony/SquidLib"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":236,"cells":{"id":{"kind":"number","value":453,"string":"453"},"original_code":{"kind":"string","value":"public static boolean[][] fill(boolean contents, int width, int height) {\n boolean[][] next = new boolean[width][height];\n if (contents) {\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], true);\n }\n }\n return next;\n }"},"code_wo_comment":{"kind":"string","value":"public static boolean[][] fill(boolean contents, int width, int height) {\n boolean[][] next = new boolean[width][height];\n if (contents) {\n for (int x = 0; x < width; x++) {\n Arrays.fill(next[x], true);\n }\n }\n return next;\n }"},"cleancode":{"kind":"string","value":"public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { arrays.fill(next[x], true); } } return next; }"},"repo":{"kind":"string","value":"SquidPony/SquidLib"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":237,"cells":{"id":{"kind":"number","value":16885,"string":"16,885"},"original_code":{"kind":"string","value":"@JsonGetter(\"limit\")\n public String getLimit ( ) { \n return this.limit;\n }"},"code_wo_comment":{"kind":"string","value":"@JsonGetter(\"limit\")\n public String getLimit ( ) { \n return this.limit;\n }"},"cleancode":{"kind":"string","value":"@jsongetter(\"limit\") public string getlimit ( ) { return this.limit; }"},"repo":{"kind":"string","value":"adams-okode/chirpstack-rest-sdk"},"label":{"kind":"list like","value":[0,0,0,0],"string":"[\n 0,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":238,"cells":{"id":{"kind":"number","value":25078,"string":"25,078"},"original_code":{"kind":"string","value":"@Override\n\tprotected void execute(CalculationMonitor monitor){\n\t\t// import the image data into 1D arrays : TO DO\n\t\tImageDataFloat\tlayersImg = new ImageDataFloat(layersImage.getImageData());\n\t\tImageDataFloat\tintensImg = new ImageDataFloat(intensityImage.getImageData());\n\t\tint nx = layersImg.getRows();\n\t\tint ny = layersImg.getCols();\n\t\tint nz = layersImg.getSlices();\n\t\tint nlayers = layersImg.getComponents()-1;\n\t\tint nxyz = nx*ny*nz;\n\t\tfloat rx = layersImg.getHeader().getDimResolutions()[0];\n\t\tfloat ry = layersImg.getHeader().getDimResolutions()[1];\n\t\tfloat rz = layersImg.getHeader().getDimResolutions()[2];\n\t\tfloat[][] layers = new float[nlayers+1][nxyz];\n\t\tfloat[][][][] buffer4 = layersImg.toArray4d();\n\t\tfor (int x=0;x 0 and layer 2 is < 0\n\t\tboolean[] ctxmask = new boolean[nxyz];\n\t\tif (maskImage.getImageData()!=null) {\n\t\t\tImageDataUByte\tmaskImg = new ImageDataUByte(maskImage.getImageData());\n\t\t\tbyte[][][] bufferbyte = maskImg.toArray3d();\n\t\t\tfor (int x=0;x=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0);\n\t\t\t}\n\t\t\tbufferbyte = null;\n\t\t\tmaskImg = null;\n\t\t} else {\n\t\t\tfor (int xyz=0;xyz=0.0 && layers[nlayers][xyz]<=0.0);\n\t\t\t}\n\t\t}\n\t\t// main algorithm\n\t\t// 1. define partial voume for each layer, each voxel\n\t\tfloat[][] pvol = new float[nlayers+1][nxyz];\n\t\tfor (int x=0; x=nlayers) {\n\t\t\t\t\tdouble[][] glm = new double[nlayers][nsample];\n\t\t\t\t\tdouble[][] data = new double[nsample][1];\n\t\t\t\t\tint idx = 0;\n\t\t\t\t\tfor (int n=0;n=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0);\n\t\t\t}\n\t\t\tbufferbyte = null;\n\t\t\tmaskImg = null;\n\t\t} else {\n\t\t\tfor (int xyz=0;xyz=0.0 && layers[nlayers][xyz]<=0.0);\n\t\t\t}\n\t\t}\n\t\n\t\n\t\tfloat[][] pvol = new float[nlayers+1][nxyz];\n\t\tfor (int x=0; x=nlayers) {\n\t\t\t\t\tdouble[][] glm = new double[nlayers][nsample];\n\t\t\t\t\tdouble[][] data = new double[nsample][1];\n\t\t\t\t\tint idx = 0;\n\t\t\t\t\tfor (int n=0;n=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskimg = null; } else { for (int xyz=0;xyz=0.0 && layers[nlayers][xyz]<=0.0); } } float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n history = this.strongholdPath.getHistory();\n ArrayList solution = new ArrayList<>();\n StrongholdGenerator.Piece current = this.strongholdPath.getHistory().get(strongholdPath.getHistory().size() - 1).getCurrentPiece();\n while (current != null) {\n solution.add(current);\n current = (StrongholdGenerator.Piece) treeAccessor.getParents().get(current);\n }\n List validEntries = history.stream()\n .filter(entry -> validateEntryForLoss(strongholdPath, strongholdPath.getNextEntry(entry)))\n .filter(entry -> !solution.contains(strongholdPath.getNextEntry(entry).getCurrentPiece()) && solution.contains(entry.getCurrentPiece()))\n .collect(Collectors.toList());\n List> losses = new ArrayList<>();\n validEntries.forEach(strongholdPathEntry -> losses.add(new Pair<>(strongholdPathEntry, loss(strongholdPath, strongholdPath.getNextEntry(strongholdPathEntry), solution))));\n this.inaccuracies = losses.stream().filter(pair -> pair.getRight() >= INACCURACY_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList());\n this.mistakes = losses.stream().filter(pair -> pair.getRight() >= MISTAKE_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList());\n this.blunders = losses.stream().filter(pair -> pair.getRight() >= BLUNDER_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList());\n inaccuracies.removeAll(this.mistakes);\n mistakes.removeAll(this.blunders);\n ArrayList> rooms = new ArrayList<>();\n history.forEach(pathEntry -> {\n Pair pair = new Pair<>(pathEntry.getCurrentPiece(), pathEntry.getTicksSpentInPiece().get());\n rooms.add(pair);\n });\n return new PlayerPathData(\n rooms,\n strongholdPath.getTotalTime(),\n computeDifficulty(solution),\n history.stream()\n .filter(pathEntry -> !solution.contains(pathEntry.getCurrentPiece()))\n .map(StrongholdPathEntry::getTicksSpentInPiece)\n .mapToInt(AtomicInteger::get)\n .sum(),\n // TODO: don't count entering the first Five-Way\n (int) history.stream()\n .map(strongholdPathEntry -> strongholdPath.getNextEntry(strongholdPathEntry))\n .filter(Objects::nonNull)\n .map(StrongholdPathEntry::getCurrentPiece)\n .filter(solution::contains)\n .count(),\n this.inaccuracies.size(),\n this.mistakes.size(),\n this.blunders.size(),\n (int) history.stream()\n .filter(entry -> !(entry.getCurrentPiece() instanceof StrongholdGenerator.PortalRoom))\n .filter(entry -> !areAdjacent(entry.getCurrentPiece(), strongholdPath.getNextEntry(entry).getCurrentPiece(), treeAccessor))\n .count(),\n history.size() - 1,\n history.stream()\n .filter(entry -> FEINBERG_AVG_ROOM_TIMES.containsKey(entry.getCurrentPiece().getClass()))\n .mapToInt(value -> value.getTicksSpentInPiece().get() - FEINBERG_AVG_ROOM_TIMES.get(value.getCurrentPiece().getClass()))\n .sum()\n );\n }"},"code_wo_comment":{"kind":"string","value":"public PlayerPathData populateStats() {\n this.playerEntity = strongholdPath.getPlayerEntity();\n StrongholdGenerator.Start start = this.strongholdPath.getStart();\n StrongholdTreeAccessor treeAccessor = (StrongholdTreeAccessor) start;\n List history = this.strongholdPath.getHistory();\n ArrayList solution = new ArrayList<>();\n StrongholdGenerator.Piece current = this.strongholdPath.getHistory().get(strongholdPath.getHistory().size() - 1).getCurrentPiece();\n while (current != null) {\n solution.add(current);\n current = (StrongholdGenerator.Piece) treeAccessor.getParents().get(current);\n }\n List validEntries = history.stream()\n .filter(entry -> validateEntryForLoss(strongholdPath, strongholdPath.getNextEntry(entry)))\n .filter(entry -> !solution.contains(strongholdPath.getNextEntry(entry).getCurrentPiece()) && solution.contains(entry.getCurrentPiece()))\n .collect(Collectors.toList());\n List> losses = new ArrayList<>();\n validEntries.forEach(strongholdPathEntry -> losses.add(new Pair<>(strongholdPathEntry, loss(strongholdPath, strongholdPath.getNextEntry(strongholdPathEntry), solution))));\n this.inaccuracies = losses.stream().filter(pair -> pair.getRight() >= INACCURACY_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList());\n this.mistakes = losses.stream().filter(pair -> pair.getRight() >= MISTAKE_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList());\n this.blunders = losses.stream().filter(pair -> pair.getRight() >= BLUNDER_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList());\n inaccuracies.removeAll(this.mistakes);\n mistakes.removeAll(this.blunders);\n ArrayList> rooms = new ArrayList<>();\n history.forEach(pathEntry -> {\n Pair pair = new Pair<>(pathEntry.getCurrentPiece(), pathEntry.getTicksSpentInPiece().get());\n rooms.add(pair);\n });\n return new PlayerPathData(\n rooms,\n strongholdPath.getTotalTime(),\n computeDifficulty(solution),\n history.stream()\n .filter(pathEntry -> !solution.contains(pathEntry.getCurrentPiece()))\n .map(StrongholdPathEntry::getTicksSpentInPiece)\n .mapToInt(AtomicInteger::get)\n .sum(),\n \n (int) history.stream()\n .map(strongholdPathEntry -> strongholdPath.getNextEntry(strongholdPathEntry))\n .filter(Objects::nonNull)\n .map(StrongholdPathEntry::getCurrentPiece)\n .filter(solution::contains)\n .count(),\n this.inaccuracies.size(),\n this.mistakes.size(),\n this.blunders.size(),\n (int) history.stream()\n .filter(entry -> !(entry.getCurrentPiece() instanceof StrongholdGenerator.PortalRoom))\n .filter(entry -> !areAdjacent(entry.getCurrentPiece(), strongholdPath.getNextEntry(entry).getCurrentPiece(), treeAccessor))\n .count(),\n history.size() - 1,\n history.stream()\n .filter(entry -> FEINBERG_AVG_ROOM_TIMES.containsKey(entry.getCurrentPiece().getClass()))\n .mapToInt(value -> value.getTicksSpentInPiece().get() - FEINBERG_AVG_ROOM_TIMES.get(value.getCurrentPiece().getClass()))\n .sum()\n );\n }"},"cleancode":{"kind":"string","value":"public playerpathdata populatestats() { this.playerentity = strongholdpath.getplayerentity(); strongholdgenerator.start start = this.strongholdpath.getstart(); strongholdtreeaccessor treeaccessor = (strongholdtreeaccessor) start; list history = this.strongholdpath.gethistory(); arraylist solution = new arraylist<>(); strongholdgenerator.piece current = this.strongholdpath.gethistory().get(strongholdpath.gethistory().size() - 1).getcurrentpiece(); while (current != null) { solution.add(current); current = (strongholdgenerator.piece) treeaccessor.getparents().get(current); } list validentries = history.stream() .filter(entry -> validateentryforloss(strongholdpath, strongholdpath.getnextentry(entry))) .filter(entry -> !solution.contains(strongholdpath.getnextentry(entry).getcurrentpiece()) && solution.contains(entry.getcurrentpiece())) .collect(collectors.tolist()); list> losses = new arraylist<>(); validentries.foreach(strongholdpathentry -> losses.add(new pair<>(strongholdpathentry, loss(strongholdpath, strongholdpath.getnextentry(strongholdpathentry), solution)))); this.inaccuracies = losses.stream().filter(pair -> pair.getright() >= inaccuracy_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); this.mistakes = losses.stream().filter(pair -> pair.getright() >= mistake_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); this.blunders = losses.stream().filter(pair -> pair.getright() >= blunder_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); inaccuracies.removeall(this.mistakes); mistakes.removeall(this.blunders); arraylist> rooms = new arraylist<>(); history.foreach(pathentry -> { pair pair = new pair<>(pathentry.getcurrentpiece(), pathentry.getticksspentinpiece().get()); rooms.add(pair); }); return new playerpathdata( rooms, strongholdpath.gettotaltime(), computedifficulty(solution), history.stream() .filter(pathentry -> !solution.contains(pathentry.getcurrentpiece())) .map(strongholdpathentry::getticksspentinpiece) .maptoint(atomicinteger::get) .sum(), (int) history.stream() .map(strongholdpathentry -> strongholdpath.getnextentry(strongholdpathentry)) .filter(objects::nonnull) .map(strongholdpathentry::getcurrentpiece) .filter(solution::contains) .count(), this.inaccuracies.size(), this.mistakes.size(), this.blunders.size(), (int) history.stream() .filter(entry -> !(entry.getcurrentpiece() instanceof strongholdgenerator.portalroom)) .filter(entry -> !areadjacent(entry.getcurrentpiece(), strongholdpath.getnextentry(entry).getcurrentpiece(), treeaccessor)) .count(), history.size() - 1, history.stream() .filter(entry -> feinberg_avg_room_times.containskey(entry.getcurrentpiece().getclass())) .maptoint(value -> value.getticksspentinpiece().get() - feinberg_avg_room_times.get(value.getcurrentpiece().getclass())) .sum() ); }"},"repo":{"kind":"string","value":"ScribbleLP/StrongholdTrainer"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":244,"cells":{"id":{"kind":"number","value":17055,"string":"17,055"},"original_code":{"kind":"string","value":"public void sendEmail(String userId1, String userId2, String asgmtName, double score, String recipientMail,\n\t\t\tString reportLink) throws Exception {\n\t\tMimeMessage message = sender.createMimeMessage();\n\t\tMimeMessageHelper helper = new MimeMessageHelper(message);\n\t\tString stud1 = userService.findById(userId1).getfName();\n\t\tString stud2 = userService.findById(userId2).getfName();\n\t\thelper.setTo(\"anubhuti.vyas.28@gmail.com\");\n\t\thelper.setText(\"Codesniffer found plagiarised submission with similarity score\" + score\n\t\t\t\t+ \"Click the below link to view the full report+\\n\" + \"https://s3.amazonaws.com/codesniffer-reports/\"\n\t\t\t\t+ reportLink+ \"/match0.html\");\n\t\t// to do add link in email\n\t\thelper.setSubject(\"Plag detected in \" + asgmtName + \" between \" + stud1 + \" and \" + stud2);\n\t\tsender.send(message);\n\t}"},"code_wo_comment":{"kind":"string","value":"public void sendEmail(String userId1, String userId2, String asgmtName, double score, String recipientMail,\n\t\t\tString reportLink) throws Exception {\n\t\tMimeMessage message = sender.createMimeMessage();\n\t\tMimeMessageHelper helper = new MimeMessageHelper(message);\n\t\tString stud1 = userService.findById(userId1).getfName();\n\t\tString stud2 = userService.findById(userId2).getfName();\n\t\thelper.setTo(\"anubhuti.vyas.28@gmail.com\");\n\t\thelper.setText(\"Codesniffer found plagiarised submission with similarity score\" + score\n\t\t\t\t+ \"Click the below link to view the full report+\\n\" + \"https://s3.amazonaws.com/codesniffer-reports/\"\n\t\t\t\t+ reportLink+ \"/match0.html\");\n\t\n\t\thelper.setSubject(\"Plag detected in \" + asgmtName + \" between \" + stud1 + \" and \" + stud2);\n\t\tsender.send(message);\n\t}"},"cleancode":{"kind":"string","value":"public void sendemail(string userid1, string userid2, string asgmtname, double score, string recipientmail, string reportlink) throws exception { mimemessage message = sender.createmimemessage(); mimemessagehelper helper = new mimemessagehelper(message); string stud1 = userservice.findbyid(userid1).getfname(); string stud2 = userservice.findbyid(userid2).getfname(); helper.setto(\"anubhuti.vyas.28@gmail.com\"); helper.settext(\"codesniffer found plagiarised submission with similarity score\" + score + \"click the below link to view the full report+\\n\" + \"https://s3.amazonaws.com/codesniffer-reports/\" + reportlink+ \"/match0.html\"); helper.setsubject(\"plag detected in \" + asgmtname + \" between \" + stud1 + \" and \" + stud2); sender.send(message); }"},"repo":{"kind":"string","value":"Stephen3333/codesniffer"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":245,"cells":{"id":{"kind":"number","value":17081,"string":"17,081"},"original_code":{"kind":"string","value":"@Override\n public void refresh()\n throws LoginException, GSSException\n {\n // TODO: do we need to call logout() on the LoginContext?\n loginContext = new LoginContext(\"\", null, null, new Configuration()\n {\n @Override\n public AppConfigurationEntry[] getAppConfigurationEntry(String name)\n {\n ImmutableMap.Builder options = ImmutableMap.builder();\n options.put(\"refreshKrb5Config\", \"true\");\n options.put(\"doNotPrompt\", \"true\");\n options.put(\"useKeyTab\", \"true\");\n if (getBoolean(\"trino.client.debugKerberos\")) {\n options.put(\"debug\", \"true\");\n }\n keytab.ifPresent(file -> options.put(\"keyTab\", file.getAbsolutePath()));\n credentialCache.ifPresent(file -> {\n options.put(\"ticketCache\", file.getAbsolutePath());\n options.put(\"renewTGT\", \"true\");\n });\n if (!keytab.isPresent() || credentialCache.isPresent()) {\n options.put(\"useTicketCache\", \"true\");\n }\n principal.ifPresent(value -> options.put(\"principal\", value));\n return new AppConfigurationEntry[] {\n new AppConfigurationEntry(Krb5LoginModule.class.getName(), REQUIRED, options.buildOrThrow())\n };\n }\n });\n loginContext.login();\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n public void refresh()\n throws LoginException, GSSException\n {\n \n loginContext = new LoginContext(\"\", null, null, new Configuration()\n {\n @Override\n public AppConfigurationEntry[] getAppConfigurationEntry(String name)\n {\n ImmutableMap.Builder options = ImmutableMap.builder();\n options.put(\"refreshKrb5Config\", \"true\");\n options.put(\"doNotPrompt\", \"true\");\n options.put(\"useKeyTab\", \"true\");\n if (getBoolean(\"trino.client.debugKerberos\")) {\n options.put(\"debug\", \"true\");\n }\n keytab.ifPresent(file -> options.put(\"keyTab\", file.getAbsolutePath()));\n credentialCache.ifPresent(file -> {\n options.put(\"ticketCache\", file.getAbsolutePath());\n options.put(\"renewTGT\", \"true\");\n });\n if (!keytab.isPresent() || credentialCache.isPresent()) {\n options.put(\"useTicketCache\", \"true\");\n }\n principal.ifPresent(value -> options.put(\"principal\", value));\n return new AppConfigurationEntry[] {\n new AppConfigurationEntry(Krb5LoginModule.class.getName(), REQUIRED, options.buildOrThrow())\n };\n }\n });\n loginContext.login();\n }"},"cleancode":{"kind":"string","value":"@override public void refresh() throws loginexception, gssexception { logincontext = new logincontext(\"\", null, null, new configuration() { @override public appconfigurationentry[] getappconfigurationentry(string name) { immutablemap.builder options = immutablemap.builder(); options.put(\"refreshkrb5config\", \"true\"); options.put(\"donotprompt\", \"true\"); options.put(\"usekeytab\", \"true\"); if (getboolean(\"trino.client.debugkerberos\")) { options.put(\"debug\", \"true\"); } keytab.ifpresent(file -> options.put(\"keytab\", file.getabsolutepath())); credentialcache.ifpresent(file -> { options.put(\"ticketcache\", file.getabsolutepath()); options.put(\"renewtgt\", \"true\"); }); if (!keytab.ispresent() || credentialcache.ispresent()) { options.put(\"useticketcache\", \"true\"); } principal.ifpresent(value -> options.put(\"principal\", value)); return new appconfigurationentry[] { new appconfigurationentry(krb5loginmodule.class.getname(), required, options.buildorthrow()) }; } }); logincontext.login(); }"},"repo":{"kind":"string","value":"SanjayTechGuru/TRINO"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":246,"cells":{"id":{"kind":"number","value":17089,"string":"17,089"},"original_code":{"kind":"string","value":"@Override\n public void reduce(BytesWritable key, Iterable values, Context context)\n throws IOException, InterruptedException {\n int defCount = 0;\n refs.clear();\n // We only expect two values, a DEF and a reference, but there might be more.\n for (BytesWritable type : values) {\n if (type.getLength() == DEF.getLength()) {\n defCount++;\n } else {\n byte[] bytes = new byte[type.getLength()];\n System.arraycopy(type.getBytes(), 0, bytes, 0, type.getLength());\n refs.add(bytes);\n }\n }\n // TODO check for more than one def, should not happen\n List refsList = new ArrayList<>(refs.size());\n String keyString = null;\n if (defCount == 0 || refs.size() != 1) {\n for (byte[] ref : refs) {\n refsList.add(COMMA_JOINER.join(Bytes.getLong(ref), Bytes.getLong(ref, 8)));\n }\n keyString = COMMA_JOINER.join(Bytes.getLong(key.getBytes()),\n Bytes.getLong(key.getBytes(), 8));\n LOG.error(\"Linked List error: Key = \" + keyString + \" References = \" + refsList);\n }\n if (defCount == 0 && refs.size() > 0) {\n // this is bad, found a node that is referenced but not defined. It must have been\n // lost, emit some info about this node for debugging purposes.\n context.write(new Text(keyString), new Text(refsList.toString()));\n context.getCounter(Counts.UNDEFINED).increment(1);\n } else if (defCount > 0 && refs.size() == 0) {\n // node is defined but not referenced\n context.write(new Text(keyString), new Text(\"none\"));\n context.getCounter(Counts.UNREFERENCED).increment(1);\n } else {\n if (refs.size() > 1) {\n if (refsList != null) {\n context.write(new Text(keyString), new Text(refsList.toString()));\n }\n context.getCounter(Counts.EXTRAREFERENCES).increment(refs.size() - 1);\n }\n // node is defined and referenced\n context.getCounter(Counts.REFERENCED).increment(1);\n }\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n public void reduce(BytesWritable key, Iterable values, Context context)\n throws IOException, InterruptedException {\n int defCount = 0;\n refs.clear();\n \n for (BytesWritable type : values) {\n if (type.getLength() == DEF.getLength()) {\n defCount++;\n } else {\n byte[] bytes = new byte[type.getLength()];\n System.arraycopy(type.getBytes(), 0, bytes, 0, type.getLength());\n refs.add(bytes);\n }\n }\n \n List refsList = new ArrayList<>(refs.size());\n String keyString = null;\n if (defCount == 0 || refs.size() != 1) {\n for (byte[] ref : refs) {\n refsList.add(COMMA_JOINER.join(Bytes.getLong(ref), Bytes.getLong(ref, 8)));\n }\n keyString = COMMA_JOINER.join(Bytes.getLong(key.getBytes()),\n Bytes.getLong(key.getBytes(), 8));\n LOG.error(\"Linked List error: Key = \" + keyString + \" References = \" + refsList);\n }\n if (defCount == 0 && refs.size() > 0) {\n \n \n context.write(new Text(keyString), new Text(refsList.toString()));\n context.getCounter(Counts.UNDEFINED).increment(1);\n } else if (defCount > 0 && refs.size() == 0) {\n \n context.write(new Text(keyString), new Text(\"none\"));\n context.getCounter(Counts.UNREFERENCED).increment(1);\n } else {\n if (refs.size() > 1) {\n if (refsList != null) {\n context.write(new Text(keyString), new Text(refsList.toString()));\n }\n context.getCounter(Counts.EXTRAREFERENCES).increment(refs.size() - 1);\n }\n \n context.getCounter(Counts.REFERENCED).increment(1);\n }\n }"},"cleancode":{"kind":"string","value":"@override public void reduce(byteswritable key, iterable values, context context) throws ioexception, interruptedexception { int defcount = 0; refs.clear(); for (byteswritable type : values) { if (type.getlength() == def.getlength()) { defcount++; } else { byte[] bytes = new byte[type.getlength()]; system.arraycopy(type.getbytes(), 0, bytes, 0, type.getlength()); refs.add(bytes); } } list refslist = new arraylist<>(refs.size()); string keystring = null; if (defcount == 0 || refs.size() != 1) { for (byte[] ref : refs) { refslist.add(comma_joiner.join(bytes.getlong(ref), bytes.getlong(ref, 8))); } keystring = comma_joiner.join(bytes.getlong(key.getbytes()), bytes.getlong(key.getbytes(), 8)); log.error(\"linked list error: key = \" + keystring + \" references = \" + refslist); } if (defcount == 0 && refs.size() > 0) { context.write(new text(keystring), new text(refslist.tostring())); context.getcounter(counts.undefined).increment(1); } else if (defcount > 0 && refs.size() == 0) { context.write(new text(keystring), new text(\"none\")); context.getcounter(counts.unreferenced).increment(1); } else { if (refs.size() > 1) { if (refslist != null) { context.write(new text(keystring), new text(refslist.tostring())); } context.getcounter(counts.extrareferences).increment(refs.size() - 1); } context.getcounter(counts.referenced).increment(1); } }"},"repo":{"kind":"string","value":"YCjia/kudu"},"label":{"kind":"list like","value":[1,1,0,0],"string":"[\n 1,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":247,"cells":{"id":{"kind":"number","value":748,"string":"748"},"original_code":{"kind":"string","value":"public boolean addNewTodo(Request req, Response res)\n {\n res.type(\"application/json\");\n Object o = JSON.parse(req.body());\n try {\n if(o.getClass().equals(BasicDBObject.class))\n {\n try {\n BasicDBObject dbO = (BasicDBObject) o;\n String owner = dbO.getString(\"owner\");\n //For some reason age is a string right now, caused by angular.\n //This is a problem and should not be this way but here ya go\n boolean status = dbO.getBoolean(\"status\");\n String body = dbO.getString(\"body\");\n String category = dbO.getString(\"category\");\n System.err.println(\"Adding new todo [owner=\" + owner + \", category=\" + category + \" body=\" + body + \" status=\" + status + ']');\n return todoController.addNewTodo(owner, category, body, status);\n }\n catch(NullPointerException e)\n {\n System.err.println(\"A value was malformed or omitted, new todo request failed.\");\n return false;\n }\n }\n else\n {\n System.err.println(\"Expected BasicDBObject, received \" + o.getClass());\n return false;\n }\n }\n catch(RuntimeException ree)\n {\n ree.printStackTrace();\n return false;\n }\n }"},"code_wo_comment":{"kind":"string","value":"public boolean addNewTodo(Request req, Response res)\n {\n res.type(\"application/json\");\n Object o = JSON.parse(req.body());\n try {\n if(o.getClass().equals(BasicDBObject.class))\n {\n try {\n BasicDBObject dbO = (BasicDBObject) o;\n String owner = dbO.getString(\"owner\");\n \n \n boolean status = dbO.getBoolean(\"status\");\n String body = dbO.getString(\"body\");\n String category = dbO.getString(\"category\");\n System.err.println(\"Adding new todo [owner=\" + owner + \", category=\" + category + \" body=\" + body + \" status=\" + status + ']');\n return todoController.addNewTodo(owner, category, body, status);\n }\n catch(NullPointerException e)\n {\n System.err.println(\"A value was malformed or omitted, new todo request failed.\");\n return false;\n }\n }\n else\n {\n System.err.println(\"Expected BasicDBObject, received \" + o.getClass());\n return false;\n }\n }\n catch(RuntimeException ree)\n {\n ree.printStackTrace();\n return false;\n }\n }"},"cleancode":{"kind":"string","value":"public boolean addnewtodo(request req, response res) { res.type(\"application/json\"); object o = json.parse(req.body()); try { if(o.getclass().equals(basicdbobject.class)) { try { basicdbobject dbo = (basicdbobject) o; string owner = dbo.getstring(\"owner\"); boolean status = dbo.getboolean(\"status\"); string body = dbo.getstring(\"body\"); string category = dbo.getstring(\"category\"); system.err.println(\"adding new todo [owner=\" + owner + \", category=\" + category + \" body=\" + body + \" status=\" + status + ']'); return todocontroller.addnewtodo(owner, category, body, status); } catch(nullpointerexception e) { system.err.println(\"a value was malformed or omitted, new todo request failed.\"); return false; } } else { system.err.println(\"expected basicdbobject, received \" + o.getclass()); return false; } } catch(runtimeexception ree) { ree.printstacktrace(); return false; } }"},"repo":{"kind":"string","value":"UMM-CSci-3601-S18/lab-4-mongo-voyageurs-national-park"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":248,"cells":{"id":{"kind":"number","value":25329,"string":"25,329"},"original_code":{"kind":"string","value":"public void shutdown() {\n\t\t try {\n\t\t\t\tLOGGER.info(\"Shutting down listener on \" + host + \":\" + port);\n\t\t\t\trunning.set(false);\n\t\t\t\t// This isn't good, the Jedis object is not thread safe\n\t\t\t\tjedis.disconnect();\n\t\t } catch (Exception e) {\n\t\t \tLOGGER.error(\"Caught exception while shutting down: \" + e.getMessage());\n\t\t }\n\t\t}"},"code_wo_comment":{"kind":"string","value":"public void shutdown() {\n\t\t try {\n\t\t\t\tLOGGER.info(\"Shutting down listener on \" + host + \":\" + port);\n\t\t\t\trunning.set(false);\n\t\t\t\n\t\t\t\tjedis.disconnect();\n\t\t } catch (Exception e) {\n\t\t \tLOGGER.error(\"Caught exception while shutting down: \" + e.getMessage());\n\t\t }\n\t\t}"},"cleancode":{"kind":"string","value":"public void shutdown() { try { logger.info(\"shutting down listener on \" + host + \":\" + port); running.set(false); jedis.disconnect(); } catch (exception e) { logger.error(\"caught exception while shutting down: \" + e.getmessage()); } }"},"repo":{"kind":"string","value":"Samsung/Spark-CEP"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":249,"cells":{"id":{"kind":"number","value":17260,"string":"17,260"},"original_code":{"kind":"string","value":"public int getLineForVertical(int vertical) {\n int high = getLineCount(), low = -1, guess;\n while (high - low > 1) {\n guess = (high + low) / 2;\n if (getLineTop(guess) > vertical)\n high = guess;\n else\n low = guess;\n }\n if (low < 0)\n return 0;\n else\n return low;\n }"},"code_wo_comment":{"kind":"string","value":"public int getLineForVertical(int vertical) {\n int high = getLineCount(), low = -1, guess;\n while (high - low > 1) {\n guess = (high + low) / 2;\n if (getLineTop(guess) > vertical)\n high = guess;\n else\n low = guess;\n }\n if (low < 0)\n return 0;\n else\n return low;\n }"},"cleancode":{"kind":"string","value":"public int getlineforvertical(int vertical) { int high = getlinecount(), low = -1, guess; while (high - low > 1) { guess = (high + low) / 2; if (getlinetop(guess) > vertical) high = guess; else low = guess; } if (low < 0) return 0; else return low; }"},"repo":{"kind":"string","value":"VPeruS/JotaTextEditor"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":250,"cells":{"id":{"kind":"number","value":9218,"string":"9,218"},"original_code":{"kind":"string","value":"@Override\n public void visitElement(PsiElement element) {\n if (this.context.skip(element)) {\n return;\n }\n // TODO: the refactor\n this.holder.registerProblem(element, this.context.getMessage());\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n public void visitElement(PsiElement element) {\n if (this.context.skip(element)) {\n return;\n }\n \n this.holder.registerProblem(element, this.context.getMessage());\n }"},"cleancode":{"kind":"string","value":"@override public void visitelement(psielement element) { if (this.context.skip(element)) { return; } this.holder.registerproblem(element, this.context.getmessage()); }"},"repo":{"kind":"string","value":"aarthibl/intellibot"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":251,"cells":{"id":{"kind":"number","value":9220,"string":"9,220"},"original_code":{"kind":"string","value":"private static ConfigurationOptions defaultOptions() {\n return ConfigurationOptions.defaults()\n .serializers(SpongeCommon.game().configManager().serializers());\n }"},"code_wo_comment":{"kind":"string","value":"private static ConfigurationOptions defaultOptions() {\n return ConfigurationOptions.defaults()\n .serializers(SpongeCommon.game().configManager().serializers());\n }"},"cleancode":{"kind":"string","value":"private static configurationoptions defaultoptions() { return configurationoptions.defaults() .serializers(spongecommon.game().configmanager().serializers()); }"},"repo":{"kind":"string","value":"SpongePowered/Common"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":252,"cells":{"id":{"kind":"number","value":25606,"string":"25,606"},"original_code":{"kind":"string","value":"@Test\n\tpublic void testRetrieveUserByName() {\n\t\tem.getTransaction().begin();\n\t\tem.createNativeQuery(\"INSERT INTO t_users( user_id, name, date_added, description)\"\n\t\t\t\t+ \" VALUES (1, 'BOOM1', '1988-09-15', 'TEST USER1');\").executeUpdate();\n\t\tem.createNativeQuery(\"INSERT INTO t_users( user_id, name, date_added, description)\"\n\t\t\t\t+ \" VALUES (2, 'BOOM2', '1988-09-15', 'TEST USER2');\").executeUpdate();\n\t\tem.createNativeQuery(\"INSERT INTO t_users( user_id, name, date_added, description)\"\n\t\t\t\t+ \" VALUES (3, 'BOOM3', '1988-09-15', 'TEST USER3');\").executeUpdate();\n\t\tem.getTransaction().commit();\n\t\tList users = null;\n\t\ttry {\n\t\t\t//TODO use .equals() once we ahve overridden appropriate methods\n\t\t\tusers = dao.getUsers();\n\t\t} catch (Throwable th){\n\t\t\tfail(th.getMessage());\n\t\t}\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.set(1988, Calendar.SEPTEMBER, 15, 0, 0, 0);\n\t\tassertEquals(3, users.size());\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tassertEquals(\"BOOM\" + users.get(i).getId(), users.get(i).getName());\n\t\t\tassertEquals(\"TEST USER\" + users.get(i).getId(), users.get(i).getDescription());\n\t\t\tassertEquals(cal.getTime().toString(), users.get(i).getDate().toString());\n\t\t}\n\t}"},"code_wo_comment":{"kind":"string","value":"@Test\n\tpublic void testRetrieveUserByName() {\n\t\tem.getTransaction().begin();\n\t\tem.createNativeQuery(\"INSERT INTO t_users( user_id, name, date_added, description)\"\n\t\t\t\t+ \" VALUES (1, 'BOOM1', '1988-09-15', 'TEST USER1');\").executeUpdate();\n\t\tem.createNativeQuery(\"INSERT INTO t_users( user_id, name, date_added, description)\"\n\t\t\t\t+ \" VALUES (2, 'BOOM2', '1988-09-15', 'TEST USER2');\").executeUpdate();\n\t\tem.createNativeQuery(\"INSERT INTO t_users( user_id, name, date_added, description)\"\n\t\t\t\t+ \" VALUES (3, 'BOOM3', '1988-09-15', 'TEST USER3');\").executeUpdate();\n\t\tem.getTransaction().commit();\n\t\tList users = null;\n\t\ttry {\n\t\t\n\t\t\tusers = dao.getUsers();\n\t\t} catch (Throwable th){\n\t\t\tfail(th.getMessage());\n\t\t}\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.set(1988, Calendar.SEPTEMBER, 15, 0, 0, 0);\n\t\tassertEquals(3, users.size());\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tassertEquals(\"BOOM\" + users.get(i).getId(), users.get(i).getName());\n\t\t\tassertEquals(\"TEST USER\" + users.get(i).getId(), users.get(i).getDescription());\n\t\t\tassertEquals(cal.getTime().toString(), users.get(i).getDate().toString());\n\t\t}\n\t}"},"cleancode":{"kind":"string","value":"@test public void testretrieveuserbyname() { em.gettransaction().begin(); em.createnativequery(\"insert into t_users( user_id, name, date_added, description)\" + \" values (1, 'boom1', '1988-09-15', 'test user1');\").executeupdate(); em.createnativequery(\"insert into t_users( user_id, name, date_added, description)\" + \" values (2, 'boom2', '1988-09-15', 'test user2');\").executeupdate(); em.createnativequery(\"insert into t_users( user_id, name, date_added, description)\" + \" values (3, 'boom3', '1988-09-15', 'test user3');\").executeupdate(); em.gettransaction().commit(); list users = null; try { users = dao.getusers(); } catch (throwable th){ fail(th.getmessage()); } calendar cal = calendar.getinstance(); cal.set(1988, calendar.september, 15, 0, 0, 0); assertequals(3, users.size()); for (int i = 0; i < 3; i++) { assertequals(\"boom\" + users.get(i).getid(), users.get(i).getname()); assertequals(\"test user\" + users.get(i).getid(), users.get(i).getdescription()); assertequals(cal.gettime().tostring(), users.get(i).getdate().tostring()); } }"},"repo":{"kind":"string","value":"andrewflbarnes/debt-tracker"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":253,"cells":{"id":{"kind":"number","value":1134,"string":"1,134"},"original_code":{"kind":"string","value":"private void restoreKVStateMetaData() throws IOException, StateMigrationException, RocksDBException {\n\t\t\tKeyedBackendSerializationProxy serializationProxy =\n\t\t\t\t\tnew KeyedBackendSerializationProxy<>(rocksDBKeyedStateBackend.userCodeClassLoader);\n\t\t\tserializationProxy.read(currentStateHandleInView);\n\t\t\t// check for key serializer compatibility; this also reconfigures the\n\t\t\t// key serializer to be compatible, if it is required and is possible\n\t\t\tif (CompatibilityUtil.resolveCompatibilityResult(\n\t\t\t\t\tserializationProxy.getKeySerializer(),\n\t\t\t\t\tUnloadableDummyTypeSerializer.class,\n\t\t\t\t\tserializationProxy.getKeySerializerConfigSnapshot(),\n\t\t\t\t\trocksDBKeyedStateBackend.keySerializer)\n\t\t\t\t.isRequiresMigration()) {\n\t\t\t\t// TODO replace with state migration; note that key hash codes need to remain the same after migration\n\t\t\t\tthrow new StateMigrationException(\"The new key serializer is not compatible to read previous keys. \" +\n\t\t\t\t\t\"Aborting now since state migration is currently not available\");\n\t\t\t}\n\t\t\tthis.keygroupStreamCompressionDecorator = serializationProxy.isUsingKeyGroupCompression() ?\n\t\t\t\tSnappyStreamCompressionDecorator.INSTANCE : UncompressedStreamCompressionDecorator.INSTANCE;\n\t\t\tList> restoredMetaInfos =\n\t\t\t\t\tserializationProxy.getStateMetaInfoSnapshots();\n\t\t\tcurrentStateHandleKVStateColumnFamilies = new ArrayList<>(restoredMetaInfos.size());\n\t\t\t//rocksDBKeyedStateBackend.restoredKvStateMetaInfos = new HashMap<>(restoredMetaInfos.size());\n\t\t\tfor (RegisteredKeyedBackendStateMetaInfo.Snapshot restoredMetaInfo : restoredMetaInfos) {\n\t\t\t\tTuple2> registeredColumn =\n\t\t\t\t\trocksDBKeyedStateBackend.kvStateInformation.get(restoredMetaInfo.getName());\n\t\t\t\tif (registeredColumn == null) {\n\t\t\t\t\tColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(\n\t\t\t\t\t\trestoredMetaInfo.getName().getBytes(ConfigConstants.DEFAULT_CHARSET),\n\t\t\t\t\t\trocksDBKeyedStateBackend.columnOptions);\n\t\t\t\t\tRegisteredKeyedBackendStateMetaInfo stateMetaInfo =\n\t\t\t\t\t\t\tnew RegisteredKeyedBackendStateMetaInfo<>(\n\t\t\t\t\t\t\t\trestoredMetaInfo.getStateType(),\n\t\t\t\t\t\t\t\trestoredMetaInfo.getName(),\n\t\t\t\t\t\t\t\trestoredMetaInfo.getNamespaceSerializer(),\n\t\t\t\t\t\t\t\trestoredMetaInfo.getStateSerializer());\n\t\t\t\t\trocksDBKeyedStateBackend.restoredKvStateMetaInfos.put(restoredMetaInfo.getName(), restoredMetaInfo);\n\t\t\t\t\tColumnFamilyHandle columnFamily = rocksDBKeyedStateBackend.db.createColumnFamily(columnFamilyDescriptor);\n\t\t\t\t\tregisteredColumn = new Tuple2>(columnFamily, stateMetaInfo);\n\t\t\t\t\trocksDBKeyedStateBackend.kvStateInformation.put(stateMetaInfo.getName(), registeredColumn);\n\t\t\t\t} else {\n\t\t\t\t\t// TODO with eager state registration in place, check here for serializer migration strategies\n\t\t\t\t}\n\t\t\t\tcurrentStateHandleKVStateColumnFamilies.add(registeredColumn.f0);\n\t\t\t}\n\t\t}"},"code_wo_comment":{"kind":"string","value":"private void restoreKVStateMetaData() throws IOException, StateMigrationException, RocksDBException {\n\t\t\tKeyedBackendSerializationProxy serializationProxy =\n\t\t\t\t\tnew KeyedBackendSerializationProxy<>(rocksDBKeyedStateBackend.userCodeClassLoader);\n\t\t\tserializationProxy.read(currentStateHandleInView);\n\t\t\n\t\t\n\t\t\tif (CompatibilityUtil.resolveCompatibilityResult(\n\t\t\t\t\tserializationProxy.getKeySerializer(),\n\t\t\t\t\tUnloadableDummyTypeSerializer.class,\n\t\t\t\t\tserializationProxy.getKeySerializerConfigSnapshot(),\n\t\t\t\t\trocksDBKeyedStateBackend.keySerializer)\n\t\t\t\t.isRequiresMigration()) {\n\t\t\t\n\t\t\t\tthrow new StateMigrationException(\"The new key serializer is not compatible to read previous keys. \" +\n\t\t\t\t\t\"Aborting now since state migration is currently not available\");\n\t\t\t}\n\t\t\tthis.keygroupStreamCompressionDecorator = serializationProxy.isUsingKeyGroupCompression() ?\n\t\t\t\tSnappyStreamCompressionDecorator.INSTANCE : UncompressedStreamCompressionDecorator.INSTANCE;\n\t\t\tList> restoredMetaInfos =\n\t\t\t\t\tserializationProxy.getStateMetaInfoSnapshots();\n\t\t\tcurrentStateHandleKVStateColumnFamilies = new ArrayList<>(restoredMetaInfos.size());\n\t\t\n\t\t\tfor (RegisteredKeyedBackendStateMetaInfo.Snapshot restoredMetaInfo : restoredMetaInfos) {\n\t\t\t\tTuple2> registeredColumn =\n\t\t\t\t\trocksDBKeyedStateBackend.kvStateInformation.get(restoredMetaInfo.getName());\n\t\t\t\tif (registeredColumn == null) {\n\t\t\t\t\tColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(\n\t\t\t\t\t\trestoredMetaInfo.getName().getBytes(ConfigConstants.DEFAULT_CHARSET),\n\t\t\t\t\t\trocksDBKeyedStateBackend.columnOptions);\n\t\t\t\t\tRegisteredKeyedBackendStateMetaInfo stateMetaInfo =\n\t\t\t\t\t\t\tnew RegisteredKeyedBackendStateMetaInfo<>(\n\t\t\t\t\t\t\t\trestoredMetaInfo.getStateType(),\n\t\t\t\t\t\t\t\trestoredMetaInfo.getName(),\n\t\t\t\t\t\t\t\trestoredMetaInfo.getNamespaceSerializer(),\n\t\t\t\t\t\t\t\trestoredMetaInfo.getStateSerializer());\n\t\t\t\t\trocksDBKeyedStateBackend.restoredKvStateMetaInfos.put(restoredMetaInfo.getName(), restoredMetaInfo);\n\t\t\t\t\tColumnFamilyHandle columnFamily = rocksDBKeyedStateBackend.db.createColumnFamily(columnFamilyDescriptor);\n\t\t\t\t\tregisteredColumn = new Tuple2>(columnFamily, stateMetaInfo);\n\t\t\t\t\trocksDBKeyedStateBackend.kvStateInformation.put(stateMetaInfo.getName(), registeredColumn);\n\t\t\t\t} else {\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\tcurrentStateHandleKVStateColumnFamilies.add(registeredColumn.f0);\n\t\t\t}\n\t\t}"},"cleancode":{"kind":"string","value":"private void restorekvstatemetadata() throws ioexception, statemigrationexception, rocksdbexception { keyedbackendserializationproxy serializationproxy = new keyedbackendserializationproxy<>(rocksdbkeyedstatebackend.usercodeclassloader); serializationproxy.read(currentstatehandleinview); if (compatibilityutil.resolvecompatibilityresult( serializationproxy.getkeyserializer(), unloadabledummytypeserializer.class, serializationproxy.getkeyserializerconfigsnapshot(), rocksdbkeyedstatebackend.keyserializer) .isrequiresmigration()) { throw new statemigrationexception(\"the new key serializer is not compatible to read previous keys. \" + \"aborting now since state migration is currently not available\"); } this.keygroupstreamcompressiondecorator = serializationproxy.isusingkeygroupcompression() ? snappystreamcompressiondecorator.instance : uncompressedstreamcompressiondecorator.instance; list> restoredmetainfos = serializationproxy.getstatemetainfosnapshots(); currentstatehandlekvstatecolumnfamilies = new arraylist<>(restoredmetainfos.size()); for (registeredkeyedbackendstatemetainfo.snapshot restoredmetainfo : restoredmetainfos) { tuple2> registeredcolumn = rocksdbkeyedstatebackend.kvstateinformation.get(restoredmetainfo.getname()); if (registeredcolumn == null) { columnfamilydescriptor columnfamilydescriptor = new columnfamilydescriptor( restoredmetainfo.getname().getbytes(configconstants.default_charset), rocksdbkeyedstatebackend.columnoptions); registeredkeyedbackendstatemetainfo statemetainfo = new registeredkeyedbackendstatemetainfo<>( restoredmetainfo.getstatetype(), restoredmetainfo.getname(), restoredmetainfo.getnamespaceserializer(), restoredmetainfo.getstateserializer()); rocksdbkeyedstatebackend.restoredkvstatemetainfos.put(restoredmetainfo.getname(), restoredmetainfo); columnfamilyhandle columnfamily = rocksdbkeyedstatebackend.db.createcolumnfamily(columnfamilydescriptor); registeredcolumn = new tuple2>(columnfamily, statemetainfo); rocksdbkeyedstatebackend.kvstateinformation.put(statemetainfo.getname(), registeredcolumn); } else { } currentstatehandlekvstatecolumnfamilies.add(registeredcolumn.f0); } }"},"repo":{"kind":"string","value":"alpinegizmo/flink"},"label":{"kind":"list like","value":[1,1,0,0],"string":"[\n 1,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":254,"cells":{"id":{"kind":"number","value":1136,"string":"1,136"},"original_code":{"kind":"string","value":"private List> readMetaData(\n\t\t\t\tStreamStateHandle metaStateHandle) throws Exception {\n\t\t\tFSDataInputStream inputStream = null;\n\t\t\ttry {\n\t\t\t\tinputStream = metaStateHandle.openInputStream();\n\t\t\t\tstateBackend.cancelStreamRegistry.registerClosable(inputStream);\n\t\t\t\tKeyedBackendSerializationProxy serializationProxy =\n\t\t\t\t\tnew KeyedBackendSerializationProxy<>(stateBackend.userCodeClassLoader);\n\t\t\t\tDataInputView in = new DataInputViewStreamWrapper(inputStream);\n\t\t\t\tserializationProxy.read(in);\n\t\t\t\t// check for key serializer compatibility; this also reconfigures the\n\t\t\t\t// key serializer to be compatible, if it is required and is possible\n\t\t\t\tif (CompatibilityUtil.resolveCompatibilityResult(\n\t\t\t\t\t\tserializationProxy.getKeySerializer(),\n\t\t\t\t\t\tUnloadableDummyTypeSerializer.class,\n\t\t\t\t\t\tserializationProxy.getKeySerializerConfigSnapshot(),\n\t\t\t\t\t\tstateBackend.keySerializer)\n\t\t\t\t\t.isRequiresMigration()) {\n\t\t\t\t\t// TODO replace with state migration; note that key hash codes need to remain the same after migration\n\t\t\t\t\tthrow new StateMigrationException(\"The new key serializer is not compatible to read previous keys. \" +\n\t\t\t\t\t\t\"Aborting now since state migration is currently not available\");\n\t\t\t\t}\n\t\t\t\treturn serializationProxy.getStateMetaInfoSnapshots();\n\t\t\t} finally {\n\t\t\t\tif (inputStream != null) {\n\t\t\t\t\tstateBackend.cancelStreamRegistry.unregisterClosable(inputStream);\n\t\t\t\t\tinputStream.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}"},"code_wo_comment":{"kind":"string","value":"private List> readMetaData(\n\t\t\t\tStreamStateHandle metaStateHandle) throws Exception {\n\t\t\tFSDataInputStream inputStream = null;\n\t\t\ttry {\n\t\t\t\tinputStream = metaStateHandle.openInputStream();\n\t\t\t\tstateBackend.cancelStreamRegistry.registerClosable(inputStream);\n\t\t\t\tKeyedBackendSerializationProxy serializationProxy =\n\t\t\t\t\tnew KeyedBackendSerializationProxy<>(stateBackend.userCodeClassLoader);\n\t\t\t\tDataInputView in = new DataInputViewStreamWrapper(inputStream);\n\t\t\t\tserializationProxy.read(in);\n\t\t\t\n\t\t\t\n\t\t\t\tif (CompatibilityUtil.resolveCompatibilityResult(\n\t\t\t\t\t\tserializationProxy.getKeySerializer(),\n\t\t\t\t\t\tUnloadableDummyTypeSerializer.class,\n\t\t\t\t\t\tserializationProxy.getKeySerializerConfigSnapshot(),\n\t\t\t\t\t\tstateBackend.keySerializer)\n\t\t\t\t\t.isRequiresMigration()) {\n\t\t\t\t\n\t\t\t\t\tthrow new StateMigrationException(\"The new key serializer is not compatible to read previous keys. \" +\n\t\t\t\t\t\t\"Aborting now since state migration is currently not available\");\n\t\t\t\t}\n\t\t\t\treturn serializationProxy.getStateMetaInfoSnapshots();\n\t\t\t} finally {\n\t\t\t\tif (inputStream != null) {\n\t\t\t\t\tstateBackend.cancelStreamRegistry.unregisterClosable(inputStream);\n\t\t\t\t\tinputStream.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}"},"cleancode":{"kind":"string","value":"private list> readmetadata( streamstatehandle metastatehandle) throws exception { fsdatainputstream inputstream = null; try { inputstream = metastatehandle.openinputstream(); statebackend.cancelstreamregistry.registerclosable(inputstream); keyedbackendserializationproxy serializationproxy = new keyedbackendserializationproxy<>(statebackend.usercodeclassloader); datainputview in = new datainputviewstreamwrapper(inputstream); serializationproxy.read(in); if (compatibilityutil.resolvecompatibilityresult( serializationproxy.getkeyserializer(), unloadabledummytypeserializer.class, serializationproxy.getkeyserializerconfigsnapshot(), statebackend.keyserializer) .isrequiresmigration()) { throw new statemigrationexception(\"the new key serializer is not compatible to read previous keys. \" + \"aborting now since state migration is currently not available\"); } return serializationproxy.getstatemetainfosnapshots(); } finally { if (inputstream != null) { statebackend.cancelstreamregistry.unregisterclosable(inputstream); inputstream.close(); } } }"},"repo":{"kind":"string","value":"alpinegizmo/flink"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":255,"cells":{"id":{"kind":"number","value":25762,"string":"25,762"},"original_code":{"kind":"string","value":"@Test\n public void testCreateDbAndTable() throws Exception {\n // 1. create connect context\n ConnectContext ctx = UtFrameUtils.createDefaultCtx();\n // 2. create database db1\n String createDbStmtStr = \"create database db1;\";\n CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseAndAnalyzeStmt(createDbStmtStr, ctx);\n Catalog.getCurrentCatalog().createDb(createDbStmt);\n System.out.println(Catalog.getCurrentCatalog().getDbNames());\n // 3. create table tbl1\n String createTblStmtStr = \"create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3',\" +\n \"'colocate_with' = 'g1');\";\n CreateTableStmt createTableStmt = (CreateTableStmt) UtFrameUtils.parseAndAnalyzeStmt(createTblStmtStr, ctx);\n Catalog.getCurrentCatalog().createTable(createTableStmt);\n // must set replicas' path hash, or the tablet scheduler won't work\n updateReplicaPathHash();\n // 4. get and test the created db and table\n Database db = Catalog.getCurrentCatalog().getDbNullable(\"default_cluster:db1\");\n Assert.assertNotNull(db);\n OlapTable tbl = (OlapTable) db.getTableNullable(\"tbl1\");\n tbl.readLock();\n try {\n Assert.assertNotNull(tbl);\n System.out.println(tbl.getName());\n Assert.assertEquals(\"Doris\", tbl.getEngine());\n Assert.assertEquals(1, tbl.getBaseSchema().size());\n } finally {\n tbl.readUnlock();\n }\n // 5. process a schema change job\n String alterStmtStr = \"alter table db1.tbl1 add column k2 int default '1'\";\n AlterTableStmt alterTableStmt = (AlterTableStmt) UtFrameUtils.parseAndAnalyzeStmt(alterStmtStr, ctx);\n Catalog.getCurrentCatalog().getAlterInstance().processAlterTable(alterTableStmt);\n // 6. check alter job\n Map alterJobs = Catalog.getCurrentCatalog().getSchemaChangeHandler().getAlterJobsV2();\n Assert.assertEquals(1, alterJobs.size());\n for (AlterJobV2 alterJobV2 : alterJobs.values()) {\n while (!alterJobV2.getJobState().isFinalState()) {\n System.out.println(\"alter job \" + alterJobV2.getJobId() + \" is running. state: \" + alterJobV2.getJobState());\n Thread.sleep(1000);\n }\n System.out.println(\"alter job \" + alterJobV2.getJobId() + \" is done. state: \" + alterJobV2.getJobState());\n Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState());\n }\n OlapTable tbl1 = (OlapTable) db.getTableNullable(\"tbl1\");\n tbl1.readLock();\n try {\n Assert.assertEquals(2, tbl1.getBaseSchema().size());\n String baseIndexName = tbl1.getIndexNameById(tbl.getBaseIndexId());\n Assert.assertEquals(baseIndexName, tbl1.getName());\n MaterializedIndexMeta indexMeta = tbl1.getIndexMetaByIndexId(tbl1.getBaseIndexId());\n Assert.assertNotNull(indexMeta);\n } finally {\n tbl1.readUnlock();\n }\n // 7. query\n // TODO: we can not process real query for now. So it has to be a explain query\n String queryStr = \"explain select * from db1.tbl1\";\n String a = UtFrameUtils.getSQLPlanOrErrorMsg(ctx, queryStr);\n System.out.println(a);\n StmtExecutor stmtExecutor = new StmtExecutor(ctx, queryStr);\n stmtExecutor.execute();\n Planner planner = stmtExecutor.planner();\n List fragments = planner.getFragments();\n Assert.assertEquals(2, fragments.size());\n PlanFragment fragment = fragments.get(1);\n Assert.assertTrue(fragment.getPlanRoot() instanceof OlapScanNode);\n Assert.assertEquals(0, fragment.getChildren().size());\n // test show backends;\n BackendsProcDir dir = new BackendsProcDir(Catalog.getCurrentSystemInfo());\n ProcResult result = dir.fetchResult();\n Assert.assertEquals(BackendsProcDir.TITLE_NAMES.size(), result.getColumnNames().size());\n Assert.assertEquals(\"{\\\"location\\\" : \\\"default\\\"}\", result.getRows().get(0).get(19));\n Assert.assertEquals(\"{\\\"lastSuccessReportTabletsTime\\\":\\\"N/A\\\",\\\"lastStreamLoadTime\\\":-1}\",\n result.getRows().get(0).get(BackendsProcDir.TITLE_NAMES.size() - 1));\n }"},"code_wo_comment":{"kind":"string","value":"@Test\n public void testCreateDbAndTable() throws Exception {\n \n ConnectContext ctx = UtFrameUtils.createDefaultCtx();\n \n String createDbStmtStr = \"create database db1;\";\n CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseAndAnalyzeStmt(createDbStmtStr, ctx);\n Catalog.getCurrentCatalog().createDb(createDbStmt);\n System.out.println(Catalog.getCurrentCatalog().getDbNames());\n \n String createTblStmtStr = \"create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3',\" +\n \"'colocate_with' = 'g1');\";\n CreateTableStmt createTableStmt = (CreateTableStmt) UtFrameUtils.parseAndAnalyzeStmt(createTblStmtStr, ctx);\n Catalog.getCurrentCatalog().createTable(createTableStmt);\n \n updateReplicaPathHash();\n \n Database db = Catalog.getCurrentCatalog().getDbNullable(\"default_cluster:db1\");\n Assert.assertNotNull(db);\n OlapTable tbl = (OlapTable) db.getTableNullable(\"tbl1\");\n tbl.readLock();\n try {\n Assert.assertNotNull(tbl);\n System.out.println(tbl.getName());\n Assert.assertEquals(\"Doris\", tbl.getEngine());\n Assert.assertEquals(1, tbl.getBaseSchema().size());\n } finally {\n tbl.readUnlock();\n }\n \n String alterStmtStr = \"alter table db1.tbl1 add column k2 int default '1'\";\n AlterTableStmt alterTableStmt = (AlterTableStmt) UtFrameUtils.parseAndAnalyzeStmt(alterStmtStr, ctx);\n Catalog.getCurrentCatalog().getAlterInstance().processAlterTable(alterTableStmt);\n \n Map alterJobs = Catalog.getCurrentCatalog().getSchemaChangeHandler().getAlterJobsV2();\n Assert.assertEquals(1, alterJobs.size());\n for (AlterJobV2 alterJobV2 : alterJobs.values()) {\n while (!alterJobV2.getJobState().isFinalState()) {\n System.out.println(\"alter job \" + alterJobV2.getJobId() + \" is running. state: \" + alterJobV2.getJobState());\n Thread.sleep(1000);\n }\n System.out.println(\"alter job \" + alterJobV2.getJobId() + \" is done. state: \" + alterJobV2.getJobState());\n Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState());\n }\n OlapTable tbl1 = (OlapTable) db.getTableNullable(\"tbl1\");\n tbl1.readLock();\n try {\n Assert.assertEquals(2, tbl1.getBaseSchema().size());\n String baseIndexName = tbl1.getIndexNameById(tbl.getBaseIndexId());\n Assert.assertEquals(baseIndexName, tbl1.getName());\n MaterializedIndexMeta indexMeta = tbl1.getIndexMetaByIndexId(tbl1.getBaseIndexId());\n Assert.assertNotNull(indexMeta);\n } finally {\n tbl1.readUnlock();\n }\n \n \n String queryStr = \"explain select * from db1.tbl1\";\n String a = UtFrameUtils.getSQLPlanOrErrorMsg(ctx, queryStr);\n System.out.println(a);\n StmtExecutor stmtExecutor = new StmtExecutor(ctx, queryStr);\n stmtExecutor.execute();\n Planner planner = stmtExecutor.planner();\n List fragments = planner.getFragments();\n Assert.assertEquals(2, fragments.size());\n PlanFragment fragment = fragments.get(1);\n Assert.assertTrue(fragment.getPlanRoot() instanceof OlapScanNode);\n Assert.assertEquals(0, fragment.getChildren().size());\n \n BackendsProcDir dir = new BackendsProcDir(Catalog.getCurrentSystemInfo());\n ProcResult result = dir.fetchResult();\n Assert.assertEquals(BackendsProcDir.TITLE_NAMES.size(), result.getColumnNames().size());\n Assert.assertEquals(\"{\\\"location\\\" : \\\"default\\\"}\", result.getRows().get(0).get(19));\n Assert.assertEquals(\"{\\\"lastSuccessReportTabletsTime\\\":\\\"N/A\\\",\\\"lastStreamLoadTime\\\":-1}\",\n result.getRows().get(0).get(BackendsProcDir.TITLE_NAMES.size() - 1));\n }"},"cleancode":{"kind":"string","value":"@test public void testcreatedbandtable() throws exception { connectcontext ctx = utframeutils.createdefaultctx(); string createdbstmtstr = \"create database db1;\"; createdbstmt createdbstmt = (createdbstmt) utframeutils.parseandanalyzestmt(createdbstmtstr, ctx); catalog.getcurrentcatalog().createdb(createdbstmt); system.out.println(catalog.getcurrentcatalog().getdbnames()); string createtblstmtstr = \"create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3',\" + \"'colocate_with' = 'g1');\"; createtablestmt createtablestmt = (createtablestmt) utframeutils.parseandanalyzestmt(createtblstmtstr, ctx); catalog.getcurrentcatalog().createtable(createtablestmt); updatereplicapathhash(); database db = catalog.getcurrentcatalog().getdbnullable(\"default_cluster:db1\"); assert.assertnotnull(db); olaptable tbl = (olaptable) db.gettablenullable(\"tbl1\"); tbl.readlock(); try { assert.assertnotnull(tbl); system.out.println(tbl.getname()); assert.assertequals(\"doris\", tbl.getengine()); assert.assertequals(1, tbl.getbaseschema().size()); } finally { tbl.readunlock(); } string alterstmtstr = \"alter table db1.tbl1 add column k2 int default '1'\"; altertablestmt altertablestmt = (altertablestmt) utframeutils.parseandanalyzestmt(alterstmtstr, ctx); catalog.getcurrentcatalog().getalterinstance().processaltertable(altertablestmt); map alterjobs = catalog.getcurrentcatalog().getschemachangehandler().getalterjobsv2(); assert.assertequals(1, alterjobs.size()); for (alterjobv2 alterjobv2 : alterjobs.values()) { while (!alterjobv2.getjobstate().isfinalstate()) { system.out.println(\"alter job \" + alterjobv2.getjobid() + \" is running. state: \" + alterjobv2.getjobstate()); thread.sleep(1000); } system.out.println(\"alter job \" + alterjobv2.getjobid() + \" is done. state: \" + alterjobv2.getjobstate()); assert.assertequals(alterjobv2.jobstate.finished, alterjobv2.getjobstate()); } olaptable tbl1 = (olaptable) db.gettablenullable(\"tbl1\"); tbl1.readlock(); try { assert.assertequals(2, tbl1.getbaseschema().size()); string baseindexname = tbl1.getindexnamebyid(tbl.getbaseindexid()); assert.assertequals(baseindexname, tbl1.getname()); materializedindexmeta indexmeta = tbl1.getindexmetabyindexid(tbl1.getbaseindexid()); assert.assertnotnull(indexmeta); } finally { tbl1.readunlock(); } string querystr = \"explain select * from db1.tbl1\"; string a = utframeutils.getsqlplanorerrormsg(ctx, querystr); system.out.println(a); stmtexecutor stmtexecutor = new stmtexecutor(ctx, querystr); stmtexecutor.execute(); planner planner = stmtexecutor.planner(); list fragments = planner.getfragments(); assert.assertequals(2, fragments.size()); planfragment fragment = fragments.get(1); assert.asserttrue(fragment.getplanroot() instanceof olapscannode); assert.assertequals(0, fragment.getchildren().size()); backendsprocdir dir = new backendsprocdir(catalog.getcurrentsysteminfo()); procresult result = dir.fetchresult(); assert.assertequals(backendsprocdir.title_names.size(), result.getcolumnnames().size()); assert.assertequals(\"{\\\"location\\\" : \\\"default\\\"}\", result.getrows().get(0).get(19)); assert.assertequals(\"{\\\"lastsuccessreporttabletstime\\\":\\\"n/a\\\",\\\"laststreamloadtime\\\":-1}\", result.getrows().get(0).get(backendsprocdir.title_names.size() - 1)); }"},"repo":{"kind":"string","value":"WilsonWangCS/incubator-doris"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":256,"cells":{"id":{"kind":"number","value":17588,"string":"17,588"},"original_code":{"kind":"string","value":"private void registerSnapshot () {\n try {\n Statement statement = connection.createStatement();\n // TODO copy over feed_id and feed_version from source namespace?\n // FIXME do the following only on databases that support schemas.\n // SQLite does not support them. Is there any advantage of schemas over flat tables?\n statement.execute(\"create schema \" + tablePrefix);\n // TODO: Record total snapshot processing time?\n // Simply insert into feeds table (no need for table creation) because making a snapshot presumes that the\n // feeds table already exists.\n PreparedStatement insertStatement = connection.prepareStatement(\n \"insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)\");\n insertStatement.setString(1, tablePrefix);\n insertStatement.setString(2, feedIdToSnapshot);\n insertStatement.execute();\n connection.commit();\n LOG.info(\"Created new snapshot namespace: {}\", insertStatement);\n } catch (Exception ex) {\n LOG.error(\"Exception while registering snapshot namespace in feeds table: {}\", ex.getMessage());\n DbUtils.closeQuietly(connection);\n }\n }"},"code_wo_comment":{"kind":"string","value":"private void registerSnapshot () {\n try {\n Statement statement = connection.createStatement();\n \n \n \n statement.execute(\"create schema \" + tablePrefix);\n \n \n \n PreparedStatement insertStatement = connection.prepareStatement(\n \"insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)\");\n insertStatement.setString(1, tablePrefix);\n insertStatement.setString(2, feedIdToSnapshot);\n insertStatement.execute();\n connection.commit();\n LOG.info(\"Created new snapshot namespace: {}\", insertStatement);\n } catch (Exception ex) {\n LOG.error(\"Exception while registering snapshot namespace in feeds table: {}\", ex.getMessage());\n DbUtils.closeQuietly(connection);\n }\n }"},"cleancode":{"kind":"string","value":"private void registersnapshot () { try { statement statement = connection.createstatement(); statement.execute(\"create schema \" + tableprefix); preparedstatement insertstatement = connection.preparestatement( \"insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)\"); insertstatement.setstring(1, tableprefix); insertstatement.setstring(2, feedidtosnapshot); insertstatement.execute(); connection.commit(); log.info(\"created new snapshot namespace: {}\", insertstatement); } catch (exception ex) { log.error(\"exception while registering snapshot namespace in feeds table: {}\", ex.getmessage()); dbutils.closequietly(connection); } }"},"repo":{"kind":"string","value":"Wilhansen/gtfs-lib"},"label":{"kind":"list like","value":[1,1,0,0],"string":"[\n 1,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":257,"cells":{"id":{"kind":"number","value":9474,"string":"9,474"},"original_code":{"kind":"string","value":"@Override\n protected void channelRead0(ChannelHandlerContext ctx,\n CoapMessage msg) {\n try {\n // Find proper device and raise event.\n Device targetDevice = ctx.channel().attr(keyDevice).get();\n if (targetDevice == null) {\n throw new InternalServerErrorException(\n \"Unable to find device\");\n }\n if (msg instanceof CoapRequest) {\n onRequestReceived(targetDevice, (CoapRequest) msg);\n } else if (msg instanceof CoapResponse) {\n // TODO: Re-architecturing required\n IRequestChannel reqChannel = ((CoapDevice) targetDevice)\n .getRequestChannel();\n CoapClient coapClient = (CoapClient) reqChannel;\n coapClient.onResponseReceived(msg);\n }\n } catch (ServerException e) {\n ctx.writeAndFlush(MessageBuilder.createResponse(msg,\n e.getErrorResponse()));\n Log.f(ctx.channel(), e);\n } catch (ClientException e) {\n Log.f(ctx.channel(), e);\n } catch (Throwable t) {\n Log.f(ctx.channel(), t);\n if (msg instanceof CoapRequest) {\n ctx.writeAndFlush(MessageBuilder.createResponse(msg,\n ResponseStatus.INTERNAL_SERVER_ERROR));\n }\n }\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n protected void channelRead0(ChannelHandlerContext ctx,\n CoapMessage msg) {\n try {\n \n Device targetDevice = ctx.channel().attr(keyDevice).get();\n if (targetDevice == null) {\n throw new InternalServerErrorException(\n \"Unable to find device\");\n }\n if (msg instanceof CoapRequest) {\n onRequestReceived(targetDevice, (CoapRequest) msg);\n } else if (msg instanceof CoapResponse) {\n \n IRequestChannel reqChannel = ((CoapDevice) targetDevice)\n .getRequestChannel();\n CoapClient coapClient = (CoapClient) reqChannel;\n coapClient.onResponseReceived(msg);\n }\n } catch (ServerException e) {\n ctx.writeAndFlush(MessageBuilder.createResponse(msg,\n e.getErrorResponse()));\n Log.f(ctx.channel(), e);\n } catch (ClientException e) {\n Log.f(ctx.channel(), e);\n } catch (Throwable t) {\n Log.f(ctx.channel(), t);\n if (msg instanceof CoapRequest) {\n ctx.writeAndFlush(MessageBuilder.createResponse(msg,\n ResponseStatus.INTERNAL_SERVER_ERROR));\n }\n }\n }"},"cleancode":{"kind":"string","value":"@override protected void channelread0(channelhandlercontext ctx, coapmessage msg) { try { device targetdevice = ctx.channel().attr(keydevice).get(); if (targetdevice == null) { throw new internalservererrorexception( \"unable to find device\"); } if (msg instanceof coaprequest) { onrequestreceived(targetdevice, (coaprequest) msg); } else if (msg instanceof coapresponse) { irequestchannel reqchannel = ((coapdevice) targetdevice) .getrequestchannel(); coapclient coapclient = (coapclient) reqchannel; coapclient.onresponsereceived(msg); } } catch (serverexception e) { ctx.writeandflush(messagebuilder.createresponse(msg, e.geterrorresponse())); log.f(ctx.channel(), e); } catch (clientexception e) { log.f(ctx.channel(), e); } catch (throwable t) { log.f(ctx.channel(), t); if (msg instanceof coaprequest) { ctx.writeandflush(messagebuilder.createresponse(msg, responsestatus.internal_server_error)); } } }"},"repo":{"kind":"string","value":"SenthilKumarGS/TizenRT"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":258,"cells":{"id":{"kind":"number","value":9490,"string":"9,490"},"original_code":{"kind":"string","value":"public LNode reverseListRec(LNode head)\n {\n // TODO: implement this method\n\t\t /*This method takes a reference to the head of a linked list and returns \n the reference to the head of the linked list in the reversed order. */\n if(head == null) { return head; }\n if(head.getLink() == null) { return head; }\n head.getLink().setLink(head);\n head.setLink(null);\n return reverseListRec(head);\n // replace this statement with your own return\n }"},"code_wo_comment":{"kind":"string","value":"public LNode reverseListRec(LNode head)\n {\n \n\t\t \n if(head == null) { return head; }\n if(head.getLink() == null) { return head; }\n head.getLink().setLink(head);\n head.setLink(null);\n return reverseListRec(head);\n \n }"},"cleancode":{"kind":"string","value":"public lnode reverselistrec(lnode head) { if(head == null) { return head; } if(head.getlink() == null) { return head; } head.getlink().setlink(head); head.setlink(null); return reverselistrec(head); }"},"repo":{"kind":"string","value":"Sailia/data_structures"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":259,"cells":{"id":{"kind":"number","value":17706,"string":"17,706"},"original_code":{"kind":"string","value":"@SuppressWarnings(\"ParameterName\")\n public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative) {\n // ask the kinematics to determine our swerve command\n ChassisSpeeds speeds;\n if (fieldRelative == true) {\n speeds = ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, rot, getHeading());\n } else {\n speeds = new ChassisSpeeds(xSpeed, ySpeed, rot);\n }\n SwerveModuleState[] swerveModuleStates = kinematics.toSwerveModuleStates(speeds);\n // sometime the Kinematics spits out too fast of speeds, so this will fix this\n SwerveDriveKinematics.desaturateWheelSpeeds(swerveModuleStates, kMaxSpeed);\n // command each swerve module\n for (int i = 0; i < modules.length; i++) {\n modules[i].setDesiredState(swerveModuleStates[i]);\n }\n // report our commands to the dashboard\n SmartDashboard.putNumber(\"SwerveDrive/xSpeed\", xSpeed);\n SmartDashboard.putNumber(\"SwerveDrive/ySpeed\", ySpeed);\n SmartDashboard.putNumber(\"SwerveDrive/rot\", rot);\n SmartDashboard.putBoolean(\"SwerveDrive/fieldRelative\", fieldRelative);\n }"},"code_wo_comment":{"kind":"string","value":"@SuppressWarnings(\"ParameterName\")\n public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative) {\n \n ChassisSpeeds speeds;\n if (fieldRelative == true) {\n speeds = ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, rot, getHeading());\n } else {\n speeds = new ChassisSpeeds(xSpeed, ySpeed, rot);\n }\n SwerveModuleState[] swerveModuleStates = kinematics.toSwerveModuleStates(speeds);\n \n SwerveDriveKinematics.desaturateWheelSpeeds(swerveModuleStates, kMaxSpeed);\n \n for (int i = 0; i < modules.length; i++) {\n modules[i].setDesiredState(swerveModuleStates[i]);\n }\n \n SmartDashboard.putNumber(\"SwerveDrive/xSpeed\", xSpeed);\n SmartDashboard.putNumber(\"SwerveDrive/ySpeed\", ySpeed);\n SmartDashboard.putNumber(\"SwerveDrive/rot\", rot);\n SmartDashboard.putBoolean(\"SwerveDrive/fieldRelative\", fieldRelative);\n }"},"cleancode":{"kind":"string","value":"@suppresswarnings(\"parametername\") public void drive(double xspeed, double yspeed, double rot, boolean fieldrelative) { chassisspeeds speeds; if (fieldrelative == true) { speeds = chassisspeeds.fromfieldrelativespeeds(xspeed, yspeed, rot, getheading()); } else { speeds = new chassisspeeds(xspeed, yspeed, rot); } swervemodulestate[] swervemodulestates = kinematics.toswervemodulestates(speeds); swervedrivekinematics.desaturatewheelspeeds(swervemodulestates, kmaxspeed); for (int i = 0; i < modules.length; i++) { modules[i].setdesiredstate(swervemodulestates[i]); } smartdashboard.putnumber(\"swervedrive/xspeed\", xspeed); smartdashboard.putnumber(\"swervedrive/yspeed\", yspeed); smartdashboard.putnumber(\"swervedrive/rot\", rot); smartdashboard.putboolean(\"swervedrive/fieldrelative\", fieldrelative); }"},"repo":{"kind":"string","value":"Sammoore15/Robot2022-2832-altencoderforingestor"},"label":{"kind":"list like","value":[0,0,0,0],"string":"[\n 0,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":260,"cells":{"id":{"kind":"number","value":1344,"string":"1,344"},"original_code":{"kind":"string","value":"private int generateNewTicketNumber() \n {\n //TODO: this may take foreever. fix\n int generated = numberGenerator.next();\n while(purchased.containsKey(generated)){\n generated = numberGenerator.next();\n }\n return generated;\n }"},"code_wo_comment":{"kind":"string","value":"private int generateNewTicketNumber() \n {\n \n int generated = numberGenerator.next();\n while(purchased.containsKey(generated)){\n generated = numberGenerator.next();\n }\n return generated;\n }"},"cleancode":{"kind":"string","value":"private int generatenewticketnumber() { int generated = numbergenerator.next(); while(purchased.containskey(generated)){ generated = numbergenerator.next(); } return generated; }"},"repo":{"kind":"string","value":"aha0x0x/LotteryApplication"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":261,"cells":{"id":{"kind":"number","value":17729,"string":"17,729"},"original_code":{"kind":"string","value":"public void setParentAtRowAndColumn(GridLayout parent, int row, int col)\n {\n // prepare the layout parameters for the EditText\n // TODO: Consider caching the layout params and only changing the spec row and spec column\n LayoutParams layoutParams = new GridLayout.LayoutParams();\n layoutParams.width = LayoutParams.WRAP_CONTENT;\n layoutParams.height = LayoutParams.WRAP_CONTENT;\n // set the row and column in the correct location of the Sudoku Board\n layoutParams.rowSpec = GridLayout.spec(row);\n layoutParams.columnSpec = GridLayout.spec(col);\n // set the layout params and add the EditText to the GridLayout parent\n _text.setLayoutParams(layoutParams);\n parent.addView(_text);\n }"},"code_wo_comment":{"kind":"string","value":"public void setParentAtRowAndColumn(GridLayout parent, int row, int col)\n {\n \n \n LayoutParams layoutParams = new GridLayout.LayoutParams();\n layoutParams.width = LayoutParams.WRAP_CONTENT;\n layoutParams.height = LayoutParams.WRAP_CONTENT;\n \n layoutParams.rowSpec = GridLayout.spec(row);\n layoutParams.columnSpec = GridLayout.spec(col);\n \n _text.setLayoutParams(layoutParams);\n parent.addView(_text);\n }"},"cleancode":{"kind":"string","value":"public void setparentatrowandcolumn(gridlayout parent, int row, int col) { layoutparams layoutparams = new gridlayout.layoutparams(); layoutparams.width = layoutparams.wrap_content; layoutparams.height = layoutparams.wrap_content; layoutparams.rowspec = gridlayout.spec(row); layoutparams.columnspec = gridlayout.spec(col); _text.setlayoutparams(layoutparams); parent.addview(_text); }"},"repo":{"kind":"string","value":"SnoBoarder/Sudoku-Solver"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":262,"cells":{"id":{"kind":"number","value":34188,"string":"34,188"},"original_code":{"kind":"string","value":"public void testZKSMFalse() throws ZKSetMembershipException, BigIntegerClassNotValid {\n\t\tBigInteger[] theSet = {new BigInteger(\"0\"), new BigInteger(\"1\"), \n\t\t\t\tnew BigInteger(\"2\"), new BigInteger(\"3\"), new BigInteger(\"4\")};\n\t\tEncryptedInteger c = new EncryptedInteger(new BigInteger(\"10\"), pub);\n\t\tBigInteger r = c.set(new BigInteger(\"10\"));\n\t\tint msgIndex = 2;\n\t\tfor (int i=0; i<10; i++) {\n\t\t\tZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c);\n\t\t\tBigInteger[] uVals = prover.genCommitments();\n\t\t\tZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet);\n\t\t\tBigInteger e = verifier.genChallenge(new BigInteger(\"128\"));\n\t\t\tprover.computeResponse(e, r);\n\t\t\tBigInteger[] eVals = prover.getEs();\n\t\t\tBigInteger[] vVals = prover.getVs();\n\t\t\tassertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability\n\t\t}\n\t}"},"code_wo_comment":{"kind":"string","value":"public void testZKSMFalse() throws ZKSetMembershipException, BigIntegerClassNotValid {\n\t\tBigInteger[] theSet = {new BigInteger(\"0\"), new BigInteger(\"1\"), \n\t\t\t\tnew BigInteger(\"2\"), new BigInteger(\"3\"), new BigInteger(\"4\")};\n\t\tEncryptedInteger c = new EncryptedInteger(new BigInteger(\"10\"), pub);\n\t\tBigInteger r = c.set(new BigInteger(\"10\"));\n\t\tint msgIndex = 2;\n\t\tfor (int i=0; i<10; i++) {\n\t\t\tZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c);\n\t\t\tBigInteger[] uVals = prover.genCommitments();\n\t\t\tZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet);\n\t\t\tBigInteger e = verifier.genChallenge(new BigInteger(\"128\"));\n\t\t\tprover.computeResponse(e, r);\n\t\t\tBigInteger[] eVals = prover.getEs();\n\t\t\tBigInteger[] vVals = prover.getVs();\n\t\t\tassertFalse(verifier.checkResponse(eVals, vVals));\n\t\t}\n\t}"},"cleancode":{"kind":"string","value":"public void testzksmfalse() throws zksetmembershipexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger(\"0\"), new biginteger(\"1\"), new biginteger(\"2\"), new biginteger(\"3\"), new biginteger(\"4\")}; encryptedinteger c = new encryptedinteger(new biginteger(\"10\"), pub); biginteger r = c.set(new biginteger(\"10\")); int msgindex = 2; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger(\"128\")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }"},"repo":{"kind":"string","value":"SoftwareEngineeringToolDemos/type-inference"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":263,"cells":{"id":{"kind":"number","value":34189,"string":"34,189"},"original_code":{"kind":"string","value":"public void testZKSMSingleMemberSetFalse() throws ZKSetMembershipException, BigIntegerClassNotValid {\n\t\tBigInteger[] theSet = {new BigInteger(\"0\")};\n\t\tEncryptedInteger c = new EncryptedInteger(BigInteger.ONE, pub);\n\t\tBigInteger r = c.set(BigInteger.ONE);\n\t\tint msgIndex = 0;\n\t\tfor (int i=0; i<10; i++) {\n\t\t\tZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c);\n\t\t\tBigInteger[] uVals = prover.genCommitments();\n\t\t\tZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet);\n\t\t\tBigInteger e = verifier.genChallenge(new BigInteger(\"128\"));\n\t\t\tprover.computeResponse(e, r);\n\t\t\tBigInteger[] eVals = prover.getEs();\n\t\t\tBigInteger[] vVals = prover.getVs();\n\t\t\tassertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability\n\t\t}\n\t}"},"code_wo_comment":{"kind":"string","value":"public void testZKSMSingleMemberSetFalse() throws ZKSetMembershipException, BigIntegerClassNotValid {\n\t\tBigInteger[] theSet = {new BigInteger(\"0\")};\n\t\tEncryptedInteger c = new EncryptedInteger(BigInteger.ONE, pub);\n\t\tBigInteger r = c.set(BigInteger.ONE);\n\t\tint msgIndex = 0;\n\t\tfor (int i=0; i<10; i++) {\n\t\t\tZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c);\n\t\t\tBigInteger[] uVals = prover.genCommitments();\n\t\t\tZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet);\n\t\t\tBigInteger e = verifier.genChallenge(new BigInteger(\"128\"));\n\t\t\tprover.computeResponse(e, r);\n\t\t\tBigInteger[] eVals = prover.getEs();\n\t\t\tBigInteger[] vVals = prover.getVs();\n\t\t\tassertFalse(verifier.checkResponse(eVals, vVals));\n\t\t}\n\t}"},"cleancode":{"kind":"string","value":"public void testzksmsinglemembersetfalse() throws zksetmembershipexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger(\"0\")}; encryptedinteger c = new encryptedinteger(biginteger.one, pub); biginteger r = c.set(biginteger.one); int msgindex = 0; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger(\"128\")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }"},"repo":{"kind":"string","value":"SoftwareEngineeringToolDemos/type-inference"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":264,"cells":{"id":{"kind":"number","value":34190,"string":"34,190"},"original_code":{"kind":"string","value":"public void testZKSMAddTrue() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid {\n\t\tBigInteger[] theSet = {new BigInteger(\"0\"), new BigInteger(\"1\"), \n\t\t\t\tnew BigInteger(\"2\"), new BigInteger(\"3\"), new BigInteger(\"4\"),\n\t\t\t\tnew BigInteger(\"6\")};\n\t\tEncryptedInteger c1 = new EncryptedInteger(new BigInteger(\"2\"), pub);\n\t\tBigInteger r1 = c1.set(new BigInteger(\"2\"));\n\t\tEncryptedInteger c2 = new EncryptedInteger(new BigInteger(\"3\"), pub);\n\t\tBigInteger r2 = c2.set(new BigInteger(\"3\"));\n\t\tEncryptedInteger c = c1.add(c2);\n\t\tBigInteger r = r1.multiply(r2).mod(this.pub.getNSquared());\n\t\tint msgIndex = 5;\n\t\tfor (int i=0; i<10; i++) {\n\t\t\tZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c);\n\t\t\tBigInteger[] uVals = prover.genCommitments();\n\t\t\tZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet);\n\t\t\tBigInteger e = verifier.genChallenge(new BigInteger(\"128\"));\n\t\t\tprover.computeResponse(e, r);\n\t\t\tBigInteger[] eVals = prover.getEs();\n\t\t\tBigInteger[] vVals = prover.getVs();\n\t\t\tassertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability\n\t\t}\n\t}"},"code_wo_comment":{"kind":"string","value":"public void testZKSMAddTrue() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid {\n\t\tBigInteger[] theSet = {new BigInteger(\"0\"), new BigInteger(\"1\"), \n\t\t\t\tnew BigInteger(\"2\"), new BigInteger(\"3\"), new BigInteger(\"4\"),\n\t\t\t\tnew BigInteger(\"6\")};\n\t\tEncryptedInteger c1 = new EncryptedInteger(new BigInteger(\"2\"), pub);\n\t\tBigInteger r1 = c1.set(new BigInteger(\"2\"));\n\t\tEncryptedInteger c2 = new EncryptedInteger(new BigInteger(\"3\"), pub);\n\t\tBigInteger r2 = c2.set(new BigInteger(\"3\"));\n\t\tEncryptedInteger c = c1.add(c2);\n\t\tBigInteger r = r1.multiply(r2).mod(this.pub.getNSquared());\n\t\tint msgIndex = 5;\n\t\tfor (int i=0; i<10; i++) {\n\t\t\tZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c);\n\t\t\tBigInteger[] uVals = prover.genCommitments();\n\t\t\tZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet);\n\t\t\tBigInteger e = verifier.genChallenge(new BigInteger(\"128\"));\n\t\t\tprover.computeResponse(e, r);\n\t\t\tBigInteger[] eVals = prover.getEs();\n\t\t\tBigInteger[] vVals = prover.getVs();\n\t\t\tassertFalse(verifier.checkResponse(eVals, vVals));\n\t\t}\n\t}"},"cleancode":{"kind":"string","value":"public void testzksmaddtrue() throws zksetmembershipexception, publickeysnotequalexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger(\"0\"), new biginteger(\"1\"), new biginteger(\"2\"), new biginteger(\"3\"), new biginteger(\"4\"), new biginteger(\"6\")}; encryptedinteger c1 = new encryptedinteger(new biginteger(\"2\"), pub); biginteger r1 = c1.set(new biginteger(\"2\")); encryptedinteger c2 = new encryptedinteger(new biginteger(\"3\"), pub); biginteger r2 = c2.set(new biginteger(\"3\")); encryptedinteger c = c1.add(c2); biginteger r = r1.multiply(r2).mod(this.pub.getnsquared()); int msgindex = 5; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger(\"128\")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }"},"repo":{"kind":"string","value":"SoftwareEngineeringToolDemos/type-inference"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":265,"cells":{"id":{"kind":"number","value":34191,"string":"34,191"},"original_code":{"kind":"string","value":"public void testZKSMManyOperations() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid {\n\t\tBigInteger[] theSet = {new BigInteger(\"0\"), new BigInteger(\"1\"), \n\t\t\t\tnew BigInteger(\"2\"), new BigInteger(\"3\"), new BigInteger(\"4\"),\n\t\t\t\tnew BigInteger(\"6\")};\n\t\tEncryptedInteger c1 = new EncryptedInteger(new BigInteger(\"2\"), pub);\n\t\tBigInteger r1 = c1.set(new BigInteger(\"2\"));\n\t\tEncryptedInteger c2 = new EncryptedInteger(new BigInteger(\"3\"), pub);\n\t\tBigInteger r2 = c2.set(new BigInteger(\"3\"));\n\t\tEncryptedInteger c = c1.add(c2);\n\t\tBigInteger r = r1.multiply(r2).mod(this.pub.getNSquared());\n\t\tint msgIndex = 5;\n\t\tfor (int i=0; i<10; i++) {\n\t\t\tZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c);\n\t\t\tBigInteger[] uVals = prover.genCommitments();\n\t\t\tZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet);\n\t\t\tBigInteger e = verifier.genChallenge(new BigInteger(\"128\"));\n\t\t\tprover.computeResponse(e, r);\n\t\t\tBigInteger[] eVals = prover.getEs();\n\t\t\tBigInteger[] vVals = prover.getVs();\n\t\t\tassertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability\n\t\t}\n\t}"},"code_wo_comment":{"kind":"string","value":"public void testZKSMManyOperations() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid {\n\t\tBigInteger[] theSet = {new BigInteger(\"0\"), new BigInteger(\"1\"), \n\t\t\t\tnew BigInteger(\"2\"), new BigInteger(\"3\"), new BigInteger(\"4\"),\n\t\t\t\tnew BigInteger(\"6\")};\n\t\tEncryptedInteger c1 = new EncryptedInteger(new BigInteger(\"2\"), pub);\n\t\tBigInteger r1 = c1.set(new BigInteger(\"2\"));\n\t\tEncryptedInteger c2 = new EncryptedInteger(new BigInteger(\"3\"), pub);\n\t\tBigInteger r2 = c2.set(new BigInteger(\"3\"));\n\t\tEncryptedInteger c = c1.add(c2);\n\t\tBigInteger r = r1.multiply(r2).mod(this.pub.getNSquared());\n\t\tint msgIndex = 5;\n\t\tfor (int i=0; i<10; i++) {\n\t\t\tZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c);\n\t\t\tBigInteger[] uVals = prover.genCommitments();\n\t\t\tZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet);\n\t\t\tBigInteger e = verifier.genChallenge(new BigInteger(\"128\"));\n\t\t\tprover.computeResponse(e, r);\n\t\t\tBigInteger[] eVals = prover.getEs();\n\t\t\tBigInteger[] vVals = prover.getVs();\n\t\t\tassertFalse(verifier.checkResponse(eVals, vVals));\n\t\t}\n\t}"},"cleancode":{"kind":"string","value":"public void testzksmmanyoperations() throws zksetmembershipexception, publickeysnotequalexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger(\"0\"), new biginteger(\"1\"), new biginteger(\"2\"), new biginteger(\"3\"), new biginteger(\"4\"), new biginteger(\"6\")}; encryptedinteger c1 = new encryptedinteger(new biginteger(\"2\"), pub); biginteger r1 = c1.set(new biginteger(\"2\")); encryptedinteger c2 = new encryptedinteger(new biginteger(\"3\"), pub); biginteger r2 = c2.set(new biginteger(\"3\")); encryptedinteger c = c1.add(c2); biginteger r = r1.multiply(r2).mod(this.pub.getnsquared()); int msgindex = 5; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger(\"128\")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }"},"repo":{"kind":"string","value":"SoftwareEngineeringToolDemos/type-inference"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":266,"cells":{"id":{"kind":"number","value":34311,"string":"34,311"},"original_code":{"kind":"string","value":"private void assertTestSummary() {\n int fails = testResult.fails().size();\n int errors = testResult.errors().size();\n int succeeds = testResult.succeeds().size();\n int testCount = fails + errors + succeeds;\n if (testMode.isJ2cl()) {\n // Like Junit4, J2CL always counts errors as failures\n fails += errors;\n errors = 0;\n // TODO(b/32608089): jsunit_test does not report number of tests correctly\n testCount = 1;\n // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct.\n assertThat(consoleLogs.stream().filter(x -> x.contains(\": PASSED\"))).hasSize(succeeds);\n }\n if (fails + errors > 0) {\n assertTestSummaryForFailure(fails, errors, testCount);\n } else {\n assertTestSummaryForSuccess(testCount);\n }\n }"},"code_wo_comment":{"kind":"string","value":"private void assertTestSummary() {\n int fails = testResult.fails().size();\n int errors = testResult.errors().size();\n int succeeds = testResult.succeeds().size();\n int testCount = fails + errors + succeeds;\n if (testMode.isJ2cl()) {\n \n fails += errors;\n errors = 0;\n \n testCount = 1;\n \n assertThat(consoleLogs.stream().filter(x -> x.contains(\": PASSED\"))).hasSize(succeeds);\n }\n if (fails + errors > 0) {\n assertTestSummaryForFailure(fails, errors, testCount);\n } else {\n assertTestSummaryForSuccess(testCount);\n }\n }"},"cleancode":{"kind":"string","value":"private void asserttestsummary() { int fails = testresult.fails().size(); int errors = testresult.errors().size(); int succeeds = testresult.succeeds().size(); int testcount = fails + errors + succeeds; if (testmode.isj2cl()) { fails += errors; errors = 0; testcount = 1; assertthat(consolelogs.stream().filter(x -> x.contains(\": passed\"))).hassize(succeeds); } if (fails + errors > 0) { asserttestsummaryforfailure(fails, errors, testcount); } else { asserttestsummaryforsuccess(testcount); } }"},"repo":{"kind":"string","value":"VishrutMehta/j2cl"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":267,"cells":{"id":{"kind":"number","value":18084,"string":"18,084"},"original_code":{"kind":"string","value":"public boolean connect(long timeoutMs) {\n if (LOG.isDebugEnabled()) LOG.debug(\"Connecting to JMX URL: {} ({})\", url, ((timeoutMs == -1) ? \"indefinitely\" : timeoutMs+\"ms timeout\"));\n long startMs = System.currentTimeMillis();\n long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);\n long currentTime = startMs;\n Throwable lastError = null;\n int attempt = 0;\n while (currentTime <= endMs) {\n currentTime = System.currentTimeMillis();\n if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption\n if (LOG.isTraceEnabled()) LOG.trace(\"trying connection to {} at time {}\", url, currentTime);\n try {\n connect();\n return true;\n } catch (Exception e) {\n Exceptions.propagateIfFatal(e);\n if (!terminated.get() && shouldRetryOn(e)) {\n if (LOG.isDebugEnabled()) LOG.debug(\"Attempt {} failed connecting to {} ({})\", new Object[] {attempt + 1, url, e.getMessage()});\n lastError = e;\n } else {\n throw Exceptions.propagate(e);\n }\n }\n attempt++;\n }\n LOG.warn(\"unable to connect to JMX url: \"+url, lastError);\n return false;\n }"},"code_wo_comment":{"kind":"string","value":"public boolean connect(long timeoutMs) {\n if (LOG.isDebugEnabled()) LOG.debug(\"Connecting to JMX URL: {} ({})\", url, ((timeoutMs == -1) ? \"indefinitely\" : timeoutMs+\"ms timeout\"));\n long startMs = System.currentTimeMillis();\n long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);\n long currentTime = startMs;\n Throwable lastError = null;\n int attempt = 0;\n while (currentTime <= endMs) {\n currentTime = System.currentTimeMillis();\n if (attempt != 0) sleep(100);\n if (LOG.isTraceEnabled()) LOG.trace(\"trying connection to {} at time {}\", url, currentTime);\n try {\n connect();\n return true;\n } catch (Exception e) {\n Exceptions.propagateIfFatal(e);\n if (!terminated.get() && shouldRetryOn(e)) {\n if (LOG.isDebugEnabled()) LOG.debug(\"Attempt {} failed connecting to {} ({})\", new Object[] {attempt + 1, url, e.getMessage()});\n lastError = e;\n } else {\n throw Exceptions.propagate(e);\n }\n }\n attempt++;\n }\n LOG.warn(\"unable to connect to JMX url: \"+url, lastError);\n return false;\n }"},"cleancode":{"kind":"string","value":"public boolean connect(long timeoutms) { if (log.isdebugenabled()) log.debug(\"connecting to jmx url: {} ({})\", url, ((timeoutms == -1) ? \"indefinitely\" : timeoutms+\"ms timeout\")); long startms = system.currenttimemillis(); long endms = (timeoutms == -1) ? long.max_value : (startms + timeoutms); long currenttime = startms; throwable lasterror = null; int attempt = 0; while (currenttime <= endms) { currenttime = system.currenttimemillis(); if (attempt != 0) sleep(100); if (log.istraceenabled()) log.trace(\"trying connection to {} at time {}\", url, currenttime); try { connect(); return true; } catch (exception e) { exceptions.propagateiffatal(e); if (!terminated.get() && shouldretryon(e)) { if (log.isdebugenabled()) log.debug(\"attempt {} failed connecting to {} ({})\", new object[] {attempt + 1, url, e.getmessage()}); lasterror = e; } else { throw exceptions.propagate(e); } } attempt++; } log.warn(\"unable to connect to jmx url: \"+url, lasterror); return false; }"},"repo":{"kind":"string","value":"YYTVicky/brooklyn-server"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":268,"cells":{"id":{"kind":"number","value":34588,"string":"34,588"},"original_code":{"kind":"string","value":"public String toString(int indentFactor) {\n try {\n StringWriter w = new StringWriter();\n synchronized (w.getBuffer()) {\n return this.write(w, indentFactor, 0).toString();\n }\n }\n catch (Exception e) {\n //there is no conceivable exception that can come out of this, but throw something\n //just in case. Want the signature to not have exception in it.\n throw new RuntimeException(\"Can not serialize JSONObject????\", e);\n }\n }"},"code_wo_comment":{"kind":"string","value":"public String toString(int indentFactor) {\n try {\n StringWriter w = new StringWriter();\n synchronized (w.getBuffer()) {\n return this.write(w, indentFactor, 0).toString();\n }\n }\n catch (Exception e) {\n \n \n throw new RuntimeException(\"Can not serialize JSONObject????\", e);\n }\n }"},"cleancode":{"kind":"string","value":"public string tostring(int indentfactor) { try { stringwriter w = new stringwriter(); synchronized (w.getbuffer()) { return this.write(w, indentfactor, 0).tostring(); } } catch (exception e) { throw new runtimeexception(\"can not serialize jsonobject????\", e); } }"},"repo":{"kind":"string","value":"agilepro/purple"},"label":{"kind":"list like","value":[0,0,0,0],"string":"[\n 0,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":269,"cells":{"id":{"kind":"number","value":18326,"string":"18,326"},"original_code":{"kind":"string","value":"private void validate() throws IllegalStateException {\n Set orderings = Sets.newHashSet();\n if(preferred != null) {\n orderings.add(preferred.getOrdering());\n }\n for(DateTimeParser parser : otherParsers) {\n if(!orderings.add(parser.getOrdering())) {\n throw new IllegalStateException(\"DateComponentOrdering can only be used once in a DateTimeMultiParser.\" +\n \"[\" + parser.getOrdering() + \"]\");\n }\n }\n }"},"code_wo_comment":{"kind":"string","value":"private void validate() throws IllegalStateException {\n Set orderings = Sets.newHashSet();\n if(preferred != null) {\n orderings.add(preferred.getOrdering());\n }\n for(DateTimeParser parser : otherParsers) {\n if(!orderings.add(parser.getOrdering())) {\n throw new IllegalStateException(\"DateComponentOrdering can only be used once in a DateTimeMultiParser.\" +\n \"[\" + parser.getOrdering() + \"]\");\n }\n }\n }"},"cleancode":{"kind":"string","value":"private void validate() throws illegalstateexception { set orderings = sets.newhashset(); if(preferred != null) { orderings.add(preferred.getordering()); } for(datetimeparser parser : otherparsers) { if(!orderings.add(parser.getordering())) { throw new illegalstateexception(\"datecomponentordering can only be used once in a datetimemultiparser.\" + \"[\" + parser.getordering() + \"]\"); } } }"},"repo":{"kind":"string","value":"adam-collins/parsers"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":270,"cells":{"id":{"kind":"number","value":18370,"string":"18,370"},"original_code":{"kind":"string","value":"public static String getEnumName(String fieldName ) {\n\t\t//Later TODO\n\t\t//return super.getEnumName(fieldName);\n\t\treturn null;\n\t}"},"code_wo_comment":{"kind":"string","value":"public static String getEnumName(String fieldName ) {\n\t\n\t\n\t\treturn null;\n\t}"},"cleancode":{"kind":"string","value":"public static string getenumname(string fieldname ) { return null; }"},"repo":{"kind":"string","value":"aloklal99/apache-ranger"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":271,"cells":{"id":{"kind":"number","value":18422,"string":"18,422"},"original_code":{"kind":"string","value":"public static StatsValues createStatsValues(StatsField statsField) {\n final SchemaField sf = statsField.getSchemaField();\n if (null == sf) {\n // function stats\n return new NumericStatsValues(statsField);\n }\n final FieldType fieldType = sf.getType(); // TODO: allow FieldType to provide impl.\n if (TrieDateField.class.isInstance(fieldType) || DatePointField.class.isInstance(fieldType)) {\n DateStatsValues statsValues = new DateStatsValues(statsField);\n if (sf.multiValued()) {\n return new SortedDateStatsValues(statsValues, statsField);\n }\n return statsValues;\n } else if (TrieField.class.isInstance(fieldType) || PointField.class.isInstance(fieldType)) {\n NumericStatsValues statsValue = new NumericStatsValues(statsField);\n if (sf.multiValued()) {\n return new SortedNumericStatsValues(statsValue, statsField);\n }\n return statsValue;\n } else if (StrField.class.isInstance(fieldType)) {\n return new StringStatsValues(statsField);\n } else if (AbstractEnumField.class.isInstance(fieldType)) {\n return new EnumStatsValues(statsField);\n } else {\n throw new SolrException(\n SolrException.ErrorCode.BAD_REQUEST,\n \"Field type \" + fieldType + \" is not currently supported\");\n }\n }"},"code_wo_comment":{"kind":"string","value":"public static StatsValues createStatsValues(StatsField statsField) {\n final SchemaField sf = statsField.getSchemaField();\n if (null == sf) {\n \n return new NumericStatsValues(statsField);\n }\n final FieldType fieldType = sf.getType();\n if (TrieDateField.class.isInstance(fieldType) || DatePointField.class.isInstance(fieldType)) {\n DateStatsValues statsValues = new DateStatsValues(statsField);\n if (sf.multiValued()) {\n return new SortedDateStatsValues(statsValues, statsField);\n }\n return statsValues;\n } else if (TrieField.class.isInstance(fieldType) || PointField.class.isInstance(fieldType)) {\n NumericStatsValues statsValue = new NumericStatsValues(statsField);\n if (sf.multiValued()) {\n return new SortedNumericStatsValues(statsValue, statsField);\n }\n return statsValue;\n } else if (StrField.class.isInstance(fieldType)) {\n return new StringStatsValues(statsField);\n } else if (AbstractEnumField.class.isInstance(fieldType)) {\n return new EnumStatsValues(statsField);\n } else {\n throw new SolrException(\n SolrException.ErrorCode.BAD_REQUEST,\n \"Field type \" + fieldType + \" is not currently supported\");\n }\n }"},"cleancode":{"kind":"string","value":"public static statsvalues createstatsvalues(statsfield statsfield) { final schemafield sf = statsfield.getschemafield(); if (null == sf) { return new numericstatsvalues(statsfield); } final fieldtype fieldtype = sf.gettype(); if (triedatefield.class.isinstance(fieldtype) || datepointfield.class.isinstance(fieldtype)) { datestatsvalues statsvalues = new datestatsvalues(statsfield); if (sf.multivalued()) { return new sorteddatestatsvalues(statsvalues, statsfield); } return statsvalues; } else if (triefield.class.isinstance(fieldtype) || pointfield.class.isinstance(fieldtype)) { numericstatsvalues statsvalue = new numericstatsvalues(statsfield); if (sf.multivalued()) { return new sortednumericstatsvalues(statsvalue, statsfield); } return statsvalue; } else if (strfield.class.isinstance(fieldtype)) { return new stringstatsvalues(statsfield); } else if (abstractenumfield.class.isinstance(fieldtype)) { return new enumstatsvalues(statsfield); } else { throw new solrexception( solrexception.errorcode.bad_request, \"field type \" + fieldtype + \" is not currently supported\"); } }"},"repo":{"kind":"string","value":"ackepenek/solr"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":272,"cells":{"id":{"kind":"number","value":18424,"string":"18,424"},"original_code":{"kind":"string","value":"public void setSelected(@Nullable PackListWidget.PackEntry entry) {\n this.setSelected(entry, true);\n }"},"code_wo_comment":{"kind":"string","value":"public void setSelected(@Nullable PackListWidget.PackEntry entry) {\n this.setSelected(entry, true);\n }"},"cleancode":{"kind":"string","value":"public void setselected(@nullable packlistwidget.packentry entry) { this.setselected(entry, true); }"},"repo":{"kind":"string","value":"VanillaImprovements/VVDownloader"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":273,"cells":{"id":{"kind":"number","value":2045,"string":"2,045"},"original_code":{"kind":"string","value":"synchronized ImmutableList getActiveEvents() {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (String id : activeJobIds) {\n JobEvent p = eventsByJobId.get(id);\n assert p != null;\n builder.add(p);\n }\n return builder.build();\n }"},"code_wo_comment":{"kind":"string","value":"synchronized ImmutableList getActiveEvents() {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (String id : activeJobIds) {\n JobEvent p = eventsByJobId.get(id);\n assert p != null;\n builder.add(p);\n }\n return builder.build();\n }"},"cleancode":{"kind":"string","value":"synchronized immutablelist getactiveevents() { immutablelist.builder builder = immutablelist.builder(); for (string id : activejobids) { jobevent p = eventsbyjobid.get(id); assert p != null; builder.add(p); } return builder.build(); }"},"repo":{"kind":"string","value":"TeamSPoon/CYC_JRTL_with_CommonLisp_OLD"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":274,"cells":{"id":{"kind":"number","value":18433,"string":"18,433"},"original_code":{"kind":"string","value":"private VdsmVm appendStatistics(VdsmVm vm, V1VirtualMachineInstance vmi) {\n VmStatistics statistics = new VmStatistics();\n statistics.setId(vm.getId());\n DateTime creationTimestampDate = vmi.getMetadata().getCreationTimestamp();\n if (creationTimestampDate != null) {\n DateTime now = DateTime.now();\n Seconds seconds = Seconds.secondsBetween(creationTimestampDate, now);\n statistics.setElapsedTime((double) seconds.getSeconds());\n }\n PrometheusClient promClient = getPrometheusClient();\n if (promClient != null) {\n // FIXME: Kubevirt currently have only kubevirt_vmi_vcpu_seconds, which is total CPU time,\n // so we are setting it here only as system time, which is wrong.\n statistics.setCpuSys(\n promClient.getVmiCpuUsage(vmi.getMetadata().getName(), vmi.getMetadata().getNamespace())\n );\n }\n return vm.setVmStatistics(statistics)\n .setDiskStatistics(Collections.emptyList())\n .setVmJobs(Collections.emptyList());\n }"},"code_wo_comment":{"kind":"string","value":"private VdsmVm appendStatistics(VdsmVm vm, V1VirtualMachineInstance vmi) {\n VmStatistics statistics = new VmStatistics();\n statistics.setId(vm.getId());\n DateTime creationTimestampDate = vmi.getMetadata().getCreationTimestamp();\n if (creationTimestampDate != null) {\n DateTime now = DateTime.now();\n Seconds seconds = Seconds.secondsBetween(creationTimestampDate, now);\n statistics.setElapsedTime((double) seconds.getSeconds());\n }\n PrometheusClient promClient = getPrometheusClient();\n if (promClient != null) {\n \n \n statistics.setCpuSys(\n promClient.getVmiCpuUsage(vmi.getMetadata().getName(), vmi.getMetadata().getNamespace())\n );\n }\n return vm.setVmStatistics(statistics)\n .setDiskStatistics(Collections.emptyList())\n .setVmJobs(Collections.emptyList());\n }"},"cleancode":{"kind":"string","value":"private vdsmvm appendstatistics(vdsmvm vm, v1virtualmachineinstance vmi) { vmstatistics statistics = new vmstatistics(); statistics.setid(vm.getid()); datetime creationtimestampdate = vmi.getmetadata().getcreationtimestamp(); if (creationtimestampdate != null) { datetime now = datetime.now(); seconds seconds = seconds.secondsbetween(creationtimestampdate, now); statistics.setelapsedtime((double) seconds.getseconds()); } prometheusclient promclient = getprometheusclient(); if (promclient != null) { statistics.setcpusys( promclient.getvmicpuusage(vmi.getmetadata().getname(), vmi.getmetadata().getnamespace()) ); } return vm.setvmstatistics(statistics) .setdiskstatistics(collections.emptylist()) .setvmjobs(collections.emptylist()); }"},"repo":{"kind":"string","value":"StevenCode/ovirt-engine"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":275,"cells":{"id":{"kind":"number","value":18456,"string":"18,456"},"original_code":{"kind":"string","value":"@Test \n @Ignore(\"dbpedia is not reliable\")\n public void testDBPedia() throws Exception {\n testResource(DBPEDIA, \"dbpedia-berlin.sparql\" );\n }"},"code_wo_comment":{"kind":"string","value":"@Test \n @Ignore(\"dbpedia is not reliable\")\n public void testDBPedia() throws Exception {\n testResource(DBPEDIA, \"dbpedia-berlin.sparql\" );\n }"},"cleancode":{"kind":"string","value":"@test @ignore(\"dbpedia is not reliable\") public void testdbpedia() throws exception { testresource(dbpedia, \"dbpedia-berlin.sparql\" ); }"},"repo":{"kind":"string","value":"YYTVicky/marmotta"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":276,"cells":{"id":{"kind":"number","value":34925,"string":"34,925"},"original_code":{"kind":"string","value":"@Test\n public void canCompleteItself() throws IOException {\n String jid = queue.put(\"Foo\", null, null);\n queue.pop().complete(); // TODO: this test passes even when this line is removed\n Assert.assertEquals(\"complete\", client.getJob(jid).getState());\n }"},"code_wo_comment":{"kind":"string","value":"@Test\n public void canCompleteItself() throws IOException {\n String jid = queue.put(\"Foo\", null, null);\n queue.pop().complete();\n Assert.assertEquals(\"complete\", client.getJob(jid).getState());\n }"},"cleancode":{"kind":"string","value":"@test public void cancompleteitself() throws ioexception { string jid = queue.put(\"foo\", null, null); queue.pop().complete(); assert.assertequals(\"complete\", client.getjob(jid).getstate()); }"},"repo":{"kind":"string","value":"Zimbra/qless-java"},"label":{"kind":"list like","value":[0,0,0,1],"string":"[\n 0,\n 0,\n 0,\n 1\n]"}}},{"rowIdx":277,"cells":{"id":{"kind":"number","value":18643,"string":"18,643"},"original_code":{"kind":"string","value":"@Override\n public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) {\n if (affectedControllerId.equals(source.getControllerId())) {\n Card card = game.getCard(objectId);\n MageObject sourceObject = source.getSourceObject(game);\n if (card != null && !card.isLand() && sourceObject != null) {\n UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter());\n if (exileId != null) {\n ExileZone exileZone = game.getState().getExile().getExileZone(exileId);\n if (exileZone != null && exileZone.contains(objectId)) {\n if (game.getTurnNum() == turnNumber) {\n if (!exileZone.contains(cardId)) {\n // last checked card this turn is no longer exiled, so you can't cast another with this effect\n // TODO: Handle if card was cast/removed from exile with effect from another card.\n // If so, this effect could prevent player from casting although they should be able to use it\n return false;\n }\n }\n this.turnNumber = game.getTurnNum();\n this.cardId = objectId;\n return true;\n }\n }\n }\n }\n return false;\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) {\n if (affectedControllerId.equals(source.getControllerId())) {\n Card card = game.getCard(objectId);\n MageObject sourceObject = source.getSourceObject(game);\n if (card != null && !card.isLand() && sourceObject != null) {\n UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter());\n if (exileId != null) {\n ExileZone exileZone = game.getState().getExile().getExileZone(exileId);\n if (exileZone != null && exileZone.contains(objectId)) {\n if (game.getTurnNum() == turnNumber) {\n if (!exileZone.contains(cardId)) {\n \n \n \n return false;\n }\n }\n this.turnNumber = game.getTurnNum();\n this.cardId = objectId;\n return true;\n }\n }\n }\n }\n return false;\n }"},"cleancode":{"kind":"string","value":"@override public boolean applies(uuid objectid, ability source, uuid affectedcontrollerid, game game) { if (affectedcontrollerid.equals(source.getcontrollerid())) { card card = game.getcard(objectid); mageobject sourceobject = source.getsourceobject(game); if (card != null && !card.island() && sourceobject != null) { uuid exileid = cardutil.getexilezoneid(game, source.getsourceid(), source.getsourceobjectzonechangecounter()); if (exileid != null) { exilezone exilezone = game.getstate().getexile().getexilezone(exileid); if (exilezone != null && exilezone.contains(objectid)) { if (game.getturnnum() == turnnumber) { if (!exilezone.contains(cardid)) { return false; } } this.turnnumber = game.getturnnum(); this.cardid = objectid; return true; } } } } return false; }"},"repo":{"kind":"string","value":"amc8391/mage"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":278,"cells":{"id":{"kind":"number","value":2359,"string":"2,359"},"original_code":{"kind":"string","value":"public static String getFilePathDiskCache(final String key) {\n if (sDiskLruCache == null) {\n return null;\n }\n // This violates encapsulation but there is no convenience method to get a filename from\n // DiskLruCache. Filename was derived from private class method Entry#getCleanFile\n // in DiskLruCache.java\n return sDiskLruCache.getDirectory()\n + File.separator\n + createValidDiskCacheKey(key)\n + \".\"\n + DISK_CACHE_INDEX;\n }"},"code_wo_comment":{"kind":"string","value":"public static String getFilePathDiskCache(final String key) {\n if (sDiskLruCache == null) {\n return null;\n }\n \n \n \n return sDiskLruCache.getDirectory()\n + File.separator\n + createValidDiskCacheKey(key)\n + \".\"\n + DISK_CACHE_INDEX;\n }"},"cleancode":{"kind":"string","value":"public static string getfilepathdiskcache(final string key) { if (sdisklrucache == null) { return null; } return sdisklrucache.getdirectory() + file.separator + createvaliddiskcachekey(key) + \".\" + disk_cache_index; }"},"repo":{"kind":"string","value":"SinnerSchraderMobileMirrors/mopub-android-sdk"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":279,"cells":{"id":{"kind":"number","value":18861,"string":"18,861"},"original_code":{"kind":"string","value":"private void setUpViews() {\n glucometerAttribution = findViewById(R.id.glucometerAttribution);\n glucometerImg = findViewById(R.id.glucometerImg);\n insertStripText = findViewById(R.id.insertStripText);\n upArrow = findViewById(R.id.upArrow);\n droplet = findViewById(R.id.dropletImg);\n attributionText = findViewById(R.id.attributionText);\n placeBloodSweatImg = findViewById(R.id.placeBloodSweatImg);\n placeBloodSweatText = findViewById(R.id.placeBloodSweatText);\n waitForReadingText = findViewById(R.id.waitForReadingText);\n progressBar = findViewById(R.id.progressBar);\n unitsText = findViewById(R.id.unitsText);\n glucoseLevelText = findViewById(R.id.glucoseLevelText);\n descriptionTxt = findViewById(R.id.descriptionTxt);\n detailsBtn = findViewById(R.id.detailsBtn);\n anotherReadingBtn = findViewById(R.id.anotherReadingBtn);\n showBtn = findViewById(R.id.button7);\n dippedBtn = findViewById(R.id.button6);\n stripBtn = findViewById(R.id.button8);\n startButton = findViewById(R.id.btnStripInserted);\n rgMode = findViewById(R.id.rgMode);\n rbBlood = findViewById(R.id.rbBlood);\n rbSweat = findViewById(R.id.rbSweat);\n rb_mg_dL = findViewById(R.id.rb_mg_dL);\n rb_mmol_L = findViewById(R.id.rb_mmol_L);\n glucometerSwitch = findViewById(R.id.glucometerSwitch);\n rgUnits = findViewById(R.id.rgUnits);\n startButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!rbSweat.isChecked() && !rbBlood.isChecked()) {\n Toast.makeText(GlucometerActivity.this, \"Please select a mode\", Toast.LENGTH_SHORT).show();\n }\n else {\n instance.sendDataToArduino(\"start\");\n instance.setReading(true);\n glucometerSwitch.setEnabled(false);\n rbBlood.setEnabled(false);\n rbSweat.setEnabled(false);\n rb_mg_dL.setEnabled(false);\n rb_mmol_L.setEnabled(false);\n startButton.setEnabled(false);\n glucometerImg.setVisibility(View.VISIBLE);\n glucometerAttribution.setVisibility(View.VISIBLE);\n insertStripText.setVisibility(View.VISIBLE);\n upArrow.setVisibility(View.VISIBLE);\n }\n }\n });\n rgMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(RadioGroup group, int checkedId) {\n switch (checkedId) {\n case R.id.rbBlood:\n instance.sendDataToArduino(\"Blood\");\n droplet.setColorFilter(Color.parseColor(\"#F44336\"));\n placeBloodSweatText.setText(\"Place blood on the test strip\");\n break;\n case R.id.rbSweat:\n instance.sendDataToArduino(\"Sweat\");\n droplet.setColorFilter(Color.parseColor(\"#1b95e0\"));\n placeBloodSweatText.setText(\"Place sweat on the test strip\");\n break;\n }\n viewDelay();\n }\n });\n glucometerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n if (isChecked){\n instance.sendDataToArduino(\"G_on\");\n viewDelay();\n }else {\n instance.sendDataToArduino(\"G_off\");\n startButton.setEnabled(false);\n rbBlood.setEnabled(false);\n rbSweat.setEnabled(false);\n rb_mg_dL.setEnabled(false);\n rb_mmol_L.setEnabled(false);\n glucometerSwitch.setEnabled(false);\n viewHandler = new Handler();\n Runnable delay = new Runnable() {\n @Override\n public void run() {\n glucometerSwitch.setEnabled(true);\n }\n };\n viewHandler.postDelayed(delay, 1000);\n }\n }\n });\n rgUnits.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(RadioGroup group, int checkedId) {\n switch (checkedId) {\n case R.id.rb_mg_dL:\n //TODO Display readings in mg/dL\n unitsText.setText(\"mg/dL\");\n break;\n case R.id.rb_mmol_L:\n //TODO Display readings in mmol/L\n unitsText.setText(\"mmol/L\");\n break;\n }\n viewDelay();\n }\n });\n detailsBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n //Move to new activity\n Intent intent = new Intent(GlucometerActivity.this, GlucoseReadingDetailsActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);\n startActivity(intent);\n }\n });\n anotherReadingBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n instance.setReading(false);\n glucometerSwitch.setEnabled(true);\n rbBlood.setEnabled(true);\n rbSweat.setEnabled(true);\n rb_mg_dL.setEnabled(true);\n rb_mmol_L.setEnabled(true);\n startButton.setEnabled(true);\n instance.setStringData(null);\n instance.setCommand(null);\n unitsText.setVisibility(View.INVISIBLE);\n glucoseLevelText.setVisibility(View.INVISIBLE);\n descriptionTxt.setVisibility(View.INVISIBLE);\n detailsBtn.setVisibility(View.INVISIBLE);\n anotherReadingBtn.setVisibility(View.INVISIBLE);\n }\n });\n showBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n instance.setCommand(\"show\");\n }\n });\n stripBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n instance.setCommand(\"strip\");\n }\n });\n dippedBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n instance.setCommand(\"dipped\");\n }\n });\n }"},"code_wo_comment":{"kind":"string","value":"private void setUpViews() {\n glucometerAttribution = findViewById(R.id.glucometerAttribution);\n glucometerImg = findViewById(R.id.glucometerImg);\n insertStripText = findViewById(R.id.insertStripText);\n upArrow = findViewById(R.id.upArrow);\n droplet = findViewById(R.id.dropletImg);\n attributionText = findViewById(R.id.attributionText);\n placeBloodSweatImg = findViewById(R.id.placeBloodSweatImg);\n placeBloodSweatText = findViewById(R.id.placeBloodSweatText);\n waitForReadingText = findViewById(R.id.waitForReadingText);\n progressBar = findViewById(R.id.progressBar);\n unitsText = findViewById(R.id.unitsText);\n glucoseLevelText = findViewById(R.id.glucoseLevelText);\n descriptionTxt = findViewById(R.id.descriptionTxt);\n detailsBtn = findViewById(R.id.detailsBtn);\n anotherReadingBtn = findViewById(R.id.anotherReadingBtn);\n showBtn = findViewById(R.id.button7);\n dippedBtn = findViewById(R.id.button6);\n stripBtn = findViewById(R.id.button8);\n startButton = findViewById(R.id.btnStripInserted);\n rgMode = findViewById(R.id.rgMode);\n rbBlood = findViewById(R.id.rbBlood);\n rbSweat = findViewById(R.id.rbSweat);\n rb_mg_dL = findViewById(R.id.rb_mg_dL);\n rb_mmol_L = findViewById(R.id.rb_mmol_L);\n glucometerSwitch = findViewById(R.id.glucometerSwitch);\n rgUnits = findViewById(R.id.rgUnits);\n startButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!rbSweat.isChecked() && !rbBlood.isChecked()) {\n Toast.makeText(GlucometerActivity.this, \"Please select a mode\", Toast.LENGTH_SHORT).show();\n }\n else {\n instance.sendDataToArduino(\"start\");\n instance.setReading(true);\n glucometerSwitch.setEnabled(false);\n rbBlood.setEnabled(false);\n rbSweat.setEnabled(false);\n rb_mg_dL.setEnabled(false);\n rb_mmol_L.setEnabled(false);\n startButton.setEnabled(false);\n glucometerImg.setVisibility(View.VISIBLE);\n glucometerAttribution.setVisibility(View.VISIBLE);\n insertStripText.setVisibility(View.VISIBLE);\n upArrow.setVisibility(View.VISIBLE);\n }\n }\n });\n rgMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(RadioGroup group, int checkedId) {\n switch (checkedId) {\n case R.id.rbBlood:\n instance.sendDataToArduino(\"Blood\");\n droplet.setColorFilter(Color.parseColor(\"#F44336\"));\n placeBloodSweatText.setText(\"Place blood on the test strip\");\n break;\n case R.id.rbSweat:\n instance.sendDataToArduino(\"Sweat\");\n droplet.setColorFilter(Color.parseColor(\"#1b95e0\"));\n placeBloodSweatText.setText(\"Place sweat on the test strip\");\n break;\n }\n viewDelay();\n }\n });\n glucometerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n if (isChecked){\n instance.sendDataToArduino(\"G_on\");\n viewDelay();\n }else {\n instance.sendDataToArduino(\"G_off\");\n startButton.setEnabled(false);\n rbBlood.setEnabled(false);\n rbSweat.setEnabled(false);\n rb_mg_dL.setEnabled(false);\n rb_mmol_L.setEnabled(false);\n glucometerSwitch.setEnabled(false);\n viewHandler = new Handler();\n Runnable delay = new Runnable() {\n @Override\n public void run() {\n glucometerSwitch.setEnabled(true);\n }\n };\n viewHandler.postDelayed(delay, 1000);\n }\n }\n });\n rgUnits.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(RadioGroup group, int checkedId) {\n switch (checkedId) {\n case R.id.rb_mg_dL:\n \n unitsText.setText(\"mg/dL\");\n break;\n case R.id.rb_mmol_L:\n \n unitsText.setText(\"mmol/L\");\n break;\n }\n viewDelay();\n }\n });\n detailsBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n \n Intent intent = new Intent(GlucometerActivity.this, GlucoseReadingDetailsActivity.class);\n intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);\n startActivity(intent);\n }\n });\n anotherReadingBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n instance.setReading(false);\n glucometerSwitch.setEnabled(true);\n rbBlood.setEnabled(true);\n rbSweat.setEnabled(true);\n rb_mg_dL.setEnabled(true);\n rb_mmol_L.setEnabled(true);\n startButton.setEnabled(true);\n instance.setStringData(null);\n instance.setCommand(null);\n unitsText.setVisibility(View.INVISIBLE);\n glucoseLevelText.setVisibility(View.INVISIBLE);\n descriptionTxt.setVisibility(View.INVISIBLE);\n detailsBtn.setVisibility(View.INVISIBLE);\n anotherReadingBtn.setVisibility(View.INVISIBLE);\n }\n });\n showBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n instance.setCommand(\"show\");\n }\n });\n stripBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n instance.setCommand(\"strip\");\n }\n });\n dippedBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n instance.setCommand(\"dipped\");\n }\n });\n }"},"cleancode":{"kind":"string","value":"private void setupviews() { glucometerattribution = findviewbyid(r.id.glucometerattribution); glucometerimg = findviewbyid(r.id.glucometerimg); insertstriptext = findviewbyid(r.id.insertstriptext); uparrow = findviewbyid(r.id.uparrow); droplet = findviewbyid(r.id.dropletimg); attributiontext = findviewbyid(r.id.attributiontext); placebloodsweatimg = findviewbyid(r.id.placebloodsweatimg); placebloodsweattext = findviewbyid(r.id.placebloodsweattext); waitforreadingtext = findviewbyid(r.id.waitforreadingtext); progressbar = findviewbyid(r.id.progressbar); unitstext = findviewbyid(r.id.unitstext); glucoseleveltext = findviewbyid(r.id.glucoseleveltext); descriptiontxt = findviewbyid(r.id.descriptiontxt); detailsbtn = findviewbyid(r.id.detailsbtn); anotherreadingbtn = findviewbyid(r.id.anotherreadingbtn); showbtn = findviewbyid(r.id.button7); dippedbtn = findviewbyid(r.id.button6); stripbtn = findviewbyid(r.id.button8); startbutton = findviewbyid(r.id.btnstripinserted); rgmode = findviewbyid(r.id.rgmode); rbblood = findviewbyid(r.id.rbblood); rbsweat = findviewbyid(r.id.rbsweat); rb_mg_dl = findviewbyid(r.id.rb_mg_dl); rb_mmol_l = findviewbyid(r.id.rb_mmol_l); glucometerswitch = findviewbyid(r.id.glucometerswitch); rgunits = findviewbyid(r.id.rgunits); startbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { if (!rbsweat.ischecked() && !rbblood.ischecked()) { toast.maketext(glucometeractivity.this, \"please select a mode\", toast.length_short).show(); } else { instance.senddatatoarduino(\"start\"); instance.setreading(true); glucometerswitch.setenabled(false); rbblood.setenabled(false); rbsweat.setenabled(false); rb_mg_dl.setenabled(false); rb_mmol_l.setenabled(false); startbutton.setenabled(false); glucometerimg.setvisibility(view.visible); glucometerattribution.setvisibility(view.visible); insertstriptext.setvisibility(view.visible); uparrow.setvisibility(view.visible); } } }); rgmode.setoncheckedchangelistener(new radiogroup.oncheckedchangelistener() { @override public void oncheckedchanged(radiogroup group, int checkedid) { switch (checkedid) { case r.id.rbblood: instance.senddatatoarduino(\"blood\"); droplet.setcolorfilter(color.parsecolor(\"#f44336\")); placebloodsweattext.settext(\"place blood on the test strip\"); break; case r.id.rbsweat: instance.senddatatoarduino(\"sweat\"); droplet.setcolorfilter(color.parsecolor(\"#1b95e0\")); placebloodsweattext.settext(\"place sweat on the test strip\"); break; } viewdelay(); } }); glucometerswitch.setoncheckedchangelistener(new compoundbutton.oncheckedchangelistener() { @override public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) { if (ischecked){ instance.senddatatoarduino(\"g_on\"); viewdelay(); }else { instance.senddatatoarduino(\"g_off\"); startbutton.setenabled(false); rbblood.setenabled(false); rbsweat.setenabled(false); rb_mg_dl.setenabled(false); rb_mmol_l.setenabled(false); glucometerswitch.setenabled(false); viewhandler = new handler(); runnable delay = new runnable() { @override public void run() { glucometerswitch.setenabled(true); } }; viewhandler.postdelayed(delay, 1000); } } }); rgunits.setoncheckedchangelistener(new radiogroup.oncheckedchangelistener() { @override public void oncheckedchanged(radiogroup group, int checkedid) { switch (checkedid) { case r.id.rb_mg_dl: unitstext.settext(\"mg/dl\"); break; case r.id.rb_mmol_l: unitstext.settext(\"mmol/l\"); break; } viewdelay(); } }); detailsbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent intent = new intent(glucometeractivity.this, glucosereadingdetailsactivity.class); intent.addflags(intent.flag_activity_no_animation); startactivity(intent); } }); anotherreadingbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setreading(false); glucometerswitch.setenabled(true); rbblood.setenabled(true); rbsweat.setenabled(true); rb_mg_dl.setenabled(true); rb_mmol_l.setenabled(true); startbutton.setenabled(true); instance.setstringdata(null); instance.setcommand(null); unitstext.setvisibility(view.invisible); glucoseleveltext.setvisibility(view.invisible); descriptiontxt.setvisibility(view.invisible); detailsbtn.setvisibility(view.invisible); anotherreadingbtn.setvisibility(view.invisible); } }); showbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand(\"show\"); } }); stripbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand(\"strip\"); } }); dippedbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand(\"dipped\"); } }); }"},"repo":{"kind":"string","value":"W6WM9M/VitalityMeter"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":280,"cells":{"id":{"kind":"number","value":10671,"string":"10,671"},"original_code":{"kind":"string","value":"public void render(SpriteBatch batch) {\n viewport.apply();\n batch.setProjectionMatrix(viewport.getCamera().combined);\n batch.begin();\n // TODO: Draw a game over message\n // Feel free to get more creative with this screen. Perhaps you could cover the screen in enemy robots?\n float timeElapsed = Utils.secondsSince(startTime);\n int enemiesToShow = (int) (Constants.ENEMY_COUNT * (timeElapsed / Constants.LEVEL_END_DURATION));\n for (int i = 0; i < enemiesToShow; i++){\n Enemy enemy = enemies.get(i);\n enemy.update(0);\n enemy.render(batch);\n }\n font.draw(batch, Constants.GAME_OVER_MESSAGE, viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2.5f, 0, Align.center, false);\n batch.end();\n }"},"code_wo_comment":{"kind":"string","value":"public void render(SpriteBatch batch) {\n viewport.apply();\n batch.setProjectionMatrix(viewport.getCamera().combined);\n batch.begin();\n \n \n float timeElapsed = Utils.secondsSince(startTime);\n int enemiesToShow = (int) (Constants.ENEMY_COUNT * (timeElapsed / Constants.LEVEL_END_DURATION));\n for (int i = 0; i < enemiesToShow; i++){\n Enemy enemy = enemies.get(i);\n enemy.update(0);\n enemy.render(batch);\n }\n font.draw(batch, Constants.GAME_OVER_MESSAGE, viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2.5f, 0, Align.center, false);\n batch.end();\n }"},"cleancode":{"kind":"string","value":"public void render(spritebatch batch) { viewport.apply(); batch.setprojectionmatrix(viewport.getcamera().combined); batch.begin(); float timeelapsed = utils.secondssince(starttime); int enemiestoshow = (int) (constants.enemy_count * (timeelapsed / constants.level_end_duration)); for (int i = 0; i < enemiestoshow; i++){ enemy enemy = enemies.get(i); enemy.update(0); enemy.render(batch); } font.draw(batch, constants.game_over_message, viewport.getworldwidth() / 2, viewport.getworldheight() / 2.5f, 0, align.center, false); batch.end(); }"},"repo":{"kind":"string","value":"Sceptres/ud406"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":281,"cells":{"id":{"kind":"number","value":2527,"string":"2,527"},"original_code":{"kind":"string","value":"public static String getEnumI18n(Locale locale, String base, T enumToGet) {\n return Language.i18n(locale, base + \".\" + enumToGet.name().toLowerCase());\n }"},"code_wo_comment":{"kind":"string","value":"public static String getEnumI18n(Locale locale, String base, T enumToGet) {\n return Language.i18n(locale, base + \".\" + enumToGet.name().toLowerCase());\n }"},"cleancode":{"kind":"string","value":"public static string getenumi18n(locale locale, string base, t enumtoget) { return language.i18n(locale, base + \".\" + enumtoget.name().tolowercase()); }"},"repo":{"kind":"string","value":"TortleWortle/CascadeBot"},"label":{"kind":"list like","value":[0,0,0,0],"string":"[\n 0,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":282,"cells":{"id":{"kind":"number","value":10747,"string":"10,747"},"original_code":{"kind":"string","value":"public JsonObject setMaxComments(int comments){\n JsonObject result = new JsonObject();\n if( dbServices.setMaxCommentsPerVideo(comments)) {\n result.addProperty(\"msg\", \"Max comments to collect for each video is now: \" + comments);\n }\n else\n result.addProperty(\"error\",\"Failed to set max comments per video\");\n return result;\n }"},"code_wo_comment":{"kind":"string","value":"public JsonObject setMaxComments(int comments){\n JsonObject result = new JsonObject();\n if( dbServices.setMaxCommentsPerVideo(comments)) {\n result.addProperty(\"msg\", \"Max comments to collect for each video is now: \" + comments);\n }\n else\n result.addProperty(\"error\",\"Failed to set max comments per video\");\n return result;\n }"},"cleancode":{"kind":"string","value":"public jsonobject setmaxcomments(int comments){ jsonobject result = new jsonobject(); if( dbservices.setmaxcommentspervideo(comments)) { result.addproperty(\"msg\", \"max comments to collect for each video is now: \" + comments); } else result.addproperty(\"error\",\"failed to set max comments per video\"); return result; }"},"repo":{"kind":"string","value":"UCY-LINC-LAB/YouTube-Twitter-Analysis"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":283,"cells":{"id":{"kind":"number","value":2557,"string":"2,557"},"original_code":{"kind":"string","value":"static OzoneClient getOzoneClient(boolean secure) throws IOException {\n OzoneConfiguration conf = new OzoneConfiguration();\n // TODO: If you don't have OM HA configured, change the following as appropriate.\n conf.set(\"ozone.om.address\", \"9.29.173.57:9862\");\n if (disableChecksum)\n conf.set(\"ozone.client.checksum.type\", \"NONE\");\n return OzoneClientFactory.getRpcClient(conf);\n }"},"code_wo_comment":{"kind":"string","value":"static OzoneClient getOzoneClient(boolean secure) throws IOException {\n OzoneConfiguration conf = new OzoneConfiguration();\n \n conf.set(\"ozone.om.address\", \"9.29.173.57:9862\");\n if (disableChecksum)\n conf.set(\"ozone.client.checksum.type\", \"NONE\");\n return OzoneClientFactory.getRpcClient(conf);\n }"},"cleancode":{"kind":"string","value":"static ozoneclient getozoneclient(boolean secure) throws ioexception { ozoneconfiguration conf = new ozoneconfiguration(); conf.set(\"ozone.om.address\", \"9.29.173.57:9862\"); if (disablechecksum) conf.set(\"ozone.client.checksum.type\", \"none\"); return ozoneclientfactory.getrpcclient(conf); }"},"repo":{"kind":"string","value":"SincereXIA/ozonerpc2"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":284,"cells":{"id":{"kind":"number","value":10797,"string":"10,797"},"original_code":{"kind":"string","value":"@Unused\n@Doc(\"Init 'record' node\")\n@Reviewed(when = \"02/12/2020\")\n@Original(version=\"2.38.0\", path=\"lib/common/shapes.c\", name=\"record_init\", key=\"h2lcuthzwljbcjwdeidw1jiv\", definition=\"static void record_init(node_t * n)\")\npublic static void record_init(ST_Agnode_s n) {\nENTERING(\"h2lcuthzwljbcjwdeidw1jiv\",\"record_init\");\ntry {\n\tST_field_t info;\n\tfinal ST_pointf ul = new ST_pointf(), sz = new ST_pointf();\n boolean flip;\n int len;\n CString textbuf;\t\t/* temp buffer for storing labels */\n\tint sides = BOTTOM | RIGHT | TOP | LEFT;\n\t/* Always use rankdir to determine how records are laid out */\n\tflip = NOT(GD_realflip(agraphof(n)));\n\tZ.z().reclblp = ND_label(n).text;\n len = strlen(Z.z().reclblp);\n /* For some forgotten reason, an empty label is parsed into a space, so\n * we need at least two bytes in textbuf.\n */\n len = MAX(len, 1);\n textbuf = CString.gmalloc(len + 1);\n if (N(info = parse_reclbl(n, flip, NOT(0), textbuf))) {\nUNSUPPORTED(\"7iezaksu9hyxhmv3r4cp4o529\"); // \tagerr(AGERR, \"bad label format %s\\n\", ND_label(n)->text);\nUNSUPPORTED(\"8f1id7rqm71svssnxbjo0uwcu\"); // \treclblp = \"\\\\N\";\nUNSUPPORTED(\"2wv3zfqhq53941rwk4vu9p9th\"); // \tinfo = parse_reclbl(n, flip, NOT(0), textbuf);\n }\n Memory.free(textbuf);\n size_reclbl(n, info);\n sz.x = POINTS(ND_width(n));;\n sz.y = POINTS(ND_height(n));\n if (mapbool(late_string(n, Z.z().N_fixed, new CString(\"false\")))) {\nUNSUPPORTED(\"8iu51xbtntpdf5sc00g91djym\"); // \tif ((sz.x < info->size.x) || (sz.y < info->size.y)) {\nUNSUPPORTED(\"4vs5u30jzsrn6fpjd327xjf7r\"); // /* should check that the record really won't fit, e.g., there may be no text.\nUNSUPPORTED(\"7k6yytek9nu1ihxix2880667g\"); // \t\t\tagerr(AGWARN, \"node '%s' size may be too small\\n\", agnameof(n));\nUNSUPPORTED(\"bnetqzovnscxile7ao44kc0qd\"); // */\nUNSUPPORTED(\"flupwh3kosf3fkhkxllllt1\"); // \t}\n } else {\n\tsz.x = MAX(info.size.x, sz.x);\n\tsz.y = MAX(info.size.y, sz.y);\n }\n resize_reclbl(info, sz, mapbool(late_string(n, Z.z().N_nojustify, new CString(\"false\"))));\n ul.___(pointfof(-sz.x / 2., sz.y / 2.));\t/* FIXME - is this still true: suspected to introduce ronding error - see Kluge below */\n pos_reclbl(info, ul, sides);\n ND_width(n, PS2INCH(info.size.x));\n ND_height(n, PS2INCH(info.size.y + 1));\t/* Kluge!! +1 to fix rounding diff between layout and rendering \n\t\t\t\t\t\t otherwise we can get -1 coords in output */\n ND_shape_info(n, info);\n} finally {\nLEAVING(\"h2lcuthzwljbcjwdeidw1jiv\",\"poly_init\");\n}\n}"},"code_wo_comment":{"kind":"string","value":"@Unused\n@Doc(\"Init 'record' node\")\n@Reviewed(when = \"02/12/2020\")\n@Original(version=\"2.38.0\", path=\"lib/common/shapes.c\", name=\"record_init\", key=\"h2lcuthzwljbcjwdeidw1jiv\", definition=\"static void record_init(node_t * n)\")\npublic static void record_init(ST_Agnode_s n) {\nENTERING(\"h2lcuthzwljbcjwdeidw1jiv\",\"record_init\");\ntry {\n\tST_field_t info;\n\tfinal ST_pointf ul = new ST_pointf(), sz = new ST_pointf();\n boolean flip;\n int len;\n CString textbuf;\t\n\tint sides = BOTTOM | RIGHT | TOP | LEFT;\n\n\tflip = NOT(GD_realflip(agraphof(n)));\n\tZ.z().reclblp = ND_label(n).text;\n len = strlen(Z.z().reclblp);\n \n len = MAX(len, 1);\n textbuf = CString.gmalloc(len + 1);\n if (N(info = parse_reclbl(n, flip, NOT(0), textbuf))) {\nUNSUPPORTED(\"7iezaksu9hyxhmv3r4cp4o529\");\nUNSUPPORTED(\"8f1id7rqm71svssnxbjo0uwcu\");\nUNSUPPORTED(\"2wv3zfqhq53941rwk4vu9p9th\");\n }\n Memory.free(textbuf);\n size_reclbl(n, info);\n sz.x = POINTS(ND_width(n));;\n sz.y = POINTS(ND_height(n));\n if (mapbool(late_string(n, Z.z().N_fixed, new CString(\"false\")))) {\nUNSUPPORTED(\"8iu51xbtntpdf5sc00g91djym\");\nUNSUPPORTED(\"4vs5u30jzsrn6fpjd327xjf7r\");\nUNSUPPORTED(\"7k6yytek9nu1ihxix2880667g\");\nUNSUPPORTED(\"bnetqzovnscxile7ao44kc0qd\");\nUNSUPPORTED(\"flupwh3kosf3fkhkxllllt1\");\n } else {\n\tsz.x = MAX(info.size.x, sz.x);\n\tsz.y = MAX(info.size.y, sz.y);\n }\n resize_reclbl(info, sz, mapbool(late_string(n, Z.z().N_nojustify, new CString(\"false\"))));\n ul.___(pointfof(-sz.x / 2., sz.y / 2.));\n pos_reclbl(info, ul, sides);\n ND_width(n, PS2INCH(info.size.x));\n ND_height(n, PS2INCH(info.size.y + 1));\n ND_shape_info(n, info);\n} finally {\nLEAVING(\"h2lcuthzwljbcjwdeidw1jiv\",\"poly_init\");\n}\n}"},"cleancode":{"kind":"string","value":"@unused @doc(\"init 'record' node\") @reviewed(when = \"02/12/2020\") @original(version=\"2.38.0\", path=\"lib/common/shapes.c\", name=\"record_init\", key=\"h2lcuthzwljbcjwdeidw1jiv\", definition=\"static void record_init(node_t * n)\") public static void record_init(st_agnode_s n) { entering(\"h2lcuthzwljbcjwdeidw1jiv\",\"record_init\"); try { st_field_t info; final st_pointf ul = new st_pointf(), sz = new st_pointf(); boolean flip; int len; cstring textbuf; int sides = bottom | right | top | left; flip = not(gd_realflip(agraphof(n))); z.z().reclblp = nd_label(n).text; len = strlen(z.z().reclblp); len = max(len, 1); textbuf = cstring.gmalloc(len + 1); if (n(info = parse_reclbl(n, flip, not(0), textbuf))) { unsupported(\"7iezaksu9hyxhmv3r4cp4o529\"); unsupported(\"8f1id7rqm71svssnxbjo0uwcu\"); unsupported(\"2wv3zfqhq53941rwk4vu9p9th\"); } memory.free(textbuf); size_reclbl(n, info); sz.x = points(nd_width(n));; sz.y = points(nd_height(n)); if (mapbool(late_string(n, z.z().n_fixed, new cstring(\"false\")))) { unsupported(\"8iu51xbtntpdf5sc00g91djym\"); unsupported(\"4vs5u30jzsrn6fpjd327xjf7r\"); unsupported(\"7k6yytek9nu1ihxix2880667g\"); unsupported(\"bnetqzovnscxile7ao44kc0qd\"); unsupported(\"flupwh3kosf3fkhkxllllt1\"); } else { sz.x = max(info.size.x, sz.x); sz.y = max(info.size.y, sz.y); } resize_reclbl(info, sz, mapbool(late_string(n, z.z().n_nojustify, new cstring(\"false\")))); ul.___(pointfof(-sz.x / 2., sz.y / 2.)); pos_reclbl(info, ul, sides); nd_width(n, ps2inch(info.size.x)); nd_height(n, ps2inch(info.size.y + 1)); nd_shape_info(n, info); } finally { leaving(\"h2lcuthzwljbcjwdeidw1jiv\",\"poly_init\"); } }"},"repo":{"kind":"string","value":"SandraBSofiaH/Final-UMldoclet"},"label":{"kind":"list like","value":[1,1,1,0],"string":"[\n 1,\n 1,\n 1,\n 0\n]"}}},{"rowIdx":285,"cells":{"id":{"kind":"number","value":19017,"string":"19,017"},"original_code":{"kind":"string","value":"private Table buildHeader() {\n Skin skin = getSkin();\n SquareButton ffBack = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-ff\"));\n ffBack.flipHorizontal();\n playBack = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-play\"), true);\n playBack.flipHorizontal();\n play = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-play\"), true);\n SquareButton ffForward = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-ff\"));\n repeatBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-repeat\"), true);\n newBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-new\"));\n newBtn.getIconCell().padTop(2).padLeft(1);\n SquareButton deleteBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-delete\"));\n upBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-play\"));\n upBtn.flipVertical();\n downBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-play\"));\n downBtn.flipVertical(); downBtn.flipHorizontal();\n Table header = new Table();\n header.setBackground(skin.getDrawable(\"timeline-top-bar-bg\"));\n Table topPart = new Table();\n Table bottomPart = new Table();\n topPart.add(ffBack).padLeft(6).left();\n //topPart.add(playBack).padLeft(6).left(); // TODO: add this back when we can support\n topPart.add(play).padLeft(6).left();\n topPart.add(ffForward).padLeft(6).left();\n topPart.add(repeatBtn).padLeft(6).left();\n topPart.add().growX().minWidth(20);\n topPart.add(upBtn).padRight(6).right();\n topPart.add(downBtn).padRight(10).right();\n topPart.add(newBtn).right().padRight(6);\n topPart.add(deleteBtn).right().padRight(6);\n topActionCell = topPart.add().right();\n typeLabel = new Label(\"Items\", skin);\n typeLabel.setColor(ColorLibrary.FONT_GRAY);\n bottomPart.add(typeLabel).padBottom(2).padLeft(5).left().expandX();\n header.add(topPart).height(33).padBottom(1).growX().row();\n header.add(bottomPart).height(16).growX().row();\n /**\n * Build header actions\n */\n ffBack.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.skipToStart);\n }\n });\n ffForward.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.skipToEnd);\n }\n });\n playBack.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.rewind);\n }\n });\n play.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.play);\n }\n });\n repeatBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.toggleLoop);\n }\n });\n deleteBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.deleteSelection);\n }\n });\n newBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.newItem);\n }\n });\n upBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.up);\n }\n });\n downBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.down);\n }\n });\n return header;\n }"},"code_wo_comment":{"kind":"string","value":"private Table buildHeader() {\n Skin skin = getSkin();\n SquareButton ffBack = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-ff\"));\n ffBack.flipHorizontal();\n playBack = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-play\"), true);\n playBack.flipHorizontal();\n play = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-play\"), true);\n SquareButton ffForward = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-ff\"));\n repeatBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-repeat\"), true);\n newBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-new\"));\n newBtn.getIconCell().padTop(2).padLeft(1);\n SquareButton deleteBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-delete\"));\n upBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-play\"));\n upBtn.flipVertical();\n downBtn = new SquareButton(skin, skin.getDrawable(\"timeline-btn-icon-play\"));\n downBtn.flipVertical(); downBtn.flipHorizontal();\n Table header = new Table();\n header.setBackground(skin.getDrawable(\"timeline-top-bar-bg\"));\n Table topPart = new Table();\n Table bottomPart = new Table();\n topPart.add(ffBack).padLeft(6).left();\n \n topPart.add(play).padLeft(6).left();\n topPart.add(ffForward).padLeft(6).left();\n topPart.add(repeatBtn).padLeft(6).left();\n topPart.add().growX().minWidth(20);\n topPart.add(upBtn).padRight(6).right();\n topPart.add(downBtn).padRight(10).right();\n topPart.add(newBtn).right().padRight(6);\n topPart.add(deleteBtn).right().padRight(6);\n topActionCell = topPart.add().right();\n typeLabel = new Label(\"Items\", skin);\n typeLabel.setColor(ColorLibrary.FONT_GRAY);\n bottomPart.add(typeLabel).padBottom(2).padLeft(5).left().expandX();\n header.add(topPart).height(33).padBottom(1).growX().row();\n header.add(bottomPart).height(16).growX().row();\n \n ffBack.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.skipToStart);\n }\n });\n ffForward.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.skipToEnd);\n }\n });\n playBack.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.rewind);\n }\n });\n play.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.play);\n }\n });\n repeatBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.toggleLoop);\n }\n });\n deleteBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.deleteSelection);\n }\n });\n newBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.newItem);\n }\n });\n upBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.up);\n }\n });\n downBtn.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n timeline.onActionButtonClicked(TimelineListener.Type.down);\n }\n });\n return header;\n }"},"cleancode":{"kind":"string","value":"private table buildheader() { skin skin = getskin(); squarebutton ffback = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-ff\")); ffback.fliphorizontal(); playback = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-play\"), true); playback.fliphorizontal(); play = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-play\"), true); squarebutton ffforward = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-ff\")); repeatbtn = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-repeat\"), true); newbtn = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-new\")); newbtn.geticoncell().padtop(2).padleft(1); squarebutton deletebtn = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-delete\")); upbtn = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-play\")); upbtn.flipvertical(); downbtn = new squarebutton(skin, skin.getdrawable(\"timeline-btn-icon-play\")); downbtn.flipvertical(); downbtn.fliphorizontal(); table header = new table(); header.setbackground(skin.getdrawable(\"timeline-top-bar-bg\")); table toppart = new table(); table bottompart = new table(); toppart.add(ffback).padleft(6).left(); toppart.add(play).padleft(6).left(); toppart.add(ffforward).padleft(6).left(); toppart.add(repeatbtn).padleft(6).left(); toppart.add().growx().minwidth(20); toppart.add(upbtn).padright(6).right(); toppart.add(downbtn).padright(10).right(); toppart.add(newbtn).right().padright(6); toppart.add(deletebtn).right().padright(6); topactioncell = toppart.add().right(); typelabel = new label(\"items\", skin); typelabel.setcolor(colorlibrary.font_gray); bottompart.add(typelabel).padbottom(2).padleft(5).left().expandx(); header.add(toppart).height(33).padbottom(1).growx().row(); header.add(bottompart).height(16).growx().row(); ffback.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.skiptostart); } }); ffforward.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.skiptoend); } }); playback.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.rewind); } }); play.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.play); } }); repeatbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.toggleloop); } }); deletebtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.deleteselection); } }); newbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.newitem); } }); upbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.up); } }); downbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.down); } }); return header; }"},"repo":{"kind":"string","value":"TheSenPie/talos"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":286,"cells":{"id":{"kind":"number","value":10974,"string":"10,974"},"original_code":{"kind":"string","value":"public Map classifyImageVGG16(IplImage iplImage) throws IOException {\n NativeImageLoader loader = new NativeImageLoader(224, 224, 3);\n BufferedImage buffImg = OpenCV.toBufferedImage(iplImage);\n INDArray image = loader.asMatrix(buffImg);\n // TODO: we should consider the model as not only the model, but also the\n // input transforms\n // for that model.\n DataNormalization scaler = new VGG16ImagePreProcessor();\n scaler.transform(image);\n INDArray[] output = vgg16.output(false, image);\n log.info(\"Complete with output from vgg16..\");\n // TODO: return a more native datastructure!\n // String predictions = TrainedModels.VGG16.decodePredictions(output[0]);\n // log.info(\"Image Predictions: {}\", predictions);\n return decodeVGG16Predictions(output[0]);\n }"},"code_wo_comment":{"kind":"string","value":"public Map classifyImageVGG16(IplImage iplImage) throws IOException {\n NativeImageLoader loader = new NativeImageLoader(224, 224, 3);\n BufferedImage buffImg = OpenCV.toBufferedImage(iplImage);\n INDArray image = loader.asMatrix(buffImg);\n \n \n \n DataNormalization scaler = new VGG16ImagePreProcessor();\n scaler.transform(image);\n INDArray[] output = vgg16.output(false, image);\n log.info(\"Complete with output from vgg16..\");\n \n \n \n return decodeVGG16Predictions(output[0]);\n }"},"cleancode":{"kind":"string","value":"public map classifyimagevgg16(iplimage iplimage) throws ioexception { nativeimageloader loader = new nativeimageloader(224, 224, 3); bufferedimage buffimg = opencv.tobufferedimage(iplimage); indarray image = loader.asmatrix(buffimg); datanormalization scaler = new vgg16imagepreprocessor(); scaler.transform(image); indarray[] output = vgg16.output(false, image); log.info(\"complete with output from vgg16..\"); return decodevgg16predictions(output[0]); }"},"repo":{"kind":"string","value":"ShaunHolt/myrobotlab"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":287,"cells":{"id":{"kind":"number","value":10975,"string":"10,975"},"original_code":{"kind":"string","value":"public Map classifyImageFileVGG16(String filename) throws IOException {\n File file = new File(filename);\n NativeImageLoader loader = new NativeImageLoader(224, 224, 3);\n INDArray image = loader.asMatrix(file);\n // TODO: we should consider the model as not only the model, but also the\n // input transforms\n // for that model.\n DataNormalization scaler = new VGG16ImagePreProcessor();\n scaler.transform(image);\n INDArray[] output = vgg16.output(false, image);\n // TODO: return a more native datastructure!\n // String predictions = TrainedModels.VGG16.decodePredictions(output[0]);\n // log.info(\"Image Predictions: {}\", predictions);\n return decodeVGG16Predictions(output[0]);\n }"},"code_wo_comment":{"kind":"string","value":"public Map classifyImageFileVGG16(String filename) throws IOException {\n File file = new File(filename);\n NativeImageLoader loader = new NativeImageLoader(224, 224, 3);\n INDArray image = loader.asMatrix(file);\n \n \n \n DataNormalization scaler = new VGG16ImagePreProcessor();\n scaler.transform(image);\n INDArray[] output = vgg16.output(false, image);\n \n \n \n return decodeVGG16Predictions(output[0]);\n }"},"cleancode":{"kind":"string","value":"public map classifyimagefilevgg16(string filename) throws ioexception { file file = new file(filename); nativeimageloader loader = new nativeimageloader(224, 224, 3); indarray image = loader.asmatrix(file); datanormalization scaler = new vgg16imagepreprocessor(); scaler.transform(image); indarray[] output = vgg16.output(false, image); return decodevgg16predictions(output[0]); }"},"repo":{"kind":"string","value":"ShaunHolt/myrobotlab"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":288,"cells":{"id":{"kind":"number","value":10994,"string":"10,994"},"original_code":{"kind":"string","value":"private long getReservedCacheSize(String uuid) {\n // TODO: Revisit the cache size after running more storage tests.\n // TODO: Figure out how to ensure ExtServices has the permissions to call\n // StorageStatsManager, because this is ignoring the cache...\n StorageManager storageManager = getSystemService(StorageManager.class);\n long freeBytes = 0;\n if (uuid == StorageManager.UUID_PRIVATE_INTERNAL) { // regular equals because of null\n freeBytes = Environment.getDataDirectory().getUsableSpace();\n } else {\n final VolumeInfo vol = storageManager.findVolumeByUuid(uuid);\n freeBytes = vol.getPath().getUsableSpace();\n }\n return Math.round(freeBytes * CACHE_RESERVE_RATIO);\n }"},"code_wo_comment":{"kind":"string","value":"private long getReservedCacheSize(String uuid) {\n \n \n \n StorageManager storageManager = getSystemService(StorageManager.class);\n long freeBytes = 0;\n if (uuid == StorageManager.UUID_PRIVATE_INTERNAL) {\n freeBytes = Environment.getDataDirectory().getUsableSpace();\n } else {\n final VolumeInfo vol = storageManager.findVolumeByUuid(uuid);\n freeBytes = vol.getPath().getUsableSpace();\n }\n return Math.round(freeBytes * CACHE_RESERVE_RATIO);\n }"},"cleancode":{"kind":"string","value":"private long getreservedcachesize(string uuid) { storagemanager storagemanager = getsystemservice(storagemanager.class); long freebytes = 0; if (uuid == storagemanager.uuid_private_internal) { freebytes = environment.getdatadirectory().getusablespace(); } else { final volumeinfo vol = storagemanager.findvolumebyuuid(uuid); freebytes = vol.getpath().getusablespace(); } return math.round(freebytes * cache_reserve_ratio); }"},"repo":{"kind":"string","value":"Y-D-Lu/rr_frameworks_base"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":289,"cells":{"id":{"kind":"number","value":11115,"string":"11,115"},"original_code":{"kind":"string","value":"public static Intent createEmailAttendeesIntent(Resources resources, String eventTitle,\n String body, List toEmails, List ccEmails, String ownerAccount) {\n List toList = toEmails;\n List ccList = ccEmails;\n if (toEmails.size() <= 0) {\n if (ccEmails.size() <= 0) {\n // TODO: Return a SEND intent if no one to email to, to at least populate\n // a draft email with the subject (and no recipients).\n throw new IllegalArgumentException(\"Both toEmails and ccEmails are empty.\");\n }\n // Email app does not work with no \"to\" recipient. Move all 'cc' to 'to'\n // in this case.\n toList = ccEmails;\n ccList = null;\n }\n // Use the event title as the email subject (prepended with 'Re: ').\n String subject = null;\n if (eventTitle != null) {\n subject = resources.getString(R.string.email_subject_prefix) + eventTitle;\n }\n // Use the SENDTO intent with a 'mailto' URI, because using SEND will cause\n // the picker to show apps like text messaging, which does not make sense\n // for email addresses. We put all data in the URI instead of using the extra\n // Intent fields (ie. EXTRA_CC, etc) because some email apps might not handle\n // those (though gmail does).\n Uri.Builder uriBuilder = new Uri.Builder();\n uriBuilder.scheme(\"mailto\");\n // We will append the first email to the 'mailto' field later (because the\n // current state of the Email app requires it). Add the remaining 'to' values\n // here. When the email codebase is updated, we can simplify this.\n if (toList.size() > 1) {\n for (int i = 1; i < toList.size(); i++) {\n // The Email app requires repeated parameter settings instead of\n // a single comma-separated list.\n uriBuilder.appendQueryParameter(\"to\", toList.get(i));\n }\n }\n // Add the subject parameter.\n if (subject != null) {\n uriBuilder.appendQueryParameter(\"subject\", subject);\n }\n // Add the subject parameter.\n if (body != null) {\n uriBuilder.appendQueryParameter(\"body\", body);\n }\n // Add the cc parameters.\n if (ccList != null && ccList.size() > 0) {\n for (String email : ccList) {\n uriBuilder.appendQueryParameter(\"cc\", email);\n }\n }\n // Insert the first email after 'mailto:' in the URI manually since Uri.Builder\n // doesn't seem to have a way to do this.\n String uri = uriBuilder.toString();\n if (uri.startsWith(\"mailto:\")) {\n StringBuilder builder = new StringBuilder(uri);\n builder.insert(7, Uri.encode(toList.get(0)));\n uri = builder.toString();\n }\n // Start the email intent. Email from the account of the calendar owner in case there\n // are multiple email accounts.\n Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));\n emailIntent.putExtra(\"fromAccountString\", ownerAccount);\n // Workaround a Email bug that overwrites the body with this intent extra. If not\n // set, it clears the body.\n if (body != null) {\n emailIntent.putExtra(Intent.EXTRA_TEXT, body);\n }\n return Intent.createChooser(emailIntent, resources.getString(R.string.email_picker_label));\n }"},"code_wo_comment":{"kind":"string","value":"public static Intent createEmailAttendeesIntent(Resources resources, String eventTitle,\n String body, List toEmails, List ccEmails, String ownerAccount) {\n List toList = toEmails;\n List ccList = ccEmails;\n if (toEmails.size() <= 0) {\n if (ccEmails.size() <= 0) {\n \n \n throw new IllegalArgumentException(\"Both toEmails and ccEmails are empty.\");\n }\n \n \n toList = ccEmails;\n ccList = null;\n }\n \n String subject = null;\n if (eventTitle != null) {\n subject = resources.getString(R.string.email_subject_prefix) + eventTitle;\n }\n \n \n \n \n \n Uri.Builder uriBuilder = new Uri.Builder();\n uriBuilder.scheme(\"mailto\");\n \n \n \n if (toList.size() > 1) {\n for (int i = 1; i < toList.size(); i++) {\n \n \n uriBuilder.appendQueryParameter(\"to\", toList.get(i));\n }\n }\n \n if (subject != null) {\n uriBuilder.appendQueryParameter(\"subject\", subject);\n }\n \n if (body != null) {\n uriBuilder.appendQueryParameter(\"body\", body);\n }\n \n if (ccList != null && ccList.size() > 0) {\n for (String email : ccList) {\n uriBuilder.appendQueryParameter(\"cc\", email);\n }\n }\n \n \n String uri = uriBuilder.toString();\n if (uri.startsWith(\"mailto:\")) {\n StringBuilder builder = new StringBuilder(uri);\n builder.insert(7, Uri.encode(toList.get(0)));\n uri = builder.toString();\n }\n \n \n Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri));\n emailIntent.putExtra(\"fromAccountString\", ownerAccount);\n \n \n if (body != null) {\n emailIntent.putExtra(Intent.EXTRA_TEXT, body);\n }\n return Intent.createChooser(emailIntent, resources.getString(R.string.email_picker_label));\n }"},"cleancode":{"kind":"string","value":"public static intent createemailattendeesintent(resources resources, string eventtitle, string body, list toemails, list ccemails, string owneraccount) { list tolist = toemails; list cclist = ccemails; if (toemails.size() <= 0) { if (ccemails.size() <= 0) { throw new illegalargumentexception(\"both toemails and ccemails are empty.\"); } tolist = ccemails; cclist = null; } string subject = null; if (eventtitle != null) { subject = resources.getstring(r.string.email_subject_prefix) + eventtitle; } uri.builder uribuilder = new uri.builder(); uribuilder.scheme(\"mailto\"); if (tolist.size() > 1) { for (int i = 1; i < tolist.size(); i++) { uribuilder.appendqueryparameter(\"to\", tolist.get(i)); } } if (subject != null) { uribuilder.appendqueryparameter(\"subject\", subject); } if (body != null) { uribuilder.appendqueryparameter(\"body\", body); } if (cclist != null && cclist.size() > 0) { for (string email : cclist) { uribuilder.appendqueryparameter(\"cc\", email); } } string uri = uribuilder.tostring(); if (uri.startswith(\"mailto:\")) { stringbuilder builder = new stringbuilder(uri); builder.insert(7, uri.encode(tolist.get(0))); uri = builder.tostring(); } intent emailintent = new intent(intent.action_sendto, uri.parse(uri)); emailintent.putextra(\"fromaccountstring\", owneraccount); if (body != null) { emailintent.putextra(intent.extra_text, body); } return intent.createchooser(emailintent, resources.getstring(r.string.email_picker_label)); }"},"repo":{"kind":"string","value":"Shusshu/Android-RecurrencePicker"},"label":{"kind":"list like","value":[0,1,1,0],"string":"[\n 0,\n 1,\n 1,\n 0\n]"}}},{"rowIdx":290,"cells":{"id":{"kind":"number","value":11181,"string":"11,181"},"original_code":{"kind":"string","value":"@NotNull\n public abstract Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z);"},"code_wo_comment":{"kind":"string","value":"@NotNull\n public abstract Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z);"},"cleancode":{"kind":"string","value":"@notnull public abstract biome getbiome(@notnull worldinfo worldinfo, int x, int y, int z);"},"repo":{"kind":"string","value":"abcd1234-byte/spigot2"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":291,"cells":{"id":{"kind":"number","value":3159,"string":"3,159"},"original_code":{"kind":"string","value":"private static void addField(SolrInputDocument doc, String fieldName, Object value, Class type, String dynamicFieldSuffix) {\n if (type.isArray())\n return; // TODO: Array types not supported yet ...\n if (dynamicFieldSuffix == null) {\n dynamicFieldSuffix = getDefaultDynamicFieldMapping(type);\n // treat strings with multiple terms as text only if using the default!\n if (\"_s\".equals(dynamicFieldSuffix)) {\n String str = (String)value;\n if (str.indexOf(\" \") != -1)\n dynamicFieldSuffix = \"_t\";\n }\n }\n if (dynamicFieldSuffix != null) // don't auto-map if we don't have a type\n doc.addField(fieldName + dynamicFieldSuffix, value);\n }"},"code_wo_comment":{"kind":"string","value":"private static void addField(SolrInputDocument doc, String fieldName, Object value, Class type, String dynamicFieldSuffix) {\n if (type.isArray())\n return;\n if (dynamicFieldSuffix == null) {\n dynamicFieldSuffix = getDefaultDynamicFieldMapping(type);\n \n if (\"_s\".equals(dynamicFieldSuffix)) {\n String str = (String)value;\n if (str.indexOf(\" \") != -1)\n dynamicFieldSuffix = \"_t\";\n }\n }\n if (dynamicFieldSuffix != null)\n doc.addField(fieldName + dynamicFieldSuffix, value);\n }"},"cleancode":{"kind":"string","value":"private static void addfield(solrinputdocument doc, string fieldname, object value, class type, string dynamicfieldsuffix) { if (type.isarray()) return; if (dynamicfieldsuffix == null) { dynamicfieldsuffix = getdefaultdynamicfieldmapping(type); if (\"_s\".equals(dynamicfieldsuffix)) { string str = (string)value; if (str.indexof(\" \") != -1) dynamicfieldsuffix = \"_t\"; } } if (dynamicfieldsuffix != null) doc.addfield(fieldname + dynamicfieldsuffix, value); }"},"repo":{"kind":"string","value":"Stratio/spark-solr"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":292,"cells":{"id":{"kind":"number","value":11407,"string":"11,407"},"original_code":{"kind":"string","value":"protected Path getRealPath2(TVFSAbstractPath path) {\n\t\tList list = new ArrayList<>();\n\t\tfor (String s : path.path) {\n\t\t\tlist.add(s);\n\t\t}\n\t\tPath p;\n\t\tif (list.isEmpty()) {\n\t\t\t//p = virtualFS.getTvFileSystem().getPath(virtualFS.getName().getName());\n\t\t\tp = fileSystem.getRootPath();\n\t\t} else {\n\t\t\tString first = \"\";\n\t\t\tString others[] = null;\n//\t\t\tif (list.size() >= 1) {\n//\t\t\t\tfirst = list.get(0);\n//\t\t\t}\n//\t\t\tif (list.size() > 1) {\n//\t\t\t\tothers = new String[list.size() - 1];\n//\n//\t\t\t\tfor (int i = 1; i < list.size(); i++) {\n//\t\t\t\t\tothers[i - 1] = list.get(i);\n//\t\t\t\t}\n//\t\t\t}\n\t\t\t//if (others == null) {\n\t\t\tp = fileSystem.getRootPath().resolve(list.stream().collect(Collectors.joining(fileSystem.getSeparator())));\n\t\t\t//p = virtualFS.getTvFileSystem().getPath(virtualFS.getName().getName(),first);\n//\t\t\t} else {\n//\t\t\t\tp = virtualFS.getTvFileSystem().getPath(first, others);\n//\t\t\t}\n\t\t}\n\t\treturn p;\n\t}"},"code_wo_comment":{"kind":"string","value":"protected Path getRealPath2(TVFSAbstractPath path) {\n\t\tList list = new ArrayList<>();\n\t\tfor (String s : path.path) {\n\t\t\tlist.add(s);\n\t\t}\n\t\tPath p;\n\t\tif (list.isEmpty()) {\n\t\t\n\t\t\tp = fileSystem.getRootPath();\n\t\t} else {\n\t\t\tString first = \"\";\n\t\t\tString others[] = null;\n\t\t\n\t\t\tp = fileSystem.getRootPath().resolve(list.stream().collect(Collectors.joining(fileSystem.getSeparator())));\n\t\t\n\t\t}\n\t\treturn p;\n\t}"},"cleancode":{"kind":"string","value":"protected path getrealpath2(tvfsabstractpath path) { list list = new arraylist<>(); for (string s : path.path) { list.add(s); } path p; if (list.isempty()) { p = filesystem.getrootpath(); } else { string first = \"\"; string others[] = null; p = filesystem.getrootpath().resolve(list.stream().collect(collectors.joining(filesystem.getseparator()))); } return p; }"},"repo":{"kind":"string","value":"abarhub/tinyvfs"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":293,"cells":{"id":{"kind":"number","value":11482,"string":"11,482"},"original_code":{"kind":"string","value":"@Override\n public void populateGui()\n {\n // Filler\n this.getFiller();\n // Items\n for (Map.Entry entry : collector.getContents().entrySet())\n {\n // Args\n Material material = entry.getKey();\n int startAmount = entry.getValue();\n double startValue = plugin.getCollectorManager().value(collector, material);\n List lore = Color.color(plugin.getConfig().getStringList(\"guis.contents.item.lore\").stream().map(text -> text.replace(\"%amount%\", String.format(\"%,d\", startAmount)).replace(\"%value%\", String.format(\"%,.1f\", startValue))).collect(Collectors.toList()));\n List components = lore.stream().map(Component::text).collect(Collectors.toList());\n // Add\n this.addItem(ItemBuilder.from(material).name(Component.text(this.getNicedEnumString(material.name()))).lore(components).asGuiItem(event ->\n {\n // Cancel\n event.setCancelled(true);\n // Args\n Player player = (Player) event.getWhoClicked();\n int amount = collector.getMaterialAmount(material);\n double total = plugin.getCollectorManager().sell(collector, material);\n // Check\n if (total == 0.0d)\n {\n // TODO: Make it so collectors don't pick up items which can't be sold\n return;\n }\n // Deposit & Inform\n plugin.getMoneyManager().pay(player.getUniqueId(), total);\n String message = plugin.getConfig().getString(\"messages.material-sold\");\n if (message != null && !message.isEmpty()) player.sendMessage(Color.color(message.replace(\"%amount%\", String.format(\"%,d\", amount)).replace(\"%material%\", this.getNicedEnumString(material.name())).replace(\"%total%\", String.format(\"%.1f\", total))));\n // Update\n this.update();\n }));\n }\n // Navigation\n this.setItem(3, 3, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color(\"Previous\"))).asGuiItem(event -> this.previous()));\n this.setItem(3, 7, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color(\"Next\"))).asGuiItem(event -> this.next()));\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n public void populateGui()\n {\n \n this.getFiller();\n \n for (Map.Entry entry : collector.getContents().entrySet())\n {\n \n Material material = entry.getKey();\n int startAmount = entry.getValue();\n double startValue = plugin.getCollectorManager().value(collector, material);\n List lore = Color.color(plugin.getConfig().getStringList(\"guis.contents.item.lore\").stream().map(text -> text.replace(\"%amount%\", String.format(\"%,d\", startAmount)).replace(\"%value%\", String.format(\"%,.1f\", startValue))).collect(Collectors.toList()));\n List components = lore.stream().map(Component::text).collect(Collectors.toList());\n \n this.addItem(ItemBuilder.from(material).name(Component.text(this.getNicedEnumString(material.name()))).lore(components).asGuiItem(event ->\n {\n \n event.setCancelled(true);\n \n Player player = (Player) event.getWhoClicked();\n int amount = collector.getMaterialAmount(material);\n double total = plugin.getCollectorManager().sell(collector, material);\n \n if (total == 0.0d)\n {\n \n return;\n }\n \n plugin.getMoneyManager().pay(player.getUniqueId(), total);\n String message = plugin.getConfig().getString(\"messages.material-sold\");\n if (message != null && !message.isEmpty()) player.sendMessage(Color.color(message.replace(\"%amount%\", String.format(\"%,d\", amount)).replace(\"%material%\", this.getNicedEnumString(material.name())).replace(\"%total%\", String.format(\"%.1f\", total))));\n \n this.update();\n }));\n }\n \n this.setItem(3, 3, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color(\"Previous\"))).asGuiItem(event -> this.previous()));\n this.setItem(3, 7, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color(\"Next\"))).asGuiItem(event -> this.next()));\n }"},"cleancode":{"kind":"string","value":"@override public void populategui() { this.getfiller(); for (map.entry entry : collector.getcontents().entryset()) { material material = entry.getkey(); int startamount = entry.getvalue(); double startvalue = plugin.getcollectormanager().value(collector, material); list lore = color.color(plugin.getconfig().getstringlist(\"guis.contents.item.lore\").stream().map(text -> text.replace(\"%amount%\", string.format(\"%,d\", startamount)).replace(\"%value%\", string.format(\"%,.1f\", startvalue))).collect(collectors.tolist())); list components = lore.stream().map(component::text).collect(collectors.tolist()); this.additem(itembuilder.from(material).name(component.text(this.getnicedenumstring(material.name()))).lore(components).asguiitem(event -> { event.setcancelled(true); player player = (player) event.getwhoclicked(); int amount = collector.getmaterialamount(material); double total = plugin.getcollectormanager().sell(collector, material); if (total == 0.0d) { return; } plugin.getmoneymanager().pay(player.getuniqueid(), total); string message = plugin.getconfig().getstring(\"messages.material-sold\"); if (message != null && !message.isempty()) player.sendmessage(color.color(message.replace(\"%amount%\", string.format(\"%,d\", amount)).replace(\"%material%\", this.getnicedenumstring(material.name())).replace(\"%total%\", string.format(\"%.1f\", total)))); this.update(); })); } this.setitem(3, 3, itembuilder.from(material.arrow).name(component.text(color.color(\"previous\"))).asguiitem(event -> this.previous())); this.setitem(3, 7, itembuilder.from(material.arrow).name(component.text(color.color(\"next\"))).asguiitem(event -> this.next())); }"},"repo":{"kind":"string","value":"Workinq/AsyncCollectors"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":294,"cells":{"id":{"kind":"number","value":3400,"string":"3,400"},"original_code":{"kind":"string","value":"protected List updateProvisioning(Map artifacts, Provisioner provisionService) throws Exception {\n ResourceInstaller resourceInstaller = provisionService.getResourceInstaller();\n Map installedResources = getInstalledResources(provisionService);\n Map requirements = new HashMap();\n Set> entries = artifacts.entrySet();\n List resourcesToInstall = new ArrayList();\n List resourceUrisInstalled = new ArrayList();\n updateStatus(\"installing\", null, null);\n for (Map.Entry entry : entries) {\n String name = entry.getKey();\n File file = entry.getValue();\n String coords = name;\n int idx = coords.lastIndexOf(':');\n if (idx > 0) {\n coords = name.substring(idx + 1);\n }\n // lets switch to gravia's mvn coordinates\n coords = coords.replace('/', ':');\n MavenCoordinates mvnCoords = parse(coords);\n URL url = file.toURI().toURL();\n if (url == null) {\n LOGGER.warn(\"Could not find URL for file \" + file);\n continue;\n }\n // TODO lets just detect wars for now for servlet engines - how do we decide on WildFly?\n boolean isShared = !isWar(name, file);\n Resource resource = findMavenResource(mvnCoords, url, isShared);\n if (resource == null) {\n LOGGER.warn(\"Could not find resource for \" + mvnCoords + \" and \" + url);\n } else {\n ResourceIdentity identity = resource.getIdentity();\n Resource oldResource = installedResources.remove(identity);\n if (oldResource == null && !resourcehandleMap.containsKey(identity)) {\n if (isShared) {\n // TODO lest not deploy shared stuff for now since bundles throw an exception when trying to stop them\n // which breaks the tests ;)\n LOGGER.debug(\"TODO not installing \" + (isShared ? \"shared\" : \"non-shared\") + \" resource: \" + identity);\n } else {\n LOGGER.info(\"Installing \" + (isShared ? \"shared\" : \"non-shared\") + \" resource: \" + identity);\n resourcesToInstall.add(resource);\n resourceUrisInstalled.add(name);\n }\n }\n }\n }\n for (Resource installedResource : installedResources.values()) {\n ResourceIdentity identity = installedResource.getIdentity();\n ResourceHandle resourceHandle = resourcehandleMap.get(identity);\n if (resourceHandle == null) {\n // TODO should not really happen when we can ask about the installed Resources\n LOGGER.warn(\"TODO: Cannot uninstall \" + installedResource + \" as we have no handle!\");\n } else {\n LOGGER.info(\"Uninstalling \" + installedResource);\n resourceHandle.uninstall();\n resourcehandleMap.remove(identity);\n LOGGER.info(\"Uninstalled \" + installedResource);\n }\n }\n if (resourcesToInstall.size() > 0) {\n LOGGER.info(\"Installing \" + resourcesToInstall.size() + \" resource(s)\");\n Set resourceHandles = new LinkedHashSet<>();\n ResourceInstaller.Context context = new DefaultInstallerContext(resourcesToInstall, requirements);\n for (Resource resource : resourcesToInstall) {\n resourceHandles.add(resourceInstaller.installResource(context, resource));\n }\n LOGGER.info(\"Got \" + resourceHandles.size() + \" resource handle(s)\");\n for (ResourceHandle resourceHandle : resourceHandles) {\n resourcehandleMap.put(resourceHandle.getResource().getIdentity(), resourceHandle);\n }\n }\n return resourceUrisInstalled;\n }"},"code_wo_comment":{"kind":"string","value":"protected List updateProvisioning(Map artifacts, Provisioner provisionService) throws Exception {\n ResourceInstaller resourceInstaller = provisionService.getResourceInstaller();\n Map installedResources = getInstalledResources(provisionService);\n Map requirements = new HashMap();\n Set> entries = artifacts.entrySet();\n List resourcesToInstall = new ArrayList();\n List resourceUrisInstalled = new ArrayList();\n updateStatus(\"installing\", null, null);\n for (Map.Entry entry : entries) {\n String name = entry.getKey();\n File file = entry.getValue();\n String coords = name;\n int idx = coords.lastIndexOf(':');\n if (idx > 0) {\n coords = name.substring(idx + 1);\n }\n \n coords = coords.replace('/', ':');\n MavenCoordinates mvnCoords = parse(coords);\n URL url = file.toURI().toURL();\n if (url == null) {\n LOGGER.warn(\"Could not find URL for file \" + file);\n continue;\n }\n \n boolean isShared = !isWar(name, file);\n Resource resource = findMavenResource(mvnCoords, url, isShared);\n if (resource == null) {\n LOGGER.warn(\"Could not find resource for \" + mvnCoords + \" and \" + url);\n } else {\n ResourceIdentity identity = resource.getIdentity();\n Resource oldResource = installedResources.remove(identity);\n if (oldResource == null && !resourcehandleMap.containsKey(identity)) {\n if (isShared) {\n \n \n LOGGER.debug(\"TODO not installing \" + (isShared ? \"shared\" : \"non-shared\") + \" resource: \" + identity);\n } else {\n LOGGER.info(\"Installing \" + (isShared ? \"shared\" : \"non-shared\") + \" resource: \" + identity);\n resourcesToInstall.add(resource);\n resourceUrisInstalled.add(name);\n }\n }\n }\n }\n for (Resource installedResource : installedResources.values()) {\n ResourceIdentity identity = installedResource.getIdentity();\n ResourceHandle resourceHandle = resourcehandleMap.get(identity);\n if (resourceHandle == null) {\n \n LOGGER.warn(\"TODO: Cannot uninstall \" + installedResource + \" as we have no handle!\");\n } else {\n LOGGER.info(\"Uninstalling \" + installedResource);\n resourceHandle.uninstall();\n resourcehandleMap.remove(identity);\n LOGGER.info(\"Uninstalled \" + installedResource);\n }\n }\n if (resourcesToInstall.size() > 0) {\n LOGGER.info(\"Installing \" + resourcesToInstall.size() + \" resource(s)\");\n Set resourceHandles = new LinkedHashSet<>();\n ResourceInstaller.Context context = new DefaultInstallerContext(resourcesToInstall, requirements);\n for (Resource resource : resourcesToInstall) {\n resourceHandles.add(resourceInstaller.installResource(context, resource));\n }\n LOGGER.info(\"Got \" + resourceHandles.size() + \" resource handle(s)\");\n for (ResourceHandle resourceHandle : resourceHandles) {\n resourcehandleMap.put(resourceHandle.getResource().getIdentity(), resourceHandle);\n }\n }\n return resourceUrisInstalled;\n }"},"cleancode":{"kind":"string","value":"protected list updateprovisioning(map artifacts, provisioner provisionservice) throws exception { resourceinstaller resourceinstaller = provisionservice.getresourceinstaller(); map installedresources = getinstalledresources(provisionservice); map requirements = new hashmap(); set> entries = artifacts.entryset(); list resourcestoinstall = new arraylist(); list resourceurisinstalled = new arraylist(); updatestatus(\"installing\", null, null); for (map.entry entry : entries) { string name = entry.getkey(); file file = entry.getvalue(); string coords = name; int idx = coords.lastindexof(':'); if (idx > 0) { coords = name.substring(idx + 1); } coords = coords.replace('/', ':'); mavencoordinates mvncoords = parse(coords); url url = file.touri().tourl(); if (url == null) { logger.warn(\"could not find url for file \" + file); continue; } boolean isshared = !iswar(name, file); resource resource = findmavenresource(mvncoords, url, isshared); if (resource == null) { logger.warn(\"could not find resource for \" + mvncoords + \" and \" + url); } else { resourceidentity identity = resource.getidentity(); resource oldresource = installedresources.remove(identity); if (oldresource == null && !resourcehandlemap.containskey(identity)) { if (isshared) { logger.debug(\"todo not installing \" + (isshared ? \"shared\" : \"non-shared\") + \" resource: \" + identity); } else { logger.info(\"installing \" + (isshared ? \"shared\" : \"non-shared\") + \" resource: \" + identity); resourcestoinstall.add(resource); resourceurisinstalled.add(name); } } } } for (resource installedresource : installedresources.values()) { resourceidentity identity = installedresource.getidentity(); resourcehandle resourcehandle = resourcehandlemap.get(identity); if (resourcehandle == null) { logger.warn(\"todo: cannot uninstall \" + installedresource + \" as we have no handle!\"); } else { logger.info(\"uninstalling \" + installedresource); resourcehandle.uninstall(); resourcehandlemap.remove(identity); logger.info(\"uninstalled \" + installedresource); } } if (resourcestoinstall.size() > 0) { logger.info(\"installing \" + resourcestoinstall.size() + \" resource(s)\"); set resourcehandles = new linkedhashset<>(); resourceinstaller.context context = new defaultinstallercontext(resourcestoinstall, requirements); for (resource resource : resourcestoinstall) { resourcehandles.add(resourceinstaller.installresource(context, resource)); } logger.info(\"got \" + resourcehandles.size() + \" resource handle(s)\"); for (resourcehandle resourcehandle : resourcehandles) { resourcehandlemap.put(resourcehandle.getresource().getidentity(), resourcehandle); } } return resourceurisinstalled; }"},"repo":{"kind":"string","value":"WillemJiang/fabric8"},"label":{"kind":"list like","value":[1,0,0,0],"string":"[\n 1,\n 0,\n 0,\n 0\n]"}}},{"rowIdx":295,"cells":{"id":{"kind":"number","value":3401,"string":"3,401"},"original_code":{"kind":"string","value":"private static MavenCoordinates parse(String coordinates) {\n MavenCoordinates result;\n String[] parts = coordinates.split(\":\");\n if (parts.length == 3) {\n result = MavenCoordinates.create(parts[0], parts[1], parts[2], null, null);\n } else if (parts.length == 4) {\n result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], null);\n } else if (parts.length == 5) {\n result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]);\n } else {\n throw new IllegalArgumentException(\"Invalid coordinates: \" + coordinates);\n }\n return result;\n }"},"code_wo_comment":{"kind":"string","value":"private static MavenCoordinates parse(String coordinates) {\n MavenCoordinates result;\n String[] parts = coordinates.split(\":\");\n if (parts.length == 3) {\n result = MavenCoordinates.create(parts[0], parts[1], parts[2], null, null);\n } else if (parts.length == 4) {\n result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], null);\n } else if (parts.length == 5) {\n result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]);\n } else {\n throw new IllegalArgumentException(\"Invalid coordinates: \" + coordinates);\n }\n return result;\n }"},"cleancode":{"kind":"string","value":"private static mavencoordinates parse(string coordinates) { mavencoordinates result; string[] parts = coordinates.split(\":\"); if (parts.length == 3) { result = mavencoordinates.create(parts[0], parts[1], parts[2], null, null); } else if (parts.length == 4) { result = mavencoordinates.create(parts[0], parts[1], parts[2], parts[3], null); } else if (parts.length == 5) { result = mavencoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]); } else { throw new illegalargumentexception(\"invalid coordinates: \" + coordinates); } return result; }"},"repo":{"kind":"string","value":"WillemJiang/fabric8"},"label":{"kind":"list like","value":[0,0,1,0],"string":"[\n 0,\n 0,\n 1,\n 0\n]"}}},{"rowIdx":296,"cells":{"id":{"kind":"number","value":19814,"string":"19,814"},"original_code":{"kind":"string","value":"@Override\n public void validateDataOnEntry()\n throws DataModelException {\n // TODO auto-generated method stub, to be implemented by parser\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n public void validateDataOnEntry()\n throws DataModelException {\n \n }"},"cleancode":{"kind":"string","value":"@override public void validatedataonentry() throws datamodelexception { }"},"repo":{"kind":"string","value":"airlenet/yang-maven-plugin"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":297,"cells":{"id":{"kind":"number","value":19815,"string":"19,815"},"original_code":{"kind":"string","value":"@Override\n public void validateDataOnExit()\n throws DataModelException {\n // TODO auto-generated method stub, to be implemented by parser\n }"},"code_wo_comment":{"kind":"string","value":"@Override\n public void validateDataOnExit()\n throws DataModelException {\n \n }"},"cleancode":{"kind":"string","value":"@override public void validatedataonexit() throws datamodelexception { }"},"repo":{"kind":"string","value":"airlenet/yang-maven-plugin"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":298,"cells":{"id":{"kind":"number","value":19923,"string":"19,923"},"original_code":{"kind":"string","value":"@OnClick(R.id.btn_meter_set_minus)\n void decreaseLevel() {\n if (mLevelToSet == Channels.CHN_MIN_VALUE_OF_EVERYTHING) {\n return;\n }\n mLevelToSet--;\n mTextViewLevel.setText(String.format(Locale.US, \"%1$d\", mLevelToSet));\n //TODO send setting level frame and change shared prefs and display\n updateLevelForPrefsAndViewAndSendFrame(mLevelToSet);\n isLevelZero();\n }"},"code_wo_comment":{"kind":"string","value":"@OnClick(R.id.btn_meter_set_minus)\n void decreaseLevel() {\n if (mLevelToSet == Channels.CHN_MIN_VALUE_OF_EVERYTHING) {\n return;\n }\n mLevelToSet--;\n mTextViewLevel.setText(String.format(Locale.US, \"%1$d\", mLevelToSet));\n \n updateLevelForPrefsAndViewAndSendFrame(mLevelToSet);\n isLevelZero();\n }"},"cleancode":{"kind":"string","value":"@onclick(r.id.btn_meter_set_minus) void decreaselevel() { if (mleveltoset == channels.chn_min_value_of_everything) { return; } mleveltoset--; mtextviewlevel.settext(string.format(locale.us, \"%1$d\", mleveltoset)); updatelevelforprefsandviewandsendframe(mleveltoset); islevelzero(); }"},"repo":{"kind":"string","value":"SirdarYangK/SirdarYKCode"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}},{"rowIdx":299,"cells":{"id":{"kind":"number","value":19924,"string":"19,924"},"original_code":{"kind":"string","value":"@OnClick(R.id.btn_meter_set_plus)\n void increaseLevel() {\n if (mLevelToSet == Channels.CHN_MAX_LEVEL) {\n return;\n }\n mLevelToSet++;\n mTextViewLevel.setText(String.format(Locale.US, \"%1$d\", mLevelToSet));\n //TODO send setting level frame and change shared prefs and display\n updateLevelForPrefsAndViewAndSendFrame(mLevelToSet);\n isLevelZero();\n }"},"code_wo_comment":{"kind":"string","value":"@OnClick(R.id.btn_meter_set_plus)\n void increaseLevel() {\n if (mLevelToSet == Channels.CHN_MAX_LEVEL) {\n return;\n }\n mLevelToSet++;\n mTextViewLevel.setText(String.format(Locale.US, \"%1$d\", mLevelToSet));\n \n updateLevelForPrefsAndViewAndSendFrame(mLevelToSet);\n isLevelZero();\n }"},"cleancode":{"kind":"string","value":"@onclick(r.id.btn_meter_set_plus) void increaselevel() { if (mleveltoset == channels.chn_max_level) { return; } mleveltoset++; mtextviewlevel.settext(string.format(locale.us, \"%1$d\", mleveltoset)); updatelevelforprefsandviewandsendframe(mleveltoset); islevelzero(); }"},"repo":{"kind":"string","value":"SirdarYangK/SirdarYKCode"},"label":{"kind":"list like","value":[0,1,0,0],"string":"[\n 0,\n 1,\n 0,\n 0\n]"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":2,"numItemsPerPage":100,"numTotalItems":1255,"offset":200,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjE4NzY5OSwic3ViIjoiL2RhdGFzZXRzL05hbUN5YW4vdGVzb3JvLWNvZGUiLCJleHAiOjE3NTYxOTEyOTksImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.0pRfZlrkjpqJGa5f_7OiMKvc-KFrTiixEmLKRQ1mwHsSBSDicXPrgeXhs60Ga0tTYTgx8OpKCz6egGc244FiDA","displayUrls":true},"discussionsStats":{"closed":1,"open":1,"total":2},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
id
int64
22
34.9k
original_code
stringlengths
31
107k
code_wo_comment
stringlengths
29
77.3k
cleancode
stringlengths
25
62.1k
repo
stringlengths
6
65
label
listlengths
4
4
30,822
public void checkBookmarks() throws IOException { for (Bookmark bookmark : bookmarksService.getBookmarks()) { bookmarksService.doCheck(bookmark); JavaFxUtils.getController(BookmarksController.class).bookmarksTableView.refresh(); } JavaFxUtils.getController(BookmarksController.class).tableView.setUserData(null); JavaFxUtils.getController(BookmarksController.class).webView.setUserData(null); //TODO refresh current bookmark if not SAME if (currentBookmark != null/* && JavaFxUtils.currentBookmark.getStatus() == BookmarkStatus.CHANGED*/) { JavaFxUtils.getController(BookmarksController.class).refresh(); } }
public void checkBookmarks() throws IOException { for (Bookmark bookmark : bookmarksService.getBookmarks()) { bookmarksService.doCheck(bookmark); JavaFxUtils.getController(BookmarksController.class).bookmarksTableView.refresh(); } JavaFxUtils.getController(BookmarksController.class).tableView.setUserData(null); JavaFxUtils.getController(BookmarksController.class).webView.setUserData(null); if (currentBookmark != nul) { JavaFxUtils.getController(BookmarksController.class).refresh(); } }
public void checkbookmarks() throws ioexception { for (bookmark bookmark : bookmarksservice.getbookmarks()) { bookmarksservice.docheck(bookmark); javafxutils.getcontroller(bookmarkscontroller.class).bookmarkstableview.refresh(); } javafxutils.getcontroller(bookmarkscontroller.class).tableview.setuserdata(null); javafxutils.getcontroller(bookmarkscontroller.class).webview.setuserdata(null); if (currentbookmark != nul) { javafxutils.getcontroller(bookmarkscontroller.class).refresh(); } }
LeonisX/jSite-Watcher
[ 0, 1, 0, 0 ]
22,752
public void remove( ) { // TODO Add remove operation support. }
public void remove( ) { }
public void remove( ) { }
JamesCao2048/BlizzardData
[ 0, 1, 0, 0 ]
30,989
public String longestPalindrome(String s) { // TODO:write your code here return ""; }
public String longestPalindrome(String s) { return ""; }
public string longestpalindrome(string s) { return ""; }
MessierObject111/algorithms-playground
[ 0, 1, 0, 0 ]
30,992
public File executeOptimization() throws IOException, InterruptedException { final String path = workingFile.getCanonicalPath(); // FIXME Handle the ImageFileOptimizationException in one of the optimizations so it does not impact the other optimizations. return executePngquant(executeOptipng(executePngout(executeAdvpng(executePngquant(executeOptipng(executePngout(executeAdvpng(workingFile, path), path), path), path), path), path), path), path); }
public File executeOptimization() throws IOException, InterruptedException { final String path = workingFile.getCanonicalPath(); return executePngquant(executeOptipng(executePngout(executeAdvpng(executePngquant(executeOptipng(executePngout(executeAdvpng(workingFile, path), path), path), path), path), path), path), path); }
public file executeoptimization() throws ioexception, interruptedexception { final string path = workingfile.getcanonicalpath(); return executepngquant(executeoptipng(executepngout(executeadvpng(executepngquant(executeoptipng(executepngout(executeadvpng(workingfile, path), path), path), path), path), path), path), path); }
MatthewJuliusScott/ImageOptimization
[ 1, 0, 0, 0 ]
23,231
@Test public void testValueOfJ() { // workaround to register this test as covering some part of the testee. // static variable access does not currently register as coverage . . . HasMutableStaticInitializer.noticeMe(); assertEquals(101, HasMutableStaticInitializer.j); }
@Test public void testValueOfJ() { HasMutableStaticInitializer.noticeMe(); assertEquals(101, HasMutableStaticInitializer.j); }
@test public void testvalueofj() { hasmutablestaticinitializer.noticeme(); assertequals(101, hasmutablestaticinitializer.j); }
Programming-Systems-Lab/pitest
[ 0, 1, 0, 0 ]
31,477
@Test public void testLineOfCaller() { assumeStackTraceDetailsAvailable(); DynamicConverter<ILoggingEvent> converter = new LineOfCallerConverter(); StringBuilder buf = new StringBuilder(); converter.write(buf, le); // the number below should be the line number of the previous line assertEquals("78", buf.toString()); // TODO: Refactor this test so that it does not depend on the actual line numbers of this file }
@Test public void testLineOfCaller() { assumeStackTraceDetailsAvailable(); DynamicConverter<ILoggingEvent> converter = new LineOfCallerConverter(); StringBuilder buf = new StringBuilder(); converter.write(buf, le); assertEquals("78", buf.toString()); }
@test public void testlineofcaller() { assumestacktracedetailsavailable(); dynamicconverter<iloggingevent> converter = new lineofcallerconverter(); stringbuilder buf = new stringbuilder(); converter.write(buf, le); assertequals("78", buf.tostring()); }
LinZong/logback-android
[ 0, 0, 0, 1 ]
23,314
@Override public void runOpMode() throws InterruptedException { /* Initialize the setDrivePowers system variables. The init() methods of our hardware class does all the work: */ FtcDashboard dashboard = FtcDashboard.getInstance(); Telemetry dashboardTelemetry = dashboard.getTelemetry(); robot.init(hardwareMap, this, true, false); /* Init Delay Option Select: */ // After init is pushed but before Start we can change the delay using dpad up/down // delayTimer.reset(); // Runs a loop to change certain settings while we wait to start while (!opModeIsActive()) { if (this.isStopRequested()) { // Leave the loop if STOP is pressed return; } if (gamepad1.dpad_up && (delayTimer.seconds() > 0.8)) { // Increases the amount of time we wait timeDelay += 1; delayTimer.reset(); } if (gamepad1.dpad_down && (delayTimer.seconds() > 0.8)) { // Decreases the amount of time we wait if (timeDelay > 0) { // No such thing as negative time timeDelay -= 1; } delayTimer.reset(); } if (((gamepad1.x) && delayTimer.seconds() > 0.8)) { // Changes Alliance Sides if (isRedAlliance) { isRedAlliance = false; robot.isRedAlliance = false; } else { isRedAlliance = true; robot.isRedAlliance = true; } delayTimer.reset(); } /** * LED code: */ if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.NONE) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_LAVA_PALETTE); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.ONE) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_OCEAN_PALETTE); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.FOUR) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_PARTY_PALETTE); } /** * Telemetry while waiting for PLAY: */ telemetry.addData("Delay Timer: ", timeDelay); if (isRedAlliance) { telemetry.addData("Alliance: ", "Red"); } else { telemetry.addData("Alliance: ", "Blue"); } telemetry.addData("Num of Rings", "%s",robot.eyes.getNumRings().toString()); dashboardTelemetry.addData("Num of Rings", "%s",robot.eyes.getNumRings().toString()); dashboardTelemetry.addData("Analysis", "%d", robot.eyes.pipeline.getAnalysis()); dashboardTelemetry.update(); telemetry.update(); /** * We don't need a "waitForStart()" since we've been running our own * loop all this time so that we can make some changes. */ } CatHW_Vision.UltimateGoalPipeline.numRings numRings = robot.eyes.getNumRings(); /** * Runs after hit start: * DO STUFF FOR the OPMODE!!! */ /** * Init the IMU after play so that it is not offset after * remaining idle for a minute or two... */ robot.driveClassic.IMU_Init(); // Time Delay: robot.robotWait(timeDelay); robot.driveOdo.quickDrive(-4,48,0.5, 0,3.0); for (int i = 0; i < 5; i++) { robot.robotWait(5); Log.d("catbot", String.format("Translate Time wait current %.2f %.2f %.1f ", robot.driveOdo.updatesThread.positionUpdate.returnXInches(), robot.driveOdo.updatesThread.positionUpdate.returnYInches(), robot.driveOdo.updatesThread.positionUpdate.returnOrientation() )); robot.driveOdo.quickDrive( -4,96,0.8, 0,5.0); robot.driveOdo.quickDrive(-52,96,0.8, 0,5.0); robot.driveOdo.quickDrive(-52,48,0.8, 0,5.0); robot.driveOdo.quickDrive( -4,48,0.8, 0,5.0); } /* for (int i = 0; i <= 5; i++) { robot.robotWait(5); robot.driveOdo.quickDrive( -4,96,0.3, -90,3.0); robot.driveOdo.quickDrive(-52,96,0.3, 0,3.0); robot.driveOdo.quickDrive(-52,48,0.3, 90,3.0); robot.driveOdo.quickDrive( -4,48,0.3, 0,3.0); } */ robot.driveOdo.updatesThread.stop(); }
@Override public void runOpMode() throws InterruptedException { FtcDashboard dashboard = FtcDashboard.getInstance(); Telemetry dashboardTelemetry = dashboard.getTelemetry(); robot.init(hardwareMap, this, true, false); delayTimer.reset(); while (!opModeIsActive()) { if (this.isStopRequested()) { return; } if (gamepad1.dpad_up && (delayTimer.seconds() > 0.8)) { timeDelay += 1; delayTimer.reset(); } if (gamepad1.dpad_down && (delayTimer.seconds() > 0.8)) { if (timeDelay > 0) { timeDelay -= 1; } delayTimer.reset(); } if (((gamepad1.x) && delayTimer.seconds() > 0.8)) { if (isRedAlliance) { isRedAlliance = false; robot.isRedAlliance = false; } else { isRedAlliance = true; robot.isRedAlliance = true; } delayTimer.reset(); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.NONE) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_LAVA_PALETTE); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.ONE) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_OCEAN_PALETTE); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.FOUR) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_PARTY_PALETTE); } telemetry.addData("Delay Timer: ", timeDelay); if (isRedAlliance) { telemetry.addData("Alliance: ", "Red"); } else { telemetry.addData("Alliance: ", "Blue"); } telemetry.addData("Num of Rings", "%s",robot.eyes.getNumRings().toString()); dashboardTelemetry.addData("Num of Rings", "%s",robot.eyes.getNumRings().toString()); dashboardTelemetry.addData("Analysis", "%d", robot.eyes.pipeline.getAnalysis()); dashboardTelemetry.update(); telemetry.update(); } CatHW_Vision.UltimateGoalPipeline.numRings numRings = robot.eyes.getNumRings(); robot.driveClassic.IMU_Init(); robot.robotWait(timeDelay); robot.driveOdo.quickDrive(-4,48,0.5, 0,3.0); for (int i = 0; i < 5; i++) { robot.robotWait(5); Log.d("catbot", String.format("Translate Time wait current %.2f %.2f %.1f ", robot.driveOdo.updatesThread.positionUpdate.returnXInches(), robot.driveOdo.updatesThread.positionUpdate.returnYInches(), robot.driveOdo.updatesThread.positionUpdate.returnOrientation() )); robot.driveOdo.quickDrive( -4,96,0.8, 0,5.0); robot.driveOdo.quickDrive(-52,96,0.8, 0,5.0); robot.driveOdo.quickDrive(-52,48,0.8, 0,5.0); robot.driveOdo.quickDrive( -4,48,0.8, 0,5.0); } robot.driveOdo.updatesThread.stop(); }
@override public void runopmode() throws interruptedexception { ftcdashboard dashboard = ftcdashboard.getinstance(); telemetry dashboardtelemetry = dashboard.gettelemetry(); robot.init(hardwaremap, this, true, false); delaytimer.reset(); while (!opmodeisactive()) { if (this.isstoprequested()) { return; } if (gamepad1.dpad_up && (delaytimer.seconds() > 0.8)) { timedelay += 1; delaytimer.reset(); } if (gamepad1.dpad_down && (delaytimer.seconds() > 0.8)) { if (timedelay > 0) { timedelay -= 1; } delaytimer.reset(); } if (((gamepad1.x) && delaytimer.seconds() > 0.8)) { if (isredalliance) { isredalliance = false; robot.isredalliance = false; } else { isredalliance = true; robot.isredalliance = true; } delaytimer.reset(); } if (robot.eyes.getnumrings() == cathw_vision.ultimategoalpipeline.numrings.none) { robot.lights.setdefaultcolor(revblinkinleddriver.blinkinpattern.rainbow_lava_palette); } if (robot.eyes.getnumrings() == cathw_vision.ultimategoalpipeline.numrings.one) { robot.lights.setdefaultcolor(revblinkinleddriver.blinkinpattern.rainbow_ocean_palette); } if (robot.eyes.getnumrings() == cathw_vision.ultimategoalpipeline.numrings.four) { robot.lights.setdefaultcolor(revblinkinleddriver.blinkinpattern.rainbow_party_palette); } telemetry.adddata("delay timer: ", timedelay); if (isredalliance) { telemetry.adddata("alliance: ", "red"); } else { telemetry.adddata("alliance: ", "blue"); } telemetry.adddata("num of rings", "%s",robot.eyes.getnumrings().tostring()); dashboardtelemetry.adddata("num of rings", "%s",robot.eyes.getnumrings().tostring()); dashboardtelemetry.adddata("analysis", "%d", robot.eyes.pipeline.getanalysis()); dashboardtelemetry.update(); telemetry.update(); } cathw_vision.ultimategoalpipeline.numrings numrings = robot.eyes.getnumrings(); robot.driveclassic.imu_init(); robot.robotwait(timedelay); robot.driveodo.quickdrive(-4,48,0.5, 0,3.0); for (int i = 0; i < 5; i++) { robot.robotwait(5); log.d("catbot", string.format("translate time wait current %.2f %.2f %.1f ", robot.driveodo.updatesthread.positionupdate.returnxinches(), robot.driveodo.updatesthread.positionupdate.returnyinches(), robot.driveodo.updatesthread.positionupdate.returnorientation() )); robot.driveodo.quickdrive( -4,96,0.8, 0,5.0); robot.driveodo.quickdrive(-52,96,0.8, 0,5.0); robot.driveodo.quickdrive(-52,48,0.8, 0,5.0); robot.driveodo.quickdrive( -4,48,0.8, 0,5.0); } robot.driveodo.updatesthread.stop(); }
PanzerSchnitter/UltimateGoal2020
[ 0, 0, 0, 0 ]
15,126
private void clanList(L2PcInstance activeChar, int index) { if (index < 1) { index = 1; } // header final StringBuilder html = StringUtil.startAppend(2000, "<html><body><br><br><center><br1><br1><table border=0 cellspacing=0 cellpadding=0><tr><td FIXWIDTH=15>&nbsp;</td><td width=610 height=30 align=left><a action=\"bypass _bbsclan_clanlist\"> CLAN COMMUNITY </a></td></tr></table><table border=0 cellspacing=0 cellpadding=0 width=610 bgcolor=434343><tr><td height=10></td></tr><tr><td fixWIDTH=5></td><td fixWIDTH=600><a action=\"bypass _bbsclan_clanhome;", String.valueOf((activeChar.getClan() != null) ? activeChar.getClan().getId() : 0), "\">[GO TO MY CLAN]</a>&nbsp;&nbsp;</td><td fixWIDTH=5></td></tr><tr><td height=10></td></tr></table><br><table border=0 cellspacing=0 cellpadding=2 bgcolor=5A5A5A width=610><tr><td FIXWIDTH=5></td><td FIXWIDTH=200 align=center>CLAN NAME</td><td FIXWIDTH=200 align=center>CLAN LEADER</td><td FIXWIDTH=100 align=center>CLAN LEVEL</td><td FIXWIDTH=100 align=center>CLAN MEMBERS</td><td FIXWIDTH=5></td></tr></table><img src=\"L2UI.Squareblank\" width=\"1\" height=\"5\">"); int i = 0; for (L2Clan cl : ClanTable.getInstance().getClans()) { if (i > ((index + 1) * 7)) { break; } if (i++ >= ((index - 1) * 7)) { StringUtil.append(html, "<img src=\"L2UI.SquareBlank\" width=\"610\" height=\"3\"><table border=0 cellspacing=0 cellpadding=0 width=610><tr> <td FIXWIDTH=5></td><td FIXWIDTH=200 align=center><a action=\"bypass _bbsclan_clanhome;", String.valueOf(cl.getId()), "\">", cl.getName(), "</a></td><td FIXWIDTH=200 align=center>", cl.getLeaderName(), "</td><td FIXWIDTH=100 align=center>", String.valueOf(cl.getLevel()), "</td><td FIXWIDTH=100 align=center>", String.valueOf(cl.getMembersCount()), "</td><td FIXWIDTH=5></td></tr><tr><td height=5></td></tr></table><img src=\"L2UI.SquareBlank\" width=\"610\" height=\"3\"><img src=\"L2UI.SquareGray\" width=\"610\" height=\"1\">"); } } html.append("<img src=\"L2UI.SquareBlank\" width=\"610\" height=\"2\"><table cellpadding=0 cellspacing=2 border=0><tr>"); if (index == 1) { html.append("<td><button action=\"\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } else { StringUtil.append(html, "<td><button action=\"_bbsclan_clanlist;", String.valueOf(index - 1), "\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } i = 0; int nbp = ClanTable.getInstance().getClanCount() / 8; if ((nbp * 8) != ClanTable.getInstance().getClanCount()) { nbp++; } for (i = 1; i <= nbp; i++) { if (i == index) { StringUtil.append(html, "<td> ", String.valueOf(i), " </td>"); } else { StringUtil.append(html, "<td><a action=\"bypass _bbsclan_clanlist;", String.valueOf(i), "\"> ", String.valueOf(i), " </a></td>"); } } if (index == nbp) { html.append("<td><button action=\"\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } else { StringUtil.append(html, "<td><button action=\"bypass _bbsclan_clanlist;", String.valueOf(index + 1), "\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } html.append("</tr></table><table border=0 cellspacing=0 cellpadding=0><tr><td width=610><img src=\"sek.cbui141\" width=\"610\" height=\"1\"></td></tr></table><table border=0><tr><td><combobox width=65 var=keyword list=\"Name;Ruler\"></td><td><edit var = \"Search\" width=130 height=11 length=\"16\"></td>" + // TODO: search (Write in BBS) "<td><button value=\"&$420;\" action=\"Write 5 -1 0 Search keyword keyword\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\"> </td> </tr></table><br><br></center></body></html>"); CommunityBoardHandler.separateAndSend(html.toString(), activeChar); }
private void clanList(L2PcInstance activeChar, int index) { if (index < 1) { index = 1; } final StringBuilder html = StringUtil.startAppend(2000, "<html><body><br><br><center><br1><br1><table border=0 cellspacing=0 cellpadding=0><tr><td FIXWIDTH=15>&nbsp;</td><td width=610 height=30 align=left><a action=\"bypass _bbsclan_clanlist\"> CLAN COMMUNITY </a></td></tr></table><table border=0 cellspacing=0 cellpadding=0 width=610 bgcolor=434343><tr><td height=10></td></tr><tr><td fixWIDTH=5></td><td fixWIDTH=600><a action=\"bypass _bbsclan_clanhome;", String.valueOf((activeChar.getClan() != null) ? activeChar.getClan().getId() : 0), "\">[GO TO MY CLAN]</a>&nbsp;&nbsp;</td><td fixWIDTH=5></td></tr><tr><td height=10></td></tr></table><br><table border=0 cellspacing=0 cellpadding=2 bgcolor=5A5A5A width=610><tr><td FIXWIDTH=5></td><td FIXWIDTH=200 align=center>CLAN NAME</td><td FIXWIDTH=200 align=center>CLAN LEADER</td><td FIXWIDTH=100 align=center>CLAN LEVEL</td><td FIXWIDTH=100 align=center>CLAN MEMBERS</td><td FIXWIDTH=5></td></tr></table><img src=\"L2UI.Squareblank\" width=\"1\" height=\"5\">"); int i = 0; for (L2Clan cl : ClanTable.getInstance().getClans()) { if (i > ((index + 1) * 7)) { break; } if (i++ >= ((index - 1) * 7)) { StringUtil.append(html, "<img src=\"L2UI.SquareBlank\" width=\"610\" height=\"3\"><table border=0 cellspacing=0 cellpadding=0 width=610><tr> <td FIXWIDTH=5></td><td FIXWIDTH=200 align=center><a action=\"bypass _bbsclan_clanhome;", String.valueOf(cl.getId()), "\">", cl.getName(), "</a></td><td FIXWIDTH=200 align=center>", cl.getLeaderName(), "</td><td FIXWIDTH=100 align=center>", String.valueOf(cl.getLevel()), "</td><td FIXWIDTH=100 align=center>", String.valueOf(cl.getMembersCount()), "</td><td FIXWIDTH=5></td></tr><tr><td height=5></td></tr></table><img src=\"L2UI.SquareBlank\" width=\"610\" height=\"3\"><img src=\"L2UI.SquareGray\" width=\"610\" height=\"1\">"); } } html.append("<img src=\"L2UI.SquareBlank\" width=\"610\" height=\"2\"><table cellpadding=0 cellspacing=2 border=0><tr>"); if (index == 1) { html.append("<td><button action=\"\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } else { StringUtil.append(html, "<td><button action=\"_bbsclan_clanlist;", String.valueOf(index - 1), "\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } i = 0; int nbp = ClanTable.getInstance().getClanCount() / 8; if ((nbp * 8) != ClanTable.getInstance().getClanCount()) { nbp++; } for (i = 1; i <= nbp; i++) { if (i == index) { StringUtil.append(html, "<td> ", String.valueOf(i), " </td>"); } else { StringUtil.append(html, "<td><a action=\"bypass _bbsclan_clanlist;", String.valueOf(i), "\"> ", String.valueOf(i), " </a></td>"); } } if (index == nbp) { html.append("<td><button action=\"\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } else { StringUtil.append(html, "<td><button action=\"bypass _bbsclan_clanlist;", String.valueOf(index + 1), "\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } html.append("</tr></table><table border=0 cellspacing=0 cellpadding=0><tr><td width=610><img src=\"sek.cbui141\" width=\"610\" height=\"1\"></td></tr></table><table border=0><tr><td><combobox width=65 var=keyword list=\"Name;Ruler\"></td><td><edit var = \"Search\" width=130 height=11 length=\"16\"></td>" + "<td><button value=\"&$420;\" action=\"Write 5 -1 0 Search keyword keyword\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\"> </td> </tr></table><br><br></center></body></html>"); CommunityBoardHandler.separateAndSend(html.toString(), activeChar); }
private void clanlist(l2pcinstance activechar, int index) { if (index < 1) { index = 1; } final stringbuilder html = stringutil.startappend(2000, "<html><body><br><br><center><br1><br1><table border=0 cellspacing=0 cellpadding=0><tr><td fixwidth=15>&nbsp;</td><td width=610 height=30 align=left><a action=\"bypass _bbsclan_clanlist\"> clan community </a></td></tr></table><table border=0 cellspacing=0 cellpadding=0 width=610 bgcolor=434343><tr><td height=10></td></tr><tr><td fixwidth=5></td><td fixwidth=600><a action=\"bypass _bbsclan_clanhome;", string.valueof((activechar.getclan() != null) ? activechar.getclan().getid() : 0), "\">[go to my clan]</a>&nbsp;&nbsp;</td><td fixwidth=5></td></tr><tr><td height=10></td></tr></table><br><table border=0 cellspacing=0 cellpadding=2 bgcolor=5a5a5a width=610><tr><td fixwidth=5></td><td fixwidth=200 align=center>clan name</td><td fixwidth=200 align=center>clan leader</td><td fixwidth=100 align=center>clan level</td><td fixwidth=100 align=center>clan members</td><td fixwidth=5></td></tr></table><img src=\"l2ui.squareblank\" width=\"1\" height=\"5\">"); int i = 0; for (l2clan cl : clantable.getinstance().getclans()) { if (i > ((index + 1) * 7)) { break; } if (i++ >= ((index - 1) * 7)) { stringutil.append(html, "<img src=\"l2ui.squareblank\" width=\"610\" height=\"3\"><table border=0 cellspacing=0 cellpadding=0 width=610><tr> <td fixwidth=5></td><td fixwidth=200 align=center><a action=\"bypass _bbsclan_clanhome;", string.valueof(cl.getid()), "\">", cl.getname(), "</a></td><td fixwidth=200 align=center>", cl.getleadername(), "</td><td fixwidth=100 align=center>", string.valueof(cl.getlevel()), "</td><td fixwidth=100 align=center>", string.valueof(cl.getmemberscount()), "</td><td fixwidth=5></td></tr><tr><td height=5></td></tr></table><img src=\"l2ui.squareblank\" width=\"610\" height=\"3\"><img src=\"l2ui.squaregray\" width=\"610\" height=\"1\">"); } } html.append("<img src=\"l2ui.squareblank\" width=\"610\" height=\"2\"><table cellpadding=0 cellspacing=2 border=0><tr>"); if (index == 1) { html.append("<td><button action=\"\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } else { stringutil.append(html, "<td><button action=\"_bbsclan_clanlist;", string.valueof(index - 1), "\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } i = 0; int nbp = clantable.getinstance().getclancount() / 8; if ((nbp * 8) != clantable.getinstance().getclancount()) { nbp++; } for (i = 1; i <= nbp; i++) { if (i == index) { stringutil.append(html, "<td> ", string.valueof(i), " </td>"); } else { stringutil.append(html, "<td><a action=\"bypass _bbsclan_clanlist;", string.valueof(i), "\"> ", string.valueof(i), " </a></td>"); } } if (index == nbp) { html.append("<td><button action=\"\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } else { stringutil.append(html, "<td><button action=\"bypass _bbsclan_clanlist;", string.valueof(index + 1), "\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } html.append("</tr></table><table border=0 cellspacing=0 cellpadding=0><tr><td width=610><img src=\"sek.cbui141\" width=\"610\" height=\"1\"></td></tr></table><table border=0><tr><td><combobox width=65 var=keyword list=\"name;ruler\"></td><td><edit var = \"search\" width=130 height=11 length=\"16\"></td>" + "<td><button value=\"&$420;\" action=\"write 5 -1 0 search keyword keyword\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\"> </td> </tr></table><br><br></center></body></html>"); communityboardhandler.separateandsend(html.tostring(), activechar); }
RollingSoftware/L2J_HighFive_Hardcore
[ 0, 1, 0, 0 ]
23,375
public void sendErrorEmail(RequestCycle cycle, Exception ex, IRequestLogger logger) { try { String customer = Utils.getCustomer(); Url url = cycle.getRequest().getUrl(); Url clientUrl = cycle.getRequest().getClientUrl(); String exStr = ExceptionUtils.getStackTrace(ex); String fullUrl = cycle.getUrlRenderer().renderFullUrl(url); int currUserId = 0; RequestData currRd = logger.getCurrentRequest(); String currSessId = Session.get().getId(); SessionData sd = null; if(currSessId != null) { SessionData[] sessions = logger.getLiveSessions(); for(SessionData s : sessions) { if(s.getSessionId().equals(currSessId)) { sd = s; break; } } } String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd); StringBuilder currSessStr = new StringBuilder(); if(sd != null) { currSessStr.append("id:").append(sd.getSessionId()).append('\n'); currSessStr.append("requestCount:").append(sd.getNumberOfRequests()).append('\n'); currSessStr.append("requestsTime:").append(sd.getTotalTimeTaken()).append('\n'); currSessStr.append("sessionSize:").append(Bytes.bytes(sd.getSessionSize())).append('\n'); currSessStr.append("sessionInfo:").append(sd.getSessionInfo()).append('\n'); currSessStr.append("startDate:").append(sd.getStartDate()).append('\n'); currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n'); currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n'); currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n"); } currSessStr.append("Requests: \n"); ((CustomRequestLogger)logger).getRequests(currSessStr); String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n " + "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s"; String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr); String subject = customer + " error"; //TODO send email here } catch (Exception e) { //ignore } }
public void sendErrorEmail(RequestCycle cycle, Exception ex, IRequestLogger logger) { try { String customer = Utils.getCustomer(); Url url = cycle.getRequest().getUrl(); Url clientUrl = cycle.getRequest().getClientUrl(); String exStr = ExceptionUtils.getStackTrace(ex); String fullUrl = cycle.getUrlRenderer().renderFullUrl(url); int currUserId = 0; RequestData currRd = logger.getCurrentRequest(); String currSessId = Session.get().getId(); SessionData sd = null; if(currSessId != null) { SessionData[] sessions = logger.getLiveSessions(); for(SessionData s : sessions) { if(s.getSessionId().equals(currSessId)) { sd = s; break; } } } String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd); StringBuilder currSessStr = new StringBuilder(); if(sd != null) { currSessStr.append("id:").append(sd.getSessionId()).append('\n'); currSessStr.append("requestCount:").append(sd.getNumberOfRequests()).append('\n'); currSessStr.append("requestsTime:").append(sd.getTotalTimeTaken()).append('\n'); currSessStr.append("sessionSize:").append(Bytes.bytes(sd.getSessionSize())).append('\n'); currSessStr.append("sessionInfo:").append(sd.getSessionInfo()).append('\n'); currSessStr.append("startDate:").append(sd.getStartDate()).append('\n'); currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n'); currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n'); currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n"); } currSessStr.append("Requests: \n"); ((CustomRequestLogger)logger).getRequests(currSessStr); String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n " + "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s"; String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr); String subject = customer + " error"; } catch (Exception e) { } }
public void senderroremail(requestcycle cycle, exception ex, irequestlogger logger) { try { string customer = utils.getcustomer(); url url = cycle.getrequest().geturl(); url clienturl = cycle.getrequest().getclienturl(); string exstr = exceptionutils.getstacktrace(ex); string fullurl = cycle.geturlrenderer().renderfullurl(url); int curruserid = 0; requestdata currrd = logger.getcurrentrequest(); string currsessid = session.get().getid(); sessiondata sd = null; if(currsessid != null) { sessiondata[] sessions = logger.getlivesessions(); for(sessiondata s : sessions) { if(s.getsessionid().equals(currsessid)) { sd = s; break; } } } string currreq = ((customrequestlogger)logger).createrequestdata(currrd, sd); stringbuilder currsessstr = new stringbuilder(); if(sd != null) { currsessstr.append("id:").append(sd.getsessionid()).append('\n'); currsessstr.append("requestcount:").append(sd.getnumberofrequests()).append('\n'); currsessstr.append("requeststime:").append(sd.gettotaltimetaken()).append('\n'); currsessstr.append("sessionsize:").append(bytes.bytes(sd.getsessionsize())).append('\n'); currsessstr.append("sessioninfo:").append(sd.getsessioninfo()).append('\n'); currsessstr.append("startdate:").append(sd.getstartdate()).append('\n'); currsessstr.append("lastrequesttime:").append(sd.getlastactive()).append('\n'); currsessstr.append("numberofrequests:").append(sd.getnumberofrequests()).append('\n'); currsessstr.append("totaltimetaken:").append(sd.gettotaltimetaken()).append("\n\n\n"); } currsessstr.append("requests: \n"); ((customrequestlogger)logger).getrequests(currsessstr); string template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n " + "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s"; string body = string.format(template, customer, fullurl, clienturl.tostring(), curruserid, currreq, currsessstr.tostring(), exstr); string subject = customer + " error"; } catch (exception e) { } }
RomanSery/codesnippets
[ 0, 1, 0, 0 ]
23,575
public static void main(String[] args) { // TODO Auto-generated method stub //Assuming stock of each sport is 2 Sports sp1=new IndoorSports(); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Billiards(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Carrom(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Badminton(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); Sports sp2=new OutdoorSports(); System.out.println("\nTotal Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Trekking(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Cricket(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new HighJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new LongJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); }
public static void main(String[] args) { Sports sp1=new IndoorSports(); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Billiards(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Carrom(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Badminton(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); Sports sp2=new OutdoorSports(); System.out.println("\nTotal Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Trekking(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Cricket(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new HighJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new LongJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); }
public static void main(string[] args) { sports sp1=new indoorsports(); system.out.println("total indoor sports stock:"+sp1.getcurrentstock()); sp1=new billiards(sp1); system.out.println("total indoor sports stock:"+sp1.getcurrentstock()); sp1=new carrom(sp1); system.out.println("total indoor sports stock:"+sp1.getcurrentstock()); sp1=new badminton(sp1); system.out.println("total indoor sports stock:"+sp1.getcurrentstock()); sports sp2=new outdoorsports(); system.out.println("\ntotal outdoor sports stock:"+sp2.getcurrentstock()); sp2=new trekking(sp2); system.out.println("total outdoor sports stock:"+sp2.getcurrentstock()); sp2=new cricket(sp2); system.out.println("total outdoor sports stock:"+sp2.getcurrentstock()); sp2=new highjump(sp2); system.out.println("total outdoor sports stock:"+sp2.getcurrentstock()); sp2=new longjump(sp2); system.out.println("total outdoor sports stock:"+sp2.getcurrentstock()); }
Saba-d-coder/6thSemIse
[ 1, 0, 0, 0 ]
15,413
public void put(String name, Scriptable start, Object value) { try { ObjectLocation variable = this.extractFieldVariable(name); if (value instanceof NativeArray) { // FIXME this breaks referential equality, but maybe it's OK variable.set(this.sequenceFromArray((NativeArray)value, start)); return; } //System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName()); if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc value = Context.jsToJava(value, Float.class); } else if (value instanceof ObjectLocation) { // here's a place where two locations could be bound to each other? value = ((ObjectLocation)value).get(); } else if (value instanceof Wrapper) { // FIXME is there a better way??? value = ((Wrapper)value).unwrap(); if (value instanceof ObjectLocation) { value = ((ObjectLocation)value).get(); } } variable.set(value); return; } catch (Exception e) { e.printStackTrace(System.err); } }
public void put(String name, Scriptable start, Object value) { try { ObjectLocation variable = this.extractFieldVariable(name); if (value instanceof NativeArray) { variable.set(this.sequenceFromArray((NativeArray)value, start)); return; } if (variable instanceof FloatLocation) { value = Context.jsToJava(value, Float.class); } else if (value instanceof ObjectLocation) { value = ((ObjectLocation)value).get(); } else if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); if (value instanceof ObjectLocation) { value = ((ObjectLocation)value).get(); } } variable.set(value); return; } catch (Exception e) { e.printStackTrace(System.err); } }
public void put(string name, scriptable start, object value) { try { objectlocation variable = this.extractfieldvariable(name); if (value instanceof nativearray) { variable.set(this.sequencefromarray((nativearray)value, start)); return; } if (variable instanceof floatlocation) { value = context.jstojava(value, float.class); } else if (value instanceof objectlocation) { value = ((objectlocation)value).get(); } else if (value instanceof wrapper) { value = ((wrapper)value).unwrap(); if (value instanceof objectlocation) { value = ((objectlocation)value).get(); } } variable.set(value); return; } catch (exception e) { e.printstacktrace(system.err); } }
LivelyKernel/sunlabs-kernel
[ 1, 0, 1, 0 ]
15,430
private static Method getMethod() { return method.get(0); }
private static Method getMethod() { return method.get(0); }
private static method getmethod() { return method.get(0); }
Modify24x7/ApkStringDecryptor
[ 1, 0, 0, 0 ]
15,621
private boolean initCipher() { try { //Obtain a cipher instance and configure it with the properties required for fingerprint authentication// if(this.cipher == null) { this.cipher = Cipher.getInstance( KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { e.printStackTrace(); return false; } try { if(this.secretKey == null) { this.secretKey = generateKey(); } if(this.keyStore != null) { if(!this.keystoreInitialized) { this.keyStore.load(null); this.keystoreInitialized = true; } } // key = (SecretKey) this.keyStore.getKey(keyName, null); todo needed? if(this.cipher != null) { if (!this.cipherInitialized) { this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey); this.cipherInitialized = true; } } //Return true if the cipher has been initialized successfully// return true; } catch (KeyPermanentlyInvalidatedException e) { //Return false if cipher initialization failed// return false; } catch (CertificateException //KeyStoreException | IOException //UnrecoverableKeyException | NullPointerException | NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); return false; } }
private boolean initCipher() { try { if(this.cipher == null) { this.cipher = Cipher.getInstance( KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { e.printStackTrace(); return false; } try { if(this.secretKey == null) { this.secretKey = generateKey(); } if(this.keyStore != null) { if(!this.keystoreInitialized) { this.keyStore.load(null); this.keystoreInitialized = true; } } if(this.cipher != null) { if (!this.cipherInitialized) { this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey); this.cipherInitialized = true; } } return true; } catch (KeyPermanentlyInvalidatedException e) { return false; } catch (CertificateException | IOException | NullPointerException | NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); return false; } }
private boolean initcipher() { try { if(this.cipher == null) { this.cipher = cipher.getinstance( keyproperties.key_algorithm_aes + "/" + keyproperties.block_mode_cbc + "/" + keyproperties.encryption_padding_pkcs7); } } catch (nosuchalgorithmexception | nosuchpaddingexception e) { e.printstacktrace(); return false; } try { if(this.secretkey == null) { this.secretkey = generatekey(); } if(this.keystore != null) { if(!this.keystoreinitialized) { this.keystore.load(null); this.keystoreinitialized = true; } } if(this.cipher != null) { if (!this.cipherinitialized) { this.cipher.init(cipher.encrypt_mode, this.secretkey); this.cipherinitialized = true; } } return true; } catch (keypermanentlyinvalidatedexception e) { return false; } catch (certificateexception | ioexception | nullpointerexception | nosuchalgorithmexception | invalidkeyexception e) { e.printstacktrace(); return false; } }
PGMacDesign/PGMacTips
[ 1, 0, 0, 0 ]
23,837
private void writeRunnerProject() throws IOException, XmlException, ParseException { // TODO revise whole method // TODO now using a newer JAPA (suuports java 8), -> maybe ANTLR supports better PathUtils.createDir(getRunnerProjectSettings().getBaseDir().toPath()); // copy snippets PathUtils.copy(getSnippetProject().getSourceDir(), getRunnerProjectSettings().getSnippetSourceDirectory().toPath()); // create INFO file writeInfoFile(); // remove SETTE annotations and imports from file Collection<File> filesWritten = Files .walk(getRunnerProjectSettings().getSnippetSourceDirectory().toPath()) .filter(Files::isRegularFile).map(Path::toFile).sorted() .collect(Collectors.toList()); for (File file : filesWritten) { // parse source with JavaParser log.debug("Parsing with JavaParser: {}", file); CompilationUnit compilationUnit = JavaParser.parse(file); log.debug("Parsed with JavaParser: {}", file); // extract type List<TypeDeclaration> types = compilationUnit.getTypes(); if (types.size() != 1) { // NOTE better exception type throw new RuntimeException( "Java source files containing more that one types are not supported"); } TypeDeclaration type = types.get(0); // skip file if Java version is not supported by the tool (@SetteSnippetContainer) // NOTE it can be also done with snippet containers... (and also done in CATG // generator!) List<AnnotationExpr> classAnnotations = type.getAnnotations(); JavaVersion reqJavaVer = getRequiredJavaVersion(classAnnotations); if (reqJavaVer != null && !getTool().supportsJavaVersion(reqJavaVer)) { System.err.println( "Skipping file: " + file + " (required Java version: " + reqJavaVer + ")"); PathUtils.delete(file.toPath()); } else { // remove SETTE annotations from the class Predicate<AnnotationExpr> isSetteAnnotation = (a -> a.getName().getName() .startsWith("Sette")); classAnnotations.removeIf(isSetteAnnotation); // remove SETTE annotations from the members for (BodyDeclaration member : type.getMembers()) { member.getAnnotations().removeIf(isSetteAnnotation); } // TODO enhance List<String> toRemovePrefixes = new ArrayList<>(); toRemovePrefixes.add("hu.bme.mit.sette.snippets.inputs"); toRemovePrefixes.add("hu.bme.mit.sette.common"); // remove SETTE imports compilationUnit.getImports().removeIf(importDeclaration -> { String impDecl = importDeclaration.getName().toString(); for (String prefix : toRemovePrefixes) { if (impDecl.startsWith(prefix)) { return true; } } return false; }); // save edited source code String source = compilationUnit.toString(); if (type instanceof EnumDeclaration) { // FIXME remove after javaparser bug is fixed source = source.replaceFirst(type.getName() + "\\s+implements\\s*\\{", type.getName() + " {"); } PathUtils.write(file.toPath(), source.getBytes()); } } // copy libraries if (getSnippetProject().getLibDir().toFile().exists()) { PathUtils.copy(getSnippetProject().getLibDir(), getRunnerProjectSettings().getSnippetLibraryDirectory().toPath()); } // create project this.eclipseProject.save(getRunnerProjectSettings().getBaseDir().toPath()); }
private void writeRunnerProject() throws IOException, XmlException, ParseException { PathUtils.createDir(getRunnerProjectSettings().getBaseDir().toPath()); PathUtils.copy(getSnippetProject().getSourceDir(), getRunnerProjectSettings().getSnippetSourceDirectory().toPath()); writeInfoFile(); Collection<File> filesWritten = Files .walk(getRunnerProjectSettings().getSnippetSourceDirectory().toPath()) .filter(Files::isRegularFile).map(Path::toFile).sorted() .collect(Collectors.toList()); for (File file : filesWritten) { log.debug("Parsing with JavaParser: {}", file); CompilationUnit compilationUnit = JavaParser.parse(file); log.debug("Parsed with JavaParser: {}", file); List<TypeDeclaration> types = compilationUnit.getTypes(); if (types.size() != 1) { throw new RuntimeException( "Java source files containing more that one types are not supported"); } TypeDeclaration type = types.get(0); List<AnnotationExpr> classAnnotations = type.getAnnotations(); JavaVersion reqJavaVer = getRequiredJavaVersion(classAnnotations); if (reqJavaVer != null && !getTool().supportsJavaVersion(reqJavaVer)) { System.err.println( "Skipping file: " + file + " (required Java version: " + reqJavaVer + ")"); PathUtils.delete(file.toPath()); } else { Predicate<AnnotationExpr> isSetteAnnotation = (a -> a.getName().getName() .startsWith("Sette")); classAnnotations.removeIf(isSetteAnnotation); for (BodyDeclaration member : type.getMembers()) { member.getAnnotations().removeIf(isSetteAnnotation); } List<String> toRemovePrefixes = new ArrayList<>(); toRemovePrefixes.add("hu.bme.mit.sette.snippets.inputs"); toRemovePrefixes.add("hu.bme.mit.sette.common"); compilationUnit.getImports().removeIf(importDeclaration -> { String impDecl = importDeclaration.getName().toString(); for (String prefix : toRemovePrefixes) { if (impDecl.startsWith(prefix)) { return true; } } return false; }); String source = compilationUnit.toString(); if (type instanceof EnumDeclaration) { source = source.replaceFirst(type.getName() + "\\s+implements\\s*\\{", type.getName() + " {"); } PathUtils.write(file.toPath(), source.getBytes()); } } if (getSnippetProject().getLibDir().toFile().exists()) { PathUtils.copy(getSnippetProject().getLibDir(), getRunnerProjectSettings().getSnippetLibraryDirectory().toPath()); } this.eclipseProject.save(getRunnerProjectSettings().getBaseDir().toPath()); }
private void writerunnerproject() throws ioexception, xmlexception, parseexception { pathutils.createdir(getrunnerprojectsettings().getbasedir().topath()); pathutils.copy(getsnippetproject().getsourcedir(), getrunnerprojectsettings().getsnippetsourcedirectory().topath()); writeinfofile(); collection<file> fileswritten = files .walk(getrunnerprojectsettings().getsnippetsourcedirectory().topath()) .filter(files::isregularfile).map(path::tofile).sorted() .collect(collectors.tolist()); for (file file : fileswritten) { log.debug("parsing with javaparser: {}", file); compilationunit compilationunit = javaparser.parse(file); log.debug("parsed with javaparser: {}", file); list<typedeclaration> types = compilationunit.gettypes(); if (types.size() != 1) { throw new runtimeexception( "java source files containing more that one types are not supported"); } typedeclaration type = types.get(0); list<annotationexpr> classannotations = type.getannotations(); javaversion reqjavaver = getrequiredjavaversion(classannotations); if (reqjavaver != null && !gettool().supportsjavaversion(reqjavaver)) { system.err.println( "skipping file: " + file + " (required java version: " + reqjavaver + ")"); pathutils.delete(file.topath()); } else { predicate<annotationexpr> issetteannotation = (a -> a.getname().getname() .startswith("sette")); classannotations.removeif(issetteannotation); for (bodydeclaration member : type.getmembers()) { member.getannotations().removeif(issetteannotation); } list<string> toremoveprefixes = new arraylist<>(); toremoveprefixes.add("hu.bme.mit.sette.snippets.inputs"); toremoveprefixes.add("hu.bme.mit.sette.common"); compilationunit.getimports().removeif(importdeclaration -> { string impdecl = importdeclaration.getname().tostring(); for (string prefix : toremoveprefixes) { if (impdecl.startswith(prefix)) { return true; } } return false; }); string source = compilationunit.tostring(); if (type instanceof enumdeclaration) { source = source.replacefirst(type.getname() + "\\s+implements\\s*\\{", type.getname() + " {"); } pathutils.write(file.topath(), source.getbytes()); } } if (getsnippetproject().getlibdir().tofile().exists()) { pathutils.copy(getsnippetproject().getlibdir(), getrunnerprojectsettings().getsnippetlibrarydirectory().topath()); } this.eclipseproject.save(getrunnerprojectsettings().getbasedir().topath()); }
SETTE-Testing/sette-tool
[ 1, 0, 1, 0 ]
15,691
public boolean isSubjectEmpty() { return TextUtils.getTrimmedLength(mSubject.getText()) == 0; }
public boolean isSubjectEmpty() { return TextUtils.getTrimmedLength(mSubject.getText()) == 0; }
public boolean issubjectempty() { return textutils.gettrimmedlength(msubject.gettext()) == 0; }
Keneral/apackages
[ 1, 0, 0, 0 ]
23,891
public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) { String sql2PlName = call.getPl2SQLName(this); if (sql2PlName == null) { // TODO: Error. throw new NullPointerException("no Pl2SQL conversion routine for " + typeName); } String target = databaseTypeHelper.buildTarget(outArg); sb.append(" :"); sb.append(outArg.outIndex); sb.append(" := "); sb.append(sql2PlName); sb.append("("); sb.append(target); sb.append(");"); sb.append(NL); }
public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) { String sql2PlName = call.getPl2SQLName(this); if (sql2PlName == null) { throw new NullPointerException("no Pl2SQL conversion routine for " + typeName); } String target = databaseTypeHelper.buildTarget(outArg); sb.append(" :"); sb.append(outArg.outIndex); sb.append(" := "); sb.append(sql2PlName); sb.append("("); sb.append(target); sb.append(");"); sb.append(NL); }
public void buildoutassignment(stringbuilder sb, plsqlargument outarg, plsqlstoredprocedurecall call) { string sql2plname = call.getpl2sqlname(this); if (sql2plname == null) { throw new nullpointerexception("no pl2sql conversion routine for " + typename); } string target = databasetypehelper.buildtarget(outarg); sb.append(" :"); sb.append(outarg.outindex); sb.append(" := "); sb.append(sql2plname); sb.append("("); sb.append(target); sb.append(");"); sb.append(nl); }
Pandrex247/patched-src-eclipselink
[ 0, 0, 1, 0 ]
23,901
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) { }
private void guestsearchactionperformed(java.awt.event.actionevent evt) { }
Jed-g/property-booking-system
[ 0, 1, 0, 0 ]
32,148
@Override protected void setUp() throws Exception { super.setUp(); // TODO: This test will actually mess with contacts on your phone. // Ideally we would use a fake content provider to give us contact data... FakeFactory.registerWithoutFakeContext(getTestContext()); // add test contacts. addTestContact("John", "650-123-1233", "[email protected]", false); addTestContact("Joe", "(650)123-1233", "[email protected]", false); addTestContact("Jim", "650 123 1233", "[email protected]", false); addTestContact("Samantha", "650-123-1235", "[email protected]", true); addTestContact("Adrienne", "650-123-1236", "[email protected]", true); }
@Override protected void setUp() throws Exception { super.setUp(); FakeFactory.registerWithoutFakeContext(getTestContext()); addTestContact("John", "650-123-1233", "[email protected]", false); addTestContact("Joe", "(650)123-1233", "[email protected]", false); addTestContact("Jim", "650 123 1233", "[email protected]", false); addTestContact("Samantha", "650-123-1235", "[email protected]", true); addTestContact("Adrienne", "650-123-1236", "[email protected]", true); }
@override protected void setup() throws exception { super.setup(); fakefactory.registerwithoutfakecontext(gettestcontext()); addtestcontact("john", "650-123-1233", "[email protected]", false); addtestcontact("joe", "(650)123-1233", "[email protected]", false); addtestcontact("jim", "650 123 1233", "[email protected]", false); addtestcontact("samantha", "650-123-1235", "[email protected]", true); addtestcontact("adrienne", "650-123-1236", "[email protected]", true); }
Keneral/apackages
[ 0, 0, 0, 1 ]
15,785
@Override public ItemStack transferStackInSlot(EntityPlayer player, int slot) { // TODO: Try to come up with a generic way of implementing this return null; }
@Override public ItemStack transferStackInSlot(EntityPlayer player, int slot) { return null; }
@override public itemstack transferstackinslot(entityplayer player, int slot) { return null; }
PC-Logix/GregsLighting-Reloaded
[ 1, 0, 0, 0 ]
7,631
public JSONArray getProjectRevisions(ProjectEndpoint endpoint) { //TODO need to add paging somewhere (page, items) to handle long commit histories String json = restInterface.get(TeamworkCloudEndpoints.GET_PROJECT_REVISIONS.buildUrl(endpoint.getHost(), endpoint.getCollection(), endpoint.getProject(), "true"), endpoint.getToken(), String.class); return new JSONArray(json); }
public JSONArray getProjectRevisions(ProjectEndpoint endpoint) { String json = restInterface.get(TeamworkCloudEndpoints.GET_PROJECT_REVISIONS.buildUrl(endpoint.getHost(), endpoint.getCollection(), endpoint.getProject(), "true"), endpoint.getToken(), String.class); return new JSONArray(json); }
public jsonarray getprojectrevisions(projectendpoint endpoint) { string json = restinterface.get(teamworkcloudendpoints.get_project_revisions.buildurl(endpoint.gethost(), endpoint.getcollection(), endpoint.getproject(), "true"), endpoint.gettoken(), string.class); return new jsonarray(json); }
Open-MBEE/sync-service
[ 0, 1, 0, 0 ]
24,107
public void ClearScreenTest(){ press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.binary_number_2); press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_divide); press(R.id.btn_all_clear); checkResult(""); checkBinary1(""); checkBinary2(""); }
public void ClearScreenTest(){ press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.binary_number_2); press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_divide); press(R.id.btn_all_clear); checkResult(""); checkBinary1(""); checkBinary2(""); }
public void clearscreentest(){ press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.binary_number_2); press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_divide); press(r.id.btn_all_clear); checkresult(""); checkbinary1(""); checkbinary2(""); }
ModestosV/Simple-Calculator
[ 0, 0, 0, 1 ]
24,108
public void DeleteTest(){ press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_del); checkBinary1("1000011111"); press(R.id.binary_number_2); press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_del); checkBinary2("10"); }
public void DeleteTest(){ press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_del); checkBinary1("1000011111"); press(R.id.binary_number_2); press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_del); checkBinary2("10"); }
public void deletetest(){ press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_del); checkbinary1("1000011111"); press(r.id.binary_number_2); press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_del); checkbinary2("10"); }
ModestosV/Simple-Calculator
[ 0, 0, 0, 1 ]
15,927
public int ExecuteGFXCommand(int cmd, int len, byte[] cmddata, int[] hasret) { len -= 4; // for the 4 byte header hasret[0] = 0; // Nothing to return by default // System.out.println("GFXCMD=" + cmd); // make sure the frame is still valid or we could crash on fullscreen mode switches if((cmd != GFXCMD_INIT) && (cmd != GFXCMD_DEINIT)) { if((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) { // System.out.println("GFXCMD while frame not displayable"); // spin until the frame is valid and displayable, if we don't we'll lose parts of the UI or crash while((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) { try { Thread.sleep(10); } catch(InterruptedException ex) {} } } } if (c != null) { switch(cmd) { case GFXCMD_INIT: case GFXCMD_DEINIT: case GFXCMD_STARTFRAME: case GFXCMD_FLIPBUFFER: c.setCursor(null); break; case GFXCMD_DRAWRECT: case GFXCMD_FILLRECT: case GFXCMD_CLEARRECT: case GFXCMD_DRAWOVAL: case GFXCMD_FILLOVAL: case GFXCMD_DRAWROUNDRECT: case GFXCMD_FILLROUNDRECT: case GFXCMD_DRAWTEXT: case GFXCMD_DRAWTEXTURED: case GFXCMD_DRAWLINE: case GFXCMD_LOADIMAGE: case GFXCMD_LOADIMAGETARGETED: case GFXCMD_UNLOADIMAGE: case GFXCMD_LOADFONT: case GFXCMD_UNLOADFONT: case GFXCMD_SETTARGETSURFACE: case GFXCMD_CREATESURFACE: break; case GFXCMD_PREPIMAGE: case GFXCMD_LOADIMAGELINE: case GFXCMD_LOADIMAGECOMPRESSED: case GFXCMD_XFMIMAGE: case GFXCMD_LOADCACHEDIMAGE: case GFXCMD_PREPIMAGETARGETED: if (!cursorHidden) c.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR)); break; } } switch(cmd) { case GFXCMD_INIT: hasret[0] = 1; // System.out.println("INIT"); // start up native renderer init0(); int windowTitleStyle = 0; try { windowTitleStyle = Integer.parseInt(MiniClient.myProperties.getProperty("window_title_style", "0")); } catch (NumberFormatException e){} if (!"true".equals(MiniClient.myProperties.getProperty("enable_custom_title_bar", MiniClient.MAC_OS_X ? "false" : "true"))) windowTitleStyle = 10; // platform default f = new MiniClientWindow(myConn.getWindowTitle(), windowTitleStyle); java.awt.LayoutManager layer = new java.awt.LayoutManager() { public void addLayoutComponent(String name, java.awt.Component comp) {} public java.awt.Dimension minimumLayoutSize(java.awt.Container parent) { return preferredLayoutSize(parent); } public java.awt.Dimension preferredLayoutSize(java.awt.Container parent) { return parent.getPreferredSize(); } public void removeLayoutComponent(java.awt.Component comp) {} public void layoutContainer(java.awt.Container parent) { c.setBounds(parent.getInsets().left, parent.getInsets().top, parent.getWidth() - parent.getInsets().left - parent.getInsets().right, parent.getHeight() - parent.getInsets().top - parent.getInsets().bottom); //System.out.println("LAYOUT frame bounds=" + f.getBounds() + " videoBounds=" + videoBounds + " parentBounds=" + parent.getBounds()); } }; f.getContentPane().setLayout(layer); try { bgImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/Background.jpg")); ensureImageIsLoaded(bgImage); logoImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/SageLogo256.png")); ensureImageIsLoaded(logoImage); } catch (Exception e) { System.out.println("ERROR:" + e); e.printStackTrace(); } f.setFocusTraversalKeysEnabled(false); /* if not connecting to localhost: - draw background to bounds (scaled) - draw logo to {{2% from left, 15% from top}{20% view width, 7% view height}}, no clipping, alpha = 0.85, adjust size to keep aspect ratio - load Arial 32 bold - draw the following text, double spaced using Arial 32 bold, white with black shadow (offset by (+2,+2)) "SageTV Placeshifter is connecting to" "the server: "+myConn.getServerName() "Please Wait..." text is centered in the view on the middle line, use font metrics to determine proper location g.setFont(pleaseWaitFont); g.setColor(java.awt.Color.black); y += 2; g.drawString(str1, 2 + (getWidth()/2) - (fm.stringWidth(str1)/2), y + fm.getAscent()); y += fm.getHeight(); g.drawString(str2, 2 + (getWidth()/2) - (fm.stringWidth(str2)/2), y + fm.getAscent()); y += 2*fm.getHeight(); g.drawString(str3, 2 + (getWidth()/2) - (fm.stringWidth(str3)/2), y + fm.getAscent()); g.setColor(java.awt.Color.white); y = (getHeight() / 2) - fh/2; g.drawString(str1, (getWidth()/2) - (fm.stringWidth(str1)/2), y + fm.getAscent()); y += fm.getHeight(); g.drawString(str2, (getWidth()/2) - (fm.stringWidth(str2)/2), y + fm.getAscent()); y += 2*fm.getHeight(); g.drawString(str3, (getWidth()/2) - (fm.stringWidth(str3)/2), y + fm.getAscent()); */ java.awt.Dimension panelSize = f.getContentPane().getSize(); c = new QuartzRendererView(); c.setSize(panelSize); c.setFocusTraversalKeysEnabled(false); f.getContentPane().add(c); try { java.awt.Image frameIcon = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/tvicon.gif")); ensureImageIsLoaded(frameIcon); f.setIconImage(frameIcon); } catch (Exception e) { System.out.println("ERROR:" + e); e.printStackTrace(); } f.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { if (!f.isFullScreen() || System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) { MiniClient.myProperties.setProperty("main_window_width", Integer.toString(f.getWidth())); MiniClient.myProperties.setProperty("main_window_height", Integer.toString(f.getHeight())); MiniClient.myProperties.setProperty("main_window_x", Integer.toString(f.getX())); MiniClient.myProperties.setProperty("main_window_y", Integer.toString(f.getY())); } myConn.close(); /* try { if (myConn.getMediaCmd().getPlaya() != null) { myConn.getMediaCmd().getPlaya().stop(); myConn.getMediaCmd().getPlaya().free(); } }catch (Exception e){} System.exit(0);*/ close(); // f.dispose(); } }); c.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { myConn.postResizeEvent(new java.awt.Dimension(c.getWidth(), c.getHeight())); } }); f.addKeyListener(this); c.addKeyListener(this); //f.addMouseListener(this); f.addMouseWheelListener(this); c.addMouseListener(this); if (ENABLE_MOUSE_MOTION_EVENTS) { //f.addMouseMotionListener(this); c.addMouseMotionListener(this); } int frameX = 100; int frameY = 100; int frameW = 720; int frameH = 480; try { frameW = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_width", "720")); frameH = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_height", "480")); frameX = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_x", "100")); frameY = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_y", "100")); } catch (NumberFormatException e){} java.awt.Point newPos = new java.awt.Point(frameX, frameY); boolean foundScreen = sage.UIUtils.isPointOnAScreen(newPos); if (!foundScreen) { newPos.x = 150; newPos.y = 150; } f.setVisible(true); f.setSize(1,1); f.setSize(Math.max(frameW, 320), Math.max(frameH, 240)); f.setLocation(newPos); if (MiniClient.fsStartup) f.setFullScreen(true); MiniClient.hideSplash(); // f.setVisible(true); return 1; case GFXCMD_DEINIT: // System.out.println("DEINIT"); close(); break; case GFXCMD_DRAWRECT: if(len==36) { float x, y, width, height; int thickness, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); // System.out.println("DRAWRECT: dest=("+x+","+y+" "+width+"x"+height+") thickness="+thickness+" argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); // FIXME: no gradients on framed rects yet... drawRect0(new java.awt.geom.Rectangle2D.Float(x, y, width, height), null, 0, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWRECT : " + len); } break; case GFXCMD_FILLRECT: // x, y, width, height, argbTL, argbTR, argbBR, argbBL if(len==32) { float x, y, width, height; int argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); // System.out.println("FILLRECT: dest=("+x+","+y+" "+width+"x"+height+") argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); if(gp != null) { drawRect0(bounds, null, 0, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), //(float)((argbTL>>24)&0xff)/255.0f); 1.0f); // alpha already supplied } else { drawRect0(bounds, null, 0, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLRECT : " + len); } break; case GFXCMD_CLEARRECT: // x, y, width, height, argbTL, argbTR, argbBR, argbBL if(len==32) { int x, y, width, height, argbTL, argbTR, argbBR, argbBL; x=readInt(0, cmddata); y=readInt(4, cmddata); width=readInt(8, cmddata); height=readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); // System.out.println("CLEARRECT: dest=("+x+","+y+" "+width+"x"+height+") argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); java.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x, y, width, height); clearRect0(destRect); } else { System.out.println("Invalid len for GFXCMD_CLEARRECT : " + len); } break; case GFXCMD_DRAWOVAL: // x, y, width, height, thickness, argbTL, argbTR, argbBR, argbBL, // clipX, clipY, clipW, clipH if(len==52) { float x, y, width, height, clipX, clipY, clipW, clipH; int thickness, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); clipX=(float)readInt(36, cmddata); clipY=(float)readInt(40, cmddata); clipW=(float)readInt(44, cmddata); clipH=(float)readInt(48, cmddata); // System.out.println("DRAWOVAL: dest=("+x+","+y+" "+width+"x"+height+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") thickness="+thickness+" argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); // FIXME: no gradient for framed ovals java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); drawOval0(bounds, clipRect, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWOVAL : " + len); } break; case GFXCMD_FILLOVAL: // x, y, width, height, argbTL, argbTR, argbBR, argbBL, // clipX, clipY, clipW, clipH if(len==48) { float x, y, width, height, clipX, clipY, clipW, clipH; int argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); clipX=(float)readInt(32, cmddata); clipY=(float)readInt(36, cmddata); clipW=(float)readInt(40, cmddata); clipH=(float)readInt(44, cmddata); // System.out.println("FILLOVAL: dest=("+x+","+y+" "+width+"x"+height+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); if(gp != null) { drawOval0(bounds, clipRect, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), 1.0f); } else { drawOval0(bounds, clipRect, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLOVAL : " + len); } break; case GFXCMD_DRAWROUNDRECT: // x, y, width, height, thickness, arcRadius, argbTL, argbTR, argbBR, argbBL, // clipX, clipY, clipW, clipH if(len==56) { float x, y, width, height, clipX, clipY, clipW, clipH; int thickness, arcRadius, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); arcRadius=readInt(20, cmddata); argbTL=readInt(24, cmddata); argbTR=readInt(28, cmddata); argbBR=readInt(32, cmddata); argbBL=readInt(36, cmddata); clipX=(float)readInt(40, cmddata); clipY=(float)readInt(44, cmddata); clipW=(float)readInt(48, cmddata); clipH=(float)readInt(52, cmddata); // System.out.println("DRAWROUNDRECT: dest=("+x+","+y+" "+width+"x"+height+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") thickness="+thickness+" arcRadius="+arcRadius+" argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); // FIXME: no gradients on stroked shapes java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); drawRect0(bounds, clipRect, arcRadius, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWROUNDRECT : " + len); } break; case GFXCMD_FILLROUNDRECT: // x, y, width, height, arcRadius, argbTL, argbTR, argbBR, argbBL, // clipX, clipY, clipW, clipH if(len==52) { float x, y, width, height, clipX, clipY, clipW, clipH; int arcRadius, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); arcRadius=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); clipX=(float)readInt(36, cmddata); clipY=(float)readInt(40, cmddata); clipW=(float)readInt(44, cmddata); clipH=(float)readInt(48, cmddata); // System.out.println("FILLROUNDRECT: dest=("+x+","+y+" "+width+"x"+height+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") arcRadius="+arcRadius+" argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); if(gp != null) { drawRect0(bounds, clipRect, arcRadius, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), //(float)((argbTL>>24)&0xff)/255.0f); 1.0f); } else { drawRect0(bounds, clipRect, arcRadius, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLROUNDRECT : " + len); } break; case GFXCMD_DRAWTEXT: // x, y, len, text, handle, argb, clipX, clipY, clipW, clipH if(len>=36 && len>=(36+readInt(8, cmddata)*2)) { float x, y, clipX, clipY, clipW, clipH; int textlen, fontHandle, argb; StringBuffer text = new StringBuffer(); int i; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); textlen=readInt(8, cmddata); for(i=0;i<textlen;i++) { text.append((char)readShort(12+i*2, cmddata)); } fontHandle=readInt(textlen*2+12, cmddata); argb=readInt(textlen*2+16, cmddata); clipX=(float)readInt(textlen*2+20, cmddata); clipY=(float)readInt(textlen*2+24, cmddata); clipW=(float)readInt(textlen*2+28, cmddata); clipH=(float)readInt(textlen*2+32, cmddata); // TODO: check if this is needed // if (System.getProperty("java.version").startsWith("1.4")) // clipW = clipW * 5 / 4; // System.out.println("DRAWTEXT: dest=("+x+","+y+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") fontHandle="+fontHandle+" argb="+Integer.toHexString(argb)+" text="+text.toString()); McFont fontPtr = (McFont)fontMap.get(new Integer(fontHandle)); if(fontPtr != null) { // use AWT string bounds or we'll clip on occasion String theString = text.toString(); // java.awt.Dimension textSize = fontPtr.getStringSize(theString); float[] positions = fontPtr.getGlyphPositions(theString); // System.out.println("drawText: \""+theString+"\" loc=("+x+","+y+") num positions="+positions.length); drawTextWithPositions0(theString, fontPtr.nativeFont, x, y, positions, new java.awt.geom.Rectangle2D.Float(clipX,clipY,clipW,clipH), new java.awt.Color(argb, true)); } } else { System.out.println("Invalid len for GFXCMD_DRAWTEXT : " + len); } break; case GFXCMD_DRAWTEXTURED: // x, y, width, height, handle, srcx, srcy, srcwidth, srcheight, blend if(len==40) { float x, y, width, height, srcx, srcy, srcwidth, srcheight; int handle, blend; // blend is a color, use alpha component for blending x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); handle=readInt(16, cmddata); // either an image handle or layer handle (if not in imageMap) srcx=(float)readInt(20, cmddata); srcy=(float)readInt(24, cmddata); srcwidth=(float)readInt(28, cmddata); srcheight=(float)readInt(32, cmddata); blend=readInt(36, cmddata); /* if height < 0 disable blending if width < 0 (font mode, composite with background and blend with given color) blend with full RGBA color else blend with alpha only */ // System.out.println("DRAWTEXTURED: handle="+handle+" dest=("+x+","+y+" "+width+"x"+height+") src=("+srcx+","+srcy+" "+srcwidth+"x"+srcheight+") blend="+Integer.toHexString(blend)); boolean doBlend = true; if(height < 0) { doBlend = false; height *= -1; } if(width < 0) { width *= -1; } else { if(doBlend) blend |= 0x00ffffff; // only use alpha } Long imagePtr = (Long)imageMap.get(new Integer(handle)); java.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x,y,width,height); java.awt.geom.Rectangle2D.Float srcRect = new java.awt.geom.Rectangle2D.Float(srcx,srcy,srcwidth,srcheight); if(imagePtr != null) { myConn.registerImageAccess(handle); // System.out.println(" (drawing image) imagePtr="+imagePtr); drawImage1(imagePtr.longValue(), destRect, srcRect, (doBlend) ? new java.awt.Color(blend, true) : null); } else { imagePtr = (Long)layerMap.get(new Integer(handle)); if(imagePtr != null) { myConn.registerImageAccess(handle); // System.out.println(" (compositing surface) layerPtr="+Long.toHexString(imagePtr.longValue())+" currentLayer="+currentLayer); float alpha = (doBlend ? (float)(((blend >> 24)&0xff))/255.0f : 1.0f); composite0(imagePtr.longValue(), currentLayer, srcRect, destRect, alpha, doBlend); } else { System.out.println("ERROR invalid handle passed for texture rendering of: " + handle); abortRenderCycle = true; } } } else { System.out.println("Invalid len for GFXCMD_DRAWTEXTURED : " + len); } break; case GFXCMD_DRAWLINE: // x1, y1, x2, y2, argb1, argb2 if(len==24) { float x1, y1, x2, y2; int argb1, argb2; x1=readInt(0, cmddata); y1=readInt(4, cmddata); x2=readInt(8, cmddata); y2=readInt(12, cmddata); argb1=readInt(16, cmddata); argb2=readInt(20, cmddata); // System.out.println("DRAWLINE: start=("+x1+","+y1+") end=("+x2+","+y2+") argb1="+Integer.toHexString(argb1)+" argb2="+Integer.toHexString(argb2)); drawLine0(x1, y1, x2, y2, 1, new java.awt.Color(argb1, true)); } else { System.out.println("Invalid len for GFXCMD_DRAWLINE : " + len); } break; case GFXCMD_LOADIMAGE: // width, height if(len>=8) { int width, height; int imghandle = 0; width=readInt(0, cmddata); height=readInt(4, cmddata); // System.out.println("LOADIMAGE: size=("+width+"x"+height+")"); if (width * height * 4 + imageCacheSize > imageCacheLimit) { imghandle = 0; } else { // creating a new image from bitmap data being sent over myConn, create a new empty image long imagePtr = createNewImage0(width, height); imghandle = handleCount++; // System.out.println(" imghandle="+imghandle+" imagePtr="+imagePtr); imageMap.put(new Integer(imghandle), new Long(imagePtr)); // actual value is filled in later when it's prepared imageCacheSize += width * height * 4; } hasret[0]=1; return imghandle; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGE : " + len); } break; case GFXCMD_LOADIMAGETARGETED: // handle, width, height // Not used unless we do uncompressed images if(len>=12) { int width, height; int imghandle = readInt(0, cmddata); width=readInt(4, cmddata); height=readInt(8, cmddata); while (width * height * 4 + imageCacheSize > imageCacheLimit) { // Keep freeing the oldest image until we have enough memory to do this int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } long imagePtr = createNewImage0(width, height); // System.out.println(" imghandle="+imghandle+" imagePtr="+imagePtr); imageMap.put(new Integer(imghandle), new Long(imagePtr)); // actual value is filled in later when it's prepared imageCacheSize += width * height * 4; myConn.registerImageAccess(imghandle); hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGETARGETED : " + len); } break; case GFXCMD_CREATESURFACE: // width, height if(len>=8) { int width, height; int handle = handleCount++;; width=readInt(0, cmddata); height=readInt(4, cmddata); // width/height is managed here long layerPtr = createLayer0(c.getSize()); layerMap.put(new Integer(handle), new Long(layerPtr)); // System.out.println("CREATESURFACE: ("+width+","+height+") handle="+handle+" layerPtr="+layerPtr); hasret[0]=1; return handle; } else { System.out.println("Invalid len for GFXCMD_CREATESURFACE : " + len); } break; case GFXCMD_PREPIMAGE: // width, height if(len>=8) { int width, height; //int imghandle = handleCount++;; width=readInt(0, cmddata); height=readInt(4, cmddata); int imghandle = 1; // System.out.println("PREPIMAGE: size=("+width+"x"+height+")"); if (width * height * 4 + imageCacheSize > imageCacheLimit) imghandle = 0; else if (len >= 12) { // We've got enough room for it and there's a cache ID, check if we've got it cached locally int strlen = readInt(8, cmddata); if (strlen > 1) { String rezName = new String(cmddata, 16, strlen - 1); // System.out.println(" rezName="+rezName); lastImageResourceID = rezName; // We use this hashcode to match it up on the loadCompressedImage call so we know we're caching the right thing lastImageResourceIDHandle = imghandle = Math.abs(lastImageResourceID.hashCode()); java.io.File cachedFile = myConn.getCachedImageFile(rezName); if (cachedFile != null) { // We've got it locally in our cache! Read it from there. long imagePtr = createImageFromPath0(cachedFile.getAbsolutePath()); if(imagePtr != 0) { java.awt.Dimension imgSize = getImageDimensions0(imagePtr); if(imgSize != null) { if(imgSize.getWidth() == width && imgSize.getHeight() == height) { // valid image in cache, use it imghandle = handleCount++; // System.out.println(" loaded from cache, imagePtr="+imagePtr+" handle="+imghandle); imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); hasret[0] = 1; return -1 * imghandle; } else freeNativeImage0(imagePtr); } else freeNativeImage0(imagePtr); } } } } //imghandle=STBGFX.GFX_loadImage(width, height); hasret[0]=1; return imghandle; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_PREPIMAGETARGETED: // handle, width, height, [rezID] if(len>=12) { int imghandle, width, height; imghandle = readInt(0, cmddata); width=readInt(4, cmddata); height=readInt(8, cmddata); int strlen = readInt(12, cmddata); while (width * height * 4 + imageCacheSize > imageCacheLimit) { // Keep freeing the oldest image until we have enough memory to do this int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } if (len >= 16) { // We will not have this cached locally...but setup our vars to track it String rezName = new String(cmddata, 20, strlen - 1); lastImageResourceID = rezName; lastImageResourceIDHandle = imghandle; System.out.println("Prepped targeted image with handle " + imghandle + " resource=" + rezName); } myConn.registerImageAccess(imghandle); hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_LOADCACHEDIMAGE: // width, height if(len>=18) { int width, height, imghandle; imghandle = readInt(0, cmddata); width = readInt(4, cmddata); height = readInt(8, cmddata); int strlen = readInt(12, cmddata); String rezName = new String(cmddata, 20, strlen - 1); System.out.println("imghandle=" + imghandle + " width=" + width + " height=" + height + " strlen=" + strlen + " rezName=" + rezName); while (width * height * 4 + imageCacheSize > imageCacheLimit) { // Keep freeing the oldest image until we have enough memory to do this int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } myConn.registerImageAccess(imghandle); try { System.out.println("Loading resource from cache: " + rezName); java.io.File cachedFile = myConn.getCachedImageFile(rezName); if (cachedFile != null) { // We've got it locally in our cache! Read it from there. System.out.println("Image found in cache!"); // We've got it locally in our cache! Read it from there. long imagePtr = createImageFromPath0(cachedFile.getAbsolutePath()); if(imagePtr != 0) { java.awt.Dimension imgSize = getImageDimensions0(imagePtr); if(imgSize != null && imgSize.getWidth() == width && imgSize.getHeight() == height) { // valid image in cache, use it // System.out.println(" loaded from cache, imagePtr="+imagePtr+" handle="+imghandle); imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); } else { if (imgSize != null) { // It doesn't match the cache System.out.println("CACHE ID verification failed for rezName=" + rezName + " target=" + width + "x" + height + " actual=" + imgSize.getWidth() + "x" + imgSize.getHeight()); } else System.out.println("CACHE Load failed for rezName=" + rezName); cachedFile.delete(); freeNativeImage0(imagePtr); // This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded. myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } else { cachedFile.delete(); // This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded. myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } else { System.out.println("ERROR Image not found in cache that should be there! rezName=" + rezName); // This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded. myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } catch (java.io.IOException e) { System.out.println("ERROR loading compressed image: " + e); } hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_UNLOADIMAGE: // handle if(len==4) { int handle; handle=readInt(0, cmddata); unloadImage(handle); myConn.clearImageAccess(handle); } else { System.out.println("Invalid len for GFXCMD_UNLOADIMAGE : " + len); } break; case GFXCMD_SETTARGETSURFACE: // handle if(len==4) { int handle; handle=readInt(0, cmddata); //STBGFX.GFX_unloadImage(handle); Long layerPtr = (Long)layerMap.get(new Integer(handle)); // System.out.println("SETTARGETSURFACE: handle="+handle+" layerPtr="+ (layerPtr == null ? "0" : Long.toHexString(layerPtr.longValue()))); currentLayer = (layerPtr != null) ? layerPtr.longValue() : 0; java.awt.Rectangle clipRect = new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight()); setLayer0(currentLayer, c.getSize(), clipRect); } else { System.out.println("Invalid len for GFXCMD_SETTARGETSURFACE : " + len); } break; case GFXCMD_LOADFONT: // namelen, name, style, size if(len>=12 && len>=(12+readInt(0, cmddata))) { int namelen, style, size; StringBuffer name = new StringBuffer(); int i; int fonthandle = handleCount++; namelen=readInt(0, cmddata); for(i=0;i<namelen-1;i++) // skip the terminating \0 character { name.append((char) cmddata[8 + i]); // an extra 4 for the header } style=readInt(namelen+4, cmddata); size=readInt(namelen+8, cmddata); // System.out.println("LOADFONT: handle="+fonthandle+" name="+name.toString()+" style="+Integer.toHexString(style)+" size="+size); McFont fontPtr = new McFont(name.toString(), style, size); // long fontPtr = loadFont0(name.toString(), style, size); if(fontPtr == null) { // FIXME: implement! // we don't have the font on this sytem (yet) see if it's cached and try to load it manually // String cacheName = name.toString() + "-" + style; // fontPtr = loadCachedFont0(cacheDir.getAbsolutePath(), name.toString() + "-" + myConn.getServerName(), style, size); // if (fontPtr == 0) { // Return that we don't have this font so it'll load it into our cache hasret[0] = 1; return 0; // } } // System.out.println(" fontPtr=" + fontPtr); fontMap.put(new Integer(fonthandle), fontPtr); hasret[0] = 1; return fonthandle; } else { System.out.println("Invalid len for GFXCMD_LOADFONT : " + len); } break; case GFXCMD_UNLOADFONT: // handle if(len==4) { int handle; handle=readInt(0, cmddata); //STBGFX.GFX_unloadFont(handle); McFont fontPtr = (McFont)fontMap.get(new Integer(handle)); // System.out.println("UNLOADFONT: handle="+handle+" fontPtr="+fontPtr); if(fontPtr != null) fontPtr.unload(); fontMap.remove(new Integer(handle)); } else { System.out.println("Invalid len for GFXCMD_UNLOADFONT : " + len); } break; case GFXCMD_LOADFONTSTREAM: // namelen, name, len, data if (len>=8) { StringBuffer name = new StringBuffer(); int namelen = readInt(0, cmddata); for(int i=0;i<namelen-1;i++) // skip the terminating \0 character { name.append((char) cmddata[8 + i]); // an extra 4 for the header } int datalen = readInt(4 + namelen, cmddata); if (len >= datalen + 8 + namelen) { // System.out.println("Saving font " + name.toString() + " to cache"); myConn.saveCacheData(name.toString() + "-" + myConn.getServerName(), cmddata, 12 + namelen, datalen); } } else { System.out.println("Invalid len for GFXCMD_LOADFONTSTREAM : " + len); } break; case GFXCMD_FLIPBUFFER: // System.out.println("FLIPBUFFER"); if (abortRenderCycle) { System.out.println("ERROR in painting cycle, ABORT was set...send full repaint command"); myConn.postRepaintEvent(0, 0, c.getWidth(), c.getHeight()); } else { present0(c.nativeView, new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight())); } hasret[0] = 1; //STBGFX.GFX_flipBuffer(); firstFrameDone = true; return 0; case GFXCMD_STARTFRAME: // System.out.println("STARTFRAME"); // prepare for a new frame to be rendered setTargetView0(c.nativeView); setLayer0(0, c.getSize(), null); // this makes sure the drawing surface gets resized properly abortRenderCycle = false; break; case GFXCMD_LOADIMAGELINE: // handle, line, len, data if(len>=12 && len>=(12+readInt(8, cmddata))) { int handle, line, len2; //unsigned char *data=&cmddata[12]; handle=readInt(0, cmddata); line=readInt(4, cmddata); len2=readInt(8, cmddata); // the last number is the offset into the data array to start reading from //STBGFX.GFX_loadImageLine(handle, line, len, data, 12); //int dataPos = 12; Long imagePtr = (Long)imageMap.get(new Integer(handle)); // System.out.println("LOADIMAGELINE: handle="+handle+" imagePtr="+imagePtr+" line="+line+" len2="+len2); if(imagePtr != null) loadImageLine0(imagePtr.longValue(), line, cmddata, 16/*12*/, len2); myConn.registerImageAccess(handle); } else { System.out.println("Invalid len for GFXCMD_LOADIMAGELINE : " + len); } break; case GFXCMD_LOADIMAGECOMPRESSED: // handle, line, len, data if(len>=8 && len>=(8+readInt(4, cmddata))) { int handle, len2; handle=readInt(0, cmddata); len2=readInt(4, cmddata); if (lastImageResourceID != null && lastImageResourceIDHandle == handle) { myConn.saveCacheData(lastImageResourceID, cmddata, 12, len2); myConn.postOfflineCacheChange(true, lastImageResourceID); } if (!myConn.doesUseAdvancedImageCaching()) { handle = handleCount++; hasret[0] = 1; } else hasret[0] = 0; myConn.registerImageAccess(handle); long imagePtr = createImageFromBytes0(cmddata, 12, len2, null); // FIXME: grab extension if possible // System.out.println("LOADIMAGECOMPRESSED: handle="+handle+" imagePtr="+imagePtr+" len2="+len2); imageMap.put(new Integer(handle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); return handle; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGECOMPRESSED : " + len); } break; case GFXCMD_XFMIMAGE: // srcHandle, destHandle, destWidth, destHeight, maskCornerArc if (len >= 20) { int srcHandle, destHandle, destWidth, destHeight, maskCornerArc; srcHandle = readInt(0, cmddata); destHandle = readInt(4, cmddata); // seems to be unused destWidth = readInt(8, cmddata); // scaled size (ignore?) destHeight = readInt(12, cmddata); maskCornerArc = readInt(16, cmddata); int rvHandle = destHandle; if (!myConn.doesUseAdvancedImageCaching()) { rvHandle = handleCount++; hasret[0] = 1; } else hasret[0] = 0; // we cheat and apply the transforms to a metaimage object without actually creating a new image (saves oodles of memory) Long srcImg = (Long)imageMap.get(new Integer(srcHandle)); // System.out.println("XFMIMAGE: srcHandle="+srcHandle+" srcImg="+srcImg+" destHandle="+destHandle+" destWidth="+destWidth+" destHeight="+destHeight+" maskCornerArc="+maskCornerArc); if(srcImg != null) { long newImage = transformImage0(srcImg.longValue(), destWidth, destHeight, maskCornerArc); if(newImage != 0) { // System.out.println(" newImage="+newImage); imageMap.put(new Integer(rvHandle), new Long(newImage)); } } return rvHandle; } else { System.out.println("Invalid len for GFXCMD_XFMIMAGE : " + len); } break; case GFXCMD_SETVIDEOPROP: if (len >= 40) { java.awt.Rectangle srcRect = new java.awt.Rectangle(readInt(4, cmddata), readInt(8, cmddata), readInt(12, cmddata), readInt(16, cmddata)); java.awt.Rectangle destRect = new java.awt.Rectangle(readInt(20, cmddata), readInt(24, cmddata), readInt(28, cmddata), readInt(32, cmddata)); System.out.println("SETVIDEOPROP: srcRect="+srcRect+" dstRect="+destRect); setVideoBounds(srcRect, destRect); } else { System.out.println("Invalid len for GFXCMD_SETVIDEOPROP: " + len); } break; default: return -1; } return 0; }
public int ExecuteGFXCommand(int cmd, int len, byte[] cmddata, int[] hasret) { len -= 4; hasret[0] = 0; if((cmd != GFXCMD_INIT) && (cmd != GFXCMD_DEINIT)) { if((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) { while((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) { try { Thread.sleep(10); } catch(InterruptedException ex) {} } } } if (c != null) { switch(cmd) { case GFXCMD_INIT: case GFXCMD_DEINIT: case GFXCMD_STARTFRAME: case GFXCMD_FLIPBUFFER: c.setCursor(null); break; case GFXCMD_DRAWRECT: case GFXCMD_FILLRECT: case GFXCMD_CLEARRECT: case GFXCMD_DRAWOVAL: case GFXCMD_FILLOVAL: case GFXCMD_DRAWROUNDRECT: case GFXCMD_FILLROUNDRECT: case GFXCMD_DRAWTEXT: case GFXCMD_DRAWTEXTURED: case GFXCMD_DRAWLINE: case GFXCMD_LOADIMAGE: case GFXCMD_LOADIMAGETARGETED: case GFXCMD_UNLOADIMAGE: case GFXCMD_LOADFONT: case GFXCMD_UNLOADFONT: case GFXCMD_SETTARGETSURFACE: case GFXCMD_CREATESURFACE: break; case GFXCMD_PREPIMAGE: case GFXCMD_LOADIMAGELINE: case GFXCMD_LOADIMAGECOMPRESSED: case GFXCMD_XFMIMAGE: case GFXCMD_LOADCACHEDIMAGE: case GFXCMD_PREPIMAGETARGETED: if (!cursorHidden) c.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR)); break; } } switch(cmd) { case GFXCMD_INIT: hasret[0] = 1; init0(); int windowTitleStyle = 0; try { windowTitleStyle = Integer.parseInt(MiniClient.myProperties.getProperty("window_title_style", "0")); } catch (NumberFormatException e){} if (!"true".equals(MiniClient.myProperties.getProperty("enable_custom_title_bar", MiniClient.MAC_OS_X ? "false" : "true"))) windowTitleStyle = 10; f = new MiniClientWindow(myConn.getWindowTitle(), windowTitleStyle); java.awt.LayoutManager layer = new java.awt.LayoutManager() { public void addLayoutComponent(String name, java.awt.Component comp) {} public java.awt.Dimension minimumLayoutSize(java.awt.Container parent) { return preferredLayoutSize(parent); } public java.awt.Dimension preferredLayoutSize(java.awt.Container parent) { return parent.getPreferredSize(); } public void removeLayoutComponent(java.awt.Component comp) {} public void layoutContainer(java.awt.Container parent) { c.setBounds(parent.getInsets().left, parent.getInsets().top, parent.getWidth() - parent.getInsets().left - parent.getInsets().right, parent.getHeight() - parent.getInsets().top - parent.getInsets().bottom); } }; f.getContentPane().setLayout(layer); try { bgImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/Background.jpg")); ensureImageIsLoaded(bgImage); logoImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/SageLogo256.png")); ensureImageIsLoaded(logoImage); } catch (Exception e) { System.out.println("ERROR:" + e); e.printStackTrace(); } f.setFocusTraversalKeysEnabled(false); java.awt.Dimension panelSize = f.getContentPane().getSize(); c = new QuartzRendererView(); c.setSize(panelSize); c.setFocusTraversalKeysEnabled(false); f.getContentPane().add(c); try { java.awt.Image frameIcon = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/tvicon.gif")); ensureImageIsLoaded(frameIcon); f.setIconImage(frameIcon); } catch (Exception e) { System.out.println("ERROR:" + e); e.printStackTrace(); } f.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { if (!f.isFullScreen() || System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) { MiniClient.myProperties.setProperty("main_window_width", Integer.toString(f.getWidth())); MiniClient.myProperties.setProperty("main_window_height", Integer.toString(f.getHeight())); MiniClient.myProperties.setProperty("main_window_x", Integer.toString(f.getX())); MiniClient.myProperties.setProperty("main_window_y", Integer.toString(f.getY())); } myConn.close(); close(); } }); c.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { myConn.postResizeEvent(new java.awt.Dimension(c.getWidth(), c.getHeight())); } }); f.addKeyListener(this); c.addKeyListener(this); f.addMouseWheelListener(this); c.addMouseListener(this); if (ENABLE_MOUSE_MOTION_EVENTS) { c.addMouseMotionListener(this); } int frameX = 100; int frameY = 100; int frameW = 720; int frameH = 480; try { frameW = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_width", "720")); frameH = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_height", "480")); frameX = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_x", "100")); frameY = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_y", "100")); } catch (NumberFormatException e){} java.awt.Point newPos = new java.awt.Point(frameX, frameY); boolean foundScreen = sage.UIUtils.isPointOnAScreen(newPos); if (!foundScreen) { newPos.x = 150; newPos.y = 150; } f.setVisible(true); f.setSize(1,1); f.setSize(Math.max(frameW, 320), Math.max(frameH, 240)); f.setLocation(newPos); if (MiniClient.fsStartup) f.setFullScreen(true); MiniClient.hideSplash(); return 1; case GFXCMD_DEINIT: close(); break; case GFXCMD_DRAWRECT: if(len==36) { float x, y, width, height; int thickness, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); drawRect0(new java.awt.geom.Rectangle2D.Float(x, y, width, height), null, 0, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWRECT : " + len); } break; case GFXCMD_FILLRECT: if(len==32) { float x, y, width, height; int argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); if(gp != null) { drawRect0(bounds, null, 0, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), 1.0f); } else { drawRect0(bounds, null, 0, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLRECT : " + len); } break; case GFXCMD_CLEARRECT: if(len==32) { int x, y, width, height, argbTL, argbTR, argbBR, argbBL; x=readInt(0, cmddata); y=readInt(4, cmddata); width=readInt(8, cmddata); height=readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); java.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x, y, width, height); clearRect0(destRect); } else { System.out.println("Invalid len for GFXCMD_CLEARRECT : " + len); } break; case GFXCMD_DRAWOVAL: if(len==52) { float x, y, width, height, clipX, clipY, clipW, clipH; int thickness, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); clipX=(float)readInt(36, cmddata); clipY=(float)readInt(40, cmddata); clipW=(float)readInt(44, cmddata); clipH=(float)readInt(48, cmddata); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); drawOval0(bounds, clipRect, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWOVAL : " + len); } break; case GFXCMD_FILLOVAL: if(len==48) { float x, y, width, height, clipX, clipY, clipW, clipH; int argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); clipX=(float)readInt(32, cmddata); clipY=(float)readInt(36, cmddata); clipW=(float)readInt(40, cmddata); clipH=(float)readInt(44, cmddata); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); if(gp != null) { drawOval0(bounds, clipRect, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), 1.0f); } else { drawOval0(bounds, clipRect, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLOVAL : " + len); } break; case GFXCMD_DRAWROUNDRECT: if(len==56) { float x, y, width, height, clipX, clipY, clipW, clipH; int thickness, arcRadius, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); arcRadius=readInt(20, cmddata); argbTL=readInt(24, cmddata); argbTR=readInt(28, cmddata); argbBR=readInt(32, cmddata); argbBL=readInt(36, cmddata); clipX=(float)readInt(40, cmddata); clipY=(float)readInt(44, cmddata); clipW=(float)readInt(48, cmddata); clipH=(float)readInt(52, cmddata); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); drawRect0(bounds, clipRect, arcRadius, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWROUNDRECT : " + len); } break; case GFXCMD_FILLROUNDRECT: if(len==52) { float x, y, width, height, clipX, clipY, clipW, clipH; int arcRadius, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); arcRadius=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); clipX=(float)readInt(36, cmddata); clipY=(float)readInt(40, cmddata); clipW=(float)readInt(44, cmddata); clipH=(float)readInt(48, cmddata); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); if(gp != null) { drawRect0(bounds, clipRect, arcRadius, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), 1.0f); } else { drawRect0(bounds, clipRect, arcRadius, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLROUNDRECT : " + len); } break; case GFXCMD_DRAWTEXT: if(len>=36 && len>=(36+readInt(8, cmddata)*2)) { float x, y, clipX, clipY, clipW, clipH; int textlen, fontHandle, argb; StringBuffer text = new StringBuffer(); int i; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); textlen=readInt(8, cmddata); for(i=0;i<textlen;i++) { text.append((char)readShort(12+i*2, cmddata)); } fontHandle=readInt(textlen*2+12, cmddata); argb=readInt(textlen*2+16, cmddata); clipX=(float)readInt(textlen*2+20, cmddata); clipY=(float)readInt(textlen*2+24, cmddata); clipW=(float)readInt(textlen*2+28, cmddata); clipH=(float)readInt(textlen*2+32, cmddata); McFont fontPtr = (McFont)fontMap.get(new Integer(fontHandle)); if(fontPtr != null) { String theString = text.toString(); float[] positions = fontPtr.getGlyphPositions(theString); drawTextWithPositions0(theString, fontPtr.nativeFont, x, y, positions, new java.awt.geom.Rectangle2D.Float(clipX,clipY,clipW,clipH), new java.awt.Color(argb, true)); } } else { System.out.println("Invalid len for GFXCMD_DRAWTEXT : " + len); } break; case GFXCMD_DRAWTEXTURED: if(len==40) { float x, y, width, height, srcx, srcy, srcwidth, srcheight; int handle, blend; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); handle=readInt(16, cmddata); srcx=(float)readInt(20, cmddata); srcy=(float)readInt(24, cmddata); srcwidth=(float)readInt(28, cmddata); srcheight=(float)readInt(32, cmddata); blend=readInt(36, cmddata); boolean doBlend = true; if(height < 0) { doBlend = false; height *= -1; } if(width < 0) { width *= -1; } else { if(doBlend) blend |= 0x00ffffff; } Long imagePtr = (Long)imageMap.get(new Integer(handle)); java.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x,y,width,height); java.awt.geom.Rectangle2D.Float srcRect = new java.awt.geom.Rectangle2D.Float(srcx,srcy,srcwidth,srcheight); if(imagePtr != null) { myConn.registerImageAccess(handle); drawImage1(imagePtr.longValue(), destRect, srcRect, (doBlend) ? new java.awt.Color(blend, true) : null); } else { imagePtr = (Long)layerMap.get(new Integer(handle)); if(imagePtr != null) { myConn.registerImageAccess(handle); float alpha = (doBlend ? (float)(((blend >> 24)&0xff))/255.0f : 1.0f); composite0(imagePtr.longValue(), currentLayer, srcRect, destRect, alpha, doBlend); } else { System.out.println("ERROR invalid handle passed for texture rendering of: " + handle); abortRenderCycle = true; } } } else { System.out.println("Invalid len for GFXCMD_DRAWTEXTURED : " + len); } break; case GFXCMD_DRAWLINE: if(len==24) { float x1, y1, x2, y2; int argb1, argb2; x1=readInt(0, cmddata); y1=readInt(4, cmddata); x2=readInt(8, cmddata); y2=readInt(12, cmddata); argb1=readInt(16, cmddata); argb2=readInt(20, cmddata); drawLine0(x1, y1, x2, y2, 1, new java.awt.Color(argb1, true)); } else { System.out.println("Invalid len for GFXCMD_DRAWLINE : " + len); } break; case GFXCMD_LOADIMAGE: if(len>=8) { int width, height; int imghandle = 0; width=readInt(0, cmddata); height=readInt(4, cmddata); if (width * height * 4 + imageCacheSize > imageCacheLimit) { imghandle = 0; } else { long imagePtr = createNewImage0(width, height); imghandle = handleCount++; imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += width * height * 4; } hasret[0]=1; return imghandle; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGE : " + len); } break; case GFXCMD_LOADIMAGETARGETED: if(len>=12) { int width, height; int imghandle = readInt(0, cmddata); width=readInt(4, cmddata); height=readInt(8, cmddata); while (width * height * 4 + imageCacheSize > imageCacheLimit) { int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } long imagePtr = createNewImage0(width, height); imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += width * height * 4; myConn.registerImageAccess(imghandle); hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGETARGETED : " + len); } break; case GFXCMD_CREATESURFACE: if(len>=8) { int width, height; int handle = handleCount++;; width=readInt(0, cmddata); height=readInt(4, cmddata); long layerPtr = createLayer0(c.getSize()); layerMap.put(new Integer(handle), new Long(layerPtr)); hasret[0]=1; return handle; } else { System.out.println("Invalid len for GFXCMD_CREATESURFACE : " + len); } break; case GFXCMD_PREPIMAGE: if(len>=8) { int width, height; width=readInt(0, cmddata); height=readInt(4, cmddata); int imghandle = 1; if (width * height * 4 + imageCacheSize > imageCacheLimit) imghandle = 0; else if (len >= 12) { int strlen = readInt(8, cmddata); if (strlen > 1) { String rezName = new String(cmddata, 16, strlen - 1); lastImageResourceID = rezName; lastImageResourceIDHandle = imghandle = Math.abs(lastImageResourceID.hashCode()); java.io.File cachedFile = myConn.getCachedImageFile(rezName); if (cachedFile != null) { long imagePtr = createImageFromPath0(cachedFile.getAbsolutePath()); if(imagePtr != 0) { java.awt.Dimension imgSize = getImageDimensions0(imagePtr); if(imgSize != null) { if(imgSize.getWidth() == width && imgSize.getHeight() == height) { imghandle = handleCount++; imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); hasret[0] = 1; return -1 * imghandle; } else freeNativeImage0(imagePtr); } else freeNativeImage0(imagePtr); } } } } hasret[0]=1; return imghandle; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_PREPIMAGETARGETED: if(len>=12) { int imghandle, width, height; imghandle = readInt(0, cmddata); width=readInt(4, cmddata); height=readInt(8, cmddata); int strlen = readInt(12, cmddata); while (width * height * 4 + imageCacheSize > imageCacheLimit) { int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } if (len >= 16) { String rezName = new String(cmddata, 20, strlen - 1); lastImageResourceID = rezName; lastImageResourceIDHandle = imghandle; System.out.println("Prepped targeted image with handle " + imghandle + " resource=" + rezName); } myConn.registerImageAccess(imghandle); hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_LOADCACHEDIMAGE: if(len>=18) { int width, height, imghandle; imghandle = readInt(0, cmddata); width = readInt(4, cmddata); height = readInt(8, cmddata); int strlen = readInt(12, cmddata); String rezName = new String(cmddata, 20, strlen - 1); System.out.println("imghandle=" + imghandle + " width=" + width + " height=" + height + " strlen=" + strlen + " rezName=" + rezName); while (width * height * 4 + imageCacheSize > imageCacheLimit) { int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } myConn.registerImageAccess(imghandle); try { System.out.println("Loading resource from cache: " + rezName); java.io.File cachedFile = myConn.getCachedImageFile(rezName); if (cachedFile != null) { System.out.println("Image found in cache!"); long imagePtr = createImageFromPath0(cachedFile.getAbsolutePath()); if(imagePtr != 0) { java.awt.Dimension imgSize = getImageDimensions0(imagePtr); if(imgSize != null && imgSize.getWidth() == width && imgSize.getHeight() == height) { imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); } else { if (imgSize != null) { System.out.println("CACHE ID verification failed for rezName=" + rezName + " target=" + width + "x" + height + " actual=" + imgSize.getWidth() + "x" + imgSize.getHeight()); } else System.out.println("CACHE Load failed for rezName=" + rezName); cachedFile.delete(); freeNativeImage0(imagePtr); myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } else { cachedFile.delete(); myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } else { System.out.println("ERROR Image not found in cache that should be there! rezName=" + rezName); myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } catch (java.io.IOException e) { System.out.println("ERROR loading compressed image: " + e); } hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_UNLOADIMAGE: if(len==4) { int handle; handle=readInt(0, cmddata); unloadImage(handle); myConn.clearImageAccess(handle); } else { System.out.println("Invalid len for GFXCMD_UNLOADIMAGE : " + len); } break; case GFXCMD_SETTARGETSURFACE: if(len==4) { int handle; handle=readInt(0, cmddata); Long layerPtr = (Long)layerMap.get(new Integer(handle)); currentLayer = (layerPtr != null) ? layerPtr.longValue() : 0; java.awt.Rectangle clipRect = new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight()); setLayer0(currentLayer, c.getSize(), clipRect); } else { System.out.println("Invalid len for GFXCMD_SETTARGETSURFACE : " + len); } break; case GFXCMD_LOADFONT: if(len>=12 && len>=(12+readInt(0, cmddata))) { int namelen, style, size; StringBuffer name = new StringBuffer(); int i; int fonthandle = handleCount++; namelen=readInt(0, cmddata); for(i=0;i<namelen-1;i++) { name.append((char) cmddata[8 + i]); } style=readInt(namelen+4, cmddata); size=readInt(namelen+8, cmddata); McFont fontPtr = new McFont(name.toString(), style, size); if(fontPtr == null) { hasret[0] = 1; return 0; } fontMap.put(new Integer(fonthandle), fontPtr); hasret[0] = 1; return fonthandle; } else { System.out.println("Invalid len for GFXCMD_LOADFONT : " + len); } break; case GFXCMD_UNLOADFONT: if(len==4) { int handle; handle=readInt(0, cmddata); McFont fontPtr = (McFont)fontMap.get(new Integer(handle)); if(fontPtr != null) fontPtr.unload(); fontMap.remove(new Integer(handle)); } else { System.out.println("Invalid len for GFXCMD_UNLOADFONT : " + len); } break; case GFXCMD_LOADFONTSTREAM: if (len>=8) { StringBuffer name = new StringBuffer(); int namelen = readInt(0, cmddata); for(int i=0;i<namelen-1;i++) { name.append((char) cmddata[8 + i]); } int datalen = readInt(4 + namelen, cmddata); if (len >= datalen + 8 + namelen) { myConn.saveCacheData(name.toString() + "-" + myConn.getServerName(), cmddata, 12 + namelen, datalen); } } else { System.out.println("Invalid len for GFXCMD_LOADFONTSTREAM : " + len); } break; case GFXCMD_FLIPBUFFER: if (abortRenderCycle) { System.out.println("ERROR in painting cycle, ABORT was set...send full repaint command"); myConn.postRepaintEvent(0, 0, c.getWidth(), c.getHeight()); } else { present0(c.nativeView, new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight())); } hasret[0] = 1; firstFrameDone = true; return 0; case GFXCMD_STARTFRAME: setTargetView0(c.nativeView); setLayer0(0, c.getSize(), null); abortRenderCycle = false; break; case GFXCMD_LOADIMAGELINE: if(len>=12 && len>=(12+readInt(8, cmddata))) { int handle, line, len2; handle=readInt(0, cmddata); line=readInt(4, cmddata); len2=readInt(8, cmddata); Long imagePtr = (Long)imageMap.get(new Integer(handle)); if(imagePtr != null) loadImageLine0(imagePtr.longValue(), line, cmddata, 1, len2); myConn.registerImageAccess(handle); } else { System.out.println("Invalid len for GFXCMD_LOADIMAGELINE : " + len); } break; case GFXCMD_LOADIMAGECOMPRESSED: if(len>=8 && len>=(8+readInt(4, cmddata))) { int handle, len2; handle=readInt(0, cmddata); len2=readInt(4, cmddata); if (lastImageResourceID != null && lastImageResourceIDHandle == handle) { myConn.saveCacheData(lastImageResourceID, cmddata, 12, len2); myConn.postOfflineCacheChange(true, lastImageResourceID); } if (!myConn.doesUseAdvancedImageCaching()) { handle = handleCount++; hasret[0] = 1; } else hasret[0] = 0; myConn.registerImageAccess(handle); long imagePtr = createImageFromBytes0(cmddata, 12, len2, null); imageMap.put(new Integer(handle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); return handle; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGECOMPRESSED : " + len); } break; case GFXCMD_XFMIMAGE: if (len >= 20) { int srcHandle, destHandle, destWidth, destHeight, maskCornerArc; srcHandle = readInt(0, cmddata); destHandle = readInt(4, cmddata); destWidth = readInt(8, cmddata); destHeight = readInt(12, cmddata); maskCornerArc = readInt(16, cmddata); int rvHandle = destHandle; if (!myConn.doesUseAdvancedImageCaching()) { rvHandle = handleCount++; hasret[0] = 1; } else hasret[0] = 0; Long srcImg = (Long)imageMap.get(new Integer(srcHandle)); if(srcImg != null) { long newImage = transformImage0(srcImg.longValue(), destWidth, destHeight, maskCornerArc); if(newImage != 0) { imageMap.put(new Integer(rvHandle), new Long(newImage)); } } return rvHandle; } else { System.out.println("Invalid len for GFXCMD_XFMIMAGE : " + len); } break; case GFXCMD_SETVIDEOPROP: if (len >= 40) { java.awt.Rectangle srcRect = new java.awt.Rectangle(readInt(4, cmddata), readInt(8, cmddata), readInt(12, cmddata), readInt(16, cmddata)); java.awt.Rectangle destRect = new java.awt.Rectangle(readInt(20, cmddata), readInt(24, cmddata), readInt(28, cmddata), readInt(32, cmddata)); System.out.println("SETVIDEOPROP: srcRect="+srcRect+" dstRect="+destRect); setVideoBounds(srcRect, destRect); } else { System.out.println("Invalid len for GFXCMD_SETVIDEOPROP: " + len); } break; default: return -1; } return 0; }
public int executegfxcommand(int cmd, int len, byte[] cmddata, int[] hasret) { len -= 4; hasret[0] = 0; if((cmd != gfxcmd_init) && (cmd != gfxcmd_deinit)) { if((f != null) ? (!f.isdisplayable() || !f.isvalid() || !f.isshowing()) : true) { while((f != null) ? (!f.isdisplayable() || !f.isvalid() || !f.isshowing()) : true) { try { thread.sleep(10); } catch(interruptedexception ex) {} } } } if (c != null) { switch(cmd) { case gfxcmd_init: case gfxcmd_deinit: case gfxcmd_startframe: case gfxcmd_flipbuffer: c.setcursor(null); break; case gfxcmd_drawrect: case gfxcmd_fillrect: case gfxcmd_clearrect: case gfxcmd_drawoval: case gfxcmd_filloval: case gfxcmd_drawroundrect: case gfxcmd_fillroundrect: case gfxcmd_drawtext: case gfxcmd_drawtextured: case gfxcmd_drawline: case gfxcmd_loadimage: case gfxcmd_loadimagetargeted: case gfxcmd_unloadimage: case gfxcmd_loadfont: case gfxcmd_unloadfont: case gfxcmd_settargetsurface: case gfxcmd_createsurface: break; case gfxcmd_prepimage: case gfxcmd_loadimageline: case gfxcmd_loadimagecompressed: case gfxcmd_xfmimage: case gfxcmd_loadcachedimage: case gfxcmd_prepimagetargeted: if (!cursorhidden) c.setcursor(java.awt.cursor.getpredefinedcursor(java.awt.cursor.wait_cursor)); break; } } switch(cmd) { case gfxcmd_init: hasret[0] = 1; init0(); int windowtitlestyle = 0; try { windowtitlestyle = integer.parseint(miniclient.myproperties.getproperty("window_title_style", "0")); } catch (numberformatexception e){} if (!"true".equals(miniclient.myproperties.getproperty("enable_custom_title_bar", miniclient.mac_os_x ? "false" : "true"))) windowtitlestyle = 10; f = new miniclientwindow(myconn.getwindowtitle(), windowtitlestyle); java.awt.layoutmanager layer = new java.awt.layoutmanager() { public void addlayoutcomponent(string name, java.awt.component comp) {} public java.awt.dimension minimumlayoutsize(java.awt.container parent) { return preferredlayoutsize(parent); } public java.awt.dimension preferredlayoutsize(java.awt.container parent) { return parent.getpreferredsize(); } public void removelayoutcomponent(java.awt.component comp) {} public void layoutcontainer(java.awt.container parent) { c.setbounds(parent.getinsets().left, parent.getinsets().top, parent.getwidth() - parent.getinsets().left - parent.getinsets().right, parent.getheight() - parent.getinsets().top - parent.getinsets().bottom); } }; f.getcontentpane().setlayout(layer); try { bgimage = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource("images/background.jpg")); ensureimageisloaded(bgimage); logoimage = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource("images/sagelogo256.png")); ensureimageisloaded(logoimage); } catch (exception e) { system.out.println("error:" + e); e.printstacktrace(); } f.setfocustraversalkeysenabled(false); java.awt.dimension panelsize = f.getcontentpane().getsize(); c = new quartzrendererview(); c.setsize(panelsize); c.setfocustraversalkeysenabled(false); f.getcontentpane().add(c); try { java.awt.image frameicon = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource("images/tvicon.gif")); ensureimageisloaded(frameicon); f.seticonimage(frameicon); } catch (exception e) { system.out.println("error:" + e); e.printstacktrace(); } f.addwindowlistener(new java.awt.event.windowadapter() { public void windowclosing(java.awt.event.windowevent evt) { if (!f.isfullscreen() || system.getproperty("os.name").tolowercase().indexof("windows") != -1) { miniclient.myproperties.setproperty("main_window_width", integer.tostring(f.getwidth())); miniclient.myproperties.setproperty("main_window_height", integer.tostring(f.getheight())); miniclient.myproperties.setproperty("main_window_x", integer.tostring(f.getx())); miniclient.myproperties.setproperty("main_window_y", integer.tostring(f.gety())); } myconn.close(); close(); } }); c.addcomponentlistener(new java.awt.event.componentadapter() { public void componentresized(java.awt.event.componentevent evt) { myconn.postresizeevent(new java.awt.dimension(c.getwidth(), c.getheight())); } }); f.addkeylistener(this); c.addkeylistener(this); f.addmousewheellistener(this); c.addmouselistener(this); if (enable_mouse_motion_events) { c.addmousemotionlistener(this); } int framex = 100; int framey = 100; int framew = 720; int frameh = 480; try { framew = integer.parseint(miniclient.myproperties.getproperty("main_window_width", "720")); frameh = integer.parseint(miniclient.myproperties.getproperty("main_window_height", "480")); framex = integer.parseint(miniclient.myproperties.getproperty("main_window_x", "100")); framey = integer.parseint(miniclient.myproperties.getproperty("main_window_y", "100")); } catch (numberformatexception e){} java.awt.point newpos = new java.awt.point(framex, framey); boolean foundscreen = sage.uiutils.ispointonascreen(newpos); if (!foundscreen) { newpos.x = 150; newpos.y = 150; } f.setvisible(true); f.setsize(1,1); f.setsize(math.max(framew, 320), math.max(frameh, 240)); f.setlocation(newpos); if (miniclient.fsstartup) f.setfullscreen(true); miniclient.hidesplash(); return 1; case gfxcmd_deinit: close(); break; case gfxcmd_drawrect: if(len==36) { float x, y, width, height; int thickness, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); drawrect0(new java.awt.geom.rectangle2d.float(x, y, width, height), null, 0, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println("invalid len for gfxcmd_drawrect : " + len); } break; case gfxcmd_fillrect: if(len==32) { float x, y, width, height; int argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); if(gp != null) { drawrect0(bounds, null, 0, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawrect0(bounds, null, 0, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println("invalid len for gfxcmd_fillrect : " + len); } break; case gfxcmd_clearrect: if(len==32) { int x, y, width, height, argbtl, argbtr, argbbr, argbbl; x=readint(0, cmddata); y=readint(4, cmddata); width=readint(8, cmddata); height=readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); java.awt.geom.rectangle2d.float destrect = new java.awt.geom.rectangle2d.float(x, y, width, height); clearrect0(destrect); } else { system.out.println("invalid len for gfxcmd_clearrect : " + len); } break; case gfxcmd_drawoval: if(len==52) { float x, y, width, height, clipx, clipy, clipw, cliph; int thickness, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); clipx=(float)readint(36, cmddata); clipy=(float)readint(40, cmddata); clipw=(float)readint(44, cmddata); cliph=(float)readint(48, cmddata); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); drawoval0(bounds, cliprect, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println("invalid len for gfxcmd_drawoval : " + len); } break; case gfxcmd_filloval: if(len==48) { float x, y, width, height, clipx, clipy, clipw, cliph; int argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); clipx=(float)readint(32, cmddata); clipy=(float)readint(36, cmddata); clipw=(float)readint(40, cmddata); cliph=(float)readint(44, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); if(gp != null) { drawoval0(bounds, cliprect, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawoval0(bounds, cliprect, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println("invalid len for gfxcmd_filloval : " + len); } break; case gfxcmd_drawroundrect: if(len==56) { float x, y, width, height, clipx, clipy, clipw, cliph; int thickness, arcradius, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); arcradius=readint(20, cmddata); argbtl=readint(24, cmddata); argbtr=readint(28, cmddata); argbbr=readint(32, cmddata); argbbl=readint(36, cmddata); clipx=(float)readint(40, cmddata); clipy=(float)readint(44, cmddata); clipw=(float)readint(48, cmddata); cliph=(float)readint(52, cmddata); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); drawrect0(bounds, cliprect, arcradius, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println("invalid len for gfxcmd_drawroundrect : " + len); } break; case gfxcmd_fillroundrect: if(len==52) { float x, y, width, height, clipx, clipy, clipw, cliph; int arcradius, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); arcradius=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); clipx=(float)readint(36, cmddata); clipy=(float)readint(40, cmddata); clipw=(float)readint(44, cmddata); cliph=(float)readint(48, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); if(gp != null) { drawrect0(bounds, cliprect, arcradius, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawrect0(bounds, cliprect, arcradius, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println("invalid len for gfxcmd_fillroundrect : " + len); } break; case gfxcmd_drawtext: if(len>=36 && len>=(36+readint(8, cmddata)*2)) { float x, y, clipx, clipy, clipw, cliph; int textlen, fonthandle, argb; stringbuffer text = new stringbuffer(); int i; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); textlen=readint(8, cmddata); for(i=0;i<textlen;i++) { text.append((char)readshort(12+i*2, cmddata)); } fonthandle=readint(textlen*2+12, cmddata); argb=readint(textlen*2+16, cmddata); clipx=(float)readint(textlen*2+20, cmddata); clipy=(float)readint(textlen*2+24, cmddata); clipw=(float)readint(textlen*2+28, cmddata); cliph=(float)readint(textlen*2+32, cmddata); mcfont fontptr = (mcfont)fontmap.get(new integer(fonthandle)); if(fontptr != null) { string thestring = text.tostring(); float[] positions = fontptr.getglyphpositions(thestring); drawtextwithpositions0(thestring, fontptr.nativefont, x, y, positions, new java.awt.geom.rectangle2d.float(clipx,clipy,clipw,cliph), new java.awt.color(argb, true)); } } else { system.out.println("invalid len for gfxcmd_drawtext : " + len); } break; case gfxcmd_drawtextured: if(len==40) { float x, y, width, height, srcx, srcy, srcwidth, srcheight; int handle, blend; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); handle=readint(16, cmddata); srcx=(float)readint(20, cmddata); srcy=(float)readint(24, cmddata); srcwidth=(float)readint(28, cmddata); srcheight=(float)readint(32, cmddata); blend=readint(36, cmddata); boolean doblend = true; if(height < 0) { doblend = false; height *= -1; } if(width < 0) { width *= -1; } else { if(doblend) blend |= 0x00ffffff; } long imageptr = (long)imagemap.get(new integer(handle)); java.awt.geom.rectangle2d.float destrect = new java.awt.geom.rectangle2d.float(x,y,width,height); java.awt.geom.rectangle2d.float srcrect = new java.awt.geom.rectangle2d.float(srcx,srcy,srcwidth,srcheight); if(imageptr != null) { myconn.registerimageaccess(handle); drawimage1(imageptr.longvalue(), destrect, srcrect, (doblend) ? new java.awt.color(blend, true) : null); } else { imageptr = (long)layermap.get(new integer(handle)); if(imageptr != null) { myconn.registerimageaccess(handle); float alpha = (doblend ? (float)(((blend >> 24)&0xff))/255.0f : 1.0f); composite0(imageptr.longvalue(), currentlayer, srcrect, destrect, alpha, doblend); } else { system.out.println("error invalid handle passed for texture rendering of: " + handle); abortrendercycle = true; } } } else { system.out.println("invalid len for gfxcmd_drawtextured : " + len); } break; case gfxcmd_drawline: if(len==24) { float x1, y1, x2, y2; int argb1, argb2; x1=readint(0, cmddata); y1=readint(4, cmddata); x2=readint(8, cmddata); y2=readint(12, cmddata); argb1=readint(16, cmddata); argb2=readint(20, cmddata); drawline0(x1, y1, x2, y2, 1, new java.awt.color(argb1, true)); } else { system.out.println("invalid len for gfxcmd_drawline : " + len); } break; case gfxcmd_loadimage: if(len>=8) { int width, height; int imghandle = 0; width=readint(0, cmddata); height=readint(4, cmddata); if (width * height * 4 + imagecachesize > imagecachelimit) { imghandle = 0; } else { long imageptr = createnewimage0(width, height); imghandle = handlecount++; imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += width * height * 4; } hasret[0]=1; return imghandle; } else { system.out.println("invalid len for gfxcmd_loadimage : " + len); } break; case gfxcmd_loadimagetargeted: if(len>=12) { int width, height; int imghandle = readint(0, cmddata); width=readint(4, cmddata); height=readint(8, cmddata); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println("freeing image to make room in cache"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println("error cannot free enough from the cache to support loading a new image!!!"); break; } } long imageptr = createnewimage0(width, height); imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += width * height * 4; myconn.registerimageaccess(imghandle); hasret[0]=0; } else { system.out.println("invalid len for gfxcmd_loadimagetargeted : " + len); } break; case gfxcmd_createsurface: if(len>=8) { int width, height; int handle = handlecount++;; width=readint(0, cmddata); height=readint(4, cmddata); long layerptr = createlayer0(c.getsize()); layermap.put(new integer(handle), new long(layerptr)); hasret[0]=1; return handle; } else { system.out.println("invalid len for gfxcmd_createsurface : " + len); } break; case gfxcmd_prepimage: if(len>=8) { int width, height; width=readint(0, cmddata); height=readint(4, cmddata); int imghandle = 1; if (width * height * 4 + imagecachesize > imagecachelimit) imghandle = 0; else if (len >= 12) { int strlen = readint(8, cmddata); if (strlen > 1) { string rezname = new string(cmddata, 16, strlen - 1); lastimageresourceid = rezname; lastimageresourceidhandle = imghandle = math.abs(lastimageresourceid.hashcode()); java.io.file cachedfile = myconn.getcachedimagefile(rezname); if (cachedfile != null) { long imageptr = createimagefrompath0(cachedfile.getabsolutepath()); if(imageptr != 0) { java.awt.dimension imgsize = getimagedimensions0(imageptr); if(imgsize != null) { if(imgsize.getwidth() == width && imgsize.getheight() == height) { imghandle = handlecount++; imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); hasret[0] = 1; return -1 * imghandle; } else freenativeimage0(imageptr); } else freenativeimage0(imageptr); } } } } hasret[0]=1; return imghandle; } else { system.out.println("invalid len for gfxcmd_prepimage : " + len); } break; case gfxcmd_prepimagetargeted: if(len>=12) { int imghandle, width, height; imghandle = readint(0, cmddata); width=readint(4, cmddata); height=readint(8, cmddata); int strlen = readint(12, cmddata); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println("freeing image to make room in cache"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println("error cannot free enough from the cache to support loading a new image!!!"); break; } } if (len >= 16) { string rezname = new string(cmddata, 20, strlen - 1); lastimageresourceid = rezname; lastimageresourceidhandle = imghandle; system.out.println("prepped targeted image with handle " + imghandle + " resource=" + rezname); } myconn.registerimageaccess(imghandle); hasret[0]=0; } else { system.out.println("invalid len for gfxcmd_prepimage : " + len); } break; case gfxcmd_loadcachedimage: if(len>=18) { int width, height, imghandle; imghandle = readint(0, cmddata); width = readint(4, cmddata); height = readint(8, cmddata); int strlen = readint(12, cmddata); string rezname = new string(cmddata, 20, strlen - 1); system.out.println("imghandle=" + imghandle + " width=" + width + " height=" + height + " strlen=" + strlen + " rezname=" + rezname); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println("freeing image to make room in cache"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println("error cannot free enough from the cache to support loading a new image!!!"); break; } } myconn.registerimageaccess(imghandle); try { system.out.println("loading resource from cache: " + rezname); java.io.file cachedfile = myconn.getcachedimagefile(rezname); if (cachedfile != null) { system.out.println("image found in cache!"); long imageptr = createimagefrompath0(cachedfile.getabsolutepath()); if(imageptr != 0) { java.awt.dimension imgsize = getimagedimensions0(imageptr); if(imgsize != null && imgsize.getwidth() == width && imgsize.getheight() == height) { imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); } else { if (imgsize != null) { system.out.println("cache id verification failed for rezname=" + rezname + " target=" + width + "x" + height + " actual=" + imgsize.getwidth() + "x" + imgsize.getheight()); } else system.out.println("cache load failed for rezname=" + rezname); cachedfile.delete(); freenativeimage0(imageptr); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } else { cachedfile.delete(); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } else { system.out.println("error image not found in cache that should be there! rezname=" + rezname); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } catch (java.io.ioexception e) { system.out.println("error loading compressed image: " + e); } hasret[0]=0; } else { system.out.println("invalid len for gfxcmd_prepimage : " + len); } break; case gfxcmd_unloadimage: if(len==4) { int handle; handle=readint(0, cmddata); unloadimage(handle); myconn.clearimageaccess(handle); } else { system.out.println("invalid len for gfxcmd_unloadimage : " + len); } break; case gfxcmd_settargetsurface: if(len==4) { int handle; handle=readint(0, cmddata); long layerptr = (long)layermap.get(new integer(handle)); currentlayer = (layerptr != null) ? layerptr.longvalue() : 0; java.awt.rectangle cliprect = new java.awt.rectangle(0, 0, c.getwidth(), c.getheight()); setlayer0(currentlayer, c.getsize(), cliprect); } else { system.out.println("invalid len for gfxcmd_settargetsurface : " + len); } break; case gfxcmd_loadfont: if(len>=12 && len>=(12+readint(0, cmddata))) { int namelen, style, size; stringbuffer name = new stringbuffer(); int i; int fonthandle = handlecount++; namelen=readint(0, cmddata); for(i=0;i<namelen-1;i++) { name.append((char) cmddata[8 + i]); } style=readint(namelen+4, cmddata); size=readint(namelen+8, cmddata); mcfont fontptr = new mcfont(name.tostring(), style, size); if(fontptr == null) { hasret[0] = 1; return 0; } fontmap.put(new integer(fonthandle), fontptr); hasret[0] = 1; return fonthandle; } else { system.out.println("invalid len for gfxcmd_loadfont : " + len); } break; case gfxcmd_unloadfont: if(len==4) { int handle; handle=readint(0, cmddata); mcfont fontptr = (mcfont)fontmap.get(new integer(handle)); if(fontptr != null) fontptr.unload(); fontmap.remove(new integer(handle)); } else { system.out.println("invalid len for gfxcmd_unloadfont : " + len); } break; case gfxcmd_loadfontstream: if (len>=8) { stringbuffer name = new stringbuffer(); int namelen = readint(0, cmddata); for(int i=0;i<namelen-1;i++) { name.append((char) cmddata[8 + i]); } int datalen = readint(4 + namelen, cmddata); if (len >= datalen + 8 + namelen) { myconn.savecachedata(name.tostring() + "-" + myconn.getservername(), cmddata, 12 + namelen, datalen); } } else { system.out.println("invalid len for gfxcmd_loadfontstream : " + len); } break; case gfxcmd_flipbuffer: if (abortrendercycle) { system.out.println("error in painting cycle, abort was set...send full repaint command"); myconn.postrepaintevent(0, 0, c.getwidth(), c.getheight()); } else { present0(c.nativeview, new java.awt.rectangle(0, 0, c.getwidth(), c.getheight())); } hasret[0] = 1; firstframedone = true; return 0; case gfxcmd_startframe: settargetview0(c.nativeview); setlayer0(0, c.getsize(), null); abortrendercycle = false; break; case gfxcmd_loadimageline: if(len>=12 && len>=(12+readint(8, cmddata))) { int handle, line, len2; handle=readint(0, cmddata); line=readint(4, cmddata); len2=readint(8, cmddata); long imageptr = (long)imagemap.get(new integer(handle)); if(imageptr != null) loadimageline0(imageptr.longvalue(), line, cmddata, 1, len2); myconn.registerimageaccess(handle); } else { system.out.println("invalid len for gfxcmd_loadimageline : " + len); } break; case gfxcmd_loadimagecompressed: if(len>=8 && len>=(8+readint(4, cmddata))) { int handle, len2; handle=readint(0, cmddata); len2=readint(4, cmddata); if (lastimageresourceid != null && lastimageresourceidhandle == handle) { myconn.savecachedata(lastimageresourceid, cmddata, 12, len2); myconn.postofflinecachechange(true, lastimageresourceid); } if (!myconn.doesuseadvancedimagecaching()) { handle = handlecount++; hasret[0] = 1; } else hasret[0] = 0; myconn.registerimageaccess(handle); long imageptr = createimagefrombytes0(cmddata, 12, len2, null); imagemap.put(new integer(handle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); return handle; } else { system.out.println("invalid len for gfxcmd_loadimagecompressed : " + len); } break; case gfxcmd_xfmimage: if (len >= 20) { int srchandle, desthandle, destwidth, destheight, maskcornerarc; srchandle = readint(0, cmddata); desthandle = readint(4, cmddata); destwidth = readint(8, cmddata); destheight = readint(12, cmddata); maskcornerarc = readint(16, cmddata); int rvhandle = desthandle; if (!myconn.doesuseadvancedimagecaching()) { rvhandle = handlecount++; hasret[0] = 1; } else hasret[0] = 0; long srcimg = (long)imagemap.get(new integer(srchandle)); if(srcimg != null) { long newimage = transformimage0(srcimg.longvalue(), destwidth, destheight, maskcornerarc); if(newimage != 0) { imagemap.put(new integer(rvhandle), new long(newimage)); } } return rvhandle; } else { system.out.println("invalid len for gfxcmd_xfmimage : " + len); } break; case gfxcmd_setvideoprop: if (len >= 40) { java.awt.rectangle srcrect = new java.awt.rectangle(readint(4, cmddata), readint(8, cmddata), readint(12, cmddata), readint(16, cmddata)); java.awt.rectangle destrect = new java.awt.rectangle(readint(20, cmddata), readint(24, cmddata), readint(28, cmddata), readint(32, cmddata)); system.out.println("setvideoprop: srcrect="+srcrect+" dstrect="+destrect); setvideobounds(srcrect, destrect); } else { system.out.println("invalid len for gfxcmd_setvideoprop: " + len); } break; default: return -1; } return 0; }
Narflex/sagetv
[ 1, 0, 1, 0 ]
7,810
public boolean isOvertaking() { if (overtakeStage != OvertakeStage.NOT_OVERTAKING) { return true; } else { return false; } }
public boolean isOvertaking() { if (overtakeStage != OvertakeStage.NOT_OVERTAKING) { return true; } else { return false; } }
public boolean isovertaking() { if (overtakestage != overtakestage.not_overtaking) { return true; } else { return false; } }
RobAlexander/SCovSGen
[ 0, 1, 0, 0 ]
16,039
public static List<String> generateParenthesis1(int n) { Set<String>[] dp = new Set[n + 1]; Set<String> first = new HashSet<>(); first.add(""); dp[0] = first; for (int i = 1; i <= n; i++) { Set<String> set = new HashSet<>(); for (String pre : dp[i - 1]) { set.add("(" + pre + ")"); } for (int m = 1; m < i; m++) { for (String p1 : dp[m]) { for (String p2 : dp[i - m]) { set.add(p1 + p2); set.add(p2 + p1); } } } dp[i] = set; } return new ArrayList<>(dp[n]); }
public static List<String> generateParenthesis1(int n) { Set<String>[] dp = new Set[n + 1]; Set<String> first = new HashSet<>(); first.add(""); dp[0] = first; for (int i = 1; i <= n; i++) { Set<String> set = new HashSet<>(); for (String pre : dp[i - 1]) { set.add("(" + pre + ")"); } for (int m = 1; m < i; m++) { for (String p1 : dp[m]) { for (String p2 : dp[i - m]) { set.add(p1 + p2); set.add(p2 + p1); } } } dp[i] = set; } return new ArrayList<>(dp[n]); }
public static list<string> generateparenthesis1(int n) { set<string>[] dp = new set[n + 1]; set<string> first = new hashset<>(); first.add(""); dp[0] = first; for (int i = 1; i <= n; i++) { set<string> set = new hashset<>(); for (string pre : dp[i - 1]) { set.add("(" + pre + ")"); } for (int m = 1; m < i; m++) { for (string p1 : dp[m]) { for (string p2 : dp[i - m]) { set.add(p1 + p2); set.add(p2 + p1); } } } dp[i] = set; } return new arraylist<>(dp[n]); }
Joybeanx/leetcode
[ 1, 0, 0, 0 ]
24,717
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Study study = ControllerUtil.findStudy(request, mStudyService); Submission submission = (Submission) study.getSubmission(); StudyCommand studyCommand = new StudyCommand(); // copy study information studyCommand.setStudy(study); // study from TBI do not contain submission_id if (submission != null) { studyCommand.setSubmission_id(submission.getId()); } List<Analysis> analysisList = study.getAnalyses(); List<AnalysisCommand> analysisCommandList = new ArrayList<AnalysisCommand>(); List<Analysis> changedAnalyses = new ArrayList<Analysis>(); StringBuilder errBuilder = new StringBuilder(); for (Analysis analysis : analysisList) { // FIXME: next if block needs to me moved to the onSumbit method when // we this controller will extend BaseFormController. if (!analysis.getValidated()) { ExecutionResult result = analysis.validate(); if (!result.isSuccessful()) { errBuilder.append(result.getErrorMessage()); } if (analysis.getValidated()) { // save to db if the validated flag is updated: changedAnalyses.add(analysis); } } //FIXME: display err message in GUI if (LOGGER.isDebugEnabled()) { LOGGER.debug(errBuilder.toString()); //$NON-NLS-1$ } // // Analysis AnalysisCommand analysisCommand = new AnalysisCommand(); BeanUtils.copyProperties(analysisCommand, analysis); // Analysis Steps for Analysis and add algorithm type List<AnalysisStep> analysisStepList = analysis.getAnalysisStepsReadOnly(); List<AnalysisStepCommand> analysisStepCommandList = new ArrayList<AnalysisStepCommand>(); for (AnalysisStep analysisStep : analysisStepList) { AnalysisStepCommand analysisStepCommand = new AnalysisStepCommand(); BeanUtils.copyProperties(analysisStepCommand, analysisStep); // analysisStepCommand.setId(analysisStep.getId()); // analysisStepCommand.setSoftwareInfo(analysisStep.getSoftwareInfo()); Algorithm algorithm = analysisStep.getAlgorithmInfo(); String algorithmType = new String(); if (algorithm instanceof LikelihoodAlgorithm) { algorithmType = Constants.ALGORITHM_LIKELIHOOD; } else if (algorithm instanceof ParsimonyAlgorithm) { algorithmType = Constants.ALGORITHM_PARSIMONY; } else if (algorithm instanceof OtherAlgorithm) { algorithmType = Constants.ALGORITHM_OTHER; }else if (algorithm instanceof BayesianAlgorithm) { algorithmType = Constants.ALGORITHM_Bayesian; } else if (algorithm instanceof EvolutionAlgorithm) { algorithmType = Constants.ALGORITHM_Evolution; } else if (algorithm instanceof JoiningAlgorithm) { algorithmType = Constants.ALGORITHM_Joining; } else if (algorithm instanceof UPGMAAlgorithm) { algorithmType = Constants.ALGORITHM_UPGMA; } // add algorithm type for analysisStepCommand analysisStepCommand.setAlgorithmType(algorithmType); // analyzed data for each analysis step List<AnalyzedData> analyzedDataSet = analysisStep.getDataSetReadOnly(); List<AnalyzedDataCommand> analyzedDataCommandList = new ArrayList<AnalyzedDataCommand>(); // Matrix or Tree? for (AnalyzedData analyzedData : analyzedDataSet) { AnalyzedDataCommand analyzedDataCommand = new AnalyzedDataCommand(); BeanUtils.copyProperties(analyzedDataCommand, analyzedData); String inputOutput = (analyzedData.isInputData()) ? ("Input") : ("Output"); analyzedDataCommand.setInputOutputType(inputOutput); if (analyzedData instanceof AnalyzedMatrix) { AnalyzedMatrix analyzedMatrix = (AnalyzedMatrix) analyzedData; analyzedDataCommand.setDataType(Constants.MATRIX_KEY); analyzedDataCommand.setDisplayName(analyzedMatrix.getMatrix().getTitle()); analyzedDataCommand.setId(analyzedMatrix.getId()); analyzedDataCommand.setDataId(analyzedMatrix.getMatrix().getId()); } else if (analyzedData instanceof AnalyzedTree) { AnalyzedTree analyzedTree = (AnalyzedTree) analyzedData; analyzedDataCommand.setDataType(Constants.TREE_KEY); analyzedDataCommand.setDisplayName(analyzedTree.getTree().getLabel()); analyzedDataCommand.setId(analyzedTree.getId()); analyzedDataCommand.setDataId(analyzedTree.getTree().getId()); } analyzedDataCommandList.add(analyzedDataCommand); } // end for // add analyzedData for analysisStepCommand Collections.sort(analyzedDataCommandList, new AnalyzedDataComparator()); analysisStepCommand.setAnalyzedDataCommandList(analyzedDataCommandList); analysisStepCommandList.add(analysisStepCommand); } analysisCommand.setAnalysisStepCommandList(analysisStepCommandList); analysisCommandList.add(analysisCommand); } getStudyService().updateCollection(changedAnalyses); studyCommand.setAnalysisCommandList(analysisCommandList); return new ModelAndView("analysisSection", Constants.STUDY_COMMAND_KEY, studyCommand); }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Study study = ControllerUtil.findStudy(request, mStudyService); Submission submission = (Submission) study.getSubmission(); StudyCommand studyCommand = new StudyCommand(); studyCommand.setStudy(study); if (submission != null) { studyCommand.setSubmission_id(submission.getId()); } List<Analysis> analysisList = study.getAnalyses(); List<AnalysisCommand> analysisCommandList = new ArrayList<AnalysisCommand>(); List<Analysis> changedAnalyses = new ArrayList<Analysis>(); StringBuilder errBuilder = new StringBuilder(); for (Analysis analysis : analysisList) { if (!analysis.getValidated()) { ExecutionResult result = analysis.validate(); if (!result.isSuccessful()) { errBuilder.append(result.getErrorMessage()); } if (analysis.getValidated()) { changedAnalyses.add(analysis); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug(errBuilder.toString()); } AnalysisCommand analysisCommand = new AnalysisCommand(); BeanUtils.copyProperties(analysisCommand, analysis); List<AnalysisStep> analysisStepList = analysis.getAnalysisStepsReadOnly(); List<AnalysisStepCommand> analysisStepCommandList = new ArrayList<AnalysisStepCommand>(); for (AnalysisStep analysisStep : analysisStepList) { AnalysisStepCommand analysisStepCommand = new AnalysisStepCommand(); BeanUtils.copyProperties(analysisStepCommand, analysisStep); Algorithm algorithm = analysisStep.getAlgorithmInfo(); String algorithmType = new String(); if (algorithm instanceof LikelihoodAlgorithm) { algorithmType = Constants.ALGORITHM_LIKELIHOOD; } else if (algorithm instanceof ParsimonyAlgorithm) { algorithmType = Constants.ALGORITHM_PARSIMONY; } else if (algorithm instanceof OtherAlgorithm) { algorithmType = Constants.ALGORITHM_OTHER; }else if (algorithm instanceof BayesianAlgorithm) { algorithmType = Constants.ALGORITHM_Bayesian; } else if (algorithm instanceof EvolutionAlgorithm) { algorithmType = Constants.ALGORITHM_Evolution; } else if (algorithm instanceof JoiningAlgorithm) { algorithmType = Constants.ALGORITHM_Joining; } else if (algorithm instanceof UPGMAAlgorithm) { algorithmType = Constants.ALGORITHM_UPGMA; } analysisStepCommand.setAlgorithmType(algorithmType); List<AnalyzedData> analyzedDataSet = analysisStep.getDataSetReadOnly(); List<AnalyzedDataCommand> analyzedDataCommandList = new ArrayList<AnalyzedDataCommand>(); for (AnalyzedData analyzedData : analyzedDataSet) { AnalyzedDataCommand analyzedDataCommand = new AnalyzedDataCommand(); BeanUtils.copyProperties(analyzedDataCommand, analyzedData); String inputOutput = (analyzedData.isInputData()) ? ("Input") : ("Output"); analyzedDataCommand.setInputOutputType(inputOutput); if (analyzedData instanceof AnalyzedMatrix) { AnalyzedMatrix analyzedMatrix = (AnalyzedMatrix) analyzedData; analyzedDataCommand.setDataType(Constants.MATRIX_KEY); analyzedDataCommand.setDisplayName(analyzedMatrix.getMatrix().getTitle()); analyzedDataCommand.setId(analyzedMatrix.getId()); analyzedDataCommand.setDataId(analyzedMatrix.getMatrix().getId()); } else if (analyzedData instanceof AnalyzedTree) { AnalyzedTree analyzedTree = (AnalyzedTree) analyzedData; analyzedDataCommand.setDataType(Constants.TREE_KEY); analyzedDataCommand.setDisplayName(analyzedTree.getTree().getLabel()); analyzedDataCommand.setId(analyzedTree.getId()); analyzedDataCommand.setDataId(analyzedTree.getTree().getId()); } analyzedDataCommandList.add(analyzedDataCommand); } Collections.sort(analyzedDataCommandList, new AnalyzedDataComparator()); analysisStepCommand.setAnalyzedDataCommandList(analyzedDataCommandList); analysisStepCommandList.add(analysisStepCommand); } analysisCommand.setAnalysisStepCommandList(analysisStepCommandList); analysisCommandList.add(analysisCommand); } getStudyService().updateCollection(changedAnalyses); studyCommand.setAnalysisCommandList(analysisCommandList); return new ModelAndView("analysisSection", Constants.STUDY_COMMAND_KEY, studyCommand); }
public modelandview handlerequest(httpservletrequest request, httpservletresponse response) throws exception { study study = controllerutil.findstudy(request, mstudyservice); submission submission = (submission) study.getsubmission(); studycommand studycommand = new studycommand(); studycommand.setstudy(study); if (submission != null) { studycommand.setsubmission_id(submission.getid()); } list<analysis> analysislist = study.getanalyses(); list<analysiscommand> analysiscommandlist = new arraylist<analysiscommand>(); list<analysis> changedanalyses = new arraylist<analysis>(); stringbuilder errbuilder = new stringbuilder(); for (analysis analysis : analysislist) { if (!analysis.getvalidated()) { executionresult result = analysis.validate(); if (!result.issuccessful()) { errbuilder.append(result.geterrormessage()); } if (analysis.getvalidated()) { changedanalyses.add(analysis); } } if (logger.isdebugenabled()) { logger.debug(errbuilder.tostring()); } analysiscommand analysiscommand = new analysiscommand(); beanutils.copyproperties(analysiscommand, analysis); list<analysisstep> analysissteplist = analysis.getanalysisstepsreadonly(); list<analysisstepcommand> analysisstepcommandlist = new arraylist<analysisstepcommand>(); for (analysisstep analysisstep : analysissteplist) { analysisstepcommand analysisstepcommand = new analysisstepcommand(); beanutils.copyproperties(analysisstepcommand, analysisstep); algorithm algorithm = analysisstep.getalgorithminfo(); string algorithmtype = new string(); if (algorithm instanceof likelihoodalgorithm) { algorithmtype = constants.algorithm_likelihood; } else if (algorithm instanceof parsimonyalgorithm) { algorithmtype = constants.algorithm_parsimony; } else if (algorithm instanceof otheralgorithm) { algorithmtype = constants.algorithm_other; }else if (algorithm instanceof bayesianalgorithm) { algorithmtype = constants.algorithm_bayesian; } else if (algorithm instanceof evolutionalgorithm) { algorithmtype = constants.algorithm_evolution; } else if (algorithm instanceof joiningalgorithm) { algorithmtype = constants.algorithm_joining; } else if (algorithm instanceof upgmaalgorithm) { algorithmtype = constants.algorithm_upgma; } analysisstepcommand.setalgorithmtype(algorithmtype); list<analyzeddata> analyzeddataset = analysisstep.getdatasetreadonly(); list<analyzeddatacommand> analyzeddatacommandlist = new arraylist<analyzeddatacommand>(); for (analyzeddata analyzeddata : analyzeddataset) { analyzeddatacommand analyzeddatacommand = new analyzeddatacommand(); beanutils.copyproperties(analyzeddatacommand, analyzeddata); string inputoutput = (analyzeddata.isinputdata()) ? ("input") : ("output"); analyzeddatacommand.setinputoutputtype(inputoutput); if (analyzeddata instanceof analyzedmatrix) { analyzedmatrix analyzedmatrix = (analyzedmatrix) analyzeddata; analyzeddatacommand.setdatatype(constants.matrix_key); analyzeddatacommand.setdisplayname(analyzedmatrix.getmatrix().gettitle()); analyzeddatacommand.setid(analyzedmatrix.getid()); analyzeddatacommand.setdataid(analyzedmatrix.getmatrix().getid()); } else if (analyzeddata instanceof analyzedtree) { analyzedtree analyzedtree = (analyzedtree) analyzeddata; analyzeddatacommand.setdatatype(constants.tree_key); analyzeddatacommand.setdisplayname(analyzedtree.gettree().getlabel()); analyzeddatacommand.setid(analyzedtree.getid()); analyzeddatacommand.setdataid(analyzedtree.gettree().getid()); } analyzeddatacommandlist.add(analyzeddatacommand); } collections.sort(analyzeddatacommandlist, new analyzeddatacomparator()); analysisstepcommand.setanalyzeddatacommandlist(analyzeddatacommandlist); analysisstepcommandlist.add(analysisstepcommand); } analysiscommand.setanalysisstepcommandlist(analysisstepcommandlist); analysiscommandlist.add(analysiscommand); } getstudyservice().updatecollection(changedanalyses); studycommand.setanalysiscommandlist(analysiscommandlist); return new modelandview("analysissection", constants.study_command_key, studycommand); }
TreeBASE/treebasetest
[ 0, 1, 1, 0 ]
148
private void addVar(Varlet v){ long key=key(v.chromosome, v.beginLoc); ArrayList<Varlet> list=keymap.get(key); assert(list!=null) : "\nCan't find "+key+" in "+keymap.keySet()+"\n"; synchronized(list){ list.add(v); if(list.size()>=WRITE_BUFFER){ if(MERGE_EQUAL_VARLETS){ mergeEqualVarlets(list); }else{ Collections.sort(list); } writeList(list); list.clear(); } } }
private void addVar(Varlet v){ long key=key(v.chromosome, v.beginLoc); ArrayList<Varlet> list=keymap.get(key); assert(list!=null) : "\nCan't find "+key+" in "+keymap.keySet()+"\n"; synchronized(list){ list.add(v); if(list.size()>=WRITE_BUFFER){ if(MERGE_EQUAL_VARLETS){ mergeEqualVarlets(list); }else{ Collections.sort(list); } writeList(list); list.clear(); } } }
private void addvar(varlet v){ long key=key(v.chromosome, v.beginloc); arraylist<varlet> list=keymap.get(key); assert(list!=null) : "\ncan't find "+key+" in "+keymap.keyset()+"\n"; synchronized(list){ list.add(v); if(list.size()>=write_buffer){ if(merge_equal_varlets){ mergeequalvarlets(list); }else{ collections.sort(list); } writelist(list); list.clear(); } } }
SilasK/BBMap
[ 1, 0, 0, 0 ]
16,664
private NiceWebDriver getNiceWebDriverInstance(DriverType driverType, Object[] oArgs){ switch(driverType) { case Chrome: return new NiceChrome().UnderloadedNiceWebDriverConstructor(oArgs).getThisWithVerbositySetTo(outputIsVerbose); case Firefox: return null; //TODO: Make Firefox subclass case IE: return null; //TODO: Make IE subclass case Edge: return null; //TODO: Make Edge subclass case Opera: return null; //TODO: Make Opera subclass case Safari: return null; //TODO: Make Safari subclass case iOS_iPhone: return null; //TODO: Make iOS_iPhone subclass case iOS_iPad: return null; //TODO: Make iOS_iPad subclass case Android: return null; //TODO: Make Android subclass case HtmlUnit: return null; //TODO: Make HtmlUnit subclass default: return null; } }
private NiceWebDriver getNiceWebDriverInstance(DriverType driverType, Object[] oArgs){ switch(driverType) { case Chrome: return new NiceChrome().UnderloadedNiceWebDriverConstructor(oArgs).getThisWithVerbositySetTo(outputIsVerbose); case Firefox: return null; case IE: return null; case Edge: return null; case Opera: return null; case Safari: return null; case iOS_iPhone: return null; case iOS_iPad: return null; case Android: return null; case HtmlUnit: return null; default: return null; } }
private nicewebdriver getnicewebdriverinstance(drivertype drivertype, object[] oargs){ switch(drivertype) { case chrome: return new nicechrome().underloadednicewebdriverconstructor(oargs).getthiswithverbositysetto(outputisverbose); case firefox: return null; case ie: return null; case edge: return null; case opera: return null; case safari: return null; case ios_iphone: return null; case ios_ipad: return null; case android: return null; case htmlunit: return null; default: return null; } }
Skenvy/SeleniumNG
[ 0, 1, 0, 0 ]
33,149
private void tag() throws Exception { String[] asFilename = (String[])m_oCmdLineMap.get("filenames"); for (int i=0; i < asFilename.length; i++) { File oSourceFile = new File(asFilename[i]); MP3File oMP3File = new MP3File(oSourceFile); if (m_oCmdLineMap.containsKey("1")) { ID3V1_1Tag oID3V1_1Tag = new ID3V1_1Tag(); if (m_oCmdLineMap.containsKey("album")) { oID3V1_1Tag.setAlbum((String)m_oCmdLineMap.get("album")); } if (m_oCmdLineMap.containsKey("artist")) { oID3V1_1Tag.setArtist((String)m_oCmdLineMap.get("artist")); } if (m_oCmdLineMap.containsKey("comment")) { oID3V1_1Tag.setComment((String)m_oCmdLineMap.get("comment")); } if (m_oCmdLineMap.containsKey("genre")) { String sGenre = (String)m_oCmdLineMap.get("genre"); oID3V1_1Tag.setGenre(ID3V1Tag.Genre.lookupGenre(sGenre)); } if (m_oCmdLineMap.containsKey("title")) { oID3V1_1Tag.setTitle((String)m_oCmdLineMap.get("title")); } if (m_oCmdLineMap.containsKey("year")) { oID3V1_1Tag.setYear(((Integer)m_oCmdLineMap.get("year")).toString()); } if (m_oCmdLineMap.containsKey("track")) { oID3V1_1Tag.setAlbumTrack(((Integer)m_oCmdLineMap.get("track")).intValue()); } oMP3File.setID3Tag(oID3V1_1Tag); } if (m_oCmdLineMap.containsKey("2")) { ID3V2_3_0Tag oID3V2_3_0Tag = new ID3V2_3_0Tag(); //HACK: Need to have padding at the end of the tag, or Winamp won't see the last frame (at least 6 bytes seem to be required). oID3V2_3_0Tag.setPaddingLength(16); if (m_oCmdLineMap.containsKey("album")) { oID3V2_3_0Tag.setAlbum((String)m_oCmdLineMap.get("album")); } if (m_oCmdLineMap.containsKey("artist")) { oID3V2_3_0Tag.setArtist((String)m_oCmdLineMap.get("artist")); } if (m_oCmdLineMap.containsKey("comment")) { oID3V2_3_0Tag.setComment((String)m_oCmdLineMap.get("comment")); } if (m_oCmdLineMap.containsKey("genre")) { oID3V2_3_0Tag.setGenre((String)m_oCmdLineMap.get("genre")); } oMP3File.setID3Tag(oID3V2_3_0Tag); if (m_oCmdLineMap.containsKey("title")) { oID3V2_3_0Tag.setTitle((String)m_oCmdLineMap.get("title")); } if (m_oCmdLineMap.containsKey("year")) { oID3V2_3_0Tag.setYear(((Integer)m_oCmdLineMap.get("year")).intValue()); } if (m_oCmdLineMap.containsKey("track")) { if (m_oCmdLineMap.containsKey("total")) { oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get("track")).intValue(), ((Integer)m_oCmdLineMap.get("total")).intValue()); } else { oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get("track")).intValue()); } } } oMP3File.sync(); } }
private void tag() throws Exception { String[] asFilename = (String[])m_oCmdLineMap.get("filenames"); for (int i=0; i < asFilename.length; i++) { File oSourceFile = new File(asFilename[i]); MP3File oMP3File = new MP3File(oSourceFile); if (m_oCmdLineMap.containsKey("1")) { ID3V1_1Tag oID3V1_1Tag = new ID3V1_1Tag(); if (m_oCmdLineMap.containsKey("album")) { oID3V1_1Tag.setAlbum((String)m_oCmdLineMap.get("album")); } if (m_oCmdLineMap.containsKey("artist")) { oID3V1_1Tag.setArtist((String)m_oCmdLineMap.get("artist")); } if (m_oCmdLineMap.containsKey("comment")) { oID3V1_1Tag.setComment((String)m_oCmdLineMap.get("comment")); } if (m_oCmdLineMap.containsKey("genre")) { String sGenre = (String)m_oCmdLineMap.get("genre"); oID3V1_1Tag.setGenre(ID3V1Tag.Genre.lookupGenre(sGenre)); } if (m_oCmdLineMap.containsKey("title")) { oID3V1_1Tag.setTitle((String)m_oCmdLineMap.get("title")); } if (m_oCmdLineMap.containsKey("year")) { oID3V1_1Tag.setYear(((Integer)m_oCmdLineMap.get("year")).toString()); } if (m_oCmdLineMap.containsKey("track")) { oID3V1_1Tag.setAlbumTrack(((Integer)m_oCmdLineMap.get("track")).intValue()); } oMP3File.setID3Tag(oID3V1_1Tag); } if (m_oCmdLineMap.containsKey("2")) { ID3V2_3_0Tag oID3V2_3_0Tag = new ID3V2_3_0Tag(); oID3V2_3_0Tag.setPaddingLength(16); if (m_oCmdLineMap.containsKey("album")) { oID3V2_3_0Tag.setAlbum((String)m_oCmdLineMap.get("album")); } if (m_oCmdLineMap.containsKey("artist")) { oID3V2_3_0Tag.setArtist((String)m_oCmdLineMap.get("artist")); } if (m_oCmdLineMap.containsKey("comment")) { oID3V2_3_0Tag.setComment((String)m_oCmdLineMap.get("comment")); } if (m_oCmdLineMap.containsKey("genre")) { oID3V2_3_0Tag.setGenre((String)m_oCmdLineMap.get("genre")); } oMP3File.setID3Tag(oID3V2_3_0Tag); if (m_oCmdLineMap.containsKey("title")) { oID3V2_3_0Tag.setTitle((String)m_oCmdLineMap.get("title")); } if (m_oCmdLineMap.containsKey("year")) { oID3V2_3_0Tag.setYear(((Integer)m_oCmdLineMap.get("year")).intValue()); } if (m_oCmdLineMap.containsKey("track")) { if (m_oCmdLineMap.containsKey("total")) { oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get("track")).intValue(), ((Integer)m_oCmdLineMap.get("total")).intValue()); } else { oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get("track")).intValue()); } } } oMP3File.sync(); } }
private void tag() throws exception { string[] asfilename = (string[])m_ocmdlinemap.get("filenames"); for (int i=0; i < asfilename.length; i++) { file osourcefile = new file(asfilename[i]); mp3file omp3file = new mp3file(osourcefile); if (m_ocmdlinemap.containskey("1")) { id3v1_1tag oid3v1_1tag = new id3v1_1tag(); if (m_ocmdlinemap.containskey("album")) { oid3v1_1tag.setalbum((string)m_ocmdlinemap.get("album")); } if (m_ocmdlinemap.containskey("artist")) { oid3v1_1tag.setartist((string)m_ocmdlinemap.get("artist")); } if (m_ocmdlinemap.containskey("comment")) { oid3v1_1tag.setcomment((string)m_ocmdlinemap.get("comment")); } if (m_ocmdlinemap.containskey("genre")) { string sgenre = (string)m_ocmdlinemap.get("genre"); oid3v1_1tag.setgenre(id3v1tag.genre.lookupgenre(sgenre)); } if (m_ocmdlinemap.containskey("title")) { oid3v1_1tag.settitle((string)m_ocmdlinemap.get("title")); } if (m_ocmdlinemap.containskey("year")) { oid3v1_1tag.setyear(((integer)m_ocmdlinemap.get("year")).tostring()); } if (m_ocmdlinemap.containskey("track")) { oid3v1_1tag.setalbumtrack(((integer)m_ocmdlinemap.get("track")).intvalue()); } omp3file.setid3tag(oid3v1_1tag); } if (m_ocmdlinemap.containskey("2")) { id3v2_3_0tag oid3v2_3_0tag = new id3v2_3_0tag(); oid3v2_3_0tag.setpaddinglength(16); if (m_ocmdlinemap.containskey("album")) { oid3v2_3_0tag.setalbum((string)m_ocmdlinemap.get("album")); } if (m_ocmdlinemap.containskey("artist")) { oid3v2_3_0tag.setartist((string)m_ocmdlinemap.get("artist")); } if (m_ocmdlinemap.containskey("comment")) { oid3v2_3_0tag.setcomment((string)m_ocmdlinemap.get("comment")); } if (m_ocmdlinemap.containskey("genre")) { oid3v2_3_0tag.setgenre((string)m_ocmdlinemap.get("genre")); } omp3file.setid3tag(oid3v2_3_0tag); if (m_ocmdlinemap.containskey("title")) { oid3v2_3_0tag.settitle((string)m_ocmdlinemap.get("title")); } if (m_ocmdlinemap.containskey("year")) { oid3v2_3_0tag.setyear(((integer)m_ocmdlinemap.get("year")).intvalue()); } if (m_ocmdlinemap.containskey("track")) { if (m_ocmdlinemap.containskey("total")) { oid3v2_3_0tag.settracknumber(((integer)m_ocmdlinemap.get("track")).intvalue(), ((integer)m_ocmdlinemap.get("total")).intvalue()); } else { oid3v2_3_0tag.settracknumber(((integer)m_ocmdlinemap.get("track")).intvalue()); } } } omp3file.sync(); } }
ShahzaibAyyub/Music-Player-Library-Java-SQL
[ 1, 0, 0, 0 ]
8,611
@Override public void actionPerformed(ActionEvent e) { if(currSel!= null && currSel instanceof GroupTreeNode){ // differentiate clones in this group GroupTreeNode gtn = (GroupTreeNode)currSel; // if(gtn.getChildCount() == 2){ // TODO: currently we only support two way comparison CloneTreeNode ctn1 = (CloneTreeNode)gtn.getChildAt(0); CloneTreeNode ctn2 = (CloneTreeNode)gtn.getChildAt(1); String file1 = ctn1.getFile(); String file2 = ctn2.getFile(); CloneComparison comparison = new CloneComparison(panel, new File(file1), new File(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end); comparison.setOpenInBackground(false); comparison.execute(); // } } }
@Override public void actionPerformed(ActionEvent e) { if(currSel!= null && currSel instanceof GroupTreeNode){ GroupTreeNode gtn = (GroupTreeNode)currSel; CloneTreeNode ctn1 = (CloneTreeNode)gtn.getChildAt(0); CloneTreeNode ctn2 = (CloneTreeNode)gtn.getChildAt(1); String file1 = ctn1.getFile(); String file2 = ctn2.getFile(); CloneComparison comparison = new CloneComparison(panel, new File(file1), new File(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end); comparison.setOpenInBackground(false); comparison.execute(); } }
@override public void actionperformed(actionevent e) { if(currsel!= null && currsel instanceof grouptreenode){ grouptreenode gtn = (grouptreenode)currsel; clonetreenode ctn1 = (clonetreenode)gtn.getchildat(0); clonetreenode ctn2 = (clonetreenode)gtn.getchildat(1); string file1 = ctn1.getfile(); string file2 = ctn2.getfile(); clonecomparison comparison = new clonecomparison(panel, new file(file1), new file(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end); comparison.setopeninbackground(false); comparison.execute(); } }
UCLA-SEAL/Grafter
[ 1, 0, 0, 0 ]
25,018
private BaseQuery buildQueryNoAggregations(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, long startOffset, int maxResults, IckleParsingResult<TypeMetadata> parsingResult) { if (parsingResult.hasGroupingOrAggregations()) { throw log.queryMustNotUseGroupingOrAggregation(); // may happen only due to internal programming error } boolean isFullTextQuery; if (parsingResult.getWhereClause() != null) { isFullTextQuery = parsingResult.getWhereClause().acceptVisitor(FullTextVisitor.INSTANCE); if (!isIndexed && isFullTextQuery) { throw new IllegalStateException("The cache must be indexed in order to use full-text queries."); } } if (parsingResult.getSortFields() != null) { for (SortField sortField : parsingResult.getSortFields()) { PropertyPath<?> p = sortField.getPath(); if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeUsedInOrderBy(p.toString()); } } } if (parsingResult.getProjectedPaths() != null) { for (PropertyPath<?> p : parsingResult.getProjectedPaths()) { if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeProjected(p.asStringPath()); } } } BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); if (normalizedWhereClause == ConstantBooleanExpr.FALSE) { // the query is a contradiction, there are no matches return new EmptyResultQuery(queryFactory, cache, queryString, namedParameters, startOffset, maxResults); } // if cache is indexed but there is no actual 'where' filter clause and we do have sorting or projections we should still use the index, otherwise just go for a non-indexed fetch-all if (!isIndexed || (normalizedWhereClause == null || normalizedWhereClause == ConstantBooleanExpr.TRUE) && parsingResult.getProjections() == null && parsingResult.getSortFields() == null) { // fully non-indexed execution because the filter matches everything or there is no indexing at all return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults); } IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata = propertyHelper.getIndexedFieldProvider().get(parsingResult.getTargetEntityMetadata()); boolean allProjectionsAreStored = true; LinkedHashMap<PropertyPath, List<Integer>> projectionsMap = null; if (parsingResult.getProjectedPaths() != null) { projectionsMap = new LinkedHashMap<>(); for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) { PropertyPath<?> p = parsingResult.getProjectedPaths()[i]; List<Integer> idx = projectionsMap.get(p); if (idx == null) { idx = new ArrayList<>(); projectionsMap.put(p, idx); if (!fieldIndexingMetadata.isStored(p.asArrayPath())) { allProjectionsAreStored = false; } } idx.add(i); } } boolean allSortFieldsAreStored = true; SortField[] sortFields = parsingResult.getSortFields(); if (sortFields != null) { // deduplicate sort fields LinkedHashMap<String, SortField> sortFieldMap = new LinkedHashMap<>(); for (SortField sf : sortFields) { PropertyPath<?> p = sf.getPath(); String asStringPath = p.asStringPath(); if (!sortFieldMap.containsKey(asStringPath)) { sortFieldMap.put(asStringPath, sf); if (!fieldIndexingMetadata.isStored(p.asArrayPath())) { allSortFieldsAreStored = false; } } } sortFields = sortFieldMap.values().toArray(new SortField[sortFieldMap.size()]); } //todo [anistor] do not allow hybrid queries with fulltext. exception, allow a fully indexed query followed by in-memory aggregation. the aggregated or 'having' field should not be analyzed //todo [anistor] do we allow aggregation in fulltext queries? //todo [anistor] do not allow hybrid fulltext queries. all 'where' fields must be indexed. all projections must be stored. BooleShannonExpansion bse = new BooleShannonExpansion(MAX_EXPANSION_COFACTORS, fieldIndexingMetadata); BooleanExpr expansion = bse.expand(normalizedWhereClause); if (expansion == normalizedWhereClause) { // identity comparison is intended here! // all involved fields are indexed, so go the Lucene way if (allSortFieldsAreStored) { if (allProjectionsAreStored) { // all projections are stored, so we can execute the query entirely against the index, and we can also sort using the index RowProcessor rowProcessor = null; if (parsingResult.getProjectedPaths() != null) { if (projectionsMap.size() != parsingResult.getProjectedPaths().length) { // but some projections are duplicated ... final Class<?>[] projectedTypes = new Class<?>[projectionsMap.size()]; final int[] map = new int[parsingResult.getProjectedPaths().length]; int j = 0; for (List<Integer> idx : projectionsMap.values()) { int i = idx.get(0); projectedTypes[j] = parsingResult.getProjectedTypes()[i]; for (int k : idx) { map[k] = j; } j++; } RowProcessor projectionProcessor = makeProjectionProcessor(projectedTypes); rowProcessor = inRow -> { if (projectionProcessor != null) { inRow = projectionProcessor.process(inRow); } Object[] outRow = new Object[map.length]; for (int i = 0; i < map.length; i++) { outRow[i] = inRow[map[i]]; } return outRow; }; PropertyPath[] deduplicatedProjection = projectionsMap.keySet().toArray(new PropertyPath[projectionsMap.size()]); IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, deduplicatedProjection, projectedTypes, sortFields); return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults); } else { rowProcessor = makeProjectionProcessor(parsingResult.getProjectedTypes()); } } return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, parsingResult, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults); } else { IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, sortFields); Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), startOffset, maxResults); String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, null); return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), -1, -1, indexQuery); } } else { // projections may be stored but some sort fields are not so we need to query the index and then execute in-memory sorting and projecting in a second phase IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, null); Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1); String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, sortFields); return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), startOffset, maxResults, indexQuery); } } if (expansion == ConstantBooleanExpr.TRUE) { // expansion leads to a full non-indexed query or the expansion is too long/complex return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults); } // some fields are indexed, run a hybrid query IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, expansion, null, null, null); Query expandedQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1); return new HybridQuery(queryFactory, cache, queryString, namedParameters, getObjectFilter(matcher, queryString, namedParameters, null), startOffset, maxResults, expandedQuery); }
private BaseQuery buildQueryNoAggregations(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, long startOffset, int maxResults, IckleParsingResult<TypeMetadata> parsingResult) { if (parsingResult.hasGroupingOrAggregations()) { throw log.queryMustNotUseGroupingOrAggregation(); } boolean isFullTextQuery; if (parsingResult.getWhereClause() != null) { isFullTextQuery = parsingResult.getWhereClause().acceptVisitor(FullTextVisitor.INSTANCE); if (!isIndexed && isFullTextQuery) { throw new IllegalStateException("The cache must be indexed in order to use full-text queries."); } } if (parsingResult.getSortFields() != null) { for (SortField sortField : parsingResult.getSortFields()) { PropertyPath<?> p = sortField.getPath(); if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeUsedInOrderBy(p.toString()); } } } if (parsingResult.getProjectedPaths() != null) { for (PropertyPath<?> p : parsingResult.getProjectedPaths()) { if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeProjected(p.asStringPath()); } } } BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); if (normalizedWhereClause == ConstantBooleanExpr.FALSE) { return new EmptyResultQuery(queryFactory, cache, queryString, namedParameters, startOffset, maxResults); } if (!isIndexed || (normalizedWhereClause == null || normalizedWhereClause == ConstantBooleanExpr.TRUE) && parsingResult.getProjections() == null && parsingResult.getSortFields() == null) { return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults); } IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata = propertyHelper.getIndexedFieldProvider().get(parsingResult.getTargetEntityMetadata()); boolean allProjectionsAreStored = true; LinkedHashMap<PropertyPath, List<Integer>> projectionsMap = null; if (parsingResult.getProjectedPaths() != null) { projectionsMap = new LinkedHashMap<>(); for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) { PropertyPath<?> p = parsingResult.getProjectedPaths()[i]; List<Integer> idx = projectionsMap.get(p); if (idx == null) { idx = new ArrayList<>(); projectionsMap.put(p, idx); if (!fieldIndexingMetadata.isStored(p.asArrayPath())) { allProjectionsAreStored = false; } } idx.add(i); } } boolean allSortFieldsAreStored = true; SortField[] sortFields = parsingResult.getSortFields(); if (sortFields != null) { LinkedHashMap<String, SortField> sortFieldMap = new LinkedHashMap<>(); for (SortField sf : sortFields) { PropertyPath<?> p = sf.getPath(); String asStringPath = p.asStringPath(); if (!sortFieldMap.containsKey(asStringPath)) { sortFieldMap.put(asStringPath, sf); if (!fieldIndexingMetadata.isStored(p.asArrayPath())) { allSortFieldsAreStored = false; } } } sortFields = sortFieldMap.values().toArray(new SortField[sortFieldMap.size()]); } BooleShannonExpansion bse = new BooleShannonExpansion(MAX_EXPANSION_COFACTORS, fieldIndexingMetadata); BooleanExpr expansion = bse.expand(normalizedWhereClause); if (expansion == normalizedWhereClause) { if (allSortFieldsAreStored) { if (allProjectionsAreStored) { RowProcessor rowProcessor = null; if (parsingResult.getProjectedPaths() != null) { if (projectionsMap.size() != parsingResult.getProjectedPaths().length) { final Class<?>[] projectedTypes = new Class<?>[projectionsMap.size()]; final int[] map = new int[parsingResult.getProjectedPaths().length]; int j = 0; for (List<Integer> idx : projectionsMap.values()) { int i = idx.get(0); projectedTypes[j] = parsingResult.getProjectedTypes()[i]; for (int k : idx) { map[k] = j; } j++; } RowProcessor projectionProcessor = makeProjectionProcessor(projectedTypes); rowProcessor = inRow -> { if (projectionProcessor != null) { inRow = projectionProcessor.process(inRow); } Object[] outRow = new Object[map.length]; for (int i = 0; i < map.length; i++) { outRow[i] = inRow[map[i]]; } return outRow; }; PropertyPath[] deduplicatedProjection = projectionsMap.keySet().toArray(new PropertyPath[projectionsMap.size()]); IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, deduplicatedProjection, projectedTypes, sortFields); return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults); } else { rowProcessor = makeProjectionProcessor(parsingResult.getProjectedTypes()); } } return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, parsingResult, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults); } else { IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, sortFields); Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), startOffset, maxResults); String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, null); return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), -1, -1, indexQuery); } } else { IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, null); Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1); String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, sortFields); return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), startOffset, maxResults, indexQuery); } } if (expansion == ConstantBooleanExpr.TRUE) { return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults); } IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, expansion, null, null, null); Query expandedQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1); return new HybridQuery(queryFactory, cache, queryString, namedParameters, getObjectFilter(matcher, queryString, namedParameters, null), startOffset, maxResults, expandedQuery); }
private basequery buildquerynoaggregations(queryfactory queryfactory, string querystring, map<string, object> namedparameters, long startoffset, int maxresults, ickleparsingresult<typemetadata> parsingresult) { if (parsingresult.hasgroupingoraggregations()) { throw log.querymustnotusegroupingoraggregation(); } boolean isfulltextquery; if (parsingresult.getwhereclause() != null) { isfulltextquery = parsingresult.getwhereclause().acceptvisitor(fulltextvisitor.instance); if (!isindexed && isfulltextquery) { throw new illegalstateexception("the cache must be indexed in order to use full-text queries."); } } if (parsingresult.getsortfields() != null) { for (sortfield sortfield : parsingresult.getsortfields()) { propertypath<?> p = sortfield.getpath(); if (propertyhelper.isrepeatedproperty(parsingresult.gettargetentitymetadata(), p.asarraypath())) { throw log.multivaluedpropertycannotbeusedinorderby(p.tostring()); } } } if (parsingresult.getprojectedpaths() != null) { for (propertypath<?> p : parsingresult.getprojectedpaths()) { if (propertyhelper.isrepeatedproperty(parsingresult.gettargetentitymetadata(), p.asarraypath())) { throw log.multivaluedpropertycannotbeprojected(p.asstringpath()); } } } booleanexpr normalizedwhereclause = booleanfilternormalizer.normalize(parsingresult.getwhereclause()); if (normalizedwhereclause == constantbooleanexpr.false) { return new emptyresultquery(queryfactory, cache, querystring, namedparameters, startoffset, maxresults); } if (!isindexed || (normalizedwhereclause == null || normalizedwhereclause == constantbooleanexpr.true) && parsingresult.getprojections() == null && parsingresult.getsortfields() == null) { return new embeddedquery(this, queryfactory, cache, querystring, namedparameters, parsingresult.getprojections(), startoffset, maxresults); } indexedfieldprovider.fieldindexingmetadata fieldindexingmetadata = propertyhelper.getindexedfieldprovider().get(parsingresult.gettargetentitymetadata()); boolean allprojectionsarestored = true; linkedhashmap<propertypath, list<integer>> projectionsmap = null; if (parsingresult.getprojectedpaths() != null) { projectionsmap = new linkedhashmap<>(); for (int i = 0; i < parsingresult.getprojectedpaths().length; i++) { propertypath<?> p = parsingresult.getprojectedpaths()[i]; list<integer> idx = projectionsmap.get(p); if (idx == null) { idx = new arraylist<>(); projectionsmap.put(p, idx); if (!fieldindexingmetadata.isstored(p.asarraypath())) { allprojectionsarestored = false; } } idx.add(i); } } boolean allsortfieldsarestored = true; sortfield[] sortfields = parsingresult.getsortfields(); if (sortfields != null) { linkedhashmap<string, sortfield> sortfieldmap = new linkedhashmap<>(); for (sortfield sf : sortfields) { propertypath<?> p = sf.getpath(); string asstringpath = p.asstringpath(); if (!sortfieldmap.containskey(asstringpath)) { sortfieldmap.put(asstringpath, sf); if (!fieldindexingmetadata.isstored(p.asarraypath())) { allsortfieldsarestored = false; } } } sortfields = sortfieldmap.values().toarray(new sortfield[sortfieldmap.size()]); } booleshannonexpansion bse = new booleshannonexpansion(max_expansion_cofactors, fieldindexingmetadata); booleanexpr expansion = bse.expand(normalizedwhereclause); if (expansion == normalizedwhereclause) { if (allsortfieldsarestored) { if (allprojectionsarestored) { rowprocessor rowprocessor = null; if (parsingresult.getprojectedpaths() != null) { if (projectionsmap.size() != parsingresult.getprojectedpaths().length) { final class<?>[] projectedtypes = new class<?>[projectionsmap.size()]; final int[] map = new int[parsingresult.getprojectedpaths().length]; int j = 0; for (list<integer> idx : projectionsmap.values()) { int i = idx.get(0); projectedtypes[j] = parsingresult.getprojectedtypes()[i]; for (int k : idx) { map[k] = j; } j++; } rowprocessor projectionprocessor = makeprojectionprocessor(projectedtypes); rowprocessor = inrow -> { if (projectionprocessor != null) { inrow = projectionprocessor.process(inrow); } object[] outrow = new object[map.length]; for (int i = 0; i < map.length; i++) { outrow[i] = inrow[map[i]]; } return outrow; }; propertypath[] deduplicatedprojection = projectionsmap.keyset().toarray(new propertypath[projectionsmap.size()]); ickleparsingresult<typemetadata> fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, deduplicatedprojection, projectedtypes, sortfields); return new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, parsingresult.getprojections(), makeresultprocessor(rowprocessor), startoffset, maxresults); } else { rowprocessor = makeprojectionprocessor(parsingresult.getprojectedtypes()); } } return new embeddedlucenequery<>(this, queryfactory, namedparameters, parsingresult, parsingresult.getprojections(), makeresultprocessor(rowprocessor), startoffset, maxresults); } else { ickleparsingresult<typemetadata> fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, null, null, sortfields); query indexquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), startoffset, maxresults); string projectionquerystr = syntaxtreeprinter.printtree(parsingresult.gettargetentityname(), parsingresult.getprojectedpaths(), null, null); return new hybridquery(queryfactory, cache, projectionquerystr, null, getobjectfilter(matcher, projectionquerystr, null, null), -1, -1, indexquery); } } else { ickleparsingresult<typemetadata> fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, null, null, null); query indexquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), -1, -1); string projectionquerystr = syntaxtreeprinter.printtree(parsingresult.gettargetentityname(), parsingresult.getprojectedpaths(), null, sortfields); return new hybridquery(queryfactory, cache, projectionquerystr, null, getobjectfilter(matcher, projectionquerystr, null, null), startoffset, maxresults, indexquery); } } if (expansion == constantbooleanexpr.true) { return new embeddedquery(this, queryfactory, cache, querystring, namedparameters, parsingresult.getprojections(), startoffset, maxresults); } ickleparsingresult<typemetadata> fpr = makefilterparsingresult(parsingresult, expansion, null, null, null); query expandedquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), -1, -1); return new hybridquery(queryfactory, cache, querystring, namedparameters, getobjectfilter(matcher, querystring, namedparameters, null), startoffset, maxresults, expandedquery); }
TomasHofman/infinispan
[ 1, 0, 0, 0 ]
448
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
449
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
450
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
451
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
452
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
453
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { Arrays.fill(next[x], true); } } return next; }
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { Arrays.fill(next[x], true); } } return next; }
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { arrays.fill(next[x], true); } } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
16,885
@JsonGetter("limit") public String getLimit ( ) { return this.limit; }
@JsonGetter("limit") public String getLimit ( ) { return this.limit; }
@jsongetter("limit") public string getlimit ( ) { return this.limit; }
adams-okode/chirpstack-rest-sdk
[ 0, 0, 0, 0 ]
25,078
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
@Override protected void execute(CalculationMonitor monitor){ ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { idx = sampled.nextSetBit(idx); double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
@override protected void execute(calculationmonitor monitor){ imagedatafloat layersimg = new imagedatafloat(layersimage.getimagedata()); imagedatafloat intensimg = new imagedatafloat(intensityimage.getimagedata()); int nx = layersimg.getrows(); int ny = layersimg.getcols(); int nz = layersimg.getslices(); int nlayers = layersimg.getcomponents()-1; int nxyz = nx*ny*nz; float rx = layersimg.getheader().getdimresolutions()[0]; float ry = layersimg.getheader().getdimresolutions()[1]; float rz = layersimg.getheader().getdimresolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersimg.toarray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersimg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensimg.toarray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensimg = null; boolean[] ctxmask = new boolean[nxyz]; if (maskimage.getimagedata()!=null) { imagedataubyte maskimg = new imagedataubyte(maskimage.getimagedata()); byte[][][] bufferbyte = maskimg.toarray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskimg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialvolumefromsurface(x, y, z, layers[l], nx, ny, nz); } } } float delta = paramextent.getvalue().floatvalue()/numerics.min(rx,ry,rz); float stdev = paramstdev.getvalue().floatvalue()/numerics.min(rx,ry,rz); corticalprofile profile = new corticalprofile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; bitset sampled = new bitset(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findfastmarchingprofileneighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { idx = sampled.nextsetbit(idx); double weight = fastmath.exp(-0.5*numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } matrix mtx = new matrix(glm); matrix smp = new matrix(data); matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.norminf(); } } } string imgname = intensityimage.getimagedata().getname(); imagedatafloat mapdata = new imagedatafloat(mapping); mapdata.setheader(layersimage.getimagedata().getheader()); mapdata.setname(imgname+"_glmprofiles"); mappedimage.setvalue(mapdata); mapdata = null; mapping = null; imagedatafloat resdata = new imagedatafloat(residual); resdata.setheader(layersimage.getimagedata().getheader()); resdata.setname(imgname+"_glmresidual"); residualimage.setvalue(resdata); resdata = null; residual = null; }
alaurent4/nighres
[ 0, 1, 0, 0 ]
16,887
@JsonGetter("offset") public String getOffset ( ) { return this.offset; }
@JsonGetter("offset") public String getOffset ( ) { return this.offset; }
@jsongetter("offset") public string getoffset ( ) { return this.offset; }
adams-okode/chirpstack-rest-sdk
[ 0, 0, 0, 0 ]
16,886
@JsonSetter("limit") public void setLimit (String value) { this.limit = value; }
@JsonSetter("limit") public void setLimit (String value) { this.limit = value; }
@jsonsetter("limit") public void setlimit (string value) { this.limit = value; }
adams-okode/chirpstack-rest-sdk
[ 0, 0, 0, 0 ]
16,888
@JsonSetter("offset") public void setOffset (String value) { this.offset = value; }
@JsonSetter("offset") public void setOffset (String value) { this.offset = value; }
@jsonsetter("offset") public void setoffset (string value) { this.offset = value; }
adams-okode/chirpstack-rest-sdk
[ 0, 0, 0, 0 ]
25,180
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
public static int staticCompare(UUID u1, UUID u2) { int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
public static int staticcompare(uuid u1, uuid u2) { int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } if (type == uuidtype.time_based.raw()) { diff = compareulongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { diff = compareulongs(u1.getleastsignificantbits(), u2.getleastsignificantbits()); } } else { diff = compareulongs(u1.getmostsignificantbits(), u2.getmostsignificantbits()); if (diff == 0) { diff = compareulongs(u1.getleastsignificantbits(), u2.getleastsignificantbits()); } } return diff; }
andrebrait/java-uuid-generator
[ 0, 0, 0, 0 ]
653
public PlayerPathData populateStats() { this.playerEntity = strongholdPath.getPlayerEntity(); StrongholdGenerator.Start start = this.strongholdPath.getStart(); StrongholdTreeAccessor treeAccessor = (StrongholdTreeAccessor) start; List<StrongholdPathEntry> history = this.strongholdPath.getHistory(); ArrayList<StructurePiece> solution = new ArrayList<>(); StrongholdGenerator.Piece current = this.strongholdPath.getHistory().get(strongholdPath.getHistory().size() - 1).getCurrentPiece(); while (current != null) { solution.add(current); current = (StrongholdGenerator.Piece) treeAccessor.getParents().get(current); } List<StrongholdPathEntry> validEntries = history.stream() .filter(entry -> validateEntryForLoss(strongholdPath, strongholdPath.getNextEntry(entry))) .filter(entry -> !solution.contains(strongholdPath.getNextEntry(entry).getCurrentPiece()) && solution.contains(entry.getCurrentPiece())) .collect(Collectors.toList()); List<Pair<StrongholdPathEntry, Double>> losses = new ArrayList<>(); validEntries.forEach(strongholdPathEntry -> losses.add(new Pair<>(strongholdPathEntry, loss(strongholdPath, strongholdPath.getNextEntry(strongholdPathEntry), solution)))); this.inaccuracies = losses.stream().filter(pair -> pair.getRight() >= INACCURACY_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); this.mistakes = losses.stream().filter(pair -> pair.getRight() >= MISTAKE_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); this.blunders = losses.stream().filter(pair -> pair.getRight() >= BLUNDER_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); inaccuracies.removeAll(this.mistakes); mistakes.removeAll(this.blunders); ArrayList<Pair<StrongholdGenerator.Piece, Integer>> rooms = new ArrayList<>(); history.forEach(pathEntry -> { Pair<StrongholdGenerator.Piece, Integer> pair = new Pair<>(pathEntry.getCurrentPiece(), pathEntry.getTicksSpentInPiece().get()); rooms.add(pair); }); return new PlayerPathData( rooms, strongholdPath.getTotalTime(), computeDifficulty(solution), history.stream() .filter(pathEntry -> !solution.contains(pathEntry.getCurrentPiece())) .map(StrongholdPathEntry::getTicksSpentInPiece) .mapToInt(AtomicInteger::get) .sum(), // TODO: don't count entering the first Five-Way (int) history.stream() .map(strongholdPathEntry -> strongholdPath.getNextEntry(strongholdPathEntry)) .filter(Objects::nonNull) .map(StrongholdPathEntry::getCurrentPiece) .filter(solution::contains) .count(), this.inaccuracies.size(), this.mistakes.size(), this.blunders.size(), (int) history.stream() .filter(entry -> !(entry.getCurrentPiece() instanceof StrongholdGenerator.PortalRoom)) .filter(entry -> !areAdjacent(entry.getCurrentPiece(), strongholdPath.getNextEntry(entry).getCurrentPiece(), treeAccessor)) .count(), history.size() - 1, history.stream() .filter(entry -> FEINBERG_AVG_ROOM_TIMES.containsKey(entry.getCurrentPiece().getClass())) .mapToInt(value -> value.getTicksSpentInPiece().get() - FEINBERG_AVG_ROOM_TIMES.get(value.getCurrentPiece().getClass())) .sum() ); }
public PlayerPathData populateStats() { this.playerEntity = strongholdPath.getPlayerEntity(); StrongholdGenerator.Start start = this.strongholdPath.getStart(); StrongholdTreeAccessor treeAccessor = (StrongholdTreeAccessor) start; List<StrongholdPathEntry> history = this.strongholdPath.getHistory(); ArrayList<StructurePiece> solution = new ArrayList<>(); StrongholdGenerator.Piece current = this.strongholdPath.getHistory().get(strongholdPath.getHistory().size() - 1).getCurrentPiece(); while (current != null) { solution.add(current); current = (StrongholdGenerator.Piece) treeAccessor.getParents().get(current); } List<StrongholdPathEntry> validEntries = history.stream() .filter(entry -> validateEntryForLoss(strongholdPath, strongholdPath.getNextEntry(entry))) .filter(entry -> !solution.contains(strongholdPath.getNextEntry(entry).getCurrentPiece()) && solution.contains(entry.getCurrentPiece())) .collect(Collectors.toList()); List<Pair<StrongholdPathEntry, Double>> losses = new ArrayList<>(); validEntries.forEach(strongholdPathEntry -> losses.add(new Pair<>(strongholdPathEntry, loss(strongholdPath, strongholdPath.getNextEntry(strongholdPathEntry), solution)))); this.inaccuracies = losses.stream().filter(pair -> pair.getRight() >= INACCURACY_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); this.mistakes = losses.stream().filter(pair -> pair.getRight() >= MISTAKE_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); this.blunders = losses.stream().filter(pair -> pair.getRight() >= BLUNDER_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); inaccuracies.removeAll(this.mistakes); mistakes.removeAll(this.blunders); ArrayList<Pair<StrongholdGenerator.Piece, Integer>> rooms = new ArrayList<>(); history.forEach(pathEntry -> { Pair<StrongholdGenerator.Piece, Integer> pair = new Pair<>(pathEntry.getCurrentPiece(), pathEntry.getTicksSpentInPiece().get()); rooms.add(pair); }); return new PlayerPathData( rooms, strongholdPath.getTotalTime(), computeDifficulty(solution), history.stream() .filter(pathEntry -> !solution.contains(pathEntry.getCurrentPiece())) .map(StrongholdPathEntry::getTicksSpentInPiece) .mapToInt(AtomicInteger::get) .sum(), (int) history.stream() .map(strongholdPathEntry -> strongholdPath.getNextEntry(strongholdPathEntry)) .filter(Objects::nonNull) .map(StrongholdPathEntry::getCurrentPiece) .filter(solution::contains) .count(), this.inaccuracies.size(), this.mistakes.size(), this.blunders.size(), (int) history.stream() .filter(entry -> !(entry.getCurrentPiece() instanceof StrongholdGenerator.PortalRoom)) .filter(entry -> !areAdjacent(entry.getCurrentPiece(), strongholdPath.getNextEntry(entry).getCurrentPiece(), treeAccessor)) .count(), history.size() - 1, history.stream() .filter(entry -> FEINBERG_AVG_ROOM_TIMES.containsKey(entry.getCurrentPiece().getClass())) .mapToInt(value -> value.getTicksSpentInPiece().get() - FEINBERG_AVG_ROOM_TIMES.get(value.getCurrentPiece().getClass())) .sum() ); }
public playerpathdata populatestats() { this.playerentity = strongholdpath.getplayerentity(); strongholdgenerator.start start = this.strongholdpath.getstart(); strongholdtreeaccessor treeaccessor = (strongholdtreeaccessor) start; list<strongholdpathentry> history = this.strongholdpath.gethistory(); arraylist<structurepiece> solution = new arraylist<>(); strongholdgenerator.piece current = this.strongholdpath.gethistory().get(strongholdpath.gethistory().size() - 1).getcurrentpiece(); while (current != null) { solution.add(current); current = (strongholdgenerator.piece) treeaccessor.getparents().get(current); } list<strongholdpathentry> validentries = history.stream() .filter(entry -> validateentryforloss(strongholdpath, strongholdpath.getnextentry(entry))) .filter(entry -> !solution.contains(strongholdpath.getnextentry(entry).getcurrentpiece()) && solution.contains(entry.getcurrentpiece())) .collect(collectors.tolist()); list<pair<strongholdpathentry, double>> losses = new arraylist<>(); validentries.foreach(strongholdpathentry -> losses.add(new pair<>(strongholdpathentry, loss(strongholdpath, strongholdpath.getnextentry(strongholdpathentry), solution)))); this.inaccuracies = losses.stream().filter(pair -> pair.getright() >= inaccuracy_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); this.mistakes = losses.stream().filter(pair -> pair.getright() >= mistake_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); this.blunders = losses.stream().filter(pair -> pair.getright() >= blunder_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); inaccuracies.removeall(this.mistakes); mistakes.removeall(this.blunders); arraylist<pair<strongholdgenerator.piece, integer>> rooms = new arraylist<>(); history.foreach(pathentry -> { pair<strongholdgenerator.piece, integer> pair = new pair<>(pathentry.getcurrentpiece(), pathentry.getticksspentinpiece().get()); rooms.add(pair); }); return new playerpathdata( rooms, strongholdpath.gettotaltime(), computedifficulty(solution), history.stream() .filter(pathentry -> !solution.contains(pathentry.getcurrentpiece())) .map(strongholdpathentry::getticksspentinpiece) .maptoint(atomicinteger::get) .sum(), (int) history.stream() .map(strongholdpathentry -> strongholdpath.getnextentry(strongholdpathentry)) .filter(objects::nonnull) .map(strongholdpathentry::getcurrentpiece) .filter(solution::contains) .count(), this.inaccuracies.size(), this.mistakes.size(), this.blunders.size(), (int) history.stream() .filter(entry -> !(entry.getcurrentpiece() instanceof strongholdgenerator.portalroom)) .filter(entry -> !areadjacent(entry.getcurrentpiece(), strongholdpath.getnextentry(entry).getcurrentpiece(), treeaccessor)) .count(), history.size() - 1, history.stream() .filter(entry -> feinberg_avg_room_times.containskey(entry.getcurrentpiece().getclass())) .maptoint(value -> value.getticksspentinpiece().get() - feinberg_avg_room_times.get(value.getcurrentpiece().getclass())) .sum() ); }
ScribbleLP/StrongholdTrainer
[ 0, 1, 0, 0 ]
17,055
public void sendEmail(String userId1, String userId2, String asgmtName, double score, String recipientMail, String reportLink) throws Exception { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); String stud1 = userService.findById(userId1).getfName(); String stud2 = userService.findById(userId2).getfName(); helper.setTo("[email protected]"); helper.setText("Codesniffer found plagiarised submission with similarity score" + score + "Click the below link to view the full report+\n" + "https://s3.amazonaws.com/codesniffer-reports/" + reportLink+ "/match0.html"); // to do add link in email helper.setSubject("Plag detected in " + asgmtName + " between " + stud1 + " and " + stud2); sender.send(message); }
public void sendEmail(String userId1, String userId2, String asgmtName, double score, String recipientMail, String reportLink) throws Exception { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); String stud1 = userService.findById(userId1).getfName(); String stud2 = userService.findById(userId2).getfName(); helper.setTo("[email protected]"); helper.setText("Codesniffer found plagiarised submission with similarity score" + score + "Click the below link to view the full report+\n" + "https://s3.amazonaws.com/codesniffer-reports/" + reportLink+ "/match0.html"); helper.setSubject("Plag detected in " + asgmtName + " between " + stud1 + " and " + stud2); sender.send(message); }
public void sendemail(string userid1, string userid2, string asgmtname, double score, string recipientmail, string reportlink) throws exception { mimemessage message = sender.createmimemessage(); mimemessagehelper helper = new mimemessagehelper(message); string stud1 = userservice.findbyid(userid1).getfname(); string stud2 = userservice.findbyid(userid2).getfname(); helper.setto("[email protected]"); helper.settext("codesniffer found plagiarised submission with similarity score" + score + "click the below link to view the full report+\n" + "https://s3.amazonaws.com/codesniffer-reports/" + reportlink+ "/match0.html"); helper.setsubject("plag detected in " + asgmtname + " between " + stud1 + " and " + stud2); sender.send(message); }
Stephen3333/codesniffer
[ 0, 1, 0, 0 ]
17,081
@Override public void refresh() throws LoginException, GSSException { // TODO: do we need to call logout() on the LoginContext? loginContext = new LoginContext("", null, null, new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { ImmutableMap.Builder<String, String> options = ImmutableMap.builder(); options.put("refreshKrb5Config", "true"); options.put("doNotPrompt", "true"); options.put("useKeyTab", "true"); if (getBoolean("trino.client.debugKerberos")) { options.put("debug", "true"); } keytab.ifPresent(file -> options.put("keyTab", file.getAbsolutePath())); credentialCache.ifPresent(file -> { options.put("ticketCache", file.getAbsolutePath()); options.put("renewTGT", "true"); }); if (!keytab.isPresent() || credentialCache.isPresent()) { options.put("useTicketCache", "true"); } principal.ifPresent(value -> options.put("principal", value)); return new AppConfigurationEntry[] { new AppConfigurationEntry(Krb5LoginModule.class.getName(), REQUIRED, options.buildOrThrow()) }; } }); loginContext.login(); }
@Override public void refresh() throws LoginException, GSSException { loginContext = new LoginContext("", null, null, new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { ImmutableMap.Builder<String, String> options = ImmutableMap.builder(); options.put("refreshKrb5Config", "true"); options.put("doNotPrompt", "true"); options.put("useKeyTab", "true"); if (getBoolean("trino.client.debugKerberos")) { options.put("debug", "true"); } keytab.ifPresent(file -> options.put("keyTab", file.getAbsolutePath())); credentialCache.ifPresent(file -> { options.put("ticketCache", file.getAbsolutePath()); options.put("renewTGT", "true"); }); if (!keytab.isPresent() || credentialCache.isPresent()) { options.put("useTicketCache", "true"); } principal.ifPresent(value -> options.put("principal", value)); return new AppConfigurationEntry[] { new AppConfigurationEntry(Krb5LoginModule.class.getName(), REQUIRED, options.buildOrThrow()) }; } }); loginContext.login(); }
@override public void refresh() throws loginexception, gssexception { logincontext = new logincontext("", null, null, new configuration() { @override public appconfigurationentry[] getappconfigurationentry(string name) { immutablemap.builder<string, string> options = immutablemap.builder(); options.put("refreshkrb5config", "true"); options.put("donotprompt", "true"); options.put("usekeytab", "true"); if (getboolean("trino.client.debugkerberos")) { options.put("debug", "true"); } keytab.ifpresent(file -> options.put("keytab", file.getabsolutepath())); credentialcache.ifpresent(file -> { options.put("ticketcache", file.getabsolutepath()); options.put("renewtgt", "true"); }); if (!keytab.ispresent() || credentialcache.ispresent()) { options.put("useticketcache", "true"); } principal.ifpresent(value -> options.put("principal", value)); return new appconfigurationentry[] { new appconfigurationentry(krb5loginmodule.class.getname(), required, options.buildorthrow()) }; } }); logincontext.login(); }
SanjayTechGuru/TRINO
[ 1, 0, 0, 0 ]
17,089
@Override public void reduce(BytesWritable key, Iterable<BytesWritable> values, Context context) throws IOException, InterruptedException { int defCount = 0; refs.clear(); // We only expect two values, a DEF and a reference, but there might be more. for (BytesWritable type : values) { if (type.getLength() == DEF.getLength()) { defCount++; } else { byte[] bytes = new byte[type.getLength()]; System.arraycopy(type.getBytes(), 0, bytes, 0, type.getLength()); refs.add(bytes); } } // TODO check for more than one def, should not happen List<String> refsList = new ArrayList<>(refs.size()); String keyString = null; if (defCount == 0 || refs.size() != 1) { for (byte[] ref : refs) { refsList.add(COMMA_JOINER.join(Bytes.getLong(ref), Bytes.getLong(ref, 8))); } keyString = COMMA_JOINER.join(Bytes.getLong(key.getBytes()), Bytes.getLong(key.getBytes(), 8)); LOG.error("Linked List error: Key = " + keyString + " References = " + refsList); } if (defCount == 0 && refs.size() > 0) { // this is bad, found a node that is referenced but not defined. It must have been // lost, emit some info about this node for debugging purposes. context.write(new Text(keyString), new Text(refsList.toString())); context.getCounter(Counts.UNDEFINED).increment(1); } else if (defCount > 0 && refs.size() == 0) { // node is defined but not referenced context.write(new Text(keyString), new Text("none")); context.getCounter(Counts.UNREFERENCED).increment(1); } else { if (refs.size() > 1) { if (refsList != null) { context.write(new Text(keyString), new Text(refsList.toString())); } context.getCounter(Counts.EXTRAREFERENCES).increment(refs.size() - 1); } // node is defined and referenced context.getCounter(Counts.REFERENCED).increment(1); } }
@Override public void reduce(BytesWritable key, Iterable<BytesWritable> values, Context context) throws IOException, InterruptedException { int defCount = 0; refs.clear(); for (BytesWritable type : values) { if (type.getLength() == DEF.getLength()) { defCount++; } else { byte[] bytes = new byte[type.getLength()]; System.arraycopy(type.getBytes(), 0, bytes, 0, type.getLength()); refs.add(bytes); } } List<String> refsList = new ArrayList<>(refs.size()); String keyString = null; if (defCount == 0 || refs.size() != 1) { for (byte[] ref : refs) { refsList.add(COMMA_JOINER.join(Bytes.getLong(ref), Bytes.getLong(ref, 8))); } keyString = COMMA_JOINER.join(Bytes.getLong(key.getBytes()), Bytes.getLong(key.getBytes(), 8)); LOG.error("Linked List error: Key = " + keyString + " References = " + refsList); } if (defCount == 0 && refs.size() > 0) { context.write(new Text(keyString), new Text(refsList.toString())); context.getCounter(Counts.UNDEFINED).increment(1); } else if (defCount > 0 && refs.size() == 0) { context.write(new Text(keyString), new Text("none")); context.getCounter(Counts.UNREFERENCED).increment(1); } else { if (refs.size() > 1) { if (refsList != null) { context.write(new Text(keyString), new Text(refsList.toString())); } context.getCounter(Counts.EXTRAREFERENCES).increment(refs.size() - 1); } context.getCounter(Counts.REFERENCED).increment(1); } }
@override public void reduce(byteswritable key, iterable<byteswritable> values, context context) throws ioexception, interruptedexception { int defcount = 0; refs.clear(); for (byteswritable type : values) { if (type.getlength() == def.getlength()) { defcount++; } else { byte[] bytes = new byte[type.getlength()]; system.arraycopy(type.getbytes(), 0, bytes, 0, type.getlength()); refs.add(bytes); } } list<string> refslist = new arraylist<>(refs.size()); string keystring = null; if (defcount == 0 || refs.size() != 1) { for (byte[] ref : refs) { refslist.add(comma_joiner.join(bytes.getlong(ref), bytes.getlong(ref, 8))); } keystring = comma_joiner.join(bytes.getlong(key.getbytes()), bytes.getlong(key.getbytes(), 8)); log.error("linked list error: key = " + keystring + " references = " + refslist); } if (defcount == 0 && refs.size() > 0) { context.write(new text(keystring), new text(refslist.tostring())); context.getcounter(counts.undefined).increment(1); } else if (defcount > 0 && refs.size() == 0) { context.write(new text(keystring), new text("none")); context.getcounter(counts.unreferenced).increment(1); } else { if (refs.size() > 1) { if (refslist != null) { context.write(new text(keystring), new text(refslist.tostring())); } context.getcounter(counts.extrareferences).increment(refs.size() - 1); } context.getcounter(counts.referenced).increment(1); } }
YCjia/kudu
[ 1, 1, 0, 0 ]
748
public boolean addNewTodo(Request req, Response res) { res.type("application/json"); Object o = JSON.parse(req.body()); try { if(o.getClass().equals(BasicDBObject.class)) { try { BasicDBObject dbO = (BasicDBObject) o; String owner = dbO.getString("owner"); //For some reason age is a string right now, caused by angular. //This is a problem and should not be this way but here ya go boolean status = dbO.getBoolean("status"); String body = dbO.getString("body"); String category = dbO.getString("category"); System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']'); return todoController.addNewTodo(owner, category, body, status); } catch(NullPointerException e) { System.err.println("A value was malformed or omitted, new todo request failed."); return false; } } else { System.err.println("Expected BasicDBObject, received " + o.getClass()); return false; } } catch(RuntimeException ree) { ree.printStackTrace(); return false; } }
public boolean addNewTodo(Request req, Response res) { res.type("application/json"); Object o = JSON.parse(req.body()); try { if(o.getClass().equals(BasicDBObject.class)) { try { BasicDBObject dbO = (BasicDBObject) o; String owner = dbO.getString("owner"); boolean status = dbO.getBoolean("status"); String body = dbO.getString("body"); String category = dbO.getString("category"); System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']'); return todoController.addNewTodo(owner, category, body, status); } catch(NullPointerException e) { System.err.println("A value was malformed or omitted, new todo request failed."); return false; } } else { System.err.println("Expected BasicDBObject, received " + o.getClass()); return false; } } catch(RuntimeException ree) { ree.printStackTrace(); return false; } }
public boolean addnewtodo(request req, response res) { res.type("application/json"); object o = json.parse(req.body()); try { if(o.getclass().equals(basicdbobject.class)) { try { basicdbobject dbo = (basicdbobject) o; string owner = dbo.getstring("owner"); boolean status = dbo.getboolean("status"); string body = dbo.getstring("body"); string category = dbo.getstring("category"); system.err.println("adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']'); return todocontroller.addnewtodo(owner, category, body, status); } catch(nullpointerexception e) { system.err.println("a value was malformed or omitted, new todo request failed."); return false; } } else { system.err.println("expected basicdbobject, received " + o.getclass()); return false; } } catch(runtimeexception ree) { ree.printstacktrace(); return false; } }
UMM-CSci-3601-S18/lab-4-mongo-voyageurs-national-park
[ 0, 0, 1, 0 ]
25,329
public void shutdown() { try { LOGGER.info("Shutting down listener on " + host + ":" + port); running.set(false); // This isn't good, the Jedis object is not thread safe jedis.disconnect(); } catch (Exception e) { LOGGER.error("Caught exception while shutting down: " + e.getMessage()); } }
public void shutdown() { try { LOGGER.info("Shutting down listener on " + host + ":" + port); running.set(false); jedis.disconnect(); } catch (Exception e) { LOGGER.error("Caught exception while shutting down: " + e.getMessage()); } }
public void shutdown() { try { logger.info("shutting down listener on " + host + ":" + port); running.set(false); jedis.disconnect(); } catch (exception e) { logger.error("caught exception while shutting down: " + e.getmessage()); } }
Samsung/Spark-CEP
[ 1, 0, 0, 0 ]
17,260
public int getLineForVertical(int vertical) { int high = getLineCount(), low = -1, guess; while (high - low > 1) { guess = (high + low) / 2; if (getLineTop(guess) > vertical) high = guess; else low = guess; } if (low < 0) return 0; else return low; }
public int getLineForVertical(int vertical) { int high = getLineCount(), low = -1, guess; while (high - low > 1) { guess = (high + low) / 2; if (getLineTop(guess) > vertical) high = guess; else low = guess; } if (low < 0) return 0; else return low; }
public int getlineforvertical(int vertical) { int high = getlinecount(), low = -1, guess; while (high - low > 1) { guess = (high + low) / 2; if (getlinetop(guess) > vertical) high = guess; else low = guess; } if (low < 0) return 0; else return low; }
VPeruS/JotaTextEditor
[ 1, 0, 0, 0 ]
9,218
@Override public void visitElement(PsiElement element) { if (this.context.skip(element)) { return; } // TODO: the refactor this.holder.registerProblem(element, this.context.getMessage()); }
@Override public void visitElement(PsiElement element) { if (this.context.skip(element)) { return; } this.holder.registerProblem(element, this.context.getMessage()); }
@override public void visitelement(psielement element) { if (this.context.skip(element)) { return; } this.holder.registerproblem(element, this.context.getmessage()); }
aarthibl/intellibot
[ 1, 0, 0, 0 ]
9,220
private static ConfigurationOptions defaultOptions() { return ConfigurationOptions.defaults() .serializers(SpongeCommon.game().configManager().serializers()); }
private static ConfigurationOptions defaultOptions() { return ConfigurationOptions.defaults() .serializers(SpongeCommon.game().configManager().serializers()); }
private static configurationoptions defaultoptions() { return configurationoptions.defaults() .serializers(spongecommon.game().configmanager().serializers()); }
SpongePowered/Common
[ 1, 0, 0, 0 ]
25,606
@Test public void testRetrieveUserByName() { em.getTransaction().begin(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (1, 'BOOM1', '1988-09-15', 'TEST USER1');").executeUpdate(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (2, 'BOOM2', '1988-09-15', 'TEST USER2');").executeUpdate(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (3, 'BOOM3', '1988-09-15', 'TEST USER3');").executeUpdate(); em.getTransaction().commit(); List<User> users = null; try { //TODO use .equals() once we ahve overridden appropriate methods users = dao.getUsers(); } catch (Throwable th){ fail(th.getMessage()); } Calendar cal = Calendar.getInstance(); cal.set(1988, Calendar.SEPTEMBER, 15, 0, 0, 0); assertEquals(3, users.size()); for (int i = 0; i < 3; i++) { assertEquals("BOOM" + users.get(i).getId(), users.get(i).getName()); assertEquals("TEST USER" + users.get(i).getId(), users.get(i).getDescription()); assertEquals(cal.getTime().toString(), users.get(i).getDate().toString()); } }
@Test public void testRetrieveUserByName() { em.getTransaction().begin(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (1, 'BOOM1', '1988-09-15', 'TEST USER1');").executeUpdate(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (2, 'BOOM2', '1988-09-15', 'TEST USER2');").executeUpdate(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (3, 'BOOM3', '1988-09-15', 'TEST USER3');").executeUpdate(); em.getTransaction().commit(); List<User> users = null; try { users = dao.getUsers(); } catch (Throwable th){ fail(th.getMessage()); } Calendar cal = Calendar.getInstance(); cal.set(1988, Calendar.SEPTEMBER, 15, 0, 0, 0); assertEquals(3, users.size()); for (int i = 0; i < 3; i++) { assertEquals("BOOM" + users.get(i).getId(), users.get(i).getName()); assertEquals("TEST USER" + users.get(i).getId(), users.get(i).getDescription()); assertEquals(cal.getTime().toString(), users.get(i).getDate().toString()); } }
@test public void testretrieveuserbyname() { em.gettransaction().begin(); em.createnativequery("insert into t_users( user_id, name, date_added, description)" + " values (1, 'boom1', '1988-09-15', 'test user1');").executeupdate(); em.createnativequery("insert into t_users( user_id, name, date_added, description)" + " values (2, 'boom2', '1988-09-15', 'test user2');").executeupdate(); em.createnativequery("insert into t_users( user_id, name, date_added, description)" + " values (3, 'boom3', '1988-09-15', 'test user3');").executeupdate(); em.gettransaction().commit(); list<user> users = null; try { users = dao.getusers(); } catch (throwable th){ fail(th.getmessage()); } calendar cal = calendar.getinstance(); cal.set(1988, calendar.september, 15, 0, 0, 0); assertequals(3, users.size()); for (int i = 0; i < 3; i++) { assertequals("boom" + users.get(i).getid(), users.get(i).getname()); assertequals("test user" + users.get(i).getid(), users.get(i).getdescription()); assertequals(cal.gettime().tostring(), users.get(i).getdate().tostring()); } }
andrewflbarnes/debt-tracker
[ 0, 1, 0, 0 ]
1,134
private void restoreKVStateMetaData() throws IOException, StateMigrationException, RocksDBException { KeyedBackendSerializationProxy<K> serializationProxy = new KeyedBackendSerializationProxy<>(rocksDBKeyedStateBackend.userCodeClassLoader); serializationProxy.read(currentStateHandleInView); // check for key serializer compatibility; this also reconfigures the // key serializer to be compatible, if it is required and is possible if (CompatibilityUtil.resolveCompatibilityResult( serializationProxy.getKeySerializer(), UnloadableDummyTypeSerializer.class, serializationProxy.getKeySerializerConfigSnapshot(), rocksDBKeyedStateBackend.keySerializer) .isRequiresMigration()) { // TODO replace with state migration; note that key hash codes need to remain the same after migration throw new StateMigrationException("The new key serializer is not compatible to read previous keys. " + "Aborting now since state migration is currently not available"); } this.keygroupStreamCompressionDecorator = serializationProxy.isUsingKeyGroupCompression() ? SnappyStreamCompressionDecorator.INSTANCE : UncompressedStreamCompressionDecorator.INSTANCE; List<RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?>> restoredMetaInfos = serializationProxy.getStateMetaInfoSnapshots(); currentStateHandleKVStateColumnFamilies = new ArrayList<>(restoredMetaInfos.size()); //rocksDBKeyedStateBackend.restoredKvStateMetaInfos = new HashMap<>(restoredMetaInfos.size()); for (RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?> restoredMetaInfo : restoredMetaInfos) { Tuple2<ColumnFamilyHandle, RegisteredKeyedBackendStateMetaInfo<?, ?>> registeredColumn = rocksDBKeyedStateBackend.kvStateInformation.get(restoredMetaInfo.getName()); if (registeredColumn == null) { ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor( restoredMetaInfo.getName().getBytes(ConfigConstants.DEFAULT_CHARSET), rocksDBKeyedStateBackend.columnOptions); RegisteredKeyedBackendStateMetaInfo<?, ?> stateMetaInfo = new RegisteredKeyedBackendStateMetaInfo<>( restoredMetaInfo.getStateType(), restoredMetaInfo.getName(), restoredMetaInfo.getNamespaceSerializer(), restoredMetaInfo.getStateSerializer()); rocksDBKeyedStateBackend.restoredKvStateMetaInfos.put(restoredMetaInfo.getName(), restoredMetaInfo); ColumnFamilyHandle columnFamily = rocksDBKeyedStateBackend.db.createColumnFamily(columnFamilyDescriptor); registeredColumn = new Tuple2<ColumnFamilyHandle, RegisteredKeyedBackendStateMetaInfo<?, ?>>(columnFamily, stateMetaInfo); rocksDBKeyedStateBackend.kvStateInformation.put(stateMetaInfo.getName(), registeredColumn); } else { // TODO with eager state registration in place, check here for serializer migration strategies } currentStateHandleKVStateColumnFamilies.add(registeredColumn.f0); } }
private void restoreKVStateMetaData() throws IOException, StateMigrationException, RocksDBException { KeyedBackendSerializationProxy<K> serializationProxy = new KeyedBackendSerializationProxy<>(rocksDBKeyedStateBackend.userCodeClassLoader); serializationProxy.read(currentStateHandleInView); if (CompatibilityUtil.resolveCompatibilityResult( serializationProxy.getKeySerializer(), UnloadableDummyTypeSerializer.class, serializationProxy.getKeySerializerConfigSnapshot(), rocksDBKeyedStateBackend.keySerializer) .isRequiresMigration()) { throw new StateMigrationException("The new key serializer is not compatible to read previous keys. " + "Aborting now since state migration is currently not available"); } this.keygroupStreamCompressionDecorator = serializationProxy.isUsingKeyGroupCompression() ? SnappyStreamCompressionDecorator.INSTANCE : UncompressedStreamCompressionDecorator.INSTANCE; List<RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?>> restoredMetaInfos = serializationProxy.getStateMetaInfoSnapshots(); currentStateHandleKVStateColumnFamilies = new ArrayList<>(restoredMetaInfos.size()); for (RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?> restoredMetaInfo : restoredMetaInfos) { Tuple2<ColumnFamilyHandle, RegisteredKeyedBackendStateMetaInfo<?, ?>> registeredColumn = rocksDBKeyedStateBackend.kvStateInformation.get(restoredMetaInfo.getName()); if (registeredColumn == null) { ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor( restoredMetaInfo.getName().getBytes(ConfigConstants.DEFAULT_CHARSET), rocksDBKeyedStateBackend.columnOptions); RegisteredKeyedBackendStateMetaInfo<?, ?> stateMetaInfo = new RegisteredKeyedBackendStateMetaInfo<>( restoredMetaInfo.getStateType(), restoredMetaInfo.getName(), restoredMetaInfo.getNamespaceSerializer(), restoredMetaInfo.getStateSerializer()); rocksDBKeyedStateBackend.restoredKvStateMetaInfos.put(restoredMetaInfo.getName(), restoredMetaInfo); ColumnFamilyHandle columnFamily = rocksDBKeyedStateBackend.db.createColumnFamily(columnFamilyDescriptor); registeredColumn = new Tuple2<ColumnFamilyHandle, RegisteredKeyedBackendStateMetaInfo<?, ?>>(columnFamily, stateMetaInfo); rocksDBKeyedStateBackend.kvStateInformation.put(stateMetaInfo.getName(), registeredColumn); } else { } currentStateHandleKVStateColumnFamilies.add(registeredColumn.f0); } }
private void restorekvstatemetadata() throws ioexception, statemigrationexception, rocksdbexception { keyedbackendserializationproxy<k> serializationproxy = new keyedbackendserializationproxy<>(rocksdbkeyedstatebackend.usercodeclassloader); serializationproxy.read(currentstatehandleinview); if (compatibilityutil.resolvecompatibilityresult( serializationproxy.getkeyserializer(), unloadabledummytypeserializer.class, serializationproxy.getkeyserializerconfigsnapshot(), rocksdbkeyedstatebackend.keyserializer) .isrequiresmigration()) { throw new statemigrationexception("the new key serializer is not compatible to read previous keys. " + "aborting now since state migration is currently not available"); } this.keygroupstreamcompressiondecorator = serializationproxy.isusingkeygroupcompression() ? snappystreamcompressiondecorator.instance : uncompressedstreamcompressiondecorator.instance; list<registeredkeyedbackendstatemetainfo.snapshot<?, ?>> restoredmetainfos = serializationproxy.getstatemetainfosnapshots(); currentstatehandlekvstatecolumnfamilies = new arraylist<>(restoredmetainfos.size()); for (registeredkeyedbackendstatemetainfo.snapshot<?, ?> restoredmetainfo : restoredmetainfos) { tuple2<columnfamilyhandle, registeredkeyedbackendstatemetainfo<?, ?>> registeredcolumn = rocksdbkeyedstatebackend.kvstateinformation.get(restoredmetainfo.getname()); if (registeredcolumn == null) { columnfamilydescriptor columnfamilydescriptor = new columnfamilydescriptor( restoredmetainfo.getname().getbytes(configconstants.default_charset), rocksdbkeyedstatebackend.columnoptions); registeredkeyedbackendstatemetainfo<?, ?> statemetainfo = new registeredkeyedbackendstatemetainfo<>( restoredmetainfo.getstatetype(), restoredmetainfo.getname(), restoredmetainfo.getnamespaceserializer(), restoredmetainfo.getstateserializer()); rocksdbkeyedstatebackend.restoredkvstatemetainfos.put(restoredmetainfo.getname(), restoredmetainfo); columnfamilyhandle columnfamily = rocksdbkeyedstatebackend.db.createcolumnfamily(columnfamilydescriptor); registeredcolumn = new tuple2<columnfamilyhandle, registeredkeyedbackendstatemetainfo<?, ?>>(columnfamily, statemetainfo); rocksdbkeyedstatebackend.kvstateinformation.put(statemetainfo.getname(), registeredcolumn); } else { } currentstatehandlekvstatecolumnfamilies.add(registeredcolumn.f0); } }
alpinegizmo/flink
[ 1, 1, 0, 0 ]
1,136
private List<RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?>> readMetaData( StreamStateHandle metaStateHandle) throws Exception { FSDataInputStream inputStream = null; try { inputStream = metaStateHandle.openInputStream(); stateBackend.cancelStreamRegistry.registerClosable(inputStream); KeyedBackendSerializationProxy<T> serializationProxy = new KeyedBackendSerializationProxy<>(stateBackend.userCodeClassLoader); DataInputView in = new DataInputViewStreamWrapper(inputStream); serializationProxy.read(in); // check for key serializer compatibility; this also reconfigures the // key serializer to be compatible, if it is required and is possible if (CompatibilityUtil.resolveCompatibilityResult( serializationProxy.getKeySerializer(), UnloadableDummyTypeSerializer.class, serializationProxy.getKeySerializerConfigSnapshot(), stateBackend.keySerializer) .isRequiresMigration()) { // TODO replace with state migration; note that key hash codes need to remain the same after migration throw new StateMigrationException("The new key serializer is not compatible to read previous keys. " + "Aborting now since state migration is currently not available"); } return serializationProxy.getStateMetaInfoSnapshots(); } finally { if (inputStream != null) { stateBackend.cancelStreamRegistry.unregisterClosable(inputStream); inputStream.close(); } } }
private List<RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?>> readMetaData( StreamStateHandle metaStateHandle) throws Exception { FSDataInputStream inputStream = null; try { inputStream = metaStateHandle.openInputStream(); stateBackend.cancelStreamRegistry.registerClosable(inputStream); KeyedBackendSerializationProxy<T> serializationProxy = new KeyedBackendSerializationProxy<>(stateBackend.userCodeClassLoader); DataInputView in = new DataInputViewStreamWrapper(inputStream); serializationProxy.read(in); if (CompatibilityUtil.resolveCompatibilityResult( serializationProxy.getKeySerializer(), UnloadableDummyTypeSerializer.class, serializationProxy.getKeySerializerConfigSnapshot(), stateBackend.keySerializer) .isRequiresMigration()) { throw new StateMigrationException("The new key serializer is not compatible to read previous keys. " + "Aborting now since state migration is currently not available"); } return serializationProxy.getStateMetaInfoSnapshots(); } finally { if (inputStream != null) { stateBackend.cancelStreamRegistry.unregisterClosable(inputStream); inputStream.close(); } } }
private list<registeredkeyedbackendstatemetainfo.snapshot<?, ?>> readmetadata( streamstatehandle metastatehandle) throws exception { fsdatainputstream inputstream = null; try { inputstream = metastatehandle.openinputstream(); statebackend.cancelstreamregistry.registerclosable(inputstream); keyedbackendserializationproxy<t> serializationproxy = new keyedbackendserializationproxy<>(statebackend.usercodeclassloader); datainputview in = new datainputviewstreamwrapper(inputstream); serializationproxy.read(in); if (compatibilityutil.resolvecompatibilityresult( serializationproxy.getkeyserializer(), unloadabledummytypeserializer.class, serializationproxy.getkeyserializerconfigsnapshot(), statebackend.keyserializer) .isrequiresmigration()) { throw new statemigrationexception("the new key serializer is not compatible to read previous keys. " + "aborting now since state migration is currently not available"); } return serializationproxy.getstatemetainfosnapshots(); } finally { if (inputstream != null) { statebackend.cancelstreamregistry.unregisterclosable(inputstream); inputstream.close(); } } }
alpinegizmo/flink
[ 1, 0, 0, 0 ]
25,762
@Test public void testCreateDbAndTable() throws Exception { // 1. create connect context ConnectContext ctx = UtFrameUtils.createDefaultCtx(); // 2. create database db1 String createDbStmtStr = "create database db1;"; CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseAndAnalyzeStmt(createDbStmtStr, ctx); Catalog.getCurrentCatalog().createDb(createDbStmt); System.out.println(Catalog.getCurrentCatalog().getDbNames()); // 3. create table tbl1 String createTblStmtStr = "create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3'," + "'colocate_with' = 'g1');"; CreateTableStmt createTableStmt = (CreateTableStmt) UtFrameUtils.parseAndAnalyzeStmt(createTblStmtStr, ctx); Catalog.getCurrentCatalog().createTable(createTableStmt); // must set replicas' path hash, or the tablet scheduler won't work updateReplicaPathHash(); // 4. get and test the created db and table Database db = Catalog.getCurrentCatalog().getDbNullable("default_cluster:db1"); Assert.assertNotNull(db); OlapTable tbl = (OlapTable) db.getTableNullable("tbl1"); tbl.readLock(); try { Assert.assertNotNull(tbl); System.out.println(tbl.getName()); Assert.assertEquals("Doris", tbl.getEngine()); Assert.assertEquals(1, tbl.getBaseSchema().size()); } finally { tbl.readUnlock(); } // 5. process a schema change job String alterStmtStr = "alter table db1.tbl1 add column k2 int default '1'"; AlterTableStmt alterTableStmt = (AlterTableStmt) UtFrameUtils.parseAndAnalyzeStmt(alterStmtStr, ctx); Catalog.getCurrentCatalog().getAlterInstance().processAlterTable(alterTableStmt); // 6. check alter job Map<Long, AlterJobV2> alterJobs = Catalog.getCurrentCatalog().getSchemaChangeHandler().getAlterJobsV2(); Assert.assertEquals(1, alterJobs.size()); for (AlterJobV2 alterJobV2 : alterJobs.values()) { while (!alterJobV2.getJobState().isFinalState()) { System.out.println("alter job " + alterJobV2.getJobId() + " is running. state: " + alterJobV2.getJobState()); Thread.sleep(1000); } System.out.println("alter job " + alterJobV2.getJobId() + " is done. state: " + alterJobV2.getJobState()); Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); } OlapTable tbl1 = (OlapTable) db.getTableNullable("tbl1"); tbl1.readLock(); try { Assert.assertEquals(2, tbl1.getBaseSchema().size()); String baseIndexName = tbl1.getIndexNameById(tbl.getBaseIndexId()); Assert.assertEquals(baseIndexName, tbl1.getName()); MaterializedIndexMeta indexMeta = tbl1.getIndexMetaByIndexId(tbl1.getBaseIndexId()); Assert.assertNotNull(indexMeta); } finally { tbl1.readUnlock(); } // 7. query // TODO: we can not process real query for now. So it has to be a explain query String queryStr = "explain select * from db1.tbl1"; String a = UtFrameUtils.getSQLPlanOrErrorMsg(ctx, queryStr); System.out.println(a); StmtExecutor stmtExecutor = new StmtExecutor(ctx, queryStr); stmtExecutor.execute(); Planner planner = stmtExecutor.planner(); List<PlanFragment> fragments = planner.getFragments(); Assert.assertEquals(2, fragments.size()); PlanFragment fragment = fragments.get(1); Assert.assertTrue(fragment.getPlanRoot() instanceof OlapScanNode); Assert.assertEquals(0, fragment.getChildren().size()); // test show backends; BackendsProcDir dir = new BackendsProcDir(Catalog.getCurrentSystemInfo()); ProcResult result = dir.fetchResult(); Assert.assertEquals(BackendsProcDir.TITLE_NAMES.size(), result.getColumnNames().size()); Assert.assertEquals("{\"location\" : \"default\"}", result.getRows().get(0).get(19)); Assert.assertEquals("{\"lastSuccessReportTabletsTime\":\"N/A\",\"lastStreamLoadTime\":-1}", result.getRows().get(0).get(BackendsProcDir.TITLE_NAMES.size() - 1)); }
@Test public void testCreateDbAndTable() throws Exception { ConnectContext ctx = UtFrameUtils.createDefaultCtx(); String createDbStmtStr = "create database db1;"; CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseAndAnalyzeStmt(createDbStmtStr, ctx); Catalog.getCurrentCatalog().createDb(createDbStmt); System.out.println(Catalog.getCurrentCatalog().getDbNames()); String createTblStmtStr = "create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3'," + "'colocate_with' = 'g1');"; CreateTableStmt createTableStmt = (CreateTableStmt) UtFrameUtils.parseAndAnalyzeStmt(createTblStmtStr, ctx); Catalog.getCurrentCatalog().createTable(createTableStmt); updateReplicaPathHash(); Database db = Catalog.getCurrentCatalog().getDbNullable("default_cluster:db1"); Assert.assertNotNull(db); OlapTable tbl = (OlapTable) db.getTableNullable("tbl1"); tbl.readLock(); try { Assert.assertNotNull(tbl); System.out.println(tbl.getName()); Assert.assertEquals("Doris", tbl.getEngine()); Assert.assertEquals(1, tbl.getBaseSchema().size()); } finally { tbl.readUnlock(); } String alterStmtStr = "alter table db1.tbl1 add column k2 int default '1'"; AlterTableStmt alterTableStmt = (AlterTableStmt) UtFrameUtils.parseAndAnalyzeStmt(alterStmtStr, ctx); Catalog.getCurrentCatalog().getAlterInstance().processAlterTable(alterTableStmt); Map<Long, AlterJobV2> alterJobs = Catalog.getCurrentCatalog().getSchemaChangeHandler().getAlterJobsV2(); Assert.assertEquals(1, alterJobs.size()); for (AlterJobV2 alterJobV2 : alterJobs.values()) { while (!alterJobV2.getJobState().isFinalState()) { System.out.println("alter job " + alterJobV2.getJobId() + " is running. state: " + alterJobV2.getJobState()); Thread.sleep(1000); } System.out.println("alter job " + alterJobV2.getJobId() + " is done. state: " + alterJobV2.getJobState()); Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); } OlapTable tbl1 = (OlapTable) db.getTableNullable("tbl1"); tbl1.readLock(); try { Assert.assertEquals(2, tbl1.getBaseSchema().size()); String baseIndexName = tbl1.getIndexNameById(tbl.getBaseIndexId()); Assert.assertEquals(baseIndexName, tbl1.getName()); MaterializedIndexMeta indexMeta = tbl1.getIndexMetaByIndexId(tbl1.getBaseIndexId()); Assert.assertNotNull(indexMeta); } finally { tbl1.readUnlock(); } String queryStr = "explain select * from db1.tbl1"; String a = UtFrameUtils.getSQLPlanOrErrorMsg(ctx, queryStr); System.out.println(a); StmtExecutor stmtExecutor = new StmtExecutor(ctx, queryStr); stmtExecutor.execute(); Planner planner = stmtExecutor.planner(); List<PlanFragment> fragments = planner.getFragments(); Assert.assertEquals(2, fragments.size()); PlanFragment fragment = fragments.get(1); Assert.assertTrue(fragment.getPlanRoot() instanceof OlapScanNode); Assert.assertEquals(0, fragment.getChildren().size()); BackendsProcDir dir = new BackendsProcDir(Catalog.getCurrentSystemInfo()); ProcResult result = dir.fetchResult(); Assert.assertEquals(BackendsProcDir.TITLE_NAMES.size(), result.getColumnNames().size()); Assert.assertEquals("{\"location\" : \"default\"}", result.getRows().get(0).get(19)); Assert.assertEquals("{\"lastSuccessReportTabletsTime\":\"N/A\",\"lastStreamLoadTime\":-1}", result.getRows().get(0).get(BackendsProcDir.TITLE_NAMES.size() - 1)); }
@test public void testcreatedbandtable() throws exception { connectcontext ctx = utframeutils.createdefaultctx(); string createdbstmtstr = "create database db1;"; createdbstmt createdbstmt = (createdbstmt) utframeutils.parseandanalyzestmt(createdbstmtstr, ctx); catalog.getcurrentcatalog().createdb(createdbstmt); system.out.println(catalog.getcurrentcatalog().getdbnames()); string createtblstmtstr = "create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3'," + "'colocate_with' = 'g1');"; createtablestmt createtablestmt = (createtablestmt) utframeutils.parseandanalyzestmt(createtblstmtstr, ctx); catalog.getcurrentcatalog().createtable(createtablestmt); updatereplicapathhash(); database db = catalog.getcurrentcatalog().getdbnullable("default_cluster:db1"); assert.assertnotnull(db); olaptable tbl = (olaptable) db.gettablenullable("tbl1"); tbl.readlock(); try { assert.assertnotnull(tbl); system.out.println(tbl.getname()); assert.assertequals("doris", tbl.getengine()); assert.assertequals(1, tbl.getbaseschema().size()); } finally { tbl.readunlock(); } string alterstmtstr = "alter table db1.tbl1 add column k2 int default '1'"; altertablestmt altertablestmt = (altertablestmt) utframeutils.parseandanalyzestmt(alterstmtstr, ctx); catalog.getcurrentcatalog().getalterinstance().processaltertable(altertablestmt); map<long, alterjobv2> alterjobs = catalog.getcurrentcatalog().getschemachangehandler().getalterjobsv2(); assert.assertequals(1, alterjobs.size()); for (alterjobv2 alterjobv2 : alterjobs.values()) { while (!alterjobv2.getjobstate().isfinalstate()) { system.out.println("alter job " + alterjobv2.getjobid() + " is running. state: " + alterjobv2.getjobstate()); thread.sleep(1000); } system.out.println("alter job " + alterjobv2.getjobid() + " is done. state: " + alterjobv2.getjobstate()); assert.assertequals(alterjobv2.jobstate.finished, alterjobv2.getjobstate()); } olaptable tbl1 = (olaptable) db.gettablenullable("tbl1"); tbl1.readlock(); try { assert.assertequals(2, tbl1.getbaseschema().size()); string baseindexname = tbl1.getindexnamebyid(tbl.getbaseindexid()); assert.assertequals(baseindexname, tbl1.getname()); materializedindexmeta indexmeta = tbl1.getindexmetabyindexid(tbl1.getbaseindexid()); assert.assertnotnull(indexmeta); } finally { tbl1.readunlock(); } string querystr = "explain select * from db1.tbl1"; string a = utframeutils.getsqlplanorerrormsg(ctx, querystr); system.out.println(a); stmtexecutor stmtexecutor = new stmtexecutor(ctx, querystr); stmtexecutor.execute(); planner planner = stmtexecutor.planner(); list<planfragment> fragments = planner.getfragments(); assert.assertequals(2, fragments.size()); planfragment fragment = fragments.get(1); assert.asserttrue(fragment.getplanroot() instanceof olapscannode); assert.assertequals(0, fragment.getchildren().size()); backendsprocdir dir = new backendsprocdir(catalog.getcurrentsysteminfo()); procresult result = dir.fetchresult(); assert.assertequals(backendsprocdir.title_names.size(), result.getcolumnnames().size()); assert.assertequals("{\"location\" : \"default\"}", result.getrows().get(0).get(19)); assert.assertequals("{\"lastsuccessreporttabletstime\":\"n/a\",\"laststreamloadtime\":-1}", result.getrows().get(0).get(backendsprocdir.title_names.size() - 1)); }
WilsonWangCS/incubator-doris
[ 1, 0, 0, 0 ]
17,588
private void registerSnapshot () { try { Statement statement = connection.createStatement(); // TODO copy over feed_id and feed_version from source namespace? // FIXME do the following only on databases that support schemas. // SQLite does not support them. Is there any advantage of schemas over flat tables? statement.execute("create schema " + tablePrefix); // TODO: Record total snapshot processing time? // Simply insert into feeds table (no need for table creation) because making a snapshot presumes that the // feeds table already exists. PreparedStatement insertStatement = connection.prepareStatement( "insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)"); insertStatement.setString(1, tablePrefix); insertStatement.setString(2, feedIdToSnapshot); insertStatement.execute(); connection.commit(); LOG.info("Created new snapshot namespace: {}", insertStatement); } catch (Exception ex) { LOG.error("Exception while registering snapshot namespace in feeds table: {}", ex.getMessage()); DbUtils.closeQuietly(connection); } }
private void registerSnapshot () { try { Statement statement = connection.createStatement(); statement.execute("create schema " + tablePrefix); PreparedStatement insertStatement = connection.prepareStatement( "insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)"); insertStatement.setString(1, tablePrefix); insertStatement.setString(2, feedIdToSnapshot); insertStatement.execute(); connection.commit(); LOG.info("Created new snapshot namespace: {}", insertStatement); } catch (Exception ex) { LOG.error("Exception while registering snapshot namespace in feeds table: {}", ex.getMessage()); DbUtils.closeQuietly(connection); } }
private void registersnapshot () { try { statement statement = connection.createstatement(); statement.execute("create schema " + tableprefix); preparedstatement insertstatement = connection.preparestatement( "insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)"); insertstatement.setstring(1, tableprefix); insertstatement.setstring(2, feedidtosnapshot); insertstatement.execute(); connection.commit(); log.info("created new snapshot namespace: {}", insertstatement); } catch (exception ex) { log.error("exception while registering snapshot namespace in feeds table: {}", ex.getmessage()); dbutils.closequietly(connection); } }
Wilhansen/gtfs-lib
[ 1, 1, 0, 0 ]
9,474
@Override protected void channelRead0(ChannelHandlerContext ctx, CoapMessage msg) { try { // Find proper device and raise event. Device targetDevice = ctx.channel().attr(keyDevice).get(); if (targetDevice == null) { throw new InternalServerErrorException( "Unable to find device"); } if (msg instanceof CoapRequest) { onRequestReceived(targetDevice, (CoapRequest) msg); } else if (msg instanceof CoapResponse) { // TODO: Re-architecturing required IRequestChannel reqChannel = ((CoapDevice) targetDevice) .getRequestChannel(); CoapClient coapClient = (CoapClient) reqChannel; coapClient.onResponseReceived(msg); } } catch (ServerException e) { ctx.writeAndFlush(MessageBuilder.createResponse(msg, e.getErrorResponse())); Log.f(ctx.channel(), e); } catch (ClientException e) { Log.f(ctx.channel(), e); } catch (Throwable t) { Log.f(ctx.channel(), t); if (msg instanceof CoapRequest) { ctx.writeAndFlush(MessageBuilder.createResponse(msg, ResponseStatus.INTERNAL_SERVER_ERROR)); } } }
@Override protected void channelRead0(ChannelHandlerContext ctx, CoapMessage msg) { try { Device targetDevice = ctx.channel().attr(keyDevice).get(); if (targetDevice == null) { throw new InternalServerErrorException( "Unable to find device"); } if (msg instanceof CoapRequest) { onRequestReceived(targetDevice, (CoapRequest) msg); } else if (msg instanceof CoapResponse) { IRequestChannel reqChannel = ((CoapDevice) targetDevice) .getRequestChannel(); CoapClient coapClient = (CoapClient) reqChannel; coapClient.onResponseReceived(msg); } } catch (ServerException e) { ctx.writeAndFlush(MessageBuilder.createResponse(msg, e.getErrorResponse())); Log.f(ctx.channel(), e); } catch (ClientException e) { Log.f(ctx.channel(), e); } catch (Throwable t) { Log.f(ctx.channel(), t); if (msg instanceof CoapRequest) { ctx.writeAndFlush(MessageBuilder.createResponse(msg, ResponseStatus.INTERNAL_SERVER_ERROR)); } } }
@override protected void channelread0(channelhandlercontext ctx, coapmessage msg) { try { device targetdevice = ctx.channel().attr(keydevice).get(); if (targetdevice == null) { throw new internalservererrorexception( "unable to find device"); } if (msg instanceof coaprequest) { onrequestreceived(targetdevice, (coaprequest) msg); } else if (msg instanceof coapresponse) { irequestchannel reqchannel = ((coapdevice) targetdevice) .getrequestchannel(); coapclient coapclient = (coapclient) reqchannel; coapclient.onresponsereceived(msg); } } catch (serverexception e) { ctx.writeandflush(messagebuilder.createresponse(msg, e.geterrorresponse())); log.f(ctx.channel(), e); } catch (clientexception e) { log.f(ctx.channel(), e); } catch (throwable t) { log.f(ctx.channel(), t); if (msg instanceof coaprequest) { ctx.writeandflush(messagebuilder.createresponse(msg, responsestatus.internal_server_error)); } } }
SenthilKumarGS/TizenRT
[ 1, 0, 0, 0 ]
9,490
public LNode reverseListRec(LNode head) { // TODO: implement this method /*This method takes a reference to the head of a linked list and returns the reference to the head of the linked list in the reversed order. */ if(head == null) { return head; } if(head.getLink() == null) { return head; } head.getLink().setLink(head); head.setLink(null); return reverseListRec(head); // replace this statement with your own return }
public LNode reverseListRec(LNode head) { if(head == null) { return head; } if(head.getLink() == null) { return head; } head.getLink().setLink(head); head.setLink(null); return reverseListRec(head); }
public lnode reverselistrec(lnode head) { if(head == null) { return head; } if(head.getlink() == null) { return head; } head.getlink().setlink(head); head.setlink(null); return reverselistrec(head); }
Sailia/data_structures
[ 0, 1, 0, 0 ]
17,706
@SuppressWarnings("ParameterName") public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative) { // ask the kinematics to determine our swerve command ChassisSpeeds speeds; if (fieldRelative == true) { speeds = ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, rot, getHeading()); } else { speeds = new ChassisSpeeds(xSpeed, ySpeed, rot); } SwerveModuleState[] swerveModuleStates = kinematics.toSwerveModuleStates(speeds); // sometime the Kinematics spits out too fast of speeds, so this will fix this SwerveDriveKinematics.desaturateWheelSpeeds(swerveModuleStates, kMaxSpeed); // command each swerve module for (int i = 0; i < modules.length; i++) { modules[i].setDesiredState(swerveModuleStates[i]); } // report our commands to the dashboard SmartDashboard.putNumber("SwerveDrive/xSpeed", xSpeed); SmartDashboard.putNumber("SwerveDrive/ySpeed", ySpeed); SmartDashboard.putNumber("SwerveDrive/rot", rot); SmartDashboard.putBoolean("SwerveDrive/fieldRelative", fieldRelative); }
@SuppressWarnings("ParameterName") public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative) { ChassisSpeeds speeds; if (fieldRelative == true) { speeds = ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, rot, getHeading()); } else { speeds = new ChassisSpeeds(xSpeed, ySpeed, rot); } SwerveModuleState[] swerveModuleStates = kinematics.toSwerveModuleStates(speeds); SwerveDriveKinematics.desaturateWheelSpeeds(swerveModuleStates, kMaxSpeed); for (int i = 0; i < modules.length; i++) { modules[i].setDesiredState(swerveModuleStates[i]); } SmartDashboard.putNumber("SwerveDrive/xSpeed", xSpeed); SmartDashboard.putNumber("SwerveDrive/ySpeed", ySpeed); SmartDashboard.putNumber("SwerveDrive/rot", rot); SmartDashboard.putBoolean("SwerveDrive/fieldRelative", fieldRelative); }
@suppresswarnings("parametername") public void drive(double xspeed, double yspeed, double rot, boolean fieldrelative) { chassisspeeds speeds; if (fieldrelative == true) { speeds = chassisspeeds.fromfieldrelativespeeds(xspeed, yspeed, rot, getheading()); } else { speeds = new chassisspeeds(xspeed, yspeed, rot); } swervemodulestate[] swervemodulestates = kinematics.toswervemodulestates(speeds); swervedrivekinematics.desaturatewheelspeeds(swervemodulestates, kmaxspeed); for (int i = 0; i < modules.length; i++) { modules[i].setdesiredstate(swervemodulestates[i]); } smartdashboard.putnumber("swervedrive/xspeed", xspeed); smartdashboard.putnumber("swervedrive/yspeed", yspeed); smartdashboard.putnumber("swervedrive/rot", rot); smartdashboard.putboolean("swervedrive/fieldrelative", fieldrelative); }
Sammoore15/Robot2022-2832-altencoderforingestor
[ 0, 0, 0, 0 ]
1,344
private int generateNewTicketNumber() { //TODO: this may take foreever. fix int generated = numberGenerator.next(); while(purchased.containsKey(generated)){ generated = numberGenerator.next(); } return generated; }
private int generateNewTicketNumber() { int generated = numberGenerator.next(); while(purchased.containsKey(generated)){ generated = numberGenerator.next(); } return generated; }
private int generatenewticketnumber() { int generated = numbergenerator.next(); while(purchased.containskey(generated)){ generated = numbergenerator.next(); } return generated; }
aha0x0x/LotteryApplication
[ 0, 0, 1, 0 ]
17,729
public void setParentAtRowAndColumn(GridLayout parent, int row, int col) { // prepare the layout parameters for the EditText // TODO: Consider caching the layout params and only changing the spec row and spec column LayoutParams layoutParams = new GridLayout.LayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT; // set the row and column in the correct location of the Sudoku Board layoutParams.rowSpec = GridLayout.spec(row); layoutParams.columnSpec = GridLayout.spec(col); // set the layout params and add the EditText to the GridLayout parent _text.setLayoutParams(layoutParams); parent.addView(_text); }
public void setParentAtRowAndColumn(GridLayout parent, int row, int col) { LayoutParams layoutParams = new GridLayout.LayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.rowSpec = GridLayout.spec(row); layoutParams.columnSpec = GridLayout.spec(col); _text.setLayoutParams(layoutParams); parent.addView(_text); }
public void setparentatrowandcolumn(gridlayout parent, int row, int col) { layoutparams layoutparams = new gridlayout.layoutparams(); layoutparams.width = layoutparams.wrap_content; layoutparams.height = layoutparams.wrap_content; layoutparams.rowspec = gridlayout.spec(row); layoutparams.columnspec = gridlayout.spec(col); _text.setlayoutparams(layoutparams); parent.addview(_text); }
SnoBoarder/Sudoku-Solver
[ 0, 1, 0, 0 ]
34,188
public void testZKSMFalse() throws ZKSetMembershipException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4")}; EncryptedInteger c = new EncryptedInteger(new BigInteger("10"), pub); BigInteger r = c.set(new BigInteger("10")); int msgIndex = 2; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability } }
public void testZKSMFalse() throws ZKSetMembershipException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4")}; EncryptedInteger c = new EncryptedInteger(new BigInteger("10"), pub); BigInteger r = c.set(new BigInteger("10")); int msgIndex = 2; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); } }
public void testzksmfalse() throws zksetmembershipexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger("0"), new biginteger("1"), new biginteger("2"), new biginteger("3"), new biginteger("4")}; encryptedinteger c = new encryptedinteger(new biginteger("10"), pub); biginteger r = c.set(new biginteger("10")); int msgindex = 2; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger("128")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }
SoftwareEngineeringToolDemos/type-inference
[ 0, 0, 1, 0 ]
34,189
public void testZKSMSingleMemberSetFalse() throws ZKSetMembershipException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0")}; EncryptedInteger c = new EncryptedInteger(BigInteger.ONE, pub); BigInteger r = c.set(BigInteger.ONE); int msgIndex = 0; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability } }
public void testZKSMSingleMemberSetFalse() throws ZKSetMembershipException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0")}; EncryptedInteger c = new EncryptedInteger(BigInteger.ONE, pub); BigInteger r = c.set(BigInteger.ONE); int msgIndex = 0; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); } }
public void testzksmsinglemembersetfalse() throws zksetmembershipexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger("0")}; encryptedinteger c = new encryptedinteger(biginteger.one, pub); biginteger r = c.set(biginteger.one); int msgindex = 0; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger("128")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }
SoftwareEngineeringToolDemos/type-inference
[ 0, 0, 1, 0 ]
34,190
public void testZKSMAddTrue() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"), new BigInteger("6")}; EncryptedInteger c1 = new EncryptedInteger(new BigInteger("2"), pub); BigInteger r1 = c1.set(new BigInteger("2")); EncryptedInteger c2 = new EncryptedInteger(new BigInteger("3"), pub); BigInteger r2 = c2.set(new BigInteger("3")); EncryptedInteger c = c1.add(c2); BigInteger r = r1.multiply(r2).mod(this.pub.getNSquared()); int msgIndex = 5; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability } }
public void testZKSMAddTrue() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"), new BigInteger("6")}; EncryptedInteger c1 = new EncryptedInteger(new BigInteger("2"), pub); BigInteger r1 = c1.set(new BigInteger("2")); EncryptedInteger c2 = new EncryptedInteger(new BigInteger("3"), pub); BigInteger r2 = c2.set(new BigInteger("3")); EncryptedInteger c = c1.add(c2); BigInteger r = r1.multiply(r2).mod(this.pub.getNSquared()); int msgIndex = 5; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); } }
public void testzksmaddtrue() throws zksetmembershipexception, publickeysnotequalexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger("0"), new biginteger("1"), new biginteger("2"), new biginteger("3"), new biginteger("4"), new biginteger("6")}; encryptedinteger c1 = new encryptedinteger(new biginteger("2"), pub); biginteger r1 = c1.set(new biginteger("2")); encryptedinteger c2 = new encryptedinteger(new biginteger("3"), pub); biginteger r2 = c2.set(new biginteger("3")); encryptedinteger c = c1.add(c2); biginteger r = r1.multiply(r2).mod(this.pub.getnsquared()); int msgindex = 5; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger("128")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }
SoftwareEngineeringToolDemos/type-inference
[ 0, 0, 1, 0 ]
34,191
public void testZKSMManyOperations() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"), new BigInteger("6")}; EncryptedInteger c1 = new EncryptedInteger(new BigInteger("2"), pub); BigInteger r1 = c1.set(new BigInteger("2")); EncryptedInteger c2 = new EncryptedInteger(new BigInteger("3"), pub); BigInteger r2 = c2.set(new BigInteger("3")); EncryptedInteger c = c1.add(c2); BigInteger r = r1.multiply(r2).mod(this.pub.getNSquared()); int msgIndex = 5; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability } }
public void testZKSMManyOperations() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"), new BigInteger("6")}; EncryptedInteger c1 = new EncryptedInteger(new BigInteger("2"), pub); BigInteger r1 = c1.set(new BigInteger("2")); EncryptedInteger c2 = new EncryptedInteger(new BigInteger("3"), pub); BigInteger r2 = c2.set(new BigInteger("3")); EncryptedInteger c = c1.add(c2); BigInteger r = r1.multiply(r2).mod(this.pub.getNSquared()); int msgIndex = 5; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); } }
public void testzksmmanyoperations() throws zksetmembershipexception, publickeysnotequalexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger("0"), new biginteger("1"), new biginteger("2"), new biginteger("3"), new biginteger("4"), new biginteger("6")}; encryptedinteger c1 = new encryptedinteger(new biginteger("2"), pub); biginteger r1 = c1.set(new biginteger("2")); encryptedinteger c2 = new encryptedinteger(new biginteger("3"), pub); biginteger r2 = c2.set(new biginteger("3")); encryptedinteger c = c1.add(c2); biginteger r = r1.multiply(r2).mod(this.pub.getnsquared()); int msgindex = 5; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger("128")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }
SoftwareEngineeringToolDemos/type-inference
[ 0, 0, 1, 0 ]
34,311
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { fails += errors; errors = 0; testCount = 1; assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
private void asserttestsummary() { int fails = testresult.fails().size(); int errors = testresult.errors().size(); int succeeds = testresult.succeeds().size(); int testcount = fails + errors + succeeds; if (testmode.isj2cl()) { fails += errors; errors = 0; testcount = 1; assertthat(consolelogs.stream().filter(x -> x.contains(": passed"))).hassize(succeeds); } if (fails + errors > 0) { asserttestsummaryforfailure(fails, errors, testcount); } else { asserttestsummaryforsuccess(testcount); } }
VishrutMehta/j2cl
[ 0, 0, 1, 0 ]
18,084
public boolean connect(long timeoutMs) { if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout")); long startMs = System.currentTimeMillis(); long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs); long currentTime = startMs; Throwable lastError = null; int attempt = 0; while (currentTime <= endMs) { currentTime = System.currentTimeMillis(); if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime); try { connect(); return true; } catch (Exception e) { Exceptions.propagateIfFatal(e); if (!terminated.get() && shouldRetryOn(e)) { if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()}); lastError = e; } else { throw Exceptions.propagate(e); } } attempt++; } LOG.warn("unable to connect to JMX url: "+url, lastError); return false; }
public boolean connect(long timeoutMs) { if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout")); long startMs = System.currentTimeMillis(); long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs); long currentTime = startMs; Throwable lastError = null; int attempt = 0; while (currentTime <= endMs) { currentTime = System.currentTimeMillis(); if (attempt != 0) sleep(100); if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime); try { connect(); return true; } catch (Exception e) { Exceptions.propagateIfFatal(e); if (!terminated.get() && shouldRetryOn(e)) { if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()}); lastError = e; } else { throw Exceptions.propagate(e); } } attempt++; } LOG.warn("unable to connect to JMX url: "+url, lastError); return false; }
public boolean connect(long timeoutms) { if (log.isdebugenabled()) log.debug("connecting to jmx url: {} ({})", url, ((timeoutms == -1) ? "indefinitely" : timeoutms+"ms timeout")); long startms = system.currenttimemillis(); long endms = (timeoutms == -1) ? long.max_value : (startms + timeoutms); long currenttime = startms; throwable lasterror = null; int attempt = 0; while (currenttime <= endms) { currenttime = system.currenttimemillis(); if (attempt != 0) sleep(100); if (log.istraceenabled()) log.trace("trying connection to {} at time {}", url, currenttime); try { connect(); return true; } catch (exception e) { exceptions.propagateiffatal(e); if (!terminated.get() && shouldretryon(e)) { if (log.isdebugenabled()) log.debug("attempt {} failed connecting to {} ({})", new object[] {attempt + 1, url, e.getmessage()}); lasterror = e; } else { throw exceptions.propagate(e); } } attempt++; } log.warn("unable to connect to jmx url: "+url, lasterror); return false; }
YYTVicky/brooklyn-server
[ 1, 0, 0, 0 ]
34,588
public String toString(int indentFactor) { try { StringWriter w = new StringWriter(); synchronized (w.getBuffer()) { return this.write(w, indentFactor, 0).toString(); } } catch (Exception e) { //there is no conceivable exception that can come out of this, but throw something //just in case. Want the signature to not have exception in it. throw new RuntimeException("Can not serialize JSONObject????", e); } }
public String toString(int indentFactor) { try { StringWriter w = new StringWriter(); synchronized (w.getBuffer()) { return this.write(w, indentFactor, 0).toString(); } } catch (Exception e) { throw new RuntimeException("Can not serialize JSONObject????", e); } }
public string tostring(int indentfactor) { try { stringwriter w = new stringwriter(); synchronized (w.getbuffer()) { return this.write(w, indentfactor, 0).tostring(); } } catch (exception e) { throw new runtimeexception("can not serialize jsonobject????", e); } }
agilepro/purple
[ 0, 0, 0, 0 ]
18,326
private void validate() throws IllegalStateException { Set<DateComponentOrdering> orderings = Sets.newHashSet(); if(preferred != null) { orderings.add(preferred.getOrdering()); } for(DateTimeParser parser : otherParsers) { if(!orderings.add(parser.getOrdering())) { throw new IllegalStateException("DateComponentOrdering can only be used once in a DateTimeMultiParser." + "[" + parser.getOrdering() + "]"); } } }
private void validate() throws IllegalStateException { Set<DateComponentOrdering> orderings = Sets.newHashSet(); if(preferred != null) { orderings.add(preferred.getOrdering()); } for(DateTimeParser parser : otherParsers) { if(!orderings.add(parser.getOrdering())) { throw new IllegalStateException("DateComponentOrdering can only be used once in a DateTimeMultiParser." + "[" + parser.getOrdering() + "]"); } } }
private void validate() throws illegalstateexception { set<datecomponentordering> orderings = sets.newhashset(); if(preferred != null) { orderings.add(preferred.getordering()); } for(datetimeparser parser : otherparsers) { if(!orderings.add(parser.getordering())) { throw new illegalstateexception("datecomponentordering can only be used once in a datetimemultiparser." + "[" + parser.getordering() + "]"); } } }
adam-collins/parsers
[ 1, 0, 0, 0 ]
18,370
public static String getEnumName(String fieldName ) { //Later TODO //return super.getEnumName(fieldName); return null; }
public static String getEnumName(String fieldName ) { return null; }
public static string getenumname(string fieldname ) { return null; }
aloklal99/apache-ranger
[ 0, 1, 0, 0 ]
18,422
public static StatsValues createStatsValues(StatsField statsField) { final SchemaField sf = statsField.getSchemaField(); if (null == sf) { // function stats return new NumericStatsValues(statsField); } final FieldType fieldType = sf.getType(); // TODO: allow FieldType to provide impl. if (TrieDateField.class.isInstance(fieldType) || DatePointField.class.isInstance(fieldType)) { DateStatsValues statsValues = new DateStatsValues(statsField); if (sf.multiValued()) { return new SortedDateStatsValues(statsValues, statsField); } return statsValues; } else if (TrieField.class.isInstance(fieldType) || PointField.class.isInstance(fieldType)) { NumericStatsValues statsValue = new NumericStatsValues(statsField); if (sf.multiValued()) { return new SortedNumericStatsValues(statsValue, statsField); } return statsValue; } else if (StrField.class.isInstance(fieldType)) { return new StringStatsValues(statsField); } else if (AbstractEnumField.class.isInstance(fieldType)) { return new EnumStatsValues(statsField); } else { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Field type " + fieldType + " is not currently supported"); } }
public static StatsValues createStatsValues(StatsField statsField) { final SchemaField sf = statsField.getSchemaField(); if (null == sf) { return new NumericStatsValues(statsField); } final FieldType fieldType = sf.getType(); if (TrieDateField.class.isInstance(fieldType) || DatePointField.class.isInstance(fieldType)) { DateStatsValues statsValues = new DateStatsValues(statsField); if (sf.multiValued()) { return new SortedDateStatsValues(statsValues, statsField); } return statsValues; } else if (TrieField.class.isInstance(fieldType) || PointField.class.isInstance(fieldType)) { NumericStatsValues statsValue = new NumericStatsValues(statsField); if (sf.multiValued()) { return new SortedNumericStatsValues(statsValue, statsField); } return statsValue; } else if (StrField.class.isInstance(fieldType)) { return new StringStatsValues(statsField); } else if (AbstractEnumField.class.isInstance(fieldType)) { return new EnumStatsValues(statsField); } else { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Field type " + fieldType + " is not currently supported"); } }
public static statsvalues createstatsvalues(statsfield statsfield) { final schemafield sf = statsfield.getschemafield(); if (null == sf) { return new numericstatsvalues(statsfield); } final fieldtype fieldtype = sf.gettype(); if (triedatefield.class.isinstance(fieldtype) || datepointfield.class.isinstance(fieldtype)) { datestatsvalues statsvalues = new datestatsvalues(statsfield); if (sf.multivalued()) { return new sorteddatestatsvalues(statsvalues, statsfield); } return statsvalues; } else if (triefield.class.isinstance(fieldtype) || pointfield.class.isinstance(fieldtype)) { numericstatsvalues statsvalue = new numericstatsvalues(statsfield); if (sf.multivalued()) { return new sortednumericstatsvalues(statsvalue, statsfield); } return statsvalue; } else if (strfield.class.isinstance(fieldtype)) { return new stringstatsvalues(statsfield); } else if (abstractenumfield.class.isinstance(fieldtype)) { return new enumstatsvalues(statsfield); } else { throw new solrexception( solrexception.errorcode.bad_request, "field type " + fieldtype + " is not currently supported"); } }
ackepenek/solr
[ 0, 1, 0, 0 ]
18,424
public void setSelected(@Nullable PackListWidget.PackEntry entry) { this.setSelected(entry, true); }
public void setSelected(@Nullable PackListWidget.PackEntry entry) { this.setSelected(entry, true); }
public void setselected(@nullable packlistwidget.packentry entry) { this.setselected(entry, true); }
VanillaImprovements/VVDownloader
[ 0, 1, 0, 0 ]
2,045
synchronized ImmutableList<JobEvent> getActiveEvents() { ImmutableList.Builder<JobEvent> builder = ImmutableList.builder(); for (String id : activeJobIds) { JobEvent p = eventsByJobId.get(id); assert p != null; builder.add(p); } return builder.build(); }
synchronized ImmutableList<JobEvent> getActiveEvents() { ImmutableList.Builder<JobEvent> builder = ImmutableList.builder(); for (String id : activeJobIds) { JobEvent p = eventsByJobId.get(id); assert p != null; builder.add(p); } return builder.build(); }
synchronized immutablelist<jobevent> getactiveevents() { immutablelist.builder<jobevent> builder = immutablelist.builder(); for (string id : activejobids) { jobevent p = eventsbyjobid.get(id); assert p != null; builder.add(p); } return builder.build(); }
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
[ 1, 0, 0, 0 ]
18,433
private VdsmVm appendStatistics(VdsmVm vm, V1VirtualMachineInstance vmi) { VmStatistics statistics = new VmStatistics(); statistics.setId(vm.getId()); DateTime creationTimestampDate = vmi.getMetadata().getCreationTimestamp(); if (creationTimestampDate != null) { DateTime now = DateTime.now(); Seconds seconds = Seconds.secondsBetween(creationTimestampDate, now); statistics.setElapsedTime((double) seconds.getSeconds()); } PrometheusClient promClient = getPrometheusClient(); if (promClient != null) { // FIXME: Kubevirt currently have only kubevirt_vmi_vcpu_seconds, which is total CPU time, // so we are setting it here only as system time, which is wrong. statistics.setCpuSys( promClient.getVmiCpuUsage(vmi.getMetadata().getName(), vmi.getMetadata().getNamespace()) ); } return vm.setVmStatistics(statistics) .setDiskStatistics(Collections.emptyList()) .setVmJobs(Collections.emptyList()); }
private VdsmVm appendStatistics(VdsmVm vm, V1VirtualMachineInstance vmi) { VmStatistics statistics = new VmStatistics(); statistics.setId(vm.getId()); DateTime creationTimestampDate = vmi.getMetadata().getCreationTimestamp(); if (creationTimestampDate != null) { DateTime now = DateTime.now(); Seconds seconds = Seconds.secondsBetween(creationTimestampDate, now); statistics.setElapsedTime((double) seconds.getSeconds()); } PrometheusClient promClient = getPrometheusClient(); if (promClient != null) { statistics.setCpuSys( promClient.getVmiCpuUsage(vmi.getMetadata().getName(), vmi.getMetadata().getNamespace()) ); } return vm.setVmStatistics(statistics) .setDiskStatistics(Collections.emptyList()) .setVmJobs(Collections.emptyList()); }
private vdsmvm appendstatistics(vdsmvm vm, v1virtualmachineinstance vmi) { vmstatistics statistics = new vmstatistics(); statistics.setid(vm.getid()); datetime creationtimestampdate = vmi.getmetadata().getcreationtimestamp(); if (creationtimestampdate != null) { datetime now = datetime.now(); seconds seconds = seconds.secondsbetween(creationtimestampdate, now); statistics.setelapsedtime((double) seconds.getseconds()); } prometheusclient promclient = getprometheusclient(); if (promclient != null) { statistics.setcpusys( promclient.getvmicpuusage(vmi.getmetadata().getname(), vmi.getmetadata().getnamespace()) ); } return vm.setvmstatistics(statistics) .setdiskstatistics(collections.emptylist()) .setvmjobs(collections.emptylist()); }
StevenCode/ovirt-engine
[ 0, 0, 1, 0 ]
18,456
@Test @Ignore("dbpedia is not reliable") public void testDBPedia() throws Exception { testResource(DBPEDIA, "dbpedia-berlin.sparql" ); }
@Test @Ignore("dbpedia is not reliable") public void testDBPedia() throws Exception { testResource(DBPEDIA, "dbpedia-berlin.sparql" ); }
@test @ignore("dbpedia is not reliable") public void testdbpedia() throws exception { testresource(dbpedia, "dbpedia-berlin.sparql" ); }
YYTVicky/marmotta
[ 1, 0, 0, 0 ]
34,925
@Test public void canCompleteItself() throws IOException { String jid = queue.put("Foo", null, null); queue.pop().complete(); // TODO: this test passes even when this line is removed Assert.assertEquals("complete", client.getJob(jid).getState()); }
@Test public void canCompleteItself() throws IOException { String jid = queue.put("Foo", null, null); queue.pop().complete(); Assert.assertEquals("complete", client.getJob(jid).getState()); }
@test public void cancompleteitself() throws ioexception { string jid = queue.put("foo", null, null); queue.pop().complete(); assert.assertequals("complete", client.getjob(jid).getstate()); }
Zimbra/qless-java
[ 0, 0, 0, 1 ]
18,643
@Override public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { if (affectedControllerId.equals(source.getControllerId())) { Card card = game.getCard(objectId); MageObject sourceObject = source.getSourceObject(game); if (card != null && !card.isLand() && sourceObject != null) { UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter()); if (exileId != null) { ExileZone exileZone = game.getState().getExile().getExileZone(exileId); if (exileZone != null && exileZone.contains(objectId)) { if (game.getTurnNum() == turnNumber) { if (!exileZone.contains(cardId)) { // last checked card this turn is no longer exiled, so you can't cast another with this effect // TODO: Handle if card was cast/removed from exile with effect from another card. // If so, this effect could prevent player from casting although they should be able to use it return false; } } this.turnNumber = game.getTurnNum(); this.cardId = objectId; return true; } } } } return false; }
@Override public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { if (affectedControllerId.equals(source.getControllerId())) { Card card = game.getCard(objectId); MageObject sourceObject = source.getSourceObject(game); if (card != null && !card.isLand() && sourceObject != null) { UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter()); if (exileId != null) { ExileZone exileZone = game.getState().getExile().getExileZone(exileId); if (exileZone != null && exileZone.contains(objectId)) { if (game.getTurnNum() == turnNumber) { if (!exileZone.contains(cardId)) { return false; } } this.turnNumber = game.getTurnNum(); this.cardId = objectId; return true; } } } } return false; }
@override public boolean applies(uuid objectid, ability source, uuid affectedcontrollerid, game game) { if (affectedcontrollerid.equals(source.getcontrollerid())) { card card = game.getcard(objectid); mageobject sourceobject = source.getsourceobject(game); if (card != null && !card.island() && sourceobject != null) { uuid exileid = cardutil.getexilezoneid(game, source.getsourceid(), source.getsourceobjectzonechangecounter()); if (exileid != null) { exilezone exilezone = game.getstate().getexile().getexilezone(exileid); if (exilezone != null && exilezone.contains(objectid)) { if (game.getturnnum() == turnnumber) { if (!exilezone.contains(cardid)) { return false; } } this.turnnumber = game.getturnnum(); this.cardid = objectid; return true; } } } } return false; }
amc8391/mage
[ 0, 0, 1, 0 ]
2,359
public static String getFilePathDiskCache(final String key) { if (sDiskLruCache == null) { return null; } // This violates encapsulation but there is no convenience method to get a filename from // DiskLruCache. Filename was derived from private class method Entry#getCleanFile // in DiskLruCache.java return sDiskLruCache.getDirectory() + File.separator + createValidDiskCacheKey(key) + "." + DISK_CACHE_INDEX; }
public static String getFilePathDiskCache(final String key) { if (sDiskLruCache == null) { return null; } return sDiskLruCache.getDirectory() + File.separator + createValidDiskCacheKey(key) + "." + DISK_CACHE_INDEX; }
public static string getfilepathdiskcache(final string key) { if (sdisklrucache == null) { return null; } return sdisklrucache.getdirectory() + file.separator + createvaliddiskcachekey(key) + "." + disk_cache_index; }
SinnerSchraderMobileMirrors/mopub-android-sdk
[ 1, 0, 0, 0 ]
18,861
private void setUpViews() { glucometerAttribution = findViewById(R.id.glucometerAttribution); glucometerImg = findViewById(R.id.glucometerImg); insertStripText = findViewById(R.id.insertStripText); upArrow = findViewById(R.id.upArrow); droplet = findViewById(R.id.dropletImg); attributionText = findViewById(R.id.attributionText); placeBloodSweatImg = findViewById(R.id.placeBloodSweatImg); placeBloodSweatText = findViewById(R.id.placeBloodSweatText); waitForReadingText = findViewById(R.id.waitForReadingText); progressBar = findViewById(R.id.progressBar); unitsText = findViewById(R.id.unitsText); glucoseLevelText = findViewById(R.id.glucoseLevelText); descriptionTxt = findViewById(R.id.descriptionTxt); detailsBtn = findViewById(R.id.detailsBtn); anotherReadingBtn = findViewById(R.id.anotherReadingBtn); showBtn = findViewById(R.id.button7); dippedBtn = findViewById(R.id.button6); stripBtn = findViewById(R.id.button8); startButton = findViewById(R.id.btnStripInserted); rgMode = findViewById(R.id.rgMode); rbBlood = findViewById(R.id.rbBlood); rbSweat = findViewById(R.id.rbSweat); rb_mg_dL = findViewById(R.id.rb_mg_dL); rb_mmol_L = findViewById(R.id.rb_mmol_L); glucometerSwitch = findViewById(R.id.glucometerSwitch); rgUnits = findViewById(R.id.rgUnits); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!rbSweat.isChecked() && !rbBlood.isChecked()) { Toast.makeText(GlucometerActivity.this, "Please select a mode", Toast.LENGTH_SHORT).show(); } else { instance.sendDataToArduino("start"); instance.setReading(true); glucometerSwitch.setEnabled(false); rbBlood.setEnabled(false); rbSweat.setEnabled(false); rb_mg_dL.setEnabled(false); rb_mmol_L.setEnabled(false); startButton.setEnabled(false); glucometerImg.setVisibility(View.VISIBLE); glucometerAttribution.setVisibility(View.VISIBLE); insertStripText.setVisibility(View.VISIBLE); upArrow.setVisibility(View.VISIBLE); } } }); rgMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rbBlood: instance.sendDataToArduino("Blood"); droplet.setColorFilter(Color.parseColor("#F44336")); placeBloodSweatText.setText("Place blood on the test strip"); break; case R.id.rbSweat: instance.sendDataToArduino("Sweat"); droplet.setColorFilter(Color.parseColor("#1b95e0")); placeBloodSweatText.setText("Place sweat on the test strip"); break; } viewDelay(); } }); glucometerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ instance.sendDataToArduino("G_on"); viewDelay(); }else { instance.sendDataToArduino("G_off"); startButton.setEnabled(false); rbBlood.setEnabled(false); rbSweat.setEnabled(false); rb_mg_dL.setEnabled(false); rb_mmol_L.setEnabled(false); glucometerSwitch.setEnabled(false); viewHandler = new Handler(); Runnable delay = new Runnable() { @Override public void run() { glucometerSwitch.setEnabled(true); } }; viewHandler.postDelayed(delay, 1000); } } }); rgUnits.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb_mg_dL: //TODO Display readings in mg/dL unitsText.setText("mg/dL"); break; case R.id.rb_mmol_L: //TODO Display readings in mmol/L unitsText.setText("mmol/L"); break; } viewDelay(); } }); detailsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Move to new activity Intent intent = new Intent(GlucometerActivity.this, GlucoseReadingDetailsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); } }); anotherReadingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setReading(false); glucometerSwitch.setEnabled(true); rbBlood.setEnabled(true); rbSweat.setEnabled(true); rb_mg_dL.setEnabled(true); rb_mmol_L.setEnabled(true); startButton.setEnabled(true); instance.setStringData(null); instance.setCommand(null); unitsText.setVisibility(View.INVISIBLE); glucoseLevelText.setVisibility(View.INVISIBLE); descriptionTxt.setVisibility(View.INVISIBLE); detailsBtn.setVisibility(View.INVISIBLE); anotherReadingBtn.setVisibility(View.INVISIBLE); } }); showBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("show"); } }); stripBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("strip"); } }); dippedBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("dipped"); } }); }
private void setUpViews() { glucometerAttribution = findViewById(R.id.glucometerAttribution); glucometerImg = findViewById(R.id.glucometerImg); insertStripText = findViewById(R.id.insertStripText); upArrow = findViewById(R.id.upArrow); droplet = findViewById(R.id.dropletImg); attributionText = findViewById(R.id.attributionText); placeBloodSweatImg = findViewById(R.id.placeBloodSweatImg); placeBloodSweatText = findViewById(R.id.placeBloodSweatText); waitForReadingText = findViewById(R.id.waitForReadingText); progressBar = findViewById(R.id.progressBar); unitsText = findViewById(R.id.unitsText); glucoseLevelText = findViewById(R.id.glucoseLevelText); descriptionTxt = findViewById(R.id.descriptionTxt); detailsBtn = findViewById(R.id.detailsBtn); anotherReadingBtn = findViewById(R.id.anotherReadingBtn); showBtn = findViewById(R.id.button7); dippedBtn = findViewById(R.id.button6); stripBtn = findViewById(R.id.button8); startButton = findViewById(R.id.btnStripInserted); rgMode = findViewById(R.id.rgMode); rbBlood = findViewById(R.id.rbBlood); rbSweat = findViewById(R.id.rbSweat); rb_mg_dL = findViewById(R.id.rb_mg_dL); rb_mmol_L = findViewById(R.id.rb_mmol_L); glucometerSwitch = findViewById(R.id.glucometerSwitch); rgUnits = findViewById(R.id.rgUnits); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!rbSweat.isChecked() && !rbBlood.isChecked()) { Toast.makeText(GlucometerActivity.this, "Please select a mode", Toast.LENGTH_SHORT).show(); } else { instance.sendDataToArduino("start"); instance.setReading(true); glucometerSwitch.setEnabled(false); rbBlood.setEnabled(false); rbSweat.setEnabled(false); rb_mg_dL.setEnabled(false); rb_mmol_L.setEnabled(false); startButton.setEnabled(false); glucometerImg.setVisibility(View.VISIBLE); glucometerAttribution.setVisibility(View.VISIBLE); insertStripText.setVisibility(View.VISIBLE); upArrow.setVisibility(View.VISIBLE); } } }); rgMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rbBlood: instance.sendDataToArduino("Blood"); droplet.setColorFilter(Color.parseColor("#F44336")); placeBloodSweatText.setText("Place blood on the test strip"); break; case R.id.rbSweat: instance.sendDataToArduino("Sweat"); droplet.setColorFilter(Color.parseColor("#1b95e0")); placeBloodSweatText.setText("Place sweat on the test strip"); break; } viewDelay(); } }); glucometerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ instance.sendDataToArduino("G_on"); viewDelay(); }else { instance.sendDataToArduino("G_off"); startButton.setEnabled(false); rbBlood.setEnabled(false); rbSweat.setEnabled(false); rb_mg_dL.setEnabled(false); rb_mmol_L.setEnabled(false); glucometerSwitch.setEnabled(false); viewHandler = new Handler(); Runnable delay = new Runnable() { @Override public void run() { glucometerSwitch.setEnabled(true); } }; viewHandler.postDelayed(delay, 1000); } } }); rgUnits.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb_mg_dL: unitsText.setText("mg/dL"); break; case R.id.rb_mmol_L: unitsText.setText("mmol/L"); break; } viewDelay(); } }); detailsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GlucometerActivity.this, GlucoseReadingDetailsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); } }); anotherReadingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setReading(false); glucometerSwitch.setEnabled(true); rbBlood.setEnabled(true); rbSweat.setEnabled(true); rb_mg_dL.setEnabled(true); rb_mmol_L.setEnabled(true); startButton.setEnabled(true); instance.setStringData(null); instance.setCommand(null); unitsText.setVisibility(View.INVISIBLE); glucoseLevelText.setVisibility(View.INVISIBLE); descriptionTxt.setVisibility(View.INVISIBLE); detailsBtn.setVisibility(View.INVISIBLE); anotherReadingBtn.setVisibility(View.INVISIBLE); } }); showBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("show"); } }); stripBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("strip"); } }); dippedBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("dipped"); } }); }
private void setupviews() { glucometerattribution = findviewbyid(r.id.glucometerattribution); glucometerimg = findviewbyid(r.id.glucometerimg); insertstriptext = findviewbyid(r.id.insertstriptext); uparrow = findviewbyid(r.id.uparrow); droplet = findviewbyid(r.id.dropletimg); attributiontext = findviewbyid(r.id.attributiontext); placebloodsweatimg = findviewbyid(r.id.placebloodsweatimg); placebloodsweattext = findviewbyid(r.id.placebloodsweattext); waitforreadingtext = findviewbyid(r.id.waitforreadingtext); progressbar = findviewbyid(r.id.progressbar); unitstext = findviewbyid(r.id.unitstext); glucoseleveltext = findviewbyid(r.id.glucoseleveltext); descriptiontxt = findviewbyid(r.id.descriptiontxt); detailsbtn = findviewbyid(r.id.detailsbtn); anotherreadingbtn = findviewbyid(r.id.anotherreadingbtn); showbtn = findviewbyid(r.id.button7); dippedbtn = findviewbyid(r.id.button6); stripbtn = findviewbyid(r.id.button8); startbutton = findviewbyid(r.id.btnstripinserted); rgmode = findviewbyid(r.id.rgmode); rbblood = findviewbyid(r.id.rbblood); rbsweat = findviewbyid(r.id.rbsweat); rb_mg_dl = findviewbyid(r.id.rb_mg_dl); rb_mmol_l = findviewbyid(r.id.rb_mmol_l); glucometerswitch = findviewbyid(r.id.glucometerswitch); rgunits = findviewbyid(r.id.rgunits); startbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { if (!rbsweat.ischecked() && !rbblood.ischecked()) { toast.maketext(glucometeractivity.this, "please select a mode", toast.length_short).show(); } else { instance.senddatatoarduino("start"); instance.setreading(true); glucometerswitch.setenabled(false); rbblood.setenabled(false); rbsweat.setenabled(false); rb_mg_dl.setenabled(false); rb_mmol_l.setenabled(false); startbutton.setenabled(false); glucometerimg.setvisibility(view.visible); glucometerattribution.setvisibility(view.visible); insertstriptext.setvisibility(view.visible); uparrow.setvisibility(view.visible); } } }); rgmode.setoncheckedchangelistener(new radiogroup.oncheckedchangelistener() { @override public void oncheckedchanged(radiogroup group, int checkedid) { switch (checkedid) { case r.id.rbblood: instance.senddatatoarduino("blood"); droplet.setcolorfilter(color.parsecolor("#f44336")); placebloodsweattext.settext("place blood on the test strip"); break; case r.id.rbsweat: instance.senddatatoarduino("sweat"); droplet.setcolorfilter(color.parsecolor("#1b95e0")); placebloodsweattext.settext("place sweat on the test strip"); break; } viewdelay(); } }); glucometerswitch.setoncheckedchangelistener(new compoundbutton.oncheckedchangelistener() { @override public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) { if (ischecked){ instance.senddatatoarduino("g_on"); viewdelay(); }else { instance.senddatatoarduino("g_off"); startbutton.setenabled(false); rbblood.setenabled(false); rbsweat.setenabled(false); rb_mg_dl.setenabled(false); rb_mmol_l.setenabled(false); glucometerswitch.setenabled(false); viewhandler = new handler(); runnable delay = new runnable() { @override public void run() { glucometerswitch.setenabled(true); } }; viewhandler.postdelayed(delay, 1000); } } }); rgunits.setoncheckedchangelistener(new radiogroup.oncheckedchangelistener() { @override public void oncheckedchanged(radiogroup group, int checkedid) { switch (checkedid) { case r.id.rb_mg_dl: unitstext.settext("mg/dl"); break; case r.id.rb_mmol_l: unitstext.settext("mmol/l"); break; } viewdelay(); } }); detailsbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent intent = new intent(glucometeractivity.this, glucosereadingdetailsactivity.class); intent.addflags(intent.flag_activity_no_animation); startactivity(intent); } }); anotherreadingbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setreading(false); glucometerswitch.setenabled(true); rbblood.setenabled(true); rbsweat.setenabled(true); rb_mg_dl.setenabled(true); rb_mmol_l.setenabled(true); startbutton.setenabled(true); instance.setstringdata(null); instance.setcommand(null); unitstext.setvisibility(view.invisible); glucoseleveltext.setvisibility(view.invisible); descriptiontxt.setvisibility(view.invisible); detailsbtn.setvisibility(view.invisible); anotherreadingbtn.setvisibility(view.invisible); } }); showbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand("show"); } }); stripbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand("strip"); } }); dippedbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand("dipped"); } }); }
W6WM9M/VitalityMeter
[ 0, 1, 0, 0 ]
10,671
public void render(SpriteBatch batch) { viewport.apply(); batch.setProjectionMatrix(viewport.getCamera().combined); batch.begin(); // TODO: Draw a game over message // Feel free to get more creative with this screen. Perhaps you could cover the screen in enemy robots? float timeElapsed = Utils.secondsSince(startTime); int enemiesToShow = (int) (Constants.ENEMY_COUNT * (timeElapsed / Constants.LEVEL_END_DURATION)); for (int i = 0; i < enemiesToShow; i++){ Enemy enemy = enemies.get(i); enemy.update(0); enemy.render(batch); } font.draw(batch, Constants.GAME_OVER_MESSAGE, viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2.5f, 0, Align.center, false); batch.end(); }
public void render(SpriteBatch batch) { viewport.apply(); batch.setProjectionMatrix(viewport.getCamera().combined); batch.begin(); float timeElapsed = Utils.secondsSince(startTime); int enemiesToShow = (int) (Constants.ENEMY_COUNT * (timeElapsed / Constants.LEVEL_END_DURATION)); for (int i = 0; i < enemiesToShow; i++){ Enemy enemy = enemies.get(i); enemy.update(0); enemy.render(batch); } font.draw(batch, Constants.GAME_OVER_MESSAGE, viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2.5f, 0, Align.center, false); batch.end(); }
public void render(spritebatch batch) { viewport.apply(); batch.setprojectionmatrix(viewport.getcamera().combined); batch.begin(); float timeelapsed = utils.secondssince(starttime); int enemiestoshow = (int) (constants.enemy_count * (timeelapsed / constants.level_end_duration)); for (int i = 0; i < enemiestoshow; i++){ enemy enemy = enemies.get(i); enemy.update(0); enemy.render(batch); } font.draw(batch, constants.game_over_message, viewport.getworldwidth() / 2, viewport.getworldheight() / 2.5f, 0, align.center, false); batch.end(); }
Sceptres/ud406
[ 0, 1, 0, 0 ]
2,527
public static <T extends Enum> String getEnumI18n(Locale locale, String base, T enumToGet) { return Language.i18n(locale, base + "." + enumToGet.name().toLowerCase()); }
public static <T extends Enum> String getEnumI18n(Locale locale, String base, T enumToGet) { return Language.i18n(locale, base + "." + enumToGet.name().toLowerCase()); }
public static <t extends enum> string getenumi18n(locale locale, string base, t enumtoget) { return language.i18n(locale, base + "." + enumtoget.name().tolowercase()); }
TortleWortle/CascadeBot
[ 0, 0, 0, 0 ]
10,747
public JsonObject setMaxComments(int comments){ JsonObject result = new JsonObject(); if( dbServices.setMaxCommentsPerVideo(comments)) { result.addProperty("msg", "Max comments to collect for each video is now: " + comments); } else result.addProperty("error","Failed to set max comments per video"); return result; }
public JsonObject setMaxComments(int comments){ JsonObject result = new JsonObject(); if( dbServices.setMaxCommentsPerVideo(comments)) { result.addProperty("msg", "Max comments to collect for each video is now: " + comments); } else result.addProperty("error","Failed to set max comments per video"); return result; }
public jsonobject setmaxcomments(int comments){ jsonobject result = new jsonobject(); if( dbservices.setmaxcommentspervideo(comments)) { result.addproperty("msg", "max comments to collect for each video is now: " + comments); } else result.addproperty("error","failed to set max comments per video"); return result; }
UCY-LINC-LAB/YouTube-Twitter-Analysis
[ 0, 1, 0, 0 ]
2,557
static OzoneClient getOzoneClient(boolean secure) throws IOException { OzoneConfiguration conf = new OzoneConfiguration(); // TODO: If you don't have OM HA configured, change the following as appropriate. conf.set("ozone.om.address", "9.29.173.57:9862"); if (disableChecksum) conf.set("ozone.client.checksum.type", "NONE"); return OzoneClientFactory.getRpcClient(conf); }
static OzoneClient getOzoneClient(boolean secure) throws IOException { OzoneConfiguration conf = new OzoneConfiguration(); conf.set("ozone.om.address", "9.29.173.57:9862"); if (disableChecksum) conf.set("ozone.client.checksum.type", "NONE"); return OzoneClientFactory.getRpcClient(conf); }
static ozoneclient getozoneclient(boolean secure) throws ioexception { ozoneconfiguration conf = new ozoneconfiguration(); conf.set("ozone.om.address", "9.29.173.57:9862"); if (disablechecksum) conf.set("ozone.client.checksum.type", "none"); return ozoneclientfactory.getrpcclient(conf); }
SincereXIA/ozonerpc2
[ 1, 0, 0, 0 ]
10,797
@Unused @Doc("Init 'record' node") @Reviewed(when = "02/12/2020") @Original(version="2.38.0", path="lib/common/shapes.c", name="record_init", key="h2lcuthzwljbcjwdeidw1jiv", definition="static void record_init(node_t * n)") public static void record_init(ST_Agnode_s n) { ENTERING("h2lcuthzwljbcjwdeidw1jiv","record_init"); try { ST_field_t info; final ST_pointf ul = new ST_pointf(), sz = new ST_pointf(); boolean flip; int len; CString textbuf; /* temp buffer for storing labels */ int sides = BOTTOM | RIGHT | TOP | LEFT; /* Always use rankdir to determine how records are laid out */ flip = NOT(GD_realflip(agraphof(n))); Z.z().reclblp = ND_label(n).text; len = strlen(Z.z().reclblp); /* For some forgotten reason, an empty label is parsed into a space, so * we need at least two bytes in textbuf. */ len = MAX(len, 1); textbuf = CString.gmalloc(len + 1); if (N(info = parse_reclbl(n, flip, NOT(0), textbuf))) { UNSUPPORTED("7iezaksu9hyxhmv3r4cp4o529"); // agerr(AGERR, "bad label format %s\n", ND_label(n)->text); UNSUPPORTED("8f1id7rqm71svssnxbjo0uwcu"); // reclblp = "\\N"; UNSUPPORTED("2wv3zfqhq53941rwk4vu9p9th"); // info = parse_reclbl(n, flip, NOT(0), textbuf); } Memory.free(textbuf); size_reclbl(n, info); sz.x = POINTS(ND_width(n));; sz.y = POINTS(ND_height(n)); if (mapbool(late_string(n, Z.z().N_fixed, new CString("false")))) { UNSUPPORTED("8iu51xbtntpdf5sc00g91djym"); // if ((sz.x < info->size.x) || (sz.y < info->size.y)) { UNSUPPORTED("4vs5u30jzsrn6fpjd327xjf7r"); // /* should check that the record really won't fit, e.g., there may be no text. UNSUPPORTED("7k6yytek9nu1ihxix2880667g"); // agerr(AGWARN, "node '%s' size may be too small\n", agnameof(n)); UNSUPPORTED("bnetqzovnscxile7ao44kc0qd"); // */ UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // } } else { sz.x = MAX(info.size.x, sz.x); sz.y = MAX(info.size.y, sz.y); } resize_reclbl(info, sz, mapbool(late_string(n, Z.z().N_nojustify, new CString("false")))); ul.___(pointfof(-sz.x / 2., sz.y / 2.)); /* FIXME - is this still true: suspected to introduce ronding error - see Kluge below */ pos_reclbl(info, ul, sides); ND_width(n, PS2INCH(info.size.x)); ND_height(n, PS2INCH(info.size.y + 1)); /* Kluge!! +1 to fix rounding diff between layout and rendering otherwise we can get -1 coords in output */ ND_shape_info(n, info); } finally { LEAVING("h2lcuthzwljbcjwdeidw1jiv","poly_init"); } }
@Unused @Doc("Init 'record' node") @Reviewed(when = "02/12/2020") @Original(version="2.38.0", path="lib/common/shapes.c", name="record_init", key="h2lcuthzwljbcjwdeidw1jiv", definition="static void record_init(node_t * n)") public static void record_init(ST_Agnode_s n) { ENTERING("h2lcuthzwljbcjwdeidw1jiv","record_init"); try { ST_field_t info; final ST_pointf ul = new ST_pointf(), sz = new ST_pointf(); boolean flip; int len; CString textbuf; int sides = BOTTOM | RIGHT | TOP | LEFT; flip = NOT(GD_realflip(agraphof(n))); Z.z().reclblp = ND_label(n).text; len = strlen(Z.z().reclblp); len = MAX(len, 1); textbuf = CString.gmalloc(len + 1); if (N(info = parse_reclbl(n, flip, NOT(0), textbuf))) { UNSUPPORTED("7iezaksu9hyxhmv3r4cp4o529"); UNSUPPORTED("8f1id7rqm71svssnxbjo0uwcu"); UNSUPPORTED("2wv3zfqhq53941rwk4vu9p9th"); } Memory.free(textbuf); size_reclbl(n, info); sz.x = POINTS(ND_width(n));; sz.y = POINTS(ND_height(n)); if (mapbool(late_string(n, Z.z().N_fixed, new CString("false")))) { UNSUPPORTED("8iu51xbtntpdf5sc00g91djym"); UNSUPPORTED("4vs5u30jzsrn6fpjd327xjf7r"); UNSUPPORTED("7k6yytek9nu1ihxix2880667g"); UNSUPPORTED("bnetqzovnscxile7ao44kc0qd"); UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); } else { sz.x = MAX(info.size.x, sz.x); sz.y = MAX(info.size.y, sz.y); } resize_reclbl(info, sz, mapbool(late_string(n, Z.z().N_nojustify, new CString("false")))); ul.___(pointfof(-sz.x / 2., sz.y / 2.)); pos_reclbl(info, ul, sides); ND_width(n, PS2INCH(info.size.x)); ND_height(n, PS2INCH(info.size.y + 1)); ND_shape_info(n, info); } finally { LEAVING("h2lcuthzwljbcjwdeidw1jiv","poly_init"); } }
@unused @doc("init 'record' node") @reviewed(when = "02/12/2020") @original(version="2.38.0", path="lib/common/shapes.c", name="record_init", key="h2lcuthzwljbcjwdeidw1jiv", definition="static void record_init(node_t * n)") public static void record_init(st_agnode_s n) { entering("h2lcuthzwljbcjwdeidw1jiv","record_init"); try { st_field_t info; final st_pointf ul = new st_pointf(), sz = new st_pointf(); boolean flip; int len; cstring textbuf; int sides = bottom | right | top | left; flip = not(gd_realflip(agraphof(n))); z.z().reclblp = nd_label(n).text; len = strlen(z.z().reclblp); len = max(len, 1); textbuf = cstring.gmalloc(len + 1); if (n(info = parse_reclbl(n, flip, not(0), textbuf))) { unsupported("7iezaksu9hyxhmv3r4cp4o529"); unsupported("8f1id7rqm71svssnxbjo0uwcu"); unsupported("2wv3zfqhq53941rwk4vu9p9th"); } memory.free(textbuf); size_reclbl(n, info); sz.x = points(nd_width(n));; sz.y = points(nd_height(n)); if (mapbool(late_string(n, z.z().n_fixed, new cstring("false")))) { unsupported("8iu51xbtntpdf5sc00g91djym"); unsupported("4vs5u30jzsrn6fpjd327xjf7r"); unsupported("7k6yytek9nu1ihxix2880667g"); unsupported("bnetqzovnscxile7ao44kc0qd"); unsupported("flupwh3kosf3fkhkxllllt1"); } else { sz.x = max(info.size.x, sz.x); sz.y = max(info.size.y, sz.y); } resize_reclbl(info, sz, mapbool(late_string(n, z.z().n_nojustify, new cstring("false")))); ul.___(pointfof(-sz.x / 2., sz.y / 2.)); pos_reclbl(info, ul, sides); nd_width(n, ps2inch(info.size.x)); nd_height(n, ps2inch(info.size.y + 1)); nd_shape_info(n, info); } finally { leaving("h2lcuthzwljbcjwdeidw1jiv","poly_init"); } }
SandraBSofiaH/Final-UMldoclet
[ 1, 1, 1, 0 ]
19,017
private Table buildHeader() { Skin skin = getSkin(); SquareButton ffBack = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-ff")); ffBack.flipHorizontal(); playBack = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play"), true); playBack.flipHorizontal(); play = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play"), true); SquareButton ffForward = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-ff")); repeatBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-repeat"), true); newBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-new")); newBtn.getIconCell().padTop(2).padLeft(1); SquareButton deleteBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-delete")); upBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play")); upBtn.flipVertical(); downBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play")); downBtn.flipVertical(); downBtn.flipHorizontal(); Table header = new Table(); header.setBackground(skin.getDrawable("timeline-top-bar-bg")); Table topPart = new Table(); Table bottomPart = new Table(); topPart.add(ffBack).padLeft(6).left(); //topPart.add(playBack).padLeft(6).left(); // TODO: add this back when we can support topPart.add(play).padLeft(6).left(); topPart.add(ffForward).padLeft(6).left(); topPart.add(repeatBtn).padLeft(6).left(); topPart.add().growX().minWidth(20); topPart.add(upBtn).padRight(6).right(); topPart.add(downBtn).padRight(10).right(); topPart.add(newBtn).right().padRight(6); topPart.add(deleteBtn).right().padRight(6); topActionCell = topPart.add().right(); typeLabel = new Label("Items", skin); typeLabel.setColor(ColorLibrary.FONT_GRAY); bottomPart.add(typeLabel).padBottom(2).padLeft(5).left().expandX(); header.add(topPart).height(33).padBottom(1).growX().row(); header.add(bottomPart).height(16).growX().row(); /** * Build header actions */ ffBack.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.skipToStart); } }); ffForward.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.skipToEnd); } }); playBack.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.rewind); } }); play.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.play); } }); repeatBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.toggleLoop); } }); deleteBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.deleteSelection); } }); newBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.newItem); } }); upBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.up); } }); downBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.down); } }); return header; }
private Table buildHeader() { Skin skin = getSkin(); SquareButton ffBack = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-ff")); ffBack.flipHorizontal(); playBack = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play"), true); playBack.flipHorizontal(); play = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play"), true); SquareButton ffForward = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-ff")); repeatBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-repeat"), true); newBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-new")); newBtn.getIconCell().padTop(2).padLeft(1); SquareButton deleteBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-delete")); upBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play")); upBtn.flipVertical(); downBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play")); downBtn.flipVertical(); downBtn.flipHorizontal(); Table header = new Table(); header.setBackground(skin.getDrawable("timeline-top-bar-bg")); Table topPart = new Table(); Table bottomPart = new Table(); topPart.add(ffBack).padLeft(6).left(); topPart.add(play).padLeft(6).left(); topPart.add(ffForward).padLeft(6).left(); topPart.add(repeatBtn).padLeft(6).left(); topPart.add().growX().minWidth(20); topPart.add(upBtn).padRight(6).right(); topPart.add(downBtn).padRight(10).right(); topPart.add(newBtn).right().padRight(6); topPart.add(deleteBtn).right().padRight(6); topActionCell = topPart.add().right(); typeLabel = new Label("Items", skin); typeLabel.setColor(ColorLibrary.FONT_GRAY); bottomPart.add(typeLabel).padBottom(2).padLeft(5).left().expandX(); header.add(topPart).height(33).padBottom(1).growX().row(); header.add(bottomPart).height(16).growX().row(); ffBack.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.skipToStart); } }); ffForward.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.skipToEnd); } }); playBack.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.rewind); } }); play.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.play); } }); repeatBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.toggleLoop); } }); deleteBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.deleteSelection); } }); newBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.newItem); } }); upBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.up); } }); downBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.down); } }); return header; }
private table buildheader() { skin skin = getskin(); squarebutton ffback = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-ff")); ffback.fliphorizontal(); playback = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-play"), true); playback.fliphorizontal(); play = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-play"), true); squarebutton ffforward = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-ff")); repeatbtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-repeat"), true); newbtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-new")); newbtn.geticoncell().padtop(2).padleft(1); squarebutton deletebtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-delete")); upbtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-play")); upbtn.flipvertical(); downbtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-play")); downbtn.flipvertical(); downbtn.fliphorizontal(); table header = new table(); header.setbackground(skin.getdrawable("timeline-top-bar-bg")); table toppart = new table(); table bottompart = new table(); toppart.add(ffback).padleft(6).left(); toppart.add(play).padleft(6).left(); toppart.add(ffforward).padleft(6).left(); toppart.add(repeatbtn).padleft(6).left(); toppart.add().growx().minwidth(20); toppart.add(upbtn).padright(6).right(); toppart.add(downbtn).padright(10).right(); toppart.add(newbtn).right().padright(6); toppart.add(deletebtn).right().padright(6); topactioncell = toppart.add().right(); typelabel = new label("items", skin); typelabel.setcolor(colorlibrary.font_gray); bottompart.add(typelabel).padbottom(2).padleft(5).left().expandx(); header.add(toppart).height(33).padbottom(1).growx().row(); header.add(bottompart).height(16).growx().row(); ffback.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.skiptostart); } }); ffforward.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.skiptoend); } }); playback.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.rewind); } }); play.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.play); } }); repeatbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.toggleloop); } }); deletebtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.deleteselection); } }); newbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.newitem); } }); upbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.up); } }); downbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.down); } }); return header; }
TheSenPie/talos
[ 0, 1, 0, 0 ]
10,974
public Map<String, Double> classifyImageVGG16(IplImage iplImage) throws IOException { NativeImageLoader loader = new NativeImageLoader(224, 224, 3); BufferedImage buffImg = OpenCV.toBufferedImage(iplImage); INDArray image = loader.asMatrix(buffImg); // TODO: we should consider the model as not only the model, but also the // input transforms // for that model. DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = vgg16.output(false, image); log.info("Complete with output from vgg16.."); // TODO: return a more native datastructure! // String predictions = TrainedModels.VGG16.decodePredictions(output[0]); // log.info("Image Predictions: {}", predictions); return decodeVGG16Predictions(output[0]); }
public Map<String, Double> classifyImageVGG16(IplImage iplImage) throws IOException { NativeImageLoader loader = new NativeImageLoader(224, 224, 3); BufferedImage buffImg = OpenCV.toBufferedImage(iplImage); INDArray image = loader.asMatrix(buffImg); DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = vgg16.output(false, image); log.info("Complete with output from vgg16.."); return decodeVGG16Predictions(output[0]); }
public map<string, double> classifyimagevgg16(iplimage iplimage) throws ioexception { nativeimageloader loader = new nativeimageloader(224, 224, 3); bufferedimage buffimg = opencv.tobufferedimage(iplimage); indarray image = loader.asmatrix(buffimg); datanormalization scaler = new vgg16imagepreprocessor(); scaler.transform(image); indarray[] output = vgg16.output(false, image); log.info("complete with output from vgg16.."); return decodevgg16predictions(output[0]); }
ShaunHolt/myrobotlab
[ 1, 0, 0, 0 ]
10,975
public Map<String, Double> classifyImageFileVGG16(String filename) throws IOException { File file = new File(filename); NativeImageLoader loader = new NativeImageLoader(224, 224, 3); INDArray image = loader.asMatrix(file); // TODO: we should consider the model as not only the model, but also the // input transforms // for that model. DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = vgg16.output(false, image); // TODO: return a more native datastructure! // String predictions = TrainedModels.VGG16.decodePredictions(output[0]); // log.info("Image Predictions: {}", predictions); return decodeVGG16Predictions(output[0]); }
public Map<String, Double> classifyImageFileVGG16(String filename) throws IOException { File file = new File(filename); NativeImageLoader loader = new NativeImageLoader(224, 224, 3); INDArray image = loader.asMatrix(file); DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = vgg16.output(false, image); return decodeVGG16Predictions(output[0]); }
public map<string, double> classifyimagefilevgg16(string filename) throws ioexception { file file = new file(filename); nativeimageloader loader = new nativeimageloader(224, 224, 3); indarray image = loader.asmatrix(file); datanormalization scaler = new vgg16imagepreprocessor(); scaler.transform(image); indarray[] output = vgg16.output(false, image); return decodevgg16predictions(output[0]); }
ShaunHolt/myrobotlab
[ 1, 0, 0, 0 ]
10,994
private long getReservedCacheSize(String uuid) { // TODO: Revisit the cache size after running more storage tests. // TODO: Figure out how to ensure ExtServices has the permissions to call // StorageStatsManager, because this is ignoring the cache... StorageManager storageManager = getSystemService(StorageManager.class); long freeBytes = 0; if (uuid == StorageManager.UUID_PRIVATE_INTERNAL) { // regular equals because of null freeBytes = Environment.getDataDirectory().getUsableSpace(); } else { final VolumeInfo vol = storageManager.findVolumeByUuid(uuid); freeBytes = vol.getPath().getUsableSpace(); } return Math.round(freeBytes * CACHE_RESERVE_RATIO); }
private long getReservedCacheSize(String uuid) { StorageManager storageManager = getSystemService(StorageManager.class); long freeBytes = 0; if (uuid == StorageManager.UUID_PRIVATE_INTERNAL) { freeBytes = Environment.getDataDirectory().getUsableSpace(); } else { final VolumeInfo vol = storageManager.findVolumeByUuid(uuid); freeBytes = vol.getPath().getUsableSpace(); } return Math.round(freeBytes * CACHE_RESERVE_RATIO); }
private long getreservedcachesize(string uuid) { storagemanager storagemanager = getsystemservice(storagemanager.class); long freebytes = 0; if (uuid == storagemanager.uuid_private_internal) { freebytes = environment.getdatadirectory().getusablespace(); } else { final volumeinfo vol = storagemanager.findvolumebyuuid(uuid); freebytes = vol.getpath().getusablespace(); } return math.round(freebytes * cache_reserve_ratio); }
Y-D-Lu/rr_frameworks_base
[ 1, 0, 0, 0 ]
11,115
public static Intent createEmailAttendeesIntent(Resources resources, String eventTitle, String body, List<String> toEmails, List<String> ccEmails, String ownerAccount) { List<String> toList = toEmails; List<String> ccList = ccEmails; if (toEmails.size() <= 0) { if (ccEmails.size() <= 0) { // TODO: Return a SEND intent if no one to email to, to at least populate // a draft email with the subject (and no recipients). throw new IllegalArgumentException("Both toEmails and ccEmails are empty."); } // Email app does not work with no "to" recipient. Move all 'cc' to 'to' // in this case. toList = ccEmails; ccList = null; } // Use the event title as the email subject (prepended with 'Re: '). String subject = null; if (eventTitle != null) { subject = resources.getString(R.string.email_subject_prefix) + eventTitle; } // Use the SENDTO intent with a 'mailto' URI, because using SEND will cause // the picker to show apps like text messaging, which does not make sense // for email addresses. We put all data in the URI instead of using the extra // Intent fields (ie. EXTRA_CC, etc) because some email apps might not handle // those (though gmail does). Uri.Builder uriBuilder = new Uri.Builder(); uriBuilder.scheme("mailto"); // We will append the first email to the 'mailto' field later (because the // current state of the Email app requires it). Add the remaining 'to' values // here. When the email codebase is updated, we can simplify this. if (toList.size() > 1) { for (int i = 1; i < toList.size(); i++) { // The Email app requires repeated parameter settings instead of // a single comma-separated list. uriBuilder.appendQueryParameter("to", toList.get(i)); } } // Add the subject parameter. if (subject != null) { uriBuilder.appendQueryParameter("subject", subject); } // Add the subject parameter. if (body != null) { uriBuilder.appendQueryParameter("body", body); } // Add the cc parameters. if (ccList != null && ccList.size() > 0) { for (String email : ccList) { uriBuilder.appendQueryParameter("cc", email); } } // Insert the first email after 'mailto:' in the URI manually since Uri.Builder // doesn't seem to have a way to do this. String uri = uriBuilder.toString(); if (uri.startsWith("mailto:")) { StringBuilder builder = new StringBuilder(uri); builder.insert(7, Uri.encode(toList.get(0))); uri = builder.toString(); } // Start the email intent. Email from the account of the calendar owner in case there // are multiple email accounts. Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri)); emailIntent.putExtra("fromAccountString", ownerAccount); // Workaround a Email bug that overwrites the body with this intent extra. If not // set, it clears the body. if (body != null) { emailIntent.putExtra(Intent.EXTRA_TEXT, body); } return Intent.createChooser(emailIntent, resources.getString(R.string.email_picker_label)); }
public static Intent createEmailAttendeesIntent(Resources resources, String eventTitle, String body, List<String> toEmails, List<String> ccEmails, String ownerAccount) { List<String> toList = toEmails; List<String> ccList = ccEmails; if (toEmails.size() <= 0) { if (ccEmails.size() <= 0) { throw new IllegalArgumentException("Both toEmails and ccEmails are empty."); } toList = ccEmails; ccList = null; } String subject = null; if (eventTitle != null) { subject = resources.getString(R.string.email_subject_prefix) + eventTitle; } Uri.Builder uriBuilder = new Uri.Builder(); uriBuilder.scheme("mailto"); if (toList.size() > 1) { for (int i = 1; i < toList.size(); i++) { uriBuilder.appendQueryParameter("to", toList.get(i)); } } if (subject != null) { uriBuilder.appendQueryParameter("subject", subject); } if (body != null) { uriBuilder.appendQueryParameter("body", body); } if (ccList != null && ccList.size() > 0) { for (String email : ccList) { uriBuilder.appendQueryParameter("cc", email); } } String uri = uriBuilder.toString(); if (uri.startsWith("mailto:")) { StringBuilder builder = new StringBuilder(uri); builder.insert(7, Uri.encode(toList.get(0))); uri = builder.toString(); } Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri)); emailIntent.putExtra("fromAccountString", ownerAccount); if (body != null) { emailIntent.putExtra(Intent.EXTRA_TEXT, body); } return Intent.createChooser(emailIntent, resources.getString(R.string.email_picker_label)); }
public static intent createemailattendeesintent(resources resources, string eventtitle, string body, list<string> toemails, list<string> ccemails, string owneraccount) { list<string> tolist = toemails; list<string> cclist = ccemails; if (toemails.size() <= 0) { if (ccemails.size() <= 0) { throw new illegalargumentexception("both toemails and ccemails are empty."); } tolist = ccemails; cclist = null; } string subject = null; if (eventtitle != null) { subject = resources.getstring(r.string.email_subject_prefix) + eventtitle; } uri.builder uribuilder = new uri.builder(); uribuilder.scheme("mailto"); if (tolist.size() > 1) { for (int i = 1; i < tolist.size(); i++) { uribuilder.appendqueryparameter("to", tolist.get(i)); } } if (subject != null) { uribuilder.appendqueryparameter("subject", subject); } if (body != null) { uribuilder.appendqueryparameter("body", body); } if (cclist != null && cclist.size() > 0) { for (string email : cclist) { uribuilder.appendqueryparameter("cc", email); } } string uri = uribuilder.tostring(); if (uri.startswith("mailto:")) { stringbuilder builder = new stringbuilder(uri); builder.insert(7, uri.encode(tolist.get(0))); uri = builder.tostring(); } intent emailintent = new intent(intent.action_sendto, uri.parse(uri)); emailintent.putextra("fromaccountstring", owneraccount); if (body != null) { emailintent.putextra(intent.extra_text, body); } return intent.createchooser(emailintent, resources.getstring(r.string.email_picker_label)); }
Shusshu/Android-RecurrencePicker
[ 0, 1, 1, 0 ]
11,181
@NotNull public abstract Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z);
@NotNull public abstract Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z);
@notnull public abstract biome getbiome(@notnull worldinfo worldinfo, int x, int y, int z);
abcd1234-byte/spigot2
[ 0, 1, 0, 0 ]
3,159
private static void addField(SolrInputDocument doc, String fieldName, Object value, Class type, String dynamicFieldSuffix) { if (type.isArray()) return; // TODO: Array types not supported yet ... if (dynamicFieldSuffix == null) { dynamicFieldSuffix = getDefaultDynamicFieldMapping(type); // treat strings with multiple terms as text only if using the default! if ("_s".equals(dynamicFieldSuffix)) { String str = (String)value; if (str.indexOf(" ") != -1) dynamicFieldSuffix = "_t"; } } if (dynamicFieldSuffix != null) // don't auto-map if we don't have a type doc.addField(fieldName + dynamicFieldSuffix, value); }
private static void addField(SolrInputDocument doc, String fieldName, Object value, Class type, String dynamicFieldSuffix) { if (type.isArray()) return; if (dynamicFieldSuffix == null) { dynamicFieldSuffix = getDefaultDynamicFieldMapping(type); if ("_s".equals(dynamicFieldSuffix)) { String str = (String)value; if (str.indexOf(" ") != -1) dynamicFieldSuffix = "_t"; } } if (dynamicFieldSuffix != null) doc.addField(fieldName + dynamicFieldSuffix, value); }
private static void addfield(solrinputdocument doc, string fieldname, object value, class type, string dynamicfieldsuffix) { if (type.isarray()) return; if (dynamicfieldsuffix == null) { dynamicfieldsuffix = getdefaultdynamicfieldmapping(type); if ("_s".equals(dynamicfieldsuffix)) { string str = (string)value; if (str.indexof(" ") != -1) dynamicfieldsuffix = "_t"; } } if (dynamicfieldsuffix != null) doc.addfield(fieldname + dynamicfieldsuffix, value); }
Stratio/spark-solr
[ 1, 0, 0, 0 ]
11,407
protected Path getRealPath2(TVFSAbstractPath path) { List<String> list = new ArrayList<>(); for (String s : path.path) { list.add(s); } Path p; if (list.isEmpty()) { //p = virtualFS.getTvFileSystem().getPath(virtualFS.getName().getName()); p = fileSystem.getRootPath(); } else { String first = ""; String others[] = null; // if (list.size() >= 1) { // first = list.get(0); // } // if (list.size() > 1) { // others = new String[list.size() - 1]; // // for (int i = 1; i < list.size(); i++) { // others[i - 1] = list.get(i); // } // } //if (others == null) { p = fileSystem.getRootPath().resolve(list.stream().collect(Collectors.joining(fileSystem.getSeparator()))); //p = virtualFS.getTvFileSystem().getPath(virtualFS.getName().getName(),first); // } else { // p = virtualFS.getTvFileSystem().getPath(first, others); // } } return p; }
protected Path getRealPath2(TVFSAbstractPath path) { List<String> list = new ArrayList<>(); for (String s : path.path) { list.add(s); } Path p; if (list.isEmpty()) { p = fileSystem.getRootPath(); } else { String first = ""; String others[] = null; p = fileSystem.getRootPath().resolve(list.stream().collect(Collectors.joining(fileSystem.getSeparator()))); } return p; }
protected path getrealpath2(tvfsabstractpath path) { list<string> list = new arraylist<>(); for (string s : path.path) { list.add(s); } path p; if (list.isempty()) { p = filesystem.getrootpath(); } else { string first = ""; string others[] = null; p = filesystem.getrootpath().resolve(list.stream().collect(collectors.joining(filesystem.getseparator()))); } return p; }
abarhub/tinyvfs
[ 1, 0, 0, 0 ]
11,482
@Override public void populateGui() { // Filler this.getFiller(); // Items for (Map.Entry<Material, Integer> entry : collector.getContents().entrySet()) { // Args Material material = entry.getKey(); int startAmount = entry.getValue(); double startValue = plugin.getCollectorManager().value(collector, material); List<String> lore = Color.color(plugin.getConfig().getStringList("guis.contents.item.lore").stream().map(text -> text.replace("%amount%", String.format("%,d", startAmount)).replace("%value%", String.format("%,.1f", startValue))).collect(Collectors.toList())); List<Component> components = lore.stream().map(Component::text).collect(Collectors.toList()); // Add this.addItem(ItemBuilder.from(material).name(Component.text(this.getNicedEnumString(material.name()))).lore(components).asGuiItem(event -> { // Cancel event.setCancelled(true); // Args Player player = (Player) event.getWhoClicked(); int amount = collector.getMaterialAmount(material); double total = plugin.getCollectorManager().sell(collector, material); // Check if (total == 0.0d) { // TODO: Make it so collectors don't pick up items which can't be sold return; } // Deposit & Inform plugin.getMoneyManager().pay(player.getUniqueId(), total); String message = plugin.getConfig().getString("messages.material-sold"); if (message != null && !message.isEmpty()) player.sendMessage(Color.color(message.replace("%amount%", String.format("%,d", amount)).replace("%material%", this.getNicedEnumString(material.name())).replace("%total%", String.format("%.1f", total)))); // Update this.update(); })); } // Navigation this.setItem(3, 3, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color("Previous"))).asGuiItem(event -> this.previous())); this.setItem(3, 7, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color("Next"))).asGuiItem(event -> this.next())); }
@Override public void populateGui() { this.getFiller(); for (Map.Entry<Material, Integer> entry : collector.getContents().entrySet()) { Material material = entry.getKey(); int startAmount = entry.getValue(); double startValue = plugin.getCollectorManager().value(collector, material); List<String> lore = Color.color(plugin.getConfig().getStringList("guis.contents.item.lore").stream().map(text -> text.replace("%amount%", String.format("%,d", startAmount)).replace("%value%", String.format("%,.1f", startValue))).collect(Collectors.toList())); List<Component> components = lore.stream().map(Component::text).collect(Collectors.toList()); this.addItem(ItemBuilder.from(material).name(Component.text(this.getNicedEnumString(material.name()))).lore(components).asGuiItem(event -> { event.setCancelled(true); Player player = (Player) event.getWhoClicked(); int amount = collector.getMaterialAmount(material); double total = plugin.getCollectorManager().sell(collector, material); if (total == 0.0d) { return; } plugin.getMoneyManager().pay(player.getUniqueId(), total); String message = plugin.getConfig().getString("messages.material-sold"); if (message != null && !message.isEmpty()) player.sendMessage(Color.color(message.replace("%amount%", String.format("%,d", amount)).replace("%material%", this.getNicedEnumString(material.name())).replace("%total%", String.format("%.1f", total)))); this.update(); })); } this.setItem(3, 3, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color("Previous"))).asGuiItem(event -> this.previous())); this.setItem(3, 7, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color("Next"))).asGuiItem(event -> this.next())); }
@override public void populategui() { this.getfiller(); for (map.entry<material, integer> entry : collector.getcontents().entryset()) { material material = entry.getkey(); int startamount = entry.getvalue(); double startvalue = plugin.getcollectormanager().value(collector, material); list<string> lore = color.color(plugin.getconfig().getstringlist("guis.contents.item.lore").stream().map(text -> text.replace("%amount%", string.format("%,d", startamount)).replace("%value%", string.format("%,.1f", startvalue))).collect(collectors.tolist())); list<component> components = lore.stream().map(component::text).collect(collectors.tolist()); this.additem(itembuilder.from(material).name(component.text(this.getnicedenumstring(material.name()))).lore(components).asguiitem(event -> { event.setcancelled(true); player player = (player) event.getwhoclicked(); int amount = collector.getmaterialamount(material); double total = plugin.getcollectormanager().sell(collector, material); if (total == 0.0d) { return; } plugin.getmoneymanager().pay(player.getuniqueid(), total); string message = plugin.getconfig().getstring("messages.material-sold"); if (message != null && !message.isempty()) player.sendmessage(color.color(message.replace("%amount%", string.format("%,d", amount)).replace("%material%", this.getnicedenumstring(material.name())).replace("%total%", string.format("%.1f", total)))); this.update(); })); } this.setitem(3, 3, itembuilder.from(material.arrow).name(component.text(color.color("previous"))).asguiitem(event -> this.previous())); this.setitem(3, 7, itembuilder.from(material.arrow).name(component.text(color.color("next"))).asguiitem(event -> this.next())); }
Workinq/AsyncCollectors
[ 0, 1, 0, 0 ]
3,400
protected List<String> updateProvisioning(Map<String, File> artifacts, Provisioner provisionService) throws Exception { ResourceInstaller resourceInstaller = provisionService.getResourceInstaller(); Map<ResourceIdentity, Resource> installedResources = getInstalledResources(provisionService); Map<Requirement, Resource> requirements = new HashMap<Requirement, Resource>(); Set<Map.Entry<String, File>> entries = artifacts.entrySet(); List<Resource> resourcesToInstall = new ArrayList<Resource>(); List<String> resourceUrisInstalled = new ArrayList<String>(); updateStatus("installing", null, null); for (Map.Entry<String, File> entry : entries) { String name = entry.getKey(); File file = entry.getValue(); String coords = name; int idx = coords.lastIndexOf(':'); if (idx > 0) { coords = name.substring(idx + 1); } // lets switch to gravia's mvn coordinates coords = coords.replace('/', ':'); MavenCoordinates mvnCoords = parse(coords); URL url = file.toURI().toURL(); if (url == null) { LOGGER.warn("Could not find URL for file " + file); continue; } // TODO lets just detect wars for now for servlet engines - how do we decide on WildFly? boolean isShared = !isWar(name, file); Resource resource = findMavenResource(mvnCoords, url, isShared); if (resource == null) { LOGGER.warn("Could not find resource for " + mvnCoords + " and " + url); } else { ResourceIdentity identity = resource.getIdentity(); Resource oldResource = installedResources.remove(identity); if (oldResource == null && !resourcehandleMap.containsKey(identity)) { if (isShared) { // TODO lest not deploy shared stuff for now since bundles throw an exception when trying to stop them // which breaks the tests ;) LOGGER.debug("TODO not installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity); } else { LOGGER.info("Installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity); resourcesToInstall.add(resource); resourceUrisInstalled.add(name); } } } } for (Resource installedResource : installedResources.values()) { ResourceIdentity identity = installedResource.getIdentity(); ResourceHandle resourceHandle = resourcehandleMap.get(identity); if (resourceHandle == null) { // TODO should not really happen when we can ask about the installed Resources LOGGER.warn("TODO: Cannot uninstall " + installedResource + " as we have no handle!"); } else { LOGGER.info("Uninstalling " + installedResource); resourceHandle.uninstall(); resourcehandleMap.remove(identity); LOGGER.info("Uninstalled " + installedResource); } } if (resourcesToInstall.size() > 0) { LOGGER.info("Installing " + resourcesToInstall.size() + " resource(s)"); Set<ResourceHandle> resourceHandles = new LinkedHashSet<>(); ResourceInstaller.Context context = new DefaultInstallerContext(resourcesToInstall, requirements); for (Resource resource : resourcesToInstall) { resourceHandles.add(resourceInstaller.installResource(context, resource)); } LOGGER.info("Got " + resourceHandles.size() + " resource handle(s)"); for (ResourceHandle resourceHandle : resourceHandles) { resourcehandleMap.put(resourceHandle.getResource().getIdentity(), resourceHandle); } } return resourceUrisInstalled; }
protected List<String> updateProvisioning(Map<String, File> artifacts, Provisioner provisionService) throws Exception { ResourceInstaller resourceInstaller = provisionService.getResourceInstaller(); Map<ResourceIdentity, Resource> installedResources = getInstalledResources(provisionService); Map<Requirement, Resource> requirements = new HashMap<Requirement, Resource>(); Set<Map.Entry<String, File>> entries = artifacts.entrySet(); List<Resource> resourcesToInstall = new ArrayList<Resource>(); List<String> resourceUrisInstalled = new ArrayList<String>(); updateStatus("installing", null, null); for (Map.Entry<String, File> entry : entries) { String name = entry.getKey(); File file = entry.getValue(); String coords = name; int idx = coords.lastIndexOf(':'); if (idx > 0) { coords = name.substring(idx + 1); } coords = coords.replace('/', ':'); MavenCoordinates mvnCoords = parse(coords); URL url = file.toURI().toURL(); if (url == null) { LOGGER.warn("Could not find URL for file " + file); continue; } boolean isShared = !isWar(name, file); Resource resource = findMavenResource(mvnCoords, url, isShared); if (resource == null) { LOGGER.warn("Could not find resource for " + mvnCoords + " and " + url); } else { ResourceIdentity identity = resource.getIdentity(); Resource oldResource = installedResources.remove(identity); if (oldResource == null && !resourcehandleMap.containsKey(identity)) { if (isShared) { LOGGER.debug("TODO not installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity); } else { LOGGER.info("Installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity); resourcesToInstall.add(resource); resourceUrisInstalled.add(name); } } } } for (Resource installedResource : installedResources.values()) { ResourceIdentity identity = installedResource.getIdentity(); ResourceHandle resourceHandle = resourcehandleMap.get(identity); if (resourceHandle == null) { LOGGER.warn("TODO: Cannot uninstall " + installedResource + " as we have no handle!"); } else { LOGGER.info("Uninstalling " + installedResource); resourceHandle.uninstall(); resourcehandleMap.remove(identity); LOGGER.info("Uninstalled " + installedResource); } } if (resourcesToInstall.size() > 0) { LOGGER.info("Installing " + resourcesToInstall.size() + " resource(s)"); Set<ResourceHandle> resourceHandles = new LinkedHashSet<>(); ResourceInstaller.Context context = new DefaultInstallerContext(resourcesToInstall, requirements); for (Resource resource : resourcesToInstall) { resourceHandles.add(resourceInstaller.installResource(context, resource)); } LOGGER.info("Got " + resourceHandles.size() + " resource handle(s)"); for (ResourceHandle resourceHandle : resourceHandles) { resourcehandleMap.put(resourceHandle.getResource().getIdentity(), resourceHandle); } } return resourceUrisInstalled; }
protected list<string> updateprovisioning(map<string, file> artifacts, provisioner provisionservice) throws exception { resourceinstaller resourceinstaller = provisionservice.getresourceinstaller(); map<resourceidentity, resource> installedresources = getinstalledresources(provisionservice); map<requirement, resource> requirements = new hashmap<requirement, resource>(); set<map.entry<string, file>> entries = artifacts.entryset(); list<resource> resourcestoinstall = new arraylist<resource>(); list<string> resourceurisinstalled = new arraylist<string>(); updatestatus("installing", null, null); for (map.entry<string, file> entry : entries) { string name = entry.getkey(); file file = entry.getvalue(); string coords = name; int idx = coords.lastindexof(':'); if (idx > 0) { coords = name.substring(idx + 1); } coords = coords.replace('/', ':'); mavencoordinates mvncoords = parse(coords); url url = file.touri().tourl(); if (url == null) { logger.warn("could not find url for file " + file); continue; } boolean isshared = !iswar(name, file); resource resource = findmavenresource(mvncoords, url, isshared); if (resource == null) { logger.warn("could not find resource for " + mvncoords + " and " + url); } else { resourceidentity identity = resource.getidentity(); resource oldresource = installedresources.remove(identity); if (oldresource == null && !resourcehandlemap.containskey(identity)) { if (isshared) { logger.debug("todo not installing " + (isshared ? "shared" : "non-shared") + " resource: " + identity); } else { logger.info("installing " + (isshared ? "shared" : "non-shared") + " resource: " + identity); resourcestoinstall.add(resource); resourceurisinstalled.add(name); } } } } for (resource installedresource : installedresources.values()) { resourceidentity identity = installedresource.getidentity(); resourcehandle resourcehandle = resourcehandlemap.get(identity); if (resourcehandle == null) { logger.warn("todo: cannot uninstall " + installedresource + " as we have no handle!"); } else { logger.info("uninstalling " + installedresource); resourcehandle.uninstall(); resourcehandlemap.remove(identity); logger.info("uninstalled " + installedresource); } } if (resourcestoinstall.size() > 0) { logger.info("installing " + resourcestoinstall.size() + " resource(s)"); set<resourcehandle> resourcehandles = new linkedhashset<>(); resourceinstaller.context context = new defaultinstallercontext(resourcestoinstall, requirements); for (resource resource : resourcestoinstall) { resourcehandles.add(resourceinstaller.installresource(context, resource)); } logger.info("got " + resourcehandles.size() + " resource handle(s)"); for (resourcehandle resourcehandle : resourcehandles) { resourcehandlemap.put(resourcehandle.getresource().getidentity(), resourcehandle); } } return resourceurisinstalled; }
WillemJiang/fabric8
[ 1, 0, 0, 0 ]
3,401
private static MavenCoordinates parse(String coordinates) { MavenCoordinates result; String[] parts = coordinates.split(":"); if (parts.length == 3) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], null, null); } else if (parts.length == 4) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], null); } else if (parts.length == 5) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]); } else { throw new IllegalArgumentException("Invalid coordinates: " + coordinates); } return result; }
private static MavenCoordinates parse(String coordinates) { MavenCoordinates result; String[] parts = coordinates.split(":"); if (parts.length == 3) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], null, null); } else if (parts.length == 4) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], null); } else if (parts.length == 5) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]); } else { throw new IllegalArgumentException("Invalid coordinates: " + coordinates); } return result; }
private static mavencoordinates parse(string coordinates) { mavencoordinates result; string[] parts = coordinates.split(":"); if (parts.length == 3) { result = mavencoordinates.create(parts[0], parts[1], parts[2], null, null); } else if (parts.length == 4) { result = mavencoordinates.create(parts[0], parts[1], parts[2], parts[3], null); } else if (parts.length == 5) { result = mavencoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]); } else { throw new illegalargumentexception("invalid coordinates: " + coordinates); } return result; }
WillemJiang/fabric8
[ 0, 0, 1, 0 ]
19,814
@Override public void validateDataOnEntry() throws DataModelException { // TODO auto-generated method stub, to be implemented by parser }
@Override public void validateDataOnEntry() throws DataModelException { }
@override public void validatedataonentry() throws datamodelexception { }
airlenet/yang-maven-plugin
[ 0, 1, 0, 0 ]
19,815
@Override public void validateDataOnExit() throws DataModelException { // TODO auto-generated method stub, to be implemented by parser }
@Override public void validateDataOnExit() throws DataModelException { }
@override public void validatedataonexit() throws datamodelexception { }
airlenet/yang-maven-plugin
[ 0, 1, 0, 0 ]
19,923
@OnClick(R.id.btn_meter_set_minus) void decreaseLevel() { if (mLevelToSet == Channels.CHN_MIN_VALUE_OF_EVERYTHING) { return; } mLevelToSet--; mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet)); //TODO send setting level frame and change shared prefs and display updateLevelForPrefsAndViewAndSendFrame(mLevelToSet); isLevelZero(); }
@OnClick(R.id.btn_meter_set_minus) void decreaseLevel() { if (mLevelToSet == Channels.CHN_MIN_VALUE_OF_EVERYTHING) { return; } mLevelToSet--; mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet)); updateLevelForPrefsAndViewAndSendFrame(mLevelToSet); isLevelZero(); }
@onclick(r.id.btn_meter_set_minus) void decreaselevel() { if (mleveltoset == channels.chn_min_value_of_everything) { return; } mleveltoset--; mtextviewlevel.settext(string.format(locale.us, "%1$d", mleveltoset)); updatelevelforprefsandviewandsendframe(mleveltoset); islevelzero(); }
SirdarYangK/SirdarYKCode
[ 0, 1, 0, 0 ]
19,924
@OnClick(R.id.btn_meter_set_plus) void increaseLevel() { if (mLevelToSet == Channels.CHN_MAX_LEVEL) { return; } mLevelToSet++; mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet)); //TODO send setting level frame and change shared prefs and display updateLevelForPrefsAndViewAndSendFrame(mLevelToSet); isLevelZero(); }
@OnClick(R.id.btn_meter_set_plus) void increaseLevel() { if (mLevelToSet == Channels.CHN_MAX_LEVEL) { return; } mLevelToSet++; mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet)); updateLevelForPrefsAndViewAndSendFrame(mLevelToSet); isLevelZero(); }
@onclick(r.id.btn_meter_set_plus) void increaselevel() { if (mleveltoset == channels.chn_max_level) { return; } mleveltoset++; mtextviewlevel.settext(string.format(locale.us, "%1$d", mleveltoset)); updatelevelforprefsandviewandsendframe(mleveltoset); islevelzero(); }
SirdarYangK/SirdarYKCode
[ 0, 1, 0, 0 ]