{ // 获取包含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\r\n\n\nA:\n\nGet rid of the rule:\nli {\n float: left;\n}\n\nbody {\r\n background-color: #333333;\r\n margin: auto;\r\n font-family: Verdana, Geneva, Tahoma, sans-serif;\r\n color: white;\r\n}\r\n\r\n#navbar {\r\n width: 100%;\r\n width: 100%;\r\n float: left;\r\n margin: 0 0 1em 0;\r\n padding: 0;\r\n background-color: #f2f2f2;\r\n border-bottom: 1px solid #ccc;\r\n}\r\n\r\n.header {\r\n font-size: 1em;\r\n margin-bottom: 5%;\r\n}\r\n\r\nh2 {\r\n font-size: 1em;\r\n text-align: left;\r\n padding-left: 2%;\r\n margin-bottom: -1em;\r\n}\r\n\r\nh5 {\r\n text-align: center;\r\n}\r\n\r\nh3 {\r\n text-align: left;\r\n padding-left: 2%;\r\n font-size: 1.4em;\r\n color: white;\r\n margin-bottom: 0;\r\n margin-top: 0;\r\n}\r\n\r\np,\r\nul,\r\nol {\r\n font-size: 1.2em;\r\n line-height: 130%;\r\n width: auto;\r\n text-align: left;\r\n padding-left: 2%;\r\n}\r\n\r\np ol {\r\n padding-left: 10%;\r\n padding-bottom: 2%;\r\n}\r\n\r\np ol li {\r\n margin-bottom: 10px;\r\n}\r\n\r\np {\r\n float: left;\r\n margin-bottom: 40px;\r\n margin-top: 0.1em;\r\n}\r\n\r\n#cover {\r\n width: 100%;\r\n}\r\n\r\n.intro .facts .bibliography {\r\n min-width: 65ch;\r\n max-width: 75ch;\r\n}\r\n\r\n#container {\r\n position: relative;\r\n text-align: center;\r\n color: white;\r\n}\r\n\r\n#cover {\r\n position: relative;\r\n width: 100%;\r\n}\r\n\r\n#headingOnPicture {\r\n position: relative;\r\n}\r\n\r\n#textOverImage {\r\n position: absolute;\r\n bottom: 0;\r\n left: 2%;\r\n}\r\n\r\n@media only screen and (max-width: 1122px) {\r\n #textOverImage {}\r\n}\r\n\r\n@media only screen and (max-width: 800px) {\r\n #textOverImage {}\r\n}\r\n\r\n#navbar ul {\r\n display: inline-block;\r\n overflow: hidden;\r\n list-style-type: none;\r\n}\r\n\r\nul {\r\n list-style-type: none;\r\n margin: 0;\r\n padding: 0;\r\n overflow: hidden;\r\n background-color: #333;\r\n display: inline-block;\r\n list-style-type: none;\r\n}\r\n\r\n\r\n\r\nli a {\r\n display: block;\r\n color: white;\r\n text-align: center;\r\n padding: 14px 16px;\r\n text-decoration: none;\r\n padding: 15px;\r\n margin: auto;\r\n}\r\n\r\nol {\r\n padding-left: 5%;\r\n}\r\n\r\nol li {\r\n margin: 0.5%;\r\n}\r\n\r\n#center {\r\n margin: auto;\r\n font-family: Verdana, Geneva, Tahoma, sans-serif;\r\n color: white;\r\n padding-left: 5%;\r\n padding-right: 5%;\r\n}\r\n\r\n* {\r\n box-sizing: border-box;\r\n}\r\n\r\nbody {\r\n font: 300 100% 'Helvetica Neue', Helvetica, Arial;\r\n}\r\n\r\n.four {\r\n width: 60;\r\n}\r\n\r\n.four a {\r\n width: 60px;\r\n}\r\n\r\n.container {\r\n width: 20%;\r\n margin: 0 auto;\r\n}\r\n\r\nul li {\r\n display: inline;\r\n text-align: center;\r\n}\r\n\r\na {\r\n display: inline-block;\r\n width: 25%;\r\n padding: .75rem 0;\r\n margin: 0;\r\n text-decoration: none;\r\n color: #333;\r\n font-size: 20px;\r\n}\r\n\r\n.one:hover~hr {\r\n opacity: 1;\r\n margin-left: 5%;\r\n}\r\n\r\n.two:hover~hr {\r\n opacity: 1;\r\n margin-left: 28%;\r\n}\r\n\r\n.three:hover~hr {\r\n opacity: 1;\r\n margin-left: 52%;\r\n}\r\n\r\n.four:hover~hr {\r\n opacity: 1;\r\n margin-left: 75%;\r\n}\r\n\r\nhr {\r\n margin-left: 0%;\r\n opacity: 0.1;\r\n height: .25rem;\r\n width: 25%;\r\n margin: 0;\r\n background: tomato;\r\n border: none;\r\n transition: .3s ease-in-out;\r\n}\r\n\r\nli b {\r\n color: powderblue;\r\n}\r\n\r\np {\r\n float: left;\r\n}\r\n\r\n.mainPart {\r\n width: 80%;\r\n padding-left: 20%;\r\n}\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n Document\r\n \r\n\r\n\r\n\r\n\r\n
\r\n
    \r\n
  • P1
  • \r\n \r\n
  • P2
  • \r\n \r\n
  • P3
  • \r\n \r\n
  • P4
  • \r\n
    \r\n
\r\n
\r\n\r\n
\r\n
\r\n \"Cover\r\n

P1: Requirements

\r\n
\r\n
\r\n
\r\n
// 18. September 2019\r\n
\r\n
\r\n
\r\n
\r\n\r\n

\r\n Administrative Details\r\n

\r\n

\r\n Antikvariatet is a cozy bar/pub/café/venue located at Bakklandet in Trondheim. It offers a great assortment of beers as well as outside serving. The inside of Antikvariatet consists of two separated areas. One offers a calm, laid-back atmosphere while\r\n the other hosts various kinds of events. The events ranges from small concerts and standup comedy to cultural performances and social debates.\r\n

\r\n\r\n

Purpose and goals

\r\n

\r\n The main purpose of this website is to inform customers about events happening at Antikvariatet. The business goal is to increase the amount of visitors to the venue. This means that the \"event\" section of the website needs to stand out. In addition,\r\n special offers also need to be clearly communicated. The website has to capture the cozy atmosphere Antikvariatet offers.\r\n

\r\n
\r\n
\r\n

Audience

\r\n

\r\n The intended user is in the age group 18 to 60. These customers tend to use the internet more for looking up information about the venue.\r\n

\r\n
\r\n
\r\n
\r\n\r\n\r\n
\r\n

\r\n The content of the site and how it is organized\r\n

\r\n

The major sections of the website:

\r\n\r\n
\r\n\r\n\r\n\r\n
\r\n
    \r\n
  1. About us: Consists of the general information about Antikvariatet. What the concept is and what they offer.
  2. \r\n
  3. Menu: Should provide the menu for the restaurant and the selection of beers in the bar.
  4. \r\n
  5. Events: Events consists of three subcategories the customer can choose between if desired. The subcategories are «Cultural events», «Sosial events» and «Concerts». The customer can also just scroll down and see the unfiltered list of events.\r\n A «Search for event or concert» - should also appear with a search bar. Next to the event there should be a button to sign up for the event.
  6. \r\n\r\n
  7. Picures: This should consists of pictures showing the cozy atmosphere and the different things they offer. It could also have an Instagram part consisting of pictures taken by customers and tagged with «Antikvariatet».
  8. \r\n\r\n
  9. Contact us: Should contain the information about where they are located with a map, the opening hours, the mail to contact them and the telephone number.
  10. \r\n
\r\n
\r\n

\r\n Functional and Non-Functional Requirements\r\n

\r\n

\r\n Non-functional:\r\n

\r\n
\r\n

\r\n Due to the large age difference of the clientele, the website should and be easy and intuitive also for users with low technology experience. The appearance of the website should reflect the warm and welcoming environment that Antikvariatet provide. The\r\n webside should be effective, and all functionalities should react within a second.\r\n

\r\n

\r\n Functional:\r\n

\r\n
\r\n

\r\n The customers should easily be provided a menu for the café. They should also able to make and send in orders for the different events. The website should provide a calendar for all the events. One should be able to click on a date and see happenings\r\n on that day, and also all happenings over a longer periode. For better usability, the customer should be able to divide the different events in smaller groups; concerts, social events or cultural activities and be able to search for events.\r\n The customer should also be able to press a button and get the website in English instead of Norwegian.\r\n

\r\n
\r\n

Final location:

\r\n

\r\n We have not yet been in touch with Antikvariatet about making an actual website for them. Howerver, the website will be hosted at one of our folk.ntnu servers.\r\n

\r\n
\r\n\r\n
\r\n\r\n\r\n\n\nIf you need to float some other set of list items then change the selector to be more specific and target only those list items, not all of them.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29005,"cells":{"text":{"kind":"string","value":"Q:\n\nUnable to extract a substring from a string\n\nI am long string array and i want to pass it to another function in the chunks of 250 characters one time, i have written this code:\nvar cStart = 0;\nvar phase = 250;\nvar cEnd = cStart + phase;\nvar count = 0;\n\nwhile (count < 10000)\n{\n string fileInStringTemp = \"\";\n fileInStringTemp = fileInString.Substring(cStart, cEnd);\n var lngth = fileInStringTemp.Length;\n\n //Do Some Work\n\n cStart += phase;\n cEnd += phase;\n count++;\n}\n\nIn the first iteration of the loop the value of lngth is 250 which is fine, in the next iteration i also want it to 250 because i am extracting substring from 250-500 characters but shockingly the value of lngth variable in the second iteration gets 500.\nWhy is that? i am also trying to initialize string variable everytime in the loop so it starts from zero but no gain.\n\nA:\n\nSubstring's second parameter is the length you want, not the stop index.\npublic string Substring(\n int startIndex,\n int length\n)\n\nSo, all you need to do is change your code to have the start index and length (phase)\nfileInString.Substring(cStart, phase)\n\nA:\n\nHere is the MSDN link about how to work with Substring:\nhttps://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx\nAccording to MSDN first parameter in Substring method is StartIndex which is defined as The zero-based starting character position of a substring and second parameter is used to define lenght of substring which is defined as The number of characters in the substring.\nSo you should try this:\nvar cStart = 0;\nvar phase = 250;\nvar count = 0;\n\nwhile (count < 10000)\n{\n string fileInStringTemp = \"\";\n fileInStringTemp = fileInString.Substring(cStart, phase);\n var lngth = fileInStringTemp.Length;\n\n //Do Some Work\n count++;\n cStart = phase * count + 1;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29006,"cells":{"text":{"kind":"string","value":"Q:\n\nMean python pandas by values in a row\n\nI have a dataframe with with multiple rows similar to the one showed below:\n wave cross cross2\n0 299.0 1.25 3.30\n1 299.5 1.30 4.20\n2 300.0 1.45 4.36\n3 300.5 1.65 4.32\n4 300.8 1.56 4.56\n\nWhat I want to do is to average the data for the same wavelengths so that is get a data frame with wave as an integer, which results in something like this:\n wave cross cross2\n0 299 1.30 3.75\n1 300 1.55 4.41\n\nwhat is the best way to achieve this with python pandas?\n\nA:\n\nUse groupby with aggreagate mean, but first cast wave column to int:\ndf = df.assign(wave = df['wave'].astype(int)).groupby('wave').mean()\n\nOr:\ndf['wave'] = df['wave'].astype(int)\ndf = df.groupby('wave').mean()\n\nOr:\ndf = df[df.columns.difference(['wave'])].groupby(df['wave'].astype(int)).mean()\n\nprint (df)\n cross cross2\nwave \n299 1.275000 3.750000\n300 1.553333 4.413333\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29007,"cells":{"text":{"kind":"string","value":"Q:\n\nGenerating all possible Domino tilings on a $4 \\times 4$ grid\n\nI have a task to write a program which generates all possible combinations of tiling domino on a $4 \\times 4$ grid. I have found many articles about tilings, but it is for me quite difficult and I didn't find any article with an algorithm that allows generating all possible combinations.\nCould someone give me some tips? How should I start with that?\nThanks in advance.\n\nA:\n\nDo this recursively: \n\nFind the top-left empty square on the board. \nIf there is no empty square, all squares are covered with dominos, just print the solution and return. \nIf there is an empty square, try to put a domino horizontally, then vertically. If that is possible, put a domino on the board and go to the step 1 again. \n\nSome backtracking is necessary along the way. You can easily grasp the idea by looking at the following Python script:\nIn Python:\nclass Table:\n table = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n domino = 0\n count = 0\n\n def findEmptyCell(self):\n for i in range(0, 4):\n for j in range(0, 4):\n if self.table[i][j] == 0:\n return (i, j)\n return None\n\n def placeDomino(self):\n cell = self.findEmptyCell()\n if cell is None:\n # we have a full board with no empy cells\n self.print()\n return\n # try to put a new domino horizontally\n x = cell[0]\n y = cell[1]\n self.domino += 1\n self.table[x][y] = self.domino\n if y < 3 and self.table[x][y + 1] == 0:\n self.table[x][y + 1] = self.domino\n self.placeDomino()\n self.table[x][y + 1] = 0\n if x < 3 and self.table[x + 1][y] == 0:\n self.table[x + 1][y] = self.domino\n self.placeDomino()\n self.table[x + 1][y] = 0\n self.table[x][y] = 0\n self.domino -= 1\n\n def print(self):\n self.count += 1\n print(\"=== Solution #%d ===\" % self.count)\n for i in range(0, 4):\n print(\"%d%d%d%d\" % (self.table[i][0], self.table[i][1], self.table[i][2], self.table[i][3]))\n print('')\n\nt = Table()\nt.placeDomino()\n\nHere is the output, 36 solutions in total (with dominoes numbered from 1 to 8):\n=== Solution #1 ===\n1122\n3344\n5566\n7788\n\n=== Solution #2 ===\n1122\n3344\n5567\n8867\n\n=== Solution #3 ===\n1122\n3344\n5667\n5887\n\n=== Solution #4 ===\n1122\n3344\n5677\n5688\n\n=== Solution #5 ===\n1122\n3344\n5678\n5678\n\n=== Solution #6 ===\n1122\n3345\n6645\n7788\n\n=== Solution #7 ===\n1122\n3345\n6745\n6788\n\n=== Solution #8 ===\n1122\n3445\n3665\n7788\n\n=== Solution #9 ===\n1122\n3455\n3466\n7788\n\n=== Solution #10 ===\n1122\n3455\n3467\n8867\n\n=== Solution #11 ===\n1122\n3456\n3456\n7788\n\n=== Solution #12 ===\n1123\n4423\n5566\n7788\n\n=== Solution #13 ===\n1123\n4423\n5567\n8867\n\n=== Solution #14 ===\n1123\n4423\n5667\n5887\n\n=== Solution #15 ===\n1123\n4423\n5677\n5688\n\n=== Solution #16 ===\n1123\n4423\n5678\n5678\n\n=== Solution #17 ===\n1123\n4523\n4566\n7788\n\n=== Solution #18 ===\n1123\n4523\n4567\n8867\n\n=== Solution #19 ===\n1223\n1443\n5566\n7788\n\n=== Solution #20 ===\n1223\n1443\n5567\n8867\n\n=== Solution #21 ===\n1223\n1443\n5667\n5887\n\n=== Solution #22 ===\n1223\n1443\n5677\n5688\n\n=== Solution #23 ===\n1223\n1443\n5678\n5678\n\n=== Solution #24 ===\n1223\n1453\n6457\n6887\n\n=== Solution #25 ===\n1233\n1244\n5566\n7788\n\n=== Solution #26 ===\n1233\n1244\n5567\n8867\n\n=== Solution #27 ===\n1233\n1244\n5667\n5887\n\n=== Solution #28 ===\n1233\n1244\n5677\n5688\n\n=== Solution #29 ===\n1233\n1244\n5678\n5678\n\n=== Solution #30 ===\n1233\n1245\n6645\n7788\n\n=== Solution #31 ===\n1233\n1245\n6745\n6788\n\n=== Solution #32 ===\n1234\n1234\n5566\n7788\n\n=== Solution #33 ===\n1234\n1234\n5567\n8867\n\n=== Solution #34 ===\n1234\n1234\n5667\n5887\n\n=== Solution #35 ===\n1234\n1234\n5677\n5688\n\n=== Solution #36 ===\n1234\n1234\n5678\n5678\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29008,"cells":{"text":{"kind":"string","value":"Q:\n\ngit - dual boot ubuntu and windows with separate data partition\n\nI just installed ubuntu along side windows 7. All of my git local working folders are on a separate data partition.\nEverything is committed in windows 7's git, but in ubuntu's git, running git status shows everything as modified. When I tried git log all the history is still there.\nI don't want to commit everything every time I switch to the other OS to work. Is there a solution?\n\nA:\n\nYour problem is that when you check out files on Windows with the git default config, they are created with CRLF (the windows default) line endings in your working directory, but committed as LF for cross-platform compatibility.\nNow your Linux sees the CRLF on every line and says that it’s different to the LF in the repo. That’s why every line is reported as different.\nI would suggest setting the line endings to LF on windows. In a previous answer I explained the details of how to do that. Following those steps will also enable line-ending normalization to LF on linux, which will avoid problems if you accidentally create some CRLF on windows and commit that in linux later on. \nYou can also just disable line ending normalization completely, but that is likely to cause trouble in the future, unless you only use a completely fixed set of editors, whose line ending handling you know very will.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29009,"cells":{"text":{"kind":"string","value":"Q:\n\nHow do I know which MongoDB version is installed by using the Command Line?\n\nWithout changing directory to \\MongoDB\\bin\\, when I call:\nmongod -v\n\nI get:\n'mongod' is not recognized as an internal or external command, operable\nprogram or batch file.\n\nWhen I call the same command from \\bin\\ it launches the server just like I'm calling:\nmongod\n\nIt is the same case with 'mongo' and 'mongos'.\nI added the \\bin\\ path to the environment variables thinking it will help but it didn't.\nTo clarify with an example, to get the version of Ruby, I can call:\nruby -v\n\nWhy can't I do the same with MongoDB?\n\nA:\n\nFirst add location of MongoDB's bin folder to PATH env variable. This is required because it is the place where mongod.exe is stored.\nFor example, if MongoDB 4.0 is in your Program Files, add \"C:\\Program Files\\MongoDB\\Server\\4.0\\bin\" to PATH for all system users.\nThen try using :\nmongod --version\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29010,"cells":{"text":{"kind":"string","value":"Q:\n\nAttach Sharepoint 2010 List attachment to gridview\n\nI have a SharePoint list, which has attachments!! \nI am using a custom grid-view to display some selected List fields from the list.\nI would like to include the attachment as an embedded document in the Grid-view, Is that possible? \n\nA:\n\nGot it worked, Created an anchor type item template in grid view.\nAnd the Href property of the anchor tab is binded with the attachment retrieved pro grammatically. Working great!!\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29011,"cells":{"text":{"kind":"string","value":"Q:\n\nHow can I write regular expression for android:host\n\nI have multiple hosts, for example:\n\nexample1.myhost.abc\nexample2.myhost.xyz\nexample3.myhost.jkl\n\nI want to write a regular expression for host name in the data attribute of intent filter. Which may look like this:\n\n\nBut its not working for me. It seems that android:host does not support regex. Is there any way to achieve it?\n\nA:\n\nIt seems that android:host does not support regex.\n\nCorrect.\n\nIs there any way to achieve it?\n\nYou can say that you handle the http scheme and not specify anything else (e.g., no host, no path). This will cover all your desired patterns, but it will also cover every other domain name.\nOr, since you can have more than one element, you can have as many host attributes as needed to cover all of your sites, without regular expressions.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29012,"cells":{"text":{"kind":"string","value":"Q:\n\nUsing Git for Angular App\n\nI'm using Yeoman to generate out an angular app. Once I'm happy with my app, I run grunt which creates a production-ready version of my application in a folder called /dist at the root of my project.\nI've then initialised this /dist directory as a Git repository with git init and pushed the files up to Bitbucket, where they currently sit right now.\nWhat I'm asking is do I have to compile my production-ready app with grunt every time I want to make a commit? It seems I have to. I'm thinking this setup might not be the most productive way to do this?\nAm I missing something, is there an easier and more productive way to handling this?\n\nA:\n\nThat workflow is odd. \nOnly source code should be in your git repository. Not the compiled/minified files. Source code is what matters.\nWhen you colaborate with somebody else, they should run grunt tasks on their own.\nDist package should be created before deploy to production. Or on regular basis by the continuous integration server.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29013,"cells":{"text":{"kind":"string","value":"Q:\n\nSelenium webdriver how to do file upload with ng-click=\"upload('files')\"\n\nI'm trying to see if this is possible - to automate a file upload when the HTML code is NOT an\n< input type='file' >\n\nbut rather a link \n File Upload \n\nWhen this link is clicked, it automatically opens a file selector to choose which file you want to upload.\nThe problem is, it does not contain an INPUT type='file' element which I could locate and then use webdriver.send_keys('/Users/myname/testfile.txt').\nHow can I go about trying to get selenium webdriver to handle this file upload? \nAny help to direct me to a solution is greatly appreciated.\n\nA:\n\nLast time that i needed this WebDriver couldn't interact with dialogs cause dialogs are the domain of the operating system and not the webpage.\nOne option would be to skip the file dialog entirely and issue a POST/GET/PUT, but this requires more advanced knowledge of the website as well as understanding of how to construct a request.\nWhat i did in that ocation was to create an auxiliar program executable for dealing with the dialog, so i called it in the middle of the Selenium script, just after generating the dialog.\nHere you have a sample of the last approach using Java & AutoIT: http://www.automationtesting.co.in/2009/07/selenium-handle-dialogs.html\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29014,"cells":{"text":{"kind":"string","value":"Q:\n\nRestrict height of div marked with display:table-cell?\n\nProblem: \nI need to use display:table (in the parent div) and display:table-cell (in the contained div) to center some content vertically. This is working except when the content overflows vertically. I want to restrict the height so that a scrollbar appears if there's any vertical overflow. \nFiddle: \nhttp://jsfiddle.net/PTSkR/110/\n(Note that in the output, the div is expanded vertically despite me setting the height to 160px)\nCSS: \nside-study-box {\n background-color: white;\n color: black;\n border: 1px solid #3D6AA2;\n text-align: center;\n height: 160px !important;\n display: table !important;\n margin: 0px !important;\n margin-left: -1px !important;\n position: relative;\n overflow-y: scroll;\n width: 100%;\n}\n\n .side-study-box .side-box-content {\n width: calc(100%);\n height: 160px !important;\n float: right;\n display: table;\n overflow-y: scroll;\n }\n\n .side-study-box .text-content-saved {\n width: 100% !important;\n font-size: 24px;\n display: table-cell;\n vertical-align: middle;\n text-align: center;\n height: 160px !important;\n max-height: 160px !important;\n background-color: white;\n padding: 0px !important;\n margin: 0px !important;\n font-family: \"Segoe UI\", Frutiger, \"Frutiger Linotype\", \"Dejavu Sans\", \"Helvetica Neue\", Arial, sans-serif;\n border: 0px !important;\n overflow-y: scroll;\n }\n\nA:\n\nhere is your fiddle updated , with max-height on content wrapper. \n.side-study-box {\n background-color: white;\n color: black;\n border: 1px solid #3D6AA2;\n display: table;\n width: 100%;\n border-spacing:1em;\n}\n.side-box-content {\nwidth: 100%;\n height: ;\n display: table-cell;\n}\n.text-content-saved {\n max-height:160px;\n overflow:auto;\n padding:5px;\n}\n\nhttp://jsfiddle.net/GCyrillus/6tLAu/\nup here first code was : the box doesn't grow.\ndown here second does first and centers content if little.\n.side-study-box {\n background-color: white;\n color: black;\n border: 1px solid #3D6AA2;\n display: table;\n width: 100%;\n border-spacing:1em;\n height:160px;\n}\n.side-box-content {\nwidth: 100%;\n height: ;\n display: table-cell;\n vertical-align:middle;\n}\n.text-content-saved {\n max-height:140px;\n overflow:auto;\n padding:5px;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29015,"cells":{"text":{"kind":"string","value":"Q:\n\nMerge duplicate cell values and their sums in Excel using VBA\n\nI am trying to merge duplicate cell values in Excel using VBA.\nHere is an example of the data:\n\nCol1 Col2\n run 1\n run 2\n see 9\n go 5\n see 1 \n\nI need to merge this information so that the data is as follows:\n\nCol1 Col2\n run 3\n see 10\n go 5 \n\nMeaning, that I need to merge the duplicate values in Column 1 and sum their corresponding values in Column 2.\nI have already consulted and tried a similar situation here: How to SUM / merge similar rows in Excel using VBA? \nWhere one of the recommendations was the following macro:\nSub Macro1()\nDim ColumnsCount As Integer\n\nColumnsCount = ActiveSheet.UsedRange.Columns.Count\n\nActiveSheet.UsedRange.Activate\n\nDo While ActiveCell.Row <= ActiveSheet.UsedRange.Rows.Count\n If ActiveCell.Value = ActiveCell.Offset(1, 0).Value Then\n For i = 1 To ColumnsCount - 1\n ActiveCell.Offset(0, i).Value = ActiveCell.Offset(0, i).Value + ActiveCell.Offset(1, i).Value\n Next\n ActiveCell.Offset(1, 0).EntireRow.Delete shift:=xlShiftUp\n Else\n ActiveCell.Offset(1, 0).Select\n End If\nLoop\nEnd Sub\n\nHowever, it seems to be creating an infinite loop that causes my excel to crash, without actually merging anything.\nDoes anyone have any suggestions as to how I can adapt this code to arrive at the merge solution that I need?\n\nA:\n\nThe following assumes your table starts in cell A1 and columns C onwards are empty (if they are not you will lose data on the merged rows)\nSub mergeCategoryValues()\nDim lngRow As Long\n\nWith ActiveSheet\n\n lngRow = .Cells(.LastCell.Row, 1).End(xlUp).Row\n\n .Cells(1).CurrentRegion.Sort key1:=.Cells(1), header:=xlNo 'change this to xlYes if your table has header cells\n\n Do\n\n If .Cells(lngRow - 1, 1) = .Cells(lngRow, 1) Then\n .Cells(lngRow - 1, 2) = .Cells(lngRow - 1, 2) + .Cells(lngRow, 2)\n .Rows(lngRow).Delete\n End If\n\n lngRow = lngRow - 1\n\n Loop Until lngRow < 2\n\nEnd With\n\nEnd Sub\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29016,"cells":{"text":{"kind":"string","value":"Q:\n\nDjango optimización de Querys\n\nEstoy haciendo una consulta en mis vistas de Django con diferentes palabras y me gustaría optimizarlo haciendo uso de una lista. \nTengo este modelo\nclass Personas(models.Model):\n id = models.AutoField(db_column='id', primary_key=True) # Field name made lowercase.\n nombre = models.CharField(db_column='nombre', unique=True, max_length=100) # Field name made lowercase.\n\nclass Meta:\n managed = False\n db_table = 'personas'\n\nHasta ahora estoy haciendo\n#siendo 'nombres' mi lista de argumentos a buscar\nprimerNombre = nombres.pop(0) #obtengo el primer argumento a buscar\nanswer = Personas.objects.filter(nombre__icontains = primerNombre)\nfor nombre in nombres:\n answer = answer | Personas.objects.filter(nombre__icontains = nombre) #Hago una union por cada consulta\n\nMe vi obligado a hacer esto porque intenté\nanswer = answer | Personas.objects.filter(nombre__in = nombres)\n\nY no me funcionó, al parecer el \"__in\" solo funciona con números. Hay alguna forma mas elegante u optima de hacerlo? Desde ya muchísimas gracias!\n\nA:\n\nNo es que __in sólo se pueda usar con números, el asunto es que la lista de nombres que estás usando no es igual al nombre que tienes registrado en la BD, lo que no se puede hacer es combinar __icontains con __in, pero si te aseguras de que los nombres en la lista nombres esten escritos igual que en la BD, tal vez pre procesandolo con .title(), .lower() o .upper(); vas a poder usar __in en tu consulta:\nPersonas.objects.filter(nombre__in = nombres)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29017,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to join a mapping table in my query\n\nI have a query that is trying to pull out all the questions in my table.\nQuestions\nPosts\nTopics\nTopic Mapping\nMy tag tables are set up with a 3rd table for mapping the question id with the topic id.\nHowever, how do I pull the name of the topic stored in the topic table with a JOIN statement\nSo basically I dont know how to do a JOIN statement on a table that has only got the topic id and not the topic name\nSELECT questions.* \n , posts.post\n , COUNT(posts.post) as total_answers\n , posts.votes\n , posts.id as post_id\n , posts.created\n , users.id as user_id\n , users.username, users.rep\n , topics.name\nFROM questions\nLEFT JOIN posts ON questions.id = posts.question_id\nLEFT JOIN users ON questions.user_id = users.id\nLEFT JOIN topics ON topic_mapping.question_id = questions.id\nGROUP BY questions.id\n\nThanks a lot\n\nA:\n\nYou need to join the question to the mapping table first.\nSELECT questions.* \n , posts.post\n , COUNT(posts.post) as total_answers\n , posts.votes\n , posts.id as post_id\n , posts.created\n , users.id as user_id\n , users.username, users.rep\n , topics.name\nFROM questions\nLEFT JOIN posts ON questions.id = posts.question_id\nLEFT JOIN users ON questions.user_id = users.id\nLEFT JOIN topic_mapping ON questions.id = topic_mapping.question_id\nLEFT JOIN topics ON topic_mapping.topic_id = topics.id\nGROUP BY questions.id\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29018,"cells":{"text":{"kind":"string","value":"Q:\n\nOOP: Application architecture issues\n\n(Nothing serious in this question)\nOnes a time I've read such an example of \"bad application architecture\":\nThere was a \"rendering application\" (browser, as far as I remember), so it was told, that having \"render()\" method in TagA, TagUL, TagDIV classes is really bad practice, because you'll have lots of \"render-code\" smeared all around. So (in this example), they adviced to have RenderA, RenderUL, RenderDIV classes that would implement rendering. And tag-objects would incapsulate those renderers.\nI can't understand why that's a bad practice. In this case we'll have lot's of render code smeared around Render-* objects. And, finaly, why not to have Redner-singleton with lot's of overriden methods? That sounds, at least, cheaper.\nWhat to read to understand it better?\n\nA:\n\nWill the rendering for all of these different objects be the same? If so, then it should only be implemented once, most likely in a base class. This would be a better solution than a Singleton, which serves a completely different purpose: mainly to implement a resource (notice its a resource, not a method) that should only exist once.\nIf each implementation of render() will be different (which is most likely the case) then there is nothing wrong with them being implemented in separate objects, this is called polymorphism. What should probably be done though, is to have a class hierarchy in which the render() method is defined in the base class (most likely as abstract) and implemented in the derived classes. This effectively formalizes the interface, meaning that any class that inherits from said base class will have the render() method available and will have to implement it.\nIf you have parts of the render code that are common, and parts that are specific to the derived classes, instead of having to duplicate the common parts in all the derived class implementations, you can use a Template Method pattern, whereby the base class method does the common parts, and orchestrates calling the derived class implementation(s). Here is a pseudo-code example in C++\nclass TagBase {\npublic:\n void render() {\n // do some common stuff here\n doRender();\n // do some more common stuff here\n }\n\n virtual void doRender() = 0;\n ....\n};\n\nclass TagA : public TagBase {\npublic:\n virtual void doRender() {\n // do your specific stuff here\n }\n};\n\nHere are a few good books:\n\nDesign Patterns, Gang of Four\nHead First Design Patterns\nHead First Object Oriented Analysis and Design\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29019,"cells":{"text":{"kind":"string","value":"Q:\n\nCalculating $\\int_{-\\infty}^{\\infty}\\frac{\\sin(ax)}{x}\\, dx$ using complex analysis\n\nI am going over my complex analysis lecture notes and there is an\nexample about calculating $$\\int_{-\\infty}^{\\infty}\\frac{\\sin(ax)}{x}\\, dx$$\nthat I don't understand.\nThe solution in the notes starts like this:\nDenote $C$ as the path from$-R$ to $R$ on the $x$-axis (where\n$R>0$ is real). Denote $C_{R}$ as the semi-circle (anti-clockwise)\nthat goes from $R$ to $-R$.\n$$\\int_{-R}^{R}\\frac{\\sin(az)}{z}\\, dz=\\int_{C}\\frac{\\sin(az)}{z}\\, dz=\\int_{C}\\frac{e^{aiz}-e^{-aiz}}{2iz}=\\frac{1}{2i}(\\int_{C}\\frac{e^{iaz}}{z}\\, dz-\\int_{C}\\frac{e^{-aiz}}{z}\\, dz)$$\nAssume $a>0$:\n$$e^{iaz}=e^{iaRe^{i\\theta}}=e^{iaR\\cos(\\theta)}-e^{-iaR\\sin(\\theta)}$$\nThus $$\\int_{C}\\frac{e^{iaz}}{z}\\, dz+\\int_{C_{R}}\\frac{e^{iaz}}{z}\\, dz=2\\pi iRes_{z=0}\\left(\\frac{e^{iaz}}{z}\\right)=2\\pi i$$\nThe next part claims that for $R\\to\\infty$:$\\int_{C}\\frac{e^{iaz}}{z}\\, dz=2\\pi i$\n(I understand this part)\nFrom here don't understand what going on in the notes, the sentences\nclaim that $$\\int_{C}\\frac{e^{-iaz}}{z}\\, dz+\\int_{C_{R}}\\frac{-e^{iaz}}{z}\\, dz=0$$\nbut I think that in a similar manner that sum is $2\\pi iRes_{z=0}(\\frac{e^{-iaz}}{z})$\nwhich I believe to be $2\\pi i\\neq0$.\nThe next two sentences afterward say that $\\lim_{R\\to\\infty}\\int_{C}\\frac{\\sin(az)}{z}\\, dz=\\frac{1}{2i}\\cdot2\\pi i=\\pi$\nand that $$\\int_{-\\infty}^{\\infty}\\frac{\\sin(ax)}{x}\\, dx=\\pi$$\nCan someone please help me understand the part about the sum $$\\int_{C}\\frac{e^{-iaz}}{z}\\, dz+\\int_{C_{R}}\\frac{-e^{iaz}}{z}\\, dz$$\n? I believe that there is a mistake here, I would also appreciate\nhelp understanding the last two claims: $$\\lim_{R\\to\\infty}\\int_{C}\\frac{\\sin(az)}{z}\\, dz=\\pi$$\nand that $$\\int_{-\\infty}^{\\infty}\\frac{\\sin(ax)}{x}\\, dx=\\pi$$\nEDIT: I read this couple more times, I now think that there is problem with the part after \"assume $a>0$\": $$e^{iaz}=e^{iaRe^{i\\theta}}=e^{iaR\\cos(\\theta)}-e^{-iaR\\sin(\\theta)}$$\nI think that the minus at the end should be $\\cdot$ and that this is a typo in the notes, but I also think there should not be an $i$ in $e^{-iaR\\sin(\\theta)}$\n\nA:\n\nWhen you break up the integral like that, you end up integrating through poles. That derivation makes no sense to me.\nNotice that $\\displaystyle \\frac{\\sin ax}{x} = \\text{Im} \\ \\frac{e^{iax}}{x}$. \nWhat you should do is let $\\displaystyle f(z) = \\frac{e^{iaz}}{z}$ and integrate around the same contour but with a small half-circle of radius $r$ about the origin.\nThere are no poles inside of the contour, but when you let $r$ to go zero, it gives a contribution of $-i \\pi$.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29020,"cells":{"text":{"kind":"string","value":"Q:\n\ndatetime strftime %s crash on windows\n\nI have this piece of code that fails on windows, but works on linux:\nimport datetime as dt\n\nts = dt.datetime.now().__format__('%s')\n#ts == '1479831118'\n\nI look into the documentation (Python 3.5) and 'format %s' don't even exist there.\nHow can I fix this and get the same output from Linux ?\nThanks\n\nA:\n\nThe code you've provided outputs current time in seconds.\nI may recommend to use time module.\nThis will return the same.\nimport time\nts = str(int(time.time()))\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29021,"cells":{"text":{"kind":"string","value":"Q:\n\nShould I use \"rand % N\" or \"rand() / (RAND_MAX / N + 1)\"?\n\nI was reading the C FAQ and found out in a question that it recommends me to use rand() / (RAND_MAX / N + 1) instead of the more popular way which is rand() % N.\nThe reasoning for that is that when N is a low number rand() % N will only use a few bits from rand().\nI tested the different approaches with N being 2 on both Windows and Linux but could not notice a difference.\n#include \n#include \n#include \n#define N 2\n\nint main(void)\n{\n srand(0);\n printf(\"rand() %% N:\\n\");\n for (int i = 0; i < 40; ++i) {\n printf(\"%d \", rand() % N);\n }\n putchar('\\n');\n\n srand(0);\n printf(\"rand() / (RAND_MAX / N + 1):\\n\");\n for (int i = 0; i < 40; ++i) {\n printf(\"%d \", rand() / (RAND_MAX / N + 1));\n }\n putchar('\\n');\n\n return 0;\n}\n\nThe output is this (on my gnu/linux machine):\nrand() % N:\n1 0 1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 0 1 0 \nrand() / (RAND_MAX / N + 1):\n1 0 1 1 1 0 0 1 0 1 0 1 0 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 1 0 1 1 1 0 1 1 0 1 0 1 \n\nBoth alternatives seem perfectly random to me. It even seems like the second approach is worse than rand % N.\nShould I use rand() % N or rand() / (RAND_MAX / N + 1)?\n\nA:\n\nIf N is a power of two, using the remainder technique is usually safe (RAND_MAX is usually a power of two minus 1, so the entire range has a power of two length). More generally, N has to divide the range of rand() in order to avoid the bias.\nOtherwise, you run into this problem, regardless of the quality of rand(). In short, the problem is that you're chopping that range into a number of \"parts\" each of length N, if N does not divide the range then the last part will not be complete. The numbers that got \"cut off\" from that part are therefore less likely to occur, since they have one fewer \"part\" they can be generated from.\nUnfortunately rand() / (RAND_MAX / N + 1) is also broken (in almost the same way), so the real answer is: don't use either of them.\nThe problem as outlined above is really fundamental, there is no way to evenly distribute X different values over Y results unless Y divides X. You can fix it by rejecting a part of the random samples, to make Y divide the new X.\n\nA:\n\nThere is another problem with rand() % n which is that it introduces a modulo bias. \nFor simplicity's sake let's pretend RAND_MAX is 7 and n is 6. You want the numbers 0, 1, 2, 3, 4, 5 to appear in the random stream with equal probability. However, 0 and 1 will appear 1/4 of the time and the other numbers only 1/8th of the time because 6 and 7 have remainders 0 and 1 respectively. You should use the other method, but carefully because truncation of fractions might introduce a similar issue.\nIf you have arc4random(), you can use arc4random_uniform() to achieve an unbiased distribution without having to be careful.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29022,"cells":{"text":{"kind":"string","value":"Q:\n\nResultSet is throwing NullPointers, but next() returns true\n\nI'm trying to set up a little JDBC project and I'm running into an error which is confusing me.\nIt's a Vocabulary and Multiple Choice Trainer.\nI've got the Multiple Choice running fine but a snipped I nearly copied from it just won't work for my vocabulary-part.\nHere it is:\nprivate void createIDList() throws ClassNotFoundException, SQLException {\n\n Class.forName(\"org.apache.derby.jdbc.ClientDriver\");\n con = DriverManager.getConnection(\"jdbc:derby://localhost:1527/DataBase\");\n stmt = con.createStatement();\n String s_s = \"SUB LIKE '%\";\n s_s = s_s + db_s.get(0) + \"%' \";\n db_s.remove(0);\n while (!db_s.isEmpty()) {\n s_s = s_s + \"OR SUB LIKE '%\" + db_s.get(0) + \"%' \";\n db_s.remove(0);\n }\n String s_t = \"TOPIC LIKE '%\";\n s_t = s_t + db_t.get(0) + \"%' \";\n db_t.remove(0);\n while (!db_t.isEmpty()) {\n s_t = s_t + \"OR TOPIC LIKE '%\" + db_t.get(0) + \"%' \";\n db_t.remove(0); \n }\n rs = stmt.executeQuery(\"SELECT ID FROM APP.Voc WHERE (\" + s_t + \") AND (\" + s_s + \")\");\n\n while (rs.next()) {\n id.add(rs.getInt(\"ID\")); //Exception is here java.lang.NullPointerException\n }}\n\nHere is the part which happens before: \npublic class Session extends javax.swing.JFrame implements KeyListener {\nint p_r = 0;\nint p_w = 0;\nint currentID = -1;\nprivate List db_t, db_s;\nprivate List id;\nConnection con;\nStatement stmt;\nResultSet rs;\nString from = \"V_ORIG\";\nString to = \"V_DEST\";\nString ans;\n\n/**\n * Creates new form Session\n */\npublic Session(List p_db_t, List p_db_s) {\n db_t = p_db_t;\n db_s = p_db_s;\n initialize(); //-->\n\nAnd initialize():\nprivate void initialize() {\n try {\n createIDList();\n } catch (ClassNotFoundException ex) {\n Logger.getLogger(Session.class.getName()).log(Level.SEVERE, null, ex);\n } catch (SQLException ex) {\n Logger.getLogger(Session.class.getName()).log(Level.SEVERE, null, ex);\n }\n Collections.shuffle(id);\n}\n\nI do receieve following error: \nException in thread \"AWT-EventQueue-0\" java.lang.NullPointerException\nat Session.createIDList(Session.java:520)\nat Session.initialize(Session.java:489)\nat Session.(Session.java:45)\nat DB_Selector.bt_goActionPerformed(DB_Selector.java:193)\nat DB_Selector.access$100(DB_Selector.java:18)\nat DB_Selector$2.actionPerformed(DB_Selector.java:83)\nat javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)\nat javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)\nat javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)\nat javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)\nat javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)\nat java.awt.Component.processMouseEvent(Component.java:6533)\nat javax.swing.JComponent.processMouseEvent(JComponent.java:3324)\nat java.awt.Component.processEvent(Component.java:6298)\nat java.awt.Container.processEvent(Container.java:2236)\nat java.awt.Component.dispatchEventImpl(Component.java:4889)\nat java.awt.Container.dispatchEventImpl(Container.java:2294)\nat java.awt.Component.dispatchEvent(Component.java:4711)\nat java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)\nat java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)\nat java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)\nat java.awt.Container.dispatchEventImpl(Container.java:2280)\nat java.awt.Window.dispatchEventImpl(Window.java:2746)\nat java.awt.Component.dispatchEvent(Component.java:4711)\nat java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)\nat java.awt.EventQueue.access$500(EventQueue.java:97)\nat java.awt.EventQueue$3.run(EventQueue.java:709)\nat java.awt.EventQueue$3.run(EventQueue.java:703)\nat java.security.AccessController.doPrivileged(Native Method)\nat java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)\nat java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)\nat java.awt.EventQueue$4.run(EventQueue.java:731)\nat java.awt.EventQueue$4.run(EventQueue.java:729)\nat java.security.AccessController.doPrivileged(Native Method)\nat java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)\nat java.awt.EventQueue.dispatchEvent(EventQueue.java:728)\nat java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)\nat java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)\nat java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)\nat java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)\nat java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)\nat java.awt.EventDispatchThread.run(EventDispatchThread.java:82)\n\nSo much so good, but what is confusing me is following:\nFirst: Why does it enter the while(rs.next()) loop. Shouldn't rs.next() return false before running into an NullPointer?\nAnd: I can get the number of columns with rs.getMetaData().getColumnCount().\nSo there has to be some kind of communication between the database and the ResultSet.\nWhen I execute the Querys manually, I do get a list of ID's.\nWhere could be the error here?\nIf you do need more information, feel free to ask.\n\nA:\n\nYour id is null.\nUse\nid = new ArrayList<>();\nwhile (rs.next()) {\n id.add(rs.getInt(\"ID\"));\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29023,"cells":{"text":{"kind":"string","value":"Q:\n\nMy clock code stops working at Ten O' Clock\n\nMy clock code works at every other hour except ten o' clock. At every other hour, it increments minutes by 1 every time seconds is 60, but at ten o' clock, for some reason, it increments minutes by 1 every time seconds is 10. I don't know what I did wrong. Please help!\npackage misk;\n\npublic class Misk {\n public static void main(String[] args) throws InterruptedException {\n int x = 0;\n int sec = 0, min = 0, hour = 9;\n while (x == 0) {\n Thread.sleep(10);\n sec++;\n if (sec == 60) {\n sec = 0;\n min++;\n }\n if (min == 60) {\n min = 0;\n hour++;\n }\n if (sec < 10) {\n if (min < 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":0\" + min + \":0\" + sec);\n }\n }\n }\n if (sec > 10) {\n if (min < 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":0\" + min + \":\" + sec);\n }\n }\n }\n if (sec < 10) {\n if (min > 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":\" + min + \":0\" + sec);\n }\n }\n }\n if (sec < 10) {\n if (min < 10) {\n if (hour > 10) {\n System.out.println(\"\" + hour + \":0\" + min + \":0\" + sec);\n }\n }\n }\n if (sec > 10) {\n if (min > 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec < 10) {\n if (min > 10) {\n if (hour > 10) {\n System.out.println(\"0\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec > 10) {\n if (min < 10) {\n if (hour > 10) {\n System.out.println(\"\" + hour + \":0\" + min + \":\" + sec);\n }\n }\n }\n if (sec > 10) {\n if (min > 10) {\n if (hour > 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min == 10) {\n if (hour == 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec > 10) {\n if (min == 10) {\n if (hour == 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min > 10) {\n if (hour == 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min == 10) {\n if (hour > 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec > 10) {\n if (min > 10) {\n if (hour == 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min > 10) {\n if (hour > 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec > 10) {\n if (min == 10) {\n if (hour > 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec < 10) {\n if (min == 10) {\n if (hour == 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min < 10) {\n if (hour == 10) {\n System.out.println(\"\" + hour + \":0\" + min + \":\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min == 10) {\n if (hour < 10) {\n System.out.println(\"\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec < 10) {\n if (min < 10) {\n if (hour == 10) {\n System.out.println(\"\" + hour + \":0\" + min + \":0\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min < 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":0\" + min + \":\" + sec);\n }\n }\n }\n if (sec < 10) {\n if (min == 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":\" + min + \":0\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min < 10) {\n if (hour > 10) {\n System.out.println(\"\" + hour + \":0\" + min + \":\" + sec);\n }\n }\n }\n if (sec < 10) {\n if (min == 10) {\n if (hour > 10) {\n System.out.println(\"\" + hour + \":\" + min + \":0\" + sec);\n }\n }\n }\n if (sec > 10) {\n if (min == 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n if (sec < 10) {\n if (min == 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":\" + min + \":0\" + sec);\n }\n }\n }\n if (sec == 10) {\n if (min > 10) {\n if (hour < 10) {\n System.out.println(\"0\" + hour + \":\" + min + \":\" + sec);\n }\n }\n }\n }\n }\n}\n\nA:\n\nFirst of all, your code is a mess.\nYou need to learn how to use conditions more effectively, also learn about formatting.\nYou can easily add '0' before any digit if it isn't a '2 digit number'.\nSystem.out.println(String.format(\"%02d %02d %02d\", hour, minute, second));\n\nYour code doesn't work at ten o' clock because all of your conditions are 'hour > 10' or 'hour < 10', and both of those are false when hour == 10.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29024,"cells":{"text":{"kind":"string","value":"Q:\n\nGoogle Chrome extension displaying json information in html\n\nIn this javascript file, I want to get the json information from a json file (config.json) that is declared in the content scripts of manifest.json. I'm sending that json file to the HTML file under the id \"help\", and upon click of the button the currently written html should change. Any ideas as to why this isn't working? Thank you!\n document.addEventListener('DOMContentLoaded', function () {\n document.querySelector('button').addEventListener('click', main); \n\n});\n\nfunction main() {\n var xhr = new HMLHttpRequest();\n xhr.open(\"GET\", chrome.extension.URL(\"config.json\"), true);\n xhr.onreadystatechange = function() {\n if (xhr.readyState == 4) {\n document.getElementById(\"help\").innerHTML = \n JSON.parse(xhr.responseText);\n }\n }\n xhr.send(); \n}\n\nA:\n\nthere is typo in your code and you have not declared config.json as web accessible resource\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.onreadystatechange = function() {\n if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {\n console.log(xmlhttp.responseText)\n document.getElementById(\"help\").innerHTML = xmlhttp.responseText;\n }\n }\n xmlhttp.open(\"GET\", chrome.extension.getURL(\"config.json\"), true);\n xmlhttp.send();\n\nAnd in manifest add\n \"web_accessible_resources\": [\"config.json\"]\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29025,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to prevent knitr from printing ## and matrix indices/row numbers?\n\nLets say I have a matrix where there's an id column that doesn't go up by 1 with each row.\nm <- matrix(c(1, \"a\", \"c\", \n 5, \"g\", \"c\", \n 4, \"b\", \"c\", \n 9, \"g\", \"a\"),\n ncol=3, byrow=TRUE)\ncolnames(m) <- c(\"id\", \"class\", \"type\")\n\nI've tried renaming the rows with rownames(m) <- NULL or rownames(m) <- c() but I always end up with an output that has the row numbers on the very left:\n id class type\n[1,] \"1\" \"a\" \"c\" \n[2,] \"5\" \"g\" \"c\" \n[3,] \"4\" \"b\" \"c\" \n[4,] \"9\" \"g\" \"a\" \n\nFurther more, if I print to PDF in knitr, I get ## running down the side:\n## id class type\n## [1,] \"1\" \"a\" \"c\" \n## [2,] \"5\" \"g\" \"c\" \n## [3,] \"4\" \"b\" \"c\" \n## [4,] \"9\" \"g\" \"a\" \n\nI would like to print a pdf that just has the data that I entered into the matrix:\nid class type\n\"1\" \"a\" \"c\" \n\"5\" \"g\" \"c\" \n\"4\" \"b\" \"c\" \n\"9\" \"g\" \"a\" \n\nA:\n\nYou can use kable from the knitr package.\nm <- matrix(\n c(1, \"a\", \"c\", 5, \"g\", \"c\", 4, \"b\", \"c\", 9, \"g\", \"a\"),\n ncol=3,\n byrow=TRUE\n)\n\ncolnames(m) <- c(\"id\", \"class\", \"type\")\n\nknitr::kable(m)\n\n# |id |class |type |\n# |:--|:-----|:----|\n# |1 |a |c |\n# |5 |g |c |\n# |4 |b |c |\n# |9 |g |a |\n\nYou could also read up on the excellent kableExtra package here, which will allow you some great formatting options.\n\nN.B. My initial answer included casting as a data frame, which remains my usual workflow when creating tables. However as was pointed out, kable will happily accept a matrix as input.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29026,"cells":{"text":{"kind":"string","value":"Q:\n\nEditing a Wizard multistep form after save - Wicked Gem / Rails\n\nI've been going round in circles all day with this. I have a large multi-step form using the Wicked gem and Ruby on Rails. It works perfectly but I can't figure out how to to get back into the form to edit individual entries. \nIim trying to make the ability to go into the client show page, click an individual client and then from there go back into the quote to edit and update it. As the Wicked gem only seems to work with show and update actions, if I try to build a standard edit action Wicked expects to be on a step therefore doesn't work. \nI read the I would have to factor the edit action into my show/update actions but I'm having difficulties. Any help would be great thanks!\nClients Controller:\nclass ClientsController < ApplicationController\nbefore_action :authenticate_user!, only: [:index, :show, :edit]\nbefore_action :set_client, only: [:edit, :show, :update]\n\ndef index\n @clients = Client.order('created_at DESC').paginate(page: params[:page], per_page: 10)\nend\n\ndef show; end\n\ndef new\n @client = Client.new \nend\n\ndef edit; end\n\ndef update\n if @client.update_attributes(client_params)\n redirect_to client_quotes_path\n flash[:success] = 'Client successfully updated'\n else\n render 'edit'\n end\n render_wizard @client\nend\n\n# After client is completed:\ndef create\n @client = Client.new(client_params)\n if @client.valid?\n @client.save\n session[:current_user_id] = @client.id\n ClientMailer.new_client(@client).deliver\n redirect_to quotes_path\n else\n flash[:alert] = 'Sorry, there was a problem with your message. Please contact us directly at ...'\n render :new\n end\nend\n\nprivate\n\ndef set_client\n @client = Client.find(params[:id])\nend\n\ndef client_params\n params.require(:client).permit(:first_name, :last_name, :title, :email, :email_confirmation,\n :phone, :time, :reminder, :ref_number, :day, :note, :logs_reminder)\nend\nend\n\nQuotes Controller:\nclass QuotesController < ApplicationController\ninclude Wicked::Wizard\nbefore_action :set_client, only: [:show, :update, :quote_success]\nsteps :profile, :employment, :general_questions, :indemnity_details, :declarations\n\ndef show\n @client.build_doctor unless @client.doctor.present?\n @client.build_dentist unless @client.dentist.present?\n @client.old_insurers.build\n @client.practice_addresses.build\n render_wizard\nend\n\ndef update\n @client.update(client_params)\n render_wizard @client\nend\n\ndef quote_success; end\n\nprivate\n\ndef set_client\n current_user = Client.find_by_id(session[:current_user_id])\n @client = current_user\nend\n\n# After full quote form is completed:\ndef finish_wizard_path\n if @client.valid?\n ClientMailer.new_quote(@client).deliver\n ClientMailer.new_quote_user_message(@client).deliver\n end\n quote_success_path\n end\nend\n\ndef client_params\n params.require(:client).permit(:name, :email, :email_confirmation, :phone, :date_required,\n :title, :first_name, :last_name, :date_of_birth, :nationality, :reg_body, :reg_date, :reg_type, :reg_number,\n :qual_place, :qual_year, :post_grad, :membership ...\n\nRoutes: \nRails.application.routes.draw do\n\ndevise_for :users\n\nroot 'clients#new'\n\nget 'client', to: 'clients#new', as: 'client'\npost 'client', to: 'clients#create'\n\nget '/client_quotes', to: 'clients#index', as: 'client_quotes'\nget '/client_quotes/:id', to: 'clients#show', as: 'client_quote'\nget '/client_quotes/:id/edit', to: 'clients#edit', as: 'edit_client_quote'\npatch '/client_quotes/:id', to: 'clients#update'\nput '/client_quotes/:id', to: 'clients#update'\n\nresources :quotes, only: [:index, :show, :update, :quote_success]\n\nget 'quote-success' => 'quotes#quote_success'\n\ndevise_scope :user do\n get '/login' => 'devise/sessions#new'\nend\nend\n\nA:\n\nMy solution to this in the end was rather than have the edit form as a multi step wizard, I've joined the form data together in a separate view page and got a traditional route to it as you mention. Not perfect but does the job!\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29027,"cells":{"text":{"kind":"string","value":"Q:\n\nPutting/Getting compressed data in SQLite with F#\n\nI am attempting to port an existing project of mine (a web scraper) from Python to F#, in order to learn F#. A component of the program saves compresses large strings (raw HTML) using LZMA, and stores it in SQLite in a makeshift key value table. The HTML string should always be unicode.\nBecause I am an F# beginner and this requires a lot of .NET interop, I am very confused as to how to accomplish this.\nI would like to know how to do this properly in F#, and using LZMA instead of GZip.\nEdit\nI had difficulty finding an LZMA2 compatible .NET library, as LZMA-SDK uses LZMA1. This would not have been compatible with my existing data compressed using LZMA2. Therefore, along with help from comments I went ahead and implemented this using Gzip.\n\nA:\n\nThis uses Gzip for compression and is compatible with the gzip.compress/gzip.decompress functions in Python 3.5.\n#if INTERACTIVE\n#r \"../packages/System.Data.SQLite.Core/lib/net46/System.Data.SQLite.dll\"\n#endif\n\nopen System.IO\nopen System.IO.Compression\nopen System.Data.SQLite\n\nlet compressString (s:string) =\n let bs = System.Text.Encoding.UTF8.GetBytes(s)\n use outStream = new MemoryStream()\n use gzOutStream = new GZipStream(outStream, CompressionMode.Compress, false)\n gzOutStream.Write(bs, 0, bs.Length)\n outStream.ToArray()\n\nlet decompressString (bs:byte[]) =\n use newInStream = new MemoryStream(bs)\n use gzOutStream = new GZipStream(newInStream, CompressionMode.Decompress, false)\n use sr = new StreamReader(gzOutStream)\n sr.ReadToEnd()\n\nlet insert dbc (key:string) (value:string) =\n let compressed = compressString value\n let cmd = new SQLiteCommand(\"INSERT into kvt (key, value) VALUES (@key, @value)\", dbc)\n cmd.Parameters.Add(new SQLiteParameter(\"@key\", key)) |> ignore\n cmd.Parameters.Add(new SQLiteParameter(\"@value\", compressed)) |> ignore\n let res = cmd.ExecuteNonQuery()\n res\n\nlet fetch dbc (key:string) =\n let cmd = new SQLiteCommand(\"SELECT value FROM kvt WHERE key = @key\", dbc)\n cmd.Parameters.Add(new SQLiteParameter(\"@key\", key)) |> ignore\n let reader = cmd.ExecuteReader()\n reader.Read() |> ignore\n let compressed = unbox reader.[\"value\"]\n decompressString compressed\n\nlet create() = \n System.Data.SQLite.SQLiteConnection.CreateFile(\"mydb.sqlite\")\n let dbc = new SQLiteConnection(\"Data Source=mydb.sqlite;Version=3;\")\n dbc.Open()\n let cmd = new SQLiteCommand(\"CREATE TABLE kvt (key TEXT PRIMARY KEY, value BLOB)\", dbc)\n let res = cmd.ExecuteNonQuery()\n dbc\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29028,"cells":{"text":{"kind":"string","value":"Q:\n\nExpressJs Compatibility with NodeJs Version\n\nI am trying to find to see if expressjs 4 can support Nodejs 10.15.3 ( Lts) version. Is there any compatibility matrix that i can look into before deciding versions to choose? \n\nA:\n\nIf you check out express/package.json you can see that express needs node v0.10.0 or newer.\nSo yes, Express.js v4 is supporting Node.js v10.15.3.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29029,"cells":{"text":{"kind":"string","value":"Q:\n\nTelerik MVC Grid does not display data\n\nI am using version 2011.2.914 of the controls. Whenever I try to bind data from my controller to a view, I can't get the data inside the collection to display on the grid. I get the \"No records to display\" message from the grid.\nI want to point out that if I am not using the Telerik grid, the data comes out fine (see below):\n Controller without Telerik Grid\nIEnumerable customerList = db.GetCustomers();\n return View(\"Index\", customerList);\n\nView\n@model IEnumerable\n\n@{\n ViewBag.Title = \"Customer Index\";\n}\n

Customer Index

\n

\n @Html.ActionLink(\"Create New\", \"Create\")\n

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n @if (ViewData.Model != null)\n {\n foreach (var item in Model)\n {\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n }\n }\n
\n Email\n \n Company\n \n FirstName\n \n LastName\n \n Address1\n \n Address2\n \n City\n \n State\n \n Zip\n \n HomePhone\n \n CellPhone\n \n Website\n \n IMAddress\n \n CreatedDate\n \n UpdatedDate\n \n
\n @Html.DisplayFor(modelItem => item.Email)\n \n @Html.DisplayFor(modelItem => item.Company)\n \n @Html.DisplayFor(modelItem => item.FirstName)\n \n @Html.DisplayFor(modelItem => item.LastName)\n \n @Html.DisplayFor(modelItem => item.Address1)\n \n @Html.DisplayFor(modelItem => item.Address2)\n \n @Html.DisplayFor(modelItem => item.City)\n \n @Html.DisplayFor(modelItem => item.State)\n \n @Html.DisplayFor(modelItem => item.Zip)\n \n @Html.DisplayFor(modelItem => item.HomePhone)\n \n @Html.DisplayFor(modelItem => item.CellPhone)\n \n @Html.DisplayFor(modelItem => item.Website)\n \n @Html.DisplayFor(modelItem => item.IMAddress)\n \n @Html.DisplayFor(modelItem => item.CreatedDate)\n \n @Html.DisplayFor(modelItem => item.UpdatedDate)\n \n @Html.ActionLink(\"Edit\", \"Edit\", new { id = item.CustomerID }) |\n @Html.ActionLink(\"Details\", \"Details\", new { id = item.CustomerID })\n
\n\nI have tried ServerSide and Ajax Binding. Both don't work. I have searched the Telerik site and the web and can't find out what is missing.\nWhat do I need to do in order to resolve this and get the data in my grid?\nHere is the code in my Customer controller for the Ajax binding (which is what I really want). Upon return of getting the data, I have an image file that I saved where the data is in the customerList collection (there is no option to attach any files in StackOverflow, so I can't show you).\nWhen the View is being rendered, I captured data while debugging for several objects. \nWhen cycling through the grid during the binding, I captured data in another file.\nController using Telerik Grid:\n using Telerik.Web.Mvc;\n public class CustomerController : Controller\n {\n[GridAction]\n public ActionResult Index()\n {\n IEnumerable customerList = db.GetCustomers();\n return View(new GridModel\n {\n Data = customerList\n });\n\n }\n }\n\nBelow, is the code in my associated View. btw, all the bound columns have intellisense that pop up for the columns in my model. This is for the Index action within the Customer controller.\n@model Telerik.Web.Mvc.GridModel\n @{\n ViewBag.Title = \"Customer Index\";\n }\n

\n Customer Index

\n

\n @Html.ActionLink(\"Create New\", \"Create\")\n

\n \n @(Html.Telerik().Grid()\n .Name(\"Customers\")\n .Columns(columns =>\n {\n columns.Bound(o => o.Email);\n columns.Bound(o => o.Company);\n columns.Bound(o => o.FirstName);\n columns.Bound(o => o.LastName);\n columns.Bound(o => o.Address1);\n columns.Bound(o => o.Address2);\n columns.Bound(o => o.City);\n columns.Bound(o => o.State);\n columns.Bound(o => o.Zip);\n columns.Bound(o => o.HomePhone);\n columns.Bound(o => o.CellPhone);\n columns.Bound(o => o.Website);\n columns.Bound(o => o.IMAddress);\n columns.Bound(o => o.CreatedDate).Format(\"{0:MM/dd/yyyy}\");\n columns.Bound(o => o.UpdatedDate).Format(\"{0:MM/dd/yyyy}\");\n }).DataBinding(dataBinding => dataBinding.Ajax().Select(\"Index\", \"Customer\"))\n .Pageable()\n .Sortable()\n .Scrollable()\n .Resizable(resizing => resizing.Columns(true))\n .Filterable())\n
\n\nA:\n\nMaybe there's a conflic with your Index action method since that you have a View that is referenced to it. The first test to do is to show your grid without playing with Ajax or anything else.\nTry this to initialize your grid when your View Index is build. Notice the Model.Data that i'm using in the Grid constructor:\n@(Html.Telerik().Grid(Model.Data)\n .Name(\"Customers\")\n .Columns(columns =>\n {\n columns.Bound(o => o.Email);\n columns.Bound(o => o.Company);\n ...\n }))\n\nIf it work, then you should try to create another Action method with another name. In my projects, i do this:\n[GridAction]\npublic ActionResult GetYeagerTechGridData()\n{\n IEnumerable customerList = db.GetCustomers();\n return View(new GridModel\n {\n Data = customerList\n });\n}\n\nand use your grid that way:\n@(Html.Telerik().Grid()\n .Name(\"Customers\")\n .Columns(columns =>\n {\n columns.Bound(o => o.Email);\n columns.Bound(o => o.Company);\n ...\n })\n .DataBinding(dataBinding => dataBinding.Ajax().Select(\"GetYeagerTechGridData\", \"Customer\")))\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29030,"cells":{"text":{"kind":"string","value":"Q:\n\nRecurrence relation and initial conditions for the number of ways to build a stack of height n cm using blocks.\n\nI'm working on a problem, and I just want to make sure that my work is correct. The problem goes like this:\n\nSuppose that we have a collection of building blocks consisting of red, blue, and\n green blocks of height 1 cm and yellow blocks of height 3 cm. Write a recurrence\n relation and initial conditions for the number of ways to build a stack of height n cm using these blocks.\n\nI let Sn be the total number of ways, and this is my solution:\nSn = Sn-1 + Sn-1 + Sn-1 + Sn-3\nSn = 3Sn-1 + Sn-3\nAnd with our initial conditions:\nS0 = 1\nS1 = 3 (blue or red or green)\nS2 = 9\nSn = 3(9) + 1 = 28.\n\nA:\n\nYes your answer is correct. I've done this one before! Similar answer here: https://answers.yahoo.com/question/index?qid=20160419091913AAPO82O\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29031,"cells":{"text":{"kind":"string","value":"Q:\n\nUse JSON file to populate a listview\n\nI have the following code which retrieves the JSON file:\npublic class GetJSON extends AsyncTask {\n @Override\n protected Void doInBackground(Void... params) { //Running in background\n try {\n httpclient = new DefaultHttpClient(new BasicHttpParams());\n HttpPost httppost = new HttpPost(\"http://pagesbyz.com/test.json\");\n // Depends on your web service\n httppost.setHeader(\"Content-type\", \"application/json\");\n HttpResponse response = httpclient.execute(httppost); \n HttpEntity entity = response.getEntity();\n\n inputStream = entity.getContent();\n // json is UTF-8 by default\n BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, \"UTF-8\"), 8);\n sb = new StringBuilder();\n\n String line = null;\n while ((line = reader.readLine()) != null)\n {\n sb.append(line + \"\\n\");\n }\n result = sb.toString();\n\n } catch (Exception e) {\n Log.i(\"TEST\", e.toString());\n // Oops\n }\n finally {\n try{if(inputStream != null)inputStream.close();}catch(Exception squish){}\n }\n return null;\n }\n\n @Override\n protected void onPreExecute() { //Activity is on progress\n }\n\n @Override\n protected void onPostExecute(Void v) { //Activity is done...\n Toast.makeText(getActivity(), result, 2000).show();\n int k = 0;\n try {\n JSONArray jsonall = new JSONArray();\n jsonArray = new JSONArray(result);\n for(int i = 0; i < jsonArray.length(); i++) {\n JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object\n if(jsonObj.getString(\"type\").equals(\"image\") || jsonObj.getString(\"type\").equals(\"text\")) { // compare for the key-value\n k++;\n jsonall.put(jsonObj);\n sId = new String[jsonall.length()];\n sType = new String[jsonall.length()];\n sData = new String[jsonall.length()];\n for (int m = 0 ; m < jsonall.length(); m++){ //4 entries made\n JSONObject c = jsonall.getJSONObject(m);\n\n String id = c.getString(\"id\");\n String type = c.getString(\"type\");\n String data = c.getString(\"data\");\n\n sId[m] = id;\n sType[m] = type;\n sData[m] = data;\n }\n }\n }\n Toast.makeText(getActivity(), String.valueOf(k), 2000).show();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n}\n\nOn the onPostExecute() function I am able to de-serialize the data, in this case by TYPE.\nI have the following code for the CustomAdapter\npublic class SetRowsCustomAdapter extends ArrayAdapter {\n Context context;\n int layoutResourceId;\n ArrayList data=new ArrayList();\n public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList data) {\n super(context, layoutResourceId, data);\n this.layoutResourceId = layoutResourceId;\n this.context = context;\n this.data = data;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View row = convertView;\n ImageHolder holder = null;\n\n if(row == null)\n {\n LayoutInflater inflater = ((Activity)context).getLayoutInflater();\n row = inflater.inflate(layoutResourceId, parent, false);\n\n holder = new ImageHolder();\n holder.tID = (TextView)row.findViewById(R.id.tvID);\n holder.tType = (TextView)row.findViewById(R.id.tvType);\n holder.tData = (TextView)row.findViewById(R.id.tvData);\n row.setTag(holder);\n }\n else\n {\n holder = (ImageHolder)row.getTag();\n }\n\n SetRows myImage = data.get(position);\n holder.tID.setText(myImage.id);\n holder.tType.setText(myImage.type);\n holder.tData.setText(myImage.data);\n return row;\n\n }\n\n static class ImageHolder\n {\n TextView tID;\n TextView tType;\n TextView tData;\n }\n}\n\nMy SetRows code is:\npublic class SetRows {\n\n String id;\n String type;\n String data;\n\n public String getData () {\n return data;\n }\n\n public void setData (String data) {\n this.data = data;\n }\n\n public String getID () {\n return id;\n }\n\n public void setID (String id) {\n this.id = id;\n }\n public String getType () {\n return type;\n }\n\n public void setType (String type) {\n this.type = type;\n }\n\n public SetRows(String id, String type, String data) {\n super();\n this.id = \"ID: \\t\" + id;\n this.type = \"TYPE: \\t\" + type;\n this.data = \"DATA: \\t\" + data;\n }\n}\n\nMy XML file for the Layout file is:\n\n\n \n\n\nThe custom layout for the ListView is:\n\n\n\n \n \n \n\n\nI want to display the data like this in a ListView from the JSON file from my server:\n\nI think I have all the information needed. I just need to know, now, how to display the information. All help is greatly appreciated. Thanks!\nUPDATE: The following code is working, but it's entering multiple entries for each:\npublic class GetJSON extends AsyncTask {\n @Override\n protected Void doInBackground(Void... params) { //Running in background\n try {\n httpclient = new DefaultHttpClient(new BasicHttpParams());\n HttpPost httppost = new HttpPost(\"http://pagesbyz.com/test.json\");\n // Depends on your web service\n httppost.setHeader(\"Content-type\", \"application/json\");\n HttpResponse response = httpclient.execute(httppost); \n HttpEntity entity = response.getEntity();\n\n inputStream = entity.getContent();\n // json is UTF-8 by default\n BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, \"UTF-8\"), 8);\n sb = new StringBuilder();\n\n String line = null;\n while ((line = reader.readLine()) != null)\n {\n sb.append(line + \"\\n\");\n }\n result = sb.toString();\n\n } catch (Exception e) {\n Log.i(\"TEST\", e.toString());\n // Oops\n }\n finally {\n try{if(inputStream != null)inputStream.close();}catch(Exception squish){}\n }\n return null;\n }\n\n @Override\n protected void onPreExecute() { //Activity is on progress\n }\n\n @Override\n protected void onPostExecute(Void v) { //Activity is done...\n //Toast.makeText(getActivity(), result, 2000).show();\n int k = 0;\n try {\n JSONArray jsonall = new JSONArray();\n jsonArray = new JSONArray(result);\n for(int i = 0; i < jsonArray.length(); i++) {\n JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object\n if(jsonObj.getString(\"type\").equals(\"image\") || jsonObj.getString(\"type\").equals(\"text\")) { // compare for the key-value\n k++;\n jsonall.put(jsonObj);\n sId = new String[jsonall.length()];\n sType = new String[jsonall.length()];\n sData = new String[jsonall.length()];\n for (int m = 0 ; m < jsonall.length(); m++){\n JSONObject c = jsonall.getJSONObject(m);\n\n String id = c.getString(\"id\");\n String type = c.getString(\"type\");\n String data = c.getString(\"data\");\n\n //sId[m] = id;\n //sType[m] = type;\n //sData[m] = data;\n contents.add(new SetRows(id, type, data));\n }\n }\n adapter = new SetRowsCustomAdapter(getActivity(), R.layout.listrow, contents);\n lAll.setAdapter(adapter);\n lAll.setOnItemClickListener(new OnItemClickListener() {\n @Override\n public void onItemClick(AdapterView parent, View view, int position,\n long id) {\n Intent myIntent = new Intent(getActivity(), DisplayWeb.class);\n startActivityForResult(myIntent, 0);\n }\n });\n }\n //Toast.makeText(getActivity(), String.valueOf(k), 2000).show();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\nThe duplicate shows up as like this:\n\nA:\n\nSublacss ListActivy and create a layout that contains a ListView with id @android:id/list\nput inside this subclass you AsyncTask and execute it in the on create.\nwhen onPostExecute is called, after you parse the JSON, create an instance of SetRowsCustomAdapter\ncall getListView().setAdapter(adapterInstance).\n @Override\n protected void onPostExecute(Void v) {\n ArrayList contents = new ArrayList();\n // other code\n\n //instead of those\n //sId[m] = id;\n //sType[m] = type;\n //sData[m] = data;\n //add \n contents.add(new SetRows(id, type, data));\n }\n\nEdit 2: You have two duplicates entry because you have an unuseful for loop (the innere one). Imo your code should look like:\n for(int i = 0; i < jsonArray.length(); i++) {\n JSONObject jsonObj = (JSONObject)jsonArray.get(i); \n if(jsonObj.getString(\"type\").equals(\"image\") || jsonObj.getString(\"type\").equals(\"text\")) { \n\n String id = jsonObj.getString(\"id\");\n String type = jsonObj.getString(\"type\");\n String data = jsonObj.getString(\"data\");\n\n contents.add(new SetRows(id, type, data));\n }\n }\n // the other stuff\n\nps. check for typo\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29032,"cells":{"text":{"kind":"string","value":"Q:\n\nAre external objects only available via Lightning Connect now?\n\nI dabbled around with External Data Sources a while back with this public Northwind OData data feed. I decided to take another look at it for a project we are working on, but it appears Salesforce has changed this feature so it no longer works with OData and external objects. The documentation now talks more about Files Connect and Lightning Connect, and doesn't say much of anything at all on how to use a Simple URL to connect to an external OData data source for defining External Objects.\nWhen I look at the screen, the page still makes mention of connecting to third-party databases and content systems:\n\nHas Salesforce removed the ability to connect to an OData Data Source using the out-of-the-box External Data Source feature?\n\nA:\n\nSimple URL is used for Files Connect and is not related to what was called Lightning Connect (now called Salesforce Connect).\nAs for whether Salesforce removed or crippled the feature, the answer is no. Salesforce Connect has ALWAYS been a paid add on. It is available for free on Developer Edition orgs to try out and see if it suits your needs, so maybe that's where you used it. \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29033,"cells":{"text":{"kind":"string","value":"Q:\n\nMvxImageViewLoader binding not working\n\nI use MvxImageViewLoader in pretty simple situation.\nOn ViewDidLoad:\n var pnlBackImage = new UIImageView(new RectangleF(0, 0, pnlBack.Frame.Width, pnlBack.Frame.Height));\n Add(pnlBackImage);\n pnlBackImageLoader = new MvxImageViewLoader(() => pnlBackImage);\n\n ...\n\n set.Bind(pnlBackImageLoader).To(x => x.UserBackgroundUrl);\n\nwhere UserBackgroundUrl is a common string property.\nBut on set.Apply() I see the following in my log and image is not loading:\n2013-06-24 13:51:26.999 SPBTouch[446:21b03] MvxBind: Error: 2.78 Problem seen during binding execution for from UserBackgroundUrl to ImageUrl - problem TargetInvocationException: Exception has been thrown by the target of an invocation.\n at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x000d9] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:236 \n at System.Reflection.MonoProperty.SetValue (System.Object obj, System.Object value, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] index, System.Globalization.CultureInfo culture) [0x00064] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoProperty.cs:353 \n at System.Reflection.PropertyInfo.SetValue (System.Object obj, System.Object value, System.Object[] index) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/PropertyInfo.cs:93 \n at Cirrious.MvvmCross.Binding.Bindings.Target.MvxPropertyInfoTargetBinding.SetValue (System.Object value) [0x00000] in :0 \n at Cirrious.MvvmCross.Binding.Bindings.MvxFullBinding.UpdateTargetFromSource (Boolean isAvailable, System.Object value) [0x00000] in :0 \nInnerException was NullReferenceException: Object reference not set to an instance of an object\n at Cirrious.MvvmCross.Binding.Views.MvxBaseImageViewLoader`1[MonoTouch.UIKit.UIImage].set_ImageUrl (System.String value) [0x00000] in :0 \n at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)\n at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x000c0] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:228 \n\nI've even defined the image loader and even the image panel as the view fields, but there is still no luck. What can cause that problem?\nThank you.\n\nA:\n\nThe inner exception error you've listed is:\n\nNullReferenceException: Object reference not set to an instance of an object\n at Cirrious.MvvmCross.Binding.Views.MvxBaseImageViewLoader`1[MonoTouch.UIKit.UIImage].set_ImageUrl (System.String value) [0x00000] in :0 \n\nI guess the thing that would cause a NullReferenceException in the set of:\n public string ImageUrl\n {\n get { return _imageHelper.ImageUrl; }\n set { _imageHelper.ImageUrl = value; }\n }\n\nis if _imageHelper is null\nLooking in MvxBaseImageViewLoader.cs#L31 this can happen if this error message is displayed Unable to resolve the image helper - have you referenced and called EnsureLoaded on the DownloadCache plugin?\nIs this error message displayed? If so, is the DownloadCache plugin (and it's dependent plugin File) loaded in your application?\n\nIf this doesn't help, try comparing your app so some of the apps in N+1. Successful use of the image views is covered in several of N+1 videos - http://mvvmcross.wordpress.com/ - e.g. N=2 or N=3\n\nA:\n\nI come here when I had the same error (exception) mentioned in this question by following the tutorial on MvvmCross CollectionView example. I found that you get this error if you missed registering/installing your plugins. I resolved the error by installing the following plugins:\n\nInstall-Package MvvmCross.ITSparta.Plugin.DownloadCache\nInstall-Package MvvmCross.ITSparta.Plugin.File\n\nWhen these plugins are installed, new files are created in your UI Project (iOS/Android) and these plugins are registered. Thus, you would not get this error.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29034,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to throw meaningful data in exceptions?\n\nI would like to throw exceptions with meaningful explanation (socket handle, process id, network interface index, ...) !\nI thought of using variable arguments worked fine but lately I figured out it's impossible to extend the class in order to implement other exception types. So I figured out using an std::ostreamstring as a an internal buffer to deal with formatting ... but doesn't compile!\nI guess it has something to deal with copy constructors. \nAnyhow here is my piece of code:\n class Exception: public std::exception {\npublic:\n Exception(const char *fmt, ...);\n Exception(const char *fname,\n const char *funcname, int line, const char *fmt, ...);\n //std::ostringstream &Get() { return os_ ; }\n ~Exception() throw();\n virtual const char *what() const throw();\nprotected:\n char err_msg_[ERRBUFSIZ];\n //std::ostringstream os_;\n};\nThe variable argumens constructor can't be inherited from! this is why I thought of std::ostringstream!\nAny advice on how to implement such approach ?\n\nA:\n\nIt is a bit awkward to pass ... arguments, but possible. You need first to convert them to va_list. So, for your derived class to be able to pass the format and the arguments to its base class something like the following can be done:\nclass Exception: public std::exception {\npublic:\n Exception(const char *fmt, ...)\n {\n va_list ap;\n va_start(ap, fmt);\n this->init(fmt, ap);\n va_end(ap);\n }\n\n virtual const char *what() const throw();\n\nprotected:\n Exception(); // for use from derived class's ctor\n\n void init(char const* fmt, va_list, ap)\n {\n vsnprintf(err_msg_, sizeof err_msg_, fmt, ap);\n }\n\n char err_msg_[ERRBUFSIZ];\n};\n\nstruct Exception2 : Exception\n{\n Exception2(const char *fmt, ...)\n {\n va_list ap;\n va_start(ap, fmt);\n this->init(fmt, ap);\n va_end(ap);\n }\n};\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29035,"cells":{"text":{"kind":"string","value":"Q:\n\nHow do I find where a line intersects itself?\n\nI am using Python 3.7 with Shapely and GeoPandas.\nI have a big line of 181,000 points, and would like to find all the points where the line intersects itself. It does so a lot.\nI don't need a new point at the precise intersection, just one of the existing points which is closest.\nI have been writing code to loop through the points and find other points close by using. \nfor i,point in gdf.iterrows():\n gdf[gdf.geometry.intersects(point.buffer(10) == True].index.tolist()\n\nWhere gdf is a geopandas GeoDataFrame where each row is a point from the line. \n(eg it looks like this:)\n geometry\n0 POINT (-47.91000 -15.78000)\n1 POINT (-47.92000 -15.78000)\n\nBut surely there is a way to do this using existing functions?\nMy way is very slow and records many duplicates at each intersection, so will require more code to reduce each intersection to one point.\n\nA:\n\nHere's how I did it\n\nslice the first feature\nmake a unary_union of the rest of the feature\ndo line intersections using shapely \nyou'll get one point of intersection.\nnow repeat for the second, third, fourth, and so on.\n\nhere's the example.\n\nsuppose a geodataframe (gdf) of 6 lines like this GeoJSON\n\nthen, apply this code to the gdf. This is returning the geometry of the intersections\n\n# the points of intersections will be appended here\npoints=[]\nfor i in gdf.id:\n print(i)\n # check overlap\n feature = gdf[gdf['id']==i]['geometry'][i]\n overlap_feature = gdf[gdf['id']!=i]['geometry'].unary_union\n intersects = feature.intersection(overlap_feature)\n points.append(intersects)\npoints\n\nnow, make a GeoDataFrame out of the points\n\nintersections = gpd.GeoDataFrame(\n {\"id\": [n for n,i in enumerate(points)]},\n crs={'init':'epsg:4326'},\n geometry=points\n)\n\nhere's the plot of the result\n\nimport matplotlib.pyplot as plt\nfig,ax = plt.subplots()\nintersections.plot(color=\"r\", ax=ax,zorder=2)\ngdf.plot(ax=ax,zorder=1)\n\nthe intersections data frame has Point and MultiPoint geometries. But there's a problem here... the points are intersecting. here's how to delete the overlapping points\nfrom shapely.geometry import Point\n\n# convert the multipoints into points \nintersections['ispoint'] = intersections['geometry'].apply(lambda x: isinstance(x, Point)) #backup\nis_point = intersections[intersections.ispoint] #check if it's point\nwas_multipoint = intersections[~intersections.ispoint].explode().reset_index() # converting the multipoint into points \n\n# now appending both data frames.\nnow_point = is_point.append(was_multipoint)\nnow_point.reset_index(inplace=True)\nnow_point = now_point[['id','geometry']]\nnow_point['id'] = now_point.index\n# ok, now_point contains all intersections, but the points are still overlapping each other\n\n# delete overlapping points\nintersections2 = now_point.copy()\npoints=[]\nn= 0\nfor i in intersections2.id:\n # check overlap\n feature = intersections2[intersections2['id']==i]['geometry'][i]\n overlap_feature = intersections2[intersections2['id']!=i]['geometry'].unary_union\n\n # IF the point is intersecting with other points, delete the point!\n if feature.intersects(overlap_feature):\n intersections2.drop(i, inplace=True)\n print(n, feature.intersects(overlap_feature))\n n+=1\nintersections2\n\nthe result is the same, but the intersection points won't overlap each other. here's the plot, and there are 6 row of dataframe, I checked.\nedit: note, using `unary_union` means that if we have a large dataset, this may be RAM consuming.\n\nA:\n\nThis splits each line at each vertice and then use crosses on all combinations of split lines:\nimport geopandas as gpd\nfrom shapely.geometry import LineString\nfrom itertools import combinations\nfrom collections import defaultdict\n\ndf = gpd.read_file('/home/bera/Desktop/crossing_lines.shp')\n\ndef findcrossings(line1, line2):\n crossings = []\n if line1.crosses(line2):\n crossings.append(line1.intersection(line2))\n return crossings\n\nresults = defaultdict(list)\nindices = df.index.to_list()\nfor i in indices: #For each row/feature/line\n line = df.geometry.iloc[i] #Fetch the geometry\n verts = [v for v in line.coords] #List all vertices\n segments = []\n for p1, p2 in zip(verts, verts[1:]): #For each pair of vertices (x1,y1) , (x2,y2)\n segment = LineString([p1, p2]) #create a line segment\n segments.append(segment)\n for l1, l2 in combinations(segments,2): #For all combinations of segments\n res = findcrossings(l1, l2) #Find crossings\n if len(res)>0:\n results[i].extend(res)\n\n#results \n#defaultdict(list,\n# {0: [,\n# ,\n# ,\n# ]})\n#Export results\n#gdf = gpd.GeoDataFrame(geometry=results[0])\n#gdf.to_file('/home/bera/Desktop/crossing_lines_self_intersections.shp')\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29036,"cells":{"text":{"kind":"string","value":"Q:\n\nInitializing struct array with arrays as elements of the struct\n\nI am trying to initialize an array of structs that contain an array. Looking at \nthis and\nthis, \nI think a pretty reasonable attempt is this:\nstruct Score_t{\n int * dice;\n int numDice;\n int value;\n};\nstruct Score_t Scores[NUMSCORES] = {\n [0]={{0,0,0},3,1000},\n [1]={{1,1,1},3,200},\n [2]={{2,2,2},3,300},\n [3]={{3,3,3},3,400},\n [4]={{4,4,4},3,500},\n [5]={{5,5,5},3,600},\n [6]={{0},3,100},\n [7]={{4},3,50}\n};\n\nHowever I can't get this to compile. Do you have any ways to get this done?\nEdit: Forgot the error message: (snipped)\n [5]={{5,5,5},3,600},\n ^\ngreed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default]\ngreed.c:79:2: warning: initialization makes pointer from integer without a cast [enabled by default]\ngreed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default]\ngreed.c:79:2: warning: excess elements in scalar initializer [enabled by default]\ngreed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default]\ngreed.c:79:2: warning: excess elements in scalar initializer [enabled by default]\ngreed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default]\ngreed.c:80:2: warning: braces around scalar initializer [enabled by default]\n\nA:\n\nint * can't be initialized with { } (not match)\nSo change to like this.\nstruct Score_t Scores[NUMSCORES] = {\n [0]={(int[]){0,0,0},3,1000},\n [1]={(int[]){1,1,1},3,200},\n [2]={(int[]){2,2,2},3,300},\n [3]={(int[]){3,3,3},3,400},\n [4]={(int[]){4,4,4},3,500},\n [5]={(int[]){5,5,5},3,600},\n [6]={(int[]){0},3,100}, //It doesn't know the number of elements\n [7]={(int[]){4},3,50} //change to [7]={(int[3]){4},3,50} or [7]={(int[]){4},1,50}\n};\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29037,"cells":{"text":{"kind":"string","value":"Q:\n\nAltering the data on diagrams\n\nI am working on a statistics project and i came across one tiny issue. I have to work out a tactic for bidding on horse racing. We were given a set of 300 races with data such as the time, favorable odds, and if the favorable won or not. So i thought I could order the table in ascending order in relation to the time, and see how are the wins spread during the day. So I had games starting from 13:35 to 21:20, so I divided the time into 1 hour chunks (except the 1st chunk which is only 25 min, and last chunk which is only 20 min) and related wins to those chunks respectively. Then I added up all the wins inside each chunk, and presented that on the chart, the chart looks like this:\n\nIt works with my tactic which is to play between 14:00 and 16:00 cause then the bookie starts making odds as favorable to himself and starts robbing you from your earned money he just gave you. The thing is that on the bottom it says 2, 4, 6, 8.. but I want to write 13:35-14:00, 14:00 - 15:00 etc.. How can I do that, given that the code I used is that:\n> plot(chunksVector, type=\"o\", col=\"blue\", xlab=\"Time\", ylab=\"Wins\")\n\nHow can I do this? I've been struggling with this one for some time now. Is there any way to alter the code?\nP.S: \"chunks\" is just the name i gave to separated wins based on 1 hour distance. So i basically have a chink13.35_14.00, chunk14.00_15.00, chunk15.00_16.00 etc.. What I want to alter is only the X axis.\nI want it to look like this:\n\nA:\n\nthe quick answer is:\nplot(chunksVector, type=\"o\", col=\"blue\", xlab=\"Time\", ylab=\"Wins\", xaxt=\"n\")\n\naxis(1, at=c(2,4,6,8), labels=c('14:00', '16:00', '18:00', '20:00'))\n\nThere are probably a few other ways messing about with time-series packages?\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29038,"cells":{"text":{"kind":"string","value":"Q:\n\nFill an ASP.NET Form from a Word Document\n\nIt's possible to fill an ASP.NET Form (MVC 4) reading (or importing) a Word Document? \nUpdate\nWe have an standard document for our pricing agreements and quotations, and what I would like implement is read that document (maybe later they want to upload the document to a dropbox account or similar service) and fill the form to create a new project in the application. The document contains the same titles only change the items, prices, etc.\nThanks for your time\nRegards\n\nA:\n\nYou can do it in two ways:\n\nClient side\n\na) Using a converter (An executable)\nb) Using component (i.g. ActiveX...)\n\nServer side\n\nServer side processing of MS Word document is much easier to handle for both client and you. After document was uploaded to a temporary folder on your server you can easily get access to it and since the format is unique and known to you, data could be extracted easily. You can then store it to database or show it on a filled form to user while any missing data could added by client in that form.\nThere are many code samples available for reading MS Word documents on the web.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29039,"cells":{"text":{"kind":"string","value":"Q:\n\nRails reading from settings.yml\n\nHi is it possible to read from an controller the settings yml? Im using rails 4.2.0\nI want to store some global information in the settings.yml to display those in the view\nat the moment I try this way:\nsettingsfile = File.read(Rails.root + \"./config/settings.yml\")\nsettingsfile = YAML.load(settingsfile)\nsettingsfile[\"default\"]\n\nworks but when I want to go deeper\nsettingsfile[\"default\"][\"info\"]\n\nits empty\nYml File\ndefault:\n supported_languages:\n de: Deutsch\n fr: Francais\n en: English\n it: Italiano\n sv: Svenska\n pt: Português\n nl: Nederlands\n es: Español\n production:\n info:\n version: 2.0.0\n datum: 11.05.2015\n\nA:\n\nwithout using gem..you can use something like ..\nyour dev/config/email.yml\n development:\n :address: smtp.service.com\n :port: 25\n :user_name: mike@gmail.com\n :password: mikepassword\nproduction:\n :address: smtp.gmail.com\n :port: 587\n :authentication: plain\n :user_name: mike@gmail.com\n :password: mikepassword\n :enable_starttls_auto: true\n\nyou can load this yml file simply like....\n email_settings = YAML::load(File.open(\"#{Rails.root.to_s}/config/email.yml\"))\n ActionMailer::Base.smtp_settings = email_settings[Rails.env] unless email_settings[Rails.env].nil?\n\nalso you may use - Rails::Application.config_for(:email) as shown in the documentation for Rails 4+ onwards.\n\nA:\n\nYou might try:\n@settingsvariable = Settings.default.supported_languages.de\n\nThis approach worked in my app.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29040,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat is a run on the pound?\n\nFrom the news today, it mentions that Jeremy Corbyn and the Labour Party is preparing to deal with a run on the pound.\nWhat is a run on the pound? Why is it making news headlines? \nWhy does Jeremy Corbyn plan for this eventuality happening?\nThe article says that it's where investors sell sterling en masse, but what can the Labour Government do in that situation?\n\nA:\n\nA \"run on the pound\" occurs when financial traders believe that it is not in their interest to own \"pounds\", but an alternative like dollars or euros, or even gold, is a better currency to own. They will then try to sell pounds, and buy the other currencies. In order to sell quickly they reduce the price at which they are selling pounds. As this happens we say that he value of the pound has dropped. Other investors seeing this drop in price may then try to sell off their pounds very quickly, cutting the price a lot. If everyone is trying to sell, then the value of the pound can drop rapidly against other currencies.\nThis has several consequences. It means that it costs more for a British company to buy things from abroad. The price of imported goods and raw materials goes up. This makes things more expensive. It makes it more costly to travel abroad. On the other hand, if you are making something in Britain and selling it abroad, it makes that thing cheaper, so it makes exporting more profitable, it also makes it cheaper for tourists to visit the UK. It would add to the costs of the government and lead to higher taxes, inflation and slower growth.\nThere was a run on the pound after the vote to leave the EU, there was also a run on the pound when it was forced to leave the ERM in 1992\nGenerally a run on the pound is a bad thing it destabilises international markets that depend on predictable prices. There is a concern that the level of government borrowing implied by the Labour party's policies would cause financial traders to sell pounds in large enough amounts to cause a run, and this would be damaging to the UK economy.\nAs such the shadow chancellor mentioned in a meeting that he was engaged in planning for this event, even though he said it was unlikely. The fact he mentioned this possibility surprised many journalists, as predicting a run on the pound can be a self-fulfilling prophesy.\nSo a run on the pound is not something that the Labour party planning to have. Instead the Labour party is planning its defensive strategy if a damaging run on the pound occurs.\n\nA:\n\nI'm assuming that the article you referred to is the first hit on Google under \"Corbyn\" and \"run on the pound\": Jeremy Corbyn: It's right to plan for run on pound\nIf so, I'm afraid you're not interpreting what the article said correctly.\nIt says:\n\nJeremy Corbyn says it is \"right to look at all these scenarios\" after his shadow chancellor suggested that there could be a run on the pound if Labour went into government.\n John McDonnell said Labour was doing \"war-game-type scenario-planning\" for events such as \"a run on the pound\".\n\nCorbyn doesn't want to do a run on the pound (to be more precise, this article does not say that he wants it. Whether he wants to or not is not something I know, as I don't know how to read minds yet). \nThe article says that he wants to prepare how to respond in the eventuality that a run on the pound happens (intentionally or not) as a result of Labour party forming the government.\n\nA:\n\nI think he's overstating expectations here. There was, immediately after Brexit, a serious run on the British Pound\n\nThe British pound fell more than 10 percent on Thursday night, reaching $1.34 per pound, after midnight Eastern time, a stunning decline for a rich country's currency in a single day. The plunge came as United Kingdom voted to leave the European Union, a historic event that shatters 40 years of efforts to foster economic integration on the continent.\n\nInside Britain that wouldn't have a lot of immediate effect, but over time that causes a jump in prices. So let's say it cost £100 for three barrels of oil before. A 10% drop in the value of the Pound means you now have to spend £111 for those same three barrels. Remember, the seller has to convert that currency to something they can use, so someone is having to sell Pounds. This generally leads to inflation (where prices rise in a long-term way).\nThere's not much a government can do to stop a run (markets are global now). In fact, in 1992 the UK tried unsuccessfully to stop the events now known as Black Wednesday, where the Pound was being short sold by a hedge fund\n\nThe UK government attempted to prop up the depreciating pound to avoid withdrawal from the monetary system the country had joined two years earlier. John Major raised interest rates to 10 percent and authorized the spending of billions worth of foreign currency reserves to buy up the sterling being sold on the currency markets, but the measures failed to prevent the pound falling below its minimum level in the ERM.\n\nCorbyn seems to be talking about another run based on a potential Labour Party victory in the next election\n\nThe planning scenario means a Labour victory would ultimately trigger the fall in the value of the pound, which has already fallen following the Brexit vote, and could be devastating for the UK economy.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29041,"cells":{"text":{"kind":"string","value":"Q:\n\nServing Streaming Content without streaming distribution\n\nI am new to Streaming Media. I am working on a web application built using Symfony 1.4. It features audio players and I am using jPlayer for the player. I use ffmpeg for encoding the audio files. Currently, I am storing my audio files on the development server. However, I would want to use Amazon S3 Storage Service for storing my audio files. While going through the information available over the WWW and Amzon's site, I came to realize that it would require a streaming distribution service viz. Amazon Cloudfront. At present, I am not using any streaming distribution while I play audio from my server. Is it necessary to use Amazon Cloudfront ? Can't I directly serve my audio files from Amazon S3 by providing a URL as http://s3.mybucket.com/XXX ? What are the consequences of serving files directly from Amazon S3 and not using Cloudfront ?\nA demo of the player that I am using can be seen here: http://audiodip.org/project/detailsProject/id/5\n\nA:\n\nIf the audio file has to be retrieved from a remote server(in your case S3) you should read and play it as a streaming audio. \nOtherwise it is like downloading the full audio file to the application server and then playing it.\nCloudfront is a content delivery service with which streaming comes of no extra cost. \nSo it is better use the streaming service from cloudfront.\nand you will have to enable your audio player to play streaming data.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29042,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to pass properties to Java when using COMPSs\n\nI have a java application which is launched with a settings file passed as a property as follows:\njava -DpropertiesFile=/path/to/properties/settings.properties -jar /path/to/jar/file.jar\n\nI would like to know how/if I can pass this properties file when running my application with COMPSs framework. \nThanks\n\nA:\n\nCurrently the only option is to set the environment variable _JAVA_OPTIONS. This is variable is read once the JVM is started.\nIn your example it would be:\nexport _JAVA_OPTIONS=-DpropertiesFile=/path/to/properties/settings.properties\n\nNB: I used export as an example, use whatever command your system has to set environment variables.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29043,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to fix state update?\n\nI draw a grid N × N. Suppose that grid is an array of N x N. I need to get the array' index when I click at the element and when put it to the store.\nThat is, I get the coordinates (x, y) relative to the canvas, and translate them into the index. The store is an associative array. Recording condition: if the store hasn't index I put it, if no I delete it.\nThe index, which I need to be written a second time as a rule and after erasing the console give the error\nTypeError index: this.state.store.has is not a function. (The 'this.state.store.has (member)', 'this.state.store.has' is not defined)\nHow to fix it?\n\nexport default class SimulationField extends React.Component {\r\n \r\n constructor(props) {\r\n super(props);\r\n \r\n this.state = {\r\n store: new Map(),\r\n scale: 20,\r\n edge: this.props.edge\r\n }\r\n }\r\n \r\n handleClick(e) {\r\n \r\n let x = Math.floor(getMouseX(e, this.refs.canvas) * this.state.scale / this.state.edge)\r\n let y = Math.floor(getMouseY(e, this.refs.canvas) * this.state.scale / this.state.edge)\r\n \r\n let element = xy2Key(this.state.scale)([x, y])\r\n \r\n this.setState({ \r\n store: ( this.state.store.has(element) )\r\n ? this.state.store.delete(element)\r\n : this.state.store.set(element, true)\r\n })\r\n }\r\n \r\n componentDidMount() {\r\n this.updateCanvas();\r\n }\r\n \r\n updateCanvas() {\r\n const ctx = this.refs.canvas.getContext('2d');\r\n renderGrid({ ctx, edge: this.state.edge, scale: this.state.scale })\r\n }\r\n \r\n render() {\r\n return (\r\n
\r\n \r\n \r\n
\r\n );\r\n }\r\n}\n\nA:\n\nNearly, but .delete won't return store like .set does.\n\nReturns true if an element in the Map object existed and has been removed, or false if the element does not exist.\n\nThis means that if this.state.store.has(element) is ever true, you are effectively just doing:\nthis.setState({ \n store: true\n})\n\nNext time you try and call store.has you are actually just trying to call true.has, which doesn't work.\nTry this instead.\nif (this.state.store.has(element)) {\n this.state.store.delete(element)\n} else {\n this.state.store.set(element, true)\n}\n\nthis.setState({ store })\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29044,"cells":{"text":{"kind":"string","value":"Q:\n\nWhat's wrong with this socket code in blackberry?\n\ni'm getting a JVM Error 104, Uncaught: NullPointerException, this is my code, I couldn't track errors: \npackage com.rim.samples.device.socketdemo;\n\nimport java.io.*;\nimport javax.microedition.io.*;\nimport net.rim.device.api.ui.*;\n\npublic class ConnectThread extends Thread\n{ \n //private InputStream _in;\n private OutputStreamWriter _out; \n private SocketDemoScreen _screen; \n\n // Constructor\n public ConnectThread()\n {\n _screen = ((SocketDemo)UiApplication.getUiApplication()).getScreen(); \n }\n\n public void run()\n {\n StreamConnection connection = null; \n String user = \"Cegooow\";\n String channel = \"#oi\";\n try\n {\n _screen.updateDisplay(\"Opening Connection...\");\n String url = \"socket://\" + _screen.getHostFieldText() + \":6667\" + (_screen.isDirectTCP() ? \";deviceside=true\" : \"\"); \n connection = (StreamConnection)Connector.open(url);\n _screen.updateDisplay(\"Connection open\");\n\n //_in = connection.openInputStream();\n\n _out = new OutputStreamWriter(connection.openOutputStream()); \n //StringBuffer s = new StringBuffer();\n\n _out.write(\"NICK \" + _screen.getNickText() + \"\\r\\n\");\n _out.write(\"USER \" + user + \"8 * : Client\\r\\n\");\n _out.write(\"JOIN \" + channel + \"\\r\\n\");\n _out.write(\"PRIVMSG \" + channel + \" \" + _screen.getMessageFieldText() + \"\\r\\n\"); \n _screen.updateDisplay(\"Done!\");\n }\n catch(IOException e)\n {\n System.err.println(e.toString());\n }\n finally\n { \n _screen.setThreadRunning(false);\n\n /*try\n { \n _in.close(); \n }\n catch(IOException ioe)\n { \n }*/\n try\n { \n _out.close(); \n }\n catch(IOException ioe)\n { \n }\n try\n { \n connection.close();\n }\n catch(IOException ioe)\n { \n }\n }\n }\n}\n\nA:\n\nTry to change the code of your finally block to smth like this:\ntry { \n if (_out != null) _out.close();\n} catch (IOException ioe) {}\n\ntry { \n if (connection != null) connection.close();\n} catch (IOException ioe) {}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29045,"cells":{"text":{"kind":"string","value":"Q:\n\nextract number from string in kdb\n\nI am quite new to kdb+q. I've come across this problem of extracting a number out of string. \nAny suggestions?\nExample:\n\"AZXER_1234_MARKET\" should output 1234 //Assume that there is only one number in the \n\nstring\n\nA:\n\nExtract the numbers then cast to required type.\nq){\"I\"$x inter .Q.n} \"AZXER_1234_MARKET\"\n1234i\n\nq){\"I\"$x inter .Q.n} \"AZXER_123411_MARKET\"\n123411i\nq){\"I\"$x inter .Q.n} \"AZXER_1234_56_MARKET\"\n123456i\nq){\"I\"$x inter .Q.n} \"AR_34_56_MAT\"\n3456i\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29046,"cells":{"text":{"kind":"string","value":"Q:\n\nTelerik Report Error Handling\n\nSo what I'm doing is creating a report from multiple data sources (stored procedures) in vb.net. I am accomplishing this by putting them into a Dataset and passing it to the report.\nSo when i get to the report i end up with an iif statement to handle multiple fields that aren't consistently named across the stored procedures (I cannot change the names) but need to go into the same text box. Here's an example:\n=IIF(Fields.TableName <> '', Fields.TableName, IIF(Fields.usuTableName <> '', Fields.usuTableName, NULL))\nAs you can see, they are both the same, but named differently thus there scare of the overriding the other. Only one will be populated. However, The problem is if one of those field values don't exists... I.E. Fields.usuTableName\nSay for instance we are filtering by date and thus nothing is returned from the stored procedure that has the naming convention of Fields.usuTableName for that date range and thus creates no dataset but the others return values. When the report goes to render we get an error because Fields.usuTableName doesn't exists but Fields.TableName does.\n\nHow can i make sure a field name is valid before running the IF statement for it?\n\nA:\n\nHere's the function i used to evaluate it before using it:\n Public Shared Function GetValue(ByVal reportItem As Processing.ReportItem, ByVal field As String) As String\n Try\n Dim testdString As String\n Try\n testdString = reportItem.DataObject(field).ToString\n Catch ex As Exception\n 'must not be date\n End Try\n\n Return reportItem.DataObject(field).ToString\n\n Catch ex As Exception\n Return \"\"\n End Try\nEnd Function\n\nI called it for every field name in the report\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29047,"cells":{"text":{"kind":"string","value":"Q:\n\nhadoop 1.x ports list - 4 more unknown ports\n\nI configured and installed hadoop 1.2.1 single node. I configured the namenode and jobtracker address with ports as \"hdfs://localhost:9000\" and \"localhost:9001\" respectively.\nAfter starting the cluster (start-all.sh). I ran netstat -nltp after this, which listed the hadoop ports.\n50030 - jobtracker Web UI\n50060 - tasktracker Web UI\n50070 - namenode Web UI\n50075 - datanode Web UI\n(http://localhost:50075/browseDirectory.jsp?dir=%2F)\n50090 - secondary namenode Web UI\n\n54310 - namenode (as configured in XML)\n54311 - jobtracker (as configured in XML)\n50010 - datanode (for data transfer)\n50020 - datanode (for block metadata operations & recovery)\n33447 - tasktracker ( not configured. Any unused local port is chosen by hadoop itself)\n\nBut, a couple of other ports also were occupied and it shows it is java process (I stopped hadoop and confirmed that these belonged to that hadoop cluster only).\n48212 - ???\n41888 - ???\n47448 - ???\n52544 - ???\n\nThese are not fixed ports. They are chosen dynamically. Because, when i restarted the cluster (stop-all.sh and start-all.sh), the other ports were same as first time, except these ports changed\n48945 - tasktracker (This is fine, as explained before)\n\nWhat about the other ports? What are these ports used for?\n44117 - ???\n59446 - ???\n52965 - ???\n56583 - ???\n\nA:\n\nThank you for posting this interesting question, Vivek.\nIt intrigued me a lot and I dig up a bit of code for Apache Hadoop 1.2.1 - startup section for each of the master and slave; \nBut there were no additional port bindings except for the standard documented one.\nI did a couple of experiments on ways we can start a namenode and observed the ports using netstat -nltpa\n1) hadoop --config ../conf namenode -regular\n2) Directly invoking the Namenode main class\n3) Add the default core-default.xml and than start up the namenode\nMy observation was for #2 and #3 only standard ports showed up, so I looked up the java options and that was the bingo.\nComment all of below in hadoop-env.sh and then start hadoop, you will see only standard port, so the additional ports you see are all JMX bin ports\nexport HADOOP_NAMENODE_OPTS=\"-Dcom.sun.management.jmxremote $HADOOP_NAMENODE_OPTS\"\nexport HADOOP_SECONDARYNAMENODE_OPTS=\"-Dcom.sun.management.jmxremote $HADOOP_SECONDARYNAMENODE_OPTS\"\nexport HADOOP_DATANODE_OPTS=\"-Dcom.sun.management.jmxremote $HADOOP_DATANODE_OPTS\"\nexport HADOOP_BALANCER_OPTS=\"-Dcom.sun.management.jmxremote $HADOOP_BALANCER_OPTS\"\nexport HADOOP_JOBTRACKER_OPTS=\"-Dcom.sun.management.jmxremote $HADOOP_JOBTRACKER_OPTS\"\n\nHope this helps.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29048,"cells":{"text":{"kind":"string","value":"Q:\n\nWhy is my dropdown label split into 2 lines in Chrome?\n\nI am trying to put some padding to the right item of the navigation bar and when I reload the page in Chrome, the name is on 1 line and the down-arrow is on the line below the name.\nWhen I click it, the problem is resolved completely until the next reload or resize. I have tried to use Firefox but I did not face the same issue, everything goes right on Firefox. \nI wonder if there is a way to get rid of this issue whenever I reload the page in Chrome?\nMoreover, is there any other way that I could move the right-place nav-item to the left a little bit without using the padding?\nAnd when the name of Dropdown menu is too short (like 5 or 6 characters), the menu only shows part of it, how do I position the menu?\nThe problem when reload page on Chrome:\n\nThe problem disappears when you click on the menu:\n\nThe issue is not on Firefox:\n\nI tried using a short label:\n\nHere's my code\n\n\n\n\n \n \n Sth\n \n \n \n \n \n \n
\n \n
\n \n\n\nA:\n\nFor your padding just use px than %\n#zzz {\n padding-right: 10px;\n }\n\nFor your second issue since you're using bootstrap it comes with it's own css which is left aligning the menu all the way to the edge. You add this to override the issue.\n.dropdown-menu {\n right: 0;\n left: inherit;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29049,"cells":{"text":{"kind":"string","value":"Q:\n\nDisplaying results from a mySQL database ...how to add a table after X results?\n\nI have a script that gets results from a mySQL database and then outputs them, 4 on each row, 20 total. Sort of like:\nX X X X\nX X X X\nX X X X\nX X X X\n\nWhat I'm trying to do, is have the script output a piece of code (that I'll then HTMLify) after the first 4 rows. How would I do that? So that the result would be:\nX X X X\nsomething else\nX X X X\nX X X X\nX X X X\n\nHere is my current code:\n(Note I on purpose deleted the mySQL query and that stuff, to make it easier).\n\n\n\n\n\n\n\n\n\n
OUTPUT GOES HERE
\n\nA:\n\nif ($i == 4) { /* Or 5 if you only want to show it when $results > 4 */\n echo 'something else';\n}\n\nOr am I missing something crucial?\nI think your code is really hard to read and maintain, by the way. I would start by building a two-dimensional array of what I want and then output that.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29050,"cells":{"text":{"kind":"string","value":"Q:\n\nIs my .then Javascript Promise Working?\n\nHere is a snippet of my code:\n.then(functionUpdate(par))\n.then(function() {\nconsole.log(\"why do I see this in my terminal before i see all of the console.log from functionUpdate()?\");\n\nI want functionUpdate(par) to finish before going on to the next function but when I look in my terminal the console.log in the next function goes off before all of the console.log within functionUpdate. I presume this means that the functions are not being called synchronously. I thought the .then promise was supposed to enforce synchronous operations. What am I doing wrong?\nI've also tried using Parse.Promise (I'm using Parse.com and have it installed) and Q to no avail. If anything I often get an error saying I can not execute then on undefined.\n\nA:\n\nThis is explicitly how promises work: they will run \"until they are done\" and functions you pass as then handlers will trigger \"whenever the promised code yields a result\". In the mean time, the rest of your script that follows the promise chain keeps running as usual.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29051,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to automatically call a query for every new connection in MySQL?\n\nIs it possible to set or initialize a query in MySQL for every new connection ?\nWhenever a connection is created, it will call a procedure or a select query automatically ?\nAny script or config option for this?\n\nA:\n\nYou may want to check init_connect variable: \n\nA string to be executed by the server for each client that connects.\n The string consists of one or more SQL statements, separated by\n semicolon characters. For example, each client session begins by\n default with autocommit mode enabled.\n\nhttp://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_init_connect\n\nA:\n\nIf you have not only mysql-client tool, but additional any application layer, there is more jedi-style :) You can create simple decorator for your connector's class that will execute some queries when instance created (in constructor)/connect method invoked.\nHope it helps\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29052,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to copy a file to a windows path with wildcards in it?\n\nI am newbie to windows os. Please pardon my question if you feel it is like a noob question. \nI am trying to copy a a file from one path to another path. The thing is that the destination path has a wildcard character in it. How to copy? I assumed it as a simple task, but not to be.\nThis is the command\ncopy *.zip \"C:\\MyCave\\iso\\SDG\\cmpdir\\copy test\\ab\\cd\\*\\gh\"\n\nThe folder after ab\\cd is dynamic. So I have tried to use wildcard, but this is throwing an error. \nThe filename, directory name, or volume label syntax is incorrect.\n 0 file(s) copied.\n\nI want to copy files in directory gh in the path. \nHow to do it?\nRegards\n\nA:\n\nI would offer this method.\nFor /D %G In (\"C:\\MyCave\\iso\\SDG\\cmpdir\\copy test\\ab\\cd\\*\") Do @For %H In (\"%G\\gh\") Do @If \"%~aH\" GEq \"d\" Copy /Y \"*.zip\" \"%~H\" 1>NUL\n\nTo begin to understand what the command does, please open a Command Prompt window, type for /?, press the ENTER key, and read the information presented. You should do the same using If /? and Copy /? too.\nThe first part, For /D %G In (\"FilePath\\*\") will return as %G directories located in FilePath. (Each of those will be your dynamic/unknown directory names).\nThe next part uses another loop to test each of those unknown directories, with your known directory names appended to it. The results from that loop, returned as %H, are then checked for the directory attribute, and if true, the copy command is performed using it.\nPlease note, that if there are more than one dynamic directory names containing a subdirectory named gh, your .zip files will be copied to each of them.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29053,"cells":{"text":{"kind":"string","value":"Q:\n\nEasy way to rename a project in android\n\nI have downloaded an Android project. To avoid name conflicts I want to move it from\ncom.android.zzz to com.my.zzz.\nAt the moment I'm using Ecplise with the standard android toolkit. Is there a better way to do the rename than to go manually through the files? \n\nA:\n\nThis is basic IDE refactoring.\nRight click the package in Eclipse -> Refactor -> Rename.\nYou will probably want to check all the options that come up in the Rename dialog.\nAnother option would be to right click the class files in Eclipse -> Refactor -> Move.\n\nA:\n\nAs usual, by pressing F2 on package name, you can rename or change the package name, and also by Right-clicking and then select Rename option, you can change or rename the Package name.\nWhen you press F2, it will show you the dialog box as:\nalt text\nIn this dialog, dont forget to check \"Update references\" check box because by making \"check\" to this check-box, it will make changes to all the references of the package which are referred by other components of project.\nHope this helps you,\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29054,"cells":{"text":{"kind":"string","value":"Q:\n\nandroid converting json to string\n\nHi I have this snippet of code :\nprotected void onPostExecute(String response) {\n String res=response.toString();\n // res = res.trim();\n res= res.replaceAll(\"\\\\s+\",\"\"); \n if(!res.equals(\"0\")){\n un.setVisibility(View.GONE);\n ok.setVisibility(View.GONE);\n error.setVisibility(View.GONE);\n key.setVisibility(View.GONE);\n merchant.setVisibility(View.VISIBLE);\n String data = getServerData(res); \n merchant.setText(data);\n }\n else\n error.setText(\"Incorrect Password\");\n\n }\n\n }\n private String getServerData(String returnString) {\n\n InputStream is = null;\n\n String result = \"\";\n\n //convert response to string\n try{\n BufferedReader reader = new BufferedReader(new InputStreamReader(is,\"iso-8859-1\"),8);\n StringBuilder sb = new StringBuilder();\n String line = null;\n while ((line = reader.readLine()) != null) {\n sb.append(line + \"\\n\");\n }\n is.close();\n result=sb.toString();\n }catch(Exception e){\n Log.e(\"log_tag\", \"Error converting result \"+e.toString());\n }\n //parse json data\n try{\n JSONArray jArray = new JSONArray(result);\n for(int i=0;i 0){\n while($result=mysql_fetch_assoc($number)){\n $output[]=$result;\n print(json_encode($result));\n }\n}\nelse{\n echo 0;\n}\n\nBasically on the android emulator screen I get the json array:\n{\"merchant_id\":\"1\",\n\"merchant_name\":\n\"ChowRestaurant\"}\n\nI wanted to display on the screen in this way:\n\"1 Chow Resstaurant\"\njust needed some guidance on this\n\nA:\n\nfor that you have to parse Json with library Gson, Jackson etc or you can also parse it manually\nManual way: http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/\nGson: https://sites.google.com/site/gson/gson-user-guide\nJackson: http://wiki.fasterxml.com/JacksonInFiveMinutes\nI will recommended to for with Gson\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29055,"cells":{"text":{"kind":"string","value":"Q:\n\nStruggling to debug java solution to leetcode algorithm\n\nI was trying to solve this problem here: https://leetcode.com/problems/trapping-rain-water/#/description\nAnd my code is providing incorrect answers, but I can't understand why. When I look at it and I run it through my head, I can't figure out what's wrong with it.\nHere is my solution:\n(Please don't provide me with information about a more efficient methodology if possible, I want to try and figure that out on my own).\npublic class Solution {\n public int trap(int[] height) {\n int totalWaterTrapped = 0;\n for (int i = 0; i < height.length; i++){\n if (i == 0){\n continue;\n } else if (i == (height.length - 1)){\n continue;\n } else {\n int tallestLeftwardHeight = height[i];\n for (int x = i; x >= 0; x--){\n if (height[x] > tallestLeftwardHeight){\n tallestLeftwardHeight = x;\n }\n }\n int tallestRightwardHeight = height[i];\n for (int y = i; y < height.length; y++){\n if (height[y] > tallestRightwardHeight){\n tallestRightwardHeight = y;\n }\n }\n\n totalWaterTrapped += (Math.min(tallestLeftwardHeight, tallestRightwardHeight) - height[i]);\n }\n }\n return totalWaterTrapped;\n }\n}\n\nThank you kindly for any help.\n\nA:\n\n if (height[x] > tallestLeftwardHeight){\n tallestLeftwardHeight = x;\n }\n\nshould be \n if (height[x] > tallestLeftwardHeight){\n tallestLeftwardHeight = height[x];\n }\n\nand\n if (height[y] > tallestRightwardHeight){\n tallestRightwardHeight = y;\n }\n\nshould be\n if (height[y] > tallestRightwardHeight){\n tallestRightwardHeight = height[y];\n }\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29056,"cells":{"text":{"kind":"string","value":"Q:\n\nxterminal dosen't pass key-strokes to emacs\n\nI opened emacs using emacs -nw. Now, when I press M-v, it opens the view menu of the terminal, instead of passing the command to emacs. Is there a way to prevent this from happening? (I'm running on linux mint)\n\nA:\n\nAssuming that by M-v you actually mean Alt+M or, in emacspeak, ^M-v, you should be able to send ^M by hitting Esc instead of Alt.\nJust replace Alt with Esc for any ^M- commands you want to run.\nIn the specific case of mate-terminal, you can switch off the shortcuts for the menus:\n\nThen, deselect the \"Enable menu access keys (such as Alt+F to open the File menu)\" option:\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29057,"cells":{"text":{"kind":"string","value":"Q:\n\nShow this inequality with fractional parts.\n\nLet $n \\geq 2$ be an integer and $x_1, x_2, \\cdots, x_n$ positive reals such that $x_1x_2 \\cdots x_n = 1$.\nShow: $$\\{x_1\\} + \\{x_2\\} + \\cdots + \\{x_n\\} < \\frac{2n-1}{2}$$\nNote: $\\{x\\}$ denotes the fractional part of $x$.\nIs $\\dfrac{2n-1}{2}$ optimal?\n\nA:\n\nAssume that $n\\geq2$, $x_1x_2\\cdots x_n=1$, and\n$$\\{x_1\\}+\\{x_2\\}+\\ldots+\\{x_n\\}\\geq n-{1\\over2}\\ .\\tag{1}$$\nPut $\\tau_i:=1-\\{x_i\\}>0$. Then $(1)$ implies $\\sum_i\\tau_i\\leq{1\\over2}$; in particular no $\\tau_i$ is $=1$. We therefore may write $x_i=m_i-\\tau_i$ with $m_i=\\lceil x_i\\rceil\\geq1$. As $\\prod_i x_i=1$ at least one $m_i$ is $\\geq2$. Now\n$$1=\\prod_i x_i=\\prod_i m_i\\cdot\\prod_i\\left(1-{\\tau_i\\over m_i}\\right)\\ .\\tag{2}$$\nWe shall need the following Lemma, which is easily proven using induction: If $n\\geq2$, $x_i>0$ $(1\\leq i\\leq n)$, and $\\sum_i x_i<1$ then\n$$\\prod_{i=1}^n(1-x_i)>1-\\sum_{i=1}^n x_i\\ .$$Since $\\sum_i{\\tau_i\\over m_i}<{1\\over2}$ we then obtain from $(2)$ the contradiction\n$$1\\geq 2\\left(1-\\sum_i{\\tau_i\\over m_i}\\right)>2\\cdot{1\\over2}=1\\ .$$ \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29058,"cells":{"text":{"kind":"string","value":"Q:\n\nAutomated FTP to upload new files to web server?\n\nI'm looking for a FTP client that I can use to upload new files from a local development machine to a remote web-server. I only want to upload the newly edited files though.\nIs there a command line utility that can do this, that I can add into an automated process? Is there a GUI client available that can do this? Would be nice to have it cross-platform too. Any ideas?\n\nA:\n\nThere is a 'backup' program called SyncBack that does this.\nYou can find out more about it here: http://www.2brightsparks.com\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29059,"cells":{"text":{"kind":"string","value":"Q:\n\nIs it acceptable for a Domain Entity to implement an interface?\n\nPlease see the question here: https://stackoverflow.com/questions/2352654/should-domain-entities-be-exposed-as-interfaces-or-as-plain-objects\nThe general consensus is that Domain Models should not contain interfaces. Now see here: https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Member.cs and specifically this code:\npublic Offer AssignOffer(OfferType offerType, IOfferValueCalculator valueCalculator) \n { \n DateTime dateExpiring = offerType.CalculateExpirationDate(); \n int value = valueCalculator.CalculateValue(this, offerType); \n\n var offer = new Offer(this, offerType, dateExpiring, value); \n\n _assignedOffers.Add(offer); \n\n NumberOfActiveOffers++; \n\n return offer; \n } \n\nThe author if this blog writes a lot about DDD.\nNotice that an interface is injected into the method here instead of a concrete type i.e. IOfferValueCalculator implements OfferValueCalculator.\nI am talking from the perspective of a DDD purist. Is it acceptable for domain entities to implement interfaces? If the answer is yes, then in what circumstances would it be acceptable to inject an IOfferCalculator into a Domain Entity: Member?\nOnce again I realise that the DDD approach is not a one size fits all and that an Anemic Domain model is suitable in a lot of cases. I am just trying to improve my knowledge of this specific area.\n\nA:\n\nIOfferValueCalculator is not a domain entity. It is a service. So it is perfectly fine for it to be an interface.\nAnd there is some nuance in the \"Should entities implement interfaces\" question. While it is true that creating interface only for it to be implemented by single entity is useless complexity. There is nothing wrong with multiple entities implementing single interface, as those entities might be interchangeably used in code, that runs same logic on all of entities.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29060,"cells":{"text":{"kind":"string","value":"Q:\n\nCount where two or more columns in a row are over a certain value [basketball, double double, triple double]\n\nI play a basketball game which allows to output its statistics as a database file, so one can calculate statistics from it that are not implemented in the game. So far I've had no problem caluclating the statistics I wanted, but now I've run into a problem: counting the number of double doubles and/or triple doubles a player made over the season from his game statistics.\nThe definition of a double double and a triple double is as follows:\nDouble-double:\n\nA double-double is defined as a performance in which a player accumulates a double-digit number total in two of five statistical categories—points, rebounds, assists, steals, and blocked shots—in a game.\n\nTriple-double:\n\nA triple-double is defined as a performance in which a player accumulates a double digit number total in three of five statistical categories—points, rebounds, assists, steals, and blocked shots—in a game.\n\nQuadruple-double (added for clarification)\n\nA quadruple-double is defined as a performance in which a player accumulates a double digit number total in four of five statistical categories—points, rebounds, assists, steals, and blocked shots—in a game.\n\nThe \"PlayerGameStats\" table stores statistics for each game a player plays and looks as follows:\nCREATE TABLE PlayerGameStats AS SELECT * FROM ( VALUES\n ( 1, 1, 1, 'Nuggets', 'Cavaliers', 6, 8, 2, 2, 0 ),\n ( 2, 1, 2, 'Nuggets', 'Clippers', 15, 7, 0, 1, 3 ),\n ( 3, 1, 6, 'Nuggets', 'Trailblazers', 11, 11, 1, 2, 1 ),\n ( 4, 1, 10, 'Nuggets', 'Mavericks', 8, 10, 2, 2, 12 ),\n ( 5, 1, 11, 'Nuggets', 'Knicks', 23, 12, 1, 0, 0 ),\n ( 6, 1, 12, 'Nuggets', 'Jazz', 8, 8, 11, 1, 0 ),\n ( 7, 1, 13, 'Nuggets', 'Suns', 7, 11, 2, 2, 1 ),\n ( 8, 1, 14, 'Nuggets', 'Kings', 10, 15, 0, 3, 1 ),\n ( 9, 1, 15, 'Nuggets', 'Kings', 9, 7, 5, 0, 4 ),\n (10, 1, 17, 'Nuggets', 'Thunder', 13, 10, 10, 1, 0 )\n) AS t(id,player_id,seasonday,team,opponent,points,rebounds,assists,steals,blocks);\n\nThe output I want to achieve looks like this:\n| player_id | team | doubleDoubles | tripleDoubles |\n|-----------|---------|---------------|---------------|\n| 1 | Nuggets | 4 | 1 |\nThe only solution I found so far is so awful it makes me puke ... ;o) ... It looks like this:\nSELECT \n player_id,\n team,\n SUM(CASE WHEN(points >= 10 AND rebounds >= 10) OR\n (points >= 10 AND assists >= 10) OR\n (points >= 10 AND steals >= 10) \n THEN 1 \n ELSE 0 \n END) AS doubleDoubles\nFROM PlayerGameStats\nGROUP BY player_id\n... and now you're probably also puking (or laughing hard) after reading this. I didn't even write out everything that would be needed to get all double double combinations, and omitted the case statement for the triple doubles because it's even more ridiculous.\nIs there a better way to do this? Either with the table structure I have or with a new table structure (I could write a script to convert the table).\nI can use MySQL 5.5 or PostgreSQL 9.2.\nHere is a link to SqlFiddle with example data and my awful solution I posted above: http://sqlfiddle.com/#!2/af6101/3\nNote that I'm not really interested in quadruple-doubles (see above) since they don't occur in the game I play as far as I know, but it would be a plus if the query is easily expandable without much rewrite to account for quadruple-doubles.\n\nA:\n\nDon't know if this is the best way. I first did a select to find out if a stat is double digit and assign it a 1 if it is. Summed all those up to find out total number of double digits per game. From there just sum up all the doubles and triples. Seems to work \nselect a.player_id, \na.team, \nsum(case when a.doubles = 2 then 1 else 0 end) as doubleDoubles, \nsum(case when a.doubles = 3 then 1 else 0 end) as tripleDoubles\nfrom\n(select *, \n(case when points > 9 then 1 else 0 end) +\n(case when rebounds > 9 then 1 else 0 end) +\n(case when assists > 9 then 1 else 0 end) +\n(case when steals > 9 then 1 else 0 end) +\n(case when blocks > 9 then 1 else 0 end) as Doubles\nfrom PlayerGameStats) a\ngroup by a.player_id, a.team\n\nA:\n\nTry this out (worked for me on MySQL 5.5):\nSELECT \n player_id,\n team,\n SUM(\n ( (points >= 10)\n + (rebounds >= 10)\n + (assists >= 10)\n + (steals >= 10)\n + (blocks >= 10) \n ) = 2\n ) double_doubles,\n SUM(\n ( (points >= 10)\n + (rebounds >= 10)\n + (assists >= 10)\n + (steals >= 10)\n + (blocks >= 10) \n ) = 3\n ) triple_doubles\nFROM PlayerGameStats\nGROUP BY player_id, team\n\nOr even shorter, by blatanly ripping off JChao's code from his answer, but taking out the unneeded CASE statements since boolean expr evaluates to {1,0} when {True,False}:\nselect a.player_id, \na.team, \nsum(a.doubles = 2) as doubleDoubles, \nsum(a.doubles = 3) as tripleDoubles\nfrom\n(select *, \n(points > 9) +\n(rebounds > 9) +\n(assists > 9) +\n(steals > 9) +\n(blocks > 9) as Doubles\nfrom PlayerGameStats) a\ngroup by a.player_id, a.team\n\nBased on the comments that the above code won't run in PostgreSQL since doesn't like to do boolean + boolean. I still don't like CASE. Here's a way out on PostgreSQL (9.3), by casting to int:\nselect a.player_id, \na.team, \nsum((a.doubles = 2)::int) as doubleDoubles, \nsum((a.doubles = 3)::int) as tripleDoubles\nfrom\n(select *, \n(points > 9)::int +\n(rebounds > 9)::int +\n(assists > 9)::int +\n(steals > 9)::int +\n(blocks > 9)::int as Doubles\nfrom PlayerGameStats) a\ngroup by a.player_id, a.team\n\nA:\n\nHere's another take on the problem.\nThe way I think of it, you're essentially working with pivoted data for the current problem, so the first thing to do is unpivot it. Unfortunately PostgreSQL doesn't provide nice tools to do that, so without getting into dynamic SQL generation in PL/PgSQL, we can at least do:\nSELECT player_id, seasonday, 'points' AS scoretype, points AS score FROM playergamestats\nUNION ALL\nSELECT player_id, seasonday, 'rebounds' AS scoretype, rebounds FROM playergamestats\nUNION ALL\nSELECT player_id, seasonday, 'assists' AS scoretype, assists FROM playergamestats\nUNION ALL\nSELECT player_id, seasonday, 'steals' AS scoretype, steals FROM playergamestats\nUNION ALL\nSELECT player_id, seasonday, 'blocks' AS scoretype, blocks FROM playergamestats\n\nThis puts the data in a more malleable form, though it's sure not pretty. Here I assume that (player_id, seasonday) is sufficient to uniquely identify players, i.e. the player ID is unique across teams. If it isn't, you'll need to include enough other info to provide a unique key.\nWith that unpivoted data it's now possible to filter and aggregate it in useful ways, like:\nSELECT\n player_id,\n count(CASE WHEN doubles = 2 THEN 1 END) AS doubledoubles,\n count(CASE WHEN doubles = 3 THEN 1 END) AS tripledoubles\nFROM (\n SELECT\n player_id, seasonday, count(*) AS doubles\n FROM\n (\n SELECT player_id, seasonday, 'points' AS scoretype, points AS score FROM playergamestats\n UNION ALL\n SELECT player_id, seasonday, 'rebounds' AS scoretype, rebounds FROM playergamestats\n UNION ALL\n SELECT player_id, seasonday, 'assists' AS scoretype, assists FROM playergamestats\n UNION ALL\n SELECT player_id, seasonday, 'steals' AS scoretype, steals FROM playergamestats\n UNION ALL\n SELECT player_id, seasonday, 'blocks' AS scoretype, blocks FROM playergamestats\n ) stats\n WHERE score >= 10\n GROUP BY player_id, seasonday\n) doublestats\nGROUP BY player_id;\n\nThis is far from pretty, and it's probably not that fast. It's maintainable though, requiring minimal changes to handle new types of stats, new columns, etc.\nSo it's more of a \"hey, did you think of\" than a serious suggestion. The goal was to model the SQL to correspond to the problem statement as directly as possible, rather than to make it fast.\n\nThis was made vastly easier by your use of sane multi-valued inserts and ANSI quoting in your MySQL-oriented SQL. Thankyou; it's nice not to see backticks for once. All I had to change was the synthetic key generation.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29061,"cells":{"text":{"kind":"string","value":"Q:\n\nPorting from Python to Java: looking for a fast implementation of an array search operation\n\nI am porting some Python code into Java and need to find an efficient implementation of the following Python operation:\nsum([x in lstLong for x in lstShort])\n\nwhere lstLong and lstShort are string lists. So here I am counting how many elements from lstShort appear in lstLong. In the Java implementation, both of these are String[]. What's the fastest way of counting this sum?\nA more general question is whether there are any generic guidelines for writing \"fast equivalents\" in Java of Python list comprehension operations like the one above. I am mostly interested in arrays/lists of Strings, in case it makes the answer easier.\n\nA:\n\nIf you convert both to ArrayList, you can use\nlstLong.retainAll(lstShort).size();\n\nYou can do the conversion with\nnew ArrayList(Arrays.asList(var));\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29062,"cells":{"text":{"kind":"string","value":"Q:\n\nDetect application refocus event\n\nI need to know each time the user is starting to use the application.\nCase 1 (OK) : The app is not started.\nThe user starts the application from scratch.\nI add a listener on the app's bootstrap, and I am aware when it starts.\nCase 2 (TODO) : The app has been started but it's not active anymore\nThe user reload the application from the taskbar.\nI want to know when the application comes from the taskbar to the foreground (like a alt+tab). \nThis is tricky to catch, because the app is still running and I don't know which event to listen to. In fact, I don't even know how to name this behaviour.\n\nA:\n\nThere is an event for app resume and pause in Cordova so you don't need to edit the Cordova class files. Below is working code I am currently using in an app for iOS/Android.\nwindow.onload = function() { \n //only fired once when app is opened\n document.addEventListener(\"deviceready\", init, false);\n //re-open app when brought to foreground\n document.addEventListener(\"resume\", init, false);\n //trigger when app is sent to background\n document.addEventListener(\"pause\", onPause, false);\n\n}\n\nfunction init() {\n console.log('device ready or resume fired');\n}\n\nA:\n\nAn ios-app developper accepted to help me. His answer suits me very well, as it seem clean et reusable. So I will produce it here : \nThe \"app come to foreground\" event can be catched through the applicationWillEnterForeground event.\nPhonegap/Cordova allows to call javascript functions through the Cordova classes. The webView object has a dedicated method to launch js scripts.\nSo I opened the file Projet/Classes/Cordova/AppDelegate.m :\n- (void)applicationWillEnterForeground:(UIApplication *)application {\n NSLog(@\"applicationWillEnterForeground: %@\", self.viewController.webView);\n [self.viewController.webView stringByEvaluatingJavaScriptFromString:@\"notifyForegroundEvent();\"];\n\n}\n\nAnd I added the notifyForegroundEvent() method somewhere in the root of my js files :\nvar notifyForegroundEvent = function() {\n console.log('notifyForegroundEvent()');\n // Do something here\n}\n\nEt voilà\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29063,"cells":{"text":{"kind":"string","value":"Q:\n\nWork done by Internal Forces\n\nWhy is it that internal forces do not change the potential energy of the system?\nAssume that a man stands on earth with a dumbell. If the dumbell is the system, when it is raised a height h, the work done by the man is +mgh and the work done by the earth is -mgh.\nIf the system is the earth and the dumbell, then the man will increase the potential energy of the system by +mgh. Where does the gravitational force of the earth on the dumbell go?\n\nA:\n\nInternal forces are the only contributors to potential energy.\nPotential energy is the energy associated with the configuration (relative positions) of a collection objects. The potential energy of a single point particle is not defined. As the configuration of the system changes, its potential energy changes according to the definition $\\Delta{\\mathrm{(P.E.)}} = -W_\\mathrm{internal}$ where $W_\\mathrm{internal}$ is the work done internally, that is, by the various internal forces against the internal components of the system.\nIn order to define potential energy, you need to have internal components applying forces to one another, and the components need to be able to move relative to one another. You need at least two objects.\nConsider the system consisting of only the dumbbell. You have implicitly modeled the dumbbell as a point particle. That is, the only attributes of interest to your analysis are its position and its mass. The internal structure, which would be of interest in other questions, say, concerning temperature, is ignored. You have applied two external forces, gravity, and the contact force of your hand. Not only is there no change in potential energy, there is no potential energy at all. Potential energy does not exist in a system consisting of, or modeled by, a single point particle. I'm not saying that the P.E. is zero. I'm saying that it is not defined.\nConsider the system consisting of the dumbbell and the earth. Now I have two objects modeled as point particles, one external force: the force of your hand, and one internal force: the mutual gravitational attraction between the Earth and the dumbbell. The internal work done in lifting the dumbbell (that is, increasing the distance between them) is $W_\\mathrm{internal} = -mgh$. The minus sign comes from the fact that the displacement is in the direction opposite to the direction of the force. (Gravity down, displacement up.) so the change in potential energy of the system is $$\\Delta\\mathrm{(P.E.)} = -W_\\mathrm{internal} = -(-mgh) = mgh$$ The external force of your hand on the dumbbell plays no role at all.\nOne of the roots of your misunderstanding is the unfortunate choice made by almost all introductory textbooks in introducing the subject of potential energy by looking at raising and lowering objects in a static gravitational field (at the surface of the earth). I know of a particular textbook that had a wonderful and correct description of potential energy. Until the next edition came out, when that description disappeared, and the conventional description appeared in its place.\naddendum\nThere's something that needs clarification. In what I've written above, I modeled all of the objects as point particles having no internal structure. That includes my model of the composite system: I took that as a point particle also, this one located at the center of mass of the composite system. External forces can accelerate the system, but that's all it can do. $F_\\mathrm{net} = ma_\\mathrm{cm}$, and the kinetic energy of the system increases in accordance with the usual analysis: $\\Delta KE = \\vec{F_\\mathrm{net}}\\cdot \\Delta \\vec{x}_\\mathrm{cm}$\nIf I take a better model for the composite system I might find that it is deformable. Suppose the system is a rubber ball. Now when I apply the external force, the object will deform. The center of mass still obeys $F_\\mathrm{net} = ma_\\mathrm{cm}$ and we still have $\\Delta KE = \\vec{F_\\mathrm{net}}\\cdot \\Delta \\vec{x}_\\mathrm{cm}$. But notice that since the object is deforming, the displacement of the center of mass is not the same as the displacement of the point of application of the force. The kinetic energy of the system increases as before: $\\Delta KE = \\vec{F_\\mathrm{net}}\\cdot \\Delta \\vec{x}_\\mathrm{cm}$, but the point of application of the force moves farther than $\\Delta \\vec{x}_\\mathrm{cm}$. More work was done than was needed to accelerate the system. Some of this extra work ends up as internal potential energy. Some as internal kinetic energy, some as thermal energy $\\ldots$. None of these energies exist in the point particle model of the system, but in a real system they do exist. In that sense, external forces can change the potential energy of a system.\nBut even in that more realistic analysis, the change in the potential energy of the system is due to the internal forces, and internal work. There is an external influence that causes deformation, but the change in potential energy is calculated from internal work.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29064,"cells":{"text":{"kind":"string","value":"Q:\n\nDjango Dynamic menu design question\n\nI want to create dynamic menus according to user permissions. As was already discussed here and by the the documentation itself, I know that I can achieve this in the templates using the following snippet:\n{% if perms.polls.can_vote %}\n
  • \n Vote\n
  • \n{% endif %}\n\nBut the problem is that for security reasons I want to limit the access to the views too. The snippet that I found in the documentation is the following:\nfrom django.contrib.auth.decorators import permission_required\n\ndef my_view(request):\n # ...\nmy_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)\n\nIsn't this against DRY principle? Isn't there a way to define only in one place what is the permission needed for each url? Perhaps in urls.py?\n\nA:\n\nEDIT: (See end of post for the original text of the answer with the initial, simple idea.)\nAfter being kindly stricken with a cluebat (see the OP's comment below), I find I can see more to the problem than before. Sorry it took so long. Anyway:\nWould this kind of template be alright for you?\n{% for mi in dyn_menu_items %}\n {% if mi.authorised %}\n {{ mi.title }}\n {% endif %}\n{% endfor %}\n\nTo make this work on the Python side, you could use RequestContext in your views with a custom context processor setting the dyn_menu_items variable appropriately. In case some background information is required, the Advanced Templates chapter of the Django Book introduces RequestContext, shows how to use it with render_to_response (kinda important :-)) etc.\nAlso, I guess at this point it could be useful to put the view functions responsible for the locked-up sections of your site in a list somewhere:\n_dyn_menu_items = [(url1, view1, title1, perm1), ...]\n\nThen you could map a couple of functions, say prepare_pattern and prepare_menu_item across that list, having it work roughly like so:\ndef prepare_pattern(menu_item):\n url1, view, title, perm = menu_item\n pattern = PREPARE_URLCONF_ENTRY_SOMEHOW(...) # fill in as appropriate\n return pattern\n\ndef prepare_menu_item(menu_item):\n url, view, title, perm = menu_item\n mi = PREPARE_THE_BIT_FOR_REQUESTCONTEXT(...) # as above\n return mi\n\nThese could be combined into a single function, of course, but not everybody would find the result more readable... Anyway, the output of map(prepare_menu_item, _dyn_menu_items) would need to be a dictionary to be passed to your views by a helpful context processor (the figuring out of which, it being the slightly tedious bit here, I'll leave to you ;-)), whereas the output of map(prepare_pattern, _dyn_menu_items), let's call it dyn_menu_patterns, would be used in patterns('', *dyn_menu_patterns), to be used in your URLconf.\nI hope this makes sense and is of some help...\nTHE PRE-EDIT ANSWER:\nBased on your short description, I'm not sure what solution would be best for you... But if the permission_required snippet does what you want, just not DRY-ly enough, how about rolling your own wrapper:\ndef ask_to_login(perm, view):\n return permission_required(perm, login_url='/loginpage/', view)\n\nYou could put this anywhere, including in URLconf. Then you could replace all mentions of '/loginpage/' with reference to a variable defined towards the top of your URLs file and you'd have yourself a solution with a single mention of the actual login URL, for one-place-only update of said URL should you have to move it around. :-)\nOf course the views would still need to be wrapped explicitly; if that bothers you, you could try to make ask_to_login into a decorator for easy wrapping at the definition site. (But perhaps it's really best not to do it, lest you force yourself to dig your views from under the decorator in case you need them undecorated at some point in the future.)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29065,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to pop Nth item in the stack [Befunge-93]\n\nIf you have the befunge program 321&,how would you access the first item (3) without throwing out the second two items?\nThe instruction \\ allows one to switch the first two items, but that doesn't get me any closer to the last one... \nThe current method I'm using is to use the p command to write the entire stack to the program memory in order to get to the last item. For example, \n32110p20p.20g10g@\n\nHowever, I feel that this isn't as elegant as it could be... There's no technique to pop the first item on the stack as N, pop the Nth item from the stack and push it to the top?\n(No is a perfectly acceptable answer)\n\nA:\n\nNot really.\nYour code could be shortened to\n32110p\\.10g@\n\nBut if you wanted a more general result, something like the following might work. Below, I am using Befunge as it was meant to be used (at least in my opinion): as a functional programming language with each function getting its own set of rows and columns. Pointers are created using directionals and storing 1's and 0's determine where the function was called. One thing I would point out though is that the stack is not meant for storage in nearly any language. Just write the stack to storage. Note that 987 overflows off a stack of length 10.\nv >>>>>>>>>>>12p:10p11pv\n 1 0 v<<<<<<<<<<<<<<<<<<\n v >210gp10g1-10p^\n >10g|\n >14p010pv\n v<<<<<<<<<<<<<<<<<<<<<<<<\n v >210g1+g10g1+10p^\n >10g11g-|\n v g21g41<\n v _ v\n>98765432102^>. 2^>.@\n\nThe above code writes up to and including the n-1th item on the stack to 'memory', writes the nth item somewhere else, reads the 'memory', then pushes the nth item onto the stack.\nThe function is called twice by the bottom line of this program.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29066,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to add more cowbell?\n\nRemember that Christopher Walken skit on Saturday Night live where he told the band “it needs more cowbell” https://en.wikipedia.org/wiki/More_cowbell ? This site automated it http://www.morecowbell.dj/ using echonest http://developer.echonest.com/ . That’s all fine. Question is: “What is the actual algorithm behind the beat detection and cowbell insertion?”\n\nA:\n\nThe beat and onset detection algorithms used at the Echo Nest are probably variants/improvements of the techniques developed by Tristan Jehan in his Ph.D. This is not the only approach, and I would recommend you to try first:\n\nGetting an onset detection function using spectral flux or complex amplitude.\nUsing this algorithm to detect beats (you can improve it using the \"comb template\" method described here to score tempo candidates - I believe this combination of Ellis' dynamic programming approach with a more sophisticated candidate scoring function is what is used in Sonic Visualizer's default beat detection vamp plug-in).\n\nAs for adding the cowbell, I think there are a bunch of heuristics that could work. First of all, you can use the breaking down of the song into sections (as provided by the EN analyzer or by an algorithm like this), and process each section individually - to have changes in the cowbell pattern coincide with changes into chorus/verse. For each section, you can align the detected onsets on a grid of 16 or 32 sixteenth note to get a discrete representation of the onsets (a bit similar to what you would see on a drum machine or sequencer); and then average these patterns to get a summary of the rhythmic structure of the section. If the section is too chaotic - use a cowbell hit on each 4th or 8th note... Possible refinements: tune the cowbell so that it matches the key of the song, stop it in the sections that have a very low loudness...\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29067,"cells":{"text":{"kind":"string","value":"Q:\n\nanimating border to transparent with keyframes\n\nI'm trying to make simple animation of a circle which border goes from red to transparent color. How I'm trying to do it is to set initial color as red and then animate it to transparent with keyframes like so: \n\n.pulse{\r\n margin: 20px;\r\n width:100px;\r\n height: 100px;\r\n background-color: red;\r\n border-radius: 100px;\r\n animation-name: pulse;\r\n animation-duration: 1s;\r\n animation-iteration-count: infinite;\r\n animation-direction: alternate;\r\n animation-timing-function: ease;\r\n}\r\n\r\n@keyframes pulse{\r\n 0%{border:solid 1px rgba(255, 0, 0, 1)}\r\n 100%{border:solid 1px rgba(255, 0, 0, 0)}\r\n}\n
    \r\n
    \r\n
    \n\nSeemingly nothing happens but after fiddling with it a bit I'm aware that the animation actually works, but the transparent animation is shown on top of existing red border and effect is that it looks like nothing is happening. \nWhat i'm trying to achive is to have the border go from red to transparent, making it look like it's pulsating but without the circle changing it's size. \n\nA:\n\nYou won't see anything because you background-color is the same color as the border color. Also your border definition inside your animation was wrong, the width must come before the border style:\nSo for example it's 1px solid color instead of solid 1px rgba(255,0,0,1).\n\n.pulse {\r\n animation: pulse 1s ease infinite alternate;\r\n background-color: #ddd;\r\n border-radius: 100px;\r\n height: 100px;\r\n margin: 20px;\r\n width: 100px;\r\n}\r\n\r\n@keyframes pulse {\r\n 0% {\r\n border: 1px solid rgba(255, 0, 0, 1)\r\n }\r\n 100% {\r\n border: 1px solid rgba(255, 0, 0, 0)\r\n }\r\n}\n
    \r\n
    \r\n
    \n\nBut i think you want to achieve a pulsating effect, therefore i would recommend you to use transform: scale() to create the desired effect.\n\n@keyframes pulse{\r\n from { transform: scale(1) }\r\n to { transform: scale(.75) }\r\n}\r\n\r\n.pulse{\r\n margin: 20px;\r\n width:100px;\r\n height: 100px;\r\n border-radius: 100px;\r\n background-color: red;\r\n animation: pulse 1s ease infinite alternate;\r\n}\n
    \r\n
    \r\n
    \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29068,"cells":{"text":{"kind":"string","value":"Q:\n\nC# Item is null for very short period of time?\n\nI have a MessageQueue class with a private List property that acts as the queue. There's only one way to add to the queue (through an Add method) and one way to take from the queue (through a Next method). I have a thread running without a delay constantly checking the queue. Occasionally, a null item gets into the queue.\nI put a breakpoint in the Add method if the item being added is null, but the breakpoint is never hit.\nI put a breakpoint in the Next method if the item being returned is null, which is getting hit.\nFurthermore, the breakpoint is set after it fetches the item, but before the queue is adjusted. What's strange is, while the returned item is null, the item that was just fetched is not null! Here is my queue-\npublic class MessageQueue\n{\n private List queue = new List();\n\n public void Add(byte[] payload)\n {\n if (payload == null)\n {\n Console.WriteLine(\"thats why\");\n }\n\n queue.Add(payload);\n }\n\n public byte[] Next()\n {\n byte[] hand = queue.First();\n\n if(hand == null)\n {\n Console.WriteLine(\"asdf\");\n }\n\n queue = queue.Skip(1).ToList();\n\n return hand;\n }\n\n public bool HasMessages\n {\n get\n {\n return queue.Count() > 0;\n }\n }\n}\n\nHere is what's in the queue-\n\nAnd here is what's in the hand-\n\nBecause I am using First on the queue, an error would be thrown if there wasn't an item.\nIn fact, just to be sure that wasn't somehow related I put a try-catch around the First call- which is never hit.\nHow is hand null when null is never added to the queue, and the first item in the queue is not null?\n\nA:\n\nList<> is not thread safe \nIf you are accessing it from different thread you can see it in a broken state.\nUse any synchronization technique or anything from thread-safe collections\nAs mentioned above: \"ConcurrentQueue is most likely what you need to use\"\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29069,"cells":{"text":{"kind":"string","value":"Q:\n\nTextfield in alertview not working in ios7?\n\nI have an application in which I'm using a specific design for a reason. I put a text field in an alert view above an otherbutton with a background image. Everything is working fine in ios 6 version.\nUIAlertView *av=[[UIAlertView alloc] initWithTitle:@\"fdhdj\" message:@\" hdfjkhfjkhdk\" delegate:self cancelButtonTitle:@\"ok\" otherButtonTitles:@\" \",@\"cancel\",nil];\n av.alertViewStyle = UIAlertViewStylePlainTextInput;\n namefield = [[UITextField alloc] initWithFrame:CGRectMake(10.0,43.0, 264.0, 44.0)];\n namefield.borderStyle = UITextBorderStyleNone;\n namefield.background = [UIImage imageNamed:@\"text_field_default.png\"];\n namefield.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;\n namefield.textAlignment = UITextAlignmentCenter;\n //[namefield setBackgroundColor:[UIColor whiteColor]];\n [av addSubview:namefield];\n [namefield release];\n av.tag=12;\n av.delegate=self; \n [av show];\n\n [av release];\n\nBut now in ios 7, I heard you can't easily alter the view hierarchy of a UIAlertView.\nOne alternative for this case is to set \n\nalert.alertViewStyle = UIAlertViewStylePlainTextInput\n\nBut can we add that text field in wherever we want? As in my case above the first otherbutton.can anybody help me?\n\nA:\n\n UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@\"Enter Student Name\" message:@\"\" delegate:self cancelButtonTitle:@\"Cancel\" otherButtonTitles:@\"Save\",nil];\n\n [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];\n [alertView show];\n\ni used to do like this ,and its working very fine \n\nA:\n\nThe simple answer to your question is NO, you can't change anything in this testField for the UIAlertViewStylePlainTextInput and you shouldn't.\nThis is from Apple:\n\nThe UIAlertView class is intended to be used as-is and does not\n support subclassing. The view hierarchy for this class is private and\n must not be modified.\n\nAnd unfortunately what you heard I heard you can't easily alter the view hierarchy of a UIAlertView is wrong, you cannot alter the view hierarchy of a UIAlertView in iOS7 at all.\nThere are a good alternative on the web, you can check in cocoacontrols.com\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29070,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to keep the implicitly declared aggregate initialization constructor?\n\nSuppose I have a class like this:\nstruct X {\n char buf[10];\n};\nX x{\"abc\"};\n\nThis compiles. However, if I add user defined constructors to the class, this implicitly declared aggregate initialization constructor will be deleted:\nstruct X {\n char buf[10];\n X(int, int) {}\n};\nX x{\"abc\"}; // compile error\n\nHow can I declare that I want default aggregate initialization constructor, just like that for default constructor X()=default? Thanks.\n\nA:\n\nThere is no \"default aggregate initialization constructor\".\nAggregate initialization only happens on aggregates. And aggregates are types that, among other things, don't have (user-provided) constructors. What you're asking for is logically impossible.\nThe correct means of doing what you want is to make a factory function to construct your type in your special way. That way, the type can remain an aggregate, but there's a short-hand way for initializing it the way you want.\nYou give a type a constructor when you want to force users to call a constructor to construct it. When you don't, you just use factory functions.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29071,"cells":{"text":{"kind":"string","value":"Q:\n\nImprove performance of MS Excel writing\n\nI am facing performance issues while reading/writing data from/to MS-Excel cells. I am using MS Excel 11.0 object library for automation with VB.NET.\nCurrently it takes too much time to read and write from/to Excel files. (10 mins to read 1000 rows :( ). It seems the cell-by-cell reading and writing approach is not that effiecient. Is there any way to read/write data using bulk operation?\n\nA:\n\nRather than reading cell by cell you could read a whole range and save it into a 2D arrray. You can then access the 2D array as you would access a cell in excel.\nI'm not well versed in VB.NET for excel objects but if you understand C# then give this link a quick read and try to implement it.\nhttp://dotnetperls.com/excel-interop \nRead the \"Getting workbook data\" section\n\nA:\n\nGreat!!! \nI used the 2D array approach and achieved the enormous performance boost!!.\nPreviously I used the cell-by-cell aprroach as shown below,\nDim cell As Excel.Range = Nothing\ncell = sheet.Cells(rowIndex, colIndex)\ncell.Value = \"Some value\"\n\nI used to iterate over a range of cells and used to copy the value in each cell.\nHere every sheet.Cells and cell.Value is an interop call and for every call it gives call to the Excel.exe, which costs more time.\nIn 2D approach I have filled the data, which is to be copied in Excel cells, in 2D array and then assigned the 2D array to the value of the selected reange of cells. It is as shown below,\nDim darray(recordCount - 1, noOfCol - 1) As String\n//Fill the data in darray\n//startPosRange = Get the range of cell from where to start writing data\nstartPosRange = startPosRange.Resize(recordCount, noOfCol)\nstartPosRange.Value = darray\n\nAfter these modifications, I gathered the performance data for both the approaches and results are surprisingly great!!. The later approach is 25 times as fast as previous one.\nSimilarly, I have used the 2D array approach for reading data from cells and seen the similar performance boost. Code samples are as shown below.\nCell-by-cell approach,\nDim usedRange As Excel.Range = sheet.UsedRange\nFor Each row As Excel.Range In usedRange.Rows()\nFor Each cellData As Excel.Range In row.Cells\n //Gather cellData.Value in some container.\nNext\n\n2D array approach,\nDim usedRange As Excel.Range = sheet.UsedRange\n//Here the array index starts from 1. why???\nDim darray(,) As Object = CType(usedRange.Value, Object(,))\n\nDim rows As Integer = darray.GetUpperBound(0)\nDim cols As Integer = darray.GetUpperBound(1)\nFor i As Integer = 1 To rows \n For j As Integer = 1 To cols\n Dim str As String\n If darray(i, j) Is Nothing Then\n str = \"\"\n Else\n str = darray(i, j).ToString\n End If\n //Use value of str\n Next\nNext\n\nPlease refer,\nhttp://support.microsoft.com/kb/306023 ,\nhttp://dotnetperls.com/excel-interop (thanks ChickSentMeHighE for the link)\nEnjoy the performance!!!\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29072,"cells":{"text":{"kind":"string","value":"Q:\n\njq- reference current position in loop\n\nI have a log file called log.json that's formatted like this: \n{\"msg\": \"Service starting up!\"} \n{\"msg\": \"Running a job!\"}\n{\"msg\": \"Error detected!\"}\n\nAnd another file called messages.json, which looks like this:\n{\"msg\": \"Service starting up!\", \"out\": \"The service has started\"}\n{\"msg\": \"Error detected!\", \"out\": \"Uh oh, there was an error!\"}\n{\"msg\": \"Service stopped\", \"out\": \"The service has stopped\"}\n\nI'm trying to write a function using jq that reads in both files, and whenever it finds a msg in log.json that matches a msg in messages.json, print the value of out in the corresponding line in messages.json. So, in this case, I'm hoping to get this as output:\n\"The service has started\"\n\"Uh oh, there was an error!\"\n\nThe closest that I've been able to get so far is the following:\njq --argfile a log.json --argfile b messages.json -n 'if ($a[].msg == $b[].msg) then $b[].out else empty end'\n\nThis successfully performs all of the comparisons that I'm hoping to make. However, rather than printing the specific out that I'm looking for, it instead prints every out whenever the if statement returns true (which makes sense. $b[].out was never redefined, and asks for each of them). So, this statement outputs:\n\"The service has started\"\n\"Uh oh, there was an error!\"\n\"The service has stopped\"\n\"The service has started\"\n\"Uh oh, there was an error!\"\n\"The service has stopped\"\n\nSo at this point, I need some way to ask for $b[current_index].out, and just print that. Is there a way for me to do this (or an entirely seperate approach that I can use)?\n\nA:\n\nmessages.json effectively defines a dictionary, so let's begin by creating a JSON dictionary which we can lookup easily. This can be done conveniently using INDEX/2 which (in case your jq does not have it) is defined as follows:\ndef INDEX(stream; idx_expr):\n reduce stream as $row ({};\n .[$row|idx_expr|\n if type != \"string\" then tojson\n else .\n end] |= $row);\n\nA first-cut solution is now straightforward:\nINDEX($messages[]; .msg) as $dict\n| inputs\n| $dict[.msg]\n| .out \n\nAssuming this is in program.jq, an appropriate invocation would be as follows (note especially the -n option):\njq -n --slurpfile messages messages.json -f program.jq log.json\n\nThe above will print null if the .msg in the log file is not in the dictionary. To filter out these nulls, you could (for example) add select(.) to the pipeline.\nAnother possibility would be to use the original .msg, as in this variation:\nINDEX($messages[]; .msg) as $dict\n| inputs\n| . as $in\n| $dict[.msg]\n| .out // $in.msg\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29073,"cells":{"text":{"kind":"string","value":"Q:\n\nJava dice roll code for review\n\nI have the below tiny program done in Java using Eclipse. \nIt just shows two dice being rolled and what number (eyes?) they show.\nCan I do it without the use of casting in the Math.random lines? Or is there a completely different (and better) way of doing this?\nI am completely new at programming, so please bear with me (also English isn't my first language.)\npublic class Meyer {\n\n public static void main(String[] args) {\n String [] die = {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"};\n\n int roll = die.length;\n\n int random1 = (int) (Math.random() * roll);\n int random2 = (int) (Math.random() * roll);\n\n String rollDice = die[random1] + \" \" + die[random2];\n\n System.out.println(\"The roll is: \" + rollDice);\n }\n}\n\nA:\n\nI would personally prefer using the Random class, and its Random#nextInt(int) method. \nNot only I find it more elegant (and avoids casting), I also find it extremely useful to be able to use the same Random object that I created and planted its seed (with the constructor Random(long)), since it makes life much easier when trying to reproduce some unexpected behavior later on.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29074,"cells":{"text":{"kind":"string","value":"Q:\n\nPreposition for conversion to another unit\n\nWhich preposition should be used when I want to say a value in a different measure unit? For example, what is a correct preposition in the following sentence?\n\nTwelve miles? I have no idea how far that is. What is it __ kilometres?\n\nA:\n\nIt depends a bit on the verb. Often you use \"in\"\n\nWhat is 12 miles in kilometres?\n(answer: about 19 km)\n\nBut with \"change\" you say \"Please change 12 miles to kilometres\" or \"into kilometres\".\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29075,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to solve the following logarithm?\n\nHow to solve this?? \nThe solution is 1001.\n\nA:\n\nHints: justify using the basic properties of logarithms the following\n$$\\log(x-1)+\\log\\sqrt[3]{x^2-1}=4+\\frac13\\log(x+1)\\iff$$\n$$\\iff\\log\\left(\\frac{(x-1)\\sqrt[3]{(x-1)(x+1)}}{\\sqrt[3]{x+1}}\\right)=4\\iff$$\n$$\\frac43\\log(x-1)=4\\iff\\log(x-1)=3\\iff x-1=10^3\\;\\ldots$$\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29076,"cells":{"text":{"kind":"string","value":"Q:\n\nRe-rendering jQuery function\n\nSo, I have following jquery function:\n jQuery('.button').click(function(e) { \n if(!isMobile) {\n jQuery('.button').featherlight({ \n }); \n } \n })\n\nThis creates an lightbox at the bottom of like below:\nBefore lightbox is opened:\n\n \n \n \n \n\nAfter lightbox is opened:\n\n \n \n \n
    Lightbox content
    \n \n\nProblem is that none of the jQuery function inside of this lightbox works as it was created after the page was loaded.\nHow do I \"re-render\" a js file after the lightbox is created?\nThanks!\nHere is an example:\njQuery('#tags').keyup(function(e){\n console.log(e); \n if(e.which == 188) {\n var tag = ...;\n var data = '';\n tags.push(tag);\n jQuery('.tags ul').append(data);\n jQuery(this).val('');\n } \n });\n\nHere, a tag input will be \"appended\" or added to a div class=\"tags\". However inside of the lightbox, this function is not executed at all.\n\nA:\n\nRe-rendering a JS file is not how javascript is supposed to work.\nWhat I recommend you to do is to run the a function in the afterContent callback.\nAs you can see in the featherlight documentation, there is a plenty of callbacks that can help you with this.\nExample:\n jQuery('.button').click(function(e) { \n if(!isMobile) {\n jQuery('.button').featherlight({\n\n afterContent: function () {\n // Do your code here\n // The lightbox content will be ready\n }\n\n }); \n } \n })\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29077,"cells":{"text":{"kind":"string","value":"Q:\n\nRoot my EVO wihtout USB cord\n\nI want to root my EVO... but my charging port is broken (I've been using an external battery charger to get around this). Anyway to get the files I need to root my EVO onto my EVO without using this cable? I was thinking about going through Box or Dropbox or something like that but I'm not sure how to download these files into a specific folder on my EVO.\nThanks.\n\nA:\n\nYou can always put the files on an SD card and transfer them to your internal storage from there, but as was said in the comments, if something happens during the process and you are unable to boot your phone, the only way to recover from that is to reflash it from the computer, using the usb cable. You can use Titanium Backup to back all of your apps up onto the SD card, and hopefully you keep everything you can backed up through Google, but you still would have an unusable phone if something happened.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29078,"cells":{"text":{"kind":"string","value":"Q:\n\nSliding Current Carousel Item in Bootstrap Modal Slider\n\nI am trying to create a simple lightbox using Bootstrap carousel and Modal. Please take a look at sample file which I have here.\nWhat I would like to do is starting the Modal Carousel as same slide (current slide) of the main carousel. As you can see from the example when I start the Modal it just start from the first item but I need to start from current active slide.\nCan you please let me know how to do this?\n
    \n
    \n
    \n
    \n
    \n \"\"/\n
    \n
    \n \"\"/\n
    \n
    \n \"\"/\n
    \n
    \n \n \n
    \n \n
    \n
    \n \n

    Modal header

    \n
    \n
    \n
    \n
    \n
    \n \"\"/\n
    \n
    \n \"\"/\n
    \n
    \n \"\"/\n
    \n
    \n \n \n
    \n
    \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n\nThansk\n\nA:\n\nThis seems to work.\n$('.bell').on('show', function() {\n var targetSlide = parseInt($('#myCarousel .active').index('#myCarousel .item'));\n $('#myCarousel2').carousel(targetSlide);\n});\n\nThis gets the current index showing on the main carousel.\n$('#myCarousel .active').index('#myCarousel .item')\n\nThis sets the current slide of the modal carousel.\n$('#myCarousel2').carousel(/*Number here*/);\n\nHere is a jsFillde with the above code.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29079,"cells":{"text":{"kind":"string","value":"Q:\n\nFlex 4.5 - unique computer information\n\nI am developing a flex 4.5 web based application and I need to make sure if the client chooses a certain level of security, each user can log only from an authorized computer.\nSo the question is how can I get some unique computer information? Anything like HDD serial number, CPU specifications, motherboard information, even the user that is logged into the Operating System can do.\nSo far the information on the web isn't giving me much hope that this can be achieved, but I had to ask.\nThanks in advance.\n\nA:\n\nThis is not easy using a browser based Flex application, but there are some workarounds. \nThe browser based Flash Player can communicate with an AIR app on the desktop using localconnection. So, you could create an AIR app that utilizes NativeProcess to retrieve your machine specific information. \nYou could also use NativeProcess from a AIR app without using the browser at all.\nA third option would be to install an application server on the client machine and have the browser based app communicate with the server to retrieve the client information.\nI consider most of these options too difficult to be practical, but it depends on how important this feature is to you.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29080,"cells":{"text":{"kind":"string","value":"Q:\n\nandroid - php fetch mysql data by user id\n\nThis my PHP URL for fetching the data from MySQL. I need to make mysqli_fetch_array code saying if filled uid in the app-data table is the same with uid in users table fetch the data from all row in app-data to the uid like every user show his items from app-data table.\n$host = \"\";\n$user = \"\";\n$pwd = \"\";\n$db = \"\"; \n\n$con = mysqli_connect($host, $user, $pwd, $db);\n\nif(mysqli_connect_errno($con)) {\n die(\"Failed to connect to MySQL: \" . mysqli_connect_error());\n} \n\n$sql = \"SELECT * FROM app_data ORDER By id\";\n$result = mysqli_query($con, $sql);\n\n$rows = array();\n\nwhile($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {\n $rows[] = $row; \n}\n\nmysqli_close($con);\n\necho json_encode($rows);\n\nA:\n\nI think this is the correct answer:\n\n LogStream& operator<<( T const& obj )\n {\n if ( myDest != nullptr ) {\n *myDest << obj;\n }\n return *this;\n }\n};\n\nThe LOG(level) macro creats an instance of one, something like:\n#define LOG(level) LogStream( getLogStream( level, __FILE__, __LINE__ ) )\n\nOf course, the getLogStream may insert any information it wants (like a timestamp) at the moment it is called.\nYou might want to add a flush in the destructor of LogStream.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29082,"cells":{"text":{"kind":"string","value":"Q:\n\nExtract text from html tags using reduce in Javascript\n\nI'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try:\n\n// JS\r\nlet par = Array.from(document.getElementsByTagName(\"p\"));\r\ndocument.write(par.reduce((a, b) => a + \", \" + b.innerHTML));\n\r\n

    Apple

    \r\n

    Strawberry

    \r\n

    Banana

    \n\nAnd here's the (wrong) output:\n\n[object HTMLParagraphElement], Strawberry, Banana\n\nWhat am I doing wrong?\nMany thanks for your help!\n\nA:\n\nreduce function takes a 2nd argument which is the initial value for the accumulator.\nBy default, it's the first item in the array.\nTo have the desired result you should write your code like this:\nlet par = Array.from(document.getElementsByTagName(\"p\"));\ndocument.write(par.reduce((a,b)=>a+\", \"+b.innerHTML, \"\"));\n\nHere is a document on reduce function from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29083,"cells":{"text":{"kind":"string","value":"Q:\n\nHow do I apply weights to particular columns in a dataframe to aggregate a new 'score' column?\n\nBy way of reproducible example, say you have the following R dataframe:\nset.seed(100)\ndf <- data.frame(Name=letters[1:5], Apples=sample(1:10, 5), Oranges=sample(1:10, 5), Bananas=sample(1:10, 5), Dates=sample(1:10, 5))\n\nAnd you want to apply the following weights to the dataframe:\nWeights <- c(Apples = \"3\", Oranges = \"2\", Bananas = \"1\")\n\nTo produce a new aggregate score column. So for example the first row (row 'a') would have the following score:\n(3*4 + 2*5 + 1*7) = 29\n\nAnd row b:\n(3*3 + 2*8 + 1*8) = 33\n\nWhat code I write to do this automatically?\nNote that the weights may not be in the same order as the columns in the dataframe, nor will there necessarily be a weight for every numeric column in the dataframe (hence why in this example there is no weight for 'dates').\n\nA:\n\nWe can use rowSums after multiplying the subset of columns in 'df' by the corresponding elements in 'Weights' (by replicating the 'Weights')\nrowSums(df[names(Weights)]*as.numeric(Weights)[col(df[names(Weights)])])\n#[1] 29 33 24 20 36\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29084,"cells":{"text":{"kind":"string","value":"Q:\n\nQt Auto-UI Testing stopping because of messagebox. How to simulate enter on messagebox?\n\nMy task is to write an automated UI test for a software being developed. It happens so, that there are radiobuttons triggering a messagebox, which stops my automated test until I manually confirm it (pressing ENTER). The issue is that I do not know how I can call that newly summoned messagebox and then have it confirmed by QTest::keyClick(, QtKey::Key_Enter); and have my automated test continue the run.\nI am using QWidgets, QApplication, Q_OBJECT and QtTest.\nI will provide a code similar to what I am working with:\nvoid testui1(){\nForm1* myform = new Form1();\nmyform->show();\nQTest::mouseClick(myform->radioButton01, Qt::LeftButton, Qt::NoModifier, QPoint(), 100);\n// Message box pops up and stops the operation until confirmed\nQTest::mouseClick(myform->radioButton02, Qt::LeftButton, Qt::NoModifier, QPoint(), 100);\n// again\n...\n}\n\nHow exactly can I script to confirm the message box automatically? The message box is only an [OK] type, so I don't need it to return whether I have pressed Yes or No. A QTest::keyClick(, Qt::Key_Enter) method needs to know to which object it should press enter to. I tried including myform into the object and it did not work. Googling I did not find the answer. I found the following result as not functioning for what I am looking for\nQWidgetList allToplevelWidgets = QApplication::topLevelWidgets();\nforeach (QWidget *w, allToplevelWidgets) {\n if (w->inherits(\"QMessageBox\")) {\n QMessageBox *mb = qobject_cast(w);\n QTest::keyClick(mb, Qt::Key_Enter);\n }\n}\n\nA:\n\nThe problem is that once you've \"clicked\" on your radio button, which results in QMessageBox::exec being called, your code stops running until the user clicks on of the buttons.\nYou can simulate the user clicking a button by starting a timer before you click on the radio button. \nIn the callback function for the timer you can use QApplication::activeModalWidget() to obtain a pointer to the message box, and then just call close on it.\nQTimer::singleShot(0, [=]()\n {\n QWidget* widget = QApplication::activeModalWidget();\n if (widget)\n widget->close();\n });\n\nIf you want to press a specific key on the message box, you can use QCoreApplication::postEvent to post a key event to the message box\nQTimer::singleShot(0, [=]()\n {\n int key = Qt::Key_Enter; // or whatever key you want\n\n QWidget* widget = QApplication::activeModalWidget();\n if (widget)\n {\n QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier); \n QCoreApplication::postEvent(widget, event);\n }\n });\n\nSo in terms of how this ties into the sample code you gave:\nvoid testui1()\n{\n Form1* myform = new Form1();\n myform->show();\n\n QTimer::singleShot(0, [=]()\n {\n QWidget* widget = QApplication::activeModalWidget();\n if (widget)\n widget->close();\n else\n QFAIL(\"no modal widget\");\n });\n\n QTest::mouseClick(myform->radioButton01, Qt::LeftButton, Qt::NoModifier, QPoint(), 100);\n}\n\nA sample app putting all the above together:\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char** argv)\n{\n QApplication app(argc, argv);\n QMainWindow window;\n\n QWidget widget;\n window.setCentralWidget(&widget);\n\n QHBoxLayout layout(&widget);\n\n QPushButton btn(\"go\");\n layout.addWidget(&btn);\n\n QObject::connect(&btn, &QPushButton::clicked, [&]()\n {\n QTimer::singleShot(0, [=]()\n {\n QWidget* widget = QApplication::activeModalWidget();\n if (widget)\n {\n widget->close();\n }\n else\n {\n std::cout << \"no active modal\\n\";\n }\n });\n\n QMessageBox(\n QMessageBox::Icon::Warning,\n \"Are you sure?\",\n \"Are you sure?\",\n QMessageBox::Yes | QMessageBox::No,\n &window).exec();\n });\n\n window.show();\n return app.exec();\n}\n\nClicking on Go will look like nothing is happening, as the QMessageBox is closed immediately. \nTo prove that the message box is shown and then closed you can increase the time in the call to QTimer::singleShot to a value such as 1000. Now it will show the message box for 1 second, and then it will be closed by the timer.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29085,"cells":{"text":{"kind":"string","value":"Q:\n\nUse years / Years of Use?\n\nI am writing a paper about pipelines in Seoul..\nAnd I have a grammatical problem to describe pipeline's years of use... \nI'd like to describe the time passed since they were installed. \nWhich one is correct and natural? \n'Use years of pipelines in Seoul,Korea' \n'Years of use of pipelines in Seoul,Korea' \n'Pipelines' use years in Seoul,Korea' \n\nA:\n\nUse years… or Years of use… or Pipelines' use years… look like titles, not parts of the report. If those are the given choices, my vote would go to Years of use of pipelines… but in real life I’d expect Life expectancy of… or something like Planned and achieved years of use…\nAre these pipelines planned or payed for in man years, calendar years or how, please? Train operators use track miles, route miles, passenger miles and other equally different measures of the same line on a map even before they take time into account but the grammar shouldn’t change.\nHere, if the pipe is replaced or painted, the maintenance guys will presumably be interested in the life expectancy of the parts, not the whole pipe-line, and measure that in something like pipe-years or paint-years, not pipe-line years.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29086,"cells":{"text":{"kind":"string","value":"Q:\n\nI need to display images next to text\n\nI am new to HTML and CSS, first year IT student. I need to display text and pictures next to each other. The text should occupy most of the page with the images to the right of the text. I know I will need to use CSS for this but I have no idea how.\n\n \r\n
    \r\n \"Logo\r\n\r\n \"Logo\r\n\r\n \"Logo\r\n\r\n \"Logo\r\n\r\n \"Logo\r\n\r\n \"Logo\r\n
    \r\n\r\n \r\n
    Payment Methods
    \r\n\r\n

    Edgars or Jet Card:

    \r\n

    Visit any of our Campuses that accept Debit and Credit Cards, and you can also pay with your Edgars or Jet Card! Please note that your Edgars or Jet Thank U Card along with the Card Holder must be present for the transaction. Proof of ID will be required

    \r\n\r\n

    Debit or Cerdit Card:

    \r\n

    A cardholder begins a credit card transaction by presenting his or her card to a merchant as payment for goods or services. The merchant uses their credit card machine, software or gateway to transmit the cardholder’s information and the details of\r\n the transaction to their acquiring bank, or the bank’s processor.

    \r\n\r\n

    SnapScan

    \r\n

    Download the SnapScan App to your Mobile Phone or Tablet Device. Open the SnapScan App, tap on “Scan” and scan the SnapCode displayed at the shop. This identifies the shop and prompts you to enter the amount you wish to pay. Enter your PIN to secure\r\n and complete the transaction. Richfield will receive a notification containing a confirmation of payment from SnapScan and your account will be updated accordingly.

    \r\n\r\n

    Standard Bank M65 Cash Payment

    \r\n

    Direct Cash Deposits can be made at any branch of Standard Bank using the M65 form which can be obtained from your nearest Campus. This form can only be used at Standard Bank branches. Don’t forget to ensure that your name AND student number are on\r\n both sections of the form.

    \r\n\r\n

    Electronic Funds Transfer (or CDI)

    \r\n

    Name of Bank: Standard Bank of South Africa

    \r\n

    Name of Account: Richfield Graduate Institute of Technology (PTY) Ltd.

    \r\n

    USE YOUR ICAS NUMBER, INITIALS AND SURNAME AS REFERENCE

    \r\n \n\nI've tried numerous examples online but I can't seem to get it to work. Below is a picture of how it's supposed to look.\nAny help will be appreciated. \nThank you in advance\n\nA:\n\nflex is definitely the way to go. This should get you started. If you upload your pictures to imgur we could see how the actual images work\n\nhtml,body{\r\nmargin:0;\r\npadding:0;\r\n}\r\n#container{\r\n display:flex;\r\n width:100vw;\r\n}\r\n\r\n#left{\r\n display:flex;\r\n flex-direction:column;\r\n width:70%;\r\n }\r\n \r\n #right{\r\n display:flex;\r\n width:30%;\r\n justify-content:center;\r\n margin-top:25%;\r\n }\r\n \r\n #group1,#group2{\r\n display:flex;\r\n flex-direction:column;\r\n }\n
    \r\n\r\n\r\n
    \r\n\r\n\r\n
    Payment Methods
    \r\n\r\n

    Edgars or Jet Card:

    \r\n

    Visit any of our Campuses that accept Debit and Credit Cards, and you can also pay with your Edgars or Jet Card! Please note that your Edgars or Jet Thank U Card along with the Card Holder must be present for the transaction. Proof of ID will be required

    \r\n\r\n

    Debit or Cerdit Card:

    \r\n

    A cardholder begins a credit card transaction by presenting his or her card to a merchant as payment for goods or services. The merchant uses their credit card machine, software or gateway to transmit the cardholder’s information and the details of\r\n the transaction to their acquiring bank, or the bank’s processor.

    \r\n\r\n

    SnapScan

    \r\n

    Download the SnapScan App to your Mobile Phone or Tablet Device. Open the SnapScan App, tap on “Scan” and scan the SnapCode displayed at the shop. This identifies the shop and prompts you to enter the amount you wish to pay. Enter your PIN to secure\r\n and complete the transaction. Richfield will receive a notification containing a confirmation of payment from SnapScan and your account will be updated accordingly.

    \r\n\r\n

    Standard Bank M65 Cash Payment

    \r\n

    Direct Cash Deposits can be made at any branch of Standard Bank using the M65 form which can be obtained from your nearest Campus. This form can only be used at Standard Bank branches. Don’t forget to ensure that your name AND student number are on\r\n both sections of the form.

    \r\n\r\n

    Electronic Funds Transfer (or CDI)

    \r\n

    Name of Bank: Standard Bank of South Africa

    \r\n

    Name of Account: Richfield Graduate Institute of Technology (PTY) Ltd.

    \r\n

    USE YOUR ICAS NUMBER, INITIALS AND SURNAME AS REFERENCE

    \r\n
    \r\n\r\n
    \n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29087,"cells":{"text":{"kind":"string","value":"Q:\n\nPhotoshop Script change each successive image\n\nI have a script that batch processes images, adding a radial blur on the blue channel. \nWhat I want to do is change the radial blur's origin or centre point in each successive image. Is there a way of scripting this? \nAt the moment for the first image, when I recorded the action, i placed the centre point manually, photoshop must have some code somewhere to show what I did. Any ideas on how to access this? \nIt's a series of the sun shining through trees, I want the radial blur to track from one side to the other like the sun does in the images (timelapse) \n\nA:\n\nThis kind of automation control isn't really available using just Photoshop actions, to go that deep you'll need to leverage Photoshop's Scripting API.\nUnfortunately I don't have much knowledge on the PS API; I'd recommend visiting ps-scripts.com, hopefully you can find some experts there.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29088,"cells":{"text":{"kind":"string","value":"Q:\n\nParameterize ORM query with where in clause\n\nI'm trying to parametrize a query that is currently working and is ripe for an SQL injection attack:\nqryAwards = ORMExecuteQuery(\n \"from Award where awardID in (#form.deleteAwardList#) and Game.Season.User.userID=:uid\",\n {uid=session.userID}\n);\nif(not isNull(qryAwards) and arrayLen(qryAwards)){\n for(i in qryAwards){\n entityDelete(i);\n }\n}\n\nI tried this, having the param without single quotes:\nqryAwards = ORMExecuteQuery(\n \"from Award where awardID in (:awardList) and Game.Season.User.userID=:uid\",\n {awardList=form.deleteAwardList, uid=session.userID}\n);\n\nI keep getting the following error:\nThe value 117,118 cannot be converted to a number.\nAnd this, with the param enclosed in single quotes:\nqryAwards = ORMExecuteQuery(\n \"from Award where awardID in (':awardList') and Game.Season.User.userID=:uid\",\n {awardList=form.deleteAwardList, uid=session.userID}\n);\n\nGets me the following error:\nInvalid parameters specified for the query.\n\nA:\n\nIn HQL (which is what you use when you do ORMExecuteQuery() ) parameters used in an IN clause need to be passed as an array. You need to convert form.deleteAwardList to an array. There are a few different ways to handle this, but this will work.\nqryAwards = ORMExecuteQuery(\n \"from Award where awardID in (:awardList) and Game.Season.User.userID=:uid\",\n {awardList=listToArray( form.deleteAwardList ), uid=session.userID}\n);\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29089,"cells":{"text":{"kind":"string","value":"Q:\n\n<> symbol in type name in C#\n\nPlease help me understand what this is : <>\nI am doing some reflection looking for types in an assembly and I get a bunch of types, all with the same name, but different methods :\n{Name = \"<>c__DisplayClass1\" \n FullName = \"HelixToolkit.Wpf.ElementSortingHelper+<>c__DisplayClass1\"}\n\nA:\n\nIt's the naming convention that the compiler uses when translating lambda expressions into classes.\nHere's an example. Starting with this class:\npublic class UserQuery\n{\n private void Main()\n {\n var x = 42;\n Func f = () => x;\n var y = f();\n }\n}\n\nThe compiler turns this into:\npublic class UserQuery\n{\n public UserQuery()\n {\n base..ctor();\n }\n\n private void Main()\n {\n UserQuery.<>\\u003C\\u003Ec__DisplayClass1 cDisplayClass1 = new UserQuery.<>\\u003C\\u003Ec__DisplayClass1();\n cDisplayClass1.x = 42;\n int num = new Func((object) cDisplayClass1, __methodptr(<\\u003CMain>\\u003Eb__0))();\n }\n\n [CompilerGenerated]\n private sealed class <>\\u003C\\u003Ec__DisplayClass1\n {\n public int x;\n\n public <>\\u003C\\u003Ec__DisplayClass1()\n {\n base..ctor();\n }\n\n public int <\\u003CMain>\\u003Eb__0()\n {\n return this.x;\n }\n }\n}\n\nNot legal c#, but legal IL.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29090,"cells":{"text":{"kind":"string","value":"Q:\n\nSwift 3 accessing nested dictionaries within json feed\n\nHi I currently have a JSON feed:\n\"hourly\":{ \n \"summary\":\"Breezy and partly cloudy tomorrow morning.\",\n \"icon\":\"wind\",\n \"data\":[ \n { \n \"time\":1479222000,\n \"summary\":\"Clear\",\n \"icon\":\"clear-night\",\n \"precipIntensity\":0,\n \"precipProbability\":0,\n \"temperature\":25.09,\n \"apparentTemperature\":25.09,\n \"dewPoint\":21.56,\n \"humidity\":0.81,\n \"windSpeed\":1.13,\n \"windBearing\":72,\n \"visibility\":9,\n \"cloudCover\":0.1,\n \"pressure\":1015.18,\n \"ozone\":242.43\n },\n { \n \"time\":1479225600,\n \"summary\":\"Clear\",\n \"icon\":\"clear-night\",\n \"precipIntensity\":0,\n \"precipProbability\":0,\n \"temperature\":24.18,\n \"apparentTemperature\":24.18,\n \"dewPoint\":20.71,\n \"humidity\":0.81,\n \"windSpeed\":1.42,\n \"windBearing\":76,\n \"visibility\":9,\n \"cloudCover\":0.1,\n \"pressure\":1015.24,\n \"ozone\":242.3\n }\n]\n\nI can access \"hourly\" and \"data\" no problem with the following code:\nlet hourly = json[\"hourly\"] as? [String : Any],\nlet data = hourly[\"data\"] as? [[String : Any]]\n\nBut what I need to do is access the first Dictionary only within data, which I cannot seem to figure out. Can anybody help please?\n\nA:\n\nYou can use first property of Array like this.\nif let hourly = json[\"hourly\"] as? [String : Any],\n let data = hourly[\"data\"] as? [[String : Any]], \n let firstDic = data.first {\n\n print(firstDic)\n //If you want `summary` value from firstDic\n print(firstDic[\"summary\"])\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29091,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to display print statements interlaced with matplotlib plots inline in Ipython?\n\nI would like to have the output of print statements interlaced with plots, in the order in which they were printed and plotted in the Ipython notebook cell. For example, consider the following code:\n(launching ipython with ipython notebook --no-browser --no-mathjax)\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\ni = 0\nfor data in manydata:\n fig, ax = plt.subplots()\n print \"data number i =\", i\n ax.hist(data)\n i = i + 1\n\nIdeally the output would look like:\ndata number i = 0\n(histogram plot)\ndata number i = 1\n(histogram plot)\n...\n\nHowever, the actual output in Ipython will look like:\ndata number i = 0\ndata number i = 1\n...\n(histogram plot)\n(histogram plot)\n...\n\nIs there a direct solution in Ipython, or a workaround or alternate solution to get the interlaced output?\n\nA:\n\nThere is simple solution, use matplotlib.pyplot.show() function after plotting.\nthis will display graph before executing next line of the code\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\ni = 0\nfor data in manydata:\n fig, ax = plt.subplots()\n print \"data number i =\", i\n ax.hist(data)\n plt.show() # this will load image to console before executing next line of code\n i = i + 1\n\nthis code will work as requested\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29092,"cells":{"text":{"kind":"string","value":"Q:\n\nRun-time error '9' Subscript out of range with Conditional Format code\n\nI'm very new to VBA (and any sort of programming in general), so I'm not sure how to proceed here. I'm guessing my error has something to do with overlapping ranges for my conditional formats as I also got errors when the code was set up a different way that were resolved once the ranges no longer overlapped. That might not be the case here, but I figured it'd be helpful to know.\nI get a 'Subscript out of range' error with the following code:\nSub test2()\n Dim rngToFormat As Range\n Set rngToFormat = ActiveSheet.Range(\"$a$1:$z$1000\")\n Dim rngToFormat2 As Range\n Set rngToFormat2 = ActiveSheet.Range(\"$k$20:$k$1000\")\n Dim rngToFormat3 As Range\n Set rngToFormat3 = ActiveSheet.Range(\"$j$22:$j$1000\")\n Dim rngToFormat4 As Range\n Set rngToFormat4 = ActiveSheet.Range(\"$i$22:$i$1000\")\n Dim rngToFormat5 As Range\n Set rngToFormat5 = ActiveSheet.Range(\"$g$20:$g$1000\")\n Dim rngToFormat6 As Range\n Set rngToFormat6 = ActiveSheet.Range(\"$d$9, $f$9\")\n Dim rngToFormat7 As Range\n Set rngToFormat7 = ActiveSheet.Range(\"$G$3:$G$7,$G$11:$G$15,$E$3:$E$7,$E$11:$E$15,$N$3:$N$7,$N$11:$N$15,$L$3:$L$7,$L$11:$L$15\")\n rngToFormat.FormatConditions.Delete\n rngToFormat.FormatConditions.Add Type:=xlExpression, _\n Formula1:=\"=if(R[]C20=1, true(), false())\"\n rngToFormat.FormatConditions(1).Font.Color = RGB(228, 109, 10)\n rngToFormat2.FormatConditions.Add Type:=xlExpression, _\n Formula1:=\"=and(R[]C7=\"\"6. Negotiate\"\", R[]C11<25)\"\n rngToFormat2.FormatConditions(2).Font.ColorIndex = 3\n rngToFormat2.FormatConditions.Add Type:=xlExpression, _\n Formula1:=\"=and(R[]C7=\"\"4. Develop\"\", R[]C11<15)\"\n rngToFormat2.FormatConditions(3).Font.ColorIndex = 3\n rngToFormat2.FormatConditions.Add Type:=xlExpression, _\n Formula1:=\"=and(R[]C7=\"\"5. Prove\"\", R[]C11<20)\"\n rngToFormat2.FormatConditions(4).Font.ColorIndex = 3\n rngToFormat2.FormatConditions.Add Type:=xlExpression, _\n Formula1:=\"=and(R[]C7=\"\"7. Committed\"\", R[]C11<30)\"\n rngToFormat2.FormatConditions(5).Font.ColorIndex = 3\n rngToFormat2.FormatConditions.Add Type:=xlExpression, _\n Formula1:=\"=and(R[]C7=\"\"Closed Won\"\", R[]C11<35)\"\n rngToFormat2.FormatConditions(6).Font.ColorIndex = 3\n rngToFormat3.FormatConditions.Add Type:=xlCellValue, _\n Operator:=xlGreater, Formula1:=200\n rngToFormat3.FormatConditions(7).Font.ColorIndex = 3\n rngToFormat4.FormatConditions.Add Type:=xlCellValue, _\n Operator:=xlGreater, Formula1:=60\n rngToFormat4.FormatConditions(8).Font.ColorIndex = 3\n rngToFormat5.FormatConditions.Add Type:=xlExpression, _\n Formula1:=\"=or(R[]C7=\"\"1. Plan\"\", R[]C7=\"\"2. Create\"\", R[]C7=\"\"3. Qualify\"\")\"\n rngToFormat5.FormatConditions(9).Font.ColorIndex = 3\n rngToFormat6.FormatConditions.Add Type:=xlCellValue, _\n Operator:=xlLess, Formula1:=0\n rngToFormat6.FormatConditions(10).Font.ColorIndex = 3\n rngToFormat6.FormatConditions(10).Interior.Color = RGB(204, 204, 255)\n rngToFormat6.FormatConditions(10).Interior.Pattern = xlSolid\n rngToFormat7.FormatConditions.Add Type:=xlCellValue, _\n Operator:=xlLess, Formula1:=0\n rngToFormat7.FormatConditions(11).Font.ColorIndex = 3\n rngToFormat7.FormatConditions(11).Interior.Color = RGB(215, 228, 158)\n rngToFormat7.FormatConditions(11).Interior.Pattern = xlSolid\nEnd Sub\n\nAny advice would be appreciated, thanks!\n\nA:\n\nThere are two problems with your code:\n\nYou only delete the conditional formats for the first range - but add conditions to all ranges - and later access a specific one that most likely is not the one you just created (FormatConditions(3))\nThe formulas you entered are the default english formulas - for some stange reason, FormatConditions.Add requires the local formulas though.\n\nI reworked your code, take a look if it solves your problem:\n\nSub test2()\n\n fctApply rng:=Range(\"$a$1:$z$1000\"), strFormulaR1C1:=\"=(R[]C20=1)\", dblRGB:=RGB(228, 109, 10), blnDeleteOldConditions:=True\n\n fctApply rng:=Range(\"$k$20:$k$1000\"), strFormulaR1C1:=\"=and(R[]C7=\"\"6. Negotiate\"\",R[]C11<25)\", intColorIndex:=3\n fctApply rng:=Range(\"$k$20:$k$1000\"), strFormulaR1C1:=\"=and(R[]C7=\"\"4. Develop\"\", R[]C11<15)\", intColorIndex:=3\n fctApply rng:=Range(\"$k$20:$k$1000\"), strFormulaR1C1:=\"=and(R[]C7=\"\"5. Prove\"\", R[]C11<20)\", intColorIndex:=3\n fctApply rng:=Range(\"$k$20:$k$1000\"), strFormulaR1C1:=\"=and(R[]C7=\"\"7. Committed\"\", R[]C11<30)\", intColorIndex:=3\n fctApply rng:=Range(\"$k$20:$k$1000\"), strFormulaR1C1:=\"=and(R[]C7=\"\"Closed Won\"\", R[]C11<35)\", intColorIndex:=3\n\n fctApply rng:=Range(\"$j$22:$j$10000\"), strFormulaR1C1:=200, intType:=xlCellValue, intOperator:=xlGreater, intColorIndex:=3\n\n fctApply rng:=Range(\"$i$22:$i$1000\"), strFormulaR1C1:=60, intType:=xlCellValue, intOperator:=xlGreater, intColorIndex:=3\n\n With fctApply(rng:=Range(\"$g$20:$g$1000\"), strFormulaR1C1:=0, intType:=xlCellValue, intOperator:=xlLess, intColorIndex:=3)\n .Interior.Color = RGB(204, 204, 255)\n .Interior.Pattern = xlSolid\n End With\n\n With fctApply(rng:=Range(\"$G$3:$G$7,$G$11:$G$15,$E$3:$E$7,$E$11:$E$15,$N$3:$N$7,$N$11:$N$15,$L$3:$L$7,$L$11:$L$15\"), strFormulaR1C1:=0, intType:=xlCellValue, intOperator:=xlLess, intColorIndex:=3)\n .Interior.Color = RGB(215, 228, 158)\n .Interior.Pattern = xlSolid\n End With\nEnd Sub\n\nPrivate Function fctApply(rng As Range, _\n strFormulaR1C1 As Variant, _\n Optional intType As XlFormatConditionType = xlExpression, _\n Optional intOperator As XlFormatConditionOperator, _\n Optional intColorIndex As Integer = -1, _\n Optional dblRGB As Double = -1, _\n Optional blnDeleteOldConditions As Boolean = False _\n ) As FormatCondition\n\n Dim objCond As FormatCondition\n Dim strFormula As String\n\n If blnDeleteOldConditions Then rng.FormatConditions.Delete\n\n strFormula = Application.ConvertFormula(strFormulaR1C1, xlR1C1, xlA1)\n\n On Error GoTo ConvertLocal\n If intOperator <> 0 Then\n rng.FormatConditions.Add Type:=intType, _\n Formula1:=strFormula, Operator:=intOperator\n Else\n rng.FormatConditions.Add Type:=intType, _\n Formula1:=strFormula\n End If\n On Error GoTo 0\n Set objCond = rng.FormatConditions(rng.FormatConditions.Count)\n If intColorIndex <> -1 Then\n objCond.Font.ColorIndex = intColorIndex\n ElseIf dblRGB <> -1 Then\n objCond.Font.Color = dblRGB\n End If\n Set fctApply = objCond\n\n Exit Function\nConvertLocal:\n With Range(\"A1\") 'change this to an empty cell address - it is temporarily used to translate from local to normal formulas\n .Formula = strFormula\n strFormula = .FormulaLocal\n .Formula = \"\"\n End With\n Resume\nEnd Function\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29093,"cells":{"text":{"kind":"string","value":"Q:\n\nIs this 'new releases in SF&F' question on topic?\n\nThis question has been closed, (not edited) and then reopened, and is now getting close votes again. One user even voted to both close and reopen it. Seems like we don't know what to do with this question. The main thrust of it is:\n\nWhere do you guys find out about recently published novels in Science Fiction and Fantasy?\nI'm not interested in reviews, news on which writer might write what, which bookstore has closed, conventions etc., just a simple list of everything that is newly available in bookstores.\n\nThey're looking for resources that provide thorough listings of Sci-fi & Fantasy book releases. Is this on topic, or off topic? Why?\n\nA:\n\nI think the question is fine.\nThe scope is well-defined, and it doesn't seem likely that there will be so many answers that we'd risk a lot of \"me too\" answers. \nWhile there could be several different yet acceptable, answers, I don't think that's sufficient reason to close it. \nThe subject itself is both relevant and of potential interest to a significant number of our members.\n\nA:\n\nThis seems like an unanswerable question. Sure, a few good sites could be recommended, but in the end, any number of answers could be equally acceptable. Given that possibility, it seems like it's not really a good question for Stack Exchange.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29094,"cells":{"text":{"kind":"string","value":"Q:\n\nHow to make ordinal tick labels adjust automatically in D3\n\nAs you can see in the example, the tick labels on an ordinal axis (scale) become crowded and illegible as the domain grows. How can I make them adjust automatically as they would on a linear axis? \n(I suppose I could use a linear scale instead, but this question and the answer from Mike Bostock himself suggest that the ordinal scale is more appropriate for this type of data. After all, the domain is discrete and I'm making a modified bar chart, where a convenient padding setting is useful.)\n\nvar x0 = d3.scaleBand()\r\n .domain(d3.range(1,6))\r\n .range([0,200]);\r\n\r\nvar x = d3.scaleBand()\r\n .domain(d3.range(1,51))\r\n .range([0,200]);\r\n\r\nvar xLinear = d3.scaleLinear()\r\n .domain([1,50])\r\n .range([0,200]);\r\n\r\nd3.select('svg').append('g')\r\n .attr('transform', 'translate(10,10)')\r\n .call(d3.axisBottom(x0));\r\n\r\nd3.select('svg').append('g')\r\n .attr('transform', 'translate(10,50)')\r\n .call(d3.axisBottom(x));\r\n\r\nd3.select('svg').append('g')\r\n .attr('transform', 'translate(10,100)')\r\n .call(d3.axisBottom(xLinear));\n\r\n\n\nA:\n\nThis solution takes advantage of the very smart built-in function d3.ticks(), which deals with edge cases so we don't have to.\n\nvar dataSmall = d3.range(1,8),\r\n dataLarge = d3.range(1, 51);\r\n\r\nvar xS = d3.scaleBand()\r\n .domain(dataSmall)\r\n .rangeRound([0,200]);\r\n\r\nvar xL = d3.scaleBand()\r\n .domain(dataLarge)\r\n .rangeRound([0,200]);\r\n\r\nfunction makeAxis(scale) {\r\n var n=5, \r\n data = scale.domain(),\r\n dataLength = data.length;\r\n \r\n return d3.axisBottom(scale).tickValues( \r\n dataLength > n ? d3.ticks(data[0], data[dataLength-1], n) : data);\r\n}\r\n\r\nd3.select('svg').append('g')\r\n .attr('transform', 'translate(10,10)')\r\n .call(makeAxis(xS));\r\n\r\nd3.select('svg').append('g')\r\n .attr('transform', 'translate(10,50)')\r\n .call(makeAxis(xL));\n\r\n\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29095,"cells":{"text":{"kind":"string","value":"Q:\n\nElementary symmetric functions of reciprocals of monic polynomials in function fields\n\nLet $q$ be a prime power and $\\mathbb{F}_q$ the field of cardinality $q$. Let $A = \\mathbb{F}_q[T]$ and let $A_+ \\subset A$ be the monic polynomials. Choose any ordering $<$ of $A_+$ and let $k$ be a positive integer. Set\n$$e(k) = \\sum_{\\begin{matrix} a_1, a_2, \\ldots, a_k \\in A_+ \\\\ a_1 \\cdots > a_k}} \\frac{1}{a_1^{s_1} \\cdots a_k^{s_k}} \\in \\mathbb{F}_q((T^{-1})),\n$$\nwhere the ordering is an arbitrarily chosen lexicographic ordering of $A_+$ and $s_1, \\ldots, s_k$ are positive integers. It seems then that your value $e(k)$ is $\\zeta_l(1, \\ldots, 1)$ of depth $k$. He also defines\n$$\n\\zeta_d(s_1, \\ldots, s_k) = \\sum_{\\substack{a_1, \\ldots, a_k \\in A_+ \\\\ \\deg a_1 > \\cdots > \\deg a_k}} \\frac{1}{a_1^{s_1} \\cdots a_k^{s_k}},\n$$\nwhich is the type of MZV you mentioned studied by Chang. He also defines a couple of other variants.\nTo address one of your questions, from what Thakur says in Remark 5.10.16, it would appear that the $e(k)$'s are probably not algebraically related to the MZV's $\\zeta_d(s_1, \\dots, s_k)$.\nAnderson and Thakur (\"Multizeta values for $\\mathbb{F}_q[t]$, their period interpretation, and relations between them\", IMRN, 2009) showed that the MZV's $\\zeta_d(s_1,\\dots, s_k)$ defined using degrees can be realized as periods of certain higher dimensional Drinfeld modules (Anderson $t$-modules) that are iterated extensions of tensor powers of the Carlitz module. They then can also be expressed as linear combinations of values of Carlitz multiple polylogarithm functions. Using this period interpretation various bits of transcendence machinery can be applied, which is the subject of the paper you mention by Chang (Compositio, 2014).\nThakur mentions in that same remark 5.10.16 that the lexicographic MZV's $\\zeta_l(s_1, \\dots, s_k)$ do not have natural relations with periods of Drinfeld modules, so at least on the surface they seem to represent a different class of numbers than the $\\zeta_d(s_1, \\dots, s_k)$'s. Thakur follows this up with numerical calculations when $q=2$ and shows that they do not appear to be rational multiples of Carlitz zeta values.\nOf course this does not answer your question definitively, but I think it would be safe to say that it is not known whether there are any general relations.\nAlso, one minor correction: when you remark that it was shown that the Carlitz zeta values $\\zeta(m)$ are algebraically independent over $\\mathbb{F}_q(T)$ (aside from the known relations involving Bernoulli-Carlitz numbers and $p$-th powers), this result is actually due to Chang and Yu (\"Determination of algebraic relations among special zeta values in positive characteristic,\" Adv. Math. 216 (2007), 321-345). In the 1991 paper of Yu, he proves that the values are all transcendental over $\\mathbb{F}_q(T)$, but the algebraic independence questions were answered later.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29096,"cells":{"text":{"kind":"string","value":"Q:\n\nHow can I set a custom font for the action bar text, and make it happen from startup?\n\nI can't get it done. My App starts with the standard font, the custom activity layout is inflated, and just then my font changes. As far as I know, I cannot directly code a custom font into the xml file of the layout I intend to inflate onto the action bar, so I got a code from another topic on the net about doing the change by referencing the TextView in the action bar and setting it in the class. Is there actually a way to make the font \"standard\", so that the app will already startup showing my custom font?\nHere is the relevant code for the main activity, which I'm trying to change:\n public class Amd extends Activity {\n\n DatabaseHandler dh = new DatabaseHandler(this);\n public ProgressDialog mProgressDialog;\n public JSONObject jsonOb;\n public Filme m;\n public ArrayList g;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.amd);\n setActionBar();\n }\n\n @SuppressLint(\"InflateParams\") private void setActionBar(){\n this.getActionBar().setDisplayShowCustomEnabled(true);\n\n LayoutInflater inflator = LayoutInflater.from(this);\n View v = inflator.inflate(R.layout.custom_action_bar, null);\n\n Typeface font = Typeface.createFromAsset(this.getAssets(), \"tcb.ttf\");\n TextView textoActionBar = (TextView) getWindow().findViewById(Resources.getSystem().getIdentifier(\"action_bar_title\", \"id\", \"android\"));\n textoActionBar.setTypeface(font);\n textoActionBar.setText(\"TESTE\");\n this.getActionBar().setCustomView(v);\n }\n\nHere is the styles xml, which I am also using to theme and color the action bar:\n \n\n \n \n\n \n\n \n\n\n\nHere is the manifest:\n \n\n\n \n\n \n\n \n \n \n \n \n \n \n \n\n\n\nHere is the layout I'm inflating to the main activity:\n \n\n \n\n \n\n \n \n\n \n\n \n\n \n \n\n\n\nWhat else should I need to specify, or do you need any other code to understand what I'm trying to do?\n\nA:\n\nSince Android ActionBar setTitle method receives a CharSequence as a parameter you can simply replace the call of your setActionBar() method with the next lines, that using span:\nTypeface font = Typeface.createFromAsset(this.getAssets(), \"tcb.ttf\");\nString actionBarTitle = \"TESTE\";\nSpannableStringBuilder ssb = new SpannableStringBuilder(actionBarTitle);\nssb.setSpan(new CustomTypefaceSpan(\"\", font), 0, actionBarTitle.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);\ngetActionBar().setTitle(ssb);\n\nAnd don't forget to add this custom typeface span class into your project.\npublic class CustomTypefaceSpan extends TypefaceSpan {\n\n private final Typeface newType;\n\n public CustomTypefaceSpan(String family, Typeface type) {\n super(family);\n newType = type;\n }\n\n @Override\n public void updateDrawState(TextPaint ds) {\n applyCustomTypeFace(ds, newType);\n }\n\n @Override\n public void updateMeasureState(TextPaint paint) {\n applyCustomTypeFace(paint, newType);\n }\n\n private static void applyCustomTypeFace(Paint paint, Typeface tf) {\n int oldStyle;\n Typeface old = paint.getTypeface();\n if (old == null) {\n oldStyle = 0;\n } else {\n oldStyle = old.getStyle();\n }\n\n int fake = oldStyle & ~tf.getStyle();\n if ((fake & Typeface.BOLD) != 0) {\n paint.setFakeBoldText(true);\n }\n\n if ((fake & Typeface.ITALIC) != 0) {\n paint.setTextSkewX(-0.25f);\n }\n\n paint.setTypeface(tf);\n }\n}\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29097,"cells":{"text":{"kind":"string","value":"Q:\n\nSet required props on component\n\nSay that I create a custom component like this:\nconst MyComponent = (props) => (\n \n {props.children}\n \n)\n\nAnd I need to make sure that props contain the variables name and id, because otherwise what I want to do is not going to work (now I know that this code will work anyhow, but hypothetically say that it won't).\nIs there a way in React to demand that certain props are passed to a component?\nMaybe this is something that is obvious, but I couldn't find any information about it. \n\nA:\n\nYou can use PropTypes. It was earlier a part of React but now it has its own npm package, https://www.npmjs.com/package/prop-types. This will give you a runtime error if ther props are not provided. Its also useful, because linters can warn you if you miss them.\nhttps://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md\nimport React from 'react';\nimport PropTypes from 'prop-types'; \n\nconst MyComponent = (props) => (\n \n {props.children}\n />\n);\n\nMyComponent.propTypes = {\n name: PropTypes.string.isRequired,\n id: PropTypes.string.isRequired,\n element: PropTypes.arrayOf(PropTypes.element).isRequired\n};\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29098,"cells":{"text":{"kind":"string","value":"Q:\n\nWhy do USB connectors only fit one way?\n\nWhy do USB plugs only fit one way into USB ports? \nForgive my ignorance, but there are several types of plugs that are \"omnidirectional\" and do not have to be oriented a certain way to fit into the corresponding plug (pursuant to shape). In the case of USB, when you're trying to plug one in blind, it can be a bit annoying if you happen to be trying to do it upside-down.\nI'm guessing this has to do with the pinouts, but then why doesn't the USB standard just negotiate for \"pin 1\" when something is plugged in, or use a functionally symmetrical pinout layout?\n\nA:\n\nMOST connectors in the world only allow one mechanical orientation. \nOnes that are not orientation specific are usually \"concentric\" such as the familiar 2.5 / 3.5 / 6mm plugs on earphones and similar. Where these have more than 2 conductors the contacts for the conductors at the inside end of the socket ride over the conductors for the tip end as the plugs are inserted. Care must be taken to ensure that no problems are cause by these spurious short term connections.\nAC power connectors in some systems can be polarity insensitive, but this can lead to safety concerns where there is some difference in attribute between the two contacts other than their ability to provide power. eg in many systems the mains power is ground referenced with one conductor essentially at ground potential. Reversing the twocontacts would still lead to a functioning power connection but may bypass protection and safety systems.\nBUT the vast majority of plug and socket systems are orientation sensitive.\n Consider the plugs for keyboards and mice (DB9, PS/2, now USB), any 3 pin power plug, trailer power connectors, telephone and network connectors (RJ10, RJ11, RJ45, ...), XLR/Cannon and similar audio connectors, video connectors for monitors (\"IBM\"/Apple/Other), SCART AV connectors, DMI, ...\n People are well used to this.\n Why should USB be any different? \nBUT, full size USB has two power connectors and two signal connectors. Rhe signal connections could easily enough be interchanged.\n But interchanging the two power connections involves routing +ve and -ve signals correctly.\n This could be done with a diode bridge and two diodes but the voltage drop of about 1.2 Volts represents a loss of about 25% of the Voltage and an immediate 25% power loss. This could be addressed with mechanical automated switching - essentially relays, or with low voltage drop electronic switches (MOSFETs or other) but the cost and complexity is not justified in view of the ease of \"just plugging it in correctly\".\nIm Mini and Micro USB systems with potentially more conductors this could have been addressed by redundant arrangements of contacts but that wastes potential resources (size or contacts) and still only results in two possible alignments, 180 degrees apart rotationally. You still could not insert it aligned long side vertical or at an angle.\n\nSuper Solution: \nFor the ultimate connector consider these two conductor wholly functionally symmetric hemaphroditic connectors. \n\nNot only can these be orientated in two orientations rotationally but there is no \"male\" or \"female\" connector - both 'plug' and 'socket' are identical. \n\nThis scheme can be extended to more conductors using a coaxial arrangement. This is a General Radio GR874 connector. If you ever meet something using these you can be fairly sure you are in the presence of greatness :-).\n\nMany many more of the same\n\nA:\n\nThree reasons: \n\nBackwards Compatibility\nThe USB standard was begun in 1994, and v. 1.0 became official in 1996. DB-25 (for \"D-subminiature\", no seriously) was the standard printer port. Everything since that date is still backwards compatible with the original specification. Making the connector omnidirectional would be an incompatibility, which is unacceptable for the standards organization which regulates USB.\nCost\nAs mentioned by mikeselectricstuff, this would add additional cost and/or size. Size is a design goal of USB (as evidenced by the trend from USB-B to USB-mini to USB-micro), and cost is always a design goal.\nLogo Placement\nNo, really. The USB specification demands that all compliant cables put the USB trident: \n\non the top side of the connector. Here's a semi-official reference: \n\nThe standard USB trident must be on the top of both plug overmolds as described in chapter 6 of the USB 2.0 specification.\n\nYou'll have to buy the USB spec if you want it straight from the horse's mouth. (Incidentally, I consider that a very appropriate idiom to apply to standards organizations that don't release their standards for free!) If the connector were reversible, the branding might not be visible, or the branding would have to be on both sides, which would make cable manufacturers unhappy.\n\nIncidentally, the last point, while it may seem rather picky of the USB standards organization to demand it, is useful. As described in this Lifehacker article, you can determine which way to connect the USB cable by looking for the trident and orienting this \"upwards\". Unless, of course, it's dark and you can't see the trident...in which case I recommend that you turn the lights on and move to a position where you can see what you're doing.\n\nA:\n\nThere is also a reason that has not been mentioned, and it's related to the concept of poka-yoke (thanks to my friend that studies industrial engineering).\nThe principle is that well-designed connectors shouldn't leave room for ambiguity, especially when potential failures or safety risks are involved. Paraphrasing Murphy's law, \n\nIf there is any way to do it wrong, he (someone) will.\n\nlike the old floppy disk, that enters in the hole only in one direction, and also SD cards, good design implies also that the final user has nearly no chance to connect it improperly, and ideally shouldn't have any doubt.\nThis is not the reason for not making it symmetrically connected, but since it has a orientation, it's made in a way that you cannot connect it in the wrong way.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29099,"cells":{"text":{"kind":"string","value":"Q:\n\nBootstrap data-toggle not working in Safari\n\nThe below code making use of bootstrap's data-toggle=\"collapse\" to do the functionality of collapse/expand on click of configured element,\nIn this case, clicking parent1 and parent2\nProblem: On click of parent element, the collapse is working from my PC using Chrome and firefox browsers, but it is not working from my iPad using safari browser.\n
    \n Technologies \n
    \n\n
    \n \n\n Vertical \n
    \n\n
    \n \n instead of
    in parent elements where we click to expand/collapse, ie \n\n Technologies \n\nand updated the styling of parentclass to have display: block;, and tested in iPad, now its working from iPad safari browser too!\nUpdates 1:\nSaw one post where it is suggesting also to use href to make Safari in iPhone understand, but I am not sure if I must use that attribute too, as when I test with href too, everytime I touch on the parent header, the page gives an impression of refreshing [page moves]. So thinking that href is not needed.\n\nUpdates 2\nUpdated using
    text
    stringlengths
    175
    47.7k
    meta
    dict
    Q: How to rename columns in ORMLite? How can we rename column name in ORMLite? I am trying to write that query SELECT id as _id from some_table Android Cursor Adapter requires us to have column named _id and ORMLite requires us to have column named id. I am trying to write that query and return Cursor from this query. Dao<NewsArticle, Long> newsArticleDao = ((SomeApp)mContext.getApplicationContext()).getDAOConnection().getDAO( NewsArticle.class); QueryBuilder<NewsArticle, Long> query = newsArticleDao.queryBuilder().selectRaw( "`id` as `_id`"); PreparedQuery<NewsArticle> preparedQuery = query.prepare(); CloseableIterator<NewsArticle> iterator = newsArticleDao.iterator(preparedQuery); AndroidDatabaseResults results = (AndroidDatabaseResults)iterator.getRawResults(); cursor = results.getRawCursor(); That's what I have so far but I am getting this error when I pass query to iterator. java.sql.SQLException: Could not compile this SELECT_RAW statement since the caller is expecting a SELECT statement. Check your QueryBuilder methods. A: I guess I have to answer my question. I still couldn't figure out how to rename column but I found the solution to problem. Android Custom Adapter requires column named_id that's true but ORMLite doesn't require the column name to be id, I was wrong about that. It wants you to mark a column as id. In my model, I marked my id and now it works like a charm. @DatabaseField(id = true) private long _id;
    { "pile_set_name": "StackExchange" }
    Q: Spark clean up shuffle spilled to disk I have a looping operation which generates some RDDs, does repartition, then a aggregatebykey operation. After the loop runs onces, it computes a final RDD, which is cached and checkpointed, and also used as the initial RDD for the next loop. These RDDs are quite large and generate lots of intermediate shuffle blocks before arriving a the final RDD for every iteration. I am compressing my shuffles and allowing shuffles to spill to disk. I notice on my worker machines that my working directory where the shuffle files are stores are not being cleaned up. Thus eventually I run out of disk space. I was under the impression that if I checkpoint my RDD, it would remove all the intermediate shuffle blocks. However this seems not to be happening. Would anyone have any ideas on how I could clean out my shuffle blocks after every iteration of the loop, or why my shuffle blocks aren't being cleaned up? A: Once you cached the RDD to your memory/disk, as long as the spark context is alive, the RDD will be stored in your memory/disk. In order to tell the driver it can remove the RDD from the memory/disk you need to use the unpersist() function. From the java-doc: /** * Mark the RDD as non-persistent, and remove all blocks for it from memory and disk. * * @param blocking Whether to block until all blocks are deleted. * @return This RDD. */ def unpersist(blocking: Boolean = true) So you can use: rdd.unpersist()
    { "pile_set_name": "StackExchange" }
    Q: Can you implement Vue.js in a Java EE web application? I just develop a tool with my classmates and we want to use Vue.js as Web interface. For Description what we programmed. We developed a Java EE web application in Eclipse. We use Tomcat 7 as web server. I search a long time and i found nothing. A: Vue.js is a javascript front-end framework. There is nothing to stop you from using that with a middle-layer/back-end technology like Java EE. In your HTML pages(or JSP) just include the Vue.js file as mentioned in the documentation, and other .js files that you create as part of your vue.js frontend application. The library can then interface with any HTTP-based backend methods that you expose (using Servlets, Controllers, etc.) depending on how your Java EE project is structured and what frameworks it uses.
    { "pile_set_name": "StackExchange" }
    Q: Did Avengers: Infinity War ignore the locations/distances set in Guardians of the Galaxy? I know the Marvel Cinematic Universe likes to keep the locations vague to avoid questions like this, but it's been established by director James Gunn that the events of the Guardians of the Galaxy take place in the Andromeda Galaxy, not our local Milky Way. That suggests that locations such as Knowhere, Xandar, and Titan are in the Andromeda Galaxy, 2.5 million light-years away from the Milky Way. (For comparison, that's approximately 25 times the 100,000-light-year diameter of the Milky Way.) Given that, we seem to have a scramble of locations in Infinity War: The Asgardian refugee vessel(s), which left the ruins of Asgard (location unspecified) and from which Heimdall sent Hulk to Earth. Thanos then dispatches his minions to Earth. The Guardians, who are nominally in Andromeda, respond to the distress call from the Asgardian refugees and pick up Thor. Some Guardians go to Knowhere in the Benatar (the Milano's successor), while others go to Nidavellir via a pod. (Isn't Nidavellir supposed to be in its own realm?) Tony Stark, Peter Parker, and Doctor Strange wind up on Titan after a what seems like a relatively short trip. Thor and Thanos wind up on Earth, but their instantaneous travel is explained by either bifrost powers or the Space Stone. Did Infinity War directors Anthony and Joe Russo retcon James Gunn's distinction between the two galaxies, or did they simply fuzz everything over? Is there an MCU or out-of-universe answer? A: Did Infinity War directors Anthony and Joe Russo retcon James Gunn's distinction between the two galaxies, or did they simply fuzz everything over? Neither. As far as we can tell, James Gunn’s Milky Way/Andromeda distinction* still holds as well as it ever did during Avengers: Infinity War. Abundant spoilers ahead! We don’t get much more accurate in the movie than the “SPACE” caption early on, but we can probably assume that all of the movie’s locations except for Earth are in the Andromeda galaxy: While the Asgardian ship originated on Asgard, the location of which is super-unclear, it left when Asgard was destroyed at the end of Thor: Ragnarok. Given that the Guardians picked up its distress call, it was presumably in Andromeda when it was attacked by Thanos and co. Given that Thor was taking his people to Earth, it was presumably on the way there already. I don’t think we’re ever told that Nidavellir is in its own “realm”, like Asgard, so given that Thor, Rocket and Groot can reach it via one of the Milano’s pods, we can assume it’s in Andromeda too, like Knowhere. As we saw in Guardians of the Galaxy, ships like the Milano can apparently travel to a bunch of Andromeda galaxy locations in fairly short order, so that takes care of most of the Guardians’ travel. As you say, all of Thanos’s journeys in the movie (including his trip to Vormir, wherever the hell that is) are done using the Space Stone’s presumably-instantaneous teleportation powers, so they’re fine. Both the Hulk’s journey from the Asgardian ship, and Thor’s trip to earth with Rocket and Groot, are via the presumably-near-instantaneous Bifrost, so they’re cool too. The only other journeys between the Milky Way and Andromeda are made by Thanos’s minions — from the Asgardian wreckage to Earth, and then Ebony Maw heading back towards Titan with Tony, Peter and Stephen along for the ride. We know from the first Guardians movie that the Milano picked up Peter Quill on Earth in 1988, and presumably made it back to Andromeda without it taking years to do so, so it seems reasonable that Team Thanos’s big donut ships can do the journey really quickly. As Maw’s leaves earth, we see it shoot off into some sort of lightning effect, so I guess he turned on the hyperdrive or whatever at that point. Out-of-universe, the movies have almost always been pretty vague about the distances and journey times involved in space travel, because they’re not really about that. This isn’t Star Trek, and we’re not calculating warp factors: all the ships can get to where they need to be, quickly enough for the story to proceed. * Which, given that it’s not mentioned in any of the movies, is strictly-speaking non-canon.
    { "pile_set_name": "StackExchange" }
    Q: How to add margin to an HTML element? https://jsfiddle.net/mp3ajvrL/ I'm trying to add a margin between the list element "contact us" and the h3 element with the text "Functional and Non-Functional Requirements". However, I am not able to do this. It looks like the h3 element covers the whole list somehow, so that the margin-top: 10px css will only add a margin above the list. Any tips? body { background-color: #333333; margin: auto; font-family: Verdana, Geneva, Tahoma, sans-serif; color: white; } #navbar { width: 100%; width: 100%; float: left; margin: 0 0 1em 0; padding: 0; background-color: #f2f2f2; border-bottom: 1px solid #ccc; } .header { font-size: 1em; margin-bottom: 5%; } h2 { font-size: 1em; text-align: left; padding-left: 2%; margin-bottom: -1em; } h5 { text-align: center; } h3 { text-align: left; padding-left: 2%; font-size: 1.4em; color: white; margin-bottom: 0; margin-top: 0; } p, ul, ol { font-size: 1.2em; line-height: 130%; width: auto; text-align: left; padding-left: 2%; } p ol { padding-left: 10%; padding-bottom: 2%; } p ol li { margin-bottom: 10px; } p { float: left; margin-bottom: 40px; margin-top: 0.1em; } #cover { width: 100%; } .intro .facts .bibliography { min-width: 65ch; max-width: 75ch; } #container { position: relative; text-align: center; color: white; } #cover { position: relative; width: 100%; } #headingOnPicture { position: relative; } #textOverImage { position: absolute; bottom: 0; left: 2%; } @media only screen and (max-width: 1122px) { #textOverImage {} } @media only screen and (max-width: 800px) { #textOverImage {} } #navbar ul { display: inline-block; overflow: hidden; list-style-type: none; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; display: inline-block; list-style-type: none; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; padding: 15px; margin: auto; } ol { padding-left: 5%; } ol li { margin: 0.5%; } #center { margin: auto; font-family: Verdana, Geneva, Tahoma, sans-serif; color: white; padding-left: 5%; padding-right: 5%; } * { box-sizing: border-box; } body { font: 300 100% 'Helvetica Neue', Helvetica, Arial; } .four { width: 60; } .four a { width: 60px; } .container { width: 20%; margin: 0 auto; } ul li { display: inline; text-align: center; } a { display: inline-block; width: 25%; padding: .75rem 0; margin: 0; text-decoration: none; color: #333; font-size: 20px; } .one:hover~hr { opacity: 1; margin-left: 5%; } .two:hover~hr { opacity: 1; margin-left: 28%; } .three:hover~hr { opacity: 1; margin-left: 52%; } .four:hover~hr { opacity: 1; margin-left: 75%; } hr { margin-left: 0%; opacity: 0.1; height: .25rem; width: 25%; margin: 0; background: tomato; border: none; transition: .3s ease-in-out; } li b { color: powderblue; } p { float: left; } .mainPart { width: 80%; padding-left: 20%; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" type="text/css" href="styling.css"> </head> <body> <div class="container"> <ul> <li class="one"><a href="/p1.html">P1</a></li> <!-- --> <li class="two"><a href="/p2.html">P2</a></li> <!-- --> <li class="three"><a href="/p3.html">P3</a></li> <!-- --> <li class="four"><a href="/p4.html">P4</a></li> <hr /> </ul> </div> <div id="container"> <header id="headingOnPicture"> <img id="cover" src="mountains.jpg" alt="Cover image" /> <h1 id="textOverImage">P1: Requirements</h1> </header> <div class="header"> <div> <div> // 18. September 2019 </div> </div> </div> <div class="mainPart"> <h3> Administrative Details </h3> <p> Antikvariatet is a cozy bar/pub/café/venue located at Bakklandet in Trondheim. It offers a great assortment of beers as well as outside serving. The inside of Antikvariatet consists of two separated areas. One offers a calm, laid-back atmosphere while the other hosts various kinds of events. The events ranges from small concerts and standup comedy to cultural performances and social debates. </p> <h3>Purpose and goals</h3> <p> The main purpose of this website is to inform customers about events happening at Antikvariatet. The business goal is to increase the amount of visitors to the venue. This means that the "event" section of the website needs to stand out. In addition, special offers also need to be clearly communicated. The website has to capture the cozy atmosphere Antikvariatet offers. </p> <br> <div> <h3>Audience</h3> <p> The intended user is in the age group 18 to 60. These customers tend to use the internet more for looking up information about the venue. </p> <br> <br> </div> <div class="content"> <h3> The content of the site and how it is organized </h3> <h2> The major sections of the website:</h2> </div> <br> <ol> <li><b>About us: </b> Consists of the general information about Antikvariatet. What the concept is and what they offer.</li> <li><b>Menu: </b>Should provide the menu for the restaurant and the selection of beers in the bar.</li> <li><b>Events: </b>Events consists of three subcategories the customer can choose between if desired. The subcategories are «Cultural events», «Sosial events» and «Concerts». The customer can also just scroll down and see the unfiltered list of events. A «Search for event or concert» - should also appear with a search bar. Next to the event there should be a button to sign up for the event.</li> <li><b>Picures: </b>This should consists of pictures showing the cozy atmosphere and the different things they offer. It could also have an Instagram part consisting of pictures taken by customers and tagged with «Antikvariatet».</li> <li><b>Contact us: </b>Should contain the information about where they are located with a map, the opening hours, the mail to contact them and the telephone number.</li> </ol> <div> <h3> Functional and Non-Functional Requirements </h3> <h2> Non-functional: </h2> <br> <p> Due to the large age difference of the clientele, the website should and be easy and intuitive also for users with low technology experience. The appearance of the website should reflect the warm and welcoming environment that Antikvariatet provide. The webside should be effective, and all functionalities should react within a second. </p> <h2> Functional: </h2> <br> <p> The customers should easily be provided a menu for the café. They should also able to make and send in orders for the different events. The website should provide a calendar for all the events. One should be able to click on a date and see happenings on that day, and also all happenings over a longer periode. For better usability, the customer should be able to divide the different events in smaller groups; concerts, social events or cultural activities and be able to search for events. The customer should also be able to press a button and get the website in English instead of Norwegian. </p> </div> <h3>Final location:</h3> <p> We have not yet been in touch with Antikvariatet about making an actual website for them. Howerver, the website will be hosted at one of our folk.ntnu servers. </p> </div> </div> </body> </html> A: Get rid of the rule: li { float: left; } body { background-color: #333333; margin: auto; font-family: Verdana, Geneva, Tahoma, sans-serif; color: white; } #navbar { width: 100%; width: 100%; float: left; margin: 0 0 1em 0; padding: 0; background-color: #f2f2f2; border-bottom: 1px solid #ccc; } .header { font-size: 1em; margin-bottom: 5%; } h2 { font-size: 1em; text-align: left; padding-left: 2%; margin-bottom: -1em; } h5 { text-align: center; } h3 { text-align: left; padding-left: 2%; font-size: 1.4em; color: white; margin-bottom: 0; margin-top: 0; } p, ul, ol { font-size: 1.2em; line-height: 130%; width: auto; text-align: left; padding-left: 2%; } p ol { padding-left: 10%; padding-bottom: 2%; } p ol li { margin-bottom: 10px; } p { float: left; margin-bottom: 40px; margin-top: 0.1em; } #cover { width: 100%; } .intro .facts .bibliography { min-width: 65ch; max-width: 75ch; } #container { position: relative; text-align: center; color: white; } #cover { position: relative; width: 100%; } #headingOnPicture { position: relative; } #textOverImage { position: absolute; bottom: 0; left: 2%; } @media only screen and (max-width: 1122px) { #textOverImage {} } @media only screen and (max-width: 800px) { #textOverImage {} } #navbar ul { display: inline-block; overflow: hidden; list-style-type: none; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; display: inline-block; list-style-type: none; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; padding: 15px; margin: auto; } ol { padding-left: 5%; } ol li { margin: 0.5%; } #center { margin: auto; font-family: Verdana, Geneva, Tahoma, sans-serif; color: white; padding-left: 5%; padding-right: 5%; } * { box-sizing: border-box; } body { font: 300 100% 'Helvetica Neue', Helvetica, Arial; } .four { width: 60; } .four a { width: 60px; } .container { width: 20%; margin: 0 auto; } ul li { display: inline; text-align: center; } a { display: inline-block; width: 25%; padding: .75rem 0; margin: 0; text-decoration: none; color: #333; font-size: 20px; } .one:hover~hr { opacity: 1; margin-left: 5%; } .two:hover~hr { opacity: 1; margin-left: 28%; } .three:hover~hr { opacity: 1; margin-left: 52%; } .four:hover~hr { opacity: 1; margin-left: 75%; } hr { margin-left: 0%; opacity: 0.1; height: .25rem; width: 25%; margin: 0; background: tomato; border: none; transition: .3s ease-in-out; } li b { color: powderblue; } p { float: left; } .mainPart { width: 80%; padding-left: 20%; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" type="text/css" href="styling.css"> </head> <body> <div class="container"> <ul> <li class="one"><a href="/p1.html">P1</a></li> <!-- --> <li class="two"><a href="/p2.html">P2</a></li> <!-- --> <li class="three"><a href="/p3.html">P3</a></li> <!-- --> <li class="four"><a href="/p4.html">P4</a></li> <hr /> </ul> </div> <div id="container"> <header id="headingOnPicture"> <img id="cover" src="mountains.jpg" alt="Cover image" /> <h1 id="textOverImage">P1: Requirements</h1> </header> <div class="header"> <div> <div> // 18. September 2019 </div> </div> </div> <div class="mainPart"> <h3> Administrative Details </h3> <p> Antikvariatet is a cozy bar/pub/café/venue located at Bakklandet in Trondheim. It offers a great assortment of beers as well as outside serving. The inside of Antikvariatet consists of two separated areas. One offers a calm, laid-back atmosphere while the other hosts various kinds of events. The events ranges from small concerts and standup comedy to cultural performances and social debates. </p> <h3>Purpose and goals</h3> <p> The main purpose of this website is to inform customers about events happening at Antikvariatet. The business goal is to increase the amount of visitors to the venue. This means that the "event" section of the website needs to stand out. In addition, special offers also need to be clearly communicated. The website has to capture the cozy atmosphere Antikvariatet offers. </p> <br> <div> <h3>Audience</h3> <p> The intended user is in the age group 18 to 60. These customers tend to use the internet more for looking up information about the venue. </p> <br> <br> </div> <div class="content"> <h3> The content of the site and how it is organized </h3> <h2> The major sections of the website:</h2> </div> <br> <ol> <li><b>About us: </b> Consists of the general information about Antikvariatet. What the concept is and what they offer.</li> <li><b>Menu: </b>Should provide the menu for the restaurant and the selection of beers in the bar.</li> <li><b>Events: </b>Events consists of three subcategories the customer can choose between if desired. The subcategories are «Cultural events», «Sosial events» and «Concerts». The customer can also just scroll down and see the unfiltered list of events. A «Search for event or concert» - should also appear with a search bar. Next to the event there should be a button to sign up for the event.</li> <li><b>Picures: </b>This should consists of pictures showing the cozy atmosphere and the different things they offer. It could also have an Instagram part consisting of pictures taken by customers and tagged with «Antikvariatet».</li> <li><b>Contact us: </b>Should contain the information about where they are located with a map, the opening hours, the mail to contact them and the telephone number.</li> </ol> <div> <h3> Functional and Non-Functional Requirements </h3> <h2> Non-functional: </h2> <br> <p> Due to the large age difference of the clientele, the website should and be easy and intuitive also for users with low technology experience. The appearance of the website should reflect the warm and welcoming environment that Antikvariatet provide. The webside should be effective, and all functionalities should react within a second. </p> <h2> Functional: </h2> <br> <p> The customers should easily be provided a menu for the café. They should also able to make and send in orders for the different events. The website should provide a calendar for all the events. One should be able to click on a date and see happenings on that day, and also all happenings over a longer periode. For better usability, the customer should be able to divide the different events in smaller groups; concerts, social events or cultural activities and be able to search for events. The customer should also be able to press a button and get the website in English instead of Norwegian. </p> </div> <h3>Final location:</h3> <p> We have not yet been in touch with Antikvariatet about making an actual website for them. Howerver, the website will be hosted at one of our folk.ntnu servers. </p> </div> </div> </body> </html> If you need to float some other set of list items then change the selector to be more specific and target only those list items, not all of them.
    { "pile_set_name": "StackExchange" }
    Q: Unable to extract a substring from a string I am long string array and i want to pass it to another function in the chunks of 250 characters one time, i have written this code: var cStart = 0; var phase = 250; var cEnd = cStart + phase; var count = 0; while (count < 10000) { string fileInStringTemp = ""; fileInStringTemp = fileInString.Substring(cStart, cEnd); var lngth = fileInStringTemp.Length; //Do Some Work cStart += phase; cEnd += phase; count++; } In the first iteration of the loop the value of lngth is 250 which is fine, in the next iteration i also want it to 250 because i am extracting substring from 250-500 characters but shockingly the value of lngth variable in the second iteration gets 500. Why is that? i am also trying to initialize string variable everytime in the loop so it starts from zero but no gain. A: Substring's second parameter is the length you want, not the stop index. public string Substring( int startIndex, int length ) So, all you need to do is change your code to have the start index and length (phase) fileInString.Substring(cStart, phase) A: Here is the MSDN link about how to work with Substring: https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx According to MSDN first parameter in Substring method is StartIndex which is defined as The zero-based starting character position of a substring and second parameter is used to define lenght of substring which is defined as The number of characters in the substring. So you should try this: var cStart = 0; var phase = 250; var count = 0; while (count < 10000) { string fileInStringTemp = ""; fileInStringTemp = fileInString.Substring(cStart, phase); var lngth = fileInStringTemp.Length; //Do Some Work count++; cStart = phase * count + 1; }
    { "pile_set_name": "StackExchange" }
    Q: Mean python pandas by values in a row I have a dataframe with with multiple rows similar to the one showed below: wave cross cross2 0 299.0 1.25 3.30 1 299.5 1.30 4.20 2 300.0 1.45 4.36 3 300.5 1.65 4.32 4 300.8 1.56 4.56 What I want to do is to average the data for the same wavelengths so that is get a data frame with wave as an integer, which results in something like this: wave cross cross2 0 299 1.30 3.75 1 300 1.55 4.41 what is the best way to achieve this with python pandas? A: Use groupby with aggreagate mean, but first cast wave column to int: df = df.assign(wave = df['wave'].astype(int)).groupby('wave').mean() Or: df['wave'] = df['wave'].astype(int) df = df.groupby('wave').mean() Or: df = df[df.columns.difference(['wave'])].groupby(df['wave'].astype(int)).mean() print (df) cross cross2 wave 299 1.275000 3.750000 300 1.553333 4.413333
    { "pile_set_name": "StackExchange" }
    Q: Generating all possible Domino tilings on a $4 \times 4$ grid I have a task to write a program which generates all possible combinations of tiling domino on a $4 \times 4$ grid. I have found many articles about tilings, but it is for me quite difficult and I didn't find any article with an algorithm that allows generating all possible combinations. Could someone give me some tips? How should I start with that? Thanks in advance. A: Do this recursively: Find the top-left empty square on the board. If there is no empty square, all squares are covered with dominos, just print the solution and return. If there is an empty square, try to put a domino horizontally, then vertically. If that is possible, put a domino on the board and go to the step 1 again. Some backtracking is necessary along the way. You can easily grasp the idea by looking at the following Python script: In Python: class Table: table = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] domino = 0 count = 0 def findEmptyCell(self): for i in range(0, 4): for j in range(0, 4): if self.table[i][j] == 0: return (i, j) return None def placeDomino(self): cell = self.findEmptyCell() if cell is None: # we have a full board with no empy cells self.print() return # try to put a new domino horizontally x = cell[0] y = cell[1] self.domino += 1 self.table[x][y] = self.domino if y < 3 and self.table[x][y + 1] == 0: self.table[x][y + 1] = self.domino self.placeDomino() self.table[x][y + 1] = 0 if x < 3 and self.table[x + 1][y] == 0: self.table[x + 1][y] = self.domino self.placeDomino() self.table[x + 1][y] = 0 self.table[x][y] = 0 self.domino -= 1 def print(self): self.count += 1 print("=== Solution #%d ===" % self.count) for i in range(0, 4): print("%d%d%d%d" % (self.table[i][0], self.table[i][1], self.table[i][2], self.table[i][3])) print('') t = Table() t.placeDomino() Here is the output, 36 solutions in total (with dominoes numbered from 1 to 8): === Solution #1 === 1122 3344 5566 7788 === Solution #2 === 1122 3344 5567 8867 === Solution #3 === 1122 3344 5667 5887 === Solution #4 === 1122 3344 5677 5688 === Solution #5 === 1122 3344 5678 5678 === Solution #6 === 1122 3345 6645 7788 === Solution #7 === 1122 3345 6745 6788 === Solution #8 === 1122 3445 3665 7788 === Solution #9 === 1122 3455 3466 7788 === Solution #10 === 1122 3455 3467 8867 === Solution #11 === 1122 3456 3456 7788 === Solution #12 === 1123 4423 5566 7788 === Solution #13 === 1123 4423 5567 8867 === Solution #14 === 1123 4423 5667 5887 === Solution #15 === 1123 4423 5677 5688 === Solution #16 === 1123 4423 5678 5678 === Solution #17 === 1123 4523 4566 7788 === Solution #18 === 1123 4523 4567 8867 === Solution #19 === 1223 1443 5566 7788 === Solution #20 === 1223 1443 5567 8867 === Solution #21 === 1223 1443 5667 5887 === Solution #22 === 1223 1443 5677 5688 === Solution #23 === 1223 1443 5678 5678 === Solution #24 === 1223 1453 6457 6887 === Solution #25 === 1233 1244 5566 7788 === Solution #26 === 1233 1244 5567 8867 === Solution #27 === 1233 1244 5667 5887 === Solution #28 === 1233 1244 5677 5688 === Solution #29 === 1233 1244 5678 5678 === Solution #30 === 1233 1245 6645 7788 === Solution #31 === 1233 1245 6745 6788 === Solution #32 === 1234 1234 5566 7788 === Solution #33 === 1234 1234 5567 8867 === Solution #34 === 1234 1234 5667 5887 === Solution #35 === 1234 1234 5677 5688 === Solution #36 === 1234 1234 5678 5678
    { "pile_set_name": "StackExchange" }
    Q: git - dual boot ubuntu and windows with separate data partition I just installed ubuntu along side windows 7. All of my git local working folders are on a separate data partition. Everything is committed in windows 7's git, but in ubuntu's git, running git status shows everything as modified. When I tried git log all the history is still there. I don't want to commit everything every time I switch to the other OS to work. Is there a solution? A: Your problem is that when you check out files on Windows with the git default config, they are created with CRLF (the windows default) line endings in your working directory, but committed as LF for cross-platform compatibility. Now your Linux sees the CRLF on every line and says that it’s different to the LF in the repo. That’s why every line is reported as different. I would suggest setting the line endings to LF on windows. In a previous answer I explained the details of how to do that. Following those steps will also enable line-ending normalization to LF on linux, which will avoid problems if you accidentally create some CRLF on windows and commit that in linux later on. You can also just disable line ending normalization completely, but that is likely to cause trouble in the future, unless you only use a completely fixed set of editors, whose line ending handling you know very will.
    { "pile_set_name": "StackExchange" }
    Q: How do I know which MongoDB version is installed by using the Command Line? Without changing directory to \MongoDB\bin\, when I call: mongod -v I get: 'mongod' is not recognized as an internal or external command, operable program or batch file. When I call the same command from \bin\ it launches the server just like I'm calling: mongod It is the same case with 'mongo' and 'mongos'. I added the \bin\ path to the environment variables thinking it will help but it didn't. To clarify with an example, to get the version of Ruby, I can call: ruby -v Why can't I do the same with MongoDB? A: First add location of MongoDB's bin folder to PATH env variable. This is required because it is the place where mongod.exe is stored. For example, if MongoDB 4.0 is in your Program Files, add "C:\Program Files\MongoDB\Server\4.0\bin" to PATH for all system users. Then try using : mongod --version
    { "pile_set_name": "StackExchange" }
    Q: Attach Sharepoint 2010 List attachment to gridview I have a SharePoint list, which has attachments!! I am using a custom grid-view to display some selected List fields from the list. I would like to include the attachment as an embedded document in the Grid-view, Is that possible? A: Got it worked, Created an anchor type item template in grid view. And the Href property of the anchor tab is binded with the attachment retrieved pro grammatically. Working great!!
    { "pile_set_name": "StackExchange" }
    Q: How can I write regular expression for android:host I have multiple hosts, for example: example1.myhost.abc example2.myhost.xyz example3.myhost.jkl I want to write a regular expression for host name in the data attribute of intent filter. Which may look like this: <data android:host=".*myhost.*" android:scheme="http"/> But its not working for me. It seems that android:host does not support regex. Is there any way to achieve it? A: It seems that android:host does not support regex. Correct. Is there any way to achieve it? You can say that you handle the http scheme and not specify anything else (e.g., no host, no path). This will cover all your desired patterns, but it will also cover every other domain name. Or, since you can have more than one <data> element, you can have as many host attributes as needed to cover all of your sites, without regular expressions.
    { "pile_set_name": "StackExchange" }
    Q: Using Git for Angular App I'm using Yeoman to generate out an angular app. Once I'm happy with my app, I run grunt which creates a production-ready version of my application in a folder called /dist at the root of my project. I've then initialised this /dist directory as a Git repository with git init and pushed the files up to Bitbucket, where they currently sit right now. What I'm asking is do I have to compile my production-ready app with grunt every time I want to make a commit? It seems I have to. I'm thinking this setup might not be the most productive way to do this? Am I missing something, is there an easier and more productive way to handling this? A: That workflow is odd. Only source code should be in your git repository. Not the compiled/minified files. Source code is what matters. When you colaborate with somebody else, they should run grunt tasks on their own. Dist package should be created before deploy to production. Or on regular basis by the continuous integration server.
    { "pile_set_name": "StackExchange" }
    Q: Selenium webdriver how to do file upload with ng-click="upload('files')" I'm trying to see if this is possible - to automate a file upload when the HTML code is NOT an < input type='file' > but rather a link <a ng-click="upload('files')"> File Upload </a> When this link is clicked, it automatically opens a file selector to choose which file you want to upload. The problem is, it does not contain an INPUT type='file' element which I could locate and then use webdriver.send_keys('/Users/myname/testfile.txt'). How can I go about trying to get selenium webdriver to handle this file upload? Any help to direct me to a solution is greatly appreciated. A: Last time that i needed this WebDriver couldn't interact with dialogs cause dialogs are the domain of the operating system and not the webpage. One option would be to skip the file dialog entirely and issue a POST/GET/PUT, but this requires more advanced knowledge of the website as well as understanding of how to construct a request. What i did in that ocation was to create an auxiliar program executable for dealing with the dialog, so i called it in the middle of the Selenium script, just after generating the dialog. Here you have a sample of the last approach using Java & AutoIT: http://www.automationtesting.co.in/2009/07/selenium-handle-dialogs.html
    { "pile_set_name": "StackExchange" }
    Q: Restrict height of div marked with display:table-cell? Problem: I need to use display:table (in the parent div) and display:table-cell (in the contained div) to center some content vertically. This is working except when the content overflows vertically. I want to restrict the height so that a scrollbar appears if there's any vertical overflow. Fiddle: http://jsfiddle.net/PTSkR/110/ (Note that in the output, the div is expanded vertically despite me setting the height to 160px) CSS: side-study-box { background-color: white; color: black; border: 1px solid #3D6AA2; text-align: center; height: 160px !important; display: table !important; margin: 0px !important; margin-left: -1px !important; position: relative; overflow-y: scroll; width: 100%; } .side-study-box .side-box-content { width: calc(100%); height: 160px !important; float: right; display: table; overflow-y: scroll; } .side-study-box .text-content-saved { width: 100% !important; font-size: 24px; display: table-cell; vertical-align: middle; text-align: center; height: 160px !important; max-height: 160px !important; background-color: white; padding: 0px !important; margin: 0px !important; font-family: "Segoe UI", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif; border: 0px !important; overflow-y: scroll; } A: here is your fiddle updated , with max-height on content wrapper. .side-study-box { background-color: white; color: black; border: 1px solid #3D6AA2; display: table; width: 100%; border-spacing:1em; } .side-box-content { width: 100%; height: ; display: table-cell; } .text-content-saved { max-height:160px; overflow:auto; padding:5px; } http://jsfiddle.net/GCyrillus/6tLAu/ up here first code was : the box doesn't grow. down here second does first and centers content if little. .side-study-box { background-color: white; color: black; border: 1px solid #3D6AA2; display: table; width: 100%; border-spacing:1em; height:160px; } .side-box-content { width: 100%; height: ; display: table-cell; vertical-align:middle; } .text-content-saved { max-height:140px; overflow:auto; padding:5px; }
    { "pile_set_name": "StackExchange" }
    Q: Merge duplicate cell values and their sums in Excel using VBA I am trying to merge duplicate cell values in Excel using VBA. Here is an example of the data: Col1 Col2 run 1 run 2 see 9 go 5 see 1 I need to merge this information so that the data is as follows: Col1 Col2 run 3 see 10 go 5 Meaning, that I need to merge the duplicate values in Column 1 and sum their corresponding values in Column 2. I have already consulted and tried a similar situation here: How to SUM / merge similar rows in Excel using VBA? Where one of the recommendations was the following macro: Sub Macro1() Dim ColumnsCount As Integer ColumnsCount = ActiveSheet.UsedRange.Columns.Count ActiveSheet.UsedRange.Activate Do While ActiveCell.Row <= ActiveSheet.UsedRange.Rows.Count If ActiveCell.Value = ActiveCell.Offset(1, 0).Value Then For i = 1 To ColumnsCount - 1 ActiveCell.Offset(0, i).Value = ActiveCell.Offset(0, i).Value + ActiveCell.Offset(1, i).Value Next ActiveCell.Offset(1, 0).EntireRow.Delete shift:=xlShiftUp Else ActiveCell.Offset(1, 0).Select End If Loop End Sub However, it seems to be creating an infinite loop that causes my excel to crash, without actually merging anything. Does anyone have any suggestions as to how I can adapt this code to arrive at the merge solution that I need? A: The following assumes your table starts in cell A1 and columns C onwards are empty (if they are not you will lose data on the merged rows) Sub mergeCategoryValues() Dim lngRow As Long With ActiveSheet lngRow = .Cells(.LastCell.Row, 1).End(xlUp).Row .Cells(1).CurrentRegion.Sort key1:=.Cells(1), header:=xlNo 'change this to xlYes if your table has header cells Do If .Cells(lngRow - 1, 1) = .Cells(lngRow, 1) Then .Cells(lngRow - 1, 2) = .Cells(lngRow - 1, 2) + .Cells(lngRow, 2) .Rows(lngRow).Delete End If lngRow = lngRow - 1 Loop Until lngRow < 2 End With End Sub
    { "pile_set_name": "StackExchange" }
    Q: Django optimización de Querys Estoy haciendo una consulta en mis vistas de Django con diferentes palabras y me gustaría optimizarlo haciendo uso de una lista. Tengo este modelo class Personas(models.Model): id = models.AutoField(db_column='id', primary_key=True) # Field name made lowercase. nombre = models.CharField(db_column='nombre', unique=True, max_length=100) # Field name made lowercase. class Meta: managed = False db_table = 'personas' Hasta ahora estoy haciendo #siendo 'nombres' mi lista de argumentos a buscar primerNombre = nombres.pop(0) #obtengo el primer argumento a buscar answer = Personas.objects.filter(nombre__icontains = primerNombre) for nombre in nombres: answer = answer | Personas.objects.filter(nombre__icontains = nombre) #Hago una union por cada consulta Me vi obligado a hacer esto porque intenté answer = answer | Personas.objects.filter(nombre__in = nombres) Y no me funcionó, al parecer el "__in" solo funciona con números. Hay alguna forma mas elegante u optima de hacerlo? Desde ya muchísimas gracias! A: No es que __in sólo se pueda usar con números, el asunto es que la lista de nombres que estás usando no es igual al nombre que tienes registrado en la BD, lo que no se puede hacer es combinar __icontains con __in, pero si te aseguras de que los nombres en la lista nombres esten escritos igual que en la BD, tal vez pre procesandolo con .title(), .lower() o .upper(); vas a poder usar __in en tu consulta: Personas.objects.filter(nombre__in = nombres)
    { "pile_set_name": "StackExchange" }
    Q: How to join a mapping table in my query I have a query that is trying to pull out all the questions in my table. Questions Posts Topics Topic Mapping My tag tables are set up with a 3rd table for mapping the question id with the topic id. However, how do I pull the name of the topic stored in the topic table with a JOIN statement So basically I dont know how to do a JOIN statement on a table that has only got the topic id and not the topic name SELECT questions.* , posts.post , COUNT(posts.post) as total_answers , posts.votes , posts.id as post_id , posts.created , users.id as user_id , users.username, users.rep , topics.name FROM questions LEFT JOIN posts ON questions.id = posts.question_id LEFT JOIN users ON questions.user_id = users.id LEFT JOIN topics ON topic_mapping.question_id = questions.id GROUP BY questions.id Thanks a lot A: You need to join the question to the mapping table first. SELECT questions.* , posts.post , COUNT(posts.post) as total_answers , posts.votes , posts.id as post_id , posts.created , users.id as user_id , users.username, users.rep , topics.name FROM questions LEFT JOIN posts ON questions.id = posts.question_id LEFT JOIN users ON questions.user_id = users.id LEFT JOIN topic_mapping ON questions.id = topic_mapping.question_id LEFT JOIN topics ON topic_mapping.topic_id = topics.id GROUP BY questions.id
    { "pile_set_name": "StackExchange" }
    Q: OOP: Application architecture issues (Nothing serious in this question) Ones a time I've read such an example of "bad application architecture": There was a "rendering application" (browser, as far as I remember), so it was told, that having "render()" method in TagA, TagUL, TagDIV classes is really bad practice, because you'll have lots of "render-code" smeared all around. So (in this example), they adviced to have RenderA, RenderUL, RenderDIV classes that would implement rendering. And tag-objects would incapsulate those renderers. I can't understand why that's a bad practice. In this case we'll have lot's of render code smeared around Render-* objects. And, finaly, why not to have Redner-singleton with lot's of overriden methods? That sounds, at least, cheaper. What to read to understand it better? A: Will the rendering for all of these different objects be the same? If so, then it should only be implemented once, most likely in a base class. This would be a better solution than a Singleton, which serves a completely different purpose: mainly to implement a resource (notice its a resource, not a method) that should only exist once. If each implementation of render() will be different (which is most likely the case) then there is nothing wrong with them being implemented in separate objects, this is called polymorphism. What should probably be done though, is to have a class hierarchy in which the render() method is defined in the base class (most likely as abstract) and implemented in the derived classes. This effectively formalizes the interface, meaning that any class that inherits from said base class will have the render() method available and will have to implement it. If you have parts of the render code that are common, and parts that are specific to the derived classes, instead of having to duplicate the common parts in all the derived class implementations, you can use a Template Method pattern, whereby the base class method does the common parts, and orchestrates calling the derived class implementation(s). Here is a pseudo-code example in C++ class TagBase { public: void render() { // do some common stuff here doRender(); // do some more common stuff here } virtual void doRender() = 0; .... }; class TagA : public TagBase { public: virtual void doRender() { // do your specific stuff here } }; Here are a few good books: Design Patterns, Gang of Four Head First Design Patterns Head First Object Oriented Analysis and Design
    { "pile_set_name": "StackExchange" }
    Q: Calculating $\int_{-\infty}^{\infty}\frac{\sin(ax)}{x}\, dx$ using complex analysis I am going over my complex analysis lecture notes and there is an example about calculating $$\int_{-\infty}^{\infty}\frac{\sin(ax)}{x}\, dx$$ that I don't understand. The solution in the notes starts like this: Denote $C$ as the path from$-R$ to $R$ on the $x$-axis (where $R>0$ is real). Denote $C_{R}$ as the semi-circle (anti-clockwise) that goes from $R$ to $-R$. $$\int_{-R}^{R}\frac{\sin(az)}{z}\, dz=\int_{C}\frac{\sin(az)}{z}\, dz=\int_{C}\frac{e^{aiz}-e^{-aiz}}{2iz}=\frac{1}{2i}(\int_{C}\frac{e^{iaz}}{z}\, dz-\int_{C}\frac{e^{-aiz}}{z}\, dz)$$ Assume $a>0$: $$e^{iaz}=e^{iaRe^{i\theta}}=e^{iaR\cos(\theta)}-e^{-iaR\sin(\theta)}$$ Thus $$\int_{C}\frac{e^{iaz}}{z}\, dz+\int_{C_{R}}\frac{e^{iaz}}{z}\, dz=2\pi iRes_{z=0}\left(\frac{e^{iaz}}{z}\right)=2\pi i$$ The next part claims that for $R\to\infty$:$\int_{C}\frac{e^{iaz}}{z}\, dz=2\pi i$ (I understand this part) From here don't understand what going on in the notes, the sentences claim that $$\int_{C}\frac{e^{-iaz}}{z}\, dz+\int_{C_{R}}\frac{-e^{iaz}}{z}\, dz=0$$ but I think that in a similar manner that sum is $2\pi iRes_{z=0}(\frac{e^{-iaz}}{z})$ which I believe to be $2\pi i\neq0$. The next two sentences afterward say that $\lim_{R\to\infty}\int_{C}\frac{\sin(az)}{z}\, dz=\frac{1}{2i}\cdot2\pi i=\pi$ and that $$\int_{-\infty}^{\infty}\frac{\sin(ax)}{x}\, dx=\pi$$ Can someone please help me understand the part about the sum $$\int_{C}\frac{e^{-iaz}}{z}\, dz+\int_{C_{R}}\frac{-e^{iaz}}{z}\, dz$$ ? I believe that there is a mistake here, I would also appreciate help understanding the last two claims: $$\lim_{R\to\infty}\int_{C}\frac{\sin(az)}{z}\, dz=\pi$$ and that $$\int_{-\infty}^{\infty}\frac{\sin(ax)}{x}\, dx=\pi$$ EDIT: I read this couple more times, I now think that there is problem with the part after "assume $a>0$": $$e^{iaz}=e^{iaRe^{i\theta}}=e^{iaR\cos(\theta)}-e^{-iaR\sin(\theta)}$$ I think that the minus at the end should be $\cdot$ and that this is a typo in the notes, but I also think there should not be an $i$ in $e^{-iaR\sin(\theta)}$ A: When you break up the integral like that, you end up integrating through poles. That derivation makes no sense to me. Notice that $\displaystyle \frac{\sin ax}{x} = \text{Im} \ \frac{e^{iax}}{x}$. What you should do is let $\displaystyle f(z) = \frac{e^{iaz}}{z}$ and integrate around the same contour but with a small half-circle of radius $r$ about the origin. There are no poles inside of the contour, but when you let $r$ to go zero, it gives a contribution of $-i \pi$.
    { "pile_set_name": "StackExchange" }
    Q: datetime strftime %s crash on windows I have this piece of code that fails on windows, but works on linux: import datetime as dt ts = dt.datetime.now().__format__('%s') #ts == '1479831118' I look into the documentation (Python 3.5) and 'format %s' don't even exist there. How can I fix this and get the same output from Linux ? Thanks A: The code you've provided outputs current time in seconds. I may recommend to use time module. This will return the same. import time ts = str(int(time.time()))
    { "pile_set_name": "StackExchange" }
    Q: Should I use "rand % N" or "rand() / (RAND_MAX / N + 1)"? I was reading the C FAQ and found out in a question that it recommends me to use rand() / (RAND_MAX / N + 1) instead of the more popular way which is rand() % N. The reasoning for that is that when N is a low number rand() % N will only use a few bits from rand(). I tested the different approaches with N being 2 on both Windows and Linux but could not notice a difference. #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 2 int main(void) { srand(0); printf("rand() %% N:\n"); for (int i = 0; i < 40; ++i) { printf("%d ", rand() % N); } putchar('\n'); srand(0); printf("rand() / (RAND_MAX / N + 1):\n"); for (int i = 0; i < 40; ++i) { printf("%d ", rand() / (RAND_MAX / N + 1)); } putchar('\n'); return 0; } The output is this (on my gnu/linux machine): rand() % N: 1 0 1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 0 1 0 rand() / (RAND_MAX / N + 1): 1 0 1 1 1 0 0 1 0 1 0 1 0 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 1 0 1 1 1 0 1 1 0 1 0 1 Both alternatives seem perfectly random to me. It even seems like the second approach is worse than rand % N. Should I use rand() % N or rand() / (RAND_MAX / N + 1)? A: If N is a power of two, using the remainder technique is usually safe (RAND_MAX is usually a power of two minus 1, so the entire range has a power of two length). More generally, N has to divide the range of rand() in order to avoid the bias. Otherwise, you run into this problem, regardless of the quality of rand(). In short, the problem is that you're chopping that range into a number of "parts" each of length N, if N does not divide the range then the last part will not be complete. The numbers that got "cut off" from that part are therefore less likely to occur, since they have one fewer "part" they can be generated from. Unfortunately rand() / (RAND_MAX / N + 1) is also broken (in almost the same way), so the real answer is: don't use either of them. The problem as outlined above is really fundamental, there is no way to evenly distribute X different values over Y results unless Y divides X. You can fix it by rejecting a part of the random samples, to make Y divide the new X. A: There is another problem with rand() % n which is that it introduces a modulo bias. For simplicity's sake let's pretend RAND_MAX is 7 and n is 6. You want the numbers 0, 1, 2, 3, 4, 5 to appear in the random stream with equal probability. However, 0 and 1 will appear 1/4 of the time and the other numbers only 1/8th of the time because 6 and 7 have remainders 0 and 1 respectively. You should use the other method, but carefully because truncation of fractions might introduce a similar issue. If you have arc4random(), you can use arc4random_uniform() to achieve an unbiased distribution without having to be careful.
    { "pile_set_name": "StackExchange" }
    Q: ResultSet is throwing NullPointers, but next() returns true I'm trying to set up a little JDBC project and I'm running into an error which is confusing me. It's a Vocabulary and Multiple Choice Trainer. I've got the Multiple Choice running fine but a snipped I nearly copied from it just won't work for my vocabulary-part. Here it is: private void createIDList() throws ClassNotFoundException, SQLException { Class.forName("org.apache.derby.jdbc.ClientDriver"); con = DriverManager.getConnection("jdbc:derby://localhost:1527/DataBase"); stmt = con.createStatement(); String s_s = "SUB LIKE '%"; s_s = s_s + db_s.get(0) + "%' "; db_s.remove(0); while (!db_s.isEmpty()) { s_s = s_s + "OR SUB LIKE '%" + db_s.get(0) + "%' "; db_s.remove(0); } String s_t = "TOPIC LIKE '%"; s_t = s_t + db_t.get(0) + "%' "; db_t.remove(0); while (!db_t.isEmpty()) { s_t = s_t + "OR TOPIC LIKE '%" + db_t.get(0) + "%' "; db_t.remove(0); } rs = stmt.executeQuery("SELECT ID FROM APP.Voc WHERE (" + s_t + ") AND (" + s_s + ")"); while (rs.next()) { id.add(rs.getInt("ID")); //Exception is here java.lang.NullPointerException }} Here is the part which happens before: public class Session extends javax.swing.JFrame implements KeyListener { int p_r = 0; int p_w = 0; int currentID = -1; private List db_t, db_s; private List<Integer> id; Connection con; Statement stmt; ResultSet rs; String from = "V_ORIG"; String to = "V_DEST"; String ans; /** * Creates new form Session */ public Session(List p_db_t, List p_db_s) { db_t = p_db_t; db_s = p_db_s; initialize(); //--> And initialize(): private void initialize() { try { createIDList(); } catch (ClassNotFoundException ex) { Logger.getLogger(Session.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(Session.class.getName()).log(Level.SEVERE, null, ex); } Collections.shuffle(id); } I do receieve following error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at Session.createIDList(Session.java:520) at Session.initialize(Session.java:489) at Session.<init>(Session.java:45) at DB_Selector.bt_goActionPerformed(DB_Selector.java:193) at DB_Selector.access$100(DB_Selector.java:18) at DB_Selector$2.actionPerformed(DB_Selector.java:83) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6533) at javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at java.awt.Component.processEvent(Component.java:6298) at java.awt.Container.processEvent(Container.java:2236) at java.awt.Component.dispatchEventImpl(Component.java:4889) at java.awt.Container.dispatchEventImpl(Container.java:2294) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466) at java.awt.Container.dispatchEventImpl(Container.java:2280) at java.awt.Window.dispatchEventImpl(Window.java:2746) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) So much so good, but what is confusing me is following: First: Why does it enter the while(rs.next()) loop. Shouldn't rs.next() return false before running into an NullPointer? And: I can get the number of columns with rs.getMetaData().getColumnCount(). So there has to be some kind of communication between the database and the ResultSet. When I execute the Querys manually, I do get a list of ID's. Where could be the error here? If you do need more information, feel free to ask. A: Your id is null. Use id = new ArrayList<>(); while (rs.next()) { id.add(rs.getInt("ID")); }
    { "pile_set_name": "StackExchange" }
    Q: My clock code stops working at Ten O' Clock My clock code works at every other hour except ten o' clock. At every other hour, it increments minutes by 1 every time seconds is 60, but at ten o' clock, for some reason, it increments minutes by 1 every time seconds is 10. I don't know what I did wrong. Please help! package misk; public class Misk { public static void main(String[] args) throws InterruptedException { int x = 0; int sec = 0, min = 0, hour = 9; while (x == 0) { Thread.sleep(10); sec++; if (sec == 60) { sec = 0; min++; } if (min == 60) { min = 0; hour++; } if (sec < 10) { if (min < 10) { if (hour < 10) { System.out.println("0" + hour + ":0" + min + ":0" + sec); } } } if (sec > 10) { if (min < 10) { if (hour < 10) { System.out.println("0" + hour + ":0" + min + ":" + sec); } } } if (sec < 10) { if (min > 10) { if (hour < 10) { System.out.println("0" + hour + ":" + min + ":0" + sec); } } } if (sec < 10) { if (min < 10) { if (hour > 10) { System.out.println("" + hour + ":0" + min + ":0" + sec); } } } if (sec > 10) { if (min > 10) { if (hour < 10) { System.out.println("0" + hour + ":" + min + ":" + sec); } } } if (sec < 10) { if (min > 10) { if (hour > 10) { System.out.println("0" + hour + ":" + min + ":" + sec); } } } if (sec > 10) { if (min < 10) { if (hour > 10) { System.out.println("" + hour + ":0" + min + ":" + sec); } } } if (sec > 10) { if (min > 10) { if (hour > 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec == 10) { if (min == 10) { if (hour == 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec > 10) { if (min == 10) { if (hour == 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec == 10) { if (min > 10) { if (hour == 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec == 10) { if (min == 10) { if (hour > 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec > 10) { if (min > 10) { if (hour == 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec == 10) { if (min > 10) { if (hour > 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec > 10) { if (min == 10) { if (hour > 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec < 10) { if (min == 10) { if (hour == 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec == 10) { if (min < 10) { if (hour == 10) { System.out.println("" + hour + ":0" + min + ":" + sec); } } } if (sec == 10) { if (min == 10) { if (hour < 10) { System.out.println("" + hour + ":" + min + ":" + sec); } } } if (sec < 10) { if (min < 10) { if (hour == 10) { System.out.println("" + hour + ":0" + min + ":0" + sec); } } } if (sec == 10) { if (min < 10) { if (hour < 10) { System.out.println("0" + hour + ":0" + min + ":" + sec); } } } if (sec < 10) { if (min == 10) { if (hour < 10) { System.out.println("0" + hour + ":" + min + ":0" + sec); } } } if (sec == 10) { if (min < 10) { if (hour > 10) { System.out.println("" + hour + ":0" + min + ":" + sec); } } } if (sec < 10) { if (min == 10) { if (hour > 10) { System.out.println("" + hour + ":" + min + ":0" + sec); } } } if (sec > 10) { if (min == 10) { if (hour < 10) { System.out.println("0" + hour + ":" + min + ":" + sec); } } } if (sec < 10) { if (min == 10) { if (hour < 10) { System.out.println("0" + hour + ":" + min + ":0" + sec); } } } if (sec == 10) { if (min > 10) { if (hour < 10) { System.out.println("0" + hour + ":" + min + ":" + sec); } } } } } } A: First of all, your code is a mess. You need to learn how to use conditions more effectively, also learn about formatting. You can easily add '0' before any digit if it isn't a '2 digit number'. System.out.println(String.format("%02d %02d %02d", hour, minute, second)); Your code doesn't work at ten o' clock because all of your conditions are 'hour > 10' or 'hour < 10', and both of those are false when hour == 10.
    { "pile_set_name": "StackExchange" }
    Q: Google Chrome extension displaying json information in html In this javascript file, I want to get the json information from a json file (config.json) that is declared in the content scripts of manifest.json. I'm sending that json file to the HTML file under the id "help", and upon click of the button the currently written html should change. Any ideas as to why this isn't working? Thank you! document.addEventListener('DOMContentLoaded', function () { document.querySelector('button').addEventListener('click', main); }); function main() { var xhr = new HMLHttpRequest(); xhr.open("GET", chrome.extension.URL("config.json"), true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { document.getElementById("help").innerHTML = JSON.parse(xhr.responseText); } } xhr.send(); } A: there is typo in your code and you have not declared config.json as web accessible resource var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.status == 200 && xmlhttp.readyState == 4) { console.log(xmlhttp.responseText) document.getElementById("help").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", chrome.extension.getURL("config.json"), true); xmlhttp.send(); And in manifest add "web_accessible_resources": ["config.json"]
    { "pile_set_name": "StackExchange" }
    Q: How to prevent knitr from printing ## and matrix indices/row numbers? Lets say I have a matrix where there's an id column that doesn't go up by 1 with each row. m <- matrix(c(1, "a", "c", 5, "g", "c", 4, "b", "c", 9, "g", "a"), ncol=3, byrow=TRUE) colnames(m) <- c("id", "class", "type") I've tried renaming the rows with rownames(m) <- NULL or rownames(m) <- c() but I always end up with an output that has the row numbers on the very left: id class type [1,] "1" "a" "c" [2,] "5" "g" "c" [3,] "4" "b" "c" [4,] "9" "g" "a" Further more, if I print to PDF in knitr, I get ## running down the side: ## id class type ## [1,] "1" "a" "c" ## [2,] "5" "g" "c" ## [3,] "4" "b" "c" ## [4,] "9" "g" "a" I would like to print a pdf that just has the data that I entered into the matrix: id class type "1" "a" "c" "5" "g" "c" "4" "b" "c" "9" "g" "a" A: You can use kable from the knitr package. m <- matrix( c(1, "a", "c", 5, "g", "c", 4, "b", "c", 9, "g", "a"), ncol=3, byrow=TRUE ) colnames(m) <- c("id", "class", "type") knitr::kable(m) # |id |class |type | # |:--|:-----|:----| # |1 |a |c | # |5 |g |c | # |4 |b |c | # |9 |g |a | You could also read up on the excellent kableExtra package here, which will allow you some great formatting options. N.B. My initial answer included casting as a data frame, which remains my usual workflow when creating tables. However as was pointed out, kable will happily accept a matrix as input.
    { "pile_set_name": "StackExchange" }
    Q: Editing a Wizard multistep form after save - Wicked Gem / Rails I've been going round in circles all day with this. I have a large multi-step form using the Wicked gem and Ruby on Rails. It works perfectly but I can't figure out how to to get back into the form to edit individual entries. Iim trying to make the ability to go into the client show page, click an individual client and then from there go back into the quote to edit and update it. As the Wicked gem only seems to work with show and update actions, if I try to build a standard edit action Wicked expects to be on a step therefore doesn't work. I read the I would have to factor the edit action into my show/update actions but I'm having difficulties. Any help would be great thanks! Clients Controller: class ClientsController < ApplicationController before_action :authenticate_user!, only: [:index, :show, :edit] before_action :set_client, only: [:edit, :show, :update] def index @clients = Client.order('created_at DESC').paginate(page: params[:page], per_page: 10) end def show; end def new @client = Client.new end def edit; end def update if @client.update_attributes(client_params) redirect_to client_quotes_path flash[:success] = 'Client successfully updated' else render 'edit' end render_wizard @client end # After client is completed: def create @client = Client.new(client_params) if @client.valid? @client.save session[:current_user_id] = @client.id ClientMailer.new_client(@client).deliver redirect_to quotes_path else flash[:alert] = 'Sorry, there was a problem with your message. Please contact us directly at ...' render :new end end private def set_client @client = Client.find(params[:id]) end def client_params params.require(:client).permit(:first_name, :last_name, :title, :email, :email_confirmation, :phone, :time, :reminder, :ref_number, :day, :note, :logs_reminder) end end Quotes Controller: class QuotesController < ApplicationController include Wicked::Wizard before_action :set_client, only: [:show, :update, :quote_success] steps :profile, :employment, :general_questions, :indemnity_details, :declarations def show @client.build_doctor unless @client.doctor.present? @client.build_dentist unless @client.dentist.present? @client.old_insurers.build @client.practice_addresses.build render_wizard end def update @client.update(client_params) render_wizard @client end def quote_success; end private def set_client current_user = Client.find_by_id(session[:current_user_id]) @client = current_user end # After full quote form is completed: def finish_wizard_path if @client.valid? ClientMailer.new_quote(@client).deliver ClientMailer.new_quote_user_message(@client).deliver end quote_success_path end end def client_params params.require(:client).permit(:name, :email, :email_confirmation, :phone, :date_required, :title, :first_name, :last_name, :date_of_birth, :nationality, :reg_body, :reg_date, :reg_type, :reg_number, :qual_place, :qual_year, :post_grad, :membership ... Routes: Rails.application.routes.draw do devise_for :users root 'clients#new' get 'client', to: 'clients#new', as: 'client' post 'client', to: 'clients#create' get '/client_quotes', to: 'clients#index', as: 'client_quotes' get '/client_quotes/:id', to: 'clients#show', as: 'client_quote' get '/client_quotes/:id/edit', to: 'clients#edit', as: 'edit_client_quote' patch '/client_quotes/:id', to: 'clients#update' put '/client_quotes/:id', to: 'clients#update' resources :quotes, only: [:index, :show, :update, :quote_success] get 'quote-success' => 'quotes#quote_success' devise_scope :user do get '/login' => 'devise/sessions#new' end end A: My solution to this in the end was rather than have the edit form as a multi step wizard, I've joined the form data together in a separate view page and got a traditional route to it as you mention. Not perfect but does the job!
    { "pile_set_name": "StackExchange" }
    Q: Putting/Getting compressed data in SQLite with F# I am attempting to port an existing project of mine (a web scraper) from Python to F#, in order to learn F#. A component of the program saves compresses large strings (raw HTML) using LZMA, and stores it in SQLite in a makeshift key value table. The HTML string should always be unicode. Because I am an F# beginner and this requires a lot of .NET interop, I am very confused as to how to accomplish this. I would like to know how to do this properly in F#, and using LZMA instead of GZip. Edit I had difficulty finding an LZMA2 compatible .NET library, as LZMA-SDK uses LZMA1. This would not have been compatible with my existing data compressed using LZMA2. Therefore, along with help from comments I went ahead and implemented this using Gzip. A: This uses Gzip for compression and is compatible with the gzip.compress/gzip.decompress functions in Python 3.5. #if INTERACTIVE #r "../packages/System.Data.SQLite.Core/lib/net46/System.Data.SQLite.dll" #endif open System.IO open System.IO.Compression open System.Data.SQLite let compressString (s:string) = let bs = System.Text.Encoding.UTF8.GetBytes(s) use outStream = new MemoryStream() use gzOutStream = new GZipStream(outStream, CompressionMode.Compress, false) gzOutStream.Write(bs, 0, bs.Length) outStream.ToArray() let decompressString (bs:byte[]) = use newInStream = new MemoryStream(bs) use gzOutStream = new GZipStream(newInStream, CompressionMode.Decompress, false) use sr = new StreamReader(gzOutStream) sr.ReadToEnd() let insert dbc (key:string) (value:string) = let compressed = compressString value let cmd = new SQLiteCommand("INSERT into kvt (key, value) VALUES (@key, @value)", dbc) cmd.Parameters.Add(new SQLiteParameter("@key", key)) |> ignore cmd.Parameters.Add(new SQLiteParameter("@value", compressed)) |> ignore let res = cmd.ExecuteNonQuery() res let fetch dbc (key:string) = let cmd = new SQLiteCommand("SELECT value FROM kvt WHERE key = @key", dbc) cmd.Parameters.Add(new SQLiteParameter("@key", key)) |> ignore let reader = cmd.ExecuteReader() reader.Read() |> ignore let compressed = unbox<byte[]> reader.["value"] decompressString compressed let create() = System.Data.SQLite.SQLiteConnection.CreateFile("mydb.sqlite") let dbc = new SQLiteConnection("Data Source=mydb.sqlite;Version=3;") dbc.Open() let cmd = new SQLiteCommand("CREATE TABLE kvt (key TEXT PRIMARY KEY, value BLOB)", dbc) let res = cmd.ExecuteNonQuery() dbc
    { "pile_set_name": "StackExchange" }
    Q: ExpressJs Compatibility with NodeJs Version I am trying to find to see if expressjs 4 can support Nodejs 10.15.3 ( Lts) version. Is there any compatibility matrix that i can look into before deciding versions to choose? A: If you check out express/package.json you can see that express needs node v0.10.0 or newer. So yes, Express.js v4 is supporting Node.js v10.15.3.
    { "pile_set_name": "StackExchange" }
    Q: Telerik MVC Grid does not display data I am using version 2011.2.914 of the controls. Whenever I try to bind data from my controller to a view, I can't get the data inside the collection to display on the grid. I get the "No records to display" message from the grid. I want to point out that if I am not using the Telerik grid, the data comes out fine (see below): Controller without Telerik Grid IEnumerable<YeagerTechWcfService.Customer> customerList = db.GetCustomers(); return View("Index", customerList); View @model IEnumerable<YeagerTech.YeagerTechWcfService.Customer> @{ ViewBag.Title = "Customer Index"; } <h2>Customer Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> Email </th> <th> Company </th> <th> FirstName </th> <th> LastName </th> <th> Address1 </th> <th> Address2 </th> <th> City </th> <th> State </th> <th> Zip </th> <th> HomePhone </th> <th> CellPhone </th> <th> Website </th> <th> IMAddress </th> <th> CreatedDate </th> <th> UpdatedDate </th> <th> </th> </tr> @if (ViewData.Model != null) { foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Email) </td> <td> @Html.DisplayFor(modelItem => item.Company) </td> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.LastName) </td> <td> @Html.DisplayFor(modelItem => item.Address1) </td> <td> @Html.DisplayFor(modelItem => item.Address2) </td> <td> @Html.DisplayFor(modelItem => item.City) </td> <td> @Html.DisplayFor(modelItem => item.State) </td> <td> @Html.DisplayFor(modelItem => item.Zip) </td> <td> @Html.DisplayFor(modelItem => item.HomePhone) </td> <td> @Html.DisplayFor(modelItem => item.CellPhone) </td> <td> @Html.DisplayFor(modelItem => item.Website) </td> <td> @Html.DisplayFor(modelItem => item.IMAddress) </td> <td> @Html.DisplayFor(modelItem => item.CreatedDate) </td> <td> @Html.DisplayFor(modelItem => item.UpdatedDate) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.CustomerID }) | @Html.ActionLink("Details", "Details", new { id = item.CustomerID }) </td> </tr> } } </table> I have tried ServerSide and Ajax Binding. Both don't work. I have searched the Telerik site and the web and can't find out what is missing. What do I need to do in order to resolve this and get the data in my grid? Here is the code in my Customer controller for the Ajax binding (which is what I really want). Upon return of getting the data, I have an image file that I saved where the data is in the customerList collection (there is no option to attach any files in StackOverflow, so I can't show you). When the View is being rendered, I captured data while debugging for several objects. When cycling through the grid during the binding, I captured data in another file. Controller using Telerik Grid: using Telerik.Web.Mvc; public class CustomerController : Controller { [GridAction] public ActionResult Index() { IEnumerable<YeagerTechWcfService.Customer> customerList = db.GetCustomers(); return View(new GridModel<YeagerTechWcfService.Customer> { Data = customerList }); } } Below, is the code in my associated View. btw, all the bound columns have intellisense that pop up for the columns in my model. This is for the Index action within the Customer controller. @model Telerik.Web.Mvc.GridModel<YeagerTech.YeagerTechWcfService.Customer> @{ ViewBag.Title = "Customer Index"; } <h2> Customer Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> @(Html.Telerik().Grid<YeagerTech.YeagerTechWcfService.Customer>() .Name("Customers") .Columns(columns => { columns.Bound(o => o.Email); columns.Bound(o => o.Company); columns.Bound(o => o.FirstName); columns.Bound(o => o.LastName); columns.Bound(o => o.Address1); columns.Bound(o => o.Address2); columns.Bound(o => o.City); columns.Bound(o => o.State); columns.Bound(o => o.Zip); columns.Bound(o => o.HomePhone); columns.Bound(o => o.CellPhone); columns.Bound(o => o.Website); columns.Bound(o => o.IMAddress); columns.Bound(o => o.CreatedDate).Format("{0:MM/dd/yyyy}"); columns.Bound(o => o.UpdatedDate).Format("{0:MM/dd/yyyy}"); }).DataBinding(dataBinding => dataBinding.Ajax().Select("Index", "Customer")) .Pageable() .Sortable() .Scrollable() .Resizable(resizing => resizing.Columns(true)) .Filterable()) </table> A: Maybe there's a conflic with your Index action method since that you have a View that is referenced to it. The first test to do is to show your grid without playing with Ajax or anything else. Try this to initialize your grid when your View Index is build. Notice the Model.Data that i'm using in the Grid constructor: @(Html.Telerik().Grid<YeagerTech.YeagerTechWcfService.Customer>(Model.Data) .Name("Customers") .Columns(columns => { columns.Bound(o => o.Email); columns.Bound(o => o.Company); ... })) If it work, then you should try to create another Action method with another name. In my projects, i do this: [GridAction] public ActionResult GetYeagerTechGridData() { IEnumerable<YeagerTechWcfService.Customer> customerList = db.GetCustomers(); return View(new GridModel<YeagerTechWcfService.Customer> { Data = customerList }); } and use your grid that way: @(Html.Telerik().Grid<YeagerTech.YeagerTechWcfService.Customer>() .Name("Customers") .Columns(columns => { columns.Bound(o => o.Email); columns.Bound(o => o.Company); ... }) .DataBinding(dataBinding => dataBinding.Ajax().Select("GetYeagerTechGridData", "Customer")))
    { "pile_set_name": "StackExchange" }
    Q: Recurrence relation and initial conditions for the number of ways to build a stack of height n cm using blocks. I'm working on a problem, and I just want to make sure that my work is correct. The problem goes like this: Suppose that we have a collection of building blocks consisting of red, blue, and green blocks of height 1 cm and yellow blocks of height 3 cm. Write a recurrence relation and initial conditions for the number of ways to build a stack of height n cm using these blocks. I let Sn be the total number of ways, and this is my solution: Sn = Sn-1 + Sn-1 + Sn-1 + Sn-3 Sn = 3Sn-1 + Sn-3 And with our initial conditions: S0 = 1 S1 = 3 (blue or red or green) S2 = 9 Sn = 3(9) + 1 = 28. A: Yes your answer is correct. I've done this one before! Similar answer here: https://answers.yahoo.com/question/index?qid=20160419091913AAPO82O
    { "pile_set_name": "StackExchange" }
    Q: Use JSON file to populate a listview I have the following code which retrieves the JSON file: public class GetJSON extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { //Running in background try { httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json"); // Depends on your web service httppost.setHeader("Content-type", "application/json"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { Log.i("TEST", e.toString()); // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} } return null; } @Override protected void onPreExecute() { //Activity is on progress } @Override protected void onPostExecute(Void v) { //Activity is done... Toast.makeText(getActivity(), result, 2000).show(); int k = 0; try { JSONArray jsonall = new JSONArray(); jsonArray = new JSONArray(result); for(int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value k++; jsonall.put(jsonObj); sId = new String[jsonall.length()]; sType = new String[jsonall.length()]; sData = new String[jsonall.length()]; for (int m = 0 ; m < jsonall.length(); m++){ //4 entries made JSONObject c = jsonall.getJSONObject(m); String id = c.getString("id"); String type = c.getString("type"); String data = c.getString("data"); sId[m] = id; sType[m] = type; sData[m] = data; } } } Toast.makeText(getActivity(), String.valueOf(k), 2000).show(); } catch (JSONException e) { e.printStackTrace(); } } } On the onPostExecute() function I am able to de-serialize the data, in this case by TYPE. I have the following code for the CustomAdapter public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> { Context context; int layoutResourceId; ArrayList<SetRows> data=new ArrayList<SetRows>(); public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) { super(context, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.context = context; this.data = data; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; ImageHolder holder = null; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new ImageHolder(); holder.tID = (TextView)row.findViewById(R.id.tvID); holder.tType = (TextView)row.findViewById(R.id.tvType); holder.tData = (TextView)row.findViewById(R.id.tvData); row.setTag(holder); } else { holder = (ImageHolder)row.getTag(); } SetRows myImage = data.get(position); holder.tID.setText(myImage.id); holder.tType.setText(myImage.type); holder.tData.setText(myImage.data); return row; } static class ImageHolder { TextView tID; TextView tType; TextView tData; } } My SetRows code is: public class SetRows { String id; String type; String data; public String getData () { return data; } public void setData (String data) { this.data = data; } public String getID () { return id; } public void setID (String id) { this.id = id; } public String getType () { return type; } public void setType (String type) { this.type = type; } public SetRows(String id, String type, String data) { super(); this.id = "ID: \t" + id; this.type = "TYPE: \t" + type; this.data = "DATA: \t" + data; } } My XML file for the Layout file is: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ListView android:id="@+id/lvAll" android:layout_height="match_parent" android:layout_width="match_parent" /> </RelativeLayout> The custom layout for the ListView is: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="@dimen/list_row_pad" android:background="@drawable/list_row_bg" > <TextView android:id="@+id/tvID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="@dimen/margin_left_tv" android:text="ID: " android:textStyle="bold" android:textColor="#FFFFFF" /> <TextView android:id="@+id/tvType" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tvID" android:layout_alignLeft="@+id/tvID" android:text="TYPE: " android:textStyle="bold" android:textColor="#FFFFFF" /> <TextView android:id="@+id/tvData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tvType" android:layout_alignLeft="@+id/tvType" android:text="DATA: " android:textStyle="bold" android:textColor="#FFFFFF" /> </RelativeLayout> I want to display the data like this in a ListView from the JSON file from my server: I think I have all the information needed. I just need to know, now, how to display the information. All help is greatly appreciated. Thanks! UPDATE: The following code is working, but it's entering multiple entries for each: public class GetJSON extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { //Running in background try { httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json"); // Depends on your web service httppost.setHeader("Content-type", "application/json"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { Log.i("TEST", e.toString()); // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} } return null; } @Override protected void onPreExecute() { //Activity is on progress } @Override protected void onPostExecute(Void v) { //Activity is done... //Toast.makeText(getActivity(), result, 2000).show(); int k = 0; try { JSONArray jsonall = new JSONArray(); jsonArray = new JSONArray(result); for(int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value k++; jsonall.put(jsonObj); sId = new String[jsonall.length()]; sType = new String[jsonall.length()]; sData = new String[jsonall.length()]; for (int m = 0 ; m < jsonall.length(); m++){ JSONObject c = jsonall.getJSONObject(m); String id = c.getString("id"); String type = c.getString("type"); String data = c.getString("data"); //sId[m] = id; //sType[m] = type; //sData[m] = data; contents.add(new SetRows(id, type, data)); } } adapter = new SetRowsCustomAdapter(getActivity(), R.layout.listrow, contents); lAll.setAdapter(adapter); lAll.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent myIntent = new Intent(getActivity(), DisplayWeb.class); startActivityForResult(myIntent, 0); } }); } //Toast.makeText(getActivity(), String.valueOf(k), 2000).show(); } catch (JSONException e) { e.printStackTrace(); } } } The duplicate shows up as like this: A: Sublacss ListActivy and create a layout that contains a ListView with id @android:id/list put inside this subclass you AsyncTask and execute it in the on create. when onPostExecute is called, after you parse the JSON, create an instance of SetRowsCustomAdapter call getListView().setAdapter(adapterInstance). @Override protected void onPostExecute(Void v) { ArrayList<SetRows> contents = new ArrayList<SetRows>(); // other code //instead of those //sId[m] = id; //sType[m] = type; //sData[m] = data; //add contents.add(new SetRows(id, type, data)); } Edit 2: You have two duplicates entry because you have an unuseful for loop (the innere one). Imo your code should look like: for(int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObj = (JSONObject)jsonArray.get(i); if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { String id = jsonObj.getString("id"); String type = jsonObj.getString("type"); String data = jsonObj.getString("data"); contents.add(new SetRows(id, type, data)); } } // the other stuff ps. check for typo
    { "pile_set_name": "StackExchange" }
    Q: Are external objects only available via Lightning Connect now? I dabbled around with External Data Sources a while back with this public Northwind OData data feed. I decided to take another look at it for a project we are working on, but it appears Salesforce has changed this feature so it no longer works with OData and external objects. The documentation now talks more about Files Connect and Lightning Connect, and doesn't say much of anything at all on how to use a Simple URL to connect to an external OData data source for defining External Objects. When I look at the screen, the page still makes mention of connecting to third-party databases and content systems: Has Salesforce removed the ability to connect to an OData Data Source using the out-of-the-box External Data Source feature? A: Simple URL is used for Files Connect and is not related to what was called Lightning Connect (now called Salesforce Connect). As for whether Salesforce removed or crippled the feature, the answer is no. Salesforce Connect has ALWAYS been a paid add on. It is available for free on Developer Edition orgs to try out and see if it suits your needs, so maybe that's where you used it.
    { "pile_set_name": "StackExchange" }
    Q: MvxImageViewLoader binding not working I use MvxImageViewLoader in pretty simple situation. On ViewDidLoad: var pnlBackImage = new UIImageView(new RectangleF(0, 0, pnlBack.Frame.Width, pnlBack.Frame.Height)); Add(pnlBackImage); pnlBackImageLoader = new MvxImageViewLoader(() => pnlBackImage); ... set.Bind(pnlBackImageLoader).To(x => x.UserBackgroundUrl); where UserBackgroundUrl is a common string property. But on set.Apply() I see the following in my log and image is not loading: 2013-06-24 13:51:26.999 SPBTouch[446:21b03] MvxBind: Error: 2.78 Problem seen during binding execution for from UserBackgroundUrl to ImageUrl - problem TargetInvocationException: Exception has been thrown by the target of an invocation. at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x000d9] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:236 at System.Reflection.MonoProperty.SetValue (System.Object obj, System.Object value, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] index, System.Globalization.CultureInfo culture) [0x00064] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoProperty.cs:353 at System.Reflection.PropertyInfo.SetValue (System.Object obj, System.Object value, System.Object[] index) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/PropertyInfo.cs:93 at Cirrious.MvvmCross.Binding.Bindings.Target.MvxPropertyInfoTargetBinding.SetValue (System.Object value) [0x00000] in <filename unknown>:0 at Cirrious.MvvmCross.Binding.Bindings.MvxFullBinding.UpdateTargetFromSource (Boolean isAvailable, System.Object value) [0x00000] in <filename unknown>:0 InnerException was NullReferenceException: Object reference not set to an instance of an object at Cirrious.MvvmCross.Binding.Views.MvxBaseImageViewLoader`1[MonoTouch.UIKit.UIImage].set_ImageUrl (System.String value) [0x00000] in <filename unknown>:0 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x000c0] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:228 I've even defined the image loader and even the image panel as the view fields, but there is still no luck. What can cause that problem? Thank you. A: The inner exception error you've listed is: NullReferenceException: Object reference not set to an instance of an object at Cirrious.MvvmCross.Binding.Views.MvxBaseImageViewLoader`1[MonoTouch.UIKit.UIImage].set_ImageUrl (System.String value) [0x00000] in :0 I guess the thing that would cause a NullReferenceException in the set of: public string ImageUrl { get { return _imageHelper.ImageUrl; } set { _imageHelper.ImageUrl = value; } } is if _imageHelper is null Looking in MvxBaseImageViewLoader.cs#L31 this can happen if this error message is displayed Unable to resolve the image helper - have you referenced and called EnsureLoaded on the DownloadCache plugin? Is this error message displayed? If so, is the DownloadCache plugin (and it's dependent plugin File) loaded in your application? If this doesn't help, try comparing your app so some of the apps in N+1. Successful use of the image views is covered in several of N+1 videos - http://mvvmcross.wordpress.com/ - e.g. N=2 or N=3 A: I come here when I had the same error (exception) mentioned in this question by following the tutorial on MvvmCross CollectionView example. I found that you get this error if you missed registering/installing your plugins. I resolved the error by installing the following plugins: Install-Package MvvmCross.ITSparta.Plugin.DownloadCache Install-Package MvvmCross.ITSparta.Plugin.File When these plugins are installed, new files are created in your UI Project (iOS/Android) and these plugins are registered. Thus, you would not get this error.
    { "pile_set_name": "StackExchange" }
    Q: How to throw meaningful data in exceptions? I would like to throw exceptions with meaningful explanation (socket handle, process id, network interface index, ...) ! I thought of using variable arguments worked fine but lately I figured out it's impossible to extend the class in order to implement other exception types. So I figured out using an std::ostreamstring as a an internal buffer to deal with formatting ... but doesn't compile! I guess it has something to deal with copy constructors. Anyhow here is my piece of code: class Exception: public std::exception { public: Exception(const char *fmt, ...); Exception(const char *fname, const char *funcname, int line, const char *fmt, ...); //std::ostringstream &Get() { return os_ ; } ~Exception() throw(); virtual const char *what() const throw(); protected: char err_msg_[ERRBUFSIZ]; //std::ostringstream os_; }; The variable argumens constructor can't be inherited from! this is why I thought of std::ostringstream! Any advice on how to implement such approach ? A: It is a bit awkward to pass ... arguments, but possible. You need first to convert them to va_list. So, for your derived class to be able to pass the format and the arguments to its base class something like the following can be done: class Exception: public std::exception { public: Exception(const char *fmt, ...) { va_list ap; va_start(ap, fmt); this->init(fmt, ap); va_end(ap); } virtual const char *what() const throw(); protected: Exception(); // for use from derived class's ctor void init(char const* fmt, va_list, ap) { vsnprintf(err_msg_, sizeof err_msg_, fmt, ap); } char err_msg_[ERRBUFSIZ]; }; struct Exception2 : Exception { Exception2(const char *fmt, ...) { va_list ap; va_start(ap, fmt); this->init(fmt, ap); va_end(ap); } };
    { "pile_set_name": "StackExchange" }
    Q: How do I find where a line intersects itself? I am using Python 3.7 with Shapely and GeoPandas. I have a big line of 181,000 points, and would like to find all the points where the line intersects itself. It does so a lot. I don't need a new point at the precise intersection, just one of the existing points which is closest. I have been writing code to loop through the points and find other points close by using. for i,point in gdf.iterrows(): gdf[gdf.geometry.intersects(point.buffer(10) == True].index.tolist() Where gdf is a geopandas GeoDataFrame where each row is a point from the line. (eg it looks like this:) geometry 0 POINT (-47.91000 -15.78000) 1 POINT (-47.92000 -15.78000) But surely there is a way to do this using existing functions? My way is very slow and records many duplicates at each intersection, so will require more code to reduce each intersection to one point. A: Here's how I did it slice the first feature make a unary_union of the rest of the feature do line intersections using shapely you'll get one point of intersection. now repeat for the second, third, fourth, and so on. here's the example. suppose a geodataframe (gdf) of 6 lines like this GeoJSON then, apply this code to the gdf. This is returning the geometry of the intersections # the points of intersections will be appended here points=[] for i in gdf.id: print(i) # check overlap feature = gdf[gdf['id']==i]['geometry'][i] overlap_feature = gdf[gdf['id']!=i]['geometry'].unary_union intersects = feature.intersection(overlap_feature) points.append(intersects) points now, make a GeoDataFrame out of the points intersections = gpd.GeoDataFrame( {"id": [n for n,i in enumerate(points)]}, crs={'init':'epsg:4326'}, geometry=points ) here's the plot of the result import matplotlib.pyplot as plt fig,ax = plt.subplots() intersections.plot(color="r", ax=ax,zorder=2) gdf.plot(ax=ax,zorder=1) the intersections data frame has Point and MultiPoint geometries. But there's a problem here... the points are intersecting. here's how to delete the overlapping points from shapely.geometry import Point # convert the multipoints into points intersections['ispoint'] = intersections['geometry'].apply(lambda x: isinstance(x, Point)) #backup is_point = intersections[intersections.ispoint] #check if it's point was_multipoint = intersections[~intersections.ispoint].explode().reset_index() # converting the multipoint into points # now appending both data frames. now_point = is_point.append(was_multipoint) now_point.reset_index(inplace=True) now_point = now_point[['id','geometry']] now_point['id'] = now_point.index # ok, now_point contains all intersections, but the points are still overlapping each other # delete overlapping points intersections2 = now_point.copy() points=[] n= 0 for i in intersections2.id: # check overlap feature = intersections2[intersections2['id']==i]['geometry'][i] overlap_feature = intersections2[intersections2['id']!=i]['geometry'].unary_union # IF the point is intersecting with other points, delete the point! if feature.intersects(overlap_feature): intersections2.drop(i, inplace=True) print(n, feature.intersects(overlap_feature)) n+=1 intersections2 the result is the same, but the intersection points won't overlap each other. here's the plot, and there are 6 row of dataframe, I checked. edit: note, using `unary_union` means that if we have a large dataset, this may be RAM consuming. A: This splits each line at each vertice and then use crosses on all combinations of split lines: import geopandas as gpd from shapely.geometry import LineString from itertools import combinations from collections import defaultdict df = gpd.read_file('/home/bera/Desktop/crossing_lines.shp') def findcrossings(line1, line2): crossings = [] if line1.crosses(line2): crossings.append(line1.intersection(line2)) return crossings results = defaultdict(list) indices = df.index.to_list() for i in indices: #For each row/feature/line line = df.geometry.iloc[i] #Fetch the geometry verts = [v for v in line.coords] #List all vertices segments = [] for p1, p2 in zip(verts, verts[1:]): #For each pair of vertices (x1,y1) , (x2,y2) segment = LineString([p1, p2]) #create a line segment segments.append(segment) for l1, l2 in combinations(segments,2): #For all combinations of segments res = findcrossings(l1, l2) #Find crossings if len(res)>0: results[i].extend(res) #results #defaultdict(list, # {0: [<shapely.geometry.point.Point at 0x7f5c83f356d0>, # <shapely.geometry.point.Point at 0x7f5c83f35990>, # <shapely.geometry.point.Point at 0x7f5c83f2be50>, # <shapely.geometry.point.Point at 0x7f5c83f2b650>]}) #Export results #gdf = gpd.GeoDataFrame(geometry=results[0]) #gdf.to_file('/home/bera/Desktop/crossing_lines_self_intersections.shp')
    { "pile_set_name": "StackExchange" }
    Q: Initializing struct array with arrays as elements of the struct I am trying to initialize an array of structs that contain an array. Looking at this and this, I think a pretty reasonable attempt is this: struct Score_t{ int * dice; int numDice; int value; }; struct Score_t Scores[NUMSCORES] = { [0]={{0,0,0},3,1000}, [1]={{1,1,1},3,200}, [2]={{2,2,2},3,300}, [3]={{3,3,3},3,400}, [4]={{4,4,4},3,500}, [5]={{5,5,5},3,600}, [6]={{0},3,100}, [7]={{4},3,50} }; However I can't get this to compile. Do you have any ways to get this done? Edit: Forgot the error message: (snipped) [5]={{5,5,5},3,600}, ^ greed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default] greed.c:79:2: warning: initialization makes pointer from integer without a cast [enabled by default] greed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default] greed.c:79:2: warning: excess elements in scalar initializer [enabled by default] greed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default] greed.c:79:2: warning: excess elements in scalar initializer [enabled by default] greed.c:79:2: warning: (near initialization for ‘Scores[5].dice’) [enabled by default] greed.c:80:2: warning: braces around scalar initializer [enabled by default] A: int * can't be initialized with { } (not match) So change to like this. struct Score_t Scores[NUMSCORES] = { [0]={(int[]){0,0,0},3,1000}, [1]={(int[]){1,1,1},3,200}, [2]={(int[]){2,2,2},3,300}, [3]={(int[]){3,3,3},3,400}, [4]={(int[]){4,4,4},3,500}, [5]={(int[]){5,5,5},3,600}, [6]={(int[]){0},3,100}, //It doesn't know the number of elements [7]={(int[]){4},3,50} //change to [7]={(int[3]){4},3,50} or [7]={(int[]){4},1,50} };
    { "pile_set_name": "StackExchange" }
    Q: Altering the data on diagrams I am working on a statistics project and i came across one tiny issue. I have to work out a tactic for bidding on horse racing. We were given a set of 300 races with data such as the time, favorable odds, and if the favorable won or not. So i thought I could order the table in ascending order in relation to the time, and see how are the wins spread during the day. So I had games starting from 13:35 to 21:20, so I divided the time into 1 hour chunks (except the 1st chunk which is only 25 min, and last chunk which is only 20 min) and related wins to those chunks respectively. Then I added up all the wins inside each chunk, and presented that on the chart, the chart looks like this: It works with my tactic which is to play between 14:00 and 16:00 cause then the bookie starts making odds as favorable to himself and starts robbing you from your earned money he just gave you. The thing is that on the bottom it says 2, 4, 6, 8.. but I want to write 13:35-14:00, 14:00 - 15:00 etc.. How can I do that, given that the code I used is that: > plot(chunksVector, type="o", col="blue", xlab="Time", ylab="Wins") How can I do this? I've been struggling with this one for some time now. Is there any way to alter the code? P.S: "chunks" is just the name i gave to separated wins based on 1 hour distance. So i basically have a chink13.35_14.00, chunk14.00_15.00, chunk15.00_16.00 etc.. What I want to alter is only the X axis. I want it to look like this: A: the quick answer is: plot(chunksVector, type="o", col="blue", xlab="Time", ylab="Wins", xaxt="n") axis(1, at=c(2,4,6,8), labels=c('14:00', '16:00', '18:00', '20:00')) There are probably a few other ways messing about with time-series packages?
    { "pile_set_name": "StackExchange" }
    Q: Fill an ASP.NET Form from a Word Document It's possible to fill an ASP.NET Form (MVC 4) reading (or importing) a Word Document? Update We have an standard document for our pricing agreements and quotations, and what I would like implement is read that document (maybe later they want to upload the document to a dropbox account or similar service) and fill the form to create a new project in the application. The document contains the same titles only change the items, prices, etc. Thanks for your time Regards A: You can do it in two ways: Client side a) Using a converter (An executable) b) Using component (i.g. ActiveX...) Server side Server side processing of MS Word document is much easier to handle for both client and you. After document was uploaded to a temporary folder on your server you can easily get access to it and since the format is unique and known to you, data could be extracted easily. You can then store it to database or show it on a filled form to user while any missing data could added by client in that form. There are many code samples available for reading MS Word documents on the web.
    { "pile_set_name": "StackExchange" }
    Q: Rails reading from settings.yml Hi is it possible to read from an controller the settings yml? Im using rails 4.2.0 I want to store some global information in the settings.yml to display those in the view at the moment I try this way: settingsfile = File.read(Rails.root + "./config/settings.yml") settingsfile = YAML.load(settingsfile) settingsfile["default"] works but when I want to go deeper settingsfile["default"]["info"] its empty Yml File default: supported_languages: de: Deutsch fr: Francais en: English it: Italiano sv: Svenska pt: Português nl: Nederlands es: Español production: info: version: 2.0.0 datum: 11.05.2015 A: without using gem..you can use something like .. your dev/config/email.yml development: :address: smtp.service.com :port: 25 :user_name: [email protected] :password: mikepassword production: :address: smtp.gmail.com :port: 587 :authentication: plain :user_name: [email protected] :password: mikepassword :enable_starttls_auto: true you can load this yml file simply like.... email_settings = YAML::load(File.open("#{Rails.root.to_s}/config/email.yml")) ActionMailer::Base.smtp_settings = email_settings[Rails.env] unless email_settings[Rails.env].nil? also you may use - Rails::Application.config_for(:email) as shown in the documentation for Rails 4+ onwards. A: You might try: @settingsvariable = Settings.default.supported_languages.de This approach worked in my app.
    { "pile_set_name": "StackExchange" }
    Q: What is a run on the pound? From the news today, it mentions that Jeremy Corbyn and the Labour Party is preparing to deal with a run on the pound. What is a run on the pound? Why is it making news headlines? Why does Jeremy Corbyn plan for this eventuality happening? The article says that it's where investors sell sterling en masse, but what can the Labour Government do in that situation? A: A "run on the pound" occurs when financial traders believe that it is not in their interest to own "pounds", but an alternative like dollars or euros, or even gold, is a better currency to own. They will then try to sell pounds, and buy the other currencies. In order to sell quickly they reduce the price at which they are selling pounds. As this happens we say that he value of the pound has dropped. Other investors seeing this drop in price may then try to sell off their pounds very quickly, cutting the price a lot. If everyone is trying to sell, then the value of the pound can drop rapidly against other currencies. This has several consequences. It means that it costs more for a British company to buy things from abroad. The price of imported goods and raw materials goes up. This makes things more expensive. It makes it more costly to travel abroad. On the other hand, if you are making something in Britain and selling it abroad, it makes that thing cheaper, so it makes exporting more profitable, it also makes it cheaper for tourists to visit the UK. It would add to the costs of the government and lead to higher taxes, inflation and slower growth. There was a run on the pound after the vote to leave the EU, there was also a run on the pound when it was forced to leave the ERM in 1992 Generally a run on the pound is a bad thing it destabilises international markets that depend on predictable prices. There is a concern that the level of government borrowing implied by the Labour party's policies would cause financial traders to sell pounds in large enough amounts to cause a run, and this would be damaging to the UK economy. As such the shadow chancellor mentioned in a meeting that he was engaged in planning for this event, even though he said it was unlikely. The fact he mentioned this possibility surprised many journalists, as predicting a run on the pound can be a self-fulfilling prophesy. So a run on the pound is not something that the Labour party planning to have. Instead the Labour party is planning its defensive strategy if a damaging run on the pound occurs. A: I'm assuming that the article you referred to is the first hit on Google under "Corbyn" and "run on the pound": Jeremy Corbyn: It's right to plan for run on pound If so, I'm afraid you're not interpreting what the article said correctly. It says: Jeremy Corbyn says it is "right to look at all these scenarios" after his shadow chancellor suggested that there could be a run on the pound if Labour went into government. John McDonnell said Labour was doing "war-game-type scenario-planning" for events such as "a run on the pound". Corbyn doesn't want to do a run on the pound (to be more precise, this article does not say that he wants it. Whether he wants to or not is not something I know, as I don't know how to read minds yet). The article says that he wants to prepare how to respond in the eventuality that a run on the pound happens (intentionally or not) as a result of Labour party forming the government. A: I think he's overstating expectations here. There was, immediately after Brexit, a serious run on the British Pound The British pound fell more than 10 percent on Thursday night, reaching $1.34 per pound, after midnight Eastern time, a stunning decline for a rich country's currency in a single day. The plunge came as United Kingdom voted to leave the European Union, a historic event that shatters 40 years of efforts to foster economic integration on the continent. Inside Britain that wouldn't have a lot of immediate effect, but over time that causes a jump in prices. So let's say it cost £100 for three barrels of oil before. A 10% drop in the value of the Pound means you now have to spend £111 for those same three barrels. Remember, the seller has to convert that currency to something they can use, so someone is having to sell Pounds. This generally leads to inflation (where prices rise in a long-term way). There's not much a government can do to stop a run (markets are global now). In fact, in 1992 the UK tried unsuccessfully to stop the events now known as Black Wednesday, where the Pound was being short sold by a hedge fund The UK government attempted to prop up the depreciating pound to avoid withdrawal from the monetary system the country had joined two years earlier. John Major raised interest rates to 10 percent and authorized the spending of billions worth of foreign currency reserves to buy up the sterling being sold on the currency markets, but the measures failed to prevent the pound falling below its minimum level in the ERM. Corbyn seems to be talking about another run based on a potential Labour Party victory in the next election The planning scenario means a Labour victory would ultimately trigger the fall in the value of the pound, which has already fallen following the Brexit vote, and could be devastating for the UK economy.
    { "pile_set_name": "StackExchange" }
    Q: Serving Streaming Content without streaming distribution I am new to Streaming Media. I am working on a web application built using Symfony 1.4. It features audio players and I am using jPlayer for the player. I use ffmpeg for encoding the audio files. Currently, I am storing my audio files on the development server. However, I would want to use Amazon S3 Storage Service for storing my audio files. While going through the information available over the WWW and Amzon's site, I came to realize that it would require a streaming distribution service viz. Amazon Cloudfront. At present, I am not using any streaming distribution while I play audio from my server. Is it necessary to use Amazon Cloudfront ? Can't I directly serve my audio files from Amazon S3 by providing a URL as http://s3.mybucket.com/XXX ? What are the consequences of serving files directly from Amazon S3 and not using Cloudfront ? A demo of the player that I am using can be seen here: http://audiodip.org/project/detailsProject/id/5 A: If the audio file has to be retrieved from a remote server(in your case S3) you should read and play it as a streaming audio. Otherwise it is like downloading the full audio file to the application server and then playing it. Cloudfront is a content delivery service with which streaming comes of no extra cost. So it is better use the streaming service from cloudfront. and you will have to enable your audio player to play streaming data.
    { "pile_set_name": "StackExchange" }
    Q: How to pass properties to Java when using COMPSs I have a java application which is launched with a settings file passed as a property as follows: java -DpropertiesFile=/path/to/properties/settings.properties -jar /path/to/jar/file.jar I would like to know how/if I can pass this properties file when running my application with COMPSs framework. Thanks A: Currently the only option is to set the environment variable _JAVA_OPTIONS. This is variable is read once the JVM is started. In your example it would be: export _JAVA_OPTIONS=-DpropertiesFile=/path/to/properties/settings.properties NB: I used export as an example, use whatever command your system has to set environment variables.
    { "pile_set_name": "StackExchange" }
    Q: How to fix state update? I draw a grid N × N. Suppose that grid is an array of N x N. I need to get the array' index when I click at the element and when put it to the store. That is, I get the coordinates (x, y) relative to the canvas, and translate them into the index. The store is an associative array. Recording condition: if the store hasn't index I put it, if no I delete it. The index, which I need to be written a second time as a rule and after erasing the console give the error TypeError index: this.state.store.has is not a function. (The 'this.state.store.has (member)', 'this.state.store.has' is not defined) How to fix it? export default class SimulationField extends React.Component { constructor(props) { super(props); this.state = { store: new Map(), scale: 20, edge: this.props.edge } } handleClick(e) { let x = Math.floor(getMouseX(e, this.refs.canvas) * this.state.scale / this.state.edge) let y = Math.floor(getMouseY(e, this.refs.canvas) * this.state.scale / this.state.edge) let element = xy2Key(this.state.scale)([x, y]) this.setState({ store: ( this.state.store.has(element) ) ? this.state.store.delete(element) : this.state.store.set(element, true) }) } componentDidMount() { this.updateCanvas(); } updateCanvas() { const ctx = this.refs.canvas.getContext('2d'); renderGrid({ ctx, edge: this.state.edge, scale: this.state.scale }) } render() { return ( <div> <canvas ref="canvas" width={this.state.edge} height={this.state.edge} onClick={this.handleClick.bind(this)}> </canvas> </div> ); } } A: Nearly, but .delete won't return store like .set does. Returns true if an element in the Map object existed and has been removed, or false if the element does not exist. This means that if this.state.store.has(element) is ever true, you are effectively just doing: this.setState({ store: true }) Next time you try and call store.has you are actually just trying to call true.has, which doesn't work. Try this instead. if (this.state.store.has(element)) { this.state.store.delete(element) } else { this.state.store.set(element, true) } this.setState({ store })
    { "pile_set_name": "StackExchange" }
    Q: What's wrong with this socket code in blackberry? i'm getting a JVM Error 104, Uncaught: NullPointerException, this is my code, I couldn't track errors: package com.rim.samples.device.socketdemo; import java.io.*; import javax.microedition.io.*; import net.rim.device.api.ui.*; public class ConnectThread extends Thread { //private InputStream _in; private OutputStreamWriter _out; private SocketDemoScreen _screen; // Constructor public ConnectThread() { _screen = ((SocketDemo)UiApplication.getUiApplication()).getScreen(); } public void run() { StreamConnection connection = null; String user = "Cegooow"; String channel = "#oi"; try { _screen.updateDisplay("Opening Connection..."); String url = "socket://" + _screen.getHostFieldText() + ":6667" + (_screen.isDirectTCP() ? ";deviceside=true" : ""); connection = (StreamConnection)Connector.open(url); _screen.updateDisplay("Connection open"); //_in = connection.openInputStream(); _out = new OutputStreamWriter(connection.openOutputStream()); //StringBuffer s = new StringBuffer(); _out.write("NICK " + _screen.getNickText() + "\r\n"); _out.write("USER " + user + "8 * : Client\r\n"); _out.write("JOIN " + channel + "\r\n"); _out.write("PRIVMSG " + channel + " " + _screen.getMessageFieldText() + "\r\n"); _screen.updateDisplay("Done!"); } catch(IOException e) { System.err.println(e.toString()); } finally { _screen.setThreadRunning(false); /*try { _in.close(); } catch(IOException ioe) { }*/ try { _out.close(); } catch(IOException ioe) { } try { connection.close(); } catch(IOException ioe) { } } } } A: Try to change the code of your finally block to smth like this: try { if (_out != null) _out.close(); } catch (IOException ioe) {} try { if (connection != null) connection.close(); } catch (IOException ioe) {}
    { "pile_set_name": "StackExchange" }
    Q: extract number from string in kdb I am quite new to kdb+q. I've come across this problem of extracting a number out of string. Any suggestions? Example: "AZXER_1234_MARKET" should output 1234 //Assume that there is only one number in the string A: Extract the numbers then cast to required type. q){"I"$x inter .Q.n} "AZXER_1234_MARKET" 1234i q){"I"$x inter .Q.n} "AZXER_123411_MARKET" 123411i q){"I"$x inter .Q.n} "AZXER_1234_56_MARKET" 123456i q){"I"$x inter .Q.n} "AR_34_56_MAT" 3456i
    { "pile_set_name": "StackExchange" }
    Q: Telerik Report Error Handling So what I'm doing is creating a report from multiple data sources (stored procedures) in vb.net. I am accomplishing this by putting them into a Dataset and passing it to the report. So when i get to the report i end up with an iif statement to handle multiple fields that aren't consistently named across the stored procedures (I cannot change the names) but need to go into the same text box. Here's an example: =IIF(Fields.TableName <> '', Fields.TableName, IIF(Fields.usuTableName <> '', Fields.usuTableName, NULL)) As you can see, they are both the same, but named differently thus there scare of the overriding the other. Only one will be populated. However, The problem is if one of those field values don't exists... I.E. Fields.usuTableName Say for instance we are filtering by date and thus nothing is returned from the stored procedure that has the naming convention of Fields.usuTableName for that date range and thus creates no dataset but the others return values. When the report goes to render we get an error because Fields.usuTableName doesn't exists but Fields.TableName does. How can i make sure a field name is valid before running the IF statement for it? A: Here's the function i used to evaluate it before using it: Public Shared Function GetValue(ByVal reportItem As Processing.ReportItem, ByVal field As String) As String Try Dim testdString As String Try testdString = reportItem.DataObject(field).ToString Catch ex As Exception 'must not be date End Try Return reportItem.DataObject(field).ToString Catch ex As Exception Return "" End Try End Function I called it for every field name in the report
    { "pile_set_name": "StackExchange" }
    Q: hadoop 1.x ports list - 4 more unknown ports I configured and installed hadoop 1.2.1 single node. I configured the namenode and jobtracker address with ports as "hdfs://localhost:9000" and "localhost:9001" respectively. After starting the cluster (start-all.sh). I ran netstat -nltp after this, which listed the hadoop ports. 50030 - jobtracker Web UI 50060 - tasktracker Web UI 50070 - namenode Web UI 50075 - datanode Web UI (http://localhost:50075/browseDirectory.jsp?dir=%2F) 50090 - secondary namenode Web UI 54310 - namenode (as configured in XML) 54311 - jobtracker (as configured in XML) 50010 - datanode (for data transfer) 50020 - datanode (for block metadata operations & recovery) 33447 - tasktracker ( not configured. Any unused local port is chosen by hadoop itself) But, a couple of other ports also were occupied and it shows it is java process (I stopped hadoop and confirmed that these belonged to that hadoop cluster only). 48212 - ??? 41888 - ??? 47448 - ??? 52544 - ??? These are not fixed ports. They are chosen dynamically. Because, when i restarted the cluster (stop-all.sh and start-all.sh), the other ports were same as first time, except these ports changed 48945 - tasktracker (This is fine, as explained before) What about the other ports? What are these ports used for? 44117 - ??? 59446 - ??? 52965 - ??? 56583 - ??? A: Thank you for posting this interesting question, Vivek. It intrigued me a lot and I dig up a bit of code for Apache Hadoop 1.2.1 - startup section for each of the master and slave; But there were no additional port bindings except for the standard documented one. I did a couple of experiments on ways we can start a namenode and observed the ports using netstat -nltpa 1) hadoop --config ../conf namenode -regular 2) Directly invoking the Namenode main class 3) Add the default core-default.xml and than start up the namenode My observation was for #2 and #3 only standard ports showed up, so I looked up the java options and that was the bingo. Comment all of below in hadoop-env.sh and then start hadoop, you will see only standard port, so the additional ports you see are all JMX bin ports export HADOOP_NAMENODE_OPTS="-Dcom.sun.management.jmxremote $HADOOP_NAMENODE_OPTS" export HADOOP_SECONDARYNAMENODE_OPTS="-Dcom.sun.management.jmxremote $HADOOP_SECONDARYNAMENODE_OPTS" export HADOOP_DATANODE_OPTS="-Dcom.sun.management.jmxremote $HADOOP_DATANODE_OPTS" export HADOOP_BALANCER_OPTS="-Dcom.sun.management.jmxremote $HADOOP_BALANCER_OPTS" export HADOOP_JOBTRACKER_OPTS="-Dcom.sun.management.jmxremote $HADOOP_JOBTRACKER_OPTS" Hope this helps.
    { "pile_set_name": "StackExchange" }
    Q: Why is my dropdown label split into 2 lines in Chrome? I am trying to put some padding to the right item of the navigation bar and when I reload the page in Chrome, the name is on 1 line and the down-arrow is on the line below the name. When I click it, the problem is resolved completely until the next reload or resize. I have tried to use Firefox but I did not face the same issue, everything goes right on Firefox. I wonder if there is a way to get rid of this issue whenever I reload the page in Chrome? Moreover, is there any other way that I could move the right-place nav-item to the left a little bit without using the padding? And when the name of Dropdown menu is too short (like 5 or 6 characters), the menu only shows part of it, how do I position the menu? The problem when reload page on Chrome: The problem disappears when you click on the menu: The issue is not on Firefox: I tried using a short label: Here's my code <style> #zzz { padding-right: 1.5%; } .navbar-brand { padding-left: 1.5% ; } .nav-link { color: #b7c9cc; } ul.navbar-nav a:hover { color: white; } .navbar-nav > li > .dropdown-menu > .dropdown-item:hover { background-color: #202e3e; } navbar-tooggler { color: white; } .custom-toggler.navbar-toggler { border-color: transparent; outline: none; } .custom-toggler .navbar-toggler-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='white' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E"); } </style> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Sth</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </head> <body> <div class="container-fullwidth"> <nav class="navbar navbar-expand-lg" style="background-color: #202e3e"> <a class="navbar-brand" href="#"> <img src="./assets/logo.png" width="32" height="32" alt=""> </a> <button class="navbar-toggler custom-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="#">Nav<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Nav</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Nav</a> </li> </ul> <!-- --> <ul class="navbar-nav" id="zzz"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown Menu </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Something</a> <a class="dropdown-item" href="#">Something</a> <a class="dropdown-item" href="#">Something</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Log Out</a> </div> </li> </ul> <!-- --> </div> </nav> </div> </body> </html> A: For your padding just use px than % #zzz { padding-right: 10px; } For your second issue since you're using bootstrap it comes with it's own css which is left aligning the menu all the way to the edge. You add this to override the issue. .dropdown-menu { right: 0; left: inherit; }
    { "pile_set_name": "StackExchange" }
    Q: Displaying results from a mySQL database ...how to add a table after X results? I have a script that gets results from a mySQL database and then outputs them, 4 on each row, 20 total. Sort of like: X X X X X X X X X X X X X X X X What I'm trying to do, is have the script output a piece of code (that I'll then HTMLify) after the first 4 rows. How would I do that? So that the result would be: X X X X something else X X X X X X X X X X X X Here is my current code: (Note I on purpose deleted the mySQL query and that stuff, to make it easier). <table width="100%" border="0" cellspacing="1" cellpadding="3"> <? $columns = 4; $results = 20; for($i = 0; $i < $results; $i++) { if($i % $columns == 0) { ?> <tr height="15" valign="top"> <? } ?> <td width="20%">OUTPUT GOES HERE</td> <? if(($i % $columns) == ($columns - 1) || ($i + 1) == $results) { ?> </tr> <? } ?> <? } ?> </table> A: if ($i == 4) { /* Or 5 if you only want to show it when $results > 4 */ echo '<tr><td colspan="4">something else</td></tr>'; } Or am I missing something crucial? I think your code is really hard to read and maintain, by the way. I would start by building a two-dimensional array of what I want and then output that.
    { "pile_set_name": "StackExchange" }
    Q: Is my .then Javascript Promise Working? Here is a snippet of my code: .then(functionUpdate(par)) .then(function() { console.log("why do I see this in my terminal before i see all of the console.log from functionUpdate()?"); I want functionUpdate(par) to finish before going on to the next function but when I look in my terminal the console.log in the next function goes off before all of the console.log within functionUpdate. I presume this means that the functions are not being called synchronously. I thought the .then promise was supposed to enforce synchronous operations. What am I doing wrong? I've also tried using Parse.Promise (I'm using Parse.com and have it installed) and Q to no avail. If anything I often get an error saying I can not execute then on undefined. A: This is explicitly how promises work: they will run "until they are done" and functions you pass as then handlers will trigger "whenever the promised code yields a result". In the mean time, the rest of your script that follows the promise chain keeps running as usual.
    { "pile_set_name": "StackExchange" }
    Q: How to automatically call a query for every new connection in MySQL? Is it possible to set or initialize a query in MySQL for every new connection ? Whenever a connection is created, it will call a procedure or a select query automatically ? Any script or config option for this? A: You may want to check init_connect variable: A string to be executed by the server for each client that connects. The string consists of one or more SQL statements, separated by semicolon characters. For example, each client session begins by default with autocommit mode enabled. http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_init_connect A: If you have not only mysql-client tool, but additional any application layer, there is more jedi-style :) You can create simple decorator for your connector's class that will execute some queries when instance created (in constructor)/connect method invoked. Hope it helps
    { "pile_set_name": "StackExchange" }
    Q: How to copy a file to a windows path with wildcards in it? I am newbie to windows os. Please pardon my question if you feel it is like a noob question. I am trying to copy a a file from one path to another path. The thing is that the destination path has a wildcard character in it. How to copy? I assumed it as a simple task, but not to be. This is the command copy *.zip "C:\MyCave\iso\SDG\cmpdir\copy test\ab\cd\*\gh" The folder after ab\cd is dynamic. So I have tried to use wildcard, but this is throwing an error. The filename, directory name, or volume label syntax is incorrect. 0 file(s) copied. I want to copy files in directory gh in the path. How to do it? Regards A: I would offer this method. For /D %G In ("C:\MyCave\iso\SDG\cmpdir\copy test\ab\cd\*") Do @For %H In ("%G\gh") Do @If "%~aH" GEq "d" Copy /Y "*.zip" "%~H" 1>NUL To begin to understand what the command does, please open a Command Prompt window, type for /?, press the ENTER key, and read the information presented. You should do the same using If /? and Copy /? too. The first part, For /D %G In ("FilePath\*") will return as %G directories located in FilePath. (Each of those will be your dynamic/unknown directory names). The next part uses another loop to test each of those unknown directories, with your known directory names appended to it. The results from that loop, returned as %H, are then checked for the directory attribute, and if true, the copy command is performed using it. Please note, that if there are more than one dynamic directory names containing a subdirectory named gh, your .zip files will be copied to each of them.
    { "pile_set_name": "StackExchange" }
    Q: Easy way to rename a project in android I have downloaded an Android project. To avoid name conflicts I want to move it from com.android.zzz to com.my.zzz. At the moment I'm using Ecplise with the standard android toolkit. Is there a better way to do the rename than to go manually through the files? A: This is basic IDE refactoring. Right click the package in Eclipse -> Refactor -> Rename. You will probably want to check all the options that come up in the Rename dialog. Another option would be to right click the class files in Eclipse -> Refactor -> Move. A: As usual, by pressing F2 on package name, you can rename or change the package name, and also by Right-clicking and then select Rename option, you can change or rename the Package name. When you press F2, it will show you the dialog box as: alt text In this dialog, dont forget to check "Update references" check box because by making "check" to this check-box, it will make changes to all the references of the package which are referred by other components of project. Hope this helps you,
    { "pile_set_name": "StackExchange" }
    Q: android converting json to string Hi I have this snippet of code : protected void onPostExecute(String response) { String res=response.toString(); // res = res.trim(); res= res.replaceAll("\\s+",""); if(!res.equals("0")){ un.setVisibility(View.GONE); ok.setVisibility(View.GONE); error.setVisibility(View.GONE); key.setVisibility(View.GONE); merchant.setVisibility(View.VISIBLE); String data = getServerData(res); merchant.setText(data); } else error.setText("Incorrect Password"); } } private String getServerData(String returnString) { InputStream is = null; String result = ""; //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //parse json data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","merchant_id: "+json_data.getInt("merchant_id")+ ", merchant_name: "+json_data.getString("merchant_name") ); //Get an output to the screen returnString += "\n\t" + jArray.getJSONObject(i); } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } return returnString; } and this php code : include 'config.php'; include 'opendb.php'; $key = $_POST['username']; $key = mysql_real_escape_string($key); $sql = "SELECT merchant_id, merchant_name FROM merchants WHERE merchant_key = '$key'"; $number = mysql_query($sql); $rows = mysql_num_rows($number); if ($rows > 0){ while($result=mysql_fetch_assoc($number)){ $output[]=$result; print(json_encode($result)); } } else{ echo 0; } Basically on the android emulator screen I get the json array: {"merchant_id":"1", "merchant_name": "ChowRestaurant"} I wanted to display on the screen in this way: "1 Chow Resstaurant" just needed some guidance on this A: for that you have to parse Json with library Gson, Jackson etc or you can also parse it manually Manual way: http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/ Gson: https://sites.google.com/site/gson/gson-user-guide Jackson: http://wiki.fasterxml.com/JacksonInFiveMinutes I will recommended to for with Gson
    { "pile_set_name": "StackExchange" }
    Q: Struggling to debug java solution to leetcode algorithm I was trying to solve this problem here: https://leetcode.com/problems/trapping-rain-water/#/description And my code is providing incorrect answers, but I can't understand why. When I look at it and I run it through my head, I can't figure out what's wrong with it. Here is my solution: (Please don't provide me with information about a more efficient methodology if possible, I want to try and figure that out on my own). public class Solution { public int trap(int[] height) { int totalWaterTrapped = 0; for (int i = 0; i < height.length; i++){ if (i == 0){ continue; } else if (i == (height.length - 1)){ continue; } else { int tallestLeftwardHeight = height[i]; for (int x = i; x >= 0; x--){ if (height[x] > tallestLeftwardHeight){ tallestLeftwardHeight = x; } } int tallestRightwardHeight = height[i]; for (int y = i; y < height.length; y++){ if (height[y] > tallestRightwardHeight){ tallestRightwardHeight = y; } } totalWaterTrapped += (Math.min(tallestLeftwardHeight, tallestRightwardHeight) - height[i]); } } return totalWaterTrapped; } } Thank you kindly for any help. A: if (height[x] > tallestLeftwardHeight){ tallestLeftwardHeight = x; } should be if (height[x] > tallestLeftwardHeight){ tallestLeftwardHeight = height[x]; } and if (height[y] > tallestRightwardHeight){ tallestRightwardHeight = y; } should be if (height[y] > tallestRightwardHeight){ tallestRightwardHeight = height[y]; }
    { "pile_set_name": "StackExchange" }
    Q: xterminal dosen't pass key-strokes to emacs I opened emacs using emacs -nw. Now, when I press M-v, it opens the view menu of the terminal, instead of passing the command to emacs. Is there a way to prevent this from happening? (I'm running on linux mint) A: Assuming that by M-v you actually mean Alt+M or, in emacspeak, ^M-v, you should be able to send ^M by hitting Esc instead of Alt. Just replace Alt with Esc for any ^M- commands you want to run. In the specific case of mate-terminal, you can switch off the shortcuts for the menus: Then, deselect the "Enable menu access keys (such as Alt+F to open the File menu)" option:
    { "pile_set_name": "StackExchange" }
    Q: Show this inequality with fractional parts. Let $n \geq 2$ be an integer and $x_1, x_2, \cdots, x_n$ positive reals such that $x_1x_2 \cdots x_n = 1$. Show: $$\{x_1\} + \{x_2\} + \cdots + \{x_n\} < \frac{2n-1}{2}$$ Note: $\{x\}$ denotes the fractional part of $x$. Is $\dfrac{2n-1}{2}$ optimal? A: Assume that $n\geq2$, $x_1x_2\cdots x_n=1$, and $$\{x_1\}+\{x_2\}+\ldots+\{x_n\}\geq n-{1\over2}\ .\tag{1}$$ Put $\tau_i:=1-\{x_i\}>0$. Then $(1)$ implies $\sum_i\tau_i\leq{1\over2}$; in particular no $\tau_i$ is $=1$. We therefore may write $x_i=m_i-\tau_i$ with $m_i=\lceil x_i\rceil\geq1$. As $\prod_i x_i=1$ at least one $m_i$ is $\geq2$. Now $$1=\prod_i x_i=\prod_i m_i\cdot\prod_i\left(1-{\tau_i\over m_i}\right)\ .\tag{2}$$ We shall need the following Lemma, which is easily proven using induction: If $n\geq2$, $x_i>0$ $(1\leq i\leq n)$, and $\sum_i x_i<1$ then $$\prod_{i=1}^n(1-x_i)>1-\sum_{i=1}^n x_i\ .$$Since $\sum_i{\tau_i\over m_i}<{1\over2}$ we then obtain from $(2)$ the contradiction $$1\geq 2\left(1-\sum_i{\tau_i\over m_i}\right)>2\cdot{1\over2}=1\ .$$
    { "pile_set_name": "StackExchange" }
    Q: Automated FTP to upload new files to web server? I'm looking for a FTP client that I can use to upload new files from a local development machine to a remote web-server. I only want to upload the newly edited files though. Is there a command line utility that can do this, that I can add into an automated process? Is there a GUI client available that can do this? Would be nice to have it cross-platform too. Any ideas? A: There is a 'backup' program called SyncBack that does this. You can find out more about it here: http://www.2brightsparks.com
    { "pile_set_name": "StackExchange" }
    Q: Is it acceptable for a Domain Entity to implement an interface? Please see the question here: https://stackoverflow.com/questions/2352654/should-domain-entities-be-exposed-as-interfaces-or-as-plain-objects The general consensus is that Domain Models should not contain interfaces. Now see here: https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Member.cs and specifically this code: public Offer AssignOffer(OfferType offerType, IOfferValueCalculator valueCalculator) { DateTime dateExpiring = offerType.CalculateExpirationDate(); int value = valueCalculator.CalculateValue(this, offerType); var offer = new Offer(this, offerType, dateExpiring, value); _assignedOffers.Add(offer); NumberOfActiveOffers++; return offer; } The author if this blog writes a lot about DDD. Notice that an interface is injected into the method here instead of a concrete type i.e. IOfferValueCalculator implements OfferValueCalculator. I am talking from the perspective of a DDD purist. Is it acceptable for domain entities to implement interfaces? If the answer is yes, then in what circumstances would it be acceptable to inject an IOfferCalculator into a Domain Entity: Member? Once again I realise that the DDD approach is not a one size fits all and that an Anemic Domain model is suitable in a lot of cases. I am just trying to improve my knowledge of this specific area. A: IOfferValueCalculator is not a domain entity. It is a service. So it is perfectly fine for it to be an interface. And there is some nuance in the "Should entities implement interfaces" question. While it is true that creating interface only for it to be implemented by single entity is useless complexity. There is nothing wrong with multiple entities implementing single interface, as those entities might be interchangeably used in code, that runs same logic on all of entities.
    { "pile_set_name": "StackExchange" }
    Q: Count where two or more columns in a row are over a certain value [basketball, double double, triple double] I play a basketball game which allows to output its statistics as a database file, so one can calculate statistics from it that are not implemented in the game. So far I've had no problem caluclating the statistics I wanted, but now I've run into a problem: counting the number of double doubles and/or triple doubles a player made over the season from his game statistics. The definition of a double double and a triple double is as follows: Double-double: A double-double is defined as a performance in which a player accumulates a double-digit number total in two of five statistical categories—points, rebounds, assists, steals, and blocked shots—in a game. Triple-double: A triple-double is defined as a performance in which a player accumulates a double digit number total in three of five statistical categories—points, rebounds, assists, steals, and blocked shots—in a game. Quadruple-double (added for clarification) A quadruple-double is defined as a performance in which a player accumulates a double digit number total in four of five statistical categories—points, rebounds, assists, steals, and blocked shots—in a game. The "PlayerGameStats" table stores statistics for each game a player plays and looks as follows: CREATE TABLE PlayerGameStats AS SELECT * FROM ( VALUES ( 1, 1, 1, 'Nuggets', 'Cavaliers', 6, 8, 2, 2, 0 ), ( 2, 1, 2, 'Nuggets', 'Clippers', 15, 7, 0, 1, 3 ), ( 3, 1, 6, 'Nuggets', 'Trailblazers', 11, 11, 1, 2, 1 ), ( 4, 1, 10, 'Nuggets', 'Mavericks', 8, 10, 2, 2, 12 ), ( 5, 1, 11, 'Nuggets', 'Knicks', 23, 12, 1, 0, 0 ), ( 6, 1, 12, 'Nuggets', 'Jazz', 8, 8, 11, 1, 0 ), ( 7, 1, 13, 'Nuggets', 'Suns', 7, 11, 2, 2, 1 ), ( 8, 1, 14, 'Nuggets', 'Kings', 10, 15, 0, 3, 1 ), ( 9, 1, 15, 'Nuggets', 'Kings', 9, 7, 5, 0, 4 ), (10, 1, 17, 'Nuggets', 'Thunder', 13, 10, 10, 1, 0 ) ) AS t(id,player_id,seasonday,team,opponent,points,rebounds,assists,steals,blocks); The output I want to achieve looks like this: | player_id | team | doubleDoubles | tripleDoubles | |-----------|---------|---------------|---------------| | 1 | Nuggets | 4 | 1 | The only solution I found so far is so awful it makes me puke ... ;o) ... It looks like this: SELECT player_id, team, SUM(CASE WHEN(points >= 10 AND rebounds >= 10) OR (points >= 10 AND assists >= 10) OR (points >= 10 AND steals >= 10) THEN 1 ELSE 0 END) AS doubleDoubles FROM PlayerGameStats GROUP BY player_id ... and now you're probably also puking (or laughing hard) after reading this. I didn't even write out everything that would be needed to get all double double combinations, and omitted the case statement for the triple doubles because it's even more ridiculous. Is there a better way to do this? Either with the table structure I have or with a new table structure (I could write a script to convert the table). I can use MySQL 5.5 or PostgreSQL 9.2. Here is a link to SqlFiddle with example data and my awful solution I posted above: http://sqlfiddle.com/#!2/af6101/3 Note that I'm not really interested in quadruple-doubles (see above) since they don't occur in the game I play as far as I know, but it would be a plus if the query is easily expandable without much rewrite to account for quadruple-doubles. A: Don't know if this is the best way. I first did a select to find out if a stat is double digit and assign it a 1 if it is. Summed all those up to find out total number of double digits per game. From there just sum up all the doubles and triples. Seems to work select a.player_id, a.team, sum(case when a.doubles = 2 then 1 else 0 end) as doubleDoubles, sum(case when a.doubles = 3 then 1 else 0 end) as tripleDoubles from (select *, (case when points > 9 then 1 else 0 end) + (case when rebounds > 9 then 1 else 0 end) + (case when assists > 9 then 1 else 0 end) + (case when steals > 9 then 1 else 0 end) + (case when blocks > 9 then 1 else 0 end) as Doubles from PlayerGameStats) a group by a.player_id, a.team A: Try this out (worked for me on MySQL 5.5): SELECT player_id, team, SUM( ( (points >= 10) + (rebounds >= 10) + (assists >= 10) + (steals >= 10) + (blocks >= 10) ) = 2 ) double_doubles, SUM( ( (points >= 10) + (rebounds >= 10) + (assists >= 10) + (steals >= 10) + (blocks >= 10) ) = 3 ) triple_doubles FROM PlayerGameStats GROUP BY player_id, team Or even shorter, by blatanly ripping off JChao's code from his answer, but taking out the unneeded CASE statements since boolean expr evaluates to {1,0} when {True,False}: select a.player_id, a.team, sum(a.doubles = 2) as doubleDoubles, sum(a.doubles = 3) as tripleDoubles from (select *, (points > 9) + (rebounds > 9) + (assists > 9) + (steals > 9) + (blocks > 9) as Doubles from PlayerGameStats) a group by a.player_id, a.team Based on the comments that the above code won't run in PostgreSQL since doesn't like to do boolean + boolean. I still don't like CASE. Here's a way out on PostgreSQL (9.3), by casting to int: select a.player_id, a.team, sum((a.doubles = 2)::int) as doubleDoubles, sum((a.doubles = 3)::int) as tripleDoubles from (select *, (points > 9)::int + (rebounds > 9)::int + (assists > 9)::int + (steals > 9)::int + (blocks > 9)::int as Doubles from PlayerGameStats) a group by a.player_id, a.team A: Here's another take on the problem. The way I think of it, you're essentially working with pivoted data for the current problem, so the first thing to do is unpivot it. Unfortunately PostgreSQL doesn't provide nice tools to do that, so without getting into dynamic SQL generation in PL/PgSQL, we can at least do: SELECT player_id, seasonday, 'points' AS scoretype, points AS score FROM playergamestats UNION ALL SELECT player_id, seasonday, 'rebounds' AS scoretype, rebounds FROM playergamestats UNION ALL SELECT player_id, seasonday, 'assists' AS scoretype, assists FROM playergamestats UNION ALL SELECT player_id, seasonday, 'steals' AS scoretype, steals FROM playergamestats UNION ALL SELECT player_id, seasonday, 'blocks' AS scoretype, blocks FROM playergamestats This puts the data in a more malleable form, though it's sure not pretty. Here I assume that (player_id, seasonday) is sufficient to uniquely identify players, i.e. the player ID is unique across teams. If it isn't, you'll need to include enough other info to provide a unique key. With that unpivoted data it's now possible to filter and aggregate it in useful ways, like: SELECT player_id, count(CASE WHEN doubles = 2 THEN 1 END) AS doubledoubles, count(CASE WHEN doubles = 3 THEN 1 END) AS tripledoubles FROM ( SELECT player_id, seasonday, count(*) AS doubles FROM ( SELECT player_id, seasonday, 'points' AS scoretype, points AS score FROM playergamestats UNION ALL SELECT player_id, seasonday, 'rebounds' AS scoretype, rebounds FROM playergamestats UNION ALL SELECT player_id, seasonday, 'assists' AS scoretype, assists FROM playergamestats UNION ALL SELECT player_id, seasonday, 'steals' AS scoretype, steals FROM playergamestats UNION ALL SELECT player_id, seasonday, 'blocks' AS scoretype, blocks FROM playergamestats ) stats WHERE score >= 10 GROUP BY player_id, seasonday ) doublestats GROUP BY player_id; This is far from pretty, and it's probably not that fast. It's maintainable though, requiring minimal changes to handle new types of stats, new columns, etc. So it's more of a "hey, did you think of" than a serious suggestion. The goal was to model the SQL to correspond to the problem statement as directly as possible, rather than to make it fast. This was made vastly easier by your use of sane multi-valued inserts and ANSI quoting in your MySQL-oriented SQL. Thankyou; it's nice not to see backticks for once. All I had to change was the synthetic key generation.
    { "pile_set_name": "StackExchange" }
    Q: Porting from Python to Java: looking for a fast implementation of an array search operation I am porting some Python code into Java and need to find an efficient implementation of the following Python operation: sum([x in lstLong for x in lstShort]) where lstLong and lstShort are string lists. So here I am counting how many elements from lstShort appear in lstLong. In the Java implementation, both of these are String[]. What's the fastest way of counting this sum? A more general question is whether there are any generic guidelines for writing "fast equivalents" in Java of Python list comprehension operations like the one above. I am mostly interested in arrays/lists of Strings, in case it makes the answer easier. A: If you convert both to ArrayList<String>, you can use lstLong.retainAll(lstShort).size(); You can do the conversion with new ArrayList<String>(Arrays.asList(var));
    { "pile_set_name": "StackExchange" }
    Q: Detect application refocus event I need to know each time the user is starting to use the application. Case 1 (OK) : The app is not started. The user starts the application from scratch. I add a listener on the app's bootstrap, and I am aware when it starts. Case 2 (TODO) : The app has been started but it's not active anymore The user reload the application from the taskbar. I want to know when the application comes from the taskbar to the foreground (like a alt+tab). This is tricky to catch, because the app is still running and I don't know which event to listen to. In fact, I don't even know how to name this behaviour. A: There is an event for app resume and pause in Cordova so you don't need to edit the Cordova class files. Below is working code I am currently using in an app for iOS/Android. window.onload = function() { //only fired once when app is opened document.addEventListener("deviceready", init, false); //re-open app when brought to foreground document.addEventListener("resume", init, false); //trigger when app is sent to background document.addEventListener("pause", onPause, false); } function init() { console.log('device ready or resume fired'); } A: An ios-app developper accepted to help me. His answer suits me very well, as it seem clean et reusable. So I will produce it here : The "app come to foreground" event can be catched through the applicationWillEnterForeground event. Phonegap/Cordova allows to call javascript functions through the Cordova classes. The webView object has a dedicated method to launch js scripts. So I opened the file Projet/Classes/Cordova/AppDelegate.m : - (void)applicationWillEnterForeground:(UIApplication *)application { NSLog(@"applicationWillEnterForeground: %@", self.viewController.webView); [self.viewController.webView stringByEvaluatingJavaScriptFromString:@"notifyForegroundEvent();"]; } And I added the notifyForegroundEvent() method somewhere in the root of my js files : var notifyForegroundEvent = function() { console.log('notifyForegroundEvent()'); // Do something here } Et voilà
    { "pile_set_name": "StackExchange" }
    Q: Work done by Internal Forces Why is it that internal forces do not change the potential energy of the system? Assume that a man stands on earth with a dumbell. If the dumbell is the system, when it is raised a height h, the work done by the man is +mgh and the work done by the earth is -mgh. If the system is the earth and the dumbell, then the man will increase the potential energy of the system by +mgh. Where does the gravitational force of the earth on the dumbell go? A: Internal forces are the only contributors to potential energy. Potential energy is the energy associated with the configuration (relative positions) of a collection objects. The potential energy of a single point particle is not defined. As the configuration of the system changes, its potential energy changes according to the definition $\Delta{\mathrm{(P.E.)}} = -W_\mathrm{internal}$ where $W_\mathrm{internal}$ is the work done internally, that is, by the various internal forces against the internal components of the system. In order to define potential energy, you need to have internal components applying forces to one another, and the components need to be able to move relative to one another. You need at least two objects. Consider the system consisting of only the dumbbell. You have implicitly modeled the dumbbell as a point particle. That is, the only attributes of interest to your analysis are its position and its mass. The internal structure, which would be of interest in other questions, say, concerning temperature, is ignored. You have applied two external forces, gravity, and the contact force of your hand. Not only is there no change in potential energy, there is no potential energy at all. Potential energy does not exist in a system consisting of, or modeled by, a single point particle. I'm not saying that the P.E. is zero. I'm saying that it is not defined. Consider the system consisting of the dumbbell and the earth. Now I have two objects modeled as point particles, one external force: the force of your hand, and one internal force: the mutual gravitational attraction between the Earth and the dumbbell. The internal work done in lifting the dumbbell (that is, increasing the distance between them) is $W_\mathrm{internal} = -mgh$. The minus sign comes from the fact that the displacement is in the direction opposite to the direction of the force. (Gravity down, displacement up.) so the change in potential energy of the system is $$\Delta\mathrm{(P.E.)} = -W_\mathrm{internal} = -(-mgh) = mgh$$ The external force of your hand on the dumbbell plays no role at all. One of the roots of your misunderstanding is the unfortunate choice made by almost all introductory textbooks in introducing the subject of potential energy by looking at raising and lowering objects in a static gravitational field (at the surface of the earth). I know of a particular textbook that had a wonderful and correct description of potential energy. Until the next edition came out, when that description disappeared, and the conventional description appeared in its place. addendum There's something that needs clarification. In what I've written above, I modeled all of the objects as point particles having no internal structure. That includes my model of the composite system: I took that as a point particle also, this one located at the center of mass of the composite system. External forces can accelerate the system, but that's all it can do. $F_\mathrm{net} = ma_\mathrm{cm}$, and the kinetic energy of the system increases in accordance with the usual analysis: $\Delta KE = \vec{F_\mathrm{net}}\cdot \Delta \vec{x}_\mathrm{cm}$ If I take a better model for the composite system I might find that it is deformable. Suppose the system is a rubber ball. Now when I apply the external force, the object will deform. The center of mass still obeys $F_\mathrm{net} = ma_\mathrm{cm}$ and we still have $\Delta KE = \vec{F_\mathrm{net}}\cdot \Delta \vec{x}_\mathrm{cm}$. But notice that since the object is deforming, the displacement of the center of mass is not the same as the displacement of the point of application of the force. The kinetic energy of the system increases as before: $\Delta KE = \vec{F_\mathrm{net}}\cdot \Delta \vec{x}_\mathrm{cm}$, but the point of application of the force moves farther than $\Delta \vec{x}_\mathrm{cm}$. More work was done than was needed to accelerate the system. Some of this extra work ends up as internal potential energy. Some as internal kinetic energy, some as thermal energy $\ldots$. None of these energies exist in the point particle model of the system, but in a real system they do exist. In that sense, external forces can change the potential energy of a system. But even in that more realistic analysis, the change in the potential energy of the system is due to the internal forces, and internal work. There is an external influence that causes deformation, but the change in potential energy is calculated from internal work.
    { "pile_set_name": "StackExchange" }
    Q: Django Dynamic menu design question I want to create dynamic menus according to user permissions. As was already discussed here and by the the documentation itself, I know that I can achieve this in the templates using the following snippet: {% if perms.polls.can_vote %} <li> <a href="/polls/vote">Vote</a> </li> {% endif %} But the problem is that for security reasons I want to limit the access to the views too. The snippet that I found in the documentation is the following: from django.contrib.auth.decorators import permission_required def my_view(request): # ... my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view) Isn't this against DRY principle? Isn't there a way to define only in one place what is the permission needed for each url? Perhaps in urls.py? A: EDIT: (See end of post for the original text of the answer with the initial, simple idea.) After being kindly stricken with a cluebat (see the OP's comment below), I find I can see more to the problem than before. Sorry it took so long. Anyway: Would this kind of template be alright for you? {% for mi in dyn_menu_items %} {% if mi.authorised %} <a href={{ mi.url }}>{{ mi.title }}</a> {% endif %} {% endfor %} To make this work on the Python side, you could use RequestContext in your views with a custom context processor setting the dyn_menu_items variable appropriately. In case some background information is required, the Advanced Templates chapter of the Django Book introduces RequestContext, shows how to use it with render_to_response (kinda important :-)) etc. Also, I guess at this point it could be useful to put the view functions responsible for the locked-up sections of your site in a list somewhere: _dyn_menu_items = [(url1, view1, title1, perm1), ...] Then you could map a couple of functions, say prepare_pattern and prepare_menu_item across that list, having it work roughly like so: def prepare_pattern(menu_item): url1, view, title, perm = menu_item pattern = PREPARE_URLCONF_ENTRY_SOMEHOW(...) # fill in as appropriate return pattern def prepare_menu_item(menu_item): url, view, title, perm = menu_item mi = PREPARE_THE_BIT_FOR_REQUESTCONTEXT(...) # as above return mi These could be combined into a single function, of course, but not everybody would find the result more readable... Anyway, the output of map(prepare_menu_item, _dyn_menu_items) would need to be a dictionary to be passed to your views by a helpful context processor (the figuring out of which, it being the slightly tedious bit here, I'll leave to you ;-)), whereas the output of map(prepare_pattern, _dyn_menu_items), let's call it dyn_menu_patterns, would be used in patterns('', *dyn_menu_patterns), to be used in your URLconf. I hope this makes sense and is of some help... THE PRE-EDIT ANSWER: Based on your short description, I'm not sure what solution would be best for you... But if the permission_required snippet does what you want, just not DRY-ly enough, how about rolling your own wrapper: def ask_to_login(perm, view): return permission_required(perm, login_url='/loginpage/', view) You could put this anywhere, including in URLconf. Then you could replace all mentions of '/loginpage/' with reference to a variable defined towards the top of your URLs file and you'd have yourself a solution with a single mention of the actual login URL, for one-place-only update of said URL should you have to move it around. :-) Of course the views would still need to be wrapped explicitly; if that bothers you, you could try to make ask_to_login into a decorator for easy wrapping at the definition site. (But perhaps it's really best not to do it, lest you force yourself to dig your views from under the decorator in case you need them undecorated at some point in the future.)
    { "pile_set_name": "StackExchange" }
    Q: How to pop Nth item in the stack [Befunge-93] If you have the befunge program 321&,how would you access the first item (3) without throwing out the second two items? The instruction \ allows one to switch the first two items, but that doesn't get me any closer to the last one... The current method I'm using is to use the p command to write the entire stack to the program memory in order to get to the last item. For example, 32110p20p.20g10g@ However, I feel that this isn't as elegant as it could be... There's no technique to pop the first item on the stack as N, pop the Nth item from the stack and push it to the top? (No is a perfectly acceptable answer) A: Not really. Your code could be shortened to 32110p\.10g@ But if you wanted a more general result, something like the following might work. Below, I am using Befunge as it was meant to be used (at least in my opinion): as a functional programming language with each function getting its own set of rows and columns. Pointers are created using directionals and storing 1's and 0's determine where the function was called. One thing I would point out though is that the stack is not meant for storage in nearly any language. Just write the stack to storage. Note that 987 overflows off a stack of length 10. v >>>>>>>>>>>12p:10p11pv 1 0 v<<<<<<<<<<<<<<<<<< v >210gp10g1-10p^ >10g| >14p010pv v<<<<<<<<<<<<<<<<<<<<<<<< v >210g1+g10g1+10p^ >10g11g-| v g21g41< v _ v >98765432102^>. 2^>.@ The above code writes up to and including the n-1th item on the stack to 'memory', writes the nth item somewhere else, reads the 'memory', then pushes the nth item onto the stack. The function is called twice by the bottom line of this program.
    { "pile_set_name": "StackExchange" }
    Q: How to add more cowbell? Remember that Christopher Walken skit on Saturday Night live where he told the band “it needs more cowbell” https://en.wikipedia.org/wiki/More_cowbell ? This site automated it http://www.morecowbell.dj/ using echonest http://developer.echonest.com/ . That’s all fine. Question is: “What is the actual algorithm behind the beat detection and cowbell insertion?” A: The beat and onset detection algorithms used at the Echo Nest are probably variants/improvements of the techniques developed by Tristan Jehan in his Ph.D. This is not the only approach, and I would recommend you to try first: Getting an onset detection function using spectral flux or complex amplitude. Using this algorithm to detect beats (you can improve it using the "comb template" method described here to score tempo candidates - I believe this combination of Ellis' dynamic programming approach with a more sophisticated candidate scoring function is what is used in Sonic Visualizer's default beat detection vamp plug-in). As for adding the cowbell, I think there are a bunch of heuristics that could work. First of all, you can use the breaking down of the song into sections (as provided by the EN analyzer or by an algorithm like this), and process each section individually - to have changes in the cowbell pattern coincide with changes into chorus/verse. For each section, you can align the detected onsets on a grid of 16 or 32 sixteenth note to get a discrete representation of the onsets (a bit similar to what you would see on a drum machine or sequencer); and then average these patterns to get a summary of the rhythmic structure of the section. If the section is too chaotic - use a cowbell hit on each 4th or 8th note... Possible refinements: tune the cowbell so that it matches the key of the song, stop it in the sections that have a very low loudness...
    { "pile_set_name": "StackExchange" }
    Q: animating border to transparent with keyframes I'm trying to make simple animation of a circle which border goes from red to transparent color. How I'm trying to do it is to set initial color as red and then animate it to transparent with keyframes like so: .pulse{ margin: 20px; width:100px; height: 100px; background-color: red; border-radius: 100px; animation-name: pulse; animation-duration: 1s; animation-iteration-count: infinite; animation-direction: alternate; animation-timing-function: ease; } @keyframes pulse{ 0%{border:solid 1px rgba(255, 0, 0, 1)} 100%{border:solid 1px rgba(255, 0, 0, 0)} } <div class="animation"> <div class="pulse"></div> </div> Seemingly nothing happens but after fiddling with it a bit I'm aware that the animation actually works, but the transparent animation is shown on top of existing red border and effect is that it looks like nothing is happening. What i'm trying to achive is to have the border go from red to transparent, making it look like it's pulsating but without the circle changing it's size. A: You won't see anything because you background-color is the same color as the border color. Also your border definition inside your animation was wrong, the width must come before the border style: So for example it's 1px solid color instead of solid 1px rgba(255,0,0,1). .pulse { animation: pulse 1s ease infinite alternate; background-color: #ddd; border-radius: 100px; height: 100px; margin: 20px; width: 100px; } @keyframes pulse { 0% { border: 1px solid rgba(255, 0, 0, 1) } 100% { border: 1px solid rgba(255, 0, 0, 0) } } <div class="animation"> <div class="pulse"></div> </div> But i think you want to achieve a pulsating effect, therefore i would recommend you to use transform: scale() to create the desired effect. @keyframes pulse{ from { transform: scale(1) } to { transform: scale(.75) } } .pulse{ margin: 20px; width:100px; height: 100px; border-radius: 100px; background-color: red; animation: pulse 1s ease infinite alternate; } <div class="animation"> <div class="pulse"></div> </div>
    { "pile_set_name": "StackExchange" }
    Q: C# Item is null for very short period of time? I have a MessageQueue class with a private List property that acts as the queue. There's only one way to add to the queue (through an Add method) and one way to take from the queue (through a Next method). I have a thread running without a delay constantly checking the queue. Occasionally, a null item gets into the queue. I put a breakpoint in the Add method if the item being added is null, but the breakpoint is never hit. I put a breakpoint in the Next method if the item being returned is null, which is getting hit. Furthermore, the breakpoint is set after it fetches the item, but before the queue is adjusted. What's strange is, while the returned item is null, the item that was just fetched is not null! Here is my queue- public class MessageQueue { private List<byte[]> queue = new List<byte[]>(); public void Add(byte[] payload) { if (payload == null) { Console.WriteLine("thats why"); } queue.Add(payload); } public byte[] Next() { byte[] hand = queue.First(); if(hand == null) { Console.WriteLine("asdf"); } queue = queue.Skip(1).ToList(); return hand; } public bool HasMessages { get { return queue.Count() > 0; } } } Here is what's in the queue- And here is what's in the hand- Because I am using First on the queue, an error would be thrown if there wasn't an item. In fact, just to be sure that wasn't somehow related I put a try-catch around the First call- which is never hit. How is hand null when null is never added to the queue, and the first item in the queue is not null? A: List<> is not thread safe If you are accessing it from different thread you can see it in a broken state. Use any synchronization technique or anything from thread-safe collections As mentioned above: "ConcurrentQueue is most likely what you need to use"
    { "pile_set_name": "StackExchange" }
    Q: Textfield in alertview not working in ios7? I have an application in which I'm using a specific design for a reason. I put a text field in an alert view above an otherbutton with a background image. Everything is working fine in ios 6 version. UIAlertView *av=[[UIAlertView alloc] initWithTitle:@"fdhdj" message:@" hdfjkhfjkhdk" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@" ",@"cancel",nil]; av.alertViewStyle = UIAlertViewStylePlainTextInput; namefield = [[UITextField alloc] initWithFrame:CGRectMake(10.0,43.0, 264.0, 44.0)]; namefield.borderStyle = UITextBorderStyleNone; namefield.background = [UIImage imageNamed:@"text_field_default.png"]; namefield.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; namefield.textAlignment = UITextAlignmentCenter; //[namefield setBackgroundColor:[UIColor whiteColor]]; [av addSubview:namefield]; [namefield release]; av.tag=12; av.delegate=self; [av show]; [av release]; But now in ios 7, I heard you can't easily alter the view hierarchy of a UIAlertView. One alternative for this case is to set alert.alertViewStyle = UIAlertViewStylePlainTextInput But can we add that text field in wherever we want? As in my case above the first otherbutton.can anybody help me? A: UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Enter Student Name" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Save",nil]; [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput]; [alertView show]; i used to do like this ,and its working very fine A: The simple answer to your question is NO, you can't change anything in this testField for the UIAlertViewStylePlainTextInput and you shouldn't. This is from Apple: The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified. And unfortunately what you heard I heard you can't easily alter the view hierarchy of a UIAlertView is wrong, you cannot alter the view hierarchy of a UIAlertView in iOS7 at all. There are a good alternative on the web, you can check in cocoacontrols.com
    { "pile_set_name": "StackExchange" }
    Q: How to keep the implicitly declared aggregate initialization constructor? Suppose I have a class like this: struct X { char buf[10]; }; X x{"abc"}; This compiles. However, if I add user defined constructors to the class, this implicitly declared aggregate initialization constructor will be deleted: struct X { char buf[10]; X(int, int) {} }; X x{"abc"}; // compile error How can I declare that I want default aggregate initialization constructor, just like that for default constructor X()=default? Thanks. A: There is no "default aggregate initialization constructor". Aggregate initialization only happens on aggregates. And aggregates are types that, among other things, don't have (user-provided) constructors. What you're asking for is logically impossible. The correct means of doing what you want is to make a factory function to construct your type in your special way. That way, the type can remain an aggregate, but there's a short-hand way for initializing it the way you want. You give a type a constructor when you want to force users to call a constructor to construct it. When you don't, you just use factory functions.
    { "pile_set_name": "StackExchange" }
    Q: Improve performance of MS Excel writing I am facing performance issues while reading/writing data from/to MS-Excel cells. I am using MS Excel 11.0 object library for automation with VB.NET. Currently it takes too much time to read and write from/to Excel files. (10 mins to read 1000 rows :( ). It seems the cell-by-cell reading and writing approach is not that effiecient. Is there any way to read/write data using bulk operation? A: Rather than reading cell by cell you could read a whole range and save it into a 2D arrray. You can then access the 2D array as you would access a cell in excel. I'm not well versed in VB.NET for excel objects but if you understand C# then give this link a quick read and try to implement it. http://dotnetperls.com/excel-interop Read the "Getting workbook data" section A: Great!!! I used the 2D array approach and achieved the enormous performance boost!!. Previously I used the cell-by-cell aprroach as shown below, Dim cell As Excel.Range = Nothing cell = sheet.Cells(rowIndex, colIndex) cell.Value = "Some value" I used to iterate over a range of cells and used to copy the value in each cell. Here every sheet.Cells and cell.Value is an interop call and for every call it gives call to the Excel.exe, which costs more time. In 2D approach I have filled the data, which is to be copied in Excel cells, in 2D array and then assigned the 2D array to the value of the selected reange of cells. It is as shown below, Dim darray(recordCount - 1, noOfCol - 1) As String //Fill the data in darray //startPosRange = Get the range of cell from where to start writing data startPosRange = startPosRange.Resize(recordCount, noOfCol) startPosRange.Value = darray After these modifications, I gathered the performance data for both the approaches and results are surprisingly great!!. The later approach is 25 times as fast as previous one. Similarly, I have used the 2D array approach for reading data from cells and seen the similar performance boost. Code samples are as shown below. Cell-by-cell approach, Dim usedRange As Excel.Range = sheet.UsedRange For Each row As Excel.Range In usedRange.Rows() For Each cellData As Excel.Range In row.Cells //Gather cellData.Value in some container. Next 2D array approach, Dim usedRange As Excel.Range = sheet.UsedRange //Here the array index starts from 1. why??? Dim darray(,) As Object = CType(usedRange.Value, Object(,)) Dim rows As Integer = darray.GetUpperBound(0) Dim cols As Integer = darray.GetUpperBound(1) For i As Integer = 1 To rows For j As Integer = 1 To cols Dim str As String If darray(i, j) Is Nothing Then str = "" Else str = darray(i, j).ToString End If //Use value of str Next Next Please refer, http://support.microsoft.com/kb/306023 , http://dotnetperls.com/excel-interop (thanks ChickSentMeHighE for the link) Enjoy the performance!!!
    { "pile_set_name": "StackExchange" }
    Q: jq- reference current position in loop I have a log file called log.json that's formatted like this: {"msg": "Service starting up!"} {"msg": "Running a job!"} {"msg": "Error detected!"} And another file called messages.json, which looks like this: {"msg": "Service starting up!", "out": "The service has started"} {"msg": "Error detected!", "out": "Uh oh, there was an error!"} {"msg": "Service stopped", "out": "The service has stopped"} I'm trying to write a function using jq that reads in both files, and whenever it finds a msg in log.json that matches a msg in messages.json, print the value of out in the corresponding line in messages.json. So, in this case, I'm hoping to get this as output: "The service has started" "Uh oh, there was an error!" The closest that I've been able to get so far is the following: jq --argfile a log.json --argfile b messages.json -n 'if ($a[].msg == $b[].msg) then $b[].out else empty end' This successfully performs all of the comparisons that I'm hoping to make. However, rather than printing the specific out that I'm looking for, it instead prints every out whenever the if statement returns true (which makes sense. $b[].out was never redefined, and asks for each of them). So, this statement outputs: "The service has started" "Uh oh, there was an error!" "The service has stopped" "The service has started" "Uh oh, there was an error!" "The service has stopped" So at this point, I need some way to ask for $b[current_index].out, and just print that. Is there a way for me to do this (or an entirely seperate approach that I can use)? A: messages.json effectively defines a dictionary, so let's begin by creating a JSON dictionary which we can lookup easily. This can be done conveniently using INDEX/2 which (in case your jq does not have it) is defined as follows: def INDEX(stream; idx_expr): reduce stream as $row ({}; .[$row|idx_expr| if type != "string" then tojson else . end] |= $row); A first-cut solution is now straightforward: INDEX($messages[]; .msg) as $dict | inputs | $dict[.msg] | .out Assuming this is in program.jq, an appropriate invocation would be as follows (note especially the -n option): jq -n --slurpfile messages messages.json -f program.jq log.json The above will print null if the .msg in the log file is not in the dictionary. To filter out these nulls, you could (for example) add select(.) to the pipeline. Another possibility would be to use the original .msg, as in this variation: INDEX($messages[]; .msg) as $dict | inputs | . as $in | $dict[.msg] | .out // $in.msg
    { "pile_set_name": "StackExchange" }
    Q: Java dice roll code for review I have the below tiny program done in Java using Eclipse. It just shows two dice being rolled and what number (eyes?) they show. Can I do it without the use of casting in the Math.random lines? Or is there a completely different (and better) way of doing this? I am completely new at programming, so please bear with me (also English isn't my first language.) public class Meyer { public static void main(String[] args) { String [] die = {"1", "2", "3", "4", "5", "6"}; int roll = die.length; int random1 = (int) (Math.random() * roll); int random2 = (int) (Math.random() * roll); String rollDice = die[random1] + " " + die[random2]; System.out.println("The roll is: " + rollDice); } } A: I would personally prefer using the Random class, and its Random#nextInt(int) method. Not only I find it more elegant (and avoids casting), I also find it extremely useful to be able to use the same Random object that I created and planted its seed (with the constructor Random(long)), since it makes life much easier when trying to reproduce some unexpected behavior later on.
    { "pile_set_name": "StackExchange" }
    Q: Preposition for conversion to another unit Which preposition should be used when I want to say a value in a different measure unit? For example, what is a correct preposition in the following sentence? Twelve miles? I have no idea how far that is. What is it __ kilometres? A: It depends a bit on the verb. Often you use "in" What is 12 miles in kilometres? (answer: about 19 km) But with "change" you say "Please change 12 miles to kilometres" or "into kilometres".
    { "pile_set_name": "StackExchange" }
    Q: How to solve the following logarithm? How to solve this?? The solution is 1001. A: Hints: justify using the basic properties of logarithms the following $$\log(x-1)+\log\sqrt[3]{x^2-1}=4+\frac13\log(x+1)\iff$$ $$\iff\log\left(\frac{(x-1)\sqrt[3]{(x-1)(x+1)}}{\sqrt[3]{x+1}}\right)=4\iff$$ $$\frac43\log(x-1)=4\iff\log(x-1)=3\iff x-1=10^3\;\ldots$$
    { "pile_set_name": "StackExchange" }
    Q: Re-rendering jQuery function So, I have following jquery function: jQuery('.button').click(function(e) { if(!isMobile) { jQuery('.button').featherlight({ }); } }) This creates an lightbox at the bottom of <body> like below: Before lightbox is opened: <body> <button> Show lightbox</button> <script src="https://...jquery.min.js"></script> <script src="https://...custom_js.js"></script> </body> After lightbox is opened: <body> <button> Show lightbox</button> <script src="https://...jquery.min.js"></script> <script src="https://...custom_js.js"></script> <div class="lightbox">Lightbox content</div> </body> Problem is that none of the jQuery function inside of this lightbox works as it was created after the page was loaded. How do I "re-render" a js file after the lightbox is created? Thanks! Here is an example: jQuery('#tags').keyup(function(e){ console.log(e); if(e.which == 188) { var tag = ...; var data = '<button>tag</button>'; tags.push(tag); jQuery('.tags ul').append(data); jQuery(this).val(''); } }); Here, a tag input will be "appended" or added to a div class="tags". However inside of the lightbox, this function is not executed at all. A: Re-rendering a JS file is not how javascript is supposed to work. What I recommend you to do is to run the a function in the afterContent callback. As you can see in the featherlight documentation, there is a plenty of callbacks that can help you with this. Example: jQuery('.button').click(function(e) { if(!isMobile) { jQuery('.button').featherlight({ afterContent: function () { // Do your code here // The lightbox content will be ready } }); } })
    { "pile_set_name": "StackExchange" }
    Q: Root my EVO wihtout USB cord I want to root my EVO... but my charging port is broken (I've been using an external battery charger to get around this). Anyway to get the files I need to root my EVO onto my EVO without using this cable? I was thinking about going through Box or Dropbox or something like that but I'm not sure how to download these files into a specific folder on my EVO. Thanks. A: You can always put the files on an SD card and transfer them to your internal storage from there, but as was said in the comments, if something happens during the process and you are unable to boot your phone, the only way to recover from that is to reflash it from the computer, using the usb cable. You can use Titanium Backup to back all of your apps up onto the SD card, and hopefully you keep everything you can backed up through Google, but you still would have an unusable phone if something happened.
    { "pile_set_name": "StackExchange" }
    Q: Sliding Current Carousel Item in Bootstrap Modal Slider I am trying to create a simple lightbox using Bootstrap carousel and Modal. Please take a look at sample file which I have here. What I would like to do is starting the Modal Carousel as same slide (current slide) of the main carousel. As you can see from the example when I start the Modal it just start from the first item but I need to start from current active slide. Can you please let me know how to do this? <div class="container"> <div class="well span9 columns"> <div id="myCarousel" class="carousel slide"> <div class="carousel-inner"> <div class="item active"> <a href=".bell" data-toggle="modal"><img src="http://bootstrapdocs.com/v2.0.3/docs/assets/img/bootstrap-mdo-sfmoma-01.jpg" alt=""/></a> </div> <div class="item"> <img src="http://bootstrapdocs.com/v2.0.3/docs/assets/img/bootstrap-mdo-sfmoma-02.jpg" alt=""/> </div> <div class="item"> <img src="http://bootstrapdocs.com/v2.0.3/docs/assets/img/bootstrap-mdo-sfmoma-03.jpg" alt=""/> </div> </div> <a class="left carousel-control" href="#myCarousel" data-slide="prev">‹</a> <a class="right carousel-control" href="#myCarousel" data-slide="next">›</a> </div> <!-- Modal --> <div id="bell" class="modal hide fade bell" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Modal header</h3> </div> <div class="modal-body"> <div id="myCarousel2" class="carousel slide"> <div class="carousel-inner"> <div class="item active"> <img src="http://bootstrapdocs.com/v2.0.3/docs/assets/img/bootstrap-mdo-sfmoma-01.jpg" alt=""/> </div> <div class="item"> <img src="http://bootstrapdocs.com/v2.0.3/docs/assets/img/bootstrap-mdo-sfmoma-02.jpg" alt=""/> </div> <div class="item"> <img src="http://bootstrapdocs.com/v2.0.3/docs/assets/img/bootstrap-mdo-sfmoma-03.jpg" alt=""/> </div> </div> <a class="left carousel-control" href="#myCarousel2" data-slide="prev">‹</a> <a class="right carousel-control" href="#myCarousel2" data-slide="next">›</a> </div> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> </div> <div class="btn-group" data-toggle="buttons-radio"> <button type="button" class="btn btn-inverse"><a href=".bell" data-toggle="modal"><i class="icon-resize-full icon-white"></i></a> </button> </div> </div> Thansk A: This seems to work. $('.bell').on('show', function() { var targetSlide = parseInt($('#myCarousel .active').index('#myCarousel .item')); $('#myCarousel2').carousel(targetSlide); }); This gets the current index showing on the main carousel. $('#myCarousel .active').index('#myCarousel .item') This sets the current slide of the modal carousel. $('#myCarousel2').carousel(/*Number here*/); Here is a jsFillde with the above code.
    { "pile_set_name": "StackExchange" }
    Q: Flex 4.5 - unique computer information I am developing a flex 4.5 web based application and I need to make sure if the client chooses a certain level of security, each user can log only from an authorized computer. So the question is how can I get some unique computer information? Anything like HDD serial number, CPU specifications, motherboard information, even the user that is logged into the Operating System can do. So far the information on the web isn't giving me much hope that this can be achieved, but I had to ask. Thanks in advance. A: This is not easy using a browser based Flex application, but there are some workarounds. The browser based Flash Player can communicate with an AIR app on the desktop using localconnection. So, you could create an AIR app that utilizes NativeProcess to retrieve your machine specific information. You could also use NativeProcess from a AIR app without using the browser at all. A third option would be to install an application server on the client machine and have the browser based app communicate with the server to retrieve the client information. I consider most of these options too difficult to be practical, but it depends on how important this feature is to you.
    { "pile_set_name": "StackExchange" }
    Q: android - php fetch mysql data by user id This my PHP URL for fetching the data from MySQL. I need to make mysqli_fetch_array code saying if filled uid in the app-data table is the same with uid in users table fetch the data from all row in app-data to the uid like every user show his items from app-data table. $host = ""; $user = ""; $pwd = ""; $db = ""; $con = mysqli_connect($host, $user, $pwd, $db); if(mysqli_connect_errno($con)) { die("Failed to connect to MySQL: " . mysqli_connect_error()); } $sql = "SELECT * FROM app_data ORDER By id"; $result = mysqli_query($con, $sql); $rows = array(); while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { $rows[] = $row; } mysqli_close($con); echo json_encode($rows); A: I think this is the correct answer: <?php $host = ""; $user = ""; $pwd = ""; $db = ""; $con = mysqli_connect($host, $user, $pwd, $db); if(mysqli_connect_errno($con)) { die("Failed to connect to MySQL: " . mysqli_connect_error()); } $sql = "SELECT * FROM app_data WHERE u_id=".$_POST['posted_uid']." ORDER By id"; $result = mysqli_query($con, $sql); $rows = array(); while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { $rows[] = $row; } mysqli_close($con); echo json_encode($rows); Little tip for the future: Don't search exactly what you want, only search in parts.
    { "pile_set_name": "StackExchange" }
    Q: How to create functions like std::cout? I'm creating my own logging utility for my project, I want to create a function like iostream's std::cout, to log to a file and print to the console as well. Here's what i want: enum { debug, error, warning, info }; LOG(level) << "test"; // level - from the above enum The result should be like this: int iPlayerID = 1337; LOG(info) << "Player " << iPlayerID << "Connected"; [Thu Jan 29 18:32:11 2015] [info] Player 1337 Connected A: std::cout is not a function, it's an object of type std::ostream which overloads operator<<. A quick sketch of how you could do it: enum Level { debug, error, warning, info }; struct Logger { std::ostream* stream; // set this in a constructor to point // either to a file or console stream Level debug_level; public: Logger& operator<<(const std::string& msg) { *stream << msg; // also print the level etc. return *this; } friend Logger& log(Logger& logger, Level n); { logger.debug_level = n; return logger; } }; Ant then use it like Logger l; log(l, debug) << "test"; A: The trick is for your LOG(level) to return a special type which contains a pointer to an std::ostream, and defines the << operator. Something like: class LogStream { std::ostream* myDest; public: LogStream( std::ostream* dest ) : myDest( dest ) {} template <typename T> LogStream& operator<<( T const& obj ) { if ( myDest != nullptr ) { *myDest << obj; } return *this; } }; The LOG(level) macro creats an instance of one, something like: #define LOG(level) LogStream( getLogStream( level, __FILE__, __LINE__ ) ) Of course, the getLogStream may insert any information it wants (like a timestamp) at the moment it is called. You might want to add a flush in the destructor of LogStream.
    { "pile_set_name": "StackExchange" }
    Q: Extract text from html tags using reduce in Javascript I'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try: // JS let par = Array.from(document.getElementsByTagName("p")); document.write(par.reduce((a, b) => a + ", " + b.innerHTML)); <!-- HTML --> <p>Apple</p> <p>Strawberry</p> <p>Banana</p> And here's the (wrong) output: [object HTMLParagraphElement], Strawberry, Banana What am I doing wrong? Many thanks for your help! A: reduce function takes a 2nd argument which is the initial value for the accumulator. By default, it's the first item in the array. To have the desired result you should write your code like this: let par = Array.from(document.getElementsByTagName("p")); document.write(par.reduce((a,b)=>a+", "+b.innerHTML, "")); Here is a document on reduce function from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a
    { "pile_set_name": "StackExchange" }
    Q: How do I apply weights to particular columns in a dataframe to aggregate a new 'score' column? By way of reproducible example, say you have the following R dataframe: set.seed(100) df <- data.frame(Name=letters[1:5], Apples=sample(1:10, 5), Oranges=sample(1:10, 5), Bananas=sample(1:10, 5), Dates=sample(1:10, 5)) And you want to apply the following weights to the dataframe: Weights <- c(Apples = "3", Oranges = "2", Bananas = "1") To produce a new aggregate score column. So for example the first row (row 'a') would have the following score: (3*4 + 2*5 + 1*7) = 29 And row b: (3*3 + 2*8 + 1*8) = 33 What code I write to do this automatically? Note that the weights may not be in the same order as the columns in the dataframe, nor will there necessarily be a weight for every numeric column in the dataframe (hence why in this example there is no weight for 'dates'). A: We can use rowSums after multiplying the subset of columns in 'df' by the corresponding elements in 'Weights' (by replicating the 'Weights') rowSums(df[names(Weights)]*as.numeric(Weights)[col(df[names(Weights)])]) #[1] 29 33 24 20 36
    { "pile_set_name": "StackExchange" }
    Q: Qt Auto-UI Testing stopping because of messagebox. How to simulate enter on messagebox? My task is to write an automated UI test for a software being developed. It happens so, that there are radiobuttons triggering a messagebox, which stops my automated test until I manually confirm it (pressing ENTER). The issue is that I do not know how I can call that newly summoned messagebox and then have it confirmed by QTest::keyClick(<object>, QtKey::Key_Enter); and have my automated test continue the run. I am using QWidgets, QApplication, Q_OBJECT and QtTest. I will provide a code similar to what I am working with: void testui1(){ Form1* myform = new Form1(); myform->show(); QTest::mouseClick(myform->radioButton01, Qt::LeftButton, Qt::NoModifier, QPoint(), 100); // Message box pops up and stops the operation until confirmed QTest::mouseClick(myform->radioButton02, Qt::LeftButton, Qt::NoModifier, QPoint(), 100); // again ... } How exactly can I script to confirm the message box automatically? The message box is only an [OK] type, so I don't need it to return whether I have pressed Yes or No. A QTest::keyClick(<target object>, Qt::Key_Enter) method needs to know to which object it should press enter to. I tried including myform into the object and it did not work. Googling I did not find the answer. I found the following result as not functioning for what I am looking for QWidgetList allToplevelWidgets = QApplication::topLevelWidgets(); foreach (QWidget *w, allToplevelWidgets) { if (w->inherits("QMessageBox")) { QMessageBox *mb = qobject_cast<QMessageBox *>(w); QTest::keyClick(mb, Qt::Key_Enter); } } A: The problem is that once you've "clicked" on your radio button, which results in QMessageBox::exec being called, your code stops running until the user clicks on of the buttons. You can simulate the user clicking a button by starting a timer before you click on the radio button. In the callback function for the timer you can use QApplication::activeModalWidget() to obtain a pointer to the message box, and then just call close on it. QTimer::singleShot(0, [=]() { QWidget* widget = QApplication::activeModalWidget(); if (widget) widget->close(); }); If you want to press a specific key on the message box, you can use QCoreApplication::postEvent to post a key event to the message box QTimer::singleShot(0, [=]() { int key = Qt::Key_Enter; // or whatever key you want QWidget* widget = QApplication::activeModalWidget(); if (widget) { QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier); QCoreApplication::postEvent(widget, event); } }); So in terms of how this ties into the sample code you gave: void testui1() { Form1* myform = new Form1(); myform->show(); QTimer::singleShot(0, [=]() { QWidget* widget = QApplication::activeModalWidget(); if (widget) widget->close(); else QFAIL("no modal widget"); }); QTest::mouseClick(myform->radioButton01, Qt::LeftButton, Qt::NoModifier, QPoint(), 100); } A sample app putting all the above together: #include <QApplication> #include <QMainWindow> #include <QHBoxLayout> #include <QPushButton> #include <QTimer> #include <QMessageBox> #include <iostream> int main(int argc, char** argv) { QApplication app(argc, argv); QMainWindow window; QWidget widget; window.setCentralWidget(&widget); QHBoxLayout layout(&widget); QPushButton btn("go"); layout.addWidget(&btn); QObject::connect(&btn, &QPushButton::clicked, [&]() { QTimer::singleShot(0, [=]() { QWidget* widget = QApplication::activeModalWidget(); if (widget) { widget->close(); } else { std::cout << "no active modal\n"; } }); QMessageBox( QMessageBox::Icon::Warning, "Are you sure?", "Are you sure?", QMessageBox::Yes | QMessageBox::No, &window).exec(); }); window.show(); return app.exec(); } Clicking on Go will look like nothing is happening, as the QMessageBox is closed immediately. To prove that the message box is shown and then closed you can increase the time in the call to QTimer::singleShot to a value such as 1000. Now it will show the message box for 1 second, and then it will be closed by the timer.
    { "pile_set_name": "StackExchange" }
    Q: Use years / Years of Use? I am writing a paper about pipelines in Seoul.. And I have a grammatical problem to describe pipeline's years of use... I'd like to describe the time passed since they were installed. Which one is correct and natural? 'Use years of pipelines in Seoul,Korea' 'Years of use of pipelines in Seoul,Korea' 'Pipelines' use years in Seoul,Korea' A: Use years… or Years of use… or Pipelines' use years… look like titles, not parts of the report. If those are the given choices, my vote would go to Years of use of pipelines… but in real life I’d expect Life expectancy of… or something like Planned and achieved years of use… Are these pipelines planned or payed for in man years, calendar years or how, please? Train operators use track miles, route miles, passenger miles and other equally different measures of the same line on a map even before they take time into account but the grammar shouldn’t change. Here, if the pipe is replaced or painted, the maintenance guys will presumably be interested in the life expectancy of the parts, not the whole pipe-line, and measure that in something like pipe-years or paint-years, not pipe-line years.
    { "pile_set_name": "StackExchange" }
    Q: I need to display images next to text I am new to HTML and CSS, first year IT student. I need to display text and pictures next to each other. The text should occupy most of the page with the images to the right of the text. I know I will need to use CSS for this but I have no idea how. <!-- Add images of accepted payment Methods --> <div class="Pics"> <img src="Edgars.jpg" alt="Logo of Edgars Thank U Card"> <img src="Jet.PNG" alt="Logo of Jet Thank U Card"> <img src="VisaCard.jpg" alt="Logo of Visa Card"> <img src="MasterCards.png" alt="Logo of Master Card"> <img src="SnapScan.png" alt="Logo of SnapScan"> <img src="Standard Bank.png" alt="Logo of Standard Bank"> </div> <!-- Adding paragraphs --> <h6 id="h06">Payment Methods</h6> <p id="headings">Edgars or Jet Card:</p> <p>Visit any of our Campuses that accept Debit and Credit Cards, and you can also pay with your Edgars or Jet Card! Please note that your Edgars or Jet Thank U Card along with the Card Holder must be present for the transaction. Proof of ID will be required</p> <p id="headings">Debit or Cerdit Card:</p> <p>A cardholder begins a credit card transaction by presenting his or her card to a merchant as payment for goods or services. The merchant uses their credit card machine, software or gateway to transmit the cardholder’s information and the details of the transaction to their acquiring bank, or the bank’s processor. </p> <p id="headings">SnapScan</p> <p>Download the SnapScan App to your Mobile Phone or Tablet Device. Open the SnapScan App, tap on “Scan” and scan the SnapCode displayed at the shop. This identifies the shop and prompts you to enter the amount you wish to pay. Enter your PIN to secure and complete the transaction. Richfield will receive a notification containing a confirmation of payment from SnapScan and your account will be updated accordingly.</p> <p id="headings">Standard Bank M65 Cash Payment</p> <p>Direct Cash Deposits can be made at any branch of Standard Bank using the M65 form which can be obtained from your nearest Campus. This form can only be used at Standard Bank branches. Don’t forget to ensure that your name AND student number are on both sections of the form.</p> <p id="headings">Electronic Funds Transfer (or CDI)</p> <p>Name of Bank: Standard Bank of South Africa</p> <p>Name of Account: Richfield Graduate Institute of Technology (PTY) Ltd.</p> <p>USE YOUR ICAS NUMBER, INITIALS AND SURNAME AS REFERENCE</p> </div> I've tried numerous examples online but I can't seem to get it to work. Below is a picture of how it's supposed to look. Any help will be appreciated. Thank you in advance A: flex is definitely the way to go. This should get you started. If you upload your pictures to imgur we could see how the actual images work html,body{ margin:0; padding:0; } #container{ display:flex; width:100vw; } #left{ display:flex; flex-direction:column; width:70%; } #right{ display:flex; width:30%; justify-content:center; margin-top:25%; } #group1,#group2{ display:flex; flex-direction:column; } <div id='container'> <div id='left'> <!-- Adding paragraphs --> <h6 id="h06">Payment Methods</h6> <p id="headings">Edgars or Jet Card:</p> <p>Visit any of our Campuses that accept Debit and Credit Cards, and you can also pay with your Edgars or Jet Card! Please note that your Edgars or Jet Thank U Card along with the Card Holder must be present for the transaction. Proof of ID will be required</p> <p id="headings">Debit or Cerdit Card:</p> <p>A cardholder begins a credit card transaction by presenting his or her card to a merchant as payment for goods or services. The merchant uses their credit card machine, software or gateway to transmit the cardholder’s information and the details of the transaction to their acquiring bank, or the bank’s processor. </p> <p id="headings">SnapScan</p> <p>Download the SnapScan App to your Mobile Phone or Tablet Device. Open the SnapScan App, tap on “Scan” and scan the SnapCode displayed at the shop. This identifies the shop and prompts you to enter the amount you wish to pay. Enter your PIN to secure and complete the transaction. Richfield will receive a notification containing a confirmation of payment from SnapScan and your account will be updated accordingly.</p> <p id="headings">Standard Bank M65 Cash Payment</p> <p>Direct Cash Deposits can be made at any branch of Standard Bank using the M65 form which can be obtained from your nearest Campus. This form can only be used at Standard Bank branches. Don’t forget to ensure that your name AND student number are on both sections of the form.</p> <p id="headings">Electronic Funds Transfer (or CDI)</p> <p>Name of Bank: Standard Bank of South Africa</p> <p>Name of Account: Richfield Graduate Institute of Technology (PTY) Ltd.</p> <p>USE YOUR ICAS NUMBER, INITIALS AND SURNAME AS REFERENCE</p> </div> <div id='right'> <div id='group1' class="Pics"> <img src="Edgars.jpg" alt="Edgars"> <img src="Jet.PNG" alt="Jet"> <img src="VisaCard.jpg" alt="Visa"> </div> <div id='group2' class='Pics'> <img src="MasterCards.png" alt="Master"> <img src="SnapScan.png" alt="SnapScan"> <img src="Standard Bank.png" alt="Standard"> </div> </div> </div>
    { "pile_set_name": "StackExchange" }
    Q: Photoshop Script change each successive image I have a script that batch processes images, adding a radial blur on the blue channel. What I want to do is change the radial blur's origin or centre point in each successive image. Is there a way of scripting this? At the moment for the first image, when I recorded the action, i placed the centre point manually, photoshop must have some code somewhere to show what I did. Any ideas on how to access this? It's a series of the sun shining through trees, I want the radial blur to track from one side to the other like the sun does in the images (timelapse) A: This kind of automation control isn't really available using just Photoshop actions, to go that deep you'll need to leverage Photoshop's Scripting API. Unfortunately I don't have much knowledge on the PS API; I'd recommend visiting ps-scripts.com, hopefully you can find some experts there.
    { "pile_set_name": "StackExchange" }
    Q: Parameterize ORM query with where in clause I'm trying to parametrize a query that is currently working and is ripe for an SQL injection attack: qryAwards = ORMExecuteQuery( "from Award where awardID in (#form.deleteAwardList#) and Game.Season.User.userID=:uid", {uid=session.userID} ); if(not isNull(qryAwards) and arrayLen(qryAwards)){ for(i in qryAwards){ entityDelete(i); } } I tried this, having the param without single quotes: qryAwards = ORMExecuteQuery( "from Award where awardID in (:awardList) and Game.Season.User.userID=:uid", {awardList=form.deleteAwardList, uid=session.userID} ); I keep getting the following error: The value 117,118 cannot be converted to a number. And this, with the param enclosed in single quotes: qryAwards = ORMExecuteQuery( "from Award where awardID in (':awardList') and Game.Season.User.userID=:uid", {awardList=form.deleteAwardList, uid=session.userID} ); Gets me the following error: Invalid parameters specified for the query. A: In HQL (which is what you use when you do ORMExecuteQuery() ) parameters used in an IN clause need to be passed as an array. You need to convert form.deleteAwardList to an array. There are a few different ways to handle this, but this will work. qryAwards = ORMExecuteQuery( "from Award where awardID in (:awardList) and Game.Season.User.userID=:uid", {awardList=listToArray( form.deleteAwardList ), uid=session.userID} );
    { "pile_set_name": "StackExchange" }
    Q: <> symbol in type name in C# Please help me understand what this is : <> I am doing some reflection looking for types in an assembly and I get a bunch of types, all with the same name, but different methods : {Name = "<>c__DisplayClass1" FullName = "HelixToolkit.Wpf.ElementSortingHelper+<>c__DisplayClass1"} A: It's the naming convention that the compiler uses when translating lambda expressions into classes. Here's an example. Starting with this class: public class UserQuery { private void Main() { var x = 42; Func<int> f = () => x; var y = f(); } } The compiler turns this into: public class UserQuery { public UserQuery() { base..ctor(); } private void Main() { UserQuery.<>\u003C\u003Ec__DisplayClass1 cDisplayClass1 = new UserQuery.<>\u003C\u003Ec__DisplayClass1(); cDisplayClass1.x = 42; int num = new Func<int>((object) cDisplayClass1, __methodptr(<\u003CMain>\u003Eb__0))(); } [CompilerGenerated] private sealed class <>\u003C\u003Ec__DisplayClass1 { public int x; public <>\u003C\u003Ec__DisplayClass1() { base..ctor(); } public int <\u003CMain>\u003Eb__0() { return this.x; } } } Not legal c#, but legal IL.
    { "pile_set_name": "StackExchange" }
    Q: Swift 3 accessing nested dictionaries within json feed Hi I currently have a JSON feed: "hourly":{ "summary":"Breezy and partly cloudy tomorrow morning.", "icon":"wind", "data":[ { "time":1479222000, "summary":"Clear", "icon":"clear-night", "precipIntensity":0, "precipProbability":0, "temperature":25.09, "apparentTemperature":25.09, "dewPoint":21.56, "humidity":0.81, "windSpeed":1.13, "windBearing":72, "visibility":9, "cloudCover":0.1, "pressure":1015.18, "ozone":242.43 }, { "time":1479225600, "summary":"Clear", "icon":"clear-night", "precipIntensity":0, "precipProbability":0, "temperature":24.18, "apparentTemperature":24.18, "dewPoint":20.71, "humidity":0.81, "windSpeed":1.42, "windBearing":76, "visibility":9, "cloudCover":0.1, "pressure":1015.24, "ozone":242.3 } ] I can access "hourly" and "data" no problem with the following code: let hourly = json["hourly"] as? [String : Any], let data = hourly["data"] as? [[String : Any]] But what I need to do is access the first Dictionary only within data, which I cannot seem to figure out. Can anybody help please? A: You can use first property of Array like this. if let hourly = json["hourly"] as? [String : Any], let data = hourly["data"] as? [[String : Any]], let firstDic = data.first { print(firstDic) //If you want `summary` value from firstDic print(firstDic["summary"]) }
    { "pile_set_name": "StackExchange" }
    Q: How to display print statements interlaced with matplotlib plots inline in Ipython? I would like to have the output of print statements interlaced with plots, in the order in which they were printed and plotted in the Ipython notebook cell. For example, consider the following code: (launching ipython with ipython notebook --no-browser --no-mathjax) %matplotlib inline import matplotlib.pyplot as plt i = 0 for data in manydata: fig, ax = plt.subplots() print "data number i =", i ax.hist(data) i = i + 1 Ideally the output would look like: data number i = 0 (histogram plot) data number i = 1 (histogram plot) ... However, the actual output in Ipython will look like: data number i = 0 data number i = 1 ... (histogram plot) (histogram plot) ... Is there a direct solution in Ipython, or a workaround or alternate solution to get the interlaced output? A: There is simple solution, use matplotlib.pyplot.show() function after plotting. this will display graph before executing next line of the code %matplotlib inline import matplotlib.pyplot as plt i = 0 for data in manydata: fig, ax = plt.subplots() print "data number i =", i ax.hist(data) plt.show() # this will load image to console before executing next line of code i = i + 1 this code will work as requested
    { "pile_set_name": "StackExchange" }
    Q: Run-time error '9' Subscript out of range with Conditional Format code I'm very new to VBA (and any sort of programming in general), so I'm not sure how to proceed here. I'm guessing my error has something to do with overlapping ranges for my conditional formats as I also got errors when the code was set up a different way that were resolved once the ranges no longer overlapped. That might not be the case here, but I figured it'd be helpful to know. I get a 'Subscript out of range' error with the following code: Sub test2() Dim rngToFormat As Range Set rngToFormat = ActiveSheet.Range("$a$1:$z$1000") Dim rngToFormat2 As Range Set rngToFormat2 = ActiveSheet.Range("$k$20:$k$1000") Dim rngToFormat3 As Range Set rngToFormat3 = ActiveSheet.Range("$j$22:$j$1000") Dim rngToFormat4 As Range Set rngToFormat4 = ActiveSheet.Range("$i$22:$i$1000") Dim rngToFormat5 As Range Set rngToFormat5 = ActiveSheet.Range("$g$20:$g$1000") Dim rngToFormat6 As Range Set rngToFormat6 = ActiveSheet.Range("$d$9, $f$9") Dim rngToFormat7 As Range Set rngToFormat7 = ActiveSheet.Range("$G$3:$G$7,$G$11:$G$15,$E$3:$E$7,$E$11:$E$15,$N$3:$N$7,$N$11:$N$15,$L$3:$L$7,$L$11:$L$15") rngToFormat.FormatConditions.Delete rngToFormat.FormatConditions.Add Type:=xlExpression, _ Formula1:="=if(R[]C20=1, true(), false())" rngToFormat.FormatConditions(1).Font.Color = RGB(228, 109, 10) rngToFormat2.FormatConditions.Add Type:=xlExpression, _ Formula1:="=and(R[]C7=""6. Negotiate"", R[]C11<25)" rngToFormat2.FormatConditions(2).Font.ColorIndex = 3 rngToFormat2.FormatConditions.Add Type:=xlExpression, _ Formula1:="=and(R[]C7=""4. Develop"", R[]C11<15)" rngToFormat2.FormatConditions(3).Font.ColorIndex = 3 rngToFormat2.FormatConditions.Add Type:=xlExpression, _ Formula1:="=and(R[]C7=""5. Prove"", R[]C11<20)" rngToFormat2.FormatConditions(4).Font.ColorIndex = 3 rngToFormat2.FormatConditions.Add Type:=xlExpression, _ Formula1:="=and(R[]C7=""7. Committed"", R[]C11<30)" rngToFormat2.FormatConditions(5).Font.ColorIndex = 3 rngToFormat2.FormatConditions.Add Type:=xlExpression, _ Formula1:="=and(R[]C7=""Closed Won"", R[]C11<35)" rngToFormat2.FormatConditions(6).Font.ColorIndex = 3 rngToFormat3.FormatConditions.Add Type:=xlCellValue, _ Operator:=xlGreater, Formula1:=200 rngToFormat3.FormatConditions(7).Font.ColorIndex = 3 rngToFormat4.FormatConditions.Add Type:=xlCellValue, _ Operator:=xlGreater, Formula1:=60 rngToFormat4.FormatConditions(8).Font.ColorIndex = 3 rngToFormat5.FormatConditions.Add Type:=xlExpression, _ Formula1:="=or(R[]C7=""1. Plan"", R[]C7=""2. Create"", R[]C7=""3. Qualify"")" rngToFormat5.FormatConditions(9).Font.ColorIndex = 3 rngToFormat6.FormatConditions.Add Type:=xlCellValue, _ Operator:=xlLess, Formula1:=0 rngToFormat6.FormatConditions(10).Font.ColorIndex = 3 rngToFormat6.FormatConditions(10).Interior.Color = RGB(204, 204, 255) rngToFormat6.FormatConditions(10).Interior.Pattern = xlSolid rngToFormat7.FormatConditions.Add Type:=xlCellValue, _ Operator:=xlLess, Formula1:=0 rngToFormat7.FormatConditions(11).Font.ColorIndex = 3 rngToFormat7.FormatConditions(11).Interior.Color = RGB(215, 228, 158) rngToFormat7.FormatConditions(11).Interior.Pattern = xlSolid End Sub Any advice would be appreciated, thanks! A: There are two problems with your code: You only delete the conditional formats for the first range - but add conditions to all ranges - and later access a specific one that most likely is not the one you just created (FormatConditions(3)) The formulas you entered are the default english formulas - for some stange reason, FormatConditions.Add requires the local formulas though. I reworked your code, take a look if it solves your problem: Sub test2() fctApply rng:=Range("$a$1:$z$1000"), strFormulaR1C1:="=(R[]C20=1)", dblRGB:=RGB(228, 109, 10), blnDeleteOldConditions:=True fctApply rng:=Range("$k$20:$k$1000"), strFormulaR1C1:="=and(R[]C7=""6. Negotiate"",R[]C11<25)", intColorIndex:=3 fctApply rng:=Range("$k$20:$k$1000"), strFormulaR1C1:="=and(R[]C7=""4. Develop"", R[]C11<15)", intColorIndex:=3 fctApply rng:=Range("$k$20:$k$1000"), strFormulaR1C1:="=and(R[]C7=""5. Prove"", R[]C11<20)", intColorIndex:=3 fctApply rng:=Range("$k$20:$k$1000"), strFormulaR1C1:="=and(R[]C7=""7. Committed"", R[]C11<30)", intColorIndex:=3 fctApply rng:=Range("$k$20:$k$1000"), strFormulaR1C1:="=and(R[]C7=""Closed Won"", R[]C11<35)", intColorIndex:=3 fctApply rng:=Range("$j$22:$j$10000"), strFormulaR1C1:=200, intType:=xlCellValue, intOperator:=xlGreater, intColorIndex:=3 fctApply rng:=Range("$i$22:$i$1000"), strFormulaR1C1:=60, intType:=xlCellValue, intOperator:=xlGreater, intColorIndex:=3 With fctApply(rng:=Range("$g$20:$g$1000"), strFormulaR1C1:=0, intType:=xlCellValue, intOperator:=xlLess, intColorIndex:=3) .Interior.Color = RGB(204, 204, 255) .Interior.Pattern = xlSolid End With With fctApply(rng:=Range("$G$3:$G$7,$G$11:$G$15,$E$3:$E$7,$E$11:$E$15,$N$3:$N$7,$N$11:$N$15,$L$3:$L$7,$L$11:$L$15"), strFormulaR1C1:=0, intType:=xlCellValue, intOperator:=xlLess, intColorIndex:=3) .Interior.Color = RGB(215, 228, 158) .Interior.Pattern = xlSolid End With End Sub Private Function fctApply(rng As Range, _ strFormulaR1C1 As Variant, _ Optional intType As XlFormatConditionType = xlExpression, _ Optional intOperator As XlFormatConditionOperator, _ Optional intColorIndex As Integer = -1, _ Optional dblRGB As Double = -1, _ Optional blnDeleteOldConditions As Boolean = False _ ) As FormatCondition Dim objCond As FormatCondition Dim strFormula As String If blnDeleteOldConditions Then rng.FormatConditions.Delete strFormula = Application.ConvertFormula(strFormulaR1C1, xlR1C1, xlA1) On Error GoTo ConvertLocal If intOperator <> 0 Then rng.FormatConditions.Add Type:=intType, _ Formula1:=strFormula, Operator:=intOperator Else rng.FormatConditions.Add Type:=intType, _ Formula1:=strFormula End If On Error GoTo 0 Set objCond = rng.FormatConditions(rng.FormatConditions.Count) If intColorIndex <> -1 Then objCond.Font.ColorIndex = intColorIndex ElseIf dblRGB <> -1 Then objCond.Font.Color = dblRGB End If Set fctApply = objCond Exit Function ConvertLocal: With Range("A1") 'change this to an empty cell address - it is temporarily used to translate from local to normal formulas .Formula = strFormula strFormula = .FormulaLocal .Formula = "" End With Resume End Function
    { "pile_set_name": "StackExchange" }
    Q: Is this 'new releases in SF&F' question on topic? This question has been closed, (not edited) and then reopened, and is now getting close votes again. One user even voted to both close and reopen it. Seems like we don't know what to do with this question. The main thrust of it is: Where do you guys find out about recently published novels in Science Fiction and Fantasy? I'm not interested in reviews, news on which writer might write what, which bookstore has closed, conventions etc., just a simple list of everything that is newly available in bookstores. They're looking for resources that provide thorough listings of Sci-fi & Fantasy book releases. Is this on topic, or off topic? Why? A: I think the question is fine. The scope is well-defined, and it doesn't seem likely that there will be so many answers that we'd risk a lot of "me too" answers. While there could be several different yet acceptable, answers, I don't think that's sufficient reason to close it. The subject itself is both relevant and of potential interest to a significant number of our members. A: This seems like an unanswerable question. Sure, a few good sites could be recommended, but in the end, any number of answers could be equally acceptable. Given that possibility, it seems like it's not really a good question for Stack Exchange.
    { "pile_set_name": "StackExchange" }
    Q: How to make ordinal tick labels adjust automatically in D3 As you can see in the example, the tick labels on an ordinal axis (scale) become crowded and illegible as the domain grows. How can I make them adjust automatically as they would on a linear axis? (I suppose I could use a linear scale instead, but this question and the answer from Mike Bostock himself suggest that the ordinal scale is more appropriate for this type of data. After all, the domain is discrete and I'm making a modified bar chart, where a convenient padding setting is useful.) var x0 = d3.scaleBand() .domain(d3.range(1,6)) .range([0,200]); var x = d3.scaleBand() .domain(d3.range(1,51)) .range([0,200]); var xLinear = d3.scaleLinear() .domain([1,50]) .range([0,200]); d3.select('svg').append('g') .attr('transform', 'translate(10,10)') .call(d3.axisBottom(x0)); d3.select('svg').append('g') .attr('transform', 'translate(10,50)') .call(d3.axisBottom(x)); d3.select('svg').append('g') .attr('transform', 'translate(10,100)') .call(d3.axisBottom(xLinear)); <script src="https://d3js.org/d3.v4.min.js"></script> <svg width='300' height='150'></svg> A: This solution takes advantage of the very smart built-in function d3.ticks(), which deals with edge cases so we don't have to. var dataSmall = d3.range(1,8), dataLarge = d3.range(1, 51); var xS = d3.scaleBand() .domain(dataSmall) .rangeRound([0,200]); var xL = d3.scaleBand() .domain(dataLarge) .rangeRound([0,200]); function makeAxis(scale) { var n=5, data = scale.domain(), dataLength = data.length; return d3.axisBottom(scale).tickValues( dataLength > n ? d3.ticks(data[0], data[dataLength-1], n) : data); } d3.select('svg').append('g') .attr('transform', 'translate(10,10)') .call(makeAxis(xS)); d3.select('svg').append('g') .attr('transform', 'translate(10,50)') .call(makeAxis(xL)); <script src="https://d3js.org/d3.v4.min.js"></script> <svg width='300' height='150'></svg>
    { "pile_set_name": "StackExchange" }
    Q: Elementary symmetric functions of reciprocals of monic polynomials in function fields Let $q$ be a prime power and $\mathbb{F}_q$ the field of cardinality $q$. Let $A = \mathbb{F}_q[T]$ and let $A_+ \subset A$ be the monic polynomials. Choose any ordering $<$ of $A_+$ and let $k$ be a positive integer. Set $$e(k) = \sum_{\begin{matrix} a_1, a_2, \ldots, a_k \in A_+ \\ a_1<a_2<\cdots<a_k \end{matrix}} \frac{1}{a_1 a_2 \cdots a_k}$$ where the sum is considered in the $T^{-1}$-adic topology. In non-archimedean analysis there is no need to discuss the order of summation. I'm trying to find out what is known about algebraic relations between the $e(k)$ over $\mathbb{F}_q(T)$. Here is what I have found so far: The $e(k)$ are very close to the Taylor coefficients of Thakur's geometric $\Gamma$ function: $$\tfrac{1}{\Gamma(z)} = z \prod_{a \in A_+} (1+z/a).$$ (See Thakur, 1991, Section 5.) But the papers I found in a quick search concentrate on evaluating $\Gamma$ at points of $\mathbb{F}_q(T)$, not the coefficients of the Taylor series. The sum $\zeta(k) = \sum_{a \in A_+} \tfrac{1}{a^k}$ is in the ring generated by the $e(k)$. This sum is called the Goss $\zeta$-function and is very well understood: We have the relations $\zeta(kp) = \zeta(k)^p$ and $\zeta((q-1) m) = B(m) \pi^{(q-1)m}$ (for positive integer $m$) where $B(m)$ is an element of $\mathbb{F}_q(t)$ analogous to a Bernoulli number and $\pi$ is a transcendental element of $\mathbb{F}_q[[(-T)^{-1/(q-1)}]]$. Other than these relations, the $\zeta(m)$ are algebraically independent over $\mathbb{F}_q(T)$. See Yu, 1991. Newton's identities show that the ring generated by the $e(k)$ is the same as the ring generated by the $\zeta(k)$ and the $e(pk)$. Obviously, this leaves room for the ring generated by the $e(k)$ to be much larger. Is the ring generated by the $e(k)$ actually this much larger, or am I missing a trick? Chang 2012 and others study $$\zeta(s_1, s_2, \ldots, s_k):= \sum_{\deg(a_1) < \deg(a_2) < \cdots < \deg(a_k)} \frac{1}{a_1^{s_1} \cdots a_k^{s_k}}.$$ Is this version of multiple $\zeta$ values related to my question, or is it unrelated? If we remove the monic condition in the summation, then the sum is of the form $\pi^k Q(k)$ for some $Q(k) \in \mathbb{F}_q(T)$. This is Proposition 2.1 in this note of mine. The reason I started going into this question is that I am spending today adding references to this paper in preparation to putting it on the arXiv and sending it off. A: Many of the various types of function field valued multiple zeta values (MZV's) were first defined by Dinesh Thakur in his book "Function Field Arithmetic" from 2004 (see section 5.10). He considers several possible definitions, for example $$ \zeta_l(s_1, \ldots, s_k) = \sum_{\substack{a_1, \ldots, a_k \in A_+ \\ a_1 > \cdots > a_k}} \frac{1}{a_1^{s_1} \cdots a_k^{s_k}} \in \mathbb{F}_q((T^{-1})), $$ where the ordering is an arbitrarily chosen lexicographic ordering of $A_+$ and $s_1, \ldots, s_k$ are positive integers. It seems then that your value $e(k)$ is $\zeta_l(1, \ldots, 1)$ of depth $k$. He also defines $$ \zeta_d(s_1, \ldots, s_k) = \sum_{\substack{a_1, \ldots, a_k \in A_+ \\ \deg a_1 > \cdots > \deg a_k}} \frac{1}{a_1^{s_1} \cdots a_k^{s_k}}, $$ which is the type of MZV you mentioned studied by Chang. He also defines a couple of other variants. To address one of your questions, from what Thakur says in Remark 5.10.16, it would appear that the $e(k)$'s are probably not algebraically related to the MZV's $\zeta_d(s_1, \dots, s_k)$. Anderson and Thakur ("Multizeta values for $\mathbb{F}_q[t]$, their period interpretation, and relations between them", IMRN, 2009) showed that the MZV's $\zeta_d(s_1,\dots, s_k)$ defined using degrees can be realized as periods of certain higher dimensional Drinfeld modules (Anderson $t$-modules) that are iterated extensions of tensor powers of the Carlitz module. They then can also be expressed as linear combinations of values of Carlitz multiple polylogarithm functions. Using this period interpretation various bits of transcendence machinery can be applied, which is the subject of the paper you mention by Chang (Compositio, 2014). Thakur mentions in that same remark 5.10.16 that the lexicographic MZV's $\zeta_l(s_1, \dots, s_k)$ do not have natural relations with periods of Drinfeld modules, so at least on the surface they seem to represent a different class of numbers than the $\zeta_d(s_1, \dots, s_k)$'s. Thakur follows this up with numerical calculations when $q=2$ and shows that they do not appear to be rational multiples of Carlitz zeta values. Of course this does not answer your question definitively, but I think it would be safe to say that it is not known whether there are any general relations. Also, one minor correction: when you remark that it was shown that the Carlitz zeta values $\zeta(m)$ are algebraically independent over $\mathbb{F}_q(T)$ (aside from the known relations involving Bernoulli-Carlitz numbers and $p$-th powers), this result is actually due to Chang and Yu ("Determination of algebraic relations among special zeta values in positive characteristic," Adv. Math. 216 (2007), 321-345). In the 1991 paper of Yu, he proves that the values are all transcendental over $\mathbb{F}_q(T)$, but the algebraic independence questions were answered later.
    { "pile_set_name": "StackExchange" }
    Q: How can I set a custom font for the action bar text, and make it happen from startup? I can't get it done. My App starts with the standard font, the custom activity layout is inflated, and just then my font changes. As far as I know, I cannot directly code a custom font into the xml file of the layout I intend to inflate onto the action bar, so I got a code from another topic on the net about doing the change by referencing the TextView in the action bar and setting it in the class. Is there actually a way to make the font "standard", so that the app will already startup showing my custom font? Here is the relevant code for the main activity, which I'm trying to change: public class Amd extends Activity { DatabaseHandler dh = new DatabaseHandler(this); public ProgressDialog mProgressDialog; public JSONObject jsonOb; public Filme m; public ArrayList<Genero> g; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.amd); setActionBar(); } @SuppressLint("InflateParams") private void setActionBar(){ this.getActionBar().setDisplayShowCustomEnabled(true); LayoutInflater inflator = LayoutInflater.from(this); View v = inflator.inflate(R.layout.custom_action_bar, null); Typeface font = Typeface.createFromAsset(this.getAssets(), "tcb.ttf"); TextView textoActionBar = (TextView) getWindow().findViewById(Resources.getSystem().getIdentifier("action_bar_title", "id", "android")); textoActionBar.setTypeface(font); textoActionBar.setText("TESTE"); this.getActionBar().setCustomView(v); } Here is the styles xml, which I am also using to theme and color the action bar: <resources xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. --> <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <!-- API 14 theme customizations can go here. --> <item name="android:actionBarStyle">@style/PurpleActionBar</item> </style> <style name="PurpleActionBar" parent="@android:style/Widget.Holo.Light.ActionBar"> <item name="android:background">#5D4480</item> <item name="android:titleTextStyle">@style/ActionText</item> </style> <style name="ActionText" parent="@android:style/TextAppearance"> <item name="android:textColor">#975CE6</item> </style> </resources> Here is the manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.virosys.amd" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="16" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppBaseTheme" > <activity android:name="com.virosys.amd.activities.Amd" android:label="AMD" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Here is the layout I'm inflating to the main activity: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@color/Purple" tools:context="com.virosys.amd.activities.Amd" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal" > <ImageButton android:id="@+id/imageButton1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginLeft="4dp" android:layout_marginTop="4dp" android:layout_marginRight="2dp" android:layout_marginBottom="2dp" android:onClick="listasOuFilmes" android:scaleType="fitXY" android:background="@null" android:src="@drawable/filmes" /> <ImageButton android:id="@+id/imageButton2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginRight="4dp" android:layout_marginTop="4dp" android:layout_marginLeft="2dp" android:layout_marginBottom="2dp" android:onClick="buscarFilme" android:scaleType="fitXY" android:background="@null" android:src="@drawable/busca" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal" > <ImageButton android:id="@+id/ImageButton3" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginLeft="4dp" android:layout_marginBottom="4dp" android:layout_marginRight="2dp" android:layout_marginTop="2dp" android:onClick="inserirFilme" android:scaleType="fitXY" android:background="@null" android:src="@drawable/noimage" /> <ImageButton android:id="@+id/ImageButton4" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginRight="4dp" android:layout_marginBottom="4dp" android:layout_marginLeft="2dp" android:layout_marginTop="2dp" android:scaleType="fitXY" android:background="@null" android:src="@drawable/config" /> </LinearLayout> </LinearLayout> What else should I need to specify, or do you need any other code to understand what I'm trying to do? A: Since Android ActionBar setTitle method receives a CharSequence as a parameter you can simply replace the call of your setActionBar() method with the next lines, that using span: Typeface font = Typeface.createFromAsset(this.getAssets(), "tcb.ttf"); String actionBarTitle = "TESTE"; SpannableStringBuilder ssb = new SpannableStringBuilder(actionBarTitle); ssb.setSpan(new CustomTypefaceSpan("", font), 0, actionBarTitle.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE); getActionBar().setTitle(ssb); And don't forget to add this custom typeface span class into your project. public class CustomTypefaceSpan extends TypefaceSpan { private final Typeface newType; public CustomTypefaceSpan(String family, Typeface type) { super(family); newType = type; } @Override public void updateDrawState(TextPaint ds) { applyCustomTypeFace(ds, newType); } @Override public void updateMeasureState(TextPaint paint) { applyCustomTypeFace(paint, newType); } private static void applyCustomTypeFace(Paint paint, Typeface tf) { int oldStyle; Typeface old = paint.getTypeface(); if (old == null) { oldStyle = 0; } else { oldStyle = old.getStyle(); } int fake = oldStyle & ~tf.getStyle(); if ((fake & Typeface.BOLD) != 0) { paint.setFakeBoldText(true); } if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } paint.setTypeface(tf); } }
    { "pile_set_name": "StackExchange" }
    Q: Set required props on component Say that I create a custom component like this: const MyComponent = (props) => ( <div className={props.name} id={props.id}> {props.children} </div> ) And I need to make sure that props contain the variables name and id, because otherwise what I want to do is not going to work (now I know that this code will work anyhow, but hypothetically say that it won't). Is there a way in React to demand that certain props are passed to a component? Maybe this is something that is obvious, but I couldn't find any information about it. A: You can use PropTypes. It was earlier a part of React but now it has its own npm package, https://www.npmjs.com/package/prop-types. This will give you a runtime error if ther props are not provided. Its also useful, because linters can warn you if you miss them. https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md import React from 'react'; import PropTypes from 'prop-types'; const MyComponent = (props) => ( <div className={props.name} id={props.id}> {props.children} /> ); MyComponent.propTypes = { name: PropTypes.string.isRequired, id: PropTypes.string.isRequired, element: PropTypes.arrayOf(PropTypes.element).isRequired };
    { "pile_set_name": "StackExchange" }
    Q: Why do USB connectors only fit one way? Why do USB plugs only fit one way into USB ports? Forgive my ignorance, but there are several types of plugs that are "omnidirectional" and do not have to be oriented a certain way to fit into the corresponding plug (pursuant to shape). In the case of USB, when you're trying to plug one in blind, it can be a bit annoying if you happen to be trying to do it upside-down. I'm guessing this has to do with the pinouts, but then why doesn't the USB standard just negotiate for "pin 1" when something is plugged in, or use a functionally symmetrical pinout layout? A: MOST connectors in the world only allow one mechanical orientation. Ones that are not orientation specific are usually "concentric" such as the familiar 2.5 / 3.5 / 6mm plugs on earphones and similar. Where these have more than 2 conductors the contacts for the conductors at the inside end of the socket ride over the conductors for the tip end as the plugs are inserted. Care must be taken to ensure that no problems are cause by these spurious short term connections. AC power connectors in some systems can be polarity insensitive, but this can lead to safety concerns where there is some difference in attribute between the two contacts other than their ability to provide power. eg in many systems the mains power is ground referenced with one conductor essentially at ground potential. Reversing the twocontacts would still lead to a functioning power connection but may bypass protection and safety systems. BUT the vast majority of plug and socket systems are orientation sensitive. Consider the plugs for keyboards and mice (DB9, PS/2, now USB), any 3 pin power plug, trailer power connectors, telephone and network connectors (RJ10, RJ11, RJ45, ...), XLR/Cannon and similar audio connectors, video connectors for monitors ("IBM"/Apple/Other), SCART AV connectors, DMI, ... People are well used to this. Why should USB be any different? BUT, full size USB has two power connectors and two signal connectors. Rhe signal connections could easily enough be interchanged. But interchanging the two power connections involves routing +ve and -ve signals correctly. This could be done with a diode bridge and two diodes but the voltage drop of about 1.2 Volts represents a loss of about 25% of the Voltage and an immediate 25% power loss. This could be addressed with mechanical automated switching - essentially relays, or with low voltage drop electronic switches (MOSFETs or other) but the cost and complexity is not justified in view of the ease of "just plugging it in correctly". Im Mini and Micro USB systems with potentially more conductors this could have been addressed by redundant arrangements of contacts but that wastes potential resources (size or contacts) and still only results in two possible alignments, 180 degrees apart rotationally. You still could not insert it aligned long side vertical or at an angle. Super Solution: For the ultimate connector consider these two conductor wholly functionally symmetric hemaphroditic connectors. Not only can these be orientated in two orientations rotationally but there is no "male" or "female" connector - both 'plug' and 'socket' are identical. This scheme can be extended to more conductors using a coaxial arrangement. This is a General Radio GR874 connector. If you ever meet something using these you can be fairly sure you are in the presence of greatness :-). Many many more of the same A: Three reasons: Backwards Compatibility The USB standard was begun in 1994, and v. 1.0 became official in 1996. DB-25 (for "D-subminiature", no seriously) was the standard printer port. Everything since that date is still backwards compatible with the original specification. Making the connector omnidirectional would be an incompatibility, which is unacceptable for the standards organization which regulates USB. Cost As mentioned by mikeselectricstuff, this would add additional cost and/or size. Size is a design goal of USB (as evidenced by the trend from USB-B to USB-mini to USB-micro), and cost is always a design goal. Logo Placement No, really. The USB specification demands that all compliant cables put the USB trident: on the top side of the connector. Here's a semi-official reference: The standard USB trident must be on the top of both plug overmolds as described in chapter 6 of the USB 2.0 specification. You'll have to buy the USB spec if you want it straight from the horse's mouth. (Incidentally, I consider that a very appropriate idiom to apply to standards organizations that don't release their standards for free!) If the connector were reversible, the branding might not be visible, or the branding would have to be on both sides, which would make cable manufacturers unhappy. Incidentally, the last point, while it may seem rather picky of the USB standards organization to demand it, is useful. As described in this Lifehacker article, you can determine which way to connect the USB cable by looking for the trident and orienting this "upwards". Unless, of course, it's dark and you can't see the trident...in which case I recommend that you turn the lights on and move to a position where you can see what you're doing. A: There is also a reason that has not been mentioned, and it's related to the concept of poka-yoke (thanks to my friend that studies industrial engineering). The principle is that well-designed connectors shouldn't leave room for ambiguity, especially when potential failures or safety risks are involved. Paraphrasing Murphy's law, If there is any way to do it wrong, he (someone) will. like the old floppy disk, that enters in the hole only in one direction, and also SD cards, good design implies also that the final user has nearly no chance to connect it improperly, and ideally shouldn't have any doubt. This is not the reason for not making it symmetrically connected, but since it has a orientation, it's made in a way that you cannot connect it in the wrong way.
    { "pile_set_name": "StackExchange" }
    Q: Bootstrap data-toggle not working in Safari The below code making use of bootstrap's data-toggle="collapse" to do the functionality of collapse/expand on click of configured element, In this case, clicking parent1 and parent2 Problem: On click of parent element, the collapse is working from my PC using Chrome and firefox browsers, but it is not working from my iPad using safari browser. <div id="parent1" type="button" class="parentclass" data-toggle="collapse" data-target="#childof1"> <strong>Technologies </strong> </div> <div id="childof1" class="collapse"> <!-- elements of child1 --> </div <div id="parent2" type="button" class="parentclass" data-toggle="collapse" data-target="#childof2"> <strong>Vertical </strong> </div> <div id="childof2" class="collapse"> <!-- elements of child2 --> </div References: http://www.w3schools.com/bootstrap/bootstrap_ref_js_collapse.asp A: I tried using a <a> instead of <div> in parent elements where we click to expand/collapse, ie <a id="parent1" type="button" class="parentclass" data-toggle="collapse" data-target="#childof1"> <strong>Technologies </strong> </a> and updated the styling of parentclass to have display: block;, and tested in iPad, now its working from iPad safari browser too! Updates 1: Saw one post where it is suggesting also to use href to make Safari in iPhone understand, but I am not sure if I must use that attribute too, as when I test with href too, everytime I touch on the parent header, the page gives an impression of refreshing [page moves]. So thinking that href is not needed. <a id="parent1" type="button" class="parentclass" data-toggle="collapse" data-target="#childof1" href="#childof1"> Updates 2 Updated using <button> instead of <a> so that expectation of an href could be easily ruled out. The output is still as expected, working in Chrome, Firefox as well as Safari. Please suggest if this is correct approach or have any alternate fixes more about data-toggle and data-*: The data-toggle attributes in Twitter Bootstrap
    { "pile_set_name": "StackExchange" }