{ // 获取包含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 !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO 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 !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; 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, 'PDF TO 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 }); }); } })(); \r\n\n\nA:\n\nSimple canvas drag and drop.\n\nCreate a mouse object and set the mouse positions and button state by listening to the mouse events.\nCreate an array of circles that describe the position and size of the each circle.\nCreate a function to draw a circle. In that function you check if the circle is out of bounds and move it if it is.\nCreate a position search function that checks each circle and how far it is from a point. If the circle is under the point (dist < circle.radius) then return a referance to that circle.\nCreate a animation loop that redraws the canvas every 1/60th of a second. In that check if the mouse is down. If it is and not dragging anything see if the mouse is over a circle. If it is select that circle for dragging. When the mouse is up drop the circle.\n\nAs it is an assignment we should not just give you the solution. But school is the only time in life when we are not allowed to ask for help, the time when we most need it. I assume that you are interested in learning and learning by example is in many situations the best.\nIf you have any questions please do ask\n\n\"use strict\";\r\nconst canvas = document.createElement(\"canvas\"); \r\ncanvas.height = innerHeight;\r\ncanvas.width = innerWidth;\r\ncanvas.style.position = \"absolute\"; \r\ncanvas.style.top = canvas.style.left = \"0px\";\r\nconst ctx = canvas.getContext(\"2d\");\r\ndocument.body.appendChild(canvas);\r\nctx.font = \"48px arial\";\r\nctx.textAlign = \"center\";\r\nctx.textBaseline = \"middle\";\r\nvar w = canvas.width;\r\nvar h = canvas.height;\r\nvar renderUpdate = true; // flags if there is a need to render\r\nvar globalTime = 0;\r\nconst mouse = {\r\n x:0,y:0,button:false\r\n};\r\nconst circles = [{\r\n x : 100,\r\n y : 100,\r\n radius : 40,\r\n col : \"red\",\r\n lineWidth : 4,\r\n highlight : false,\r\n },{\r\n x : 200,\r\n y : 100,\r\n radius : 40,\r\n col : \"green\",\r\n lineWidth : 4,\r\n highlight : false,\r\n }, \r\n];\r\nvar closestCircle; // holds result of function findClosestCircle2Point\r\nconst drag = { // if dragging this holds the circle being dragged\r\n circle : null,\r\n offsetX : 0, // distance from mouse to circle center when drag started\r\n offsetY : 0,\r\n}\r\nconst message = { // a message to inform of problems.\r\n time : 120, // 60 ticks per second\r\n text: \"Click drag circles\",\r\n}\r\n// adds mouse events listeners\r\ncanvas.addEventListener(\"mousemove\",mouseEvent)\r\ncanvas.addEventListener(\"mousedown\",mouseEvent)\r\ncanvas.addEventListener(\"mouseup\",mouseEvent)\r\n\r\n// function to handle all mouse events\r\nfunction mouseEvent(e){\r\n var m = mouse;\r\n var bounds = canvas.getBoundingClientRect();\r\n m.x = e.clientX - bounds.left; \r\n m.y = e.clientY - bounds.top; \r\n if(e.type === \"mousedown\"){\r\n m.button = true;\r\n }else if(e.type === \"mouseup\"){\r\n m.button = false;\r\n }\r\n renderUpdate = true; // flag that there could be a render change.\r\n}\r\n\r\n\r\n\r\n// this finds the closest circle under x,y if nothing under the point then retVal.circle = null\r\nfunction findClosestCircle2Point(x, y, retVal){\r\n if(retVal === undefined){\r\n retVal = {};\r\n }\r\n var minDist = Infinity;\r\n var dist;\r\n var xx,yy;\r\n retVal.circle = null;\r\n for(var i = 0; i < circles.length; i ++){\r\n xx = x - circles[i].x;\r\n yy = y - circles[i].y;\r\n dist = Math.sqrt(xx*xx+yy*yy);\r\n if(dist < minDist && dist <= circles[i].radius){\r\n minDist = dist;\r\n retVal.circle = circles[i];\r\n }\r\n }\r\n return retVal;\r\n}\r\n\r\n// this draws a circle, adds highlight if needed and makes sure the circle does not go outside the canvas\r\nfunction drawCircle(circle){\r\n var c = circle;\r\n var rad = c.radius + c.lineWidth / 2; // get radius plus half line width\r\n // keep circle inside canvas\r\n c.x = c.x - rad < 0 ? c.x = rad : c.x + rad >= w ? c.x = w-rad : c.x;\r\n c.y = c.y - rad < 0 ? c.y = rad : c.y + rad >= h ? c.y = h-rad : c.y;\r\n ctx.lineWidth = 4;\r\n if(c.highlight){ // highlight the circle if needed\r\n ctx.strokeStyle = \"#0F0\";\r\n ctx.globalAlpha = 0.5;\r\n ctx.beginPath();\r\n ctx.arc(c.x,c.y,c.radius + c.lineWidth,0,Math.PI * 2);\r\n ctx.stroke();\r\n c.highlight = false;\r\n }\r\n // draw the circle\r\n ctx.fillStyle = c.col;\r\n ctx.strokeStyle = c.col;\r\n ctx.globalAlpha = 0.5;\r\n ctx.beginPath();\r\n ctx.arc(c.x,c.y,c.radius,0,Math.PI * 2);\r\n ctx.fill();\r\n ctx.globalAlpha = 1;\r\n ctx.stroke();\r\n}\r\n\r\n\r\n// main update function\r\nfunction update(time){\r\n globalTime = time;\r\n requestAnimationFrame(update); // get the next animation frame.\r\n if(!renderUpdate ){ // don't render if there is no need\r\n return;\r\n }\r\n renderUpdate = false;\r\n\r\n\r\n ctx.clearRect(0,0,w,h);\r\n // when not dragging look for the closest circle under the mouse and highlight it\r\n if(drag.circle === null){\r\n closestCircle = findClosestCircle2Point(mouse.x,mouse.y,closestCircle); \r\n if(closestCircle.circle !== null){\r\n closestCircle.circle.highlight = true;\r\n }\r\n }\r\n if(mouse.button){ // if the mouse is down start dragging if circle is under mouse\r\n if(drag.circle === null){\r\n if(closestCircle.circle !== null){\r\n drag.circle = closestCircle.circle;\r\n drag.offsetX = mouse.x - drag.circle.x;\r\n drag.offsetY = mouse.y - drag.circle.y;\r\n }else{\r\n mouse.button = false;\r\n }\r\n }else{\r\n drag.circle.x = mouse.x - drag.offsetX;\r\n drag.circle.y = mouse.y - drag.offsetY;\r\n }\r\n }else{ // drop circle \r\n drag.circle = null;\r\n }\r\n for(var i = 0; i < circles.length; i ++){ // draw all circles\r\n drawCircle(circles[i]);\r\n }\r\n \r\n // display any messages if needed.\r\n if(message.time > 0){\r\n message.time -= 1;\r\n ctx.fillStyle = \"black\";\r\n ctx.fillText(message.text,w/2,h/2);\r\n renderUpdate = true; // while message is up need to render.\r\n }\r\n \r\n}\r\nrequestAnimationFrame(update); // start the whole thing going.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28949,"cells":{"text":{"kind":"string","value":"Q:\n\nUsing the iPad Pro with Apple digital AV Adapter and headphone jack adapter\n\nI am using the digital AV USB-C to connect my iPad to an external display via HDMI. \nNow I want to connect external speakers via a headphone jack. \nI plugged the AV adapter into the iPad, plugged HDMI into the adapter and plugged the headphone jack in the AV adapter using the USB-C headphone jack adapter from apple. (I used the USB-C Port of the AV adapter). \nThe iPad does not recognize the external speakers, and the audio is coming out of the iPad speakers. I cannot change this in the control center. \nIs the AV Adapter capable of routing audio to its USB-C port?\nOr am I missing something?\n\nA:\n\nThe USB-C port on the Digital AV Multiport adapter is for charging only. It doesn't carry any data at all - and therefore also not sound.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28950,"cells":{"text":{"kind":"string","value":"Q:\n\nMysql performance: 1 query over 3 tables or 2 queries?\n\nI need data from 3 different tables:\n\nCatergory table\nScoretable 1\nScoretable 2\n\nWhat is now better for the performance?\n\nMake 3 seperated SELECT Queries\nMake 2 queries and connect scoretable 1 and 2 and make a normal select query for the categories\nConnect all 3 queries in 1?\n\nNumber 2:\nSELECT scoretable1.category, scoretable1.score, scoretable2.score\nFROM scoretable1, scoretable2\nWHERE scoretable1.consultant = scoretable2.consultant \nAND scoretable2.consultant = '14' \nAND scoretable1.category = scoretable2.category\n\nThank you very much!\nP.S. The category table is very small so I could export it also as a cache file as a serialized array? (Maybe the best way for this table)\n\nA:\n\nMy guess would be that it is best to do it in one query. But i'm not absolutely sure. Maybe the query analyser can help you out here.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28951,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to remove warning: link.res contains output sections; did you forget -T?\n\nI'm using fpc compiler and I want to remove this warning. I've read fpc's options but I can't find how to do that. Is this possible?\nit appear when I run command:\nfpc foo.pas\n\nout:\n\nTarget OS: Linux for i386 Compiling foo.pas Linking p2 /usr/bin/ld:\n warning: link.res contains output sections; did you forget -T? 79\n lines compiled, 0.1 sec\n\nA:\n\nIt's a bug in certain LD versions. Just ignore it for now, or see if your distro has an update for your LD. (package binutils)\nhttp://www.freepascal.org/faq.var#unix-ld219\n\nA:\n\nIt‘s not a bug because ld behaves like its specification. The man page of ld 2.28 reads:\n\nIf the linker cannot recognize the format of an object file, it will assume that it is a linker script. A script specified in this way augments the main linker script used for the link (either the default linker script or the one specified by using -T). This feature permits the linker to link against a file which appears to be an object or an archive, but actually merely defines some symbol values, or uses \"INPUT\" or \"GROUP\" to load other objects. Specifying a script in this way merely augments the main linker script, with the extra commands placed after the main script; use the -T option to replace the default linker script entirely, but note the effect of the \"INSERT\" command.\n\nTL;DR ☺. In a nutshell: In most cases the users are not aware of the linker script they are using because a “main script” (= default script) is provided by the tool chain. The main script heavily refers to intrinsics of the compiler-generated sections and you have to learn the ropes to change it. Most users do not.\nThe common approach to provide your own script is via the -T option. That way the main linker script is ignored and your script takes over control over the linkage. But you have to write everything from scratch.\nIf you just want to add a minor feature, you can write your specs into a file and append the file name to the command line of ld (or gcc / g++) without the -T option. That way the main linker script still does the chief work but your file augments it. If you use this approach, you get the message of the header of this thread to inform you that you might have provided a broken object unintentionally.\nThe source of this confusion is that there is no way to specify the rôle of the additional file. This could easily be resolved by adding another option to ld just like the -dT option for “default scriptfile”: Introduce a -sT option for “supplemental scriptfile”.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28952,"cells":{"text":{"kind":"string","value":"Q:\n\nlocalscroll's hash option, flickers the page when scrolling. How can I make the scrolling smooth\n\nI'm implementing a jquery plugin (localscroll) to smooth scroll to named anchor elements withing a page. localscroll supports an option called 'hash', what it basically does is it appends the named anchor hash into the URL making it easy for the user to bookmark and move using the browser back/forward buttons.\n\nHTML\n\n\nJavascript (jquery)\n$(document).ready(function () {\n $(\"#navigation\").localScroll({\n offset: {left: 0, top: -56},\n hash: true,\n easing: 'easeInOutExpo'\n });\n});\n\nThe above code runs fine, but whenever a link is clicked the scrolling starts with a flicker (probably because the default behavior of the browser is to jump to the named anchor). This flicker thing is more visible in Firefox than Chrome or Safari and is a big NO-NO. How can I make the transition smooth with the address bar reflecting the current named anchor?? Any help is much appreciated. Thanx!\n\nA:\n\nI found out why my page was flickering upon clicking the links mapped with localscroll. I was including the jquery.js file after the localscroll.js file, which was causing this strange behavior. So, I included all the minified versions of jquery, localscroll, easing and other javascripts that I was using in my scripts in a single .js file and this fixed the problem.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28953,"cells":{"text":{"kind":"string","value":"Q:\n\nstringr: how to recover sentences from a string that was derived from concatenating those sentences\n\nI have three units strings which each contain commas (\",\"). Each unit string also begins with a capital letter. These strings have been concatenated in a paste0() fashion such that a comma (\",\") and no spaces separate the original unit strings. \nI provide R code below to give more context to my question:\nstring1 <- \"I like dogs, cats, and pigs\"\nstring2 <- \"Community health centers, businesses, stores\"\nstring3 <- \"Jamie Foxx sings, dances, and acts\"\nstring_combined <- paste0(string1,\",\",string2,\",\",string3)\nstring_combined\n\n[1] \"I like dogs, cats, and pigs,Community health centers, businesses, stores,Jamie Foxx sings, dances, and acts\"\n\nAs can be seen from the console output above, the strings meet at the junction of:\n\nlast lowercase letter of first string\na comma\nfirst uppercase letter of the 2nd string\nno spaces at the junction of unit strings\n\nI have used the str_view_all(string = string_combined,pattern = \",\\\\S\") to locate where the strings join, but I am not sure how to recover the original unit strings (string1, string2, string3). \nQuestion: How can I recover the original unit strings from the larger string (string_combined), which is a concatenation of the unit strings, recognizing that the original unit strings, which themselves contain commas, are separated by commas in the concatenated string.\nPerhaps someone might be able to help answer my question. Thank you.\n\nA:\n\nYou can use the pattern described above in strsplit\nstrsplit(string_combined, \"(?<=[a-z]),(?=[A-Z])\",perl = TRUE)[[1]]\n\n#[1] \"I like dogs, cats, and pigs\" \"Community health centers, businesses, stores\"\n#[3] \"Jamie Foxx sings, dances, and acts\" \n\nand similar with stringr::str_split\nstringr::str_split(string_combined, \"(?<=[a-z]),(?=[A-Z])\")[[1]] \n\nThis splits the string at lower case letter(a-z), followed by comma (,), followed by upper-case letter (A-Z). \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28954,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to Add Custom CSS Buttons to WordPress as a Shortcode?\n\nHow do I add custom CSS buttons as a shortcode like this: \n[button class=\"mybutton1\" link=\"home\"]\nI have the CSS of the button from here\n.myButton {\n\n -moz-box-shadow:inset 0px 1px 0px 0px #cf866c;\n -webkit-box-shadow:inset 0px 1px 0px 0px #cf866c;\n box-shadow:inset 0px 1px 0px 0px #cf866c;\n\n background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #d0451b), color-stop(1, #bc3315));\n background:-moz-linear-gradient(top, #d0451b 5%, #bc3315 100%);\n background:-webkit-linear-gradient(top, #d0451b 5%, #bc3315 100%);\n background:-o-linear-gradient(top, #d0451b 5%, #bc3315 100%);\n background:-ms-linear-gradient(top, #d0451b 5%, #bc3315 100%);\n background:linear-gradient(to bottom, #d0451b 5%, #bc3315 100%);\n filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#d0451b', endColorstr='#bc3315',GradientType=0);\n\n background-color:#d0451b;\n\n -moz-border-radius:3px;\n -webkit-border-radius:3px;\n border-radius:3px;\n\n border:1px solid #942911;\n\n display:inline-block;\n color:#ffffff;\n font-family:arial;\n font-size:13px;\n font-weight:normal;\n padding:6px 24px;\n text-decoration:none;\n\n text-shadow:0px 1px 0px #854629;\n\n}\n.myButton:hover {\n\n background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #bc3315), color-stop(1, #d0451b));\n background:-moz-linear-gradient(top, #bc3315 5%, #d0451b 100%);\n background:-webkit-linear-gradient(top, #bc3315 5%, #d0451b 100%);\n background:-o-linear-gradient(top, #bc3315 5%, #d0451b 100%);\n background:-ms-linear-gradient(top, #bc3315 5%, #d0451b 100%);\n background:linear-gradient(to bottom, #bc3315 5%, #d0451b 100%);\n filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#bc3315', endColorstr='#d0451b',GradientType=0);\n\n background-color:#bc3315;\n}\n.myButton:active {\n position:relative;\n top:1px;\n}\n\nI wish to add this to my WordPress site as a shortcode. How do I do this?\nThanks!\n\nA:\n\nfunction myButton($atts, $content = ''){ \n\n extract(shortcode_atts(array(\n 'text' => '',\n 'link' => ''\n ), $atts)); \n\n $html = '
' . $text . '
';\n return $html; \n}\n\nadd_shortcode('mybutton', 'myButton');\n\nAdd this to your functions.php and you will be able to call the button within wordpress using the shortcode you wanted. \nAs you can see the class and the link you set become the variables to be used in the shortcode. \nIf you want to add text to the button you could change the html to the following:\n$html = '
' . $content . '
';\n\nand use it like this\n[button class='mybutton' link='home']mybuttonname[/button]\n\nHope this helps\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28955,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to say \"as you wish\" in Chinese\n\nI want to know what to say in the following scenario: I am pushing someone for his own good, and he is not doing what I want, so I would then say to him \"Okay, as you wish.\" How can I express this in Chinese? \n\nUpdate: 如你所愿(rúnǐsuǒyuàn)from Google Translate is not understood as having the same meaning by Chinese speakers.\n\nA:\n\nI think that “随你便” may suit your needs. This phrase can be translated as \"as you wish\" or \"suit yourself\" or even \"whatever.\"\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28956,"cells":{"text":{"kind":"string","value":"Q:\n\nreliable place to buy .io domains\n\nI'm looking around trying to find a good place to buy .io domains.\nSuddenly, I think I'm surrounded by scammers, since .io domain providers websites, are really badly-designed and I am not feeling of confident about dealing with them.\nI'm trying to deal with nic.io guys right now.\nIf somebody could point me out some company, it would be appreciated. Specially because the domain costs £60. It's not that cheap to spend with someone that could just leave you waiting for some answer after the payment.\n\nA:\n\nNic.io seems to be the official registry and primary registrar for registering .io domains, so if you don't want to register through them, you're SOL. There are other registrars that also sell .io domains, but they're still just going through nic.io.\nI'm sorry if you have bad feelings about nic.io, but that's just the nature of the domain name industry. When you have a regulatory agency like ICANN/Network Solutions, the industry naturally becomes dominated by sleazy companies. You can thank cronyism for that.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28957,"cells":{"text":{"kind":"string","value":"Q:\n\nselected option value cannot be reset\n\nI'm having two select boxes on my mvc razor view which are styled using selectBoxIt plugin\nOn changing #ddHour I want to reset #ddDay select(to set on first select choice)\nvar selectedDay = $('#ddDay option:nth-child(1)').val();\n\nI tried with \n$(\"#ddDay\").selectBoxIt('refresh');\n\nbut it always returns same previously selected #ddDay option\n\nA:\n\nYou should use selectOption to do that:\n$(\"#ddDay\").selectBoxIt().data(\"selectBox-selectBoxIt\").selectOption('yourSelectBoxValue');\n\nRegards.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28958,"cells":{"text":{"kind":"string","value":"Q:\n\nSearch a div and narrow down options\n\nI have div with a bunch of cities inside. And it is frustrating when you don't find the city you are looking for.\nSo I'm trying to add a search bar, to exclude the cities that doesn't match the search string.\n
\n
\n \n
\n
\n\n\nHere is an attempt in a Fiddle.\nThis one with highlight was the reference: http://jsfiddle.net/FranWahl/aSjqT/\nMy question is:\nHow can i search a div, and exclude strings that is not \"searched\" for.\n\nA:\n\nIn your fiddle do\n\n$(\"#search\").on(\"keyup\", function() {\r\n var value = $(this).val().toUpperCase();\r\n \r\n $(\"#cities a\").each(function(index) { \r\n $row = $(this); \r\n var id = $row.text().toUpperCase(); \r\n //All match\r\n //if (id.indexOf(value) == -1) {\r\n //For startWith Match\r\n if (!id.startsWith(value)) {\r\n $row.hide();\r\n }\r\n else {\r\n $row.show();\r\n }\r\n });\r\n });\n\r\n
\r\n
\r\n \r\n
\r\n
\r\n
\r\n \n\nhttps://jsfiddle.net/k8rp18qb/2/\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28959,"cells":{"text":{"kind":"string","value":"Q:\n\nPython: count specific occurrences in a dictionary\n\nSay I have a dictionary like this:\nd={\n'0101001':(1,0.0), \n'0101002':(2,0.0),\n'0101003':(3,0.5),\n'0103001':(1,0.0),\n'0103002':(2,0.9),\n'0103003':(3,0.4),\n'0105001':(1,0.0),\n'0105002':(2,1.0),\n'0105003':(3,0.0)}\n\nConsidering that the first four digits of each key consitute the identifier of a \"slot\" of elements (e.g., '0101', '0103', '0105'), how can I count the number of occurrences of 0.0 for each slot?\nThe intended outcome is a dict like this:\nresult={\n'0101': 2,\n'0103': 1,\n'0105': 2} \n\nApologies for not being able to provide my attempt as I don't really know how to do this.\n\nA:\n\nUse a Counter, add the first four digits of the key if the value is what you're looking for:\nfrom collections import Counter\n\ncounts = Counter()\n\nfor key, value in d.items():\n if value[1] == 0.0:\n counts[key[:4]] += 1\n\nprint counts\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28960,"cells":{"text":{"kind":"string","value":"Q:\n\nChrome extension Script Injection to each open tab\n\nI tried to build simple extension according to the examples: \nfrom here and here\nand I must be doing something wrong here.\nAll I want is for start that on each loading page ( or even better before loading ) it will popup \nhello alert\nmanifest.json\n{\n \"background\": {\n \"page\": \"background.html\"\n },\n \"content_scripts\": [\n {\n \"matches\": [\"http://*/*\",\"https://*/*\"], \n \"js\": [\"jquery-1.8.2.min.js\",\"contentscript.js\"],\n \"run_at\": \"document_end\"\n }\n ],\n \"web_accessible_resources\": [\n \"script_inpage.js\"\n ],\n \"browser_action\": {\n\n \"default_popup\": \"popup.html\",\n \"default_title\": \"Test 123\"\n },\n \"content_security_policy\": \"script-src 'self'; media-src *; object-src 'self'\",\n \"description\": \"Simple Test 123.\",\n\n \"manifest_version\": 2,\n \"minimum_chrome_version\": \"18\",\n \"name\": \"Test 123\",\n \"permissions\": [ \n \"unlimitedStorage\",\n \"http://*/\",\n \"tabs\",\n ],\n\n \"version\": \"2.6\"\n}\n\nbackground.html is empty for now \ncontentscript.js:\nvar s = document.createElement('script');\ns.src = chrome.extension.getURL('script_inpage.js');\n(document.head||document.documentElement).appendChild(s);\ns.onload = function() {\n s.parentNode.removeChild(s);\n};\n\nscript_inpage.js:\nalert(\"this is script\");\n\nThere is no error even when I trigger the developer console window. \n\nA:\n\nYour manifest file is invalid, there's a superfluous comma after the last entry in the \"permissions\" section:\n\"permissions\": [ \n \"unlimitedStorage\",\n \"http://*/\",\n \"tabs\", // <-- Remove that comma\n],\n\nIf you want your script to run as early as possible, use \"run_at\": \"document_start\" instead of \"document_end\". Then, your script will run before and even exist.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28961,"cells":{"text":{"kind":"string","value":"Q:\n\nHow do I connect to the ManagedObjectContext object of the File Owner in XCode 4\n\nI'm building a really simple Core Data app in XCode 4. There's an entity model with just one entity (Employee) and just one attribute (name).\nIn IB I've added a default Table View to display the employees, two buttons (one to add an employee and another to delete an employee) and an ArrayController.\nIt is my understanding that the ArrayController's managedObjectContext somehow needs to be connected to the one that is initialised by the App Delegate. I can see the code for initialising the context but IB does not let me connect to it.\nHow do I do this connection?\nMany thanks.\n\nA:\n\nHow does Interface Builder not allow you connect it? Bindings are not the same as IBOutlets in Interface Builder context. If file owner is instance of AppDelegate (which always has initial managed object context) you just should define NSArrayController's managedObjectContext binding's object as File's owner and set managedObjectContext as its model path.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28962,"cells":{"text":{"kind":"string","value":"Q:\n\nHow can I print one Array value of a SSJS RetrieveRequest\n\nI have made a Retrieve call using the below code, but am struggling to print the Email field values into a clean list.\nI can get this output and can see the email addresses are pulling through:\n\n{\"Name\":null,\"Keys\":null,\"Type\":\"DataExtensionObject\",\"Properties\":[{\"Name\":\"Email\",\"Value\":\"1449domain@yahoo.com\"}],\"Client\":null,\"PartnerKey\":null,\"PartnerProperties\":null,\"CreatedDate\":\"0001-01-01T00:00:00.000\",\"CreatedDateSpecified\":false,\"ModifiedDate\":null,\"ModifiedDateSpecified\":false,\"ID\":0,\"IDSpecified\":false,\"ObjectID\":null,\"CustomerKey\":null,\"Owner\":null,\"CorrelationID\":null,\"ObjectState\":null,\"IsPlatformObject\":false,\"IsPlatformObjectSpecified\":false}1:\n {\"Name\":null,\"Keys\":null,\"Type\":\"DataExtensionObject\",\"Properties\":\n\nThe code I'm using is:\n\n\n\nthank you\n\nA:\n\ntry this:\nfor (var i in rows) {\n\n var output = rows[i];
\n\n var properties = output[\"Properties\"]\n\n var email = \"\";\n\n for (var j in properties) {\n var name = properties[j][\"Name\"];\n var value = properties[j][\"Value\"];\n\n if(name ==\"Email\") //Find KeyValuePair for email\n {\n email = value;\n break; // break the properties loop\n }\n\n }\n\n if(email!=\"\")\n {\n Write(\"Email for row \" + i + \": \" + email + \"
\");\n }else{\n Write(\"Can't find email for row \" + i + \"
\");\n }\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28963,"cells":{"text":{"kind":"string","value":"Q:\n\nSSRS Chart for Milestones\n\nI need to create a SSRS report to present actual start date vs. planned start dates for milestones of a project (selected as input parameter)\nThe chart should look like this:\n\nI have created the table in a separate table. However, I don’t know which chart type should I use and how do I have to set up the chart? (Chart Data, Category Groups and Series Groups).\n(Data comes from SQL Server, SSRS Version 14.0.1016.285; SSDT 15.6.4)\nMany Thanks in advance\n\nA:\n\nThis might look a bit long winded but it's fairly simple so stick with it :)\nTo start with I did not know your data structure so I've just made some assumptions. You may have to rework some of this to get it to fit but I've tried to keep it simple.\nThe approach will be to use a subreport to plot the dots and a main report to show the overall table. With this in mind, as we will have more than one dataset referencing our data I added some tables to my sample database before I started wit the following.\nThe first is a simple table containing months and years, you could a use view over a date table if you have one but this will do for now.\nCREATE TABLE prjYearMonth (Year int, Month int)\n\nINSERT INTO prjYearMonth VALUES\n(2018, 8),\n(2018, 9),\n(2018, 10),\n(2018, 11),\n(2018, 12),\n(2019, 1),\n(2019, 2)\n\nNext is the project milestone table\nCREATE TABLE prjMileStones (msID int, msLabel varchar(50), msPlannedStart date, msActualStart date)\n\nINSERT INTO prjMileStones VALUES\n(1, 'Milestone 1', '2018-10-30', '2018-12-13'),\n(2, 'Milestone 2', '2018-11-12', '2018-12-10'),\n(3, 'Milestone 3', '2018-10-21', '2018-12-25'),\n(4, 'Milestone 4', '2018-10-18', '2018-11-28'),\n(5, 'Milestone 6', '2019-01-08', '2019-01-29')\n\nOK, Now let's start the report...\nCreate a new empty report then add a dataset with the following query\nSELECT \n * \n FROM prjYearMonth d\n LEFT JOIN prjMileStones t on (d.Year = YEAR(t.msPlannedStart) AND d.Month = Month(t.msPlannedStart))\n or (d.Year = YEAR(t.msActualStart) AND d.Month = Month(t.msActualStart))\n\nNow add a matrix item to the report. Add a Row Group that groups on msLabel. \nNext add two Column Groups. First a group that groups on Month and then add a parent group that groups on Year.\nAdd columns on the row group so that you end up with 4 columns msID; msLabel; msPlannedStart; msActualStart.\nFinally (for now) set the Expression of the Month field (the one in the column header) to be \n= Format(DATESERIAL(2017, Fields!Month.Value, 1), \"MMM\")\n\nThis will just give us the month name rather than the number (the 2017 is irrelevant, any year will do). Now just format as required.\nYou report design should look something like this..\n\nIf we run the report now we will get this..\n\nNow to plot the dots...\nFor this we will create a small subreport. The subreport will accept 3 parameters. Year, Month, msID (the milestone ID from your main table). We will need the data in a slightly different structure for this sub report but the work can be done in the dataset query so nothing new is required in the database itself.\nSo, create a new report, let's call it _subMonthChart.\nNext add a dataset with the following query..\nDECLARE @t TABLE(msID int, msLabel varchar(50), PlannedOrActual varchar(1), msStartDate date)\n\nINSERT INTO @t \n SELECT msId, mslabel, 'P', msPlannedStart FROM prjMileStones\n UNION ALL\n SELECT msId, mslabel, 'A', msActualStart FROM prjMileStones\n\nSELECT \n 1 AS Y, Day(msStartDate) as Day, PlannedOrActual \n FROM prjYearMonth d\n LEFT JOIN @t t on (d.Year = YEAR(t.msStartDate) AND d.Month = Month(t.msStartDate))\n WHERE [Year] = @Year and [Month] = @Month and msID = @msID\n\nYour report should now have 3 parameters that were automatically created, edit all three to Allow Nulls.\nNote: The Y in the dataset is just some arbitrary value to help plot on the chart,. I will set the Y axis to range from 0 - 2 so 1 will sit in the middle.\nNext, add a line chart with markers. Don't worry about the size for now...\nSet the Values as Y\nSet the Category Groups as Day\nSet the Series Groups as PlannedOrActual\nRight click the horizontal Axis, choose properties and set the Axis Type to Scalar, switch off 'Always include zero' then set Min = 1, Max = 31, Interval = 1, Interval Type = Default.\nNote that for data in months that don't have 31 days the plots points will not be accurate but they will be close enough for your purposes.\nRight click the Vertical Axis, choose properties and set the Mn=0, Max=2, Interval = 1, Interval Type = Default\nNext, right click on one of the series lines and choose properties. Set the marker to Diamond, the marker size to 8pt and the Marker Color this expression =IIF(Fields!PlannedOrActual.Value = \"P\", \"Blue\", \"Green\")\nThe report design should look something like this... (check the highlighted bits in particular)\n\nNow let's quickly test the subreport, based on my sample data I set the parameters to 2019, 1 and 5 and get the following results....\n\nAs we can see, our two dates that fall in January for this milestone were plotted in roughly the correct positions. \nNearly there...\nNext right click on both Axes and turn off 'Show Axis' so we hide them.\nNow resize the chart to something that will fit in the main report cell. In my example I set the size to 2cm, 1.2cm and moved it top left of the report. Then set the report to be the same size as the chart (2cm,1.2cm again in my case).\nSave the sub report and go back to your main report...\nFor the 'Data' cell where the rows and columns intersect, set the size to match the subreport size (2cm, 1.2cm) then right click the cell and insert subreport.\nRight click the newly inserted subreport item and choose properties.\nChoose _subMonthChart as the subreport from the dropdown.\nClick the parameters tab. Add an entry for each parameter (Year/Month/msID) and set its value to be the corresponding field from the dataset.\nFINALLY !!!! Set the border on the cell containing the subreport to have borders all round, just so it matches your mock-up..\nYour report design should now look like this...\n\nNow when the report runs, it will pass in the month, year and milestone ID to the subreport in each cell which in turn will plot the dates as required.\nWhen we run the report we should finally get this...\n\nThis may need some refining but hopefully you can get this going based on this. If you have trouble I suggest you recreate this example in its entirety, get it working and then swap out the database parts to fit your current database.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28964,"cells":{"text":{"kind":"string","value":"Q:\n\ntelnet: connect to address 192.168.33.x: Connection refused - over Vagrant centos machine\n\nI have created a centos machine and installed nexus service over it.\nNexus service is running on 8081 port which i have opened from the vagrant file using below command inside the vagrant file.\n machine1.vm.network \"private_network\", ip: \"192.168.33.x\"\n machine1.vm.network \"forwarded_port\", guest: 80, host: 80\n machine1.vm.network \"forwarded_port\", guest: 8080, host: 8080\n machine1.vm.network \"forwarded_port\", guest: 8081, host: 8081\n\nThe nexus service is running fine on the centos machine but the telnet to the port from the same server as well as server from its network is failing. The port is not reachable from the host windows machine as well.\nThe server IP is reachable from its network machines, here all 3 network machines are created from vagrant file\nI have tried to see and confirm the nexus service is actually running on 8081 port, and its running\nI have tried to open a port 8081 to ensure firewall is not blocking using below command\niptables -A INPUT -p tcp -m tcp --dport 8081 -j ACCEPT\n\nI have browsed through multiple forum to see if any solution works, I acknowledge this is very generic error even i have faced in past, but in this case not able to identify the root cause. I doubt if its related to vagrant specific configuration\nAlso, i tried to curl the service from centos server and host server, it doesnt work:\n]$ curl http://localhost:8081\ncurl: (7) Failed connect to localhost:8081; Connection refused\n\nnetstat command doesnt give any result:\nnetstat -an|grep 8081\n[vagrant@master1 bin]$\n\nhowever the nexus service is up and running on the server with the same port\nHere is vagrant file code\n config.vm.define \"machine1\" do |machine1|\n machine1.vm.provider \"virtualbox\" do |host|\n host.memory = \"2048\"\n host.cpus = 1\n end\n machine1.vm.hostname = \"machine1\"\n machine1.vm.network \"private_network\", ip: \"192.168.33.x3\"\n machine1.vm.network \"forwarded_port\", guest: 80, host: 80\n machine1.vm.network \"forwarded_port\", guest: 8080, host: 8080\n machine1.vm.network \"forwarded_port\", guest: 8081, host: 8081\n machine1.vm.synced_folder \"../data\", \"/data\"\n end\n\n config.vm.define \"machine2\" do |machine2|\n machine2.vm.provider \"virtualbox\" do |host|\n host.memory = \"2048\"\n host.cpus = 1\n end\n machine2.vm.hostname = \"machine2\"\n machine2.vm.box = \"generic/ubuntu1804\"\n machine2.vm.box_check_update = false\n machine2.vm.network \"private_network\", ip: \"192.168.33.x2\"\n machine2.vm.network \"forwarded_port\", guest: 80, host: 85\n machine2.vm.network \"forwarded_port\", guest: 8080, host: 8085\n machine2.vm.network \"forwarded_port\", guest: 8081, host: 8090\n end\n\n config.vm.define \"master\" do |master|\n master.vm.provider \"virtualbox\" do |hosts|\n hosts.memory = \"2048\"\n hosts.cpus = 2\n end\n master.vm.hostname = \"master\"\n master.vm.network \"private_network\", ip: \"192.168.33.x1\"\n end\n\nend\n\nAs the nexus service is running on port 8081, i should be able to access the service from my host machine using http://localhost:8081.\n\nA:\n\nThe issue is most likely the Vagrant networking as you guessed. If you just want to access the nexus service running on guest from the host, perhaps this can be useful.\nTo workaround, you may try to make the Vagrant box available on public network and then access it using the public IP and for that, you will have to enable config.vm.network \"public_network\" in your Vagrant file and then just do a vagrant reload. Once done, try accessing http://public_IP_of_guest:8081 \nPlease let me know how it goes.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28965,"cells":{"text":{"kind":"string","value":"Q:\n\nHow do I assign multiple UI's to a parameter, such as both UILabels and UIButtons?\n\nI am trying to create a function that flips a UILabel, UIButton, etc. 180 degrees so that it is upside down. My problem is that I cannot find a way to give the function a parameter that is assigned to UILabels, UIButtons, etc.\nI have tried using \"Any\" to assign to my parameter, but Any does not have the method transform.\nHere is my code so far without the parameter having anything assigned:\nfunc rotate180(object: ) {\n\nobject.transform = CGAffineTransformMakeRotation(rotationAngle: 3.14)\n\n{\n\nA:\n\nYou could also implement this as an extension:\nextension UIView {\n func rotate180() {\n self.transform = CGAffineTransform(rotationAngle: 3.14)\n }\n}\n\nUsage:\nmyButton.rotate180()\nmyLabel.rotate180()\nmyView.rotate180()\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28966,"cells":{"text":{"kind":"string","value":"Q:\n\nProblem with DateTimeContinuousAxis, one day is added to each date without no apparent reason [Nativescript-Angular]\n\nI receive a json like this from chartService, But when I try to show the data, 1 day is added to each date. I am using Genymotion for emulate. I don't know if it could be an internal emulator time zone problem, will anyone know what is happening?\nJSON = [{\n\"fecha\": \"2019-09-23\",\n\"km_rec\": 431.56\n}, {\n\"fecha\": \"2019-09-25\",\n\"km_rec\": 187.12\n}, {\n\"fecha\": \"2019-09-26\",\n\"km_rec\": 270.08\n}, {\n\"fecha\": \"2019-09-27\",\n\"km_rec\": 121.04\n}, {\n\"fecha\": \"2019-09-28\",\n\"km_rec\": 407.96\n}, {\n\"fecha\": \"2019-09-29\",\n\"km_rec\": 10.98\n}]\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n\n\nngOnInit() {\n this.initDataItems()\n}\n\n private initDataItems() {\n this.checkedDistanceData();\n}\n\ncheckedDistanceData() {\n this.query(Config.storage.vehicleSelected, veh => {\n this.query(moment().format('YYYY-MM-DD') + this.id_veh, data => {\n if (data) {\n this.setChartDistance(JSON.parse(data.value));\n ...\n } else {\n this.chartService();\n ...\n }\n });\n };\n });\n\n chartService() {\n this.httpGet(route (www.dis....),\n data => {\n this.setChartDistance(data);\n this.changeDetector.detectChanges();\n },\n error => {\n error...\n }, null);\n}\n get getchartDistance() {\n return distance;\n}\n\n setChartDistance(chart) {\n this.distance = chart;\n}\n\nA:\n\nAccording to the documentation, you should store your dates in milliseconds.\nMost likely you're passing a date object that is getting serialized and on deserialization it's losing/gaining some hours and flipping to the next day.\nYou might want to run some tests if using UTC or the local timezone is better for this (since you're using moment you can use moment.utc() and then get it in ms).\nSee the example here: https://github.com/NativeScript/nativescript-ui-samples/blob/master/chart/app/examples/data-models/date-time-model.ts\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28967,"cells":{"text":{"kind":"string","value":"Q:\n\nSimple question about inertia law and trajectory\n\nI know this question is so simple, maybe a middle school level, so if this question doesn't fit here, please let me know.\nSuppose the particle bellow is in the vacuum with a constant velocity $\\vec{v_1}$. If we add a force towards the left, we get an acceleration vector $\\vec{a}$. Therefore, there is an increasing velocity $\\vec{v_2}$ towards the left.\nMy question is $v_1$ is keeping pushing the particle up with the same speed forever? In this case how would be its trajectory?\n\nA:\n\nYes, $\\vec{v_{1}}$ (or $\\vec{v_{y}}$) would be constant because there is no force accelerating nor decelerating along the direction of $\\vec{v_{y}}$.\nTherefore the equation of motion would be as follows, assuming upwards (along $\\vec{v_{y}}$) is positive $y$ axis, and left (along $\\vec{v_{x}}$) is negative $x$ axis.\n$\\vec{v_{y}} = v_{y} \\vec{{j}}$ \n$\\vec{v_{x}} = (-at) \\vec{i}$\nFrom the equations of motion, along $y$ axis, $y = {v_{y}}{t}$ - (1)\nAnd along $x$ axis, $x = -\\frac{at^{2}}{2}$ - (2)\nEliminating $t$ from (1) and (2), we get $\\frac{x}{y^{2}} = -\\frac{a}{2(v_{y})^{2}}$, this is the equation of the path traveled by the particle.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28968,"cells":{"text":{"kind":"string","value":"Q:\n\nMongoDB Conditional validation on arrays and embedded documents\n\nI have a number of documents in my database where I am applying document validation. All of these documents may have embedded documents. I can apply simple validation along the lines of SQL non NULL checks (these are essentially enforcing the primary key constraints) but what I would like to do is apply some sort of conditional validation to the optional arrays and embedded documents. By example, lets say I have a document that looks like this:\n{\n \"date\": <>,\n \"name\" : <>,\n \"assets\" : << amount of money we have to trade with>>\n}\n\nClearly I can put validation on this document to ensure that date name and assets all exist at insertion time. Lets say, however, that I'm managing a stock portfolio and the document can have future updates to show an array of stocks like this:\n{\n \"date\" : <>,\n \"name\" : <>,\n \"assets\" : << amount of money we have to trade with>>\n \"portfolio\" : [\n { \"stockName\" : \"IBM\",\n \"pricePaid\" : 155.39,\n \"sharesHeld\" : 100\n },\n { \"stockName\" : \"Microsoft\",\n \"pricePaid\" : 57.22,\n \"sharesHeld\" : 250\n }\n ]\n}\n\nIs it possible to to apply a conditional validation to this array of sub documents? It's valid for the portfolio to not be there but if it is each document in the array must contain the three fields \"stockName\", \"pricePaid\" and \"sharesHeld\".\n\nA:\n\nMongoShell\ndb.createCollection(\"collectionname\",\n{\n validator: {\n $or: [\n {\n \"portfolio\": {\n $exists: false\n }\n },\n {\n $and: [\n {\n \"portfolio\": {\n $exists: true\n }\n },\n {\n \"portfolio.stockName\": {\n $type: \"string\",\n $exists: true\n }\n },\n {\n \"portfolio.pricePaid\": {\n $type: \"double\",\n $exists: true\n }\n },\n {\n \"portfolio.sharesHeld\": {\n $type: \"double\",\n $exists: true\n }\n }\n ]\n }\n ]\n }\n})\n\nWith this above validation in place you can insert documents with or without portfolio.\nAfter executing the validator in shell, then you can insert data of following \ndb.collectionname.insert({\n \"_id\" : ObjectId(\"58061aac8812662c9ae1b479\"),\n \"date\" : ISODate(\"2016-10-18T12:50:52.372Z\"),\n \"name\" : \"B\",\n \"assets\" : 200\n})\n\ndb.collectionname.insert({\n \"_id\" : ObjectId(\"58061ab48812662c9ae1b47a\"),\n \"date\" : ISODate(\"2016-10-18T12:51:00.747Z\"),\n \"name\" : \"A\",\n \"assets\" : 100,\n \"portfolio\" : [\n {\n \"stockName\" : \"Microsoft\",\n \"pricePaid\" : 57.22,\n \"sharesHeld\" : 250\n }\n ]\n})\n\nIf we try to insert a document like this \n\ndb.collectionname.insert({\n \"date\" : new Date(),\n \"name\" : \"A\",\n \"assets\" : 100,\n \"portfolio\" : [\n { \"stockName\" : \"IBM\",\n\n \"sharesHeld\" : 100\n }\n ]\n})\n\nthen we will get the below error message\nWriteResult({\n \"nInserted\" : 0,\n \"writeError\" : {\n \"code\" : 121,\n \"errmsg\" : \"Document failed validation\"\n }\n})\n\nUsing Mongoose\nYes it can be done, Based on your scenario you may need to initialize the parent and the child schema.\nShown below would be a sample of child(portfolio) schema in mongoose.\nvar mongoose = require('mongoose');\nvar Schema = mongoose.Schema;\n\nvar portfolioSchema = new Schema({\n \"stockName\" : { type : String, required : true },\n \"pricePaid\" : { type : Number, required : true },\n \"sharesHeld\" : { type : Number, required : true },\n}\n\nReferences:\nhttp://mongoosejs.com/docs/guide.html\nhttp://mongoosejs.com/docs/subdocs.html\nCan I require an attribute to be set in a mongodb collection? (not null)\nHope it Helps!\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28969,"cells":{"text":{"kind":"string","value":"Q:\n\nIs Surdarshan Chakra mentioned In Vedic literature?\n\nThe Surdarshan Chakra is Lord vishnu's weapon mentioned in many puranas and in Itihasas. But is there any reference of Surdarshana Chakra in Vedic literature (that is Vedas,Upanishads,Brahmans).the wikipedia says in the Rigveda the Chakra was Vishnu's symbol as the wheel of time, so where exactly is Chakra of Lord Vishnu mentioned?\n\nA:\n\nYes surdarshan chakra was called Vishnu s chakra in ancient texts including RIG Veda and even in valmiki Ramayana it is called Vishnu s Chakra. \n\nHe, like a rounded wheel, hath in swift motion set his ninety racing steeds together with the four.Developed, vast in form, with those who sing forth praise, a youth, no more a child, he cometh to our call(Rig veda 1.155.6)\n\nThe word Chakra is translated as wheel,even Wikipedia says in Yajurveda vishnu s chakra is mention but till now i could not find a refernce in yajur Veda. \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28970,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat is the meaning of \"block special\"?\n\nI tried this command on my Linux Ubuntu prompt in Amazon Web Services\nsudo file /dev/xvda1\n\nand the output is\n/dev/xvda1: block special \n\nWhat is the meaning of block special in the output?\n\nA:\n\nMost of the things you find below /dev are either \"block special\" or \"character special\" things, and you rather to not change them manually. Your example shows a disk drive partition provided by Xen (what on a \"normal, nonvirtual machine\" would be /dev/sda1). \nFor more details on this special device, please see What is the “/dev/ xvda1 ” device?\nFor more details on what devices, and especially block devices are, you may consult Device file - Wikipedia, the free encyclopedia.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28971,"cells":{"text":{"kind":"string","value":"Q:\n\nIs it valid to mix assets and expenses when calculating the worth of a house?\n\nI'm trying to calculate (for myself, not relying on other people's graphs) when it becomes worth it to buy vs. rent.\nOn the positive side, there is:\n\nthe down payment,\nproperty that (roughly, over the long term, unless you live where it was horribly overpriced during the early 2000s bubble) appreciates about 4%/year, and\na declining mortgage balance.\n\nBut on the negative side are ongoing yearly expenses, some which decline over the years, and others that keep on rising:\n\nMortgage interest,\nPMI (maybe),\nProperty taxes,\nMaintenance & repair, and\nHome ownwer's insurance.\n\nIf after 30 years you wind up with a house that's worth $1M, but spent $700K in expenses, do you wind with an effective house-only Net Worth of $1M - $700K = $300K?\nIt seems like I'm mixing apples (assets and debts) and oranges (expenses).\n\nA:\n\nA house's value is whatever it is sold for when you sell it. This doesn't change based on how much you put into the house. There are a lot of examples of that, but let's say you buy a house for $100K. If you assume that the home's \"value\" increases at 4% per year (and inflation stays at 0%), your house will objectively be worth $324K at the end of 30 years.\nSo the home's value is simply what the house can be sold for when you are ready to sell. If you can't sell it (for example if a housing bubble comes up or external factors like somebody building a nuclear power plant next door), the house is worth nothing. \nThe concept you are mixing up is return on investment (ROI) and value. Your ROI is the difference between what you invested and its value at the time of the sale. Value is value regardless of how much you put in it, ROI takes into account all the expenses you \"invest\" in order to get to the value in the future.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28972,"cells":{"text":{"kind":"string","value":"Q:\n\nSQL JOINS and naming joined column\n\nI have a Products table and Downloads table.\nThe Downloads table has 4 fields, ID, Name, Category and Download\nThe Products table has 3 fields specific to Downloads: Downloads, Order Guides and Submittal Sheets. Each one of these fields stores the ID of the record from the Downloads table. There will never be the same Download ID value for these 3 fields in the Product table.\nI have the follow SQL statement:\nSELECT product_id, product_name, product_download, product_submittal, product_ordering_guide, product_status, tbl_downloads.download_id, tbl_downloads.download_name\nFROM tbl_products\nLEFT JOIN tbl_downloads ON tbl_products.product_download=tbl_downloads.download_id\nLEFT JOIN tbl_downloads ON tbl_products.product_submittal=tbl_downloads.download_id\nLEFT JOIN tbl_downloads ON tbl_products.product_order_guide=tbl_downloads.download_id\n\nIt generates the following error:\n\n#1066 - Not unique table/alias: 'tbl_downloads'\n\nThis error makes sense and I know it was going to happen, but I don't know how to fix it. I need to add an Alias, but not sure where.\nIf I remove the last two JOIN statements, everything works as expected.\nThanks\n\nA:\n\nYou need to use unique aliases if you are joining the same table multiple times:\nSELECT product_id, product_name, \n product_download, product_submittal, \n product_ordering_guide, product_status, \n d1.download_id DownloadId, \n d1.download_name DownloadName,\n d2.download_id SubmittalDownloadId, \n d2.download_name SubmittalDownloadName,\n d3.download_id GuideDownloadId, \n d3.download_name GuideDownloadName\nFROM tbl_products\nLEFT JOIN tbl_downloads d1\n ON tbl_products.product_download=d1.download_id\nLEFT JOIN tbl_downloads d2\n ON tbl_products.product_submittal=d2.download_id\nLEFT JOIN tbl_downloads d3\n ON tbl_products.product_order_guide=d3.download_id\n\nFor example I used d1, d2 and d3 but you might want to be more descriptive in your aliases so it is clear what each join is doing, like this:\nSELECT product_id, product_name, \n product_download, product_submittal, \n product_ordering_guide, product_status, \n download.download_id DownloadId, \n download.download_name DownloadName,\n submittal.download_id SubmittalDownloadId, \n submittal.download_name SubmittalDownloadName,\n guide.download_id GuideDownloadId, \n guide.download_name GuideDownloadName\nFROM tbl_products\nLEFT JOIN tbl_downloads download\n ON tbl_products.product_download=download.download_id\nLEFT JOIN tbl_downloads submittal\n ON tbl_products.product_submittal=submittal.download_id\nLEFT JOIN tbl_downloads guide\n ON tbl_products.product_order_guide=guide.download_id\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28973,"cells":{"text":{"kind":"string","value":"Q:\n\nDatagrid not showing data in wpf with c#\n\nI am trying to use a dataGrid in WPF with c#. But I cannot get my datagrid to show any of my data in the table when I run my program in debug mode. I have this code executing when the datagrid loads. But all I see is an empty square.\nprivate void dataGrid1_Loaded(object sender, RoutedEventArgs e)\n{\n var items = new List();\n\n items.Add(new SaveTable(\"A\" , 0));\n items.Add(new SaveTable(\"B\" , 0));\n items.Add(new SaveTable(\"C\" , 0));\n items.Add(new SaveTable(\"D\" , 0));\n items.Add(new SaveTable(\"E\" , 0));\n\n var grid = sender as DataGrid;\n grid.ItemsSource = items; \n}\n\nI save a class named SaveTable which looks like this:\nclass SaveTable\n{\n\n public string Name { get; set; }\n public double Value { get; set; }\n\n public SaveTable(string name, double value)\n {\n this.Name = name;\n this.Value = value;\n }\n}\n\nI got this code format online and it seems like everything is right? any suggestions?\nhere is the xaml code for that window\n\n\n \n \n \n \n \n \n \n \n \n \n \n\n\nI added a breakpoint and the code isn't being executed. I am using the Loaded event, should I be using a different event?\n\nA:\n\nYour code works fine with Loaded event but at the moment you set AutoGenerateColumns=\"False\" and don't define columns. You need to either define columns manually \n\n \n \n \n \n\n\nor let it auto generate columns\n\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28974,"cells":{"text":{"kind":"string","value":"Q:\n\nUsing array of chars as an array of long ints\n\nOn my AVR I have an array of chars that hold color intensity information in the form of {R,G,B,x,R,G,B,x,...} (x being an unused byte). Is there any simple way to write a long int (32-bits) to char myArray[4*LIGHTS] so I can write a 0x00BBGGRR number easily? \nMy typecasting is rough, and I'm not sure how to write it. I'm guessing just make a pointer to a long int type and set that equal to myArray, but then I don't know how to arbitrarily tell it to set group x to myColor.\nuint8_t myLights[4*LIGHTS];\nuint32_t *myRGBGroups = myLights; // ?\n\n*myRGBGroups = WHITE; // sets the first 4 bytes to WHITE\n // ...but how to set the 10th group?\n\nEdit: I'm not sure if typecasting is even the proper term, as I think that would be if it just truncated the 32-bit number to 8-bits?\n\nA:\n\ntypedef union {\n struct {\n uint8_t red;\n uint8_t green;\n uint8_t blue;\n uint8_t alpha;\n } rgba;\n uint32_t single;\n} Color;\n\nColor colors[LIGHTS];\n\ncolors[0].single = WHITE;\ncolors[0].rgba.red -= 5;\n\nNOTE: On a little-endian system, the low-order byte of the 4-byte value will be the alpha value; whereas it will be the red value on a big-endian system.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28975,"cells":{"text":{"kind":"string","value":"Q:\n\nhow to parse xml with multiple root element\n\nI need to parse both var & group root elements.\nCode\nimport xml.etree.ElementTree as ET\ntree_ownCloud = ET.parse('0020-syslog_rules.xml')\nroot = tree_ownCloud.getroot()\n\nError\n\nxml.etree.ElementTree.ParseError: junk after document element: line 17, column 0\n\nSample XML\ncore_dumped|failure|error|attack| bad |illegal |denied|refused|unauthorized|fatal|failed|Segmentation Fault|Corrupted\n\n\n \n ^Couldn't open /etc/securetty\n File missing. Root access unrestricted.\n pci_dss_10.2.4,gpg13_4.1,\n \n\n \n $BAD_WORDS\n alert_by_email\n Unknown problem somewhere in the system.\n gpg13_4.3,\n \n\n\nI tried following couple of other questions on stackoverflow here, but none helped.\nI know the reason, due to which it is not getting parsed, people have usually tried hacks. IMO it's a very common usecase to have multiple root elements in XML, and something must be there in ET parsing library to get this done.\n\nA:\n\nAs mentioned in the comment, an XML file cannot have multiple roots. Simple as that.\nIf you do receive/store data in this format (and then it's not proper XML). You could consider a hack of surrounding what you have with a fake tag, e.g.\nimport xml.etree.ElementTree as ET\n\nwith open(\"0020-syslog_rules.xml\", \"r\") as inputFile: \n fileContent = inputFile.read()\n root = ET.fromstring(\"\" + fileContent +\"\")\n print(root)\n\nA:\n\nActually, the example data is not a well-formed XML document, but it is a well-formed XML entity. Some XML parsers have an option to accept an entity rather than a document, and in XPath 3.1 you can parse this using the parse-xml-fragment() function.\nAnother way to parse a fragment like this is to create a wrapper document which references it as an external entity:\n\n]>\n&e;\n\nand then supply this wrapper document as the input to your XML parser.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28976,"cells":{"text":{"kind":"string","value":"Q:\n\nWrite a non-recursive algorithm to compute n factorial\n\nI am having problems writing a code in java to compute n! without recursion. I know how to do it in loops, but I am not sure how to do it non-recursively.\nprocedure factorial\n\nif n = 1 or n = 0\nreturn 1\nif n>1\nreturn(n*factorial(n-1))\nend\n\nA:\n\nHere is an iterative solution:\nint factorial(int n) {\n int f = 1;\n for(int i=1;i<=n;i++) {\n f *= i;\n }\n return f;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28977,"cells":{"text":{"kind":"string","value":"Q:\n\nInstalação do Magento dando erro de php extension\n\nEstou rodando a instalação do Magento 2.0.1 no xampp v3.2.2, e quando irá fazer o check de php extension surge o seguinte erro conforme a imagem abaixo:\n\nAlguém já passou por esse problema pode auxiliar?\n\nA:\n\nVá no php.ini no Xampp, e procure as linhas (se for Windows):\n;extension=php_xsl.dll\n;extension=php_soap.dll\n;extension=php_intl.dll\n\nSe estiver no Windows abra o php.ini pelo notepad++ ou sublimetext, no bloco de notas do Windows não vai abrir direito devido a quebra de linhas\n\nSe for Linux/Mac\n;extension=xsl.so\n;extension=soap.so\n;extension=intl.so\n\nSe for PHP7.2:\n;extension=xsl\n;extension=soap\n;extension=intl\n\nEntão tire o ; da frente e salve o php.ini, deve ficar assim (windows):\nextension=php_xsl.dll\nextension=php_soap.dll\nextension=php_intl.dll\n\nSe for Linux/Mac\nextension=xsl.so\nextension=soap.so\nextension=intl.so\n\nSe for PHP7.2:\nextension=xsl\nextension=soap\nextension=intl\n\nEntão reiniciei o Apache pelo painel do Xampp\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28978,"cells":{"text":{"kind":"string","value":"Q:\n\nPython: how to split and return a list from a function to avoid memory error\n\nI am currently working with a function that enumerates all cycles within a specific array (a digraph) and I need them all. This function returns all cycles as a list of lists (each sublist being a cycle, e.g. result=[[0,1,0],[0,1,2,0]] is a list containing 2 cycles starting and ending in node 0). However, there are millions of cycles so for big digraphs I get a memory error (MemoryError: MemoryError()) since the list of lists containing all cycles is too big. \nI would like that the function splits the result in several arrays so I do not get the memory error. Is that possible? and would that solve the issue?\nI tried to do that by splitting the results array as a list of sub-results (the sub-results have a maximum size, say 10 million which is below the 500 million max size stated here: How Big can a Python Array Get? ). The idea is that the result is a list containing sub-results: result=[sub-result1, sub-result2]. However, I get a different memory error: no mem for new parser.\nThe way I do that is as follows:\nif SplitResult == False:\n result = [] # list to accumulate the circuits found\n # append cycles to the result list\n if cycle_found(): #cycle_found() just for example\n result.append(new_cycle)\nelif SplitResult == True:\n result = [[]] # list of lists to accumulate the circuits found\n # append cycles to the LAST result SUB-lists\n if cycle_found(): #cycle_found() just for example\n result[len(result)-1].append(new_cycle)\n # create a new sublist when the size of the LAST result SUB-lists\n # reaches the size limit (ResultSize) \n if len(result[len(result)-1]) == ResultSize:\n result.append([])\n\nMaybe the issue is that I merge all sub-results within the results list. In that case, how can I return a variable number of results from a function?\nIn particular I divide all simple cycles of a 12 node complete digraph in sublists of 10 million cycles. I know there are 115,443,382 cycles in total, so I should get a list with 16 sublists, the first 15 containing 10 million cycles each and the last one containing 443,382 cycles. Instead of that I get a different memory error: no mem for new parser.\nThis procedure works for an 11 node complete digraph which returns 2 sublists, the first containing the 10 million cycles (10000000) and the other containing 976184. In case it is of any help, their memory footprint is \n>>> sys.getsizeof(cycles_list[0])\n40764028\n>>> sys.getsizeof(cycles_list[1])\n4348732\n\nThen, I guess we should add the size of each cycle listed:\n>>> sys.getsizeof(cycles_list[0][4])\n56\n>>> cycles_list[0][4]\n[0, 1, 2, 3, 4, 0]\n\nAny help will be most welcome,\nThanks for reading,\nAleix\n\nA:\n\nThank you for your suggestions. Indeed the right approach to avoid memory issues when returning arrays is simply by avoiding creating so big result arrays. Thus, generator functions are the way forward.\nGenerator functions are well explained here: What does the \"yield\" keyword do in Python?\nI would just add that a normal function becomes a generator function at the very moment where you add a yield in it. Also, if you add a return statement the generation of iterables will end when reaching it (some generator functions do not have \"return\" and are thus infinite).\nDespite the simple use of generators I had some hard time transforming the original function into a generator function since it was a recursive function (i.e. calling itself). However, this entry shows how a recursive generator function looks like Help understanding how this recursive python function works? and so I could apply it to my function.\nAgain, thanks to all for your support,\nAleix\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28979,"cells":{"text":{"kind":"string","value":"Q:\n\nRounding off percentages in plotly pie charts\n\nlabel=c(\"<25%\",\"25 - 50%\",\">75%\")\nvalues=c(4,2,3)\ndf=data.frame(label,values)\nplot_ly(df, labels = ~label, values = ~values,text=values,textposition=\"auto\", type = 'pie') %>%layout(title = 'Percentage Effort time',showlegend=T,\n xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),\n yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))\n\nWhen I run this code, I get a pie chart with percentages and the numbers. How can I obtain percentages that are rounded off to whole numbers instead of decimal points?\n\nA:\n\nYou can use textinfo='text' to hide the percent values and provide a custom formatted label with text:\n text = ~paste(round((values / sum(values))*100, 0)),\n textinfo='text',\n\nComplete example:\nlibrary(magrittr)\nlibrary(plotly)\n\nlabel=c(\"<25%\",\"25 - 50%\",\">75%\")\nvalues=c(4,2,3)\ndf=data.frame(label,values)\nplot_ly(df, \n labels = ~label, \n values = ~values,\n text = ~paste(round((values / sum(values))*100, 0)),\n #textinfo='none',\n #textinfo='label+value+percent',\n textinfo='text',\n textposition=\"auto\", type = 'pie') %>% layout(title = 'Percentage Effort time', showlegend=T,\n xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),\n yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)\n )\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28980,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to make a click event occur in BackboneJs\n\nI'm just staring to learn backboneJs and im stuck with one issue here. I'm trying to POST a record to a list where im unable to perform a click event on the button that will post the record. Below is the view im using:\nBackboneView:\nvar NewSubAccount = Backbone.View.extend({\n initialize: function(){\n\n },\n el: '#sub-account-list'\n events:{\n 'click #save' : 'saveList'\n },\n\n render: function(id){ \n\n debugger;\n value = new SubAccountModel();\n var template = $(\"#sub-account-list\").html(_.template(createtmpl, {data:value.attributes}));\n\n },\n saveList: function(){\n debugger;\n\n value = new SubAccountModel();\n var values = $('form#create-sub-account').serializeArray();\n\n value.save(values, {\n success: function(value){\n\n alert('hello');\n\n }\n });\n }\n\n });\n\nHTML:\n
\n\n Sub Account Creation\n\n \n
\n\n \n
\n\n \n \n\n
\n\nEDIT:\nhere is the router im using to render the 'newSubAccount':\nroutes: { \n 'new': 'newSubAccount', \n },\nevents:{\n 'click .create-sub-account' : 'savesubAccount'\n },\nnewSubAccount: function(){\n\n var newsubaccount = new NewSubAccount(); \n newsubaccount.render();\n },\n\nWhen i perform the click event, it dorectly takes me back to the main page, without even going into the debug mode ( i set a debugger at the value = new SubAccountModel();, and it didnt go through. I'm wondering if my way of writing the click event is worng or im i missing something. Please anyone any ideas, appreciated.\nThanks.Let me know if it needs more details.\n\nA:\n\nThe problem you have is clicking on the #save button is submitting the form, this is what is reloading the page. There are a couple of options you can do:\n1) Make the save button a plain button rather than a submit button, so that it doesn't try to submit the form:\n \n\n2) If your intention is to use the save to submit the form, then you\n should capture the submit of the form rather than the click of the\n button and prevent the form from submitting the to the server,\n consider the following:\nvar NewSubAccount = Backbone.View.extend({\n el: '#sub-account-list'\n events:{\n 'submit form#create-sub-account' : 'saveList' //Listen for the submit event on the form.\n },\n render: function(id){\n value = new SubAccountModel();\n var template = $(\"#sub-account-list\").html(_.template(createtmpl, {data:value.attributes}));\n },\n saveList: function(event){\n event.preventDefault(); // Prevent the form from submitting, as you are handling it manually\n\n value = new SubAccountModel();\n var values = $('form#create-sub-account').serializeArray();\n\n value.save(values, {\n success: function(value){\n alert('hello');\n }\n });\n }\n});\n\nThe other advantage you get from listening to the form in this way, is that other methods of submitting the form (such as pressing enter) will also be collected and handled correctly as well.\nAs a side note:\nYou shouldn't have events in your router. Instead you should make views that handle all the user interaction. \nRouter - Deals with the interaction between the browser state (URL) and what the user sees (UI). Its main focus should be converting the URL into Views on the page (the UI).\nView - Deals with the interaction between the user and the data. Its main focus is to display any data in the UI and allow the user to interact with it. For example, submitting a form.\nModel - Deals with the interaction between the browser and the server (AJAX requests). Its main focus should be to handle the data that is saved/fetched from the server. The View should use models to encapsulate data and display it in the UI.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28981,"cells":{"text":{"kind":"string","value":"Q:\n\nWhy is my print getting messed up mid-print?\n\nI am using Slic3r to generate the GCode for my Marlin-based printer. For some reason with increasing height my print starts to get messed up. On another part it starts to act like this when there are small parts. Is this related to my Slic3r settings, maybe to much filament being extruded or is this due to something else?\nAny help is highly appreciated and I can provide more pictures of messed up parts or slic3r config if necessary.\n\nA:\n\nTo me, this looks like a combination of bad filament, high temperature and/or fast speeds.\n\nToo high extrusion temperature will make difficult to let each layer cool enough before the next layer begins. This is why you see the poor results on the smaller areas of the print in your second photo.\nIf you're using bad filament (out of round, non-virgin, or poorly stored filament) you might see a series of over/under extrusion areas or smoke from moisture in the filament.\nSlowing down your feed rates can be tricky if your extrusion temps are too high. By slowing down, you're allowing layers to cool down a little bit more and solidify. If your previous layers are still relatively molten, you'll notice that the new layer of filament will adhere to it and potentially drag the previous layers as the nozzle continues to move. You'll see the results of this in the top-arc layers with an uneven curvature.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28982,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to delete Javascript object property?\n\nI am trying to delete a object property which is shallow copy of another object.\nBut the problem arises when I try to delete it, it never goes off while original value throws expected output.\n\nvar obj = {\r\n name:\"Tom\"\r\n};\r\n\r\nvar newObj = Object.create(obj);\r\ndelete newObj.name;//It never works!\r\n\r\nconsole.log(newObj.name);//name is still there\n\nA:\n\nnewObj inherits from obj.\nYou can delete the property by accessing the parent object:\ndelete Object.getPrototypeOf(newObj).name;\n\n(which changes the parent object)\nYou can also shadow it, by setting the value to undefined (for example):\nnewObj.name = undefined;\n\nBut you can't remove the property on newObj without deleting it from the parent object as the prototype is looked up the prototype chain until it is found. \n\nA:\n\nBasically Object.create will create an object , set its prototype as per the passed object and it will return it. So if you want to delete any property from the returned object of Object.create, you have to access its prototype.\nvar obj = { name:\"Tom\" };\nvar newObj = Object.create(obj);\ndelete Object.getPrototypeOf(newObj).name\nconsole.log(newObj.name); //undefined.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28983,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to deal with 1 to many SQL (Table inputs) in Pentaho Kettle\n\nI have a situation where in i have the following tables.\nEmployee - emp_id, emp_name, emp_address\nEmployee_assets - emp_id(FK), asset_id, asset_name (1-many for employee)\nEmployee_family_members - emp_id(FK), fm_name, fm_relationship (1-many for employee)\nNow, I have to run a scheduled kettle job which reads in the data from these tables in say batches of 1000 employees and create a XML output for those 1000 records based on the relationship in DB with family members and assets. It will be a nested XML record for every employee. \nPlease note that the performance of this kettle job is very crucial in my scenario.\n\nI have two questions here -\n\nWhat is the best way to pull in records from the database for a 1-many relationship in schema?\nWhat is the best way to generate the XML output structure given that XML join steps are a performance hit?\n\nA:\n\nHere is how I have achieved this.\n\nSo, there is one Table Input step to read the base table and subsequently create the XML chunk for it. Subsequently, in the flow, I am using the 1-many relationship (child table) as another Database join step passing the relationship key to it. Once the data is pulled out, the XMLs are generated for the child rows. This is then passed on to the Modified Java Script Value step(merge rows) which then merges the content using trans_Status = SKIP_TRANSFORMATION for similar rows. Once similar rows are merged/concatenated, the putRow(row) is used to dump it out as an output to the next step. \nPlease note, that this required the SQL to have order by/sorted based on the relationship keys. This is performing alright, so I can proceed with it.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28984,"cells":{"text":{"kind":"string","value":"Q:\n\nIs there simple “angularJS” way using ng-repeat directive, to replace characters in object.name string with other character directly?\n\nIf the object's property name is Bob_Kenneth_Frank (as actual value) to Bob Kenneth Frank (displayed output)\nI unsuccessfully tried different variants of:\nhtml\nng-repeat=\"myChange(person.name) in persons\"\n\nin controller\nfunction myChange(name){\n return name.replace(/_/g, \" \")\n}\n\nA:\n\nUse a custom filter.\nSee a working demo.\nangular.module('app').filter('replaceUnderscoreBySpace', function () {\n return function (input) {\n return input.replace(/_/g, ' ');\n };\n});\n\nView:\n
\n {{x | replaceUnderscoreBySpace}}\n
\n\nExplanations on Todd Motto Blog\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28985,"cells":{"text":{"kind":"string","value":"Q:\n\nConcerned, freelancer I don't know may run off. How should I pay a freelancer?\n\nI've found an illustrator, who's work I really like. I saw his work online so have never met the person in 'real life'. He's named his price which is quite a lot of money. Therefore, I have concerns about paying someone who I don't really know. The last thing I'd want is for them to take off with my money without doing the work.\nI've proposed half now and half on completion, although half is still quite a lot of money. If possible, I don't want to go through one of those freelancing sites, like Elance, as I can imagine they'd probably take quite a large cut.\nHow can I tackle payment safely so that I know the freelancer won't run off?\n\nA:\n\nFor fixed price projects, depending on the size of the contract I always did 50% up front and 50% upon delivery. For larger contracts (+1500 euros) I took 30% up front. The freelancer thinks the same way: \"I'm not going to do work if there is a chance the client just runs off with my work and doesn't pay me!\".\nThere is always a risk, but if the freelancer has decent references there is no reason he would want to run off: if he just does his job he gets another 50% or 70%. \nI never worked with escrow services, it just costs extra and I never heard of a freelancer taking half and just running off. Which of course doesn't offer any certainty, and I should mention I never worked with freelancers or clients that where more than a few hundred kilometers from me. \n\nA:\n\nThis service seems like it offers the protection you require and gives a third party the funds until the freelancer has completed and delivered the product\nhttps://www.escrow.com/\n\nEscrow.com reduces the risk of fraud by acting as a trusted third-party that collects, holds and only disperses funds when both Buyers and Sellers are satisfied.\n\nA:\n\nSo you want a feast without spending an ounce of flour? If you find a solution I would like to hear it as well :). \nWorking with a remote freelancer is always risky. That's why you always start with small and in time increase amount of work. Why don't you give him to do only a part of a job?! Paying 50% of the small part is worth of risk. If you however started with a large project, then you're probably not so good with money planning and you will eventually be hurt. You have to build trust with the remote freelancer first. \nNext, web services like odesk or elance offer clients a great comfort since you can review freelancer's portfolio and your money is pretty safe in fixed-price projects. And they charge you for that safety. \nLastly, services like Skrill offer money escrow so you may take a look at that as well. \nPS. I am writing this thinking that you two cannot sign a liable contract e.g. you cannot sue him efficiently. If you can sign a good contract where he can financially be responsible for bad work, then sign it. \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28986,"cells":{"text":{"kind":"string","value":"Q:\n\nTerm symbols for nitrogen: determining J\n\nI'm trying to figure out what terms are possible for nitrogen with the electron configuration $\\ce{[He] 2s^2 2p^3}$. There is an old question on StackExchange and the corresponding answer was a great help already but doesn't mention $J$ or specify what terms exactly are possible. I'll try to explain how I would determine the possible terms:\nThe s-electrons needn't be considered for they complete the s subshell, this means I'm left with three p-electrons. I do get the same results for the possible values of $L$ and $S$ as user orthocresol provided with his answer namely:\n$L=3,2,1,0$\n$S=3/2, 1/2$\nNow the possible values of J range from $L+S$ to $|L-S|$:\nFor $L=0$ there are two S-Terms*: $^4\\!S$ and $^2\\!S$ giving \n$$^4\\!S_{3/2} \\quad ^2\\!S_{1/2}$$\n$L=1$ gives two terms*: $^4\\!P$ and $^2\\!P$, the former term has the following possible J values: $J = 5/2, 3/2, 1/2$ and the latter: $J=3/2, 1/2$. The P-Terms of this electron configuration are:\n$$^4\\!P_{5/2} \\quad ^4\\!P_{3/2} \\quad ^4\\!P_{1/2} \\quad ^2\\!P_{3/2}\\quad ^2\\!P_{1/2}$$\nDoing the same for $L=2$ there are two D-Terms*: $^4\\!D$ and $^2\\!D$, possible J values for the former: $J = 7/2, 5/2, 3/2, 1/2$ and for the latter: $J = 5/2, 3/2$. This gives six different terms.\nI'm stopping at this point because I think I'm not doing it right. Using the NIST ASD I only see five terms with this electron configuration in the Grotrian diagram:\n$$^4\\!S_{3/2}, ^2\\!D_{5/2}, ^2\\!D_{3/2}, ^2\\!P_{1/2}, ^2\\!P_{3/2}$$ \nand according to the book \"Physical Chemistry: A Molecular Approach\" Table 8.4 for three p-electrons only $^2\\!P,^2\\!D,^4\\!S$ Terms are possible. What's wrong with my approach that I'm that much off? \n*Question on the side: I don't think it's correct to use the term \"term\" here because what I'm talking about is split into actual terms. Is there a way to refer to, for example, the $^4\\!D$-Terms in general, maybe term system?\n\nA:\n\nFirstly, regarding the extra question: Atkins' Molecular Quantum Mechanics (5th ed.) uses \"term\" for $^2\\!S$, and \"level\" for $^2\\!S_{1/2}$.\nBack to the main question. It's been a long time since I did term symbols, so I am happy to be corrected, but if I am not wrong, your $^4\\!P$, $^4\\!D$, and $^2\\!S$ terms are not allowed because of the Pauli exclusion principle. The argument is pretty similar to the one in the comments on my answer, which you're already aware of.\nA term with $S = 3/2$ must have a set of states with $M_S = +3/2, +1/2, -1/2, -3/2$. Likewise, a $P$ term with $L = 1$ must also have a set of states with $M_L = +1, 0, -1$. Consequently, the total number of states associated with a single term $^{2S+1}\\!L$ is $(2S+1)(2L+1)$. (The total number of states in a level, $^{2S+1}\\!L_J$, is $2J+1$, and you can also show that the sum of this over the allowed values of $J$ is equal to $(2S+1)(2L+1)$.)\nOne of those twelve states in the purported $^4\\!P$ term must have $(M_S, M_L) = (+3/2, +1)$. However, $M_S = +3/2$ can only be achieved if all three electrons have the same spin (spin up in this case), which in turn necessitates that the three electrons are all in different p-orbitals, such that $M_L = \\sum m_l = +1 + 0 + -1 = 0$.\nErgo, a state with $(M_S, M_L) = (+3/2, +1)$ cannot exist, and the entire term $^4\\!P$ cannot be possible. The same argument also applies to the $^4\\!D$ term.\nI suspect that showing that the $^2\\!S$ term is forbidden is somewhat trickier. I had a similar issue before with carbon, which is an easier system to understand (only two electrons to consider instead of three), so maybe you will find this useful: Pauli-forbidden term symbols for atomic carbon.\nOut of the three surviving terms ($^2\\!P$, $^2\\!D$, $^4\\!S$) you already see from NIST that all the possible $J$ values (from $|L-S|$ to $L+S$) are allowed, so there is no issue with your calculation of $J$.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28987,"cells":{"text":{"kind":"string","value":"Q:\n\njQuery body click problem\n\nI have a div I want to hide when clicking outside it. \nIt almost works, except the button class is only changing once every two times. \nI click on the button, the active button class is added and the dropdown slides down, I click somewhere outside the dropdown, it slides up and the button class returns to it's original state. BUT, when I repeat this, the button class 'isActive' is not added.\nHere's the function:\nfunction toggleSelectGroupList(){\n $('#groupListSortby').slideToggle(30);\n\n $('body').click(function(){ \n $('#groupListSortby').click(function(e) { e.stopPropagation(); })\n $('#groupListSortby').hide(); \n $('.sortFriends .btngrey .gfx').toggleClass('isActive');\n $('.sortFriends .btngrey a').toggleClass('isActive');\n }); \n}\n\nMarkup:\n
\n\n
\n \n All friends\n
\n\n
\n \n
\n\n
\n\nA:\n\nYou should bind your click handlers from the beginning, and the propagation stop should be immediately bound as well, like this overall:\n$(function() {\n $(\".sortFriends .btngrey a\").click(function(e) {\n $('#groupListSortby').slideToggle(30);\n $('.sortFriends .btngrey .gfx, .sortFriends .btngrey a').toggleClass('isActive');\n e.stopPropagation();\n });\n $('#groupListSortby').click(function(e) {\n e.stopPropagation(); \n });\n $('body').click(function(){ \n $('#groupListSortby').hide(); \n $('.sortFriends .btngrey .gfx, .sortFriends .btngrey a').removeClass('isActive');\n }); \n});\n\nTo match, your shouldn't have an onclick inline with this anymore, just this will do:\n\n\nYou can test it out here.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28988,"cells":{"text":{"kind":"string","value":"Q:\n\nAnalytical approximation of indefinite integral on a given interval to a given precision\n\nI'm looking for an analytical approximation of \n$\\int_a^b e^{-x^2}\\mathrm{erf}(x+c) dx$\nthat would be accurate to precision $\\varepsilon$ for $a,b,c$ within a certain range. How do I ask Mathematica for that?\nI tried to Integrate the above expression, but no analytical solutions were found.\n\nA:\n\nOne can construct a Chebyshev series approximation to the integrand for an interval, such as -5 <= x <=5 mentioned in the comments, and integrate it to get a series expansion for the integral. It is well known that Chebyshev series representation have numerical advantages over power series. I saw a comment about a NPU-supported method, but I don't know what that is, this being a Mathematica site. Most numerical systems have access to an FFT, in one way or another, I think, and, of course, to trigonometric functions. That is all that is really needed.\nSome auxiliary functions used here (code below):\n\nchebSeries[f, {a, b}, n, precision] computes the Chebyshev expansion of order n for f[x] over a <= x <= b.\niCheb[c, {a, b}, k] integrates the Chebyshev series c, plus k. \nf = chebFunc[c,{a,b}], computes the function represented by the Chebyshev coefficients c = {c0, c1,...} over the interval {a, b}.\n\nThe first step is to compute the coefficients of the integrand as a function of x for a given value of c. The are saved (memoized) for the sake of speed, but it is not essential. An antiderivative of the integrand is computed with iCheb[coeff[c], {-5, 5}]. Depending on c, one needs a series of order 70 to 90+ to get a theoretical error of less than machine precision, so computing one of order 2^7 = 128 is sufficient for all c. (See Boyd, Chebyshev and Fourier\nSpectral Methods, Dover, New York,\n2001, ch. 2., for a discussion of the convergence theory of Chebyshev series.)\nClearAll[coeffs];\ncoeffs[c_?NumericQ] := coeffs[c] =\n Module[{\n cc, (* Chebyshev coefficients *)\n pg = 16, (* Precision goal: *)\n sum, (* sum of tail = error bound *)\n max, (* max coefficient to measure rel. error *)\n len}, (* how many terms of the tail to drop *)\n cc = chebSeries[Function[x, Exp[-x^2] Erf[x + c]], {-5, 5}, 128];\n max = Max@Abs@cc;\n sum = 0;\n (* trim tail of series of unneeded coefficients (smaller than desired precision) *)\n len = LengthWhile[Reverse[cc], (sum += Abs[#1]) < 10^-pg max &];\n Drop[cc, -len]\n ];\n\nNext we can define the user's sought-after function in terms of the antiderivative:\nfunc[a_, b_, c_] := \n With[{antiderivative = chebFunc[\n N@iCheb[coeffs[SetPrecision[c, Infinity]], {-5, 5}, 0],\n {-5, 5}]},\n antiderivative[b] - antiderivative[a]\n ];\n\nThe following computes the relative and absolute error of func on a hundred random inputs, using a high-precision NIntegrate[] to compute the \"true\" value.\ncmp[a_, b_, c_] := {(#1 - #2)/#2, #1 - #2} &[\n func[a, b, c],\n NIntegrate[Exp[-x^2] Erf[x + SetPrecision[c, Infinity]], {x, a, b}, \n WorkingPrecision -> 40]\n ]\n\nListLinePlot[\n Transpose@RealExponent[cmp @@@ RandomReal[{-5, 5}, {100, 3}]], \n PlotRange -> {-20, 0}, PlotLabel -> \"Error\", \n PlotLegends -> {\"Rel.\", \"Abs.\"}]\n\nThe yellow line shows the absolute error is limited to a few ulps. The theoretical bound on the error does not take into account rounding error (in both the coefficients and the evaluation of the series). The lines that drop off the bottom are the result of an error of zero.\nAuxiliary functions\n(* Chebyshev extreme points *)\nchebExtrema::usage = \n \"chebExtrema[n,precision] returns the Chebyshev extreme points of order n\";\nchebExtrema[n_, prec_: MachinePrecision] := \n N[Cos[Range[0, n]/n Pi], prec];\n\n(* Chebyshev series approximation to f *)\nClear[chebSeries];\nchebSeries::usage = \n \"chebSeries[f,{a,b},n,precision] computes the Chebyshev expansion \\\nof order n for f[x] over a <= x <= b.\";\nchebSeries[f_, {a_, b_}, n_, prec_: MachinePrecision] := \n Module[{x, y, cc},\n x = Rescale[chebExtrema[n, prec], {-1, 1}, {a, b}];\n y = f /@ x; (* function values at Chebyshev points *)\n cc = Sqrt[2/n] FourierDCT[y, 1]; (* get coeffs from values *)\n cc[[{1, -1}]] /= 2; (* adjust first & last coeffs *)\n cc\n ];\n\n(* Integrate a Chebyshev series -- cf. Clenshaw-Norton, Comp.J., 1963, p89, eq. (12) *)\nClear[iCheb];\niCheb::usage = \"iCheb[c, {a, b}, k] integrates the Chebyshev series c, plus k\";\niCheb[c0_, {a_, b_}, k_: 0] := Module[{c, i, i0}, \n c[1] = 2 First[c0];\n c[n_] /; 1 < n <= Length[c0] := c0[[n]];\n c[_] := 0;\n i = 1/2 (b - a) Table[(c[n - 1] - c[n + 1])/(2 (n - 1)), {n, 2, Length[c0] + 1}];\n i0 = i[[2 ;; All ;; 2]];\n Prepend[i, k - Sum[(-1)^n*i0[[n]], {n, Length[i0]}]]]\n\n(* chebFunc[c,...] computes the function represented by a Chebyshev series *)\nchebFunc::usage = \n \"f = chebFunc[c,{a,b}], c = {c0,c1,...} Chebyshev coefficients, over the interval {a,b}\n y = chebFunc[c,{a,b}][x] evaluates the function\";\nchebFunc[c_, dom_][x_] := chebFunc[c, dom, x];\nchebFunc[c_?VectorQ, {a_, b_}, x_] := \n Cos[Range[0, Length[c] - 1] ArcCos[(2 x - (a + b))/(b - a)]].c;\n\nUpdate: Comparison of Chebyshev and power series\nPerhaps it would be worth illustrating the difference between power series and Chebyshev series approximations for those who are not familiar with it. (One should become familiar with it, for Chebyshev expansions are to functions what decimal expansions are to numbers.)\nKey differences:\n\nSymbolic series expansion of the function Erf[x + c] grows extremely fast and takes a much longer time to evaluate than the DCT-I used to compute the Chebyshev coefficients. Attempting a degree 40 expansion hanged the computer and I had to kill the kernel.\nAside from not being able to compute the series expansion to arbitrary order, it is probably impossible to get convergence for a fixed precision due to rounding error. At machine precision, you cannot even get 2 digits throughout the interval {c, -5, 5}, for a = -4, b = 4 up to order 25. OTOH, the Chebyshev series has an exponential order of convergence and can nearly achieve machine precision with machine precision coefficients.\nIt is fairly easy to figure out when you have enough terms of a Chebyshev series $\\sum a_j T_j$, because the error is bounded by the tail $\\sum |a_j|$ and the $a_n \\rightarrow 0$ roughly geometrically on average.\nIf you don't have fast trigonometric functions, then instead of the code in chebFunc above, you can use Clenshaw's algorithm (see chebeval) to evaluate the series.\n\nHere's another implementation of Mariusz's power series idea. I speed up the integration with a \"power rule\" int[{n}] for\n$$ \\int \\exp\\left(-x^2\\right) x^n \\; dx\\,.$$\nOf course it turned out that Series was the bigger bottleneck.\nClearAll[sol, int];\nint[{0}] = Integrate[Exp[-x^2], x, Assumptions -> x ∈ Reals];\nint[{n_}] = Integrate[Exp[-t^2] t^n, {t, 0, x}, \n Assumptions -> n > 0 && n ∈ Integers && t ∈ Reals];\n$seriesCoefficientPart = 3;\nsol[n_] := sol[n] = Total@MapIndexed[\n First@Differences[#1 int[#2 - 1] /. {{x -> a}, {x -> b}}] &,\n Series[Erf[x + c], {x, 0, n}][[$seriesCoefficientPart]]\n ];\n\n(* Times *)\nFirst@*AbsoluteTiming@*sol /@ {2, 10, 20, 22, 23, 24, 25}\n(* {0.013267, 0.071065, 2.01908, 7.6296, 23.4752, 33.1553, 48.3542} *)\n\n(* Sizes *)\nLeafCount /@ sol /@ {2, 10, 20, 22, 23, 24, 25}\n(* {163, 693, 2413, 2765, 1100459, 1779935, 2879267} *)\n\nChebyshev speed for c = 4, per evaluation of c:\nFirst@AbsoluteTiming@func[a, b, 4, #] & /@ {2, 10, 20, 25}\n(* {0.002047, 0.000184, 0.000248, 0.000276} *)\n\nTo illustrate the issue with power series, the graphics below shows the error in approximating Erf[x + c] by its Taylor series (times Exp[-x^2] for c = -4, -2, 0, 2, 4 and various orders. It does pretty good for Abs[x] < 1 as the order increases, but it gets worse for Abs[x] > 4.\nGraphicsRow[\n Table[\n Plot[\n Evaluate@Table[\n Exp[-x^2] (Erf[x + c] - Normal@Series[Erf[x + c], {x, 0, n}]) // \n RealExponent,\n {c, -4, 4, 2}],\n {x, -5, 5},\n PlotRange -> {-18, 0}, Frame -> True, Axes -> False, \n PlotLabel -> Row[{\"Order \", n}], AspectRatio -> 1, \n FrameLabel -> {\"x\", \"Log error\"}], {n, {2, 10, 20, 25}}],\n PlotLabel -> \"Error in approximating integrand by power series\"]\n\nThe two plots below compare the absolute error of approximating by power series and by Chebyshev series. The convergence of the Chebyshev series is remarkable by comparison.\nPlot[Evaluate@Table[\n sol[n] - exact[a, b, c] /. {a -> -4, b -> 4} // RealExponent,\n {n, {2, 10, 20, 25}}],\n {c, -5, 5},\n PlotRange -> {-18, 0}, Frame -> True, Axes -> False, \n GridLines -> {None, -Range[2, 16, 2]}, \n PlotLabel -> \"Log error for power series of order n\", \n FrameLabel -> {\"c\", \"Log error\"},\n PlotLegends -> {2, 10, 20, 25}]\n\nPlot[Evaluate@Table[\n func[a, b, c, n] - exact[a, b, c] /. {a -> -4, b -> 4} // RealExponent,\n {n, {2, 10, 20, 30, 40, 50, 60}}],\n {c, -5, 5},\n PlotRange -> {-18, 0}, Frame -> True, Axes -> False, \n GridLines -> {None, -Range[2, 16, 2]}, \n PlotLabel -> \"Log error for Chebyshev series of order n\", \n FrameLabel -> {\"c\", \"Log error\"},\n PlotLegends -> {2, 10, 20, 30, 40, 50, 60}]\n\nDetermining the order of the approximation:\ntrim[cc_, eps_] := Module[{sum, max, len},\n max = Max@Abs@cc;\n sum = 0;\n len = LengthWhile[Reverse[cc], (sum += Abs[#1]) < eps max &];\n Drop[cc, -len]\n ]\n\nManipulate[\n With[{cc = iCheb[chebSeries[Exp[-#^2] Erf[# + c] &, -5, 5, 128, 32], {-5, 5}]},\n With[{order = Length@trim[cc, 10^-accuracy]},\n ListPlot[\n RealExponent@cc,\n PlotLabel -> Column[{\n Row[{\"Chebyshev coefficients a[n] for \", \n HoldForm[\"c\"] -> Chop[N[c, {2, 1.5}], 0.05], \", \"}],\n Row[{\"For accuracy \", SetPrecision[10^-accuracy, 2], \" use order \", order}]\n }, Alignment -> Center],\n Frame -> True, FrameLabel -> {\"n\", \"exponent of a[n]\"},\n GridLines -> {{order}, {-accuracy}}, PlotRange -> {-31, 1}]\n ]],\n {{c, 4}, -5, 5, 1/10}, {{accuracy, 16.}, 2, 28}]\n\nAddendum: Failed ideas - Maybe someone can make them work...\nThe Chebyshev series of Exp[-x^2] can be computed over {-x0, x0} exactly in terms of modified Bessel functions BesselI[]. Therefore, so can the series for Erf[x]. I was seduced into trying to come up with a way to compute the OP's function in this way but the +c in Erf[x + c] was too ornery. \nOne thing that would be needed is a way to write ChebyshevT[n, x + c] as a Chebyshev series in ChebyshevT[n, x]. The coefficients would be polynomials in c (with integer coefficients), which themselves could be represented as Chebyshev expansions. This can be done, in fact, but it's a bit cumbersome and slow. Further the Chebyshev coefficients for n = 64 get bigger than 2^100, and I worried about numerical stability. For the moment, I have given up without testing it. The way above seems superior, in simplicity, as well as (probably) in speed and numerics.\n\nA:\n\nMaybe so:\nExpand with Series a function Erf[x+c] e.g for order 2.\nn = 2;\nfunc = Normal@Series[Erf[x + c], {x, 0, n}]\n\n$-\\frac{2 c e^{-c^2} x^2}{\\sqrt{\\pi }}+\\frac{2 e^{-c^2} x}{\\sqrt{\\pi }}+\\text{erf}(c)$\n\nsol = Simplify@Integrate[Exp[-x^2]*func, {x, a, b}]\n\n$\\frac{-c e^{-c^2} \\left(2 e^{-a^2} a-\\sqrt{\\pi } \\text{erf}(a)-2 b e^{-b^2}+\\sqrt{\\pi }\n \\text{erf}(b)\\right)+2 e^{-c^2} \\left(e^{-a^2}-e^{-b^2}\\right)+\\pi \\text{erf}(c)\n (\\text{erf}(b)-\\text{erf}(a))}{2 \\sqrt{\\pi }}$\n\nCheck numerics:\n a = -4;\n b = 4;\n c = 4;\n sol2 = NIntegrate[Exp[-x^2]*Erf[x + c], {x, a, b}]\n (*1.77234*)\n\n sol // N\n (*1.77245*)\n\nFrom Documentation Center Precision[x] is- Log[10, dx/x].\n -Log[10, Abs[(sol - sol2)/sol2]]\n (*4.20019*)\n\nI have 4 significant digit.\n\nFrom OP qestion:\n\nCan Mathematica predict for the given function and interval how many terms it needs in the Series for the accuracy ϵ on that interval?\n\nYes I use NonlinearModelFit.Generate data for order n from 1 to 20;\n data = Table[{n,\n func = Normal@Series[Erf[x + c], {x, 0, n}]; \n sol = Simplify@Integrate[Exp[-x^2]*func, {x, a, b}]; \n a = -4;(*Interval (a,b)*)\n b = 4;\n c = 4;\n sol2 = NIntegrate[Exp[-x^2]*Erf[x + c], {x, a, b}];\n sol1 = (sol /. c -> 4 /. a -> -4 /. b -> 4) // N;\n-Log[10, Abs[(sol1 - sol2)/sol2]]}, {n, 1, 20}]\n\n (*{{1, 4.19844}, {2, 4.20019}, {3, 4.20019}, {4, 4.21306}, {5, \n 4.21306}, {6, 4.27069}, {7, 4.27069}, {8, 4.46324}, {9, \n 4.46324}, {10, 5.23787}, {11, 5.23787}, {12, 4.86359}, {13, \n 4.86359}, {14, 5.124}, {15, 5.124}, {16, 5.10868}, {17, \n 5.10868}, {18, 5.37338}, {19, 5.37338}, {20, 5.20063}}*)\n\n nlm = NonlinearModelFit[data, a1 + a2*Exp[a3*n + a4], {a1, a2, a3, a4}, n]\n Normal@nlm\n\nModel:\n\n$1.15801 e^{0.00463001 n+2.53736}-10.621$\n\n Show[Plot[Normal@nlm, {n, 0, 20}], ListPlot[data], \n AxesOrigin -> {0, 0}, PlotRange -> {Automatic, {0, 5.5}}, \n AxesLabel -> {n, \"significant digits\"}]\n\nfor n=20 I have:\n nlm[20]\n (*5.44438*)\n\n5 significant digit.\nfor n=200 I have:\n nlm[200]\n (*26.3475*)\n\n26 significant digit.\nYou may change a model in NonlinearModelFit.Maybe my model is not the best.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28989,"cells":{"text":{"kind":"string","value":"Q:\n\nHow can i create multiple markers on a google map?\n\nI need to show multiple pointers based on the given latitude and longitude values.I did one sample but it comes only one pointers.As shown code below.\nMeteor Js Code :\nthis are my objects\nvar latlong1 = {\n\n lat: 17.385044,\n\n long: 78.486671\n\n }\n\n console.log(\"* 2 *\");\n\n var latlong2 = {\n\n lat: 16.306652,\n\n long: 80.436540\n\n }\n\n var latlong3 = {\n\n lat:15.505723,\n\n long: 80.049922\n\n }\n\n var latlong4 = {\n\n lat: 15.317277,\n\n long: 75.713888\n\n }\n\ni know i can create it like this.\nvar marker = new google.maps.Marker({\n\n position: new google.maps.LatLng(lat, long),\n\n map: map,\n\n draggable: true,\n\n animation: google.maps.Animation.DROP,\n\n icon: icon\n\n });\n\nand use values inside the position \nnew google.maps.LatLng(latlong3.lat, latlong3.long)\n\nBut there is another way? \n\nA:\n\nYou should first Create an array based on that object values.\nvar latLong =[];\n\nand lester create a simple function.\nfunction createMarkers(){\n for(var i = 0 ; i \n{\n private Long id;\n @IndexedEmbedded\n private Customer customer;\n @Field(index=Index.TOKENIZED, store=Store.NO)\n private String question;\n @Field(index=Index.TOKENIZED, store=Store.NO)\n private String answer;\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n public Long getId()\n {\n return id;\n }\n public void setId(Long id)\n {\n this.id = id;\n }\n\n @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL)\n @JoinColumn(name=\"customer_id\")\n public Customer getCustomer()\n {\n return customer;\n }\n public void setCustomer(Customer customer)\n {\n this.customer = customer;\n }\n\n @Column(name=\"question\", length=1500)\n public String getQuestion()\n {\n return question;\n }\n public void setQuestion(String question)\n {\n this.question = question;\n }\n\n @Column(name=\"answer\", length=1500)\n public String getAnswer()\n {\n return answer;\n }\n public void setAnswer(String answer)\n {\n this.answer = answer;\n }\n @Override\n public int hashCode()\n {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((id == null) ? 0 : id.hashCode());\n return result;\n }\n @Override\n public boolean equals(Object obj)\n {\n if (this == obj) return true;\n if (obj == null) return false;\n if (getClass() != obj.getClass()) return false;\n CustomerFaq other = (CustomerFaq) obj;\n if (id == null)\n {\n if (other.id != null) return false;\n } else if (!id.equals(other.id)) return false;\n return true;\n }\n @Override\n public int compareTo(CustomerFaq o)\n {\n if (this.getCustomer().equals(o.getCustomer()))\n {\n return this.getId().compareTo(o.getId());\n }\n else\n {\n return this.getCustomer().getId().compareTo(o.getCustomer().getId());\n }\n }\n}\n\nHere's a snippet of my Customer domain object:\nimport org.hibernate.search.annotations.Field;\nimport org.hibernate.search.annotations.Index;\nimport org.hibernate.search.annotations.Store;\nimport javax.persistence.Entity;\n// ... other imports\n\n@Entity\npublic class Customer\n{\n @Field(index=Index.TOKENIZED, store=Store.YES)\n private Long id;\n\n // ... other instance vars\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n public Long getId()\n {\n return id;\n }\n public void setId(Long id)\n {\n this.id = id;\n }\n\nAnd my persistence.xml:\n\n\n\n org.hibernate.ejb.HibernatePersistence\n \n \n \n \n \n \n \n \n \n\n \n \n\n\nAnd finally, here's the query that's being used in a DAO:\npublic List searchFaqs(String question, Customer customer)\n {\n FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());\n QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(CustomerFaq.class).get();\n org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields(\"question\", \"answer\").matching(question).createQuery();\n\n org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, CustomerFaq.class);\n\n List matchingQuestionsList = fullTextQuery.list();\n log.debug(\"Found \" + matchingQuestionsList.size() + \" matching questions\");\n List list = new ArrayList();\n for (CustomerFaq customerFaq : matchingQuestionsList)\n {\n log.debug(\"Comparing \" + customerFaq.getCustomer() + \" to \" + customer + \" -> \" + customerFaq.getCustomer().equals(customer));\n log.debug(\"Does list already contain this customer FAQ? \" + list.contains(customerFaq));\n if (customerFaq.getCustomer().equals(customer) && !list.contains(customerFaq))\n {\n list.add(customerFaq);\n }\n }\n log.debug(\"Returning \" + list.size() + \" matching questions based on customer: \" + customer);\n return list;\n }\n\nA:\n\nIt looks like the actual location where my software was looking for the indexBase was incorrect.\nWhen I looked through the logs, I noticed that it was referring to two different locations when loading the indexBase. \nOne location that Hibernate Search was loading this indexBase was from \"C:/Program Files/Apache Software Foundation/Tomcat 6.0/tmp/indexes\", then a little later on in the logs (during the startup phase) I saw that it was also loading from the place I had set it to in my persistence.xml file (\"C:/lucene/indexes\").\nSo realizing this, I just changed the location in my persistence.xml file to match the location that it was (for some reason) also looking. Once those two matched up, BINGO, everything worked!\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28994,"cells":{"text":{"kind":"string","value":"Q:\n\nVim autoindent (gg=G) is terribly broken for JS indentation\n\nMy end goal here is to use gg=G to autoindent all of my JS code compliant to an eslintrc.js file.\nSo, currently I have syntastic and vim-javascript looking at my JS code with the following in my .vimrc\nlet g:syntastic_javascript_checkers=[\"eslint\"]\n\nLets say that I have some decent JS like the following\nconst path = require('path');\n\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\n\nconst PATHS = {\n app : path.join(__dirname, 'app'),\n build : path.join(__dirname, 'build'),\n};\n\nconst commonConfig = {\n entry : {\n app : PATHS.app,\n },\n output : {\n path : PATHS.build,\n filename : '[name].js',\n },\n plugins : [\n new HtmlWebpackPlugin({\n title : 'Webpack Demo',\n }),\n ],\n};\n\nThe gg=G (normal mode) command mutilates the above into the following.\nconst path = require('path');\n\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\n\nconst PATHS = {\napp : path.join(__dirname, 'app'),\n build : path.join(__dirname, 'build'),\n};\n\nconst commonConfig = {\nentry : {\napp : PATHS.app,\n },\noutput : {\npath : PATHS.build,\n filename : '[name].js',\n },\nplugins : [\n new HtmlWebpackPlugin({\ntitle : 'Webpack Demo',\n}),\n],\n };\n\nWhich is not cool. \nBtw, vim-js-indent and vim-jsx-improve didn't do anything either. \nAny help is very welcome, many thanks are in advance.\n\nA:\n\nYour \"not cool\" example is the result of the \"generic\" indenting you get when Vim didn't recognize your buffer as JavaScript and/or didn't apply JavaScript-specific indentation rules.\nThat code is indented correctly with this minimal setup:\n$ vim -Nu NONE --cmd 'filetype indent on' filename.js\n\nwhich:\n\ndetects that your buffer contains JavaScript,\napplies JavaScript-specific indentation rules.\n\nTo ensure proper indenting, you must add this line to your vimrc:\nfiletype indent on\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28995,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to insert Flash without JavaScript in the most compatible but valid way?\n\nI'm looking for a way to embed Flash into a XHTML Transitional page that does not rely on enabled JavaScript, which validates and that works across all major Browsers including IE6.\nSo far I'm using this solution which seems to work just fine:\nhttp://latrine.dgx.cz/how-to-correctly-insert-a-flash-into-xhtml#toc-final-solution\nHowever, when this method is used in an RSS Feed it seems that Feedburner and Google Reader at least (maybe other feed readers, too) strip the whole object tags and only leave the alternative content.\nAny suggestions how to improve this?\n\nA:\n\nGoogle Reader only support the embed tag :-/\nhttp://www.google.com/support/reader/bin/answer.py?hl=en&answer=70664\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28996,"cells":{"text":{"kind":"string","value":"Q:\n\nExecute commands in a file\n\nI am using the 2003 textbook - http://www.amazon.com/Unix-Shell-Programming-3rd-Edition/dp/0672324903\nMy OS is linux L-ubuntu 13 which is not based on POSIX (I think)\nIt says that I can store who | wc -l in a file called nu and then execute nu. But, before that I need to make this file executable by using chmod +x file(s). This does not work. How do I make the nu \"command\" work ? I know I can do it by naming nu as nu.sh and then doing bash nu.sh, but I want to try this way also. \n\nA:\n\nTo execute a file that is not in the PATH, you must give a properly qualified directory name. While giving the name of the file in the current directory is sufficient as an argument to a program, in order to execute a shell script or other executable file, you must give at least a relative path. For example, if the file is in your home directory, which is also the working directory, any of the following are acceptable:\n./nu\n~/nu\n/home/username/nu\n\nHowever, simply nu will only attempt to search the PATH, which probably includes places such as /bin, /usr/bin, and so on. \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28997,"cells":{"text":{"kind":"string","value":"Q:\n\nObjective C - when should \"typedef\" precede \"enum\", and when should an enum be named?\n\nIn sample code, I have seen this:\ntypedef enum Ename { Bob, Mary, John} EmployeeName;\n\nand this:\ntypedef enum {Bob, Mary, John} EmployeeName;\n\nand this:\ntypedef enum {Bob, Mary, John};\n\nbut what compiled successfully for me was this:\nenum {Bob, Mary, John};\n\nI put that line in a .h file above the @interface line, and then when I #import that .h file into a different class's .m file, methods there can see the enum.\nSo, when are the other variants needed?\nIf I could name the enum something like EmployeeNames, and then, when I type \"EmployeeNames\" followed by a \".\", it would be nice if a list pops up showing what the enum choices are.\n\nA:\n\nIn C (and hence Objective C), an enum type has to be prefixed with enum every time you use it.\nenum MyEnum enumVar;\n\nBy making a typedef:\ntypedef MyEnum MyEnumT;\n\nYou can write the shorter:\nMyEnumT enumVar;\n\nThe alternative declarations declare the enum itself and the typedef in one declaration.\n// gives the enum itself a name, as well as the typedef\ntypedef enum Ename { Bob, Mary, John} EmployeeName;\n\n// leaves the enum anonymous, only gives a name to the typedef\ntypedef enum {Bob, Mary, John} EmployeeName;\n\n// leaves both anonymous, so Bob, Mary and John are just names for values of an anonymous type\ntypedef enum {Bob, Mary, John};\n\nA:\n\nThe names inside enum { } define the enumerated values. When you give it a name, you can use it as a type together with the keyword enum, e.g. enum EmployeeName b = Bob;. If you also typedef it, then you can drop the enum when you declare variables of that type, e.g. EmployeeName b = Bob; instead of the previous example.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28998,"cells":{"text":{"kind":"string","value":"Q:\n\nHow I can load a model in TDB TripleStore\n\nI have a question for you:\nI would like to load a file on my Jena TDB TripleStore.\nMy file is very big, about 80Mb and about 700000 triples RDF. When I try to load it, the execution stops working or takes a very long time.\nI'm using this code that I do run on a Web Service:\n String file = \"C:\\\\file.nt\";\n String directory;\n directory = \"C:\\\\tdb\";\n Dataset dataset = TDBFactory.createDataset(directory);\n\n Model model = ModelFactory.createDefaultModel();\n\n TDBLoader.loadModel(model, file );\n dataset.addNamedModel(\"http://nameFile\", model); \n\n return model;\n\nSometimes I get an error of Java heap space:\nCaused by: java.lang.OutOfMemoryError: Java heap space\n at org.apache.jena.riot.tokens.TokenizerText.parseToken(TokenizerText.java:170)\n at org.apache.jena.riot.tokens.TokenizerText.hasNext(TokenizerText.java:86)\n at org.apache.jena.atlas.iterator.PeekIterator.fill(PeekIterator.java:50)\n at org.apache.jena.atlas.iterator.PeekIterator.next(PeekIterator.java:92)\n at org.apache.jena.riot.lang.LangEngine.nextToken(LangEngine.java:99)\n at org.apache.jena.riot.lang.LangNTriples.parseOne(LangNTriples.java:67)\n at org.apache.jena.riot.lang.LangNTriples.runParser(LangNTriples.java:54)\n at org.apache.jena.riot.lang.LangBase.parse(LangBase.java:42)\n at org.apache.jena.riot.RDFParserRegistry$ReaderRIOTFactoryImpl$1.read(RDFParserRegistry.java:142)\n at org.apache.jena.riot.RDFDataMgr.process(RDFDataMgr.java:859)\n at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:255)\n at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:241)\n at org.apache.jena.riot.adapters.RDFReaderRIOT_Web.read(RDFReaderRIOT_Web.java:96)\n at com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:241)\n at com.hp.hpl.jena.tdb.TDBLoader.loadAnything(TDBLoader.java:294)\n at com.hp.hpl.jena.tdb.TDBLoader.loadModel(TDBLoader.java:125)\n at com.hp.hpl.jena.tdb.TDBLoader.loadModel(TDBLoader.java:119)\n\nHow I can load this file in a model Jena and save it in TDB? Thanks in advance.\n\nA:\n\nYou need to allocate more memory for your JVM at statup. When you have too little, the process will spend too much time performing garbage collection, and will ultimately fail.\nFor example, start your JVM with 4 GB of memory by:\njava -Xms4G -XmxG\n\nIf you are in an IDE such as Eclipse, you can change your run configuration so that the application has additional memory as well.\nAside from that, the only change that jumps out at me is that you are using an in-memory model for the actual loading operation, when you can actually use a model backed by TDB instead. This can help to alleviate your memory problems because TDB dynamially moves its indexes to disk.\nChange:\nDataset dataset = TDBFactory.createDataset(directory);\nModel model = ModelFactory.createDefaultModel();\nTDBLoader.loadModel(model, file );\ndataset.addNamedModel(\"http://nameFile\", model);\n\nto this:\nDataset dataset = TDBFactory.createDataset(directory);\nModel model = dataset.getNamedModel(\"http://nameFile\");\nTDBLoader.loadModel(model, file );\n\nNow your system depends on TDB's ability to make good decisions about when to leave data in memory and when to flush it to disk.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":28999,"cells":{"text":{"kind":"string","value":"Q:\n\nxamarin shared preferences replace\n\nI am new on xamarin android development and i have a problem with return shared preferences getString method.\nISharedPreferences pref = PreferenceManager.GetDefaultSharedPreferences(this);\n string loginToken = pref.GetString(\"token\", string.Empty);\n if (!string.IsNullOrEmpty(loginToken))\n {\n this result return=> \"\\\"QuZzOXjLead6rmBuSjs6vJ269BKmiXvOKPmy47y46ms\\\"\"\n\nand replace method not worked. How can i clear \"\\\" and \\\"\" symbols?\n\nA:\n\n\\\" is just an escaping for \" - so just do a string.Replace(\"\\\"\", \"\")\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":289,"numItemsPerPage":100,"numTotalItems":29950,"offset":28900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Nzk5NjMzNiwic3ViIjoiL2RhdGFzZXRzL3N1b2x5ZXIvcGlsZV9zdGFja2V4Y2hhbmdlIiwiZXhwIjoxNzU3OTk5OTM2LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0._htN9Sg6FPlU0TRgAnY0ebaLl6Vx6b_ntD-ca9CvwC8PnDjPL6cm4i9f1KWB5_4SJaIEXIhcFNP77TXli43iCQ","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
text
stringlengths
175
47.7k
meta
dict
Q: Summation involving binomial coefficients #1 I am asked to find the following sum:$$\sum_{i=0}^{100}\binom{k}{i}\binom{M-k}{100-i}\frac{(k-i)}{M-100}$$ The first two terms in the expression i.e, the binomial coefficients is actually $\binom{M}{100}$ as $\binom{k}{i}$ is the coefficient of $x^i$ in $(1+x)^k$ and $\binom{M-k}{100-i}$ is the coefficient of $x^{100-i}$ in $(1+x)^{M-k}$. Simplifying things I get an answer which is no was close to the actual answer. A: Note that by Vandermonde's identity, $$\sum_{i=0}^{100}\binom{k}{i}\binom{M-k}{100-i}k=k\sum_{i=0}^{100}\binom{k}{i}\binom{M-k}{100-i}=k\binom{M}{100}$$ and $$\sum_{i=0}^{100}\binom{k}{i}\binom{M-k}{100-i}i=\sum_{i=1}^{100}\frac{k}{i}\binom{k-1}{i-1}\binom{M-k}{100-i}i=k\sum_{i=1}^{100}\binom{k-1}{i-1}\binom{M-k}{99-(i-1)}\\ =k\sum_{j=0}^{99}\binom{k-1}{j}\binom{M-k}{99-j}=k\binom{M-1}{99}=\frac{k100}{M}\binom{M}{100}.$$ Hence $$\sum_{i=0}^{100}\binom{k}{i}\binom{M-k}{100-i}\frac{(k-i)}{M-100}= \frac{1}{M-100}\left(k\binom{M}{100}-\frac{k100}{M}\binom{M}{100}\right)= \frac{k}{M}\binom{M}{100}.$$
{ "pile_set_name": "StackExchange" }
Q: ffmpeg Invalid data found when processing input h264 to h265 I want to convert video files from h264 to h265. The command I use worked for many files so far, but now I get an error for some files: # ffmpeg -i rst.mkv -vcodec hevc -x265-params crf=28 -sn -acodec copy -map 0 out.mkv ffmpeg version 2.8.6 Copyright (c) 2000-2016 the FFmpeg developers built with gcc 4.8.5 (Gentoo 4.8.5 p1.3, pie-0.6.2) configuration: --prefix=/usr --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --enable-shared --cc=x86_64-pc-linux-gnu-gcc --cxx=x86_64-pc-linux-gnu-g++ --ar=x86_64-pc-linux-gnu-ar --optflags='-O2 -pipe -march=core2' --disable-static --enable-avfilter --enable-avresample --disable-stripping --disable-indev=v4l2 --disable-outdev=v4l2 --disable-indev=alsa --disable-indev=oss --disable-indev=jack --disable-outdev=alsa --disable-outdev=oss --disable-outdev=sdl --enable-bzlib --disable-runtime-cpudetect --disable-debug --disable-doc --disable-gnutls --enable-gpl --enable-hardcoded-tables --enable-iconv --disable-lzma --enable-network --disable-openssl --enable-postproc --disable-libsmbclient --disable-ffplay --disable-sdl --disable-vaapi --disable-vdpau --disable-xlib --disable-libxcb --disable-libxcb-shm --disable-libxcb-xfixes --enable-zlib --disable-libcdio --disable-libiec61883 --disable-libdc1394 --disable-libcaca --disable-openal --disable-opengl --disable-libv4l2 --disable-libpulse --disable-libopencore-amrwb --disable-libopencore-amrnb --disable-libfdk-aac --disable-libopenjpeg --disable-libbluray --disable-libcelt --disable-libgme --disable-libgsm --disable-libmodplug --disable-libopus --disable-libquvi --disable-librtmp --disable-libssh --disable-libschroedinger --disable-libspeex --enable-libvorbis --enable-libvpx --disable-libzvbi --disable-libbs2b --disable-libflite --disable-frei0r --disable-libfribidi --disable-fontconfig --disable-ladspa --disable-libass --disable-libfreetype --disable-libsoxr --enable-pthreads --disable-libvo-aacenc --disable-libvo-amrwbenc --disable-libmp3lame --disable-libaacplus --disable-libfaac --disable-libsnappy --enable-libtheora --disable-libtwolame --disable-libwavpack --disable-libwebp --enable-libx264 --enable-libx265 --disable-libxvid --disable-x11grab --disable-amd3dnow --disable-amd3dnowext --disable-avx --disable-avx2 --disable-fma3 --disable-fma4 --disable-sse3 --disable-ssse3 --disable-sse4 --disable-sse42 --disable-xop --cpu=core2 libavutil 54. 31.100 / 54. 31.100 libavcodec 56. 60.100 / 56. 60.100 libavformat 56. 40.101 / 56. 40.101 libavdevice 56. 4.100 / 56. 4.100 libavfilter 5. 40.101 / 5. 40.101 libavresample 2. 1. 0 / 2. 1. 0 libswscale 3. 1.101 / 3. 1.101 libswresample 1. 2.101 / 1. 2.101 libpostproc 53. 3.100 / 53. 3.100 Input #0, matroska,webm, from 'rst.mkv': Metadata: encoder : libebml v1.0.0 + libmatroska v1.0 Duration: 00:21:22.28, start: 0.000000, bitrate: 11533 kb/s Chapter #0:0: start 0.000000, end 159.784000 Metadata: title : 00:00:00.000 Chapter #0:1: start 159.784000, end 642.266000 Metadata: title : 00:02:39.784 Chapter #0:2: start 642.266000, end 1225.641000 Metadata: title : 00:10:42.266 Chapter #0:3: start 1225.641000, end 1254.878000 Metadata: title : 00:20:25.641 Chapter #0:4: start 1254.878000, end 1282.281000 Metadata: title : 00:20:54.878 Chapter #0:5: start 1282.364000, end 1282.281000 Metadata: title : 00:21:22.364 Stream #0:0(eng): Video: h264 (High), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 23.98 fps, 23.98 tbr, 1k tbn, 47.95 tbc (default) Stream #0:1(ger): Audio: ac3, 48000 Hz, 5.1(side), fltp, 384 kb/s (default) Stream #0:2(eng): Audio: dts (DTS), 48000 Hz, 5.1(side), fltp, 1536 kb/s File 'tbbt-s07e02.mkv' already exists. Overwrite ? [y/N] y x265 [info]: HEVC encoder version 1.9 x265 [info]: build info [Linux][GCC 4.8.5][64 bit] 8bit+10bit+12bit x265 [info]: using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.1 Cache64 x265 [info]: Main profile, Level-4 (Main tier) x265 [info]: Thread pool created using 4 threads x265 [info]: frame threads / pool features : 2 / wpp(17 rows) x265 [info]: Coding QT: max CU size, min CU size : 64 / 8 x265 [info]: Residual QT: max TU size, max depth : 32 / 1 inter / 1 intra x265 [info]: ME / range / subpel / merge : hex / 57 / 2 / 2 x265 [info]: Keyframe min / max / scenecut : 23 / 250 / 40 x265 [info]: Lookahead / bframes / badapt : 20 / 4 / 2 x265 [info]: b-pyramid / weightp / weightb : 1 / 1 / 0 x265 [info]: References / ref-limit cu / depth : 3 / 1 / 1 x265 [info]: AQ: mode / str / qg-size / cu-tree : 1 / 1.0 / 32 / 1 x265 [info]: Rate Control / qCompress : CRF-28.0 / 0.60 x265 [info]: tools: rd=3 psy-rd=2.00 signhide tmvp strong-intra-smoothing x265 [info]: tools: lslices=6 deblock sao [matroska @ 0x1b09450] Codec for stream 1 does not use global headers but container format requires global headers [matroska @ 0x1b09450] Codec for stream 2 does not use global headers but container format requires global headers [matroska @ 0x1b09450] Invalid chapter start (1282364000000) or end (1282281000000). Output #0, matroska, to 'out.mkv': Metadata: encoder : Lavf56.40.101 Chapter #0:0: start 0.000000, end 159.784000 Metadata: title : 00:00:00.000 Chapter #0:1: start 159.784000, end 642.266000 Metadata: title : 00:02:39.784 Chapter #0:2: start 642.266000, end 1225.641000 Metadata: title : 00:10:42.266 Chapter #0:3: start 1225.641000, end 1254.878000 Metadata: title : 00:20:25.641 Chapter #0:4: start 1254.878000, end 1282.281000 Metadata: title : 00:20:54.878 Chapter #0:5: start 1282.364000, end 1282.281000 Metadata: title : 00:21:22.364 Stream #0:0(eng): Video: hevc (libx265), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], q=2-31, 23.98 fps, 1k tbn, 23.98 tbc (default) Metadata: encoder : Lavc56.60.100 libx265 Stream #0:1(ger): Audio: ac3 ([0] [0][0] / 0x2000), 48000 Hz, 5.1(side), 384 kb/s (default) Stream #0:2(eng): Audio: dts ([1] [0][0] / 0x2001), 48000 Hz, 5.1(side), 1536 kb/s Stream mapping: Stream #0:0 -> #0:0 (h264 (native) -> hevc (libx265)) Stream #0:1 -> #0:1 (copy) Stream #0:2 -> #0:2 (copy) Could not write header for output file #0 (incorrect codec parameters ?): Invalid data found when processing input encoded 0 frames The files in question are playable by for example mpv, so they are not corrupt. A: I would start with the first error. [matroska @ 0x1b09450] Codec for stream 1 does not use global headers but container format requires global headers Try including the following to correc that: "-flags +global_header". And to convert an h264 to h265 you can use the following command with a standard FFmpeg install (assuming input.mp4 is a valid h264 file). Not sure if there are any unique flags required for an .mkv file but give that a try. Command I use for .mp4 files: ffmpeg -i /path/input.mp4 -c:v libx265 -c:a copy -flags +global_header /path/output.mp4
{ "pile_set_name": "StackExchange" }
Q: Populating two types of UITableViewCell in a single UITableView I have a ViewController called notificationsVC with two tableViews - notifTable and messageTable. In notifTable I have two types of UITableViewCells - As you can see there's a followed you and commented/liked your post patterns. Until now I have been using two UITableViewCell's like this. (reuse identifier - cell1 and cell3) The first one I made a coach touch file named notification_cell.swift and another notification2_cell.swift notification_cell.swift import UIKit class notification_cell: UITableViewCell { @IBOutlet weak var profilePic: UIImageView! @IBOutlet weak var username: UILabel! @IBOutlet weak var followNotif: UILabel! } notification2_cell.swift import UIKit class notification2_cell: UITableViewCell { @IBOutlet weak var profilePic: UIImageView! @IBOutlet weak var username: UILabel! @IBOutlet weak var c_l_notif: UILabel! @IBOutlet weak var postImage: UIImageView! } I have four arrays in all - var username = [String]() var notif = [String]() var u_id = [String]() var p_id = [String]() For eg, when I do a API call I get this username-> ["Anton Griezmann", "Anonymous", "Anonymous"] u_id-> ["2", "30", "31"] notif-> ["followed you", "liked your post", "liked your post"] p_id-> ["", "9", "9"] What I'm trying to do is whenever there's a blank "" in p_id I know I have to initialise cell1 and otherwise cell3 This is my code for cellForRowAtIndexpath func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ var cell = UITableViewCell() var index = [Int]() if(tableView==self.notifTable) { for i in 0..<p_id.count { if p_id[indexPath.row].isEmpty { index.append(i) //cell for followed you let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! notification_cell cell.username.text = username[indexPath.row] cell.followNotif.text = notif[indexPath.row] return cell } else { //cell for commented/liked let cell = tableView.dequeueReusableCellWithIdentifier("cell3", forIndexPath: indexPath) as! notification2_cell cell.username.text = username[indexPath.row] cell.c_l_notif.text = notif[indexPath.row] return cell } } } else { let cell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) cell.textLabel?.text = "hola" return cell } } What I get when I run it is this That is the first cell is getting overwritten again. I need a way to find out which cell should be initialised at what indexPath but can't think of how. Any suggestions are welcome! A: First of all you are returning wrong cell in your cellForRowAtIndexPath try to return cell inside the if - else block, and if you want to check for p_id[indexPath.row] is "" means it is empty so you can check its length or use isEmpty function of String, There is no need to go through a loop, Also. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ if(tableView==self.notifTable) { if (p_id[indexPath.row].isEmpty) { //cell for followed you let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! notification_cell cell.username.text = username[indexPath.row] cell.followNotif.text = notif[indexPath.row] return cell } else { //cell for commented/liked let cell = tableView.dequeueReusableCellWithIdentifier("cell3", forIndexPath: indexPath) as! notification2_cell cell.username.text = username[indexPath.row] cell.c_l_notif.text = notif[indexPath.row] return cell } } else { let cell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) cell.textLabel?.text = "hola" return cell } }
{ "pile_set_name": "StackExchange" }
Q: How do I write different operator[] for LValue and RValue? I am trying to interface a C library to my C++ project. The library has its own vector type, assume to be VECTOR, and it provides element access: int vector_set_value(VECTOR* vec, int index, double new_value); int vector_get_value(VECTOR* vec, int index, double* retrieved_value); Now it would be good to wrap the get and set operations by operator[] overloading double& operator[](int index); const double& operator[](int index) const; But how do I tell operator[] have different behavior, between vec[index]=3 and double value=vec[3]? For the prior vector_set_value should be called while for the latter vector_get_value should be called. A: I would not attempt to wrap one interface into the other. That being said, if you really want to do this one possible solution is to create a proxy object, and have your operator[] return that proxy object. The proxy object would have conversions into the underlying type const double& for reading, and overloaded operator= for writing. Each one of them would call the appropriate library function. This will allow for syntax that looks like that of C++ std::vector: MyVector v(...); v[1] = 10.1; double d = v[1]; but it will be problematic. The proxy object cannot replace the real type in all contexts, only in some of them. And even there, the semantics are different, so while it may look like a regular vector, one day you will try to use the proxy in a way it does not support and you will be puzzled at the leaking abstraction
{ "pile_set_name": "StackExchange" }
Q: Objective-C: NSInputStream and NSOutputStream for testing purposes I have an class in my application that is initialized with an NSInputStream. For testing purposes i want to write data on an NSOutputStream which then is received by that input stream. This should trigger the NSStreamEventHasBytesAvailable event. The only thing is that i do not know how to set this up. Does anybody has an idea? Or suggestions how to unit test a class with has an NSStream as dependency. Thanks A: This is actually really tricky since it appears that you can only create an input stream using a file, a URL or an NSData. You can't connect an input stream to an output stream, although you might be able to write a single class that implements both interfaces. The easiest way to do the unit test would probably be to create your input stream from an NSData whose bytes you have already read in from the output stream.
{ "pile_set_name": "StackExchange" }
Q: Battery charger filter circuit I'm working on a project where I have to make a powerfull battery charger. And someone I'm working with told me that it is a good idea to have mains voltage connected to a full bridge rectifier and after that something like a Sallen-Key filter. But is there a reason for that? I do not get why it is an important feature. Thanks a lot A: You are getting way ahead of yourself. Whether you need to monitor line voltage or not, and what filtering you need to apply to that if you do, are design details you are not ready for. You have to start out with basic specs of what this "battery charger" is supposed to do before you can decide how it's supposed to do it. Sit down and specify things like what line voltage range it will work with, whether PFC will be necessary, what type and quantity of batteries it will charge, how fast it should charge them, what tradeoffs you might want to make with capacity versus lifetime, etc, etc.
{ "pile_set_name": "StackExchange" }
Q: Get count of documents without loading the whole collection in DerbyJS 0.6 How can I count the results of a query without loading the whole resultset into memory? The easy way of counting documents returned by a query would be: var q = model.query('mycollection', { date: today }); q.fetch(function() { var length = q.get().length; }); But this would load the whole resultset into memory and "count" an array in javascript. When you have lots of data you don't want to do this. I think. Counting the underlying mongodb collection is rather complicated since LiveDB (I think it is LiveDB) creates many mongodb documents for one derbyjs document. The internets point to this google groups thread from 2013, but the solution described there (putting $count: true into the query options) doesn't seem to work in DerbyJS 0.6 and current mongodb.". query.extraRef is undefined. A: It is done like described in the google groups thread. But query.extraRef is now query.refExtra. Example: var q = model.query('mycollection', { $count: true, date: today }); q.refExtra('_page.docsOfToday'); q.fetch();
{ "pile_set_name": "StackExchange" }
Q: c# to AS400 / JD Edwards - run program - Data source name not found and no default driver specified UPDATE: The code example below works. I changed the connection string. That was the problem. For an alternative (non-ADO) solution, see Mike Wills's link in the comments. I have a c# class that (if I ever get it working) runs a program written in RPG code on AS/400 - JD Edwards. I know next to nothing about AS/400 and/or JD Edwards. I've got other classes in my (intranet) web app that connect to JD Edwards, running SQL queries and setting/getting data. All of these are using the IBM.Data.DB2.iSeries dll and are working great. For this, I wrote a similar class using the aforementioned dll, but it wasn't working. I even read somewhere online that you can't run a program using this dll. I found that a little fishy, but on suggestion from my JD Edwards co-worker, I scrapped the class and re-wrote it using the adodb dll. No data need be returned from this program run. I just want the program to run. Here is a dummified version of the class: private void runJDEProgram() { ADODB.Connection cn = new ADODB.Connection(); cn.ConnectionString = "Provider=ABABAB;Data Source=111.111.111"; ADODB.Command cmdDetail = new ADODB.Command(); cn.Open(); //has to be open before setting an active connection. cmdDetail.ActiveConnection=cn; cmdDetail.CommandType = ADODB.CommandTypeEnum.adCmdText; cmdDetail.CommandText = "{{CALL BLAH.BLAH(?,?)}}"; cmdDetail.Prepared = true; cmdDetail.Parameters.Append(cmdDetail.CreateParameter("P1", ADODB.DataTypeEnum.adChar, ADODB.ParameterDirectionEnum.adParamInput, 10, "BLAH123")); cmdDetail.Parameters.Append(cmdDetail.CreateParameter("P2", ADODB.DataTypeEnum.adChar, ADODB.ParameterDirectionEnum.adParamInput, 10, "BLAH456")); object dummy = Type.Missing; //otherwise, we couldn't get past this. cmdDetail.Execute(out dummy, ref dummy, 0); cn.Close(); } Here's the error I get when it runs: {"[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"} Where am I screwing up? Thanks! EDIT: The connection string works when querying the AS/400 to get/set data. Does it need to be modified for an operation like this, or for use with ADO? A: The connection string has to be different for this, for some reason. I don't use the same connection string for the other classes that just run queries. The above connection string worked fine (with the appropriate values, of course). It will prompt for password, but the JDE folks here wanted that.
{ "pile_set_name": "StackExchange" }
Q: Magic __get in php i need help about this below: i understand the code but i do not understand the output of the last line why the output is b,A,B and not A,b,B ? class magic{ public $a = "A"; protected $b = array("a" => "A", "b" => "B","c" => "C"); protected $c = array(1,2,3); public function __get($name){ echo "$name,"; return $this -> b[$name]; } } $m = new magic(); echo $m->a; // A // because $a is public echo $m->b; // b,B // because $b is protected echo $m->a.",".$m->b; // b,A,B A: The problem is that your echoing the name in your __get() method, this will output the value straight away, but return the value of the variable to display later. If you change the routine to... public function __get($name){ //echo "$name,"; return "$name,".$this -> b[$name]; } Your output becomes - A,b,B
{ "pile_set_name": "StackExchange" }
Q: Compiler.getTask ERROR Compiler I am compiling this class with JavaCompiler and it gives me a compilation error if the String that I pass to compile is this: public class className extends classNeed{ } But if I delete public it works. What could I do to make it compilable with: JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); String program = code; Iterable<? extends JavaFileObject> fileObjects; fileObjects = getJavaSourceFromString(program); String[] options = new String[]{"-d", contextClass.getPath()+"temp/"+pathJar+"/", "-classpath",contextClass.getBasePath()+"WEBINF/lib/lib1.jar; "+contextClass.getBasePath()+"WEB-INF/lib/lib2.jar"}; compiler.getTask(null, null, null, Arrays.asList(options), null, fileObjects).call(); and it still working being public? EDIT: ERROR string:///code.java:16: class className is public, should be declared in a filed className.java but the name is the same A: Public classes need to be declared in their own files? I think the compiler doesn't feel that the input has come from a correctly-named .java file, as per the language specification. (Public classes must be defined in their own files). Maybe you've got the paths wrong, the Java compiler appears to reject it based on Java file/ declared package and classname mismatch.
{ "pile_set_name": "StackExchange" }
Q: Why are étale morphisms called "étale"? Alexander Grothendieck developed the theory of "locally trivial coverings spaces for rings/schemes" in SGAI as an analog to the theory of covering spaces in algebraic topology. He called such coverings étale morphisms; does anyone know why? Étale translates to something like; spread out, or slack. But there are also a number of other possible translations. None of which seem to suit the apparent properties of étale. Is there a manner in which we can think of étale morphisms which make the name obvious? A: From Milne's site: There are two different words in French, "étaler", which means spread out or displayed and is used in "éspace étalé", and "étale", which is rare except in poetry. According to Illusie, it is the second that Grothendieck chose for étale morphism. The Petit Larousse defines "mer étale" as "mer qui ne monte ni ne descend", i.e., the sea at the point of high or low tide. For example, there is the quote from Hugo which I included in my book "La mer était étale, mais le reflux commencait a se sentir". I think Grothendieck chose the word because the way he pictured étale morphisms reminded him of a calm sea at high tide under a full moon (locally almost parallel bands of light, but not globally). I find this image beautiful. A footnote in Mumford's Red Book on Algebraic Geometry says: "The word apparently refers to the appearance of the sea at high tide under a full moon in certain types of weather." Milne also linked this image A: The use of étale predates SGA, and "spread out" fits Grothendieck’s idea of all-encompassing topos, "vast" and "slack", better than usual, as these things go. The name of étale morphisms derives from that. Also, French étaler comes from old French estal, which meant position/place, same as Greek topos, although it is unclear if that was intended too. See What are the benefits of viewing a sheaf from the “espace étalé” perspective? thread on Math Overflow for a more mathematical discussion. Here is Grothendieck’s own explanation from Récoltes et Semailles: "The crucial thing here, from the viewpoint of the Weil conjectures, is that the new notion [of space] is vast enough, that we can associate to each scheme a “generalized space” or “topos” (called the “étale topos” of the scheme in question). Certain “cohomology invariants” of this topos (“childish” in their simplicity!) seemed to have a good chance of offering “what it takes” to give the conjectures their full meaning, and (who knows!) perhaps to give the means of proving them." The idea was part of Grothendieck's general strategy for proving the Weil conjectures, which Serre explained to him in cohomological terms in 1955. Étale covers were inspired by Serre's "isotrivial covers". As McLarty's comments in The Rising Sea: "Cohomology gives algebraic invariants of a topos, just as it used to give invariants of a topological space. Each topological space determines a topos with the sheaf cohomology. Each group determines a topos with the group cohomology. The same, Grothendieck knew, would work for cases yet unimagined... For the Weil conjectures it only remained to find the natural topos for each arithmetic space—recalling that up to 1956 or so the spaces themselves were not adequately defined. In fact this conception of “toposes” came to Grothendieck as the way to combine his theory of schemes with Serre’s idea of isotrivial covers and produce the cohomology." This strategy was put in motion in collaboration with Artin in the early 1960-s, the time of SGA, see Jackson's As If Summoned from the Void: "When Grothendieck came to Harvard in 1961, “I asked him to tell me the definition of étale cohomology,” Artin recalled with a laugh. The definition had not yet been formulated precisely. Said Artin, “Actually we argued about the definition for the whole fall”. After moving to the Massachusetts Institute of Technology in 1962, Artin gave a seminar on étale cohomology. He spent much of the following two years at the IHÉS working with Grothendieck."
{ "pile_set_name": "StackExchange" }
Q: Prevent duplicate save using MongoRepository I have a service to perform CRUD operation in mongo. I am using MongoRepository for this. I problem i am having is when i am inserting duplicate entries i am unable to get any errors back. @Document(collection = "test") public class MongoInsert { @Id private String identifier; private String value; @PersistenceConstructor public MongoInsert(String identifier, String value) { this.identifier = identifier; this.value = value; } } I wrote a test which tries to insert the same object twice, the test passes, i am expecting the second insert to thrown an exception. My mongoTemplate defination is <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="myMongoDbFactory"/> <constructor-arg name="mongoConverter" ref="myMappingConverter"/> <property name="writeResultChecking" value="EXCEPTION"/> </bean> i have tried with 'writeConcern' set to 'ACKNOWLEDGED', but then i was getting erros Caused by: org.springframework.data.mongodb.UncategorizedMongoDbException: { "serverUsed" : "127.0.0.1:27017" , "ok" : 0 , "code" : 2 , "errmsg" : "cannot use non-majority 'w' mode ACKNOWLEDGED when a host is not a member of a replica set"}; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "ok" : 0 , "code" : 2 , "errmsg" : "cannot use non-majority 'w' mode ACKNOWLEDGED when a host is not a member of a replica set"} What am i missing here? A: Try to use instead of <property name="writeConcern" value="ACKNOWLEDGED"/> this one <property name="writeConcern"> <value type="com.mongodb.WriteConcern">ACKNOWLEDGED</value> </property> (for detail: How assign bean's property an Enum value in Spring config file?)
{ "pile_set_name": "StackExchange" }
Q: Algorithm for iteratively reversing a complex function? This algorithm finds a given value n by iterating between a lower bound and upper bound, similar to binary search. How can I improve this algorithm? A few details. The value n is almost always less than 1.0, but this isn't a boundary condition. It is, however, never less than 0. def approx_value(n, lower_bound, upper_bound, precision = 0.001): approx = (lower_bound + upper_bound) / 2.0 while (abs(approx - n) > precision): if n > approx: lower_bound = approx else: upper_bound = approx approx = (lower_bound + upper_bound) / 2.0 return approx def approx_value_no_bounds(n, precision = 0.0001): approx = 1.0 while (abs(approx - n) > precision): if approx > n: #decrease volatility return approx_value(n, 0.0, approx) else: approx *= 2 return approx I know this seems odd because the value of n is already supplied, but the algorithm is not complete. Basically, n is the solution of a complex equation that cannot be solved for approx in closed form, so I'm doing it iteratively. Eventually, this algorithm will compare the value of the function when using approx with the value n and return approx is it approximates the input variable well enough. I'm hoping to keep the running time in O(log(n)), which is why I modelled it somewhat after binary search, albeit only somewhat because the upper bound is not necessarily known immediately. A: This sounds like a classic optimization problem. These are well studied, and there are several well-known algorithms. Some simple but reasonably efficient ones are Newton's method or gradient descent. You could also try the nonlinear-simplex algorithm if the above don't work very well for your function. The running time vs accuracy tradeoff here depends on the nature of the function you are trying to solve for.
{ "pile_set_name": "StackExchange" }
Q: public T GetMyClass() where T : MyClass, new() { /* is this pointless? */ } are the two methods in the class "Confused" below the same? class MyClass { public override string ToString() { return "I am confused now"; } } class Confused { public MyClass GetMyClass() { return new MyClass(); } public T GetMyClass<T>() where T : MyClass, new() { return System.Activator.CreateInstance<T>(); } } class Program { static void Main() { Confused c = new Confused(); System.Console.WriteLine(c.GetMyClass()); System.Console.WriteLine(c.GetMyClass<MyClass>()); } } They produce different IL, but is there any reason to write the generic version other than the 'straight up' version other than to confuse the heck out of collegues :) A: If you write the generic version, you can instantiate and return derived classes: where T : MyClass Also, with the generic version you don't need the activation code: return new T(); This is because you have specified: where T : new() The generic constraint enforcing a public parameterless constructor. A: Sure there's a difference. Let's say you have a second class deriving from MyClass: class MyClass2 : MyClass { } Then you can do MyClass2 myClass2 = confused.GetMyClass<MyClass2>(); You can't do that with the other function.
{ "pile_set_name": "StackExchange" }
Q: Error moving files in xcode I made an application on Xcode. I made a mistake moving my files in an other folder and now this error appeared : <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/ViewAlbum.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/homePage.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/MasterTableViewController.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/AddViewController.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/MedecineDetails.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/Medecine.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/LoginViewController.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/RegisterViewController.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/AppDelegate.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/DetailViewController.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/ViewPhoto.swift' <unknown>:0: error: no such file or directory: '/Users/coeimac1/Desktop/learning 5535512147/UserLoginandRegistration/UserLoginandRegistration/UserLoginandRegistration/MedecineTableView.swift' Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1 I removed all the files in the right folder but it still not working.I don't understand why it cannot find My files that are actually in the place indicated in the error.. My files in Product (the .app and the .xctest) appear in red. Do you have any idea how I can solve this ? A: Moving files from a directory to another may change their paths. So a quick fix for that is to select the file from the Project navigator view, then from the File inspector, set the Location to Relative to Project.
{ "pile_set_name": "StackExchange" }
Q: Animating fade in/out of TextView whilst changing text Basically I want to use an AlphaAnimation to fade a TextView out, then change the text of that TextView, and then finally fade it back in again using another AlphaAnimation. But I don't know how to perform this sequentially. What's the best way to achieve this? A: I found a clean solution, it's called TextSwitcher. Does what I want with less fuss. A: You can do it like this, place two textviews one above the other and set different text for the two textviews and with onclick you can fadeout and fadein the two views(Remember two views shd have the same orientation) Check this code. AlphaAnimation fadeIn = new AlphaAnimation(0.0f , 1.0f ) ; fadeIn.setDuration(1200); fadeIn.setFillAfter(true); AlphaAnimation fadeOut = new AlphaAnimation( 1.0f , 0.0f ) ; fadeOut.setDuration(1200); fadeOut.setFillAfter(true); mswtview4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mswtview4.startAnimation(fadeOut); mswtview4.setVisibility(View.GONE); } }); mswtview2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mswtview2.startAnimation(fadeIn); mswtview4.setVisibility(View.VISIBLE); } });
{ "pile_set_name": "StackExchange" }
Q: Did Stephen King like Frank Darabont's ending of "The Mist"? Frank Darabont's movie The Mist is based on a Stephen King short story The Mist. But the two do not have the same ending. Here is how the short story ends (as per Wikipedia): David, Billy, Amanda, and elderly, yet tough, school teacher Hilda Reppler reach the car and leave Bridgton, driving south for hours through a mist-shrouded, monster-filled New England. After finding refuge for the night, David listens to a radio and, through the overwhelming static, possibly hears a single word broadcast: "Hartford". With that one shred of hope, he prepares to drive on into an uncertain future. Whereas the movie has a much more definite ending (again as per Wikipedia): Driving through the mist, David finds his house destroyed and his wife dead. Devastated, he drives the group south, passing destroyed vehicles and seeing a gigantic six-legged, tentacled beast. When they run out of gas, the group decides there is no point in going on. David shoots the others rather than have them endure horrifying deaths, but is left with no bullet to use on himself. He leaves the car and waits to be killed, but the mist suddenly recedes, revealing that the U.S. Army has arrived, rescued whatever survivors, and restored order. Among the survivors is the woman who left the store at the phenomenon's onset, accompanied by her two children. David breaks down with the realization that they were only moments from being rescued and had likely been driving away from help the entire time. Did King approve of this ending? A: In a recent interview with Frank Darabont by Nick Schager for Yahoo Movies, Darabont first explains his reason for changing the ending: When I first read Steve’s [Stephen King] story back a zillion years ago [in 1980’s Dark Forces anthology], I thought, “Wow, that’s a great story,” but I thought that for a movie, it should have a more conclusive sort of feeling. He points out that the story itself was the inspiration for it: So I was trying to puzzle through what that conclusive ending would be, and he kind of lays the groundwork for that, actually. There’s a line of the story where he contemplates that eventuality. And I thought, well, that seems like a clear marker for me, that Steve laid in there. The ending of the movie of course fits into a certain tradition: When that came to me, it just felt like the kind of Twilight Zone ending that really stays with you. You know, “Time Enough at Last” where Burgess Meredith breaks his glasses — that kind of ending, where you’re like “Oh no, if he’d only waited two more minutes!” I liked the horrendous irony of it. And it was also fueled by Darabont's own feelings: At that time, I was feeling a little bit pissed off at the world. There’s definitely a political element to that movie, which you don’t have to look too hard to see. Though it’s not a political movie, it’s in many ways a very political movie. I was feeling a little angry at the world, and at our country at that time [The Mist was released in 2007], so it felt like a valid way to end a movie. It doesn’t always have to be a happy ending. It shouldn’t always be a happy ending. Having grown up in the ’70s, it wasn’t always a happy ending. And I always loved endings like that. Getting to the answer to the question: Darabont did ask King for input before filming: But I thought, “OK, I’m going to let Steve decide. If Stephen King reads my script and says, ‘Dude, what are you doing, are you out of your mind? You can’t end my story this way,’ then I would actually not have made the movie.” But he read it and said, “Oh, I love this ending. I wish I’d thought of it.” He said that, once a generation, a movie should come along that just really pisses the audience off, and flips their expectations of a happy ending right on the head. He pointed to the original Night of the Living Dead as one of those endings that just scarred you.
{ "pile_set_name": "StackExchange" }
Q: Convert two booleans to an int Probably this is extremely easy. If I have two booleans, a and b, how can I get the equivalent "binary" number? false and false = 0 false and true = 1 true and false = 2 true and true = 3 A: (left ? 2 : 0) + (right ? 1 : 0); Not sure if java handles booleans like C, but if it does: 2*left+right; A: Since you have marked this as language-agnostic, I'd post how to do this in Scala. :-) scala> implicit def boolToAddable(a: Boolean) = new { | def +(b: Boolean): Int = (a, b) match { | case (false, false) => 0 | case (false, true) => 1 | case (true, false) => 2 | case (true, true) => 3 | } | } boolToAddable: (a: Boolean)java.lang.Object{def +(b: Boolean): Int} scala> false + false res0: Int = 0 scala> false + true res1: Int = 1 scala> true + false res2: Int = 2 scala> true + true res3: Int = 3 Alternatively you could use the trick suggested by @David above: scala> implicit def boolToAddable(a: Boolean) = new { | def +(b: Boolean) = (if(a) 2 else 0) + (if(b) 1 else 0) | } boolToAddable: (a: Boolean)java.lang.Object{def +(b: Boolean): Int}
{ "pile_set_name": "StackExchange" }
Q: CSS Positioning - Best Way To Position Whats' the best way to position? Float, Relative, Absolute? Lets say I want to position something like this: How do I position something like this and what's the best way to do it? Float, Relative, Absolute? A: If you want a fluid layout, use floats. Positioning elements relative/absolute causes them to display as inline therefore a height/width is required and they then become non-fluid.
{ "pile_set_name": "StackExchange" }
Q: Reduce font size I need your assistance regarding my problem. In fact, I've tried to change the slider's font size on my website : http://compil2rai.com/ on the style.css file, but the changes are not taken in account. Any help ? http://i.stack.imgur.com/LhKlL.jpg A: Not a WordPress question, but add the following in your stylesheet: .featured-text h2, .featured-text h2 a { font-size: 24px !important; /* set font size */ } In the future, simply Inspect Element to find which class or tag to style.
{ "pile_set_name": "StackExchange" }
Q: Unbound classpath variable When rebuilding my project with Maven I sometimes get hundreds of 'unbound classpath variable M2_REPO/etc/..' in my eclipse errors, most of the time when I rebuild again it goes away but on this occasion its cursed me enough to stick around. When actually going through the file system, the jars it details that are not there are actually there. Eclipse is just not seeing them for some reason. My m2_repo is correctly referenced in my preferences->java->classpathvariables section and my environmental variables are likewise properly set. Any ideas for me folks? A: If you already did several times STEP 1, go to STEP 2 STEP 1 Try deleting and redefining env vars: Open the Eclipse Preferences [Window - Preferences] Go to [Java - Build Path - Classpath Variables] Click New and set its name as M2_REPO Click Folder and select your Maven repository folder. For example, my repository folder is C:/Users/user/.m2/repository Rebuild the Project. Beside from inside of Eclipse, you can also add the M2_REPO variable from command line using this Maven command: mvn -Declipse.workspace=<path-to-eclipse-workspace> eclipse:add-maven-repo STEP 2 If your build path is correctly defined, check Maven settings.xml: Window --> Preferences --> Maven ---> User Settings If not, set it there and change localRepository path in settings tag inside settings.xml. Normally you will find settings.xml in .m2 folder under the user folder (for eg. C:\Documents and Settings\userName.m2). A: Well, I tried the steps in @Jordi's answer. But those didn't make any difference. And I tried some ritualistic things in eclipse such as: closing the project and opening it restarting the IDE cleaning and rebuilding etc... with no success. Then strange thing happened when I changed the Java complience level to 1.8 and revert it back to 1.6. It worked! All unbound classpath variable errors are gone now.
{ "pile_set_name": "StackExchange" }
Q: Correct Way to Add byte Variables into byte Arrays What I am trying to do is get input from the user and store it in a byte array. Please note, I must store var1 variable in a byte array and not a list. Console.Write("Enter a number: "); byte var1 = byte.Parse(Console.ReadLine()); byte[] byteArray = new byte[] {}; byteArray[0] = var1; A: Arrays are fixed in size, you must specifiy the size of the array when you create it. In your example you told it to make an array of size 0 by putting the {} after the byte[]. Instead remove the {} and just put a 1 between the [] Console.Write("Enter a number: "); byte var1 = byte.Parse(Console.ReadLine()); byte[] byteArray = new byte[1]; byteArray[0] = var1;
{ "pile_set_name": "StackExchange" }
Q: Character Limit How do I setup a character limit in a specific column to limit the amount of characters? A: In your list/library settings. Go to the column section and find the field you want to limit. Click on the field to go to its settings. There is an option for Maximum number of characters. By default this will be 255 for a Single line of Text field. You can change it to less than that here.
{ "pile_set_name": "StackExchange" }
Q: Unordered Couple in Ruby I would like to calculate the similarity between users, which is reciprocal. similarity[:user1][:user2] == similarity[:user2][:user1] So it would be great to use: unordered_set(:user1, :user2) = 1 unordered_set(:user2, :user1) += 1 read_unordered_set(:user1, :user2) #=> 2 read_unordered_set(:user2, :user1) #=> 2 How can I get a similar behaviour in Ruby? A: http://www.ruby-doc.org/core/classes/Set.html [1, 2].to_set == [2, 1].to_set Might help...
{ "pile_set_name": "StackExchange" }
Q: Find the same divs in DOM tree I have a DOM tree: <div id="all"> <div id="second"> <div id="target"></div> * <div id="somediv"></div> </div> <div id="second"> <div id="target"></div> <div id="somediv"></div> </div> <div id="second"> <div id="target"></div> <div id="somediv"></div> </div> </div> How I can get all divs with id="target"? $('#second').siblings().andSelf().children(':first') - shows only the first target (*), ignoring the rest. A: You can't have multiple divs with the same ID in an HTML document. Instead, use class="target". Then you can get all divs with the class target in all with $("#all .target")
{ "pile_set_name": "StackExchange" }
Q: No outlier detection in boxplot I would like to plot boxplots of dataframes (see sample code below). What I'm wondering is: How can I disable the detection of outlier? I don't want to remove them, I just want a plot which visualizes the data by marking 0%, 25%, 50% and 75% of the datapoints without considering any criteria for outliers etc. How do I have to modify my code to achieve this? Can I change the outlier detection criteria in a way that it behaves like disabled? I would be very grateful for any help and if there is already another threat about this (which I didn't find), I would be happy to get a link to it. Many thanks! Jordin import numpy as np import pandas as pd import matplotlib.pyplot as plt np.random.seed(1234) df = pd.DataFrame(np.random.randn(10, 4), columns=['Col1', 'Col2', 'Col3', 'Col4']) plt.figure() plt.boxplot(df.values) plt.show() EDIT: I would like to include this outlier when drawing the whiskers and not just not show it. A: You're looking for the whis parameter. For the documentation: whis : float, sequence, or string (default = 1.5) As a float, determines the reach of the whiskers to the beyond the first and third quartiles. In other words, where IQR is the interquartile range (Q3-Q1), the upper whisker will extend to last datum less than Q3 + whisIQR). Similarly, the lower whisker will extend to the first datum greater than Q1 - whisIQR. Beyond the whiskers, data are considered outliers and are plotted as individual points. Set this to an unreasonably high value to force the whiskers to show the min and max values. Alternatively, set this to an ascending sequence of percentile (e.g., [5, 95]) to set the whiskers at specific percentiles of the data. Finally, whis can be the string 'range' to force the whiskers to the min and max of the data. Add it like so: df.boxplot(whis=99)
{ "pile_set_name": "StackExchange" }
Q: My Rewrite folder doesn't work This is my .htaccess : AddDefaultCharset UTF-8 DefaultLanguage fr-FR Options -Indexes RewriteEngine on RewriteBase / <Files .htaccess> Order Allow,Deny Deny from all </Files> RewriteRule ^cle-usb-populaires/$ /top-cle-usb.php [QSA] RewriteRule ^informatique/$ /informatique.php [QSA] RewriteRule ^cles-usb/$ /informatique.php?groupe=usb [QSA] This Rewrite Work RewriteRule ^cle-usb-populaires/$ /top-cle-usb.php [QSA] This Rewrite DON'T Work RewriteRule ^informatique/$ /informatique.php [QSA] This Rewrite Work RewriteRule ^cles-usb/$ /informatique.php?groupe=usb [QSA] So i don't understand why the 1st & 3rd Rewrite work, not the 2nd ... :( Any idea ? A: This Rewrite Work RewriteRule ^cle-usb-populaires/$ /top-cle-usb.php [QSA] This Rewrite DON'T Work RewriteRule ^informatique/$ /informatique.php [QSA] It is most likely due to option MultiViews turned on. Turn it off using this line at top of your .htaccess: Options -MultiViews Option MultiViews (see http://httpd.apache.org/docs/2.4/content-negotiation.html) is used by Apache's content negotiation module that runs before mod_rewrite and makes Apache server match extensions of files. So if /file is the URL then Apache will serve /file.html.
{ "pile_set_name": "StackExchange" }
Q: Wordpress permalink with trailing slash give 404 I have the wordpress on this url: http://www.website.com/blog/ If I try to open any post the url only work as: http://www.website.com/blog/%postname% When I try to put trailing slash at the end it give error 404. http://www.website.com/blog/%postname%/ This is my .htaccess IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule> A: I found the error: It was URlScan It was blocking my Urls because some of them contain dots. example: http://website.com/blog/test-3.0/style/foo.css I opened up the UrlScan.ini file located: %windir%\system32\inetsrv\urlscan\UrlScan.ini And changed AllowDotInPath=0 to AllowDotInPath=1
{ "pile_set_name": "StackExchange" }
Q: A simple “printing” calculator When I'm typing in a digit I see Type in a digit 1 Type in an operator ERROR: Unknown operator! accumulator = 0.000000 Type in a digit Why step - printf("Type in an operator ") is skipped and is replaced by - default: printf ("ERROR: Unknown operator!\n"); break; Thanks for the help in advance! // Program to produce a simple printing calculator #include <stdio.h> #include <stdbool.h> int main (void) { double accumulator = 0.0, number; // The accumulator shall be 0 at startup char operator; bool isCalculating = true; // Set flag indicating that calculations are ongoing printf("You can use 4 operator for arithmetic + - / *\n"); printf("To set accumulator to some number use operator S or s\n"); printf("To exit from this program use operator E or e\n"); printf ("Begin Calculations\n"); while (isCalculating) // The loop ends when operator is = 'E' { printf("Type in a digit "); scanf ("%lf", &number); // Get input from the user. printf("Type in an operator "); scanf ("%c", &operator); // The conditions and their associated calculations switch (operator) { case '+': accumulator += number; break; case '-': accumulator -= number; break; case '*': accumulator *= number; break; case '/': if (number == 0) printf ("ERROR: Division by 0 is not allowed!"); else accumulator /= number; break; case 'S': case 's': accumulator = number; break; case 'E': case 'e': isCalculating = false; break; default: printf ("ERROR: Unknown operator!\n"); break; } printf ("accumulator = %f\n", accumulator); } printf ("End of Calculations"); return 0; } A: scanf for a char consumes the newline characters. So the scanned char is "linefeed" instead of the one you're expecting. I replaced: scanf ("%c", &operator); by scanf ("%*c%c", &operator); (consuming linefeed before the operator without assigning it using %*c format) and your code worked fine.
{ "pile_set_name": "StackExchange" }
Q: Looping through python function and savings inputs and function value in a matrix format I have a function, f, and I am trying to evaluate it at x, y and z: x = range(60,70) y = range(0,5) z = ["type1", "type2"] results = [f(v,w,j) for v in x for w in y for j in z] Right now "results" is a long vector, but I would like to get a matrix that looks something like this: x1 y1 z1 f(x1,y1,z1) x2 y1 z1 f(x2,y1,z1) ... x9 y1 z1 f(x9,y1,z1) x1 y2 z1 f(x1,y2,z1) x2 y2 z1 f(x2,y2,z1) ... x9 y2 z1 f(x9,y2,z1) x1 y1 z2 f(x1,y1,z2) ... covering all the possible combinations. So far I have tried this: z = [] for v in x: for w in y: for j in z: z = [v, w, j, f(v,w,j)] which is giving me the right format, but only evaluating one of the scenarios. Any guidance is appreciate it . Thanks! A: Here is program which might help you: x = range(60, 70) y = range(0,5) z = ["type1", "type2"] ans = [] for i in x: for j in y: for k in z: ans.append([i, j, k, f(i, j, k)]) print(ans)
{ "pile_set_name": "StackExchange" }
Q: r - import data, columns are character spaces I have a file containing data which I need to import into a dataframe but the setup of the file is quite terrible. the file I am trying to import is a list of 344 characters (32 colums, 445k rows). Each column is specific range of character spaces. Column 1 is character spaces 1:2 Column 2 is character spaces 3:6 Column 3 is character spaces 7:20 and so forth. data example: the.data <- list("32154The street", "12546The clouds", "23236The jungle") what I need it to look like col1 col2 col3 32 154 The street 12 546 The Clouds 23 236 The jungle What I've tried: substr(the.data, 1,2) substr(the.data, 3,6) substr(the.data, 7,20) and bind it together I would like to find a better solution I also tried to insert commas at the right character spaces, export it as a csv and re-import (or use textConnection) but ran into problems there. A: readr in the tidyverse can read fixed width data. library('tidyverse') read_fwf(paste(the.data, collapse='\n'), fwf_widths(c(2,3,15))) #> # A tibble: 3 x 3 #> X1 X2 X3 #> <int> <int> <chr> #> 1 32 154 The street #> 2 12 546 The clouds #> 3 23 236 The jungle
{ "pile_set_name": "StackExchange" }
Q: "sitemap-questions-0.xml" shows up in Google search results Google seems to be finding a "sitemap-questions-0.xml" on android.stackexchange.com. However, when I go to click on it, I get a 404 error. Here's the link that Google gives me: https://android.stackexchange.com/sitemap-questions-0.xml Here's a screenshot: Is this an old result from when Googlebot did its crawling, or does the file actually exist but return a 404 to prevent regular users from trying to access it? A: This is part of the site's Sitemap - a machine-readable directory for search engines. It's only served to search engines, since it can be quite large and isn't particularly useful to anyone else. Normally, this wouldn't show up in Google's search results - I would expect it to disappear eventually.
{ "pile_set_name": "StackExchange" }
Q: C++ pointer and stack memory management I have a General question about memory management in my c++ code. The compiler complains that there is a potential memory leak when I replace a pointer to an object with an new pointer to an object that I have initialized dynamically on the stack. Example: int* foo(int* h){ int* b = new int(5); b = h; //Memory leak here. How do I delete b without creating a dangling pointer? return b; } I then use this function to change the state of a pointer int i = 1; int* c = &i; foo(c); So my question is I have a class that has a function similar to the one above. when can I delete b from the foo function? delete b; would this go into the destructor (which would not help me, as I am using function foo loads of times. so the heap would get used up possibly....? ) If I have not provided enough info above. Please let me know. A: If you really want to replace the pointer's value with a new pointer allocated in the function, I would recommend using a reference: void SomeClass::foo(int*& h) { delete h; h = new int(5); } Of course, this will break if you call it with a pointer to an int which is not on the heap, since you can't delete it in that case. So don't do that. A: Since this is a general question, my preferred general approach would be to use a smart pointer handled using RAII within your class. The smart pointer encapsulates the raw pointer, and handles required memory management for you - when your class is destructed, whatever pointer value is held therein at the time will get cleaned up without you having to manually delete it. When you assign a new value to the smart pointer, it auto-deletes the existing value for you, if any. boost::scoped_ptr as a class member ought to work well for you here. There also seems to be confusion here about what's on the stack and what's on the heap. You will not use up the stack simply because you are calling foo over and over (unless you recurse into foo unbounded, in which case you will eventually run out of stack space). Your local variable b is on the stack, but it points to memory that is allocated using new on the heap. When you exit foo, the stack is reset for the calling function - the stack memory used for b is now available for the next function it calls - but you still need to retain ownership (and eventually release) the heap memory to which b pointed. EDIT: some sample code should clarify smart pointer approach class MyClass { public: MyClass() {} // no explicit init for myPointer needed ~MyClass() {} // frees up any pointer held in myPointer, no explicit delete needed void Foo(int* c) { myPointer.reset(c); // releases any existing value, takes ownership of c } private: boost::scoped_ptr<int> myPointer; // initially empty };
{ "pile_set_name": "StackExchange" }
Q: Taking over a project - What should I ask the previous programmer? I'm taking over a development of a commercial web site. This site was developed over two years by another programmer. It's mostly a one-man job (maintain and expand the site). I'll have a 2-3 days transition period when the other programmer will show me the system. But from what I know, there is little documentation. Everything is in the code (which is kind of documented). Here is what I'm planning to ask so far: Explanation on the most complex elements of the system Description of the overall architecture Description of the support tools (IDE setup, unit tests, deployment mechanism) Any book, website, podcast he used to influence the architecture of the system Any other I'm missing? [EDIT] Thanks everyone. Lost of good propositions. I wished I could accept more than one answer! Additionally, I would also add: What have you done specifically to improve the performance of the system, and where is the bottleneck right now? Related to that, what have you done regarding the security of the system? (what have you done, and where are the security holes right now) One last thing: the developer said that he will be available to to answer my questions later on if I need it. It's his "baby" after all. But I really think that in 6 months he will have moved on and his availability will be much more reduced! A: Before you look at the code: Clear the objs and the exes, and let him/her rebuild the thing. Watch for any manual interaction (does it build via "make" alone or is there some fiddling involved). Better yet: give him/her a naked (just bought) machine, let him/her demonstrate a checkout and rebuild. Then see how the app is started and comes up (any secret options to input?). Then: in a pair programming session, add one or two features to the system and see where and how these are implemented. The above may sound stupid, but I have seen projects where building alone was a nightmare, and a lot of knowledge was in the brain of the developer only. Not having a trusted build environment and having to figure out how to rebuild is a nighmare. A: Be sure to ask for all login information for the web servers, domain registrars, database servers, email servers, and anything else you can think of. It sounds crazy, but often times developers will register domain names with themselves as the administrative and technical contacts. The company will then have to jump through all sorts of hoops with the registrar in order to get the domain back, if the original programmer can't be contacted. A: "If you could go back and redevelop this system, what would you do differently"
{ "pile_set_name": "StackExchange" }
Q: Can I specify a verbose name in a manyToMany automatically generated model? I have the following models: class Doctor(models.Model): #some attributes... class Meta: verbose_name = _(u'doctor') verbose_name_plural = _(u'doctors') class Patient(models.Model): #some attributes... medical_consult = models.ManyToManyField(Doctor) class Meta: verbose_name = _('patient') verbose_name_plural = _('patients') Is there any way to set a verbose_name to the model Patient_doctor that is automatically created when I use the ManyToManyField? A: medical_consult = models.ManyToManyField(Doctor, through='PatientDoctor') # ... class PatientDoctor(models.Model): patient = models.ForeignKey(Patient) doctor = models.ForeignKey(Doctor) # ... class Meta: verbose_name = _('patient_doctor') # ...
{ "pile_set_name": "StackExchange" }
Q: improving write to file speed I have a program that writes output when it's finished, and a specific file takes a very large amount of time, and I was wondering if I could do something to improve its speed. This file ends up being 25 mbs or more it has around 17000 lines, each line having about 500 fields the way it works is: procedure CWaitList.WriteData(AFile : string; AReplicat : integer; AllFields : Boolean); var fout : TextFile; idx, ndx : integer; MyPat : CPatientItem; begin ndx := FList.Count - 1; AssignFile(fout, AFile); Append(fout); for idx := 0 to ndx do begin MyPat := CPatientItem(FList.Objects[idx]); if not Assigned(MyPat) then Continue; MyPat.WriteItem(fout, AReplicat, AllFields); end; CloseFile(fout); end; WriteItem is a procedure that gets all the values from MyPat and writes them to the file, and also calls 3 other functions that also write values to the file so overall, the WriteData loop ends up being around 1700 and each line ends up having around 500 fields I was just wondering if there is anything I could do to improve its performance or if it's always going to take a long time because of how much data it has to write thanks A: The right way to speed up a TextFile is to use SetTextBuf. And perhaps adding {$I-} .... {$I+} around all file access. var TmpBuf: array[word] of byte; .. {$I-} AssignFile(fout, AFile); Append(fout); SetTextBuf(fOut,TmpBuf); for idx := 0 to ndx do begin MyPat := CPatientItem(FList.Objects[idx]); if not Assigned(MyPat) then Continue; MyPat.WriteItem(fout, AReplicat, AllFields); end; if ioresult<>0 then ShowMessage('Error writing file'); CloseFile(fout); {$I+} end; In all cases, the old file API is not to be used nowadays... {$I-} .... {$I+} is to be added also around all your sub routines adding content to the text file. I've some experiment about huge text file and buffer creation. I've written a dedicated class in the Open Source SynCommons unit, named TTextWriter, which is UTF-8 oriented. I use it in particular for JSON production or LOG writing at highest possible speed. It avoid most temporary heap allocation (e.g. for conversion from an integer value), so it's even very good at multi-thread scaling. Some high-level methods are available to format some text from an open array, like the format() function, but much faster. Here is the interface of this class: /// simple writer to a Stream, specialized for the TEXT format // - use an internal buffer, faster than string+string // - some dedicated methods is able to encode any data with JSON escape TTextWriter = class protected B, BEnd: PUTF8Char; fStream: TStream; fInitialStreamPosition: integer; fStreamIsOwned: boolean; // internal temporary buffer fTempBufSize: Integer; fTempBuf: PUTF8Char; // [0..4] for 'u0001' four-hex-digits template, [5..7] for one UTF-8 char BufUnicode: array[0..7] of AnsiChar; /// flush and go to next char function FlushInc: PUTF8Char; function GetLength: integer; public /// the data will be written to the specified Stream // - aStream may be nil: in this case, it MUST be set before using any // Add*() method constructor Create(aStream: TStream; aBufSize: integer=1024); /// the data will be written to an internal TMemoryStream constructor CreateOwnedStream; /// release fStream is is owned destructor Destroy; override; /// retrieve the data as a string // - only works if the associated Stream Inherits from TMemoryStream: return // '' if it is not the case function Text: RawUTF8; /// write pending data to the Stream procedure Flush; /// append one char to the buffer procedure Add(c: AnsiChar); overload; {$ifdef HASINLINE}inline;{$endif} /// append two chars to the buffer procedure Add(c1,c2: AnsiChar); overload; {$ifdef HASINLINE}inline;{$endif} /// append an Integer Value as a String procedure Add(Value: Int64); overload; /// append an Integer Value as a String procedure Add(Value: integer); overload; /// append a Currency from its Int64 in-memory representation procedure AddCurr64(Value: PInt64); overload; /// append a Currency from its Int64 in-memory representation procedure AddCurr64(const Value: Int64); overload; /// append a TTimeLog value, expanded as Iso-8601 encoded text procedure AddTimeLog(Value: PInt64); /// append a TDateTime value, expanded as Iso-8601 encoded text procedure AddDateTime(Value: PDateTime); overload; /// append a TDateTime value, expanded as Iso-8601 encoded text procedure AddDateTime(const Value: TDateTime); overload; /// append an Unsigned Integer Value as a String procedure AddU(Value: cardinal); /// append a floating-point Value as a String // - double precision with max 3 decimals is default here, to avoid rounding // problems procedure Add(Value: double; decimals: integer=3); overload; /// append strings or integers with a specified format // - % = #37 indicates a string, integer, floating-point, or class parameter // to be appended as text (e.g. class name) // - $ = #36 indicates an integer to be written with 2 digits and a comma // - £ = #163 indicates an integer to be written with 4 digits and a comma // - µ = #181 indicates an integer to be written with 3 digits without any comma // - ¤ = #164 indicates CR+LF chars // - CR = #13 indicates CR+LF chars // - § = #167 indicates to trim last comma // - since some of this characters above are > #127, they are not UTF-8 // ready, so we expect the input format to be WinAnsi, i.e. mostly English // text (with chars < #128) with some values to be inserted inside // - if StringEscape is false (by default), the text won't be escaped before // adding; but if set to true text will be JSON escaped at writing procedure Add(Format: PWinAnsiChar; const Values: array of const; Escape: TTextWriterKind=twNone); overload; /// append CR+LF chars procedure AddCR; {$ifdef HASINLINE}inline;{$endif} /// write the same character multiple times procedure AddChars(aChar: AnsiChar; aCount: integer); /// append an Integer Value as a 2 digits String with comma procedure Add2(Value: integer); /// append the current date and time, in a log-friendly format // - e.g. append '20110325 19241502 ' // - this method is very fast, and avoid most calculation or API calls procedure AddCurrentLogTime; /// append an Integer Value as a 4 digits String with comma procedure Add4(Value: integer); /// append an Integer Value as a 3 digits String without any added comma procedure Add3(Value: integer); /// append a line of text with CR+LF at the end procedure AddLine(const Text: shortstring); /// append a String procedure AddString(const Text: RawUTF8); {$ifdef HASINLINE}inline;{$endif} /// append a ShortString procedure AddShort(const Text: ShortString); {$ifdef HASINLINE}inline;{$endif} /// append a ShortString property name, as '"PropName":' procedure AddPropName(const PropName: ShortString); /// append an Instance name and pointer, as '"TObjectList(00425E68)"'+SepChar // - Instance must be not nil procedure AddInstanceName(Instance: TObject; SepChar: AnsiChar); /// append an Instance name and pointer, as 'TObjectList(00425E68)'+SepChar // - Instance must be not nil procedure AddInstancePointer(Instance: TObject; SepChar: AnsiChar); /// append an array of integers as CSV procedure AddCSV(const Integers: array of Integer); overload; /// append an array of doubles as CSV procedure AddCSV(const Doubles: array of double; decimals: integer); overload; /// append an array of RawUTF8 as CSV procedure AddCSV(const Values: array of RawUTF8); overload; /// write some data as hexa chars procedure WrHex(P: PAnsiChar; Len: integer); /// write some data Base64 encoded // - if withMagic is TRUE, will write as '"\uFFF0base64encodedbinary"' procedure WrBase64(P: PAnsiChar; Len: cardinal; withMagic: boolean); /// write some #0 ended UTF-8 text, according to the specified format procedure Add(P: PUTF8Char; Escape: TTextWriterKind); overload; /// write some #0 ended UTF-8 text, according to the specified format procedure Add(P: PUTF8Char; Len: PtrInt; Escape: TTextWriterKind); overload; /// write some #0 ended Unicode text as UTF-8, according to the specified format procedure AddW(P: PWord; Len: PtrInt; Escape: TTextWriterKind); overload; /// append some chars to the buffer // - if Len is 0, Len is calculated from zero-ended char // - don't escapes chars according to the JSON RFC procedure AddNoJSONEscape(P: Pointer; Len: integer=0); /// append some binary data as hexadecimal text conversion procedure AddBinToHex(P: Pointer; Len: integer); /// fast conversion from binary data into hexa chars, ready to be displayed // - using this function with Bin^ as an integer value will encode it // in big-endian order (most-signignifican byte first): use it for display // - up to 128 bytes may be converted procedure AddBinToHexDisplay(Bin: pointer; BinBytes: integer); /// add the pointer into hexa chars, ready to be displayed procedure AddPointer(P: PtrUInt); /// append some unicode chars to the buffer // - WideCharCount is the unicode chars count, not the byte size // - don't escapes chars according to the JSON RFC // - will convert the Unicode chars into UTF-8 procedure AddNoJSONEscapeW(P: PWord; WideCharCount: integer); /// append some UTF-8 encoded chars to the buffer // - if Len is 0, Len is calculated from zero-ended char // - escapes chars according to the JSON RFC procedure AddJSONEscape(P: Pointer; Len: PtrInt=0); overload; /// append some UTF-8 encoded chars to the buffer, from a generic string type // - faster than AddJSONEscape(pointer(StringToUTF8(string)) // - if Len is 0, Len is calculated from zero-ended char // - escapes chars according to the JSON RFC procedure AddJSONEscapeString(const s: string); {$ifdef UNICODE}inline;{$endif} /// append some Unicode encoded chars to the buffer // - if Len is 0, Len is calculated from zero-ended widechar // - escapes chars according to the JSON RFC procedure AddJSONEscapeW(P: PWord; Len: PtrInt=0); /// append an open array constant value to the buffer // - "" will be added if necessary // - escapes chars according to the JSON RFC // - very fast (avoid most temporary storage) procedure AddJSONEscape(const V: TVarRec); overload; /// append a dynamic array content as UTF-8 encoded JSON array // - expect a dynamic array TDynArray wrapper as incoming parameter // - TIntegerDynArray, TInt64DynArray, TCardinalDynArray, TDoubleDynArray, // TCurrencyDynArray, TWordDynArray and TByteDynArray will be written as // numerical JSON values // - TRawUTF8DynArray, TWinAnsiDynArray, TRawByteStringDynArray, // TStringDynArray, TWideStringDynArray, TSynUnicodeDynArray, TTimeLogDynArray, // and TDateTimeDynArray will be written as escaped UTF-8 JSON strings // (and Iso-8601 textual encoding if necessary) // - any other kind of dynamic array (including array of records) will be // written as Base64 encoded binary stream, with a JSON_BASE64_MAGIC prefix // (UTF-8 encoded \uFFF0 special code) // - examples: '[1,2,3,4]' or '["\uFFF0base64encodedbinary"]' procedure AddDynArrayJSON(const DynArray: TDynArray); /// append some chars to the buffer in one line // - P should be ended with a #0 // - will write #1..#31 chars as spaces (so content will stay on the same line) procedure AddOnSameLine(P: PUTF8Char); overload; /// append some chars to the buffer in one line // - will write #0..#31 chars as spaces (so content will stay on the same line) procedure AddOnSameLine(P: PUTF8Char; Len: PtrInt); overload; /// append some wide chars to the buffer in one line // - will write #0..#31 chars as spaces (so content will stay on the same line) procedure AddOnSameLineW(P: PWord; Len: PtrInt); /// serialize as JSON the given object // - this default implementation will write null, or only write the // class name and pointer if FullExpand is true - use TJSONSerializer. // WriteObject method for full RTTI handling // - default implementation will write TList/TCollection/TStrings/TRawUTF8List // as appropriate array of class name/pointer (if FullExpand=true) or string procedure WriteObject(Value: TObject; HumanReadable: boolean=false; DontStoreDefault: boolean=true; FullExpand: boolean=false); virtual; /// the last char appended is canceled procedure CancelLastChar; {$ifdef HASINLINE}inline;{$endif} /// the last char appended is canceled if it was a ',' procedure CancelLastComma; {$ifdef HASINLINE}inline;{$endif} /// rewind the Stream to the position when Create() was called procedure CancelAll; /// count of add byte to the stream property TextLength: integer read GetLength; /// the internal TStream used for storage property Stream: TStream read fStream write fStream; end; As you can see, there is even some serialization available, and the CancelLastComma / CancelLastChar methods are very useful to produce fast JSON or CSV data from a loop. About speed and timing, this routine is faster than my disk access, which is around 100 MB / s. I think it can achieve around 500 MB / s when appending data in a TMemoryStream instead of a TFileStream. A: I haven't done it in a while, but you should be able to set a bigger text I/O buffer like this: var fout : TextFile; idx, ndx : integer; MyPat : CPatientItem; Buffer: array[0..65535] of char; // 64K - example begin ndx := FList.Count - 1; AssignFile(fout, AFile); SetTextBuf(fout, Buffer); Append(fout); A: Use Process Explorer from SysInternals to watch the output. I think you'll see that you're writing thousands or millions of little chunks. Using streaming I/O, where you write in one I/O operation, will dramatically improve things. http://live.sysinternals.com/procexp.exe
{ "pile_set_name": "StackExchange" }
Q: How to copy in a column of a dataframe the value of the previous row only 1 time? Everything is in the question. To illustrate, I have the following example: date <- c("01.02.2011","02.02.2011","03.02.2011","04.02.2011","05.02.2011","01.02.2011","02.02.2011","03.02.2011","04.02.2011","05.02.2011") date <- as.Date(date, format="%d.%m.%Y") ID <- c("A","A","A","A","A","B","B","B","B","B") indicator <- c(NA,NA,NA,"2.025",NA,NA,"6.777",NA,NA,NA) df <- data.frame(date, ID, indicator) So I have one dataframe looking like this: date ID indicator 1 2011-02-01 A <NA> 2 2011-02-02 A <NA> 3 2011-02-03 A <NA> 4 2011-02-04 A 2.025 5 2011-02-05 A <NA> 6 2011-02-01 B <NA> 7 2011-02-02 B 6.777 8 2011-02-03 B <NA> 9 2011-02-04 B <NA> 10 2011-02-05 B <NA> I would like to copy the values (so not NA) in the column indicator 1 time in the next row in order to obtain: date ID indicator 1 2011-02-01 A <NA> 2 2011-02-02 A <NA> 3 2011-02-03 A <NA> 4 2011-02-04 A 2.025 5 2011-02-05 A 2.025 6 2011-02-01 B <NA> 7 2011-02-02 B 6.777 8 2011-02-03 B 6.777 9 2011-02-04 B <NA> 10 2011-02-05 B <NA> I tried with: df[which(df$indicator != NA)+1, "indicator"] <- but I don't manage to find what I should put after "<-" to retrieve the corresponding values? My dataframe has in fact around 20000 rows so I cannot do it manually. If any editing is needed, do not hesitate to let me know. Thanks in advance for your help A: Here is a tidyverse approach. If the previous row indicator is not NA, then copy it. Otherwise, no change. Note I mutate the indicator column to character as it comes out a factor from the example dataframe provided. library(tidyverse) df %>% group_by(ID) %>% mutate(indicator = as.character(indicator)) %>% mutate(indicator = ifelse(!is.na(lag(indicator)), lag(indicator), indicator)) Output # A tibble: 10 x 3 # Groups: ID [2] date ID indicator <date> <fct> <chr> 1 2011-02-01 A NA 2 2011-02-02 A NA 3 2011-02-03 A NA 4 2011-02-04 A 2.025 5 2011-02-05 A 2.025 6 2011-02-01 B NA 7 2011-02-02 B 6.777 8 2011-02-03 B 6.777 9 2011-02-04 B NA 10 2011-02-05 B NA
{ "pile_set_name": "StackExchange" }
Q: How do I get CSV files into an Estimator in Tensorflow 1.6 I am new to tensorflow (and my first question in StackOverflow) As a learning tool, I am trying to do something simple. (4 days later I am still confused) I have one CSV file with 36 columns (3500 records) with 0s and 1s. I am envisioning this file as a flattened 6x6 matrix. I have another CSV file with 1 columnn of ground truth 0 or 1 (3500 records) which indicates if at least 4 of the 6 of elements in the 6x6 matrix's diagonal are 1's. I am not sure I have processed the CSV files correctly. I am confused as to how I create the features dictionary and Labels and how that fits into the DNNClassifier I am using TensorFlow 1.6, Python 3.6 Below is the small amount of code I have so far. import tensorflow as tf import os def x_map(line): rDefaults = [[] for cl in range(36)] x_row = tf.decode_csv(line, record_defaults=rDefaults) return x_row def y_map(line): line = tf.string_to_number(line, out_type=tf.int32) y_row = tf.one_hot(line, depth=2) return y_row x_path_file = os.path.join('D:', 'Diag', '6x6_train.csv') y_path_file = os.path.join('D:', 'Diag', 'HasDiag_train.csv') filenames = [x_path_file] x_dataset = tf.data.TextLineDataset(filenames) x_dataset = x_dataset.map(x_map) x_dataset = x_dataset.batch(1) x_iter = x_dataset.make_one_shot_iterator() x_next_el = x_iter.get_next() filenames = [y_path_file] y_dataset = tf.data.TextLineDataset(filenames) y_dataset = y_dataset.map(y_map) y_dataset = y_dataset.batch(1) y_iter = y_dataset.make_one_shot_iterator() y_next_el = y_iter.get_next() init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) x_el = (sess.run(x_next_el)) y_el = (sess.run(y_next_el)) The output for x_el is: (array([1.], dtype=float32), array([1.], dtype=float32), array([1.], dtype=float32), array([1.], dtype=float32), array([1.], dtype=float32), array([0.] ... it goes on... The output for y_el is: [[1. 0.]] A: You're pretty much there for a minimal working model. The main issue I see is that tf.decode_csv returns a tuple of tensors, where as I expect you want a single tensor with all values. Easy fix: x_row = tf.stack(tf.decode_csv(line, record_defaults=rDefaults)) That should work... but it fails to take advantage of many of the awesome things the tf.data.Dataset API has to offer, like shuffling, parallel threading etc. For example, if you shuffle each dataset, those shuffling operations won't be consistent. This is because you've created two separate datasets and manipulated them independently. If you create them independently, zip them together then manipulate, those manipulations will be consistent. Try something along these lines: def get_inputs( count=None, shuffle=True, buffer_size=1000, batch_size=32, num_parallel_calls=8, x_paths=[x_path_file], y_paths=[y_path_file]): """ Get x, y inputs. Args: count: number of epochs. None indicates infinite epochs. shuffle: whether or not to shuffle the dataset buffer_size: used in shuffle batch_size: size of batch. See outputs below num_parallel_calls: used in map. Note if > 1, intra-batch ordering will be shuffled x_paths: list of paths to x-value files. y_paths: list of paths to y-value files. Returns: x: (batch_size, 6, 6) tensor y: (batch_size, 2) tensor of 1-hot labels """ def x_map(line): rDefaults = [[] for cl in range(n_dims**2)] x_row = tf.stack(tf.decode_csv(line, record_defaults=rDefaults)) return x_row def y_map(line): line = tf.string_to_number(line, out_type=tf.int32) y_row = tf.one_hot(line, depth=2) return y_row def xy_map(x, y): return x_map(x), y_map(y) x_ds = tf.data.TextLineDataset(x_paths) y_ds = tf.data.TextLineDataset(y_paths) combined = tf.data.Dataset.zip((x_ds, y_ds)) combined = combined.repeat(count=count) if shuffle: combined = combined.shuffle(buffer_size) combined = combined.map(xy_map, num_parallel_calls=num_parallel_calls) combined = combined.batch(batch_size) x, y = combined.make_one_shot_iterator().get_next() return x, y To experiment/debug, x, y = get_inputs() with tf.Session() as sess: xv, yv = sess.run((x, y)) print(xv.shape, yv.shape) For use in an estimator, pass the function itself. estimator.train(get_inputs, max_steps=10000) def get_eval_inputs(): return get_inputs( count=1, shuffle=False x_paths=[x_eval_paths], y_paths=[y_eval_paths]) estimator.eval(get_eval_inputs)
{ "pile_set_name": "StackExchange" }
Q: Error: [$parse:syntax] when passing values as parameter in angular controller method I get an error in my developer console as such: Error: [$parse:syntax] http://errors.angularjs.org/1.6.5/$parse/syntax?p0=%7B&p1=invalid%20key&p2=43&p3=GetTimelineByUserIdAndProjectId(u.UserId%2C%7B%7BselectedProject.Id%7D%7D)&p4=%7BselectedProject.Id%7D%7D) angular $scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) { alert(userId +"-"+projectId); } HTML <div class="active tab-pane" id="view_projects"> <div> <form class="form-inline"> <select ng-model="selectedProject" class="selectpicker" data-live-search="true" ng-options="s.Description for s in allProjects track by s.Id" ng-change="getProjectsByUserId(selectedProject.Id)" select-picker></select> <select ng-model="selectedDeveloper" class="selectpicker" data-live-search="true" ng-options="u.ID as u.FullName for u in allUsers" select-picker></select> </form> </div> <br/> <div > <div class="panel panel-default" style="width:25%" ng-show="showUserTable"> <div class="panel-body"> <table class="table table-bordered table-hover"> <thead> <tr> <th>Developers for {{selectedProject.Description}}</th> </tr> </thead> <tbody> <tr ng-repeat="u in usersByProjectId"> <td ng-click="GetTimelineByUserIdAndProjectId(u.UserId,{{selectedProject.Id}})"><a href="javascript:void(0);"> {{u.Developer}}</a></td> </tr> </tbody> </table> </div> </div> </div> I should be able to get the "alert" when I click on the list. If I just get the u.userId I am actually able to get the alert with the value but when I add the {{selectedProject.Id}} that's when I get the error. A: Inside ng-click you don't need to put interpolation because you are already entering expression. We give {{interpolation}} to write expressions in HTML. In your case ng-click is already an expression so it you don't need that {{}} there in ng-click. you give GetTimelineByUserIdAndProjectId(u.UserId,selectedProject.Id)
{ "pile_set_name": "StackExchange" }
Q: What tools should I use to build my website? I'm looking to build a new website with user accounts and a few custom pages built from the account information. I have access to MySQL, PHP, Python, and Ruby, along with some of the standard CMS's: (WordPress, Drupal, Joomla, Django, etc) from my hosting provider (HostGator). I'm very comfortable with MySQL and Java, but haven't done any PHP and only a little Python. Would a CMS make sense? What areas is it likely to help with? what resources are there to help me get started with this sort of site? Thanks! Assuming I'm going to use PHP which excludes Django. WordPress seems very blog oriented. Is one of these CMS's more suited for a simple data-centric site? A: It really depends on what you want out of your site, Joomla is cool but is too much for a simple site with less then 10 pages. You can go with anything just keep the User and content management in mind. But if you care lots for your design, then go and have search for template in area that you want your site and then make the decision for CMS! A: PHP and Python are both easy to learn; PHP is more widely used, Python is (in my opinion) a cleaner language. YMMV. Wordpress, Drupal, and Joomla are "ready-to-go" with minimal set-up; Django is more of a "write your own CMS" product. My suggestion would be to start with WordPress right now - by the time you start running into things WordPress won't do for you, you will be much better informed for choosing a replacement.
{ "pile_set_name": "StackExchange" }
Q: Python non-int float Alright so I have beat my head over my desk for a few days over this one and I still cannot get it I keep getting this problem: Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 44, in <module> File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 35, in main File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in __init__ builtins.TypeError: can't multiply sequence by non-int of type 'float' over and over. I think I have hit the wall and really I have done a ecent amount of looking and testing but if anyone could point me in teh right direction it would be greatly appreciated. from math import pi, sin, cos, radians def getInputs(): a = input("Enter the launch angle (in degrees): ") v = input("Enter the initial velocity (in meters/sec): ") h = input("Enter the initial height (in meters): ") t = input("Enter the time interval between position calculations: ") return a,v,h,t class Projectile: def __init__(self, angle, velocity, height): self.xpos = 0.0 self.ypos = height theta = pi *(angle)/180 self.xvel = velocity * cos(theta) self.yvel = velocity * sin(theta) def update(self, time): self.xpos = self.xpos + time * self.xvel yvel1 = self.yvel - 9.8 * time self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 self.yvel = yvel1 def getY(self): "Returns the y position (height) of this projectile." return self.ypos def getX(self): "Returns the x position (distance) of this projectile." return self.xpos def main(): a, v, h, t = getInputs() cball = Projectile(a, v, h) zenith = cball.getY() while cball.getY() >= 0: cball.update(t) if cball.getY() > zenith: zenith = cball.getY() print ("/n Distance traveled: {%0.1f} meters." % (cball.getY())) print ("The heighest the cannon ball reached was %0.1f meters." % (zenith)) if __name__ == "__main__": main() A: Your input functions return strings, not numeric types. You need to convert them to integers or floats first as appropriate. I think the particular error you're seeing is when you try to calculate theta. You multiply pi (a floating-point number) by angle (which holds a string). The message is telling you that you can't multiply a string by a float, but that you could multiply a string by an int. (E.g. "spam" * 4 gives you "spamspamspamspam", but "spam" * 3.14 would make no sense.) Unfortunately, that's not a very helpful message, because for you it's not pi that's the wrong type, but angle, which should be a number. You should be able to fix this by changing getInputs: def getInputs(): a = float(input("Enter the launch angle (in degrees): ")) v = float(input("Enter the initial velocity (in meters/sec): ")) h = float(input("Enter the initial height (in meters): ")) t = float(input("Enter the time interval between position calculations: ")) return a,v,h,t I should also note that this is an area where Python 2.* and Python 3.* have different behaviour. In Python 2.* , input read a line of text and then evaluated it as a Python expression, while raw_input read a line of text and returned a string. In Python 3.* , input now does what raw_input did before - reads a line of text and returns a string. While the 'evaluate it as an expression' behaviour could be helpful for simple examples, it was also dangerous for anything but a trivial example. A user could type in any expression at all and it would be evaluated, which could do all sorts of unexpected things to your program or computer.
{ "pile_set_name": "StackExchange" }
Q: How to select mysql SUM from multiple tables and other columns from another table? I have three tables: cash, cheque and bill. All three tables share two common columns: billId and customerId. Bill Table +--------+------------+---------+------------+ | billId | date | bAmount | customerId | +--------+------------+---------+------------+ | #1 | 01-05-2016 | 120.00 | 2 | +--------+------------+---------+------------+ | #2 | 10-05-2016 | 100.00 | 2 | +--------+------------+---------+------------+ | #3 | 20-05-2016 | 80.00 | 2 | +--------+------------+---------+------------+ | #4 | 20-05-2016 | 70.00 | 2 | +--------+------------+---------+------------+ | #5 | 27-05-2016 | 50.00 | 2 | +--------+------------+---------+------------+ | #6 | 28-05-2016 | 20.00 | 2 | +--------+------------+---------+------------+ Cheque Table +----------+--------+------------+----------+ | chequeId | billId | customerId | chAmount | +----------+--------+------------+----------+ | 1 | #1 | 2 | 50.00 | +----------+--------+------------+----------+ | 2 | #2 | 2 | 25.00 | +----------+--------+------------+----------+ | 3 | #5 | 2 | 36.00 | +----------+--------+------------+----------+ | 4 | #4 | 2 | 23.00 | +----------+--------+------------+----------+ Cash Table +--------+--------+------------+----------+ | cashId | billId | customerId | caAmount | +--------+--------+------------+----------+ | 1 | #1 | 2 | 55.00 | +--------+--------+------------+----------+ | 2 | #2 | 2 | 70.00 | +--------+--------+------------+----------+ | 3 | #3 | 2 | 69.00 | +--------+--------+------------+----------+ | 4 | #4 | 2 | 23.00 | +--------+--------+------------+----------+ I have to generate a query to generate results like below: +--------+------------+--------+---------+ | billId | date | amount | pending | +--------+------------+--------+---------+ | #1 | 01-05-2016 | 120.00 | 15.00 | +--------+------------+--------+---------+ | #2 | 10-05-2016 | 100.00 | 05.00 | +--------+------------+--------+---------+ | #3 | 20-05-2016 | 80.00 | 11.00 | +--------+------------+--------+---------+ | #4 | 20-05-2016 | 70.00 | 14.00 | +--------+------------+--------+---------+ | #5 | 27-05-2016 | 50.00 | 04.00 | +--------+------------+--------+---------+ I am sending a value for customerID to this page from another page, like $customerId = $_REQUEST['customerId'] and from this I have to select BillId and Date from the Bill Table, amount (which is computed by the sum of chAmount+caAmount), and pending (which is computed by the difference of bAmount-(chAmount+caAmount)). Since billId #6 doesn't have any records in the cheque and cash tables it doesn't need to be yielded in the results. Please mention a proper MySql query and explain it. A: Normally, you should try something but as I am in my "good days" I wrote the full SQL statement : SELECT b.billId, b.bDate, b.bAmount, SUM(ch.chAmount) chAmountSum, SUM(ca.caAmount) caAmountSum, (b.bAmount - ( IFNULL(SUM(ch.chAmount), 0) + IFNULL(SUM(ca.caAmount), 0))) pending FROM bill b LEFT JOIN cheque ch on ch.billId = b.billId LEFT JOIN cash ca on ca.billID = b.billId GROUP BY b.billID; You have to select all columns that you want to display For the last one (pending), make your operation (amount - (cheque + cash)) and if it is a null value, replace it by "0" thanks to IFNULL SQL function Use LEFT JOIN because you want all bills even if there is no associated payment yet (cheque / cash) GROUP BY from your reference column : billID
{ "pile_set_name": "StackExchange" }
Q: creating users with Django REST Framework - not authenticate I am working with Django users, and I've hashed the passwords when I create an user with Django REST Framework and I override the create and update methods on my serializer to hash my passwords users class UserSerializer(serializers.ModelSerializer): #username = models.CharField() def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def update(self, instance, validated_data): for attr, value in validated_data.items(): if attr == 'password': instance.set_password(value) else: setattr(instance, attr, value) instance.save() return instance class Meta: model = User fields = ('url', 'username', 'password', 'first_name','last_name', 'age', 'sex', 'photo', 'email', 'is_player', 'team', 'position', 'is_staff', 'is_active', 'is_superuser', 'is_player', 'weight', 'height', 'nickname', 'number_matches', 'accomplished_matches', 'time_available', 'leg_profile', 'number_shirt_preferred', 'team_support', 'player_preferred', 'last_login', ) My views.py is this: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', ) My REST_FRAMEWORK settings are: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'PAGE_SIZE': 10 } The inconvenient that I have is that when I create and user via rest framework, the password is hashed, but I cannot sign in or login via rest authentication and Django admin too. How to can I hash my passwords and sign in via Djago REST FRamework too? Best Regards A: Add rest framework authentication setting with following also 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) Ref http://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication And for token autentication go through doc http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
{ "pile_set_name": "StackExchange" }
Q: Running ffmpeg.exe through windows service fails to complete while dealing with large files I am using ffmpeg.exe to convert video files to flv format. For that purpose i use a windows service to run the conversion process in background. While trying to convert large files(i experienced it when the file size is >14MB) through windows service it gets stuck at the line which starts the process(ie, process.start();). But when i tried to execute ffmpeg.exe directly from command prompt it worked with out any problems. My code in windows service is as follows: private Thread WorkerThread; protected override void OnStart(string[] args) { WorkerThread = new Thread(new ThreadStart(StartHandlingVideo)); WorkerThread.Start(); } protected override void OnStop() { WorkerThread.Abort(); } private void StartHandlingVideo() { FilArgs = string.Format("-i {0} -ar 22050 -qscale 1 {1}", InputFile, OutputFile); Process proc; proc = new Process(); try { proc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe"; proc.StartInfo.Arguments = FilArgs; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; eventLog1.WriteEntry("Going to start process of convertion"); proc.Start(); string StdOutVideo = proc.StandardOutput.ReadToEnd(); string StdErrVideo = proc.StandardError.ReadToEnd(); eventLog1.WriteEntry("Convertion Successful"); eventLog1.WriteEntry(StdErrVideo); } catch (Exception ex) { eventLog1.WriteEntry("Convertion Failed"); eventLog1.WriteEntry(ex.ToString()); } finally { proc.WaitForExit(); proc.Close(); } How can I get rid of this situation. A: It seems you caught a deadlock because you performed a synchronous read to the end of both redirected streams. A reference from MSDN: There is a similar issue when you read all text from both the standard output and standard error streams. The following C# code, for example, performs a read operation on both streams. // Do not perform a synchronous read to the end of both // redirected streams. // string output = p.StandardOutput.ReadToEnd(); // string error = p.StandardError.ReadToEnd(); // p.WaitForExit(); // Use asynchronous read operations on at least one of the streams. p.BeginOutputReadLine(); string error = p.StandardError.ReadToEnd(); p.WaitForExit(); The code example avoids the deadlock condition by performing asynchronous read operations on the StandardOutput stream. A deadlock condition results if the parent process calls p.StandardOutput.ReadToEnd followed by p.StandardError.ReadToEnd and the child process writes enough text to fill its error stream. The parent process would wait indefinitely for the child process to close its StandardOutput stream. The child process would wait indefinitely for the parent to read from the full StandardError stream. You can use asynchronous read operations to avoid these dependencies and their deadlock potential. Alternately, you can avoid the deadlock condition by creating two threads and reading the output of each stream on a separate thread.
{ "pile_set_name": "StackExchange" }
Q: Spring create unique @Component for every POST request Say I have a Spring validator that is annotated with @Component. This validator runs every time a POST request comes in. It is @Autowired in to the controller. Problem here is that the validator is a singleton by default. It also contains a list storing any and all errors. Everytime this validator is called, the list is emptied. My worry is that if multiple requests come in at the same time, this validator would break. Is there anyway to still utilize the power of Spring Boot but make sure that everytime the @PostMapping is called, the instance gets a new fresh validator only for itself? A: Use @Component @Scope(WebApplicationContext.SCOPE_REQUEST) to ensure that for each Request an own component is created. Or @RequestScope @Component
{ "pile_set_name": "StackExchange" }
Q: Excel VBA embedded FOR Loop to exclude cells from the outer conditional Starting with the following code: Dim lastRow As Long With ActiveSheet lastRow = .Range("C" & .Rows.Count).End(xlUp).Row End With Dim HeadCell As Range For Each HeadCell In Range("C1:C" & lastRow) If Len(HeadCell) < 6 And Len(HeadCell) > 1 Then HeadCell.Select With Selection.Font .Bold = True .Underline = xlUnderlineStyleSingle End With Else End If ActiveCell.Offset(1, 0).Select Next This works so far as I expected. It goes thru my worksheet scanning column "C" for values of a certain length and then formats it accordingly. What I'd prefer it do is check if the cell was any other particular value, and if true, ignore the formatting requirement and move on to the next cell as per usual. I thought that adding an embedded For loop would do this, but my logic must be wrong because it essentially ignores the For loop completely and runs it as normal. If Len(HeadCell) < 6 And Len(HeadCell) > 1 Then For i = 1 To 99 If HeadCell = i Then Exit For End If Next i I'm actually looking for to ignore cells that have values equal 1 thru 99. That's not a typo. If the HeadCell has a value equal to 1 thru 99, then ignore the formatting part of the original conditional and move on to the next cell. A: There are 2 ways to solve the issue: Using an IF Just add a second if statement in your for loop and place the code inside that if. (see the 2 separate lines in the code below for what to add) Your for loop code would look like this: For Each HeadCell In Range("C1:C" & lastRow) If Len(HeadCell) < 6 And Len(HeadCell) > 1 Then if HeadCell <= 0 OR HeadCell >= 100 then HeadCell.Select With Selection.Font .Bold = True .Underline = xlUnderlineStyleSingle End With End If Else End If ActiveCell.Offset(1, 0).Select Next Continue in the for loop You tried to continue with the first loop, but exit for just exits that loop. You're looking for Next nextcell
{ "pile_set_name": "StackExchange" }
Q: Loading large Images into Listview So my Listview has been lagging, because I am loading too many Pictures into it. So I searched the web and found two particular ideas to solve the problem: using a AsyncTask, as mentioned here downscaling the images, as mentioned here So since I am new to Developing with Android I gave the AsyncTask a shot and failed. The examples I have seen, were mostly using URLs to download pictures, and since I am using a sqlite DB I just couldn't get the examples to work for me. So here is my try: static class ViewHolder { TextView imageTextView; ImageView favImageView; int position; } //Constructor for List Items private class favImagesListAdapter extends ArrayAdapter<FavImages>{ private LayoutInflater mInflater = LayoutInflater.from(context); public favImagesListAdapter(){ super (MainActivity.this, R.layout.listview_item, FavImages); } @Override public View getView (final int position, View convertView, ViewGroup parent){ ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.listview_item, parent, false); holder = new ViewHolder(); holder.imageTextView = (TextView) convertView.findViewById(R.id.favName); holder.favImageView = (ImageView) convertView.findViewById(R.id.favImage); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } FavImages currentFav = FavImages.get(position); holder.imageTextView.setText(currentFav.getImageName()); new AsyncTask<ViewHolder, Void, Bitmap>() { private ViewHolder v; @Override protected Bitmap doInBackground(ViewHolder... params) { v = params[0]; return mFakeImageLoader.getImage(); } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); if (v.position == position) { // If this item hasn't been recycled already, hide the // progress and set and show the image //v.progress.setVisibility(View.GONE); v.favImageView.setVisibility(View.VISIBLE); v.favImageView.setImageBitmap(result); } } }.execute(holder); //old Version that causes lags ContentResolver cr = getContentResolver(); try { holder.favImageView.setImageBitmap(MediaStore.Images.Media.getBitmap(cr, currentFav.getImagePath())); } catch (IOException e) { e.printStackTrace(); } return convertView; } } Since I didn't have a reference what the FakeImageLoader does, I tried to reduce the size of the Images in there, but it didn't work, so I took a reference Code I found on a google Site like so: public class FakeImageLoader { private Bitmap mBmp; public FakeImageLoader(Context cxt) { mBmp= BitmapFactory.decodeResource(cxt.getResources(), R.drawable.ic_launcher); } public Bitmap getImage() { try { Thread.sleep(new Random().nextInt(5000)); } catch (InterruptedException e) { e.printStackTrace(); } return mBmp; } } But using that class just caused errors (because used for something totally different?). So I am asking, what do I need the FakeImageLoader (maybe not that good of a name) to do, to load the images best (guessing just have to scale the images down) and mostly how do I do it. I have also read about Picasso, but I want to keep the App small and learn by doing (or asking). If more code helps I will do so if asked. Edit: Using the FakeImageLoader class did not work (actually pretty obvious), so I changed my whole ListAdapter with the Asynctask to this: static class ViewHolder { TextView imageTextView; ImageView favImageView; int position; } //Constructor for List Items private class favImagesListAdapter extends ArrayAdapter<FavImages>{ private LayoutInflater mInflater = LayoutInflater.from(context); public favImagesListAdapter(){ super (MainActivity.this, R.layout.listview_item, FavImages); } @Override public View getView (final int position, View convertView, ViewGroup parent){ ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.listview_item, parent, false); holder = new ViewHolder(); holder.imageTextView = (TextView) convertView.findViewById(R.id.favName); holder.favImageView = (ImageView) convertView.findViewById(R.id.favImage); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final FavImages currentFav = FavImages.get(position); holder.imageTextView.setText(currentFav.getImageName()); class MyAsyncTask extends AsyncTask<ViewHolder, Void, Bitmap> { private ViewHolder v; @Override protected Bitmap doInBackground(ViewHolder... params) { v = params[0]; return getImage(); } private Bitmap getImage() { Bitmap mBmp; ContentResolver cr = getContentResolver(); MainActivity.ViewHolder holder = null; com.adrianopaulus.favoriten.FavImages currentFav1 = FavImages.get(position); try { mBmp = holder.favImageView.setImageBitmap(MediaStore.Images.Media.getBitmap(cr, currentFav1.getImagePath())); return mBmp; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } //return mBmp; } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); if (v.position == position) { // If this item hasn't been recycled already, hide the // progress and set and show the image //v.progress.setVisibility(View.GONE); v.favImageView.setVisibility(View.VISIBLE); v.favImageView.setImageBitmap(result); } } }MyAsyncTask.execute((Runnable) holder); return convertView; } } But it some has a Problem with following line: mBmp = holder.favImageView.setImageBitmap(MediaStore.Images.Media.getBitmap(cr, currentFav1.getImagePath())); and I don't know what I am doing wrong. A: Make use of Universal image loader library. This load images asynchronously and it doesn't lags your listview. https://github.com/nostra13/Android-Universal-Image-Loader It has an example in it. Enjoy :)
{ "pile_set_name": "StackExchange" }
Q: Google signIn tokenId is invalid_token I need to get google+ signIn tokenId. Here is my code: var mGSO = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(WEB_CLIENT_ID)//from developer console .requestEmail() .build() mGoogleApiClient = GoogleApiClient.Builder(mActivity) .enableAutoManage(mActivity, this) .addApi(Auth.GOOGLE_SIGN_IN_API, mGSO) .build() override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data) var tokenId = result.signInAccount.idToken } So I successfully get tokenId, but when I try to check it here (https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=) I receive message: { "error": "invalid_token", "error_description": "Invalid Value" } Token the same every time I try to get it! What is happening? Any idea how to fix this? UPDATE found this issue: https://github.com/PhilipGarnero/django-rest-framework-social-oauth2/issues/61 I was using the wrong google token from my sign-in on iOS. I originally used user.authentication.idToken which is wrong, and will not work. The correct token is user.authentication.accessToken. but i cant find any similar accessToken at GoogleSignInResult object.... UPDATE 2 i am using debug apk. here is my button click code: fun onGooglePlusClicked(v: View) { val signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient) mActivity?.startActivityForResult(signInIntent, GOOGLE_SIGN_IN) } A: The answer was founded here: https://developers.google.com/identity/protocols/CrossClientAuth key words: GoogleAuthUtil.getToken() so, here is my updated code: override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data) Observable.create(Observable.OnSubscribe<String> { var **accessTokent** = GoogleAuthUtil.getToken(mActivity!!, result.signInAccount.account, "oauth2:" + Scopes.PLUS_LOGIN) //send token to server }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe() } hope this will help someone :)
{ "pile_set_name": "StackExchange" }
Q: HTML5 Javascript: How to Make Sure a Drawn Object Cannot Leave the Canvas I have the following assignment problem that I'm struggling to solve: Write an application that uses a canvas element to create two circles (with different colors) in two different parts of the canvas. The circle should be able to be dragged within the canvas, and should stop when it gets to the edges. Put another way, the edge of the circle should not go past the edge of the canvas. Each circle should be dragged separately. When you release the mouse button, the circle should stop. So far I've created the two circles, however, I'm having trouble with the part where I have to make it so that the two circles can be dragged but not off the canvas. I'm quite sure this is supposed to be done with an event listener but I can't figure out how to code this. Would greatly appreciate some assistance or insight. What I have so far: <!DOCTYPE html> <html> <head> <script> window.onload = draw; function draw(){ var canvas = document.getElementById("circleCanvas"); var ctx = canvas.getContext("2d"); ctx.arc(100,75,50,0,2*Math.PI); ctx.fillStyle = "green"; ctx.fill(); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.arc(100,200,50,0,2*Math.PI); ctx.fillStyle = "blue"; ctx.fill(); ctx.stroke(); ctx.closePath(); } </script> </head> <body> <canvas id="circleCanvas" width="500" height="500"></canvas> </body> </html> A: Simple canvas drag and drop. Create a mouse object and set the mouse positions and button state by listening to the mouse events. Create an array of circles that describe the position and size of the each circle. Create a function to draw a circle. In that function you check if the circle is out of bounds and move it if it is. Create a position search function that checks each circle and how far it is from a point. If the circle is under the point (dist < circle.radius) then return a referance to that circle. Create a animation loop that redraws the canvas every 1/60th of a second. In that check if the mouse is down. If it is and not dragging anything see if the mouse is over a circle. If it is select that circle for dragging. When the mouse is up drop the circle. As it is an assignment we should not just give you the solution. But school is the only time in life when we are not allowed to ask for help, the time when we most need it. I assume that you are interested in learning and learning by example is in many situations the best. If you have any questions please do ask "use strict"; const canvas = document.createElement("canvas"); canvas.height = innerHeight; canvas.width = innerWidth; canvas.style.position = "absolute"; canvas.style.top = canvas.style.left = "0px"; const ctx = canvas.getContext("2d"); document.body.appendChild(canvas); ctx.font = "48px arial"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; var w = canvas.width; var h = canvas.height; var renderUpdate = true; // flags if there is a need to render var globalTime = 0; const mouse = { x:0,y:0,button:false }; const circles = [{ x : 100, y : 100, radius : 40, col : "red", lineWidth : 4, highlight : false, },{ x : 200, y : 100, radius : 40, col : "green", lineWidth : 4, highlight : false, }, ]; var closestCircle; // holds result of function findClosestCircle2Point const drag = { // if dragging this holds the circle being dragged circle : null, offsetX : 0, // distance from mouse to circle center when drag started offsetY : 0, } const message = { // a message to inform of problems. time : 120, // 60 ticks per second text: "Click drag circles", } // adds mouse events listeners canvas.addEventListener("mousemove",mouseEvent) canvas.addEventListener("mousedown",mouseEvent) canvas.addEventListener("mouseup",mouseEvent) // function to handle all mouse events function mouseEvent(e){ var m = mouse; var bounds = canvas.getBoundingClientRect(); m.x = e.clientX - bounds.left; m.y = e.clientY - bounds.top; if(e.type === "mousedown"){ m.button = true; }else if(e.type === "mouseup"){ m.button = false; } renderUpdate = true; // flag that there could be a render change. } // this finds the closest circle under x,y if nothing under the point then retVal.circle = null function findClosestCircle2Point(x, y, retVal){ if(retVal === undefined){ retVal = {}; } var minDist = Infinity; var dist; var xx,yy; retVal.circle = null; for(var i = 0; i < circles.length; i ++){ xx = x - circles[i].x; yy = y - circles[i].y; dist = Math.sqrt(xx*xx+yy*yy); if(dist < minDist && dist <= circles[i].radius){ minDist = dist; retVal.circle = circles[i]; } } return retVal; } // this draws a circle, adds highlight if needed and makes sure the circle does not go outside the canvas function drawCircle(circle){ var c = circle; var rad = c.radius + c.lineWidth / 2; // get radius plus half line width // keep circle inside canvas c.x = c.x - rad < 0 ? c.x = rad : c.x + rad >= w ? c.x = w-rad : c.x; c.y = c.y - rad < 0 ? c.y = rad : c.y + rad >= h ? c.y = h-rad : c.y; ctx.lineWidth = 4; if(c.highlight){ // highlight the circle if needed ctx.strokeStyle = "#0F0"; ctx.globalAlpha = 0.5; ctx.beginPath(); ctx.arc(c.x,c.y,c.radius + c.lineWidth,0,Math.PI * 2); ctx.stroke(); c.highlight = false; } // draw the circle ctx.fillStyle = c.col; ctx.strokeStyle = c.col; ctx.globalAlpha = 0.5; ctx.beginPath(); ctx.arc(c.x,c.y,c.radius,0,Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; ctx.stroke(); } // main update function function update(time){ globalTime = time; requestAnimationFrame(update); // get the next animation frame. if(!renderUpdate ){ // don't render if there is no need return; } renderUpdate = false; ctx.clearRect(0,0,w,h); // when not dragging look for the closest circle under the mouse and highlight it if(drag.circle === null){ closestCircle = findClosestCircle2Point(mouse.x,mouse.y,closestCircle); if(closestCircle.circle !== null){ closestCircle.circle.highlight = true; } } if(mouse.button){ // if the mouse is down start dragging if circle is under mouse if(drag.circle === null){ if(closestCircle.circle !== null){ drag.circle = closestCircle.circle; drag.offsetX = mouse.x - drag.circle.x; drag.offsetY = mouse.y - drag.circle.y; }else{ mouse.button = false; } }else{ drag.circle.x = mouse.x - drag.offsetX; drag.circle.y = mouse.y - drag.offsetY; } }else{ // drop circle drag.circle = null; } for(var i = 0; i < circles.length; i ++){ // draw all circles drawCircle(circles[i]); } // display any messages if needed. if(message.time > 0){ message.time -= 1; ctx.fillStyle = "black"; ctx.fillText(message.text,w/2,h/2); renderUpdate = true; // while message is up need to render. } } requestAnimationFrame(update); // start the whole thing going.
{ "pile_set_name": "StackExchange" }
Q: Using the iPad Pro with Apple digital AV Adapter and headphone jack adapter I am using the digital AV USB-C to connect my iPad to an external display via HDMI. Now I want to connect external speakers via a headphone jack. I plugged the AV adapter into the iPad, plugged HDMI into the adapter and plugged the headphone jack in the AV adapter using the USB-C headphone jack adapter from apple. (I used the USB-C Port of the AV adapter). The iPad does not recognize the external speakers, and the audio is coming out of the iPad speakers. I cannot change this in the control center. Is the AV Adapter capable of routing audio to its USB-C port? Or am I missing something? A: The USB-C port on the Digital AV Multiport adapter is for charging only. It doesn't carry any data at all - and therefore also not sound.
{ "pile_set_name": "StackExchange" }
Q: Mysql performance: 1 query over 3 tables or 2 queries? I need data from 3 different tables: Catergory table Scoretable 1 Scoretable 2 What is now better for the performance? Make 3 seperated SELECT Queries Make 2 queries and connect scoretable 1 and 2 and make a normal select query for the categories Connect all 3 queries in 1? Number 2: SELECT scoretable1.category, scoretable1.score, scoretable2.score FROM scoretable1, scoretable2 WHERE scoretable1.consultant = scoretable2.consultant AND scoretable2.consultant = '14' AND scoretable1.category = scoretable2.category Thank you very much! P.S. The category table is very small so I could export it also as a cache file as a serialized array? (Maybe the best way for this table) A: My guess would be that it is best to do it in one query. But i'm not absolutely sure. Maybe the query analyser can help you out here.
{ "pile_set_name": "StackExchange" }
Q: How to remove warning: link.res contains output sections; did you forget -T? I'm using fpc compiler and I want to remove this warning. I've read fpc's options but I can't find how to do that. Is this possible? it appear when I run command: fpc foo.pas out: Target OS: Linux for i386 Compiling foo.pas Linking p2 /usr/bin/ld: warning: link.res contains output sections; did you forget -T? 79 lines compiled, 0.1 sec A: It's a bug in certain LD versions. Just ignore it for now, or see if your distro has an update for your LD. (package binutils) http://www.freepascal.org/faq.var#unix-ld219 A: It‘s not a bug because ld behaves like its specification. The man page of ld 2.28 reads: If the linker cannot recognize the format of an object file, it will assume that it is a linker script. A script specified in this way augments the main linker script used for the link (either the default linker script or the one specified by using -T). This feature permits the linker to link against a file which appears to be an object or an archive, but actually merely defines some symbol values, or uses "INPUT" or "GROUP" to load other objects. Specifying a script in this way merely augments the main linker script, with the extra commands placed after the main script; use the -T option to replace the default linker script entirely, but note the effect of the "INSERT" command. TL;DR ☺. In a nutshell: In most cases the users are not aware of the linker script they are using because a “main script” (= default script) is provided by the tool chain. The main script heavily refers to intrinsics of the compiler-generated sections and you have to learn the ropes to change it. Most users do not. The common approach to provide your own script is via the -T option. That way the main linker script is ignored and your script takes over control over the linkage. But you have to write everything from scratch. If you just want to add a minor feature, you can write your specs into a file and append the file name to the command line of ld (or gcc / g++) without the -T option. That way the main linker script still does the chief work but your file augments it. If you use this approach, you get the message of the header of this thread to inform you that you might have provided a broken object unintentionally. The source of this confusion is that there is no way to specify the rôle of the additional file. This could easily be resolved by adding another option to ld just like the -dT option for “default scriptfile”: Introduce a -sT option for “supplemental scriptfile”.
{ "pile_set_name": "StackExchange" }
Q: localscroll's hash option, flickers the page when scrolling. How can I make the scrolling smooth I'm implementing a jquery plugin (localscroll) to smooth scroll to named anchor elements withing a page. localscroll supports an option called 'hash', what it basically does is it appends the named anchor hash into the URL making it easy for the user to bookmark and move using the browser back/forward buttons. HTML <ul id="navigation" class="main_menu"> <li><a href="#panel_home">Home</a></li> <li><a href="#panel_story">Story</a></li> <li><a href="#panel_mantra">Mantra</a></li> <li><a href="#panel_showcase">Showcase</a></li> <li><a href="#panel_experience">Experience Us</a></li> </ul> Javascript (jquery) $(document).ready(function () { $("#navigation").localScroll({ offset: {left: 0, top: -56}, hash: true, easing: 'easeInOutExpo' }); }); The above code runs fine, but whenever a link is clicked the scrolling starts with a flicker (probably because the default behavior of the browser is to jump to the named anchor). This flicker thing is more visible in Firefox than Chrome or Safari and is a big NO-NO. How can I make the transition smooth with the address bar reflecting the current named anchor?? Any help is much appreciated. Thanx! A: I found out why my page was flickering upon clicking the links mapped with localscroll. I was including the jquery.js file after the localscroll.js file, which was causing this strange behavior. So, I included all the minified versions of jquery, localscroll, easing and other javascripts that I was using in my scripts in a single .js file and this fixed the problem.
{ "pile_set_name": "StackExchange" }
Q: stringr: how to recover sentences from a string that was derived from concatenating those sentences I have three units strings which each contain commas (","). Each unit string also begins with a capital letter. These strings have been concatenated in a paste0() fashion such that a comma (",") and no spaces separate the original unit strings. I provide R code below to give more context to my question: string1 <- "I like dogs, cats, and pigs" string2 <- "Community health centers, businesses, stores" string3 <- "Jamie Foxx sings, dances, and acts" string_combined <- paste0(string1,",",string2,",",string3) string_combined [1] "I like dogs, cats, and pigs,Community health centers, businesses, stores,Jamie Foxx sings, dances, and acts" As can be seen from the console output above, the strings meet at the junction of: last lowercase letter of first string a comma first uppercase letter of the 2nd string no spaces at the junction of unit strings I have used the str_view_all(string = string_combined,pattern = ",\\S") to locate where the strings join, but I am not sure how to recover the original unit strings (string1, string2, string3). Question: How can I recover the original unit strings from the larger string (string_combined), which is a concatenation of the unit strings, recognizing that the original unit strings, which themselves contain commas, are separated by commas in the concatenated string. Perhaps someone might be able to help answer my question. Thank you. A: You can use the pattern described above in strsplit strsplit(string_combined, "(?<=[a-z]),(?=[A-Z])",perl = TRUE)[[1]] #[1] "I like dogs, cats, and pigs" "Community health centers, businesses, stores" #[3] "Jamie Foxx sings, dances, and acts" and similar with stringr::str_split stringr::str_split(string_combined, "(?<=[a-z]),(?=[A-Z])")[[1]] This splits the string at lower case letter(a-z), followed by comma (,), followed by upper-case letter (A-Z).
{ "pile_set_name": "StackExchange" }
Q: How to Add Custom CSS Buttons to WordPress as a Shortcode? How do I add custom CSS buttons as a shortcode like this: [button class="mybutton1" link="home"] I have the CSS of the button from here .myButton { -moz-box-shadow:inset 0px 1px 0px 0px #cf866c; -webkit-box-shadow:inset 0px 1px 0px 0px #cf866c; box-shadow:inset 0px 1px 0px 0px #cf866c; background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #d0451b), color-stop(1, #bc3315)); background:-moz-linear-gradient(top, #d0451b 5%, #bc3315 100%); background:-webkit-linear-gradient(top, #d0451b 5%, #bc3315 100%); background:-o-linear-gradient(top, #d0451b 5%, #bc3315 100%); background:-ms-linear-gradient(top, #d0451b 5%, #bc3315 100%); background:linear-gradient(to bottom, #d0451b 5%, #bc3315 100%); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#d0451b', endColorstr='#bc3315',GradientType=0); background-color:#d0451b; -moz-border-radius:3px; -webkit-border-radius:3px; border-radius:3px; border:1px solid #942911; display:inline-block; color:#ffffff; font-family:arial; font-size:13px; font-weight:normal; padding:6px 24px; text-decoration:none; text-shadow:0px 1px 0px #854629; } .myButton:hover { background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #bc3315), color-stop(1, #d0451b)); background:-moz-linear-gradient(top, #bc3315 5%, #d0451b 100%); background:-webkit-linear-gradient(top, #bc3315 5%, #d0451b 100%); background:-o-linear-gradient(top, #bc3315 5%, #d0451b 100%); background:-ms-linear-gradient(top, #bc3315 5%, #d0451b 100%); background:linear-gradient(to bottom, #bc3315 5%, #d0451b 100%); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#bc3315', endColorstr='#d0451b',GradientType=0); background-color:#bc3315; } .myButton:active { position:relative; top:1px; } I wish to add this to my WordPress site as a shortcode. How do I do this? Thanks! A: function myButton($atts, $content = ''){ extract(shortcode_atts(array( 'text' => '', 'link' => '' ), $atts)); $html = '<a href="' . $link . '"><div class="myButton">' . $text . '</div></a>'; return $html; } add_shortcode('mybutton', 'myButton'); Add this to your functions.php and you will be able to call the button within wordpress using the shortcode you wanted. As you can see the class and the link you set become the variables to be used in the shortcode. If you want to add text to the button you could change the html to the following: $html = '<a href="' . $link . '"><div class="' . $class . '" >' . $content . '</div></a>'; and use it like this [button class='mybutton' link='home']mybuttonname[/button] Hope this helps
{ "pile_set_name": "StackExchange" }
Q: How to say "as you wish" in Chinese I want to know what to say in the following scenario: I am pushing someone for his own good, and he is not doing what I want, so I would then say to him "Okay, as you wish." How can I express this in Chinese? Update: 如你所愿(rúnǐsuǒyuàn)from Google Translate is not understood as having the same meaning by Chinese speakers. A: I think that “随你便” may suit your needs. This phrase can be translated as "as you wish" or "suit yourself" or even "whatever."
{ "pile_set_name": "StackExchange" }
Q: reliable place to buy .io domains I'm looking around trying to find a good place to buy .io domains. Suddenly, I think I'm surrounded by scammers, since .io domain providers websites, are really badly-designed and I am not feeling of confident about dealing with them. I'm trying to deal with nic.io guys right now. If somebody could point me out some company, it would be appreciated. Specially because the domain costs £60. It's not that cheap to spend with someone that could just leave you waiting for some answer after the payment. A: Nic.io seems to be the official registry and primary registrar for registering .io domains, so if you don't want to register through them, you're SOL. There are other registrars that also sell .io domains, but they're still just going through nic.io. I'm sorry if you have bad feelings about nic.io, but that's just the nature of the domain name industry. When you have a regulatory agency like ICANN/Network Solutions, the industry naturally becomes dominated by sleazy companies. You can thank cronyism for that.
{ "pile_set_name": "StackExchange" }
Q: selected option value cannot be reset I'm having two select boxes on my mvc razor view which are styled using selectBoxIt plugin On changing #ddHour I want to reset #ddDay select(to set on first select choice) var selectedDay = $('#ddDay option:nth-child(1)').val(); I tried with $("#ddDay").selectBoxIt('refresh'); but it always returns same previously selected #ddDay option A: You should use selectOption to do that: $("#ddDay").selectBoxIt().data("selectBox-selectBoxIt").selectOption('yourSelectBoxValue'); Regards.
{ "pile_set_name": "StackExchange" }
Q: Search a div and narrow down options I have div with a bunch of cities inside. And it is frustrating when you don't find the city you are looking for. So I'm trying to add a search bar, to exclude the cities that doesn't match the search string. <form> <div class="form-group"> <input type="text" class="form-control" id="exampleInputEmail1" placeholder="quick city search"> </div> </form> <div id="cities"> <div id="cities"> <a href="http://www.example.com/?city=alingsas" style="font-size: <?php echo mt_rand(5, 40); ?>px">Alingsås</a> <a href="http://www.example.com/?city=borlange" style="font-size: <?php echo mt_rand(5, 40); ?>px">Borlänge</a> <a href="http://www.example.com/?city=boras" style="font-size: <?php echo mt_rand(5, 40); ?>px">Borås</a> <a href="http://www.example.com/?city=eskilstuna" style="font-size: <?php echo mt_rand(5, 40); ?>px">Eskilstuna</a> <a href="http://www.example.com/?city=falun" style="font-size: <?php echo mt_rand(5, 40); ?>px">Falun</a> <a href="http://www.example.com/?city=goteborg" style="font-size: <?php echo mt_rand(5, 40); ?>px">Göteborg</a> <a href="http://www.example.com/?city=gavle" style="font-size: <?php echo mt_rand(5, 40); ?>px">Gävle</a> <a href="http://www.example.com/?city=halmstad" style="font-size: <?php echo mt_rand(5, 40); ?>px">Halmstad</a> <a href="http://www.example.com/?city=helsingborg" style="font-size: <?php echo mt_rand(5, 40); ?>px">Helsingborg</a> <a href="http://www.example.com/?city=hudiksvall" style="font-size: <?php echo mt_rand(5, 40); ?>px">Hudiksvall</a> <a href="http://www.example.com/?city=harnosand" style="font-size: <?php echo mt_rand(5, 40); ?>px">Härnösand</a> <a href="http://www.example.com/?city=jonkoping" style="font-size: <?php echo mt_rand(5, 40); ?>px">Jönköping</a> <a href="http://www.example.com/?city=kalmar" style="font-size: <?php echo mt_rand(5, 40); ?>px">Kalmar</a> </div> </div> Here is an attempt in a Fiddle. This one with highlight was the reference: http://jsfiddle.net/FranWahl/aSjqT/ My question is: How can i search a div, and exclude strings that is not "searched" for. A: In your fiddle do $("#search").on("keyup", function() { var value = $(this).val().toUpperCase(); $("#cities a").each(function(index) { $row = $(this); var id = $row.text().toUpperCase(); //All match //if (id.indexOf(value) == -1) { //For startWith Match if (!id.startsWith(value)) { $row.hide(); } else { $row.show(); } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <div class="form-group"> <input type="text" class="form-control" id="search" placeholder="quick city search"> </div> </form> <div> <div id="cities"> <a href="http://www.example.com/?city=alingsas" style="font-size: <?php echo mt_rand(5, 40); ?>px">Alingsås</a> <a href="http://www.example.com/?city=borlange" style="font-size: <?php echo mt_rand(5, 40); ?>px">Borlänge</a> <a href="http://www.example.com/?city=boras" style="font-size: <?php echo mt_rand(5, 40); ?>px">Borås</a> <a href="http://www.example.com/?city=eskilstuna" style="font-size: <?php echo mt_rand(5, 40); ?>px">Eskilstuna</a> <a href="http://www.example.com/?city=falun" style="font-size: <?php echo mt_rand(5, 40); ?>px">Falun</a> <a href="http://www.example.com/?city=goteborg" style="font-size: <?php echo mt_rand(5, 40); ?>px">Göteborg</a> <a href="http://www.example.com/?city=gavle" style="font-size: <?php echo mt_rand(5, 40); ?>px">Gävle</a> <a href="http://www.example.com/?city=halmstad" style="font-size: <?php echo mt_rand(5, 40); ?>px">Halmstad</a> <a href="http://www.example.com/?city=helsingborg" style="font-size: <?php echo mt_rand(5, 40); ?>px">Helsingborg</a> <a href="http://www.example.com/?city=hudiksvall" style="font-size: <?php echo mt_rand(5, 40); ?>px">Hudiksvall</a> <a href="http://www.example.com/?city=harnosand" style="font-size: <?php echo mt_rand(5, 40); ?>px">Härnösand</a> <a href="http://www.example.com/?city=jonkoping" style="font-size: <?php echo mt_rand(5, 40); ?>px">Jönköping</a> <a href="http://www.example.com/?city=kalmar" style="font-size: <?php echo mt_rand(5, 40); ?>px">Kalmar</a> </div> https://jsfiddle.net/k8rp18qb/2/
{ "pile_set_name": "StackExchange" }
Q: Python: count specific occurrences in a dictionary Say I have a dictionary like this: d={ '0101001':(1,0.0), '0101002':(2,0.0), '0101003':(3,0.5), '0103001':(1,0.0), '0103002':(2,0.9), '0103003':(3,0.4), '0105001':(1,0.0), '0105002':(2,1.0), '0105003':(3,0.0)} Considering that the first four digits of each key consitute the identifier of a "slot" of elements (e.g., '0101', '0103', '0105'), how can I count the number of occurrences of 0.0 for each slot? The intended outcome is a dict like this: result={ '0101': 2, '0103': 1, '0105': 2} Apologies for not being able to provide my attempt as I don't really know how to do this. A: Use a Counter, add the first four digits of the key if the value is what you're looking for: from collections import Counter counts = Counter() for key, value in d.items(): if value[1] == 0.0: counts[key[:4]] += 1 print counts
{ "pile_set_name": "StackExchange" }
Q: Chrome extension Script Injection to each open tab I tried to build simple extension according to the examples: from here and here and I must be doing something wrong here. All I want is for start that on each loading page ( or even better before loading ) it will popup hello alert manifest.json { "background": { "page": "background.html" }, "content_scripts": [ { "matches": ["http://*/*","https://*/*"], "js": ["jquery-1.8.2.min.js","contentscript.js"], "run_at": "document_end" } ], "web_accessible_resources": [ "script_inpage.js" ], "browser_action": { "default_popup": "popup.html", "default_title": "Test 123" }, "content_security_policy": "script-src 'self'; media-src *; object-src 'self'", "description": "Simple Test 123.", "manifest_version": 2, "minimum_chrome_version": "18", "name": "Test 123", "permissions": [ "unlimitedStorage", "http://*/", "tabs", ], "version": "2.6" } background.html is empty for now contentscript.js: var s = document.createElement('script'); s.src = chrome.extension.getURL('script_inpage.js'); (document.head||document.documentElement).appendChild(s); s.onload = function() { s.parentNode.removeChild(s); }; script_inpage.js: alert("this is script"); There is no error even when I trigger the developer console window. A: Your manifest file is invalid, there's a superfluous comma after the last entry in the "permissions" section: "permissions": [ "unlimitedStorage", "http://*/", "tabs", // <-- Remove that comma ], If you want your script to run as early as possible, use "run_at": "document_start" instead of "document_end". Then, your script will run before <head> and <body> even exist.
{ "pile_set_name": "StackExchange" }
Q: How do I connect to the ManagedObjectContext object of the File Owner in XCode 4 I'm building a really simple Core Data app in XCode 4. There's an entity model with just one entity (Employee) and just one attribute (name). In IB I've added a default Table View to display the employees, two buttons (one to add an employee and another to delete an employee) and an ArrayController. It is my understanding that the ArrayController's managedObjectContext somehow needs to be connected to the one that is initialised by the App Delegate. I can see the code for initialising the context but IB does not let me connect to it. How do I do this connection? Many thanks. A: How does Interface Builder not allow you connect it? Bindings are not the same as IBOutlets in Interface Builder context. If file owner is instance of AppDelegate (which always has initial managed object context) you just should define NSArrayController's managedObjectContext binding's object as File's owner and set managedObjectContext as its model path.
{ "pile_set_name": "StackExchange" }
Q: How can I print one Array value of a SSJS RetrieveRequest I have made a Retrieve call using the below code, but am struggling to print the Email field values into a clean list. I can get this output and can see the email addresses are pulling through: {"Name":null,"Keys":null,"Type":"DataExtensionObject","Properties":[{"Name":"Email","Value":"[email protected]"}],"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","CreatedDateSpecified":false,"ModifiedDate":null,"ModifiedDateSpecified":false,"ID":0,"IDSpecified":false,"ObjectID":null,"CustomerKey":null,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false,"IsPlatformObjectSpecified":false}1: {"Name":null,"Keys":null,"Type":"DataExtensionObject","Properties": The code I'm using is: <script runat="server"> Platform.Load("Core","1.1.1"); <br><br> var rr = Platform.Function.CreateObject("RetrieveRequest");<br><br> Platform.Function.SetObjectProperty(rr, "ObjectType", "DataExtensionObject[1_Master_Data]");<br> Platform.Function.AddObjectArrayItem(rr, "Properties", "Email");<br> <br> do { var results = [0,0]; var rows = Platform.Function.InvokeRetrieve(rr, results); <br> var runstatus = results[0];<br> var requestId = results[1];<br> <br><br> if (rows != null) {<br> for (var i in rows) {<br> var output = rows[i];<br> Write(i + ": " + output + " <br/>");<br> Write(Stringify(rows[i]));<br> } <br> } <br> rr.ContinueRequest = requestId;<br> } while (runstatus == "MoreDataAvailable")<br><br> </script> thank you A: try this: for (var i in rows) { var output = rows[i];<br> var properties = output["Properties"] var email = ""; for (var j in properties) { var name = properties[j]["Name"]; var value = properties[j]["Value"]; if(name =="Email") //Find KeyValuePair for email { email = value; break; // break the properties loop } } if(email!="") { Write("Email for row " + i + ": " + email + " <br/>"); }else{ Write("Can't find email for row " + i + "<br/>"); } }
{ "pile_set_name": "StackExchange" }
Q: SSRS Chart for Milestones I need to create a SSRS report to present actual start date vs. planned start dates for milestones of a project (selected as input parameter) The chart should look like this: I have created the table in a separate table. However, I don’t know which chart type should I use and how do I have to set up the chart? (Chart Data, Category Groups and Series Groups). (Data comes from SQL Server, SSRS Version 14.0.1016.285; SSDT 15.6.4) Many Thanks in advance A: This might look a bit long winded but it's fairly simple so stick with it :) To start with I did not know your data structure so I've just made some assumptions. You may have to rework some of this to get it to fit but I've tried to keep it simple. The approach will be to use a subreport to plot the dots and a main report to show the overall table. With this in mind, as we will have more than one dataset referencing our data I added some tables to my sample database before I started wit the following. The first is a simple table containing months and years, you could a use view over a date table if you have one but this will do for now. CREATE TABLE prjYearMonth (Year int, Month int) INSERT INTO prjYearMonth VALUES (2018, 8), (2018, 9), (2018, 10), (2018, 11), (2018, 12), (2019, 1), (2019, 2) Next is the project milestone table CREATE TABLE prjMileStones (msID int, msLabel varchar(50), msPlannedStart date, msActualStart date) INSERT INTO prjMileStones VALUES (1, 'Milestone 1', '2018-10-30', '2018-12-13'), (2, 'Milestone 2', '2018-11-12', '2018-12-10'), (3, 'Milestone 3', '2018-10-21', '2018-12-25'), (4, 'Milestone 4', '2018-10-18', '2018-11-28'), (5, 'Milestone 6', '2019-01-08', '2019-01-29') OK, Now let's start the report... Create a new empty report then add a dataset with the following query SELECT * FROM prjYearMonth d LEFT JOIN prjMileStones t on (d.Year = YEAR(t.msPlannedStart) AND d.Month = Month(t.msPlannedStart)) or (d.Year = YEAR(t.msActualStart) AND d.Month = Month(t.msActualStart)) Now add a matrix item to the report. Add a Row Group that groups on msLabel. Next add two Column Groups. First a group that groups on Month and then add a parent group that groups on Year. Add columns on the row group so that you end up with 4 columns msID; msLabel; msPlannedStart; msActualStart. Finally (for now) set the Expression of the Month field (the one in the column header) to be = Format(DATESERIAL(2017, Fields!Month.Value, 1), "MMM") This will just give us the month name rather than the number (the 2017 is irrelevant, any year will do). Now just format as required. You report design should look something like this.. If we run the report now we will get this.. Now to plot the dots... For this we will create a small subreport. The subreport will accept 3 parameters. Year, Month, msID (the milestone ID from your main table). We will need the data in a slightly different structure for this sub report but the work can be done in the dataset query so nothing new is required in the database itself. So, create a new report, let's call it _subMonthChart. Next add a dataset with the following query.. DECLARE @t TABLE(msID int, msLabel varchar(50), PlannedOrActual varchar(1), msStartDate date) INSERT INTO @t SELECT msId, mslabel, 'P', msPlannedStart FROM prjMileStones UNION ALL SELECT msId, mslabel, 'A', msActualStart FROM prjMileStones SELECT 1 AS Y, Day(msStartDate) as Day, PlannedOrActual FROM prjYearMonth d LEFT JOIN @t t on (d.Year = YEAR(t.msStartDate) AND d.Month = Month(t.msStartDate)) WHERE [Year] = @Year and [Month] = @Month and msID = @msID Your report should now have 3 parameters that were automatically created, edit all three to Allow Nulls. Note: The Y in the dataset is just some arbitrary value to help plot on the chart,. I will set the Y axis to range from 0 - 2 so 1 will sit in the middle. Next, add a line chart with markers. Don't worry about the size for now... Set the Values as Y Set the Category Groups as Day Set the Series Groups as PlannedOrActual Right click the horizontal Axis, choose properties and set the Axis Type to Scalar, switch off 'Always include zero' then set Min = 1, Max = 31, Interval = 1, Interval Type = Default. Note that for data in months that don't have 31 days the plots points will not be accurate but they will be close enough for your purposes. Right click the Vertical Axis, choose properties and set the Mn=0, Max=2, Interval = 1, Interval Type = Default Next, right click on one of the series lines and choose properties. Set the marker to Diamond, the marker size to 8pt and the Marker Color this expression =IIF(Fields!PlannedOrActual.Value = "P", "Blue", "Green") The report design should look something like this... (check the highlighted bits in particular) Now let's quickly test the subreport, based on my sample data I set the parameters to 2019, 1 and 5 and get the following results.... As we can see, our two dates that fall in January for this milestone were plotted in roughly the correct positions. Nearly there... Next right click on both Axes and turn off 'Show Axis' so we hide them. Now resize the chart to something that will fit in the main report cell. In my example I set the size to 2cm, 1.2cm and moved it top left of the report. Then set the report to be the same size as the chart (2cm,1.2cm again in my case). Save the sub report and go back to your main report... For the 'Data' cell where the rows and columns intersect, set the size to match the subreport size (2cm, 1.2cm) then right click the cell and insert subreport. Right click the newly inserted subreport item and choose properties. Choose _subMonthChart as the subreport from the dropdown. Click the parameters tab. Add an entry for each parameter (Year/Month/msID) and set its value to be the corresponding field from the dataset. FINALLY !!!! Set the border on the cell containing the subreport to have borders all round, just so it matches your mock-up.. Your report design should now look like this... Now when the report runs, it will pass in the month, year and milestone ID to the subreport in each cell which in turn will plot the dates as required. When we run the report we should finally get this... This may need some refining but hopefully you can get this going based on this. If you have trouble I suggest you recreate this example in its entirety, get it working and then swap out the database parts to fit your current database.
{ "pile_set_name": "StackExchange" }
Q: telnet: connect to address 192.168.33.x: Connection refused - over Vagrant centos machine I have created a centos machine and installed nexus service over it. Nexus service is running on 8081 port which i have opened from the vagrant file using below command inside the vagrant file. machine1.vm.network "private_network", ip: "192.168.33.x" machine1.vm.network "forwarded_port", guest: 80, host: 80 machine1.vm.network "forwarded_port", guest: 8080, host: 8080 machine1.vm.network "forwarded_port", guest: 8081, host: 8081 The nexus service is running fine on the centos machine but the telnet to the port from the same server as well as server from its network is failing. The port is not reachable from the host windows machine as well. The server IP is reachable from its network machines, here all 3 network machines are created from vagrant file I have tried to see and confirm the nexus service is actually running on 8081 port, and its running I have tried to open a port 8081 to ensure firewall is not blocking using below command iptables -A INPUT -p tcp -m tcp --dport 8081 -j ACCEPT I have browsed through multiple forum to see if any solution works, I acknowledge this is very generic error even i have faced in past, but in this case not able to identify the root cause. I doubt if its related to vagrant specific configuration Also, i tried to curl the service from centos server and host server, it doesnt work: ]$ curl http://localhost:8081 curl: (7) Failed connect to localhost:8081; Connection refused netstat command doesnt give any result: netstat -an|grep 8081 [vagrant@master1 bin]$ however the nexus service is up and running on the server with the same port Here is vagrant file code config.vm.define "machine1" do |machine1| machine1.vm.provider "virtualbox" do |host| host.memory = "2048" host.cpus = 1 end machine1.vm.hostname = "machine1" machine1.vm.network "private_network", ip: "192.168.33.x3" machine1.vm.network "forwarded_port", guest: 80, host: 80 machine1.vm.network "forwarded_port", guest: 8080, host: 8080 machine1.vm.network "forwarded_port", guest: 8081, host: 8081 machine1.vm.synced_folder "../data", "/data" end config.vm.define "machine2" do |machine2| machine2.vm.provider "virtualbox" do |host| host.memory = "2048" host.cpus = 1 end machine2.vm.hostname = "machine2" machine2.vm.box = "generic/ubuntu1804" machine2.vm.box_check_update = false machine2.vm.network "private_network", ip: "192.168.33.x2" machine2.vm.network "forwarded_port", guest: 80, host: 85 machine2.vm.network "forwarded_port", guest: 8080, host: 8085 machine2.vm.network "forwarded_port", guest: 8081, host: 8090 end config.vm.define "master" do |master| master.vm.provider "virtualbox" do |hosts| hosts.memory = "2048" hosts.cpus = 2 end master.vm.hostname = "master" master.vm.network "private_network", ip: "192.168.33.x1" end end As the nexus service is running on port 8081, i should be able to access the service from my host machine using http://localhost:8081. A: The issue is most likely the Vagrant networking as you guessed. If you just want to access the nexus service running on guest from the host, perhaps this can be useful. To workaround, you may try to make the Vagrant box available on public network and then access it using the public IP and for that, you will have to enable config.vm.network "public_network" in your Vagrant file and then just do a vagrant reload. Once done, try accessing http://public_IP_of_guest:8081 Please let me know how it goes.
{ "pile_set_name": "StackExchange" }
Q: How do I assign multiple UI's to a parameter, such as both UILabels and UIButtons? I am trying to create a function that flips a UILabel, UIButton, etc. 180 degrees so that it is upside down. My problem is that I cannot find a way to give the function a parameter that is assigned to UILabels, UIButtons, etc. I have tried using "Any" to assign to my parameter, but Any does not have the method transform. Here is my code so far without the parameter having anything assigned: func rotate180(object: ) { object.transform = CGAffineTransformMakeRotation(rotationAngle: 3.14) { A: You could also implement this as an extension: extension UIView { func rotate180() { self.transform = CGAffineTransform(rotationAngle: 3.14) } } Usage: myButton.rotate180() myLabel.rotate180() myView.rotate180()
{ "pile_set_name": "StackExchange" }
Q: Problem with DateTimeContinuousAxis, one day is added to each date without no apparent reason [Nativescript-Angular] I receive a json like this from chartService, But when I try to show the data, 1 day is added to each date. I am using Genymotion for emulate. I don't know if it could be an internal emulator time zone problem, will anyone know what is happening? JSON = [{ "fecha": "2019-09-23", "km_rec": 431.56 }, { "fecha": "2019-09-25", "km_rec": 187.12 }, { "fecha": "2019-09-26", "km_rec": 270.08 }, { "fecha": "2019-09-27", "km_rec": 121.04 }, { "fecha": "2019-09-28", "km_rec": 407.96 }, { "fecha": "2019-09-29", "km_rec": 10.98 }] <StackLayout class="c-stacklayout" alignItems="flex-end"> <GridLayout class="modal_chart"> <RadCartesianChart tkExampleTitle tkToggleNavButton> <DateTimeCategoricalAxis tkCartesianHorizontalAxis dateFormat="dd-MMM" labelFitMode="Rotate" labelRotationAngle="-1.2" labelTextColor="black"></DateTimeCategoricalAxis> <LinearAxis tkCartesianVerticalAxis allowPan="false" allowZoom="false"></LinearAxis> <LineSeries tkCartesianSeries selectionMode="DataPointMultiple" showLabels="true" [items]="distance" valueProperty="km_rec" categoryProperty="fecha"> <PointLabelStyle tkLineLabelStyle fontStyle="Bold" fillColor="#FC6060" textSize="12" textColor="White"> </PointLabelStyle> </LineSeries> <RadCartesianChartGrid tkCartesianGrid horizontalLinesVisible="true" verticalLinesVisible="false" verticalStripLinesVisible="false" horizontalStripLinesVisible="true" > </RadCartesianChartGrid> </RadCartesianChart> </GridLayout> </StackLayout> ngOnInit() { this.initDataItems() } private initDataItems() { this.checkedDistanceData(); } checkedDistanceData() { this.query(Config.storage.vehicleSelected, veh => { this.query(moment().format('YYYY-MM-DD') + this.id_veh, data => { if (data) { this.setChartDistance(JSON.parse(data.value)); ... } else { this.chartService(); ... } }); }; }); chartService() { this.httpGet(route (www.dis....), data => { this.setChartDistance(data); this.changeDetector.detectChanges(); }, error => { error... }, null); } get getchartDistance() { return distance; } setChartDistance(chart) { this.distance = chart; } A: According to the documentation, you should store your dates in milliseconds. Most likely you're passing a date object that is getting serialized and on deserialization it's losing/gaining some hours and flipping to the next day. You might want to run some tests if using UTC or the local timezone is better for this (since you're using moment you can use moment.utc() and then get it in ms). See the example here: https://github.com/NativeScript/nativescript-ui-samples/blob/master/chart/app/examples/data-models/date-time-model.ts
{ "pile_set_name": "StackExchange" }
Q: Simple question about inertia law and trajectory I know this question is so simple, maybe a middle school level, so if this question doesn't fit here, please let me know. Suppose the particle bellow is in the vacuum with a constant velocity $\vec{v_1}$. If we add a force towards the left, we get an acceleration vector $\vec{a}$. Therefore, there is an increasing velocity $\vec{v_2}$ towards the left. My question is $v_1$ is keeping pushing the particle up with the same speed forever? In this case how would be its trajectory? A: Yes, $\vec{v_{1}}$ (or $\vec{v_{y}}$) would be constant because there is no force accelerating nor decelerating along the direction of $\vec{v_{y}}$. Therefore the equation of motion would be as follows, assuming upwards (along $\vec{v_{y}}$) is positive $y$ axis, and left (along $\vec{v_{x}}$) is negative $x$ axis. $\vec{v_{y}} = v_{y} \vec{{j}}$ $\vec{v_{x}} = (-at) \vec{i}$ From the equations of motion, along $y$ axis, $y = {v_{y}}{t}$ - (1) And along $x$ axis, $x = -\frac{at^{2}}{2}$ - (2) Eliminating $t$ from (1) and (2), we get $\frac{x}{y^{2}} = -\frac{a}{2(v_{y})^{2}}$, this is the equation of the path traveled by the particle.
{ "pile_set_name": "StackExchange" }
Q: MongoDB Conditional validation on arrays and embedded documents I have a number of documents in my database where I am applying document validation. All of these documents may have embedded documents. I can apply simple validation along the lines of SQL non NULL checks (these are essentially enforcing the primary key constraints) but what I would like to do is apply some sort of conditional validation to the optional arrays and embedded documents. By example, lets say I have a document that looks like this: { "date": <<insertion date>>, "name" : <<the portfolio name>>, "assets" : << amount of money we have to trade with>> } Clearly I can put validation on this document to ensure that date name and assets all exist at insertion time. Lets say, however, that I'm managing a stock portfolio and the document can have future updates to show an array of stocks like this: { "date" : <<insertion date>>, "name" : <<the portfolio name>>, "assets" : << amount of money we have to trade with>> "portfolio" : [ { "stockName" : "IBM", "pricePaid" : 155.39, "sharesHeld" : 100 }, { "stockName" : "Microsoft", "pricePaid" : 57.22, "sharesHeld" : 250 } ] } Is it possible to to apply a conditional validation to this array of sub documents? It's valid for the portfolio to not be there but if it is each document in the array must contain the three fields "stockName", "pricePaid" and "sharesHeld". A: MongoShell db.createCollection("collectionname", { validator: { $or: [ { "portfolio": { $exists: false } }, { $and: [ { "portfolio": { $exists: true } }, { "portfolio.stockName": { $type: "string", $exists: true } }, { "portfolio.pricePaid": { $type: "double", $exists: true } }, { "portfolio.sharesHeld": { $type: "double", $exists: true } } ] } ] } }) With this above validation in place you can insert documents with or without portfolio. After executing the validator in shell, then you can insert data of following db.collectionname.insert({ "_id" : ObjectId("58061aac8812662c9ae1b479"), "date" : ISODate("2016-10-18T12:50:52.372Z"), "name" : "B", "assets" : 200 }) db.collectionname.insert({ "_id" : ObjectId("58061ab48812662c9ae1b47a"), "date" : ISODate("2016-10-18T12:51:00.747Z"), "name" : "A", "assets" : 100, "portfolio" : [ { "stockName" : "Microsoft", "pricePaid" : 57.22, "sharesHeld" : 250 } ] }) If we try to insert a document like this db.collectionname.insert({ "date" : new Date(), "name" : "A", "assets" : 100, "portfolio" : [ { "stockName" : "IBM", "sharesHeld" : 100 } ] }) then we will get the below error message WriteResult({ "nInserted" : 0, "writeError" : { "code" : 121, "errmsg" : "Document failed validation" } }) Using Mongoose Yes it can be done, Based on your scenario you may need to initialize the parent and the child schema. Shown below would be a sample of child(portfolio) schema in mongoose. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var portfolioSchema = new Schema({ "stockName" : { type : String, required : true }, "pricePaid" : { type : Number, required : true }, "sharesHeld" : { type : Number, required : true }, } References: http://mongoosejs.com/docs/guide.html http://mongoosejs.com/docs/subdocs.html Can I require an attribute to be set in a mongodb collection? (not null) Hope it Helps!
{ "pile_set_name": "StackExchange" }
Q: Is Surdarshan Chakra mentioned In Vedic literature? The Surdarshan Chakra is Lord vishnu's weapon mentioned in many puranas and in Itihasas. But is there any reference of Surdarshana Chakra in Vedic literature (that is Vedas,Upanishads,Brahmans).the wikipedia says in the Rigveda the Chakra was Vishnu's symbol as the wheel of time, so where exactly is Chakra of Lord Vishnu mentioned? A: Yes surdarshan chakra was called Vishnu s chakra in ancient texts including RIG Veda and even in valmiki Ramayana it is called Vishnu s Chakra. He, like a rounded wheel, hath in swift motion set his ninety racing steeds together with the four.Developed, vast in form, with those who sing forth praise, a youth, no more a child, he cometh to our call(Rig veda 1.155.6) The word Chakra is translated as wheel,even Wikipedia says in Yajurveda vishnu s chakra is mention but till now i could not find a refernce in yajur Veda.
{ "pile_set_name": "StackExchange" }
Q: What is the meaning of "block special"? I tried this command on my Linux Ubuntu prompt in Amazon Web Services sudo file /dev/xvda1 and the output is /dev/xvda1: block special What is the meaning of block special in the output? A: Most of the things you find below /dev are either "block special" or "character special" things, and you rather to not change them manually. Your example shows a disk drive partition provided by Xen (what on a "normal, nonvirtual machine" would be /dev/sda1). For more details on this special device, please see What is the “/dev/ xvda1 ” device? For more details on what devices, and especially block devices are, you may consult Device file - Wikipedia, the free encyclopedia.
{ "pile_set_name": "StackExchange" }
Q: Is it valid to mix assets and expenses when calculating the worth of a house? I'm trying to calculate (for myself, not relying on other people's graphs) when it becomes worth it to buy vs. rent. On the positive side, there is: the down payment, property that (roughly, over the long term, unless you live where it was horribly overpriced during the early 2000s bubble) appreciates about 4%/year, and a declining mortgage balance. But on the negative side are ongoing yearly expenses, some which decline over the years, and others that keep on rising: Mortgage interest, PMI (maybe), Property taxes, Maintenance & repair, and Home ownwer's insurance. If after 30 years you wind up with a house that's worth $1M, but spent $700K in expenses, do you wind with an effective house-only Net Worth of $1M - $700K = $300K? It seems like I'm mixing apples (assets and debts) and oranges (expenses). A: A house's value is whatever it is sold for when you sell it. This doesn't change based on how much you put into the house. There are a lot of examples of that, but let's say you buy a house for $100K. If you assume that the home's "value" increases at 4% per year (and inflation stays at 0%), your house will objectively be worth $324K at the end of 30 years. So the home's value is simply what the house can be sold for when you are ready to sell. If you can't sell it (for example if a housing bubble comes up or external factors like somebody building a nuclear power plant next door), the house is worth nothing. The concept you are mixing up is return on investment (ROI) and value. Your ROI is the difference between what you invested and its value at the time of the sale. Value is value regardless of how much you put in it, ROI takes into account all the expenses you "invest" in order to get to the value in the future.
{ "pile_set_name": "StackExchange" }
Q: SQL JOINS and naming joined column I have a Products table and Downloads table. The Downloads table has 4 fields, ID, Name, Category and Download The Products table has 3 fields specific to Downloads: Downloads, Order Guides and Submittal Sheets. Each one of these fields stores the ID of the record from the Downloads table. There will never be the same Download ID value for these 3 fields in the Product table. I have the follow SQL statement: SELECT product_id, product_name, product_download, product_submittal, product_ordering_guide, product_status, tbl_downloads.download_id, tbl_downloads.download_name FROM tbl_products LEFT JOIN tbl_downloads ON tbl_products.product_download=tbl_downloads.download_id LEFT JOIN tbl_downloads ON tbl_products.product_submittal=tbl_downloads.download_id LEFT JOIN tbl_downloads ON tbl_products.product_order_guide=tbl_downloads.download_id It generates the following error: #1066 - Not unique table/alias: 'tbl_downloads' This error makes sense and I know it was going to happen, but I don't know how to fix it. I need to add an Alias, but not sure where. If I remove the last two JOIN statements, everything works as expected. Thanks A: You need to use unique aliases if you are joining the same table multiple times: SELECT product_id, product_name, product_download, product_submittal, product_ordering_guide, product_status, d1.download_id DownloadId, d1.download_name DownloadName, d2.download_id SubmittalDownloadId, d2.download_name SubmittalDownloadName, d3.download_id GuideDownloadId, d3.download_name GuideDownloadName FROM tbl_products LEFT JOIN tbl_downloads d1 ON tbl_products.product_download=d1.download_id LEFT JOIN tbl_downloads d2 ON tbl_products.product_submittal=d2.download_id LEFT JOIN tbl_downloads d3 ON tbl_products.product_order_guide=d3.download_id For example I used d1, d2 and d3 but you might want to be more descriptive in your aliases so it is clear what each join is doing, like this: SELECT product_id, product_name, product_download, product_submittal, product_ordering_guide, product_status, download.download_id DownloadId, download.download_name DownloadName, submittal.download_id SubmittalDownloadId, submittal.download_name SubmittalDownloadName, guide.download_id GuideDownloadId, guide.download_name GuideDownloadName FROM tbl_products LEFT JOIN tbl_downloads download ON tbl_products.product_download=download.download_id LEFT JOIN tbl_downloads submittal ON tbl_products.product_submittal=submittal.download_id LEFT JOIN tbl_downloads guide ON tbl_products.product_order_guide=guide.download_id
{ "pile_set_name": "StackExchange" }
Q: Datagrid not showing data in wpf with c# I am trying to use a dataGrid in WPF with c#. But I cannot get my datagrid to show any of my data in the table when I run my program in debug mode. I have this code executing when the datagrid loads. But all I see is an empty square. private void dataGrid1_Loaded(object sender, RoutedEventArgs e) { var items = new List<SaveTable>(); items.Add(new SaveTable("A" , 0)); items.Add(new SaveTable("B" , 0)); items.Add(new SaveTable("C" , 0)); items.Add(new SaveTable("D" , 0)); items.Add(new SaveTable("E" , 0)); var grid = sender as DataGrid; grid.ItemsSource = items; } I save a class named SaveTable which looks like this: class SaveTable { public string Name { get; set; } public double Value { get; set; } public SaveTable(string name, double value) { this.Name = name; this.Value = value; } } I got this code format online and it seems like everything is right? any suggestions? here is the xaml code for that window <Window x:Class="RobustCalculator.Storage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Storage" Height="499" Width="546" Activated="Window_Activated" Loaded="Window_Loaded"> <Grid> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="A" VerticalAlignment="Top" /> <TextBox HorizontalAlignment="Left" Margin="24,10,0,306" Name="valueA" Width="120" TextChanged="valueA_TextChanged" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="24,39,0,0" Name="valueB" VerticalAlignment="Top" Width="120" TextChanged="valueB_TextChanged" /> <TextBlock Height="20" HorizontalAlignment="Left" Margin="10,42,0,0" Name="textBlock2" Text="B" VerticalAlignment="Top" Width="20" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="24,71,0,0" Name="valueC" VerticalAlignment="Top" Width="120" TextChanged="valueC_TextChanged" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,72,0,0" Name="textBlock3" Text="C" VerticalAlignment="Top" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,101,0,0" Name="textBlock4" Text="D" VerticalAlignment="Top" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="24,98,0,0" Name="valueD" VerticalAlignment="Top" Width="120" TextChanged="valueD_TextChanged" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="24,130,0,0" Name="valueE" VerticalAlignment="Top" Width="120" TextChanged="valueE_TextChanged" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="11,131,0,0" Name="textBlock5" Text="E" VerticalAlignment="Top" /> <DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="235,130,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" SelectionChanged="dataGrid1_SelectionChanged" Loaded="dataGrid1_Loaded" /> </Grid> I added a breakpoint and the code isn't being executed. I am using the Loaded event, should I be using a different event? A: Your code works fine with Loaded event but at the moment you set AutoGenerateColumns="False" and don't define columns. You need to either define columns manually <DataGrid AutoGenerateColumns="False" ... Loaded="dataGrid1_Loaded"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Name}" Header="Name"/> <DataGridTextColumn Binding="{Binding Value}" Header="Value"/> </DataGrid.Columns> </DataGrid> or let it auto generate columns <DataGrid AutoGenerateColumns="True" ... Loaded="dataGrid1_Loaded"/>
{ "pile_set_name": "StackExchange" }
Q: Using array of chars as an array of long ints On my AVR I have an array of chars that hold color intensity information in the form of {R,G,B,x,R,G,B,x,...} (x being an unused byte). Is there any simple way to write a long int (32-bits) to char myArray[4*LIGHTS] so I can write a 0x00BBGGRR number easily? My typecasting is rough, and I'm not sure how to write it. I'm guessing just make a pointer to a long int type and set that equal to myArray, but then I don't know how to arbitrarily tell it to set group x to myColor. uint8_t myLights[4*LIGHTS]; uint32_t *myRGBGroups = myLights; // ? *myRGBGroups = WHITE; // sets the first 4 bytes to WHITE // ...but how to set the 10th group? Edit: I'm not sure if typecasting is even the proper term, as I think that would be if it just truncated the 32-bit number to 8-bits? A: typedef union { struct { uint8_t red; uint8_t green; uint8_t blue; uint8_t alpha; } rgba; uint32_t single; } Color; Color colors[LIGHTS]; colors[0].single = WHITE; colors[0].rgba.red -= 5; NOTE: On a little-endian system, the low-order byte of the 4-byte value will be the alpha value; whereas it will be the red value on a big-endian system.
{ "pile_set_name": "StackExchange" }
Q: how to parse xml with multiple root element I need to parse both var & group root elements. Code import xml.etree.ElementTree as ET tree_ownCloud = ET.parse('0020-syslog_rules.xml') root = tree_ownCloud.getroot() Error xml.etree.ElementTree.ParseError: junk after document element: line 17, column 0 Sample XML <var name="BAD_WORDS">core_dumped|failure|error|attack| bad |illegal |denied|refused|unauthorized|fatal|failed|Segmentation Fault|Corrupted</var> <group name="syslog,errors,"> <rule id="1001" level="2"> <match>^Couldn't open /etc/securetty</match> <description>File missing. Root access unrestricted.</description> <group>pci_dss_10.2.4,gpg13_4.1,</group> </rule> <rule id="1002" level="2"> <match>$BAD_WORDS</match> <options>alert_by_email</options> <description>Unknown problem somewhere in the system.</description> <group>gpg13_4.3,</group> </rule> </group> I tried following couple of other questions on stackoverflow here, but none helped. I know the reason, due to which it is not getting parsed, people have usually tried hacks. IMO it's a very common usecase to have multiple root elements in XML, and something must be there in ET parsing library to get this done. A: As mentioned in the comment, an XML file cannot have multiple roots. Simple as that. If you do receive/store data in this format (and then it's not proper XML). You could consider a hack of surrounding what you have with a fake tag, e.g. import xml.etree.ElementTree as ET with open("0020-syslog_rules.xml", "r") as inputFile: fileContent = inputFile.read() root = ET.fromstring("<fake>" + fileContent +"</fake>") print(root) A: Actually, the example data is not a well-formed XML document, but it is a well-formed XML entity. Some XML parsers have an option to accept an entity rather than a document, and in XPath 3.1 you can parse this using the parse-xml-fragment() function. Another way to parse a fragment like this is to create a wrapper document which references it as an external entity: <!DOCTYPE wrapper [ <!ENTITY e SYSTEM "fragment.xml"> ]> <wrapper>&e;</wrapper> and then supply this wrapper document as the input to your XML parser.
{ "pile_set_name": "StackExchange" }
Q: Write a non-recursive algorithm to compute n factorial I am having problems writing a code in java to compute n! without recursion. I know how to do it in loops, but I am not sure how to do it non-recursively. procedure factorial if n = 1 or n = 0 return 1 if n>1 return(n*factorial(n-1)) end A: Here is an iterative solution: int factorial(int n) { int f = 1; for(int i=1;i<=n;i++) { f *= i; } return f; }
{ "pile_set_name": "StackExchange" }
Q: Instalação do Magento dando erro de php extension Estou rodando a instalação do Magento 2.0.1 no xampp v3.2.2, e quando irá fazer o check de php extension surge o seguinte erro conforme a imagem abaixo: Alguém já passou por esse problema pode auxiliar? A: Vá no php.ini no Xampp, e procure as linhas (se for Windows): ;extension=php_xsl.dll ;extension=php_soap.dll ;extension=php_intl.dll Se estiver no Windows abra o php.ini pelo notepad++ ou sublimetext, no bloco de notas do Windows não vai abrir direito devido a quebra de linhas Se for Linux/Mac ;extension=xsl.so ;extension=soap.so ;extension=intl.so Se for PHP7.2: ;extension=xsl ;extension=soap ;extension=intl Então tire o ; da frente e salve o php.ini, deve ficar assim (windows): extension=php_xsl.dll extension=php_soap.dll extension=php_intl.dll Se for Linux/Mac extension=xsl.so extension=soap.so extension=intl.so Se for PHP7.2: extension=xsl extension=soap extension=intl Então reiniciei o Apache pelo painel do Xampp
{ "pile_set_name": "StackExchange" }
Q: Python: how to split and return a list from a function to avoid memory error I am currently working with a function that enumerates all cycles within a specific array (a digraph) and I need them all. This function returns all cycles as a list of lists (each sublist being a cycle, e.g. result=[[0,1,0],[0,1,2,0]] is a list containing 2 cycles starting and ending in node 0). However, there are millions of cycles so for big digraphs I get a memory error (MemoryError: MemoryError()) since the list of lists containing all cycles is too big. I would like that the function splits the result in several arrays so I do not get the memory error. Is that possible? and would that solve the issue? I tried to do that by splitting the results array as a list of sub-results (the sub-results have a maximum size, say 10 million which is below the 500 million max size stated here: How Big can a Python Array Get? ). The idea is that the result is a list containing sub-results: result=[sub-result1, sub-result2]. However, I get a different memory error: no mem for new parser. The way I do that is as follows: if SplitResult == False: result = [] # list to accumulate the circuits found # append cycles to the result list if cycle_found(): #cycle_found() just for example result.append(new_cycle) elif SplitResult == True: result = [[]] # list of lists to accumulate the circuits found # append cycles to the LAST result SUB-lists if cycle_found(): #cycle_found() just for example result[len(result)-1].append(new_cycle) # create a new sublist when the size of the LAST result SUB-lists # reaches the size limit (ResultSize) if len(result[len(result)-1]) == ResultSize: result.append([]) Maybe the issue is that I merge all sub-results within the results list. In that case, how can I return a variable number of results from a function? In particular I divide all simple cycles of a 12 node complete digraph in sublists of 10 million cycles. I know there are 115,443,382 cycles in total, so I should get a list with 16 sublists, the first 15 containing 10 million cycles each and the last one containing 443,382 cycles. Instead of that I get a different memory error: no mem for new parser. This procedure works for an 11 node complete digraph which returns 2 sublists, the first containing the 10 million cycles (10000000) and the other containing 976184. In case it is of any help, their memory footprint is >>> sys.getsizeof(cycles_list[0]) 40764028 >>> sys.getsizeof(cycles_list[1]) 4348732 Then, I guess we should add the size of each cycle listed: >>> sys.getsizeof(cycles_list[0][4]) 56 >>> cycles_list[0][4] [0, 1, 2, 3, 4, 0] Any help will be most welcome, Thanks for reading, Aleix A: Thank you for your suggestions. Indeed the right approach to avoid memory issues when returning arrays is simply by avoiding creating so big result arrays. Thus, generator functions are the way forward. Generator functions are well explained here: What does the "yield" keyword do in Python? I would just add that a normal function becomes a generator function at the very moment where you add a yield in it. Also, if you add a return statement the generation of iterables will end when reaching it (some generator functions do not have "return" and are thus infinite). Despite the simple use of generators I had some hard time transforming the original function into a generator function since it was a recursive function (i.e. calling itself). However, this entry shows how a recursive generator function looks like Help understanding how this recursive python function works? and so I could apply it to my function. Again, thanks to all for your support, Aleix
{ "pile_set_name": "StackExchange" }
Q: Rounding off percentages in plotly pie charts label=c("<25%","25 - 50%",">75%") values=c(4,2,3) df=data.frame(label,values) plot_ly(df, labels = ~label, values = ~values,text=values,textposition="auto", type = 'pie') %>%layout(title = 'Percentage Effort time',showlegend=T, xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE), yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)) When I run this code, I get a pie chart with percentages and the numbers. How can I obtain percentages that are rounded off to whole numbers instead of decimal points? A: You can use textinfo='text' to hide the percent values and provide a custom formatted label with text: text = ~paste(round((values / sum(values))*100, 0)), textinfo='text', Complete example: library(magrittr) library(plotly) label=c("<25%","25 - 50%",">75%") values=c(4,2,3) df=data.frame(label,values) plot_ly(df, labels = ~label, values = ~values, text = ~paste(round((values / sum(values))*100, 0)), #textinfo='none', #textinfo='label+value+percent', textinfo='text', textposition="auto", type = 'pie') %>% layout(title = 'Percentage Effort time', showlegend=T, xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE), yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE) )
{ "pile_set_name": "StackExchange" }
Q: How to make a click event occur in BackboneJs I'm just staring to learn backboneJs and im stuck with one issue here. I'm trying to POST a record to a list where im unable to perform a click event on the button that will post the record. Below is the view im using: BackboneView: var NewSubAccount = Backbone.View.extend({ initialize: function(){ }, el: '#sub-account-list' events:{ 'click #save' : 'saveList' }, render: function(id){ debugger; value = new SubAccountModel(); var template = $("#sub-account-list").html(_.template(createtmpl, {data:value.attributes})); }, saveList: function(){ debugger; value = new SubAccountModel(); var values = $('form#create-sub-account').serializeArray(); value.save(values, { success: function(value){ alert('hello'); } }); } }); HTML: <form id="create-sub-account" role="form"> <legend>Sub Account Creation</legend> <label><em>Account Name</em></label> <input type = "text" name ="name" value=""></input><br/> <label><em>Description</em></label> <input type = "text" name ="desc" value = ""></input><br/> <button type="submit" id="save">Save</button> <button id="cancel">Cancel</button> </form> EDIT: here is the router im using to render the 'newSubAccount': routes: { 'new': 'newSubAccount', }, events:{ 'click .create-sub-account' : 'savesubAccount' }, newSubAccount: function(){ var newsubaccount = new NewSubAccount(); newsubaccount.render(); }, When i perform the click event, it dorectly takes me back to the main page, without even going into the debug mode ( i set a debugger at the value = new SubAccountModel();, and it didnt go through. I'm wondering if my way of writing the click event is worng or im i missing something. Please anyone any ideas, appreciated. Thanks.Let me know if it needs more details. A: The problem you have is clicking on the #save button is submitting the form, this is what is reloading the page. There are a couple of options you can do: 1) Make the save button a plain button rather than a submit button, so that it doesn't try to submit the form: <button type="submit" id="save" type="button">Save</button> 2) If your intention is to use the save to submit the form, then you should capture the submit of the form rather than the click of the button and prevent the form from submitting the to the server, consider the following: var NewSubAccount = Backbone.View.extend({ el: '#sub-account-list' events:{ 'submit form#create-sub-account' : 'saveList' //Listen for the submit event on the form. }, render: function(id){ value = new SubAccountModel(); var template = $("#sub-account-list").html(_.template(createtmpl, {data:value.attributes})); }, saveList: function(event){ event.preventDefault(); // Prevent the form from submitting, as you are handling it manually value = new SubAccountModel(); var values = $('form#create-sub-account').serializeArray(); value.save(values, { success: function(value){ alert('hello'); } }); } }); The other advantage you get from listening to the form in this way, is that other methods of submitting the form (such as pressing enter) will also be collected and handled correctly as well. As a side note: You shouldn't have events in your router. Instead you should make views that handle all the user interaction. Router - Deals with the interaction between the browser state (URL) and what the user sees (UI). Its main focus should be converting the URL into Views on the page (the UI). View - Deals with the interaction between the user and the data. Its main focus is to display any data in the UI and allow the user to interact with it. For example, submitting a form. Model - Deals with the interaction between the browser and the server (AJAX requests). Its main focus should be to handle the data that is saved/fetched from the server. The View should use models to encapsulate data and display it in the UI.
{ "pile_set_name": "StackExchange" }
Q: Why is my print getting messed up mid-print? I am using Slic3r to generate the GCode for my Marlin-based printer. For some reason with increasing height my print starts to get messed up. On another part it starts to act like this when there are small parts. Is this related to my Slic3r settings, maybe to much filament being extruded or is this due to something else? Any help is highly appreciated and I can provide more pictures of messed up parts or slic3r config if necessary. A: To me, this looks like a combination of bad filament, high temperature and/or fast speeds. Too high extrusion temperature will make difficult to let each layer cool enough before the next layer begins. This is why you see the poor results on the smaller areas of the print in your second photo. If you're using bad filament (out of round, non-virgin, or poorly stored filament) you might see a series of over/under extrusion areas or smoke from moisture in the filament. Slowing down your feed rates can be tricky if your extrusion temps are too high. By slowing down, you're allowing layers to cool down a little bit more and solidify. If your previous layers are still relatively molten, you'll notice that the new layer of filament will adhere to it and potentially drag the previous layers as the nozzle continues to move. You'll see the results of this in the top-arc layers with an uneven curvature.
{ "pile_set_name": "StackExchange" }
Q: How to delete Javascript object property? I am trying to delete a object property which is shallow copy of another object. But the problem arises when I try to delete it, it never goes off while original value throws expected output. var obj = { name:"Tom" }; var newObj = Object.create(obj); delete newObj.name;//It never works! console.log(newObj.name);//name is still there A: newObj inherits from obj. You can delete the property by accessing the parent object: delete Object.getPrototypeOf(newObj).name; (which changes the parent object) You can also shadow it, by setting the value to undefined (for example): newObj.name = undefined; But you can't remove the property on newObj without deleting it from the parent object as the prototype is looked up the prototype chain until it is found. A: Basically Object.create will create an object , set its prototype as per the passed object and it will return it. So if you want to delete any property from the returned object of Object.create, you have to access its prototype. var obj = { name:"Tom" }; var newObj = Object.create(obj); delete Object.getPrototypeOf(newObj).name console.log(newObj.name); //undefined.
{ "pile_set_name": "StackExchange" }
Q: How to deal with 1 to many SQL (Table inputs) in Pentaho Kettle I have a situation where in i have the following tables. Employee - emp_id, emp_name, emp_address Employee_assets - emp_id(FK), asset_id, asset_name (1-many for employee) Employee_family_members - emp_id(FK), fm_name, fm_relationship (1-many for employee) Now, I have to run a scheduled kettle job which reads in the data from these tables in say batches of 1000 employees and create a XML output for those 1000 records based on the relationship in DB with family members and assets. It will be a nested XML record for every employee. Please note that the performance of this kettle job is very crucial in my scenario. I have two questions here - What is the best way to pull in records from the database for a 1-many relationship in schema? What is the best way to generate the XML output structure given that XML join steps are a performance hit? A: Here is how I have achieved this. So, there is one Table Input step to read the base table and subsequently create the XML chunk for it. Subsequently, in the flow, I am using the 1-many relationship (child table) as another Database join step passing the relationship key to it. Once the data is pulled out, the XMLs are generated for the child rows. This is then passed on to the Modified Java Script Value step(merge rows) which then merges the content using trans_Status = SKIP_TRANSFORMATION for similar rows. Once similar rows are merged/concatenated, the putRow(row) is used to dump it out as an output to the next step. Please note, that this required the SQL to have order by/sorted based on the relationship keys. This is performing alright, so I can proceed with it.
{ "pile_set_name": "StackExchange" }
Q: Is there simple “angularJS” way using ng-repeat directive, to replace characters in object.name string with other character directly? If the object's property name is Bob_Kenneth_Frank (as actual value) to Bob Kenneth Frank (displayed output) I unsuccessfully tried different variants of: html ng-repeat="myChange(person.name) in persons" in controller function myChange(name){ return name.replace(/_/g, " ") } A: Use a custom filter. See a working demo. angular.module('app').filter('replaceUnderscoreBySpace', function () { return function (input) { return input.replace(/_/g, ' '); }; }); View: <div ng-repeat="x in y"> {{x | replaceUnderscoreBySpace}} </div> Explanations on Todd Motto Blog
{ "pile_set_name": "StackExchange" }
Q: Concerned, freelancer I don't know may run off. How should I pay a freelancer? I've found an illustrator, who's work I really like. I saw his work online so have never met the person in 'real life'. He's named his price which is quite a lot of money. Therefore, I have concerns about paying someone who I don't really know. The last thing I'd want is for them to take off with my money without doing the work. I've proposed half now and half on completion, although half is still quite a lot of money. If possible, I don't want to go through one of those freelancing sites, like Elance, as I can imagine they'd probably take quite a large cut. How can I tackle payment safely so that I know the freelancer won't run off? A: For fixed price projects, depending on the size of the contract I always did 50% up front and 50% upon delivery. For larger contracts (+1500 euros) I took 30% up front. The freelancer thinks the same way: "I'm not going to do work if there is a chance the client just runs off with my work and doesn't pay me!". There is always a risk, but if the freelancer has decent references there is no reason he would want to run off: if he just does his job he gets another 50% or 70%. I never worked with escrow services, it just costs extra and I never heard of a freelancer taking half and just running off. Which of course doesn't offer any certainty, and I should mention I never worked with freelancers or clients that where more than a few hundred kilometers from me. A: This service seems like it offers the protection you require and gives a third party the funds until the freelancer has completed and delivered the product https://www.escrow.com/ Escrow.com reduces the risk of fraud by acting as a trusted third-party that collects, holds and only disperses funds when both Buyers and Sellers are satisfied. A: So you want a feast without spending an ounce of flour? If you find a solution I would like to hear it as well :). Working with a remote freelancer is always risky. That's why you always start with small and in time increase amount of work. Why don't you give him to do only a part of a job?! Paying 50% of the small part is worth of risk. If you however started with a large project, then you're probably not so good with money planning and you will eventually be hurt. You have to build trust with the remote freelancer first. Next, web services like odesk or elance offer clients a great comfort since you can review freelancer's portfolio and your money is pretty safe in fixed-price projects. And they charge you for that safety. Lastly, services like Skrill offer money escrow so you may take a look at that as well. PS. I am writing this thinking that you two cannot sign a liable contract e.g. you cannot sue him efficiently. If you can sign a good contract where he can financially be responsible for bad work, then sign it.
{ "pile_set_name": "StackExchange" }
Q: Term symbols for nitrogen: determining J I'm trying to figure out what terms are possible for nitrogen with the electron configuration $\ce{[He] 2s^2 2p^3}$. There is an old question on StackExchange and the corresponding answer was a great help already but doesn't mention $J$ or specify what terms exactly are possible. I'll try to explain how I would determine the possible terms: The s-electrons needn't be considered for they complete the s subshell, this means I'm left with three p-electrons. I do get the same results for the possible values of $L$ and $S$ as user orthocresol provided with his answer namely: $L=3,2,1,0$ $S=3/2, 1/2$ Now the possible values of J range from $L+S$ to $|L-S|$: For $L=0$ there are two S-Terms*: $^4\!S$ and $^2\!S$ giving $$^4\!S_{3/2} \quad ^2\!S_{1/2}$$ $L=1$ gives two terms*: $^4\!P$ and $^2\!P$, the former term has the following possible J values: $J = 5/2, 3/2, 1/2$ and the latter: $J=3/2, 1/2$. The P-Terms of this electron configuration are: $$^4\!P_{5/2} \quad ^4\!P_{3/2} \quad ^4\!P_{1/2} \quad ^2\!P_{3/2}\quad ^2\!P_{1/2}$$ Doing the same for $L=2$ there are two D-Terms*: $^4\!D$ and $^2\!D$, possible J values for the former: $J = 7/2, 5/2, 3/2, 1/2$ and for the latter: $J = 5/2, 3/2$. This gives six different terms. I'm stopping at this point because I think I'm not doing it right. Using the NIST ASD I only see five terms with this electron configuration in the Grotrian diagram: $$^4\!S_{3/2}, ^2\!D_{5/2}, ^2\!D_{3/2}, ^2\!P_{1/2}, ^2\!P_{3/2}$$ and according to the book "Physical Chemistry: A Molecular Approach" Table 8.4 for three p-electrons only $^2\!P,^2\!D,^4\!S$ Terms are possible. What's wrong with my approach that I'm that much off? *Question on the side: I don't think it's correct to use the term "term" here because what I'm talking about is split into actual terms. Is there a way to refer to, for example, the $^4\!D$-Terms in general, maybe term system? A: Firstly, regarding the extra question: Atkins' Molecular Quantum Mechanics (5th ed.) uses "term" for $^2\!S$, and "level" for $^2\!S_{1/2}$. Back to the main question. It's been a long time since I did term symbols, so I am happy to be corrected, but if I am not wrong, your $^4\!P$, $^4\!D$, and $^2\!S$ terms are not allowed because of the Pauli exclusion principle. The argument is pretty similar to the one in the comments on my answer, which you're already aware of. A term with $S = 3/2$ must have a set of states with $M_S = +3/2, +1/2, -1/2, -3/2$. Likewise, a $P$ term with $L = 1$ must also have a set of states with $M_L = +1, 0, -1$. Consequently, the total number of states associated with a single term $^{2S+1}\!L$ is $(2S+1)(2L+1)$. (The total number of states in a level, $^{2S+1}\!L_J$, is $2J+1$, and you can also show that the sum of this over the allowed values of $J$ is equal to $(2S+1)(2L+1)$.) One of those twelve states in the purported $^4\!P$ term must have $(M_S, M_L) = (+3/2, +1)$. However, $M_S = +3/2$ can only be achieved if all three electrons have the same spin (spin up in this case), which in turn necessitates that the three electrons are all in different p-orbitals, such that $M_L = \sum m_l = +1 + 0 + -1 = 0$. Ergo, a state with $(M_S, M_L) = (+3/2, +1)$ cannot exist, and the entire term $^4\!P$ cannot be possible. The same argument also applies to the $^4\!D$ term. I suspect that showing that the $^2\!S$ term is forbidden is somewhat trickier. I had a similar issue before with carbon, which is an easier system to understand (only two electrons to consider instead of three), so maybe you will find this useful: Pauli-forbidden term symbols for atomic carbon. Out of the three surviving terms ($^2\!P$, $^2\!D$, $^4\!S$) you already see from NIST that all the possible $J$ values (from $|L-S|$ to $L+S$) are allowed, so there is no issue with your calculation of $J$.
{ "pile_set_name": "StackExchange" }
Q: jQuery body click problem I have a div I want to hide when clicking outside it. It almost works, except the button class is only changing once every two times. I click on the button, the active button class is added and the dropdown slides down, I click somewhere outside the dropdown, it slides up and the button class returns to it's original state. BUT, when I repeat this, the button class 'isActive' is not added. Here's the function: function toggleSelectGroupList(){ $('#groupListSortby').slideToggle(30); $('body').click(function(){ $('#groupListSortby').click(function(e) { e.stopPropagation(); }) $('#groupListSortby').hide(); $('.sortFriends .btngrey .gfx').toggleClass('isActive'); $('.sortFriends .btngrey a').toggleClass('isActive'); }); } Markup: <div class="sortFriends"> <div class="btngrey"> <span class="gfx"></span> <a onClick="toggleSelectGroupList()">All friends</a> </div> <div class="dropdownList" id="groupListSortby"> <ul> <li class="isActive"> <span class="gfx"></span> <a href="#">All friends</a> </li> <li> <a href="#">Recently added</a> </li> <li class="last"> <a href="#">The Railers</a> </li> </ul> </div> </div> A: You should bind your click handlers from the beginning, and the propagation stop should be immediately bound as well, like this overall: $(function() { $(".sortFriends .btngrey a").click(function(e) { $('#groupListSortby').slideToggle(30); $('.sortFriends .btngrey .gfx, .sortFriends .btngrey a').toggleClass('isActive'); e.stopPropagation(); }); $('#groupListSortby').click(function(e) { e.stopPropagation(); }); $('body').click(function(){ $('#groupListSortby').hide(); $('.sortFriends .btngrey .gfx, .sortFriends .btngrey a').removeClass('isActive'); }); }); To match, your <a> shouldn't have an onclick inline with this anymore, just this will do: <div class="btngrey"> <span class="gfx"></span> <a href="#">All friends</a> </div> You can test it out here.
{ "pile_set_name": "StackExchange" }
Q: Analytical approximation of indefinite integral on a given interval to a given precision I'm looking for an analytical approximation of $\int_a^b e^{-x^2}\mathrm{erf}(x+c) dx$ that would be accurate to precision $\varepsilon$ for $a,b,c$ within a certain range. How do I ask Mathematica for that? I tried to Integrate the above expression, but no analytical solutions were found. A: One can construct a Chebyshev series approximation to the integrand for an interval, such as -5 <= x <=5 mentioned in the comments, and integrate it to get a series expansion for the integral. It is well known that Chebyshev series representation have numerical advantages over power series. I saw a comment about a NPU-supported method, but I don't know what that is, this being a Mathematica site. Most numerical systems have access to an FFT, in one way or another, I think, and, of course, to trigonometric functions. That is all that is really needed. Some auxiliary functions used here (code below): chebSeries[f, {a, b}, n, precision] computes the Chebyshev expansion of order n for f[x] over a <= x <= b. iCheb[c, {a, b}, k] integrates the Chebyshev series c, plus k. f = chebFunc[c,{a,b}], computes the function represented by the Chebyshev coefficients c = {c0, c1,...} over the interval {a, b}. The first step is to compute the coefficients of the integrand as a function of x for a given value of c. The are saved (memoized) for the sake of speed, but it is not essential. An antiderivative of the integrand is computed with iCheb[coeff[c], {-5, 5}]. Depending on c, one needs a series of order 70 to 90+ to get a theoretical error of less than machine precision, so computing one of order 2^7 = 128 is sufficient for all c. (See Boyd, Chebyshev and Fourier Spectral Methods, Dover, New York, 2001, ch. 2., for a discussion of the convergence theory of Chebyshev series.) ClearAll[coeffs]; coeffs[c_?NumericQ] := coeffs[c] = Module[{ cc, (* Chebyshev coefficients *) pg = 16, (* Precision goal: *) sum, (* sum of tail = error bound *) max, (* max coefficient to measure rel. error *) len}, (* how many terms of the tail to drop *) cc = chebSeries[Function[x, Exp[-x^2] Erf[x + c]], {-5, 5}, 128]; max = Max@Abs@cc; sum = 0; (* trim tail of series of unneeded coefficients (smaller than desired precision) *) len = LengthWhile[Reverse[cc], (sum += Abs[#1]) < 10^-pg max &]; Drop[cc, -len] ]; Next we can define the user's sought-after function in terms of the antiderivative: func[a_, b_, c_] := With[{antiderivative = chebFunc[ N@iCheb[coeffs[SetPrecision[c, Infinity]], {-5, 5}, 0], {-5, 5}]}, antiderivative[b] - antiderivative[a] ]; The following computes the relative and absolute error of func on a hundred random inputs, using a high-precision NIntegrate[] to compute the "true" value. cmp[a_, b_, c_] := {(#1 - #2)/#2, #1 - #2} &[ func[a, b, c], NIntegrate[Exp[-x^2] Erf[x + SetPrecision[c, Infinity]], {x, a, b}, WorkingPrecision -> 40] ] ListLinePlot[ Transpose@RealExponent[cmp @@@ RandomReal[{-5, 5}, {100, 3}]], PlotRange -> {-20, 0}, PlotLabel -> "Error", PlotLegends -> {"Rel.", "Abs."}] The yellow line shows the absolute error is limited to a few ulps. The theoretical bound on the error does not take into account rounding error (in both the coefficients and the evaluation of the series). The lines that drop off the bottom are the result of an error of zero. Auxiliary functions (* Chebyshev extreme points *) chebExtrema::usage = "chebExtrema[n,precision] returns the Chebyshev extreme points of order n"; chebExtrema[n_, prec_: MachinePrecision] := N[Cos[Range[0, n]/n Pi], prec]; (* Chebyshev series approximation to f *) Clear[chebSeries]; chebSeries::usage = "chebSeries[f,{a,b},n,precision] computes the Chebyshev expansion \ of order n for f[x] over a <= x <= b."; chebSeries[f_, {a_, b_}, n_, prec_: MachinePrecision] := Module[{x, y, cc}, x = Rescale[chebExtrema[n, prec], {-1, 1}, {a, b}]; y = f /@ x; (* function values at Chebyshev points *) cc = Sqrt[2/n] FourierDCT[y, 1]; (* get coeffs from values *) cc[[{1, -1}]] /= 2; (* adjust first & last coeffs *) cc ]; (* Integrate a Chebyshev series -- cf. Clenshaw-Norton, Comp.J., 1963, p89, eq. (12) *) Clear[iCheb]; iCheb::usage = "iCheb[c, {a, b}, k] integrates the Chebyshev series c, plus k"; iCheb[c0_, {a_, b_}, k_: 0] := Module[{c, i, i0}, c[1] = 2 First[c0]; c[n_] /; 1 < n <= Length[c0] := c0[[n]]; c[_] := 0; i = 1/2 (b - a) Table[(c[n - 1] - c[n + 1])/(2 (n - 1)), {n, 2, Length[c0] + 1}]; i0 = i[[2 ;; All ;; 2]]; Prepend[i, k - Sum[(-1)^n*i0[[n]], {n, Length[i0]}]]] (* chebFunc[c,...] computes the function represented by a Chebyshev series *) chebFunc::usage = "f = chebFunc[c,{a,b}], c = {c0,c1,...} Chebyshev coefficients, over the interval {a,b} y = chebFunc[c,{a,b}][x] evaluates the function"; chebFunc[c_, dom_][x_] := chebFunc[c, dom, x]; chebFunc[c_?VectorQ, {a_, b_}, x_] := Cos[Range[0, Length[c] - 1] ArcCos[(2 x - (a + b))/(b - a)]].c; Update: Comparison of Chebyshev and power series Perhaps it would be worth illustrating the difference between power series and Chebyshev series approximations for those who are not familiar with it. (One should become familiar with it, for Chebyshev expansions are to functions what decimal expansions are to numbers.) Key differences: Symbolic series expansion of the function Erf[x + c] grows extremely fast and takes a much longer time to evaluate than the DCT-I used to compute the Chebyshev coefficients. Attempting a degree 40 expansion hanged the computer and I had to kill the kernel. Aside from not being able to compute the series expansion to arbitrary order, it is probably impossible to get convergence for a fixed precision due to rounding error. At machine precision, you cannot even get 2 digits throughout the interval {c, -5, 5}, for a = -4, b = 4 up to order 25. OTOH, the Chebyshev series has an exponential order of convergence and can nearly achieve machine precision with machine precision coefficients. It is fairly easy to figure out when you have enough terms of a Chebyshev series $\sum a_j T_j$, because the error is bounded by the tail $\sum |a_j|$ and the $a_n \rightarrow 0$ roughly geometrically on average. If you don't have fast trigonometric functions, then instead of the code in chebFunc above, you can use Clenshaw's algorithm (see chebeval) to evaluate the series. Here's another implementation of Mariusz's power series idea. I speed up the integration with a "power rule" int[{n}] for $$ \int \exp\left(-x^2\right) x^n \; dx\,.$$ Of course it turned out that Series was the bigger bottleneck. ClearAll[sol, int]; int[{0}] = Integrate[Exp[-x^2], x, Assumptions -> x ∈ Reals]; int[{n_}] = Integrate[Exp[-t^2] t^n, {t, 0, x}, Assumptions -> n > 0 && n ∈ Integers && t ∈ Reals]; $seriesCoefficientPart = 3; sol[n_] := sol[n] = Total@MapIndexed[ First@Differences[#1 int[#2 - 1] /. {{x -> a}, {x -> b}}] &, Series[Erf[x + c], {x, 0, n}][[$seriesCoefficientPart]] ]; (* Times *) First@*AbsoluteTiming@*sol /@ {2, 10, 20, 22, 23, 24, 25} (* {0.013267, 0.071065, 2.01908, 7.6296, 23.4752, 33.1553, 48.3542} *) (* Sizes *) LeafCount /@ sol /@ {2, 10, 20, 22, 23, 24, 25} (* {163, 693, 2413, 2765, 1100459, 1779935, 2879267} *) Chebyshev speed for c = 4, per evaluation of c: First@AbsoluteTiming@func[a, b, 4, #] & /@ {2, 10, 20, 25} (* {0.002047, 0.000184, 0.000248, 0.000276} *) To illustrate the issue with power series, the graphics below shows the error in approximating Erf[x + c] by its Taylor series (times Exp[-x^2] for c = -4, -2, 0, 2, 4 and various orders. It does pretty good for Abs[x] < 1 as the order increases, but it gets worse for Abs[x] > 4. GraphicsRow[ Table[ Plot[ Evaluate@Table[ Exp[-x^2] (Erf[x + c] - Normal@Series[Erf[x + c], {x, 0, n}]) // RealExponent, {c, -4, 4, 2}], {x, -5, 5}, PlotRange -> {-18, 0}, Frame -> True, Axes -> False, PlotLabel -> Row[{"Order ", n}], AspectRatio -> 1, FrameLabel -> {"x", "Log error"}], {n, {2, 10, 20, 25}}], PlotLabel -> "Error in approximating integrand by power series"] The two plots below compare the absolute error of approximating by power series and by Chebyshev series. The convergence of the Chebyshev series is remarkable by comparison. Plot[Evaluate@Table[ sol[n] - exact[a, b, c] /. {a -> -4, b -> 4} // RealExponent, {n, {2, 10, 20, 25}}], {c, -5, 5}, PlotRange -> {-18, 0}, Frame -> True, Axes -> False, GridLines -> {None, -Range[2, 16, 2]}, PlotLabel -> "Log error for power series of order n", FrameLabel -> {"c", "Log error"}, PlotLegends -> {2, 10, 20, 25}] Plot[Evaluate@Table[ func[a, b, c, n] - exact[a, b, c] /. {a -> -4, b -> 4} // RealExponent, {n, {2, 10, 20, 30, 40, 50, 60}}], {c, -5, 5}, PlotRange -> {-18, 0}, Frame -> True, Axes -> False, GridLines -> {None, -Range[2, 16, 2]}, PlotLabel -> "Log error for Chebyshev series of order n", FrameLabel -> {"c", "Log error"}, PlotLegends -> {2, 10, 20, 30, 40, 50, 60}] Determining the order of the approximation: trim[cc_, eps_] := Module[{sum, max, len}, max = Max@Abs@cc; sum = 0; len = LengthWhile[Reverse[cc], (sum += Abs[#1]) < eps max &]; Drop[cc, -len] ] Manipulate[ With[{cc = iCheb[chebSeries[Exp[-#^2] Erf[# + c] &, -5, 5, 128, 32], {-5, 5}]}, With[{order = Length@trim[cc, 10^-accuracy]}, ListPlot[ RealExponent@cc, PlotLabel -> Column[{ Row[{"Chebyshev coefficients a[n] for ", HoldForm["c"] -> Chop[N[c, {2, 1.5}], 0.05], ", "}], Row[{"For accuracy ", SetPrecision[10^-accuracy, 2], " use order ", order}] }, Alignment -> Center], Frame -> True, FrameLabel -> {"n", "exponent of a[n]"}, GridLines -> {{order}, {-accuracy}}, PlotRange -> {-31, 1}] ]], {{c, 4}, -5, 5, 1/10}, {{accuracy, 16.}, 2, 28}] Addendum: Failed ideas - Maybe someone can make them work... The Chebyshev series of Exp[-x^2] can be computed over {-x0, x0} exactly in terms of modified Bessel functions BesselI[]. Therefore, so can the series for Erf[x]. I was seduced into trying to come up with a way to compute the OP's function in this way but the +c in Erf[x + c] was too ornery. One thing that would be needed is a way to write ChebyshevT[n, x + c] as a Chebyshev series in ChebyshevT[n, x]. The coefficients would be polynomials in c (with integer coefficients), which themselves could be represented as Chebyshev expansions. This can be done, in fact, but it's a bit cumbersome and slow. Further the Chebyshev coefficients for n = 64 get bigger than 2^100, and I worried about numerical stability. For the moment, I have given up without testing it. The way above seems superior, in simplicity, as well as (probably) in speed and numerics. A: Maybe so: Expand with Series a function Erf[x+c] e.g for order 2. n = 2; func = Normal@Series[Erf[x + c], {x, 0, n}] $-\frac{2 c e^{-c^2} x^2}{\sqrt{\pi }}+\frac{2 e^{-c^2} x}{\sqrt{\pi }}+\text{erf}(c)$ sol = Simplify@Integrate[Exp[-x^2]*func, {x, a, b}] $\frac{-c e^{-c^2} \left(2 e^{-a^2} a-\sqrt{\pi } \text{erf}(a)-2 b e^{-b^2}+\sqrt{\pi } \text{erf}(b)\right)+2 e^{-c^2} \left(e^{-a^2}-e^{-b^2}\right)+\pi \text{erf}(c) (\text{erf}(b)-\text{erf}(a))}{2 \sqrt{\pi }}$ Check numerics: a = -4; b = 4; c = 4; sol2 = NIntegrate[Exp[-x^2]*Erf[x + c], {x, a, b}] (*1.77234*) sol // N (*1.77245*) From Documentation Center Precision[x] is- Log[10, dx/x]. -Log[10, Abs[(sol - sol2)/sol2]] (*4.20019*) I have 4 significant digit. From OP qestion: Can Mathematica predict for the given function and interval how many terms it needs in the Series for the accuracy ϵ on that interval? Yes I use NonlinearModelFit.Generate data for order n from 1 to 20; data = Table[{n, func = Normal@Series[Erf[x + c], {x, 0, n}]; sol = Simplify@Integrate[Exp[-x^2]*func, {x, a, b}]; a = -4;(*Interval (a,b)*) b = 4; c = 4; sol2 = NIntegrate[Exp[-x^2]*Erf[x + c], {x, a, b}]; sol1 = (sol /. c -> 4 /. a -> -4 /. b -> 4) // N; -Log[10, Abs[(sol1 - sol2)/sol2]]}, {n, 1, 20}] (*{{1, 4.19844}, {2, 4.20019}, {3, 4.20019}, {4, 4.21306}, {5, 4.21306}, {6, 4.27069}, {7, 4.27069}, {8, 4.46324}, {9, 4.46324}, {10, 5.23787}, {11, 5.23787}, {12, 4.86359}, {13, 4.86359}, {14, 5.124}, {15, 5.124}, {16, 5.10868}, {17, 5.10868}, {18, 5.37338}, {19, 5.37338}, {20, 5.20063}}*) nlm = NonlinearModelFit[data, a1 + a2*Exp[a3*n + a4], {a1, a2, a3, a4}, n] Normal@nlm Model: $1.15801 e^{0.00463001 n+2.53736}-10.621$ Show[Plot[Normal@nlm, {n, 0, 20}], ListPlot[data], AxesOrigin -> {0, 0}, PlotRange -> {Automatic, {0, 5.5}}, AxesLabel -> {n, "significant digits"}] for n=20 I have: nlm[20] (*5.44438*) 5 significant digit. for n=200 I have: nlm[200] (*26.3475*) 26 significant digit. You may change a model in NonlinearModelFit.Maybe my model is not the best.
{ "pile_set_name": "StackExchange" }
Q: How can i create multiple markers on a google map? I need to show multiple pointers based on the given latitude and longitude values.I did one sample but it comes only one pointers.As shown code below. Meteor Js Code : this are my objects var latlong1 = { lat: 17.385044, long: 78.486671 } console.log("* 2 *"); var latlong2 = { lat: 16.306652, long: 80.436540 } var latlong3 = { lat:15.505723, long: 80.049922 } var latlong4 = { lat: 15.317277, long: 75.713888 } i know i can create it like this. var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, long), map: map, draggable: true, animation: google.maps.Animation.DROP, icon: icon }); and use values inside the position new google.maps.LatLng(latlong3.lat, latlong3.long) But there is another way? A: You should first Create an array based on that object values. var latLong =[]; and lester create a simple function. function createMarkers(){ for(var i = 0 ; i <latLong.length ; i++) { lat = latLong[i].lat; long = latLong[i].long; var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, long), map: map, icon: 'http://Yourimagesourcehere' }); } } Test and tell me.
{ "pile_set_name": "StackExchange" }
Q: R calculated variable from integer variable - how? I have a variable (HTB) which is an integer - it can have a value of either 1 or 2. I have done some calaculations which have involved aggregating HTB by user name - so I know how often the user got a 1 or a 2 response The resulting data frame therefore displays variables HTB.1 and HTB.2 I would like to calculate the percentage of HTB=2 for each user but this results$HTBpercent<-results$HTB.2/(results$HTB.1+results$HTB.2)*100 does not work (presumably because it is really one variable) How do I do this? A: You probably have something like: df <- aggregate(c(1,1,2,2), list(c(1,2,1,2)), FUN=table) df # Group.1 x.1 x.2 #1 1 1 1 #2 2 1 1 ...where df$x is a matrix, like: df$x # 1 2 #[1,] 1 1 #[2,] 1 1 Therefore, df$perc2 <- df$x[,"2"] / rowSums(df$x) df # Group.1 x.1 x.2 perc2 #1 1 1 1 0.5 #2 2 1 1 0.5
{ "pile_set_name": "StackExchange" }
Q: How can dhcpcd ignore static IP settings in /etc/dhcpcd.conf? Yesterday I had to switch my home network back from DHCP to static IPs, but my Raspberry Pi 3B (with the current Raspbian) keeps on using an invalid IP address, namely: eth0 Link encap:Ethernet HWaddr b8:27:eb:4c:cb:8c inet addr:169.254.168.86 Bcast:169.254.255.255 Mask:255.255.0.0 inet6 addr: fe80::243a:4333:fc91:c87/64 Scope:Link The address isn't even valid for my network, as its address is now this one: 169.254.164.0/24 After reading a couple of answers here at SE, I edited my /etc/dhcpcd.conf as follows: # A sample configuration for dhcpcd. # See dhcpcd.conf(5) for details. # Allow users of this group to interact with dhcpcd via the control socket. #controlgroup wheel # Inform the DHCP server of our hostname for DDNS. hostname # Use the hardware address of the interface for the Client ID. clientid # or # Use the same DUID + IAID as set in DHCPv6 for DHCPv4 ClientID as per RFC4361. #duid # Persist interface configuration when dhcpcd exits. persistent # Rapid commit support. # Safe to enable by default because it requires the equivalent option set # on the server to actually work. option rapid_commit # A ServerID is required by RFC2131. require dhcp_server_identifier # Generate Stable Private IPv6 Addresses instead of hardware based ones slaac private # A hook script is provided to lookup the hostname if not set by the DHCP # server, but it should not be run by default. nohook lookup-hostname # Configures eth0 for a static IP address and routing. # Added 2017/12/25 by JR. interface eth0 static ip_address = 169.254.164.3/24 static routers = 169.254.164.1 static domain_name_servers = 212.6.64.14 The DHCP client restarts nicely: ● dhcpcd.service - dhcpcd on all interfaces Loaded: loaded (/lib/systemd/system/dhcpcd.service; enabled) Active: active (running) since Sun 2017-12-24 22:28:40 CET; 12min ago Process: 1396 ExecStop=/sbin/dhcpcd -x (code=exited, status=0/SUCCESS) Process: 1401 ExecStart=/sbin/dhcpcd -q -b (code=exited, status=0/SUCCESS) Main PID: 1402 (dhcpcd) CGroup: /system.slice/dhcpcd.service └─1402 /sbin/dhcpcd -q -b Dec 24 22:28:40 autoradio dhcpcd[1401]: dev: loaded udev Dec 24 22:28:40 autoradio systemd[1]: Started dhcpcd on all interfaces. Dec 24 22:28:40 autoradio dhcpcd[1402]: DUID 00:01:00:01:1e:da:f2:49:b8:27:eb:94:1f:4d Dec 24 22:28:40 autoradio dhcpcd[1402]: eth0: IAID eb:4c:cb:8c Dec 24 22:28:40 autoradio dhcpcd[1402]: wlan0: waiting for carrier Dec 24 22:28:40 autoradio dhcpcd[1402]: eth0: soliciting a DHCP lease Dec 24 22:28:40 autoradio dhcpcd[1402]: eth0: soliciting an IPv6 router Dec 24 22:28:50 autoradio dhcpcd[1402]: eth0: using IPv4LL address 169.254.168.86 Dec 24 22:28:50 autoradio dhcpcd[1402]: eth0: adding route to 169.254.0.0/16 Dec 24 22:28:52 autoradio dhcpcd[1402]: eth0: no IPv6 Routers available But: The client neither sets the IP address, nor standard route, so that I've gotta do this manually. Why? Does anybody know what's wrong here? Any help would be greatly appreciated. UPDATE: The server is now complaining about a "martial" IP of my Raspi: [15741.931325] IPv4: martian source 169.254.164.1 from 169.254.168.86, on dev eth2 [15741.931331] ll header: 00000000: ff ff ff ff ff ff b8 27 eb 4c cb 8c 08 06 .......'.L.... UPDATE #2: Upon another user's request, here's the current dhcpcd.conf: pi@autoradio:~ $ cat /etc/dhcpcd.conf hostname persistent option rapid_commit option domain_name_servers, domain_name, domain_search, host_name option classless_static_routes option ntp_servers require dhcp_server_identifier slaac private nohook lookup-hostname # Configures eth0 for a static IP address and routing. # Added 2017/12/25 by JR. interface eth0 #static ip_address = 169.254.164.3/24 #static routers = 169.254.164.1 #static domain_name_servers = 212.6.64.14 A: It is FUTILE trying to set a Link-local address These are NOT routable and are NOT static. If you absolutely MUST set a static address How to set up Static IP Address explains how to do it.
{ "pile_set_name": "StackExchange" }
Q: Linux: how to move each file into a correspondingly named folder I have a small but interesting task here. I have a list of files with same extension, for ex. a.abc b.abc c.abc What I want here is to first create folders called a, b, c... for each .abc file, and then move each one into its folder. I was able to get the first step done pretty straightforwardly using a cmd line find ... | sed ... | xargs mkdir..., but when I tried to use a similar cmd to move each file into its own folder, I couldn't find the answer. I'm not fluent with the cmd here, and I have a very fuzzy memory that in find cmd I can use some kind of back reference to reuse the file/directory name, did I remember it wrong? Searched it up but couldn't find a good reference. Can anyone help me to complete the cmd here? Thanks. A: Here's your one liner find . -name "*.abc" -exec sh -c 'NEWDIR=`basename "$1" .abc` ; mkdir "$NEWDIR" ; mv "$1" "$NEWDIR" ' _ {} \; or alternatively find . -name "*.abc" -exec sh -c 'mkdir "${1%.*}" ; mv "$1" "${1%.*}" ' _ {} \; And this is a better guide at using find than the man page. This page explains the parameter expansion that is going on (to understand the ${1%.*} A: Here is a find and xargs solution which handles filenames with spaces: find . -type f -print0 | xargs -0 -l sh -c 'mkdir "${1%.*}" && mv "$1" "${1%.*}"' sh Note that it does not support filenames with newlines and/or shell-expandable characters.
{ "pile_set_name": "StackExchange" }
Q: Hibernate Search behaves differently between DEV and PROD with same databse I have one domain object that needs to be indexed by Hibernate Search. When I do a FullTextQuery on this object on my DEV machine, I get the expected results. I then deploy the app to a WAR and explode it to my PROD server (a VPS). When I perform the same "search" on my PROD machine, I don't get the expected results at all (it seems like some results are missing). I've run LUKE to ensure that everything was properly indexed, and it appears that everything is where it should be... I'm new to Hibernate Search, so any help would be appreciated. Here's my domain Object: package com.chatter.domain; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.apache.solr.analysis.LowerCaseFilterFactory; import org.apache.solr.analysis.SnowballPorterFilterFactory; import org.apache.solr.analysis.StandardTokenizerFactory; import org.hibernate.search.annotations.AnalyzerDef; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.IndexedEmbedded; import org.hibernate.search.annotations.Parameter; import org.hibernate.search.annotations.Store; import org.hibernate.search.annotations.TokenFilterDef; import org.hibernate.search.annotations.TokenizerDef; @Entity @Table(name="faq") @Indexed() @AnalyzerDef(name = "customanalyzer", tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class), filters = { @TokenFilterDef(factory = LowerCaseFilterFactory.class), @TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = { @Parameter(name = "language", value = "English") }) }) public class CustomerFaq implements Comparable<CustomerFaq> { private Long id; @IndexedEmbedded private Customer customer; @Field(index=Index.TOKENIZED, store=Store.NO) private String question; @Field(index=Index.TOKENIZED, store=Store.NO) private String answer; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="customer_id") public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } @Column(name="question", length=1500) public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } @Column(name="answer", length=1500) public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CustomerFaq other = (CustomerFaq) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public int compareTo(CustomerFaq o) { if (this.getCustomer().equals(o.getCustomer())) { return this.getId().compareTo(o.getId()); } else { return this.getCustomer().getId().compareTo(o.getCustomer().getId()); } } } Here's a snippet of my Customer domain object: import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Store; import javax.persistence.Entity; // ... other imports @Entity public class Customer { @Field(index=Index.TOKENIZED, store=Store.YES) private Long id; // ... other instance vars @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } And my persistence.xml: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/> <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database --> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/> <property name="hibernate.connection.charSet" value="UTF-8"/> <!-- Hibernate Search configuration --> <property name="hibernate.search.default.directory_provider" value="filesystem" /> <property name="hibernate.search.default.indexBase" value="C:/lucene/indexes" /> </properties> </persistence-unit> </persistence> And finally, here's the query that's being used in a DAO: public List<CustomerFaq> searchFaqs(String question, Customer customer) { FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession()); QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(CustomerFaq.class).get(); org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("question", "answer").matching(question).createQuery(); org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, CustomerFaq.class); List<CustomerFaq> matchingQuestionsList = fullTextQuery.list(); log.debug("Found " + matchingQuestionsList.size() + " matching questions"); List<CustomerFaq> list = new ArrayList<CustomerFaq>(); for (CustomerFaq customerFaq : matchingQuestionsList) { log.debug("Comparing " + customerFaq.getCustomer() + " to " + customer + " -> " + customerFaq.getCustomer().equals(customer)); log.debug("Does list already contain this customer FAQ? " + list.contains(customerFaq)); if (customerFaq.getCustomer().equals(customer) && !list.contains(customerFaq)) { list.add(customerFaq); } } log.debug("Returning " + list.size() + " matching questions based on customer: " + customer); return list; } A: It looks like the actual location where my software was looking for the indexBase was incorrect. When I looked through the logs, I noticed that it was referring to two different locations when loading the indexBase. One location that Hibernate Search was loading this indexBase was from "C:/Program Files/Apache Software Foundation/Tomcat 6.0/tmp/indexes", then a little later on in the logs (during the startup phase) I saw that it was also loading from the place I had set it to in my persistence.xml file ("C:/lucene/indexes"). So realizing this, I just changed the location in my persistence.xml file to match the location that it was (for some reason) also looking. Once those two matched up, BINGO, everything worked!
{ "pile_set_name": "StackExchange" }
Q: Vim autoindent (gg=G) is terribly broken for JS indentation My end goal here is to use gg=G to autoindent all of my JS code compliant to an eslintrc.js file. So, currently I have syntastic and vim-javascript looking at my JS code with the following in my .vimrc let g:syntastic_javascript_checkers=["eslint"] Lets say that I have some decent JS like the following const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const PATHS = { app : path.join(__dirname, 'app'), build : path.join(__dirname, 'build'), }; const commonConfig = { entry : { app : PATHS.app, }, output : { path : PATHS.build, filename : '[name].js', }, plugins : [ new HtmlWebpackPlugin({ title : 'Webpack Demo', }), ], }; The gg=G (normal mode) command mutilates the above into the following. const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const PATHS = { app : path.join(__dirname, 'app'), build : path.join(__dirname, 'build'), }; const commonConfig = { entry : { app : PATHS.app, }, output : { path : PATHS.build, filename : '[name].js', }, plugins : [ new HtmlWebpackPlugin({ title : 'Webpack Demo', }), ], }; Which is not cool. Btw, vim-js-indent and vim-jsx-improve didn't do anything either. Any help is very welcome, many thanks are in advance. A: Your "not cool" example is the result of the "generic" indenting you get when Vim didn't recognize your buffer as JavaScript and/or didn't apply JavaScript-specific indentation rules. That code is indented correctly with this minimal setup: $ vim -Nu NONE --cmd 'filetype indent on' filename.js which: detects that your buffer contains JavaScript, applies JavaScript-specific indentation rules. To ensure proper indenting, you must add this line to your vimrc: filetype indent on
{ "pile_set_name": "StackExchange" }
Q: How to insert Flash without JavaScript in the most compatible but valid way? I'm looking for a way to embed Flash into a XHTML Transitional page that does not rely on enabled JavaScript, which validates and that works across all major Browsers including IE6. So far I'm using this solution which seems to work just fine: http://latrine.dgx.cz/how-to-correctly-insert-a-flash-into-xhtml#toc-final-solution However, when this method is used in an RSS Feed it seems that Feedburner and Google Reader at least (maybe other feed readers, too) strip the whole object tags and only leave the alternative content. Any suggestions how to improve this? A: Google Reader only support the embed tag :-/ http://www.google.com/support/reader/bin/answer.py?hl=en&answer=70664
{ "pile_set_name": "StackExchange" }
Q: Execute commands in a file I am using the 2003 textbook - http://www.amazon.com/Unix-Shell-Programming-3rd-Edition/dp/0672324903 My OS is linux L-ubuntu 13 which is not based on POSIX (I think) It says that I can store who | wc -l in a file called nu and then execute nu. But, before that I need to make this file executable by using chmod +x file(s). This does not work. How do I make the nu "command" work ? I know I can do it by naming nu as nu.sh and then doing bash nu.sh, but I want to try this way also. A: To execute a file that is not in the PATH, you must give a properly qualified directory name. While giving the name of the file in the current directory is sufficient as an argument to a program, in order to execute a shell script or other executable file, you must give at least a relative path. For example, if the file is in your home directory, which is also the working directory, any of the following are acceptable: ./nu ~/nu /home/username/nu However, simply nu will only attempt to search the PATH, which probably includes places such as /bin, /usr/bin, and so on.
{ "pile_set_name": "StackExchange" }
Q: Objective C - when should "typedef" precede "enum", and when should an enum be named? In sample code, I have seen this: typedef enum Ename { Bob, Mary, John} EmployeeName; and this: typedef enum {Bob, Mary, John} EmployeeName; and this: typedef enum {Bob, Mary, John}; but what compiled successfully for me was this: enum {Bob, Mary, John}; I put that line in a .h file above the @interface line, and then when I #import that .h file into a different class's .m file, methods there can see the enum. So, when are the other variants needed? If I could name the enum something like EmployeeNames, and then, when I type "EmployeeNames" followed by a ".", it would be nice if a list pops up showing what the enum choices are. A: In C (and hence Objective C), an enum type has to be prefixed with enum every time you use it. enum MyEnum enumVar; By making a typedef: typedef MyEnum MyEnumT; You can write the shorter: MyEnumT enumVar; The alternative declarations declare the enum itself and the typedef in one declaration. // gives the enum itself a name, as well as the typedef typedef enum Ename { Bob, Mary, John} EmployeeName; // leaves the enum anonymous, only gives a name to the typedef typedef enum {Bob, Mary, John} EmployeeName; // leaves both anonymous, so Bob, Mary and John are just names for values of an anonymous type typedef enum {Bob, Mary, John}; A: The names inside enum { } define the enumerated values. When you give it a name, you can use it as a type together with the keyword enum, e.g. enum EmployeeName b = Bob;. If you also typedef it, then you can drop the enum when you declare variables of that type, e.g. EmployeeName b = Bob; instead of the previous example.
{ "pile_set_name": "StackExchange" }
Q: How I can load a model in TDB TripleStore I have a question for you: I would like to load a file on my Jena TDB TripleStore. My file is very big, about 80Mb and about 700000 triples RDF. When I try to load it, the execution stops working or takes a very long time. I'm using this code that I do run on a Web Service: String file = "C:\\file.nt"; String directory; directory = "C:\\tdb"; Dataset dataset = TDBFactory.createDataset(directory); Model model = ModelFactory.createDefaultModel(); TDBLoader.loadModel(model, file ); dataset.addNamedModel("http://nameFile", model); return model; Sometimes I get an error of Java heap space: Caused by: java.lang.OutOfMemoryError: Java heap space at org.apache.jena.riot.tokens.TokenizerText.parseToken(TokenizerText.java:170) at org.apache.jena.riot.tokens.TokenizerText.hasNext(TokenizerText.java:86) at org.apache.jena.atlas.iterator.PeekIterator.fill(PeekIterator.java:50) at org.apache.jena.atlas.iterator.PeekIterator.next(PeekIterator.java:92) at org.apache.jena.riot.lang.LangEngine.nextToken(LangEngine.java:99) at org.apache.jena.riot.lang.LangNTriples.parseOne(LangNTriples.java:67) at org.apache.jena.riot.lang.LangNTriples.runParser(LangNTriples.java:54) at org.apache.jena.riot.lang.LangBase.parse(LangBase.java:42) at org.apache.jena.riot.RDFParserRegistry$ReaderRIOTFactoryImpl$1.read(RDFParserRegistry.java:142) at org.apache.jena.riot.RDFDataMgr.process(RDFDataMgr.java:859) at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:255) at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:241) at org.apache.jena.riot.adapters.RDFReaderRIOT_Web.read(RDFReaderRIOT_Web.java:96) at com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:241) at com.hp.hpl.jena.tdb.TDBLoader.loadAnything(TDBLoader.java:294) at com.hp.hpl.jena.tdb.TDBLoader.loadModel(TDBLoader.java:125) at com.hp.hpl.jena.tdb.TDBLoader.loadModel(TDBLoader.java:119) How I can load this file in a model Jena and save it in TDB? Thanks in advance. A: You need to allocate more memory for your JVM at statup. When you have too little, the process will spend too much time performing garbage collection, and will ultimately fail. For example, start your JVM with 4 GB of memory by: java -Xms4G -XmxG If you are in an IDE such as Eclipse, you can change your run configuration so that the application has additional memory as well. Aside from that, the only change that jumps out at me is that you are using an in-memory model for the actual loading operation, when you can actually use a model backed by TDB instead. This can help to alleviate your memory problems because TDB dynamially moves its indexes to disk. Change: Dataset dataset = TDBFactory.createDataset(directory); Model model = ModelFactory.createDefaultModel(); TDBLoader.loadModel(model, file ); dataset.addNamedModel("http://nameFile", model); to this: Dataset dataset = TDBFactory.createDataset(directory); Model model = dataset.getNamedModel("http://nameFile"); TDBLoader.loadModel(model, file ); Now your system depends on TDB's ability to make good decisions about when to leave data in memory and when to flush it to disk.
{ "pile_set_name": "StackExchange" }
Q: xamarin shared preferences replace I am new on xamarin android development and i have a problem with return shared preferences getString method. ISharedPreferences pref = PreferenceManager.GetDefaultSharedPreferences(this); string loginToken = pref.GetString("token", string.Empty); if (!string.IsNullOrEmpty(loginToken)) { this result return=> "\"QuZzOXjLead6rmBuSjs6vJ269BKmiXvOKPmy47y46ms\"" and replace method not worked. How can i clear "\" and \"" symbols? A: \" is just an escaping for " - so just do a string.Replace("\"", "")
{ "pile_set_name": "StackExchange" }