{ // 获取包含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 }); }); } })(); \n\n\nServer answer:\n\nHTTP Status 500 - An exception occurred processing JSP page /webi.jsp\n at line 14\ntype Exception report\nmessage An exception occurred processing JSP page /webi.jsp at line 14\ndescription The server encountered an internal error that prevented it\n from fulfilling this request.\nexception org.apache.jasper.JasperException: An exception occurred\n processing JSP page /webi.jsp at line 14\n11: 12: <% 13: 14: AwsSns snsClient = new AwsSns(); 15: 16:\n %> 17:\n\nStacktrace:\n org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)\n org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)\n org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)\n org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)\n javax.servlet.http.HttpServlet.service(HttpServlet.java:728)\n org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)\n\nroot cause \njavax.servlet.ServletException: java.lang.NoClassDefFoundError: com/amazonaws/AmazonWebServiceRequest\n org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:912)\n org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:841)\n org.apache.jsp.webi_jsp._jspService(webi_jsp.java:88)\n org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)\n javax.servlet.http.HttpServlet.service(HttpServlet.java:728)\n org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)\n org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)\n org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)\n javax.servlet.http.HttpServlet.service(HttpServlet.java:728)\n org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)\n\nThe package name is correct and class name is ok.\nWhat's wrong in this code?\nThanks in advance.\n\nA:\n\nI solved my problem.\nI'm using the Amazon Web Services library and it was in incorrect folder. I have move the libs to WEB-INF/lib folder and the problem was solved.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29395,"cells":{"text":{"kind":"string","value":"Q:\n\nhere-document gives 'unexpected end of file' error\n\nI need my script to send an email from terminal. Based on what I've seen here and many other places online, I formatted it like this:\n/var/mail -s \"$SUBJECT\" \"$EMAIL\" << EOF\nHere's a line of my message!\nAnd here's another line!\nLast line of the message here!\nEOF\n\nHowever, when I run this I get this warning:\nmyfile.sh: line x: warning: here-document at line y delimited by end-of-file (wanted 'EOF')\n\nmyfile.sh: line x+1: syntax error: unexpected end of file\n\n...where line x is the last written line of code in the program, and line y is the line with /var/mail in it. I've tried replacing EOF with other things (ENDOFMESSAGE, FINISH, etc.) but to no avail. Nearly everything I've found online has it done this way, and I'm really new at bash so I'm having a hard time figuring it out on my own. Could anyone offer any help?\n\nA:\n\nThe EOF token must be at the beginning of the line, you can't indent it along with the block of code it goes with.\nIf you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code.\nAlso make sure you have no whitespace after the EOF token on the line.\n\nA:\n\nThe line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second \"EOF\" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat:\ncat -A myfile.sh\n\nOnce you see the output from cat -A the solution will be obvious: remove the offending characters.\n\nA:\n\nPlease try to remove the preceeding spaces before EOF:-\n/var/mail -s \"$SUBJECT\" \"$EMAIL\" <<-EOF\n\nUsing instead of for ident AND using <<-EOF works fine. \nThe \"-\" removes the , not , but at least this works.\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29396,"cells":{"text":{"kind":"string","value":"Q:\n\nLaravel/Octobercms eager load relation with one record\n\nI am having a Main table \"devices\"\neach device has a oneToMany relation with \"devicelogs\"\nDevice Model\nclass Device extends Model\n{\n public $hasMany = [\n 'devicelogs' => 'Myhome\\Myplugin\\Models\\Devicelog'\n ];\n}\n\nDeviceLog Model:\nclass Devicelog extends Model\n{\n public $belongsTo = [\n 'device' => 'Myhome\\Myplugin\\Models\\Device'\n ];\n}\n\nI want to eager load devicelogs relations with only one record in response with latest log for that relation.\nI've tried doing:\n$d = Device::with([\n 'devicelogs' => function ($query) {\n $query->latest('created_at')->limit(1)->get();\n }\n])->get();\n\nwith this i only get one device with relation devicelogs having one latest record. I want all device with one device log.\nI tried following:\n$d = Device::with([\n 'devicelogs' => function ($query) {\n $query->first();\n }\n])->get();\n\nwith this i only get one device with relation devicelogs having one first record.\nWhen I do :\n$d = Device::with([\n 'devicelogs' => function ($query) {\n $query->orderBy('created_at','desc');\n }\n])->get();\n\nI do get all devices loaded with relations collection in desc order. But issue is i dont want entire devicelogs, I just want latest/last one for each device.\nSo I tried doing:\n$d = Device::with([\n 'devicelogs' => function ($query) {\n $query->orderBy('created_at','desc')->limit(1);\n }\n])->get();\n\nThis again only gets latest/last devicelogs with single record for only one device. rest all devices get empty devicelogs relation.\nIn record I have atleast 2 or more devicelog for each device.\nWhat i want is to have onely one and last/latest devicelog to return for each device when i run eager loading.\nIm not sure where exactly im doing wrong. \n\nA:\n\nThere is a way around this which you may benefit from. In Laravel you would simply define a new relation and make it a hasOne.\nSince OctoberCMS still has access to use the Laravel style relation methods. You could do something like the following;\nin your Device.php model\npublic function latestDeviceLog()\n{\n return $this->hasOne('Myhome\\Myplugin\\Models\\Devicelog')->latest();\n}\n\nthen you can access with.\nDevice::with('latestDeviceLog')->get();\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29397,"cells":{"text":{"kind":"string","value":"Q:\n\nПереход на следующий таб при нажатии на ссылку\n\nЗдравствуйте!\nИмеется код:\n
\n\n
    \n
  • Первая вкладка
  • \n
  • Вторая вкладка
  • \n
\n\n\n\n
\nТекст 1

';\n }\n else {\n echo '

Текст 2

';\n }\n ?>\n
\n\n
\n\nИ соответственно файл js:\n(function($) {\n$(function() {\n\n$('ul.tabs').each(function(i) {\n var storage = localStorage.getItem('tab'+i);\n if (storage) $(this).find('li').eq(storage).addClass('current').siblings().removeClass('current')\n .parents('div.section').find('div.box').hide().eq(storage).show();\n})\n\n$('ul.tabs').on('click', 'li:not(.current)', function() {\n $(this).addClass('current').siblings().removeClass('current')\n .parents('div.section').find('div.box').eq($(this).index()).fadeIn(150).siblings('div.box').hide();\n var ulIndex = $('ul.tabs').index($(this).parents('ul.tabs'));\n localStorage.removeItem('tab'+ulIndex);\n localStorage.setItem('tab'+ulIndex, $(this).index());\n})\n\n})\n})(jQuery)\n\nНемогу понять, как сделать так, чтобы при нажатии на param автоматически открывало вторую вкладку с Текст 1.\n\nA:\n\nУзнаю знакомый по другому заданию код, js, мне кажется, почти такой же, как там. И в том задании я его переписал в более удобочитаемый вид, поэтому решил сделать решение на основе того переделанного кода, так как использовать текущий код для добавления нужного функционала, это разрыв мозга.\nНе очень понял, зачем вам в ссылке на следующий таб код PHP, что именно вы хотите передавать этим кодом.\nЕсли делать без PHP, то получается такой код на JS, все манипуляции с меню сохраняются в localStorage, что позволяет при обновлении страницы оставаться на том табе, который был активен перед обновлением:\n$(document).ready(function() {\n\n // Загрузка из localStorage сохранённого пункта меню и открытие его\n var storage = localStorage.getItem('item');\n if (storage && storage !== \"#\") {\n $('.nav-tabs a[href=\"' + storage + '\"]').tab('show');\n }\n\n // Функция клика на произвольный пункт меню\n $('ul.nav').on('click', 'li:not(.active, .dropdown, .disabled, .divider)', function() {\n var itemId = $(this).find('a').attr('href');\n localStorage.setItem('item', itemId);\n });\n\n var list = $('ul.nav').find('li');\n\n var length = list.length - 1;\n\n // Функция клика на кнопку Next\n $('.next').click(function() {\n list.each(function(i) {\n if($(this).hasClass('active') && !$(this).hasClass('dropdown')) {\n if (i != length) {\n $(this).removeClass('active'); \n searchValidItem(i);\n return false;\n } else {\n $(this).removeClass('active'); \n searchValidItem(-1);\n return false;\n }\n }\n });\n });\n});\n\n// Функция для определения следующего подходящего пункта в меню\nvar searchValidItem = function(index) {\n var list = $('ul.nav').find('li');\n var nextIndex = index+1;\n var nextItem = list.eq(nextIndex);\n if (!nextItem.hasClass(\"disabled\") && !nextItem.hasClass(\"dropdown\") && !nextItem.hasClass(\"divider\")) {\n nextItem.find(\"a\").tab('show');\n localStorage.setItem('item', nextItem.find('a').attr('href'));\n } else {\n searchValidItem(nextIndex);\n }\n};\n\nПример сделал на основе своего кода из задания по ссылке выше. Сделал также циклическое переключение табов, думаю, не помешает. :)\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29398,"cells":{"text":{"kind":"string","value":"Q:\n\nProving the set $S:=\\cup_{m,n\\in\\mathbb{Z}}T_{m,n},$ in $\\mathbb{R^2},$ is dense\n\nThe set $S:=\\cup_{m,n\\in\\mathbb{Z}}T_{m,n},$ in $\\mathbb{R^2},$ where $T_{m,n}$ is the straight line passing through the origin and the point $(m,n)$ is dense. How to prove it? \nI am thinking in the way that any line passing through origin and point $(m,n)$is simply $y=\\frac{n}{m}x;(m\\neq0)$ and $x=0$ if $m=0$. Therefore our set S looks: $$\\{(x,y)\\in\\mathbb{R^2}|y=\\frac{n}{m}x, (m,n)\\in\\mathbb{Z}\\setminus \\{0\\}\\times \\mathbb{Z}\\}\\cup \\{y-\\textrm{axis}\\}.$$ Now, here onward suppose we take any point $(a,b)\\in\\mathbb{R^2}$ and any $\\epsilon>0$ , then we have to show that $B_{\\epsilon}(a,b)\\cap S \\neq \\phi \\quad i.e. \\quad |(a,b)-(x,\\frac{n}{m}x)|<\\epsilon$ for some $(m,n)\\in\\mathbb{Z}\\setminus \\{0\\}\\times \\mathbb{Z}$ or $|(a,b)-(0,y)|<\\epsilon$ for some $y\\in\\mathbb{R}$. Here I'm convinced that we can always choose such $m,n,x$ that $\\frac{n}{m}x \\rightarrow b $ but how will that ensure me $|a-x|<{\\epsilon}^2.$ I confused here.\n\nA:\n\nIt might be helpful to look at it this way: Each of the lines\n$$\\{re^{i\\arctan (m/n)}: r\\in \\mathbb R, m\\in \\mathbb Z, n\\in \\mathbb N\\}$$\nis contained in $S.$ The set of quotients $\\{m/n\\}$ is dense in $\\mathbb R,$ hence the set $\\{\\arctan (m/n)\\}$ is dense in $(-\\pi/2, \\pi/2).$\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}},{"rowIdx":29399,"cells":{"text":{"kind":"string","value":"Q:\n\nProbability of the union of $3$ events?\n\nI need some clarification for why the probability of the union of three events is equal to the right side in the following:\n$$P(E\\cup F\\cup G)=P(E)+P(F)+P(G)-P(E\\cap F)-P(E\\cap G)-P(F\\cap G)+P(E\\cap F\\cap G)$$\nWhat I don't understand is, why is the last term(intersection of all) added back just once, when it was subtracted three times as it appears from a Venn Diagram?\nHere on page 3, this is explained but not in enough details that I can understand it:\nhttp://www.math.dartmouth.edu/archive/m19w03/public_html/Section6-2.pdf\n\nA:\n\nOne of the axioms of probability is that if $A_1, A_2, \\dots$ are disjoint, then\n$$\\begin{align}\n\\mathbb{P}\\left(\\bigcup_{i=1}^{\\infty}A_i\\right) = \\sum\\limits_{i=1}^{\\infty}\\mathbb{P}\\left(A_i\\right)\\text{.}\\tag{*}\n\\end{align}$$\nIt so happens that this is also true if you have a finite number of disjoint events. If you're interested in more detail, consult a measure-theoretic probability textbook.\nLet's motivate the proof for the probability of the union of three events by using this axiom to prove the probability of the union of two events.\n\nTheorem. For two events $A$ and $B$, $\\mathbb{P}\\left(A \\cup B\\right) = \\mathbb{P}(A) + \\mathbb{P}(B) - \\mathbb{P}(A \\cap B)$.\nProof. Write $$A \\cup B = \\left(A \\cap B\\right) \\cup \\left(A \\cap B^{c}\\right) \\cup \\left(A^{c} \\cap B\\right)\\text{.}$$ Notice also that $A = \\left(A \\cap B^{c}\\right) \\cup\\left(A \\cap B\\right)$ and $B = \\left(B \\cap A^{c}\\right) \\cup \\left(A \\cap B\\right)$. \n\nSince we have written $A$ and $B$ as disjoint unions of sets, applying (*) in the finite case, we have that \n $$\\begin{align}\n\\mathbb{P}\\left(A\\right) &= \\mathbb{P}\\left(A \\cap B^{c}\\right) + \\mathbb{P}\\left(A \\cap B\\right) \\\\\n\\mathbb{P}\\left(B\\right) &= \\mathbb{P}\\left(B \\cap A^{c}\\right) + \\mathbb{P}\\left(A \\cap B\\right) \\\\\n\\end{align}$$\n Similarly, since $A \\cup B = \\left(A \\cap B\\right) \\cup \\left(A \\cap B^{c}\\right) \\cup \\left(A^{c} \\cap B\\right)$ is a disjoint union of sets,\n $$\\begin{align}\n\\mathbb{P}\\left(A \\cup B\\right) &= \\mathbb{P}\\left[ \\left(A \\cap B\\right) \\cup \\left(A \\cap B^{c}\\right) \\cup \\left(A^{c} \\cap B\\right) \\right] \\\\\n&= \\overbrace{\\mathbb{P}\\left(A \\cap B\\right) + \\mathbb{P}\\left(A \\cap B^{c}\\right)}^{\\mathbb{P}(A)} + \\mathbb{P}\\left(A^{c} \\cap B\\right) \\\\\n&= \\mathbb{P}\\left(A\\right) + \\overbrace{\\mathbb{P}\\left(A^{c} \\cap B\\right)}^{\\mathbb{P}(B)-\\mathbb{P}(A \\cap B)} \\\\\n&= \\mathbb{P}\\left(A\\right) + \\mathbb{P}\\left(B\\right) - \\mathbb{P}\\left(A \\cap B\\right)\\text{. } \\square\n\\end{align}$$\n\nNow, armed with the result that we proved in the previous theorem, we can now prove the result for the probability of the union of three events.\n\nTheorem. $\\mathbb{P}\\left(A \\cup B \\cup C\\right) = \\mathbb{P}\\left(A\\right) + \\mathbb{P}\\left(B\\right) + \\mathbb{P}\\left(C\\right) - \\mathbb{P}\\left(A \\cap B\\right) - \\mathbb{P}\\left(A \\cap C\\right) - \\mathbb{P}\\left(B \\cap C\\right) + \\mathbb{P}\\left(A \\cap B \\cap C\\right)$\nProof. Since $A \\cup B \\cup C = \\left(A \\cup B\\right) \\cup C$, by the previous theorem, \n $$\\begin{align}\n\\mathbb{P}\\left(A \\cup B \\cup C\\right) &= \\mathbb{P}((A \\cup B)\\cup C) \\\\\n&= \\overbrace{\\mathbb{P}\\left(A \\cup B\\right) + \\mathbb{P}\\left(C\\right) - \\mathbb{P}\\left[\\left(A \\cup B\\right) \\cap C\\right]}^{\\text{applying the previous theorem to }\\mathbb{P}((A \\cup B)\\cup C)} \\\\\n&= \\overbrace{\\mathbb{P}\\left(A\\right) + \\mathbb{P}\\left(B\\right) - \\mathbb{P}\\left(A \\cap B\\right)}^{\\mathbb{P}\\left(A \\cup B\\right) \\text{ from the previous theorem}} + \\mathbb{P}\\left(C\\right) - \\mathbb{P}\\left[\\overbrace{\\left(A \\cap C\\right) \\cup \\left(B \\cap C\\right)}^{(A \\cup B)\\cap C\\text{ (distributive property of sets)}}\\right] \\\\\n&= \\mathbb{P}\\left(A\\right) + \\mathbb{P}\\left(B\\right) - \\mathbb{P}\\left(A \\cap B\\right) + \\mathbb{P}\\left(C\\right) \\\\\n&\\qquad- \\overbrace{\\Big[\\mathbb{P}\\left(A \\cap C\\right) + \\mathbb{P}\\left(B \\cap C\\right) - \\mathbb{P}\\left[\\left(A \\cap C\\right) \\cap \\left(B \\cap C\\right) \\right]\\Big]}^{\\text{applying the previous theorem to }\\mathbb{P}\\left(\\left(A \\cap C\\right) \\cup \\left(B \\cap C\\right)\\right)}\\text{,}\n\\end{align}$$\n and since $\\left(A \\cap C\\right) \\cap \\left(B \\cap C\\right) = A \\cap B \\cap C$, the result is proven. $\\square$\n\nA:\n\nSince in this formula you add this part 3 times(in the first 3 terms) and subtract it also 3 times(in the next 3 terms), you have to add it again.\n\nA:\n\nAn interesting way to find the answer is by looking at the following Venn diagram:\n\nThe numbers in red indicate how many times a certain section has been included/added by using $P(A) + P(B) + P(C)$. The sections which feature more than once must be subtracted from the total to find the final answer.\n\nThe blank sections are added once. No subtraction required.\nThe dashed (||) sections represent $P(A \\cap B \\cap C^c)$, $P(A \\cap B^c \\cap C)$, and $P(A^c \\cap B \\cap C)$. Each appears twice so each must be subtracted once.\nThe dotted (::) section represents $P(A \\cap B \\cap C)$. Appears thrice so it must subtracted twice.\n\nThis yields:\n$$P(A \\cup B \\cup C ) = P(A) + P(B) + P(C) - P(A \\cap B \\cap C^c) - P(A \\cap B^c \\cap C) - P(A^c \\cap B \\cap C) - 2P(A \\cap B \\cap C).$$\nObserving from the figure that \n$$P(A \\cap B \\cap C^c) = P(A \\cap B) - P(A \\cap B \\cap C),$$\n$$P(A \\cap B^c \\cap C) = P(A \\cap C) - P(A \\cap B \\cap C),$$\n$$P(A^c \\cap B \\cap C) = P(B \\cap C) -P(A \\cap B \\cap C),$$\nThe final answer is given by\n$$P(A \\cup B \\cup C ) = P(A) + P(B) + P(C) - P(A \\cap B) - P(A \\cap C) - P(B \\cap C) + P(A \\cap B \\cap C).$$\n\n"},"meta":{"kind":"string","value":"{\n \"pile_set_name\": \"StackExchange\"\n}"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":293,"numItemsPerPage":100,"numTotalItems":29950,"offset":29300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Nzg0MjIxMSwic3ViIjoiL2RhdGFzZXRzL3N1b2x5ZXIvcGlsZV9zdGFja2V4Y2hhbmdlIiwiZXhwIjoxNzU3ODQ1ODExLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.LzXpmcWmBX34Mw618rKuLAVslQB4CyqtoLsdyMB9__knNrnElMqczIsDPBwmrTnri5IduaBHCYhvOwcG-8NVDw","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
text
stringlengths
175
47.7k
meta
dict
Q: Swift/iOS 8: search bar raising fatal error: unexpectedly found nil while unwrapping an Optional value Following this tutorial, I have just added a "Search Bar and Search Display Controller" to my Table View Controller. As you can see from the following screenshot, the table and the search bar are correctly loaded: by using "Cell" as cell reuse identifier. Anyway, there are two problems: 1) When the search bar is tapped it simply disappears under the navigation bar even if it still accepts text to search 2) as soon as I start typing something in the search bar (even if it is "hidden") then an exception mentioned in title is raised. Here is my code where the line with /***/ is where the exception raises: import UIKit class AllTasksViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate { var allTasks = [Task]() var taskService = TaskService() var organizedTasks = TaskMenuItems() var filteredTasks = [Task]() override func viewWillAppear(animated: Bool) { self.tabBarController?.navigationItem.setHidesBackButton(true, animated: true) self.tabBarController?.navigationItem.rightBarButtonItem = self.editButtonItem() if (LoggedUser.isLogged) { self.navigationItem.setHidesBackButton(false, animated: true) self.taskService.requestAllTasks { (response) in self.allTasks = self.taskService.loadTasks(response) as! [Task] self.organizedTasks.organize(self.allTasks) /*println(self.organizedTasks.items["Aperti"]?.count) println(self.organizedTasks.items["Chiusi"]?.count) println(self.organizedTasks.items["Scaduti"]?.count) println(self.organizedTasks.items["Sospesi"]?.count)*/ dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* Number of sections */ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.organizedTasks.sections.count } /* Number of rows for each section */ override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == self.searchDisplayController!.searchResultsTableView { return self.filteredTasks.count } switch section { case 0: return self.organizedTasks.items["Aperti"]!.count case 1: return self.organizedTasks.items["Chiusi"]!.count case 2: return self.organizedTasks.items["Scaduti"]!.count case 3: return self.organizedTasks.items["Sospesi"]!.count default: return -1 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { l? var selectedStatus:String let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell /***/ var task:Task if tableView == self.searchDisplayController!.searchResultsTableView { task = filteredTasks[indexPath.row] cell.textLabel?.text = task.titolo cell.detailTextLabel?.textColor = Settings.decideColor(task.priorita) cell.detailTextLabel?.text = task.priorita return cell } switch indexPath.section { case 0: /*let cell = tableView.dequeueReusableCellWithIdentifier("OpenTasks", forIndexPath: indexPath) as! UITableViewCell*/ selectedStatus = "Aperti" break case 1: /*let cell = tableView.dequeueReusableCellWithIdentifier("ClosedTasks", forIndexPath: indexPath) as! UITableViewCell*/ selectedStatus = "Chiusi" break case 2: /*let cell = tableView.dequeueReusableCellWithIdentifier("ExpiredTasks", forIndexPath: indexPath) as! UITableViewCell*/ selectedStatus = "Scaduti" break case 3: /*let cell = tableView.dequeueReusableCellWithIdentifier("SuspendedTasks", forIndexPath: indexPath) as! UITableViewCell*/ selectedStatus = "Sospesi" break default: /*let cell = tableView.dequeueReusableCellWithIdentifier("", forIndexPath: indexPath) as! UITableViewCell*/ selectedStatus = "" break } task = self.organizedTasks.items[selectedStatus]![indexPath.row] cell.textLabel?.text = task.titolo cell.detailTextLabel?.textColor = Settings.decideColor(task.priorita) cell.detailTextLabel?.text = task.priorita return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch (section) { case 0: let count = self.organizedTasks.items["Aperti"]!.count return "Aperti (\(count))" case 1: let count = self.organizedTasks.items["Chiusi"]!.count return "Chiusi (\(count))" case 2: let count = self.organizedTasks.items["Scaduti"]!.count return "Scaduti (\(count))" case 3: let count = self.organizedTasks.items["Sospesi"]!.count return "Sospesi (\(count))" default: return "" } } func filterContentForSearchText(searchText: String, scope:String="All") { // Filter the array using the filter method self.filteredTasks = self.allTasks.filter({( task: Task) -> Bool in let categoryMatch = (scope == "All") || (task.priorita == scope) let stringMatch = task.titolo.rangeOfString(searchText) return categoryMatch && (stringMatch != nil) }) } func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool { self.filterContentForSearchText(searchString) return true } func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchScope searchOption: Int) -> Bool { self.filterContentForSearchText(self.searchDisplayController!.searchBar.text) return true } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } } I don't know why these two things happen. It seems that it can't create another cell with "Cell" identifier but this is strange because when the table is loaded (without using the search bar) all is ok so the identifier Cell is registered. Please, can you help? A: Try the following code where you have configured your search display controller or in viewDidLoad: self.searchDisplayController.searchResultsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") Also, use tableView. dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) It's worth mentioning that, UISearchDisplayController is deprecated in iOS 8, use UISearchController instead.
{ "pile_set_name": "StackExchange" }
Q: Is there any way to align ChIP-seq reads to telomeres? I know that telomeres are highly repeated sequences, but is there any way to retain any reads that map to these regions (on HG38)? I recently managed to find some protein binding to centromeres, which are also mainly repeats. Therefore I wondered if there was any way to pick up signal on the telomeres. My team and I are investigating binding of a protein complex to DNA and the experimental team reported that they saw it a bit on telomeres, so we were wondering if there was any way to measure this through bioinformatics. If not then it's no problem, we would just like to know. A: This paper https://www.biorxiv.org/content/10.1101/728519v1.full examines the mapping of some human telomeric sequences, and indicates that there is something like 130kb missing at the telomeres in the HG38 assembly. One option might be to take the HG38 assembly, and add some missing telomere sequences as an additional pseudochromosome to the FASTA file. Then if you used this modified reference to align your reads, you should soon get a feel for the level of telomeric reads in your data set.
{ "pile_set_name": "StackExchange" }
Q: convert html code of radiobutton using rails helpers How can I achieve the below radiobutton in html using rails helpers?? I do have a field guests in my database where the selected value of the radio button gets stored. <div class="segmented-control" style="width: 100%; color: #5FBAAC"> <input type="radio" name="guests" id="1"> <input type="radio" name="guests" id="2"> <input type="radio" name="guests" id="3"> <input type="radio" name="guests" id="4"> <input type="radio" name="guests" id="5"> <input type="radio" name="guests" id="6"> <label for="1" data-value="1">1</label> <label for="2" data-value="2">2</label> <label for="3" data-value="3">3</label> <label for="4" data-value="4">4</label> <label for="5" data-value="5">5</label> <label for="6" data-value="6+">6</label> </div> I tried using <%= f.select :guests, [["1","1"], ["2","2"], ["3","3"], ["4","4"], ["5","5"],["6","6"]], id: "guests", class: "form-control" %> But not working A: There is a helper method called options_for_select which transforms an array of arrays into select input options. <%= f.select :guests, options_for_select([["1","1"],["2","2"],["3","3"],["4","4"], ["5","5"],["6","6"]]), id: "guests", class: "form-control" %> documentation : http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select
{ "pile_set_name": "StackExchange" }
Q: Conditionals in an Active Record query I have a large database of information. They are mostly patients. Some of them have email addresses and some of them don't. I can pull an additional email address by simply running Patient.last.email However I only want to see the patients who do not have email addresses. (I think its about half of the ones that I have) I've tried both these below, but not having the best of luck. Patient.includes(:email).where('email = ?', 'nil') Patient.includes(:email).where('email = ?' 'nil').references(:email) Would anyone know what I'm doing wrong? A: Simple then. Patient.where(email: nil) Should get you your result.
{ "pile_set_name": "StackExchange" }
Q: serving image files from django admin For a site I'm building (first website from scratch btw so new to django) I want to provide to the administrator a means to deploy images from the admin pages, which will be used to drive the business logic from the customer's perspective. However I want the administrator to be able to view these images from the admin page too. So I want one common images folder to be accessible from app views and the admin view. I currently have only one app named retailFilters. Now actually deploying some files to my media/images folder isn't a problem, I add a record (specifying an image to upload) on the admin page and sure enough, the files are waiting exactly where I expected to be. I also realise I have to tell django where to serve them from, and from poking around the internet I have my MEDIA_ROOT, MEDIA_URL and urlpatterns defined as: settings.py ... parent_dir = os.path.abspath(os.path.dirname(__file__) + '/..') MEDIA_ROOT = os.path.join(parent_dir, 'media/') MEDIA_URL = 'media/' (and INSTALLED_APPS includes django.contrib.staticfiles)) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) However the response to clicking on them is that admin bails out with a banner error: "Filter with ID "1/change/media/images/2012-03-29".27.05.jpg" doesn't exist. Perhaps it was deleted?" My python version is 2.7.10 My django version is 1.11 My Directory structure at the moment (root is project directory) is as follows: . ├── db.sqlite3 ├── manage.py ├── media │   └── images │   └── 2012-03-29_22.27.05.jpg ├── NOTES ├── retailFilters │   ├── admin.py │   ├── admin.pyc │   ├── apps.py │   ├── fixtures │   │   └── boltons.json │   ├── __init__.py │   ├── __init__.pyc │   ├── migrations │   │   ├── 0001_initial.py │   │   ├── 0001_initial.pyc │   │   ├── 0002_auto_20170816_1934.py │   │   ├── 0002_auto_20170816_1934.pyc │   │   ├── __init__.py │   │   └── __init__.pyc │   ├── models.py │   ├── models.pyc │   ├── tables │   │   ├── Bolt_On_Group.py │   │   ├── Bolt_On_Group.pyc │   │   ├── Bolt_On.py │   │   ├── Bolt_On.pyc │   │   ├── Filter.py │   │   ├── Filter.pyc │   │   ├── __init__.py │   │   ├── __init__.pyc │   │   ├── Order_Payment.py │   │   ├── Order_Payment.pyc │   │   ├── Order.py │   │   ├── Order.pyc │   │   ├── Payment_Vendor.py │   │   ├── Payment_Vendor.pyc │   │   ├── User.py │   │   └── User.pyc │   ├── tests.py │   └── views.py ├── snapify │   ├── __init__.py │   ├── __init__.pyc │   ├── settings.py │   ├── settings.pyc │   ├── urls.py │   ├── urls.pyc │   ├── wsgi.py │   └── wsgi.pyc └── static └── retailFilters └── media └── images my admin.py has: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.models import Group from tables.Filter import Filter admin.site.unregister(User) admin.site.unregister(Group) <...other un-related admin entries ...> @admin.register(Filter) class FILTER_Admin(admin.ModelAdmin) : fields = ('DESCRIPTION', 'FILENAME', 'CATEGORY', 'PRICE') #list_display = ('show_image',) and my model for Filter is: Filter.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.core.files.storage import FileSystemStorage import os import pdb categories = {'T': 'Personalised Template', 'C': 'Custom Filter'} images = 'images' class Filter(models.Model) : FILTER_REFERENCE = models.IntegerField(primary_key = True) FILENAME = models.ImageField(upload_to = images) DESCRIPTION = models.TextField() CATEGORY = models.CharField(max_length = 1, null = True, choices = [(x, categories[x]) for x in categories]) PRICE = models.DecimalField(default = 0.00, max_digits = 5, decimal_places = 2) def __unicode__(self) : return self.DESCRIPTION #def show_image(self) : # #pdb.set_trace() # return '<a href="{0}"><img src="{0}"></a>'.format(self.FILENAME) #show_image.allow_tags = True and the last output from the runserver commandline: System check identified no issues (0 silenced). August 16, 2017 - 20:03:42 Django version 1.11.1, using settings 'snapify.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [16/Aug/2017 20:03:44] "GET /admin/ HTTP/1.1" 200 4683 [16/Aug/2017 20:03:47] "GET /admin/retailFilters/filter/ HTTP/1.1" 200 4203 [16/Aug/2017 20:03:47] "GET /admin/jsi18n/ HTTP/1.1" 200 3217 [16/Aug/2017 20:03:55] "POST /admin/retailFilters/filter/ HTTP/1.1" 200 3175 [16/Aug/2017 20:03:57] "POST /admin/retailFilters/filter/ HTTP/1.1" 302 0 [16/Aug/2017 20:03:57] "GET /admin/retailFilters/filter/ HTTP/1.1" 200 3189 [16/Aug/2017 20:03:58] "GET /admin/jsi18n/ HTTP/1.1" 200 3217 [16/Aug/2017 20:04:04] "GET /admin/retailFilters/filter/ HTTP/1.1" 200 3067 [16/Aug/2017 20:04:06] "GET /admin/retailFilters/ HTTP/1.1" 200 3167 [16/Aug/2017 20:04:08] "GET /admin/retailFilters/filter/add/ HTTP/1.1" 200 5420 [16/Aug/2017 20:04:08] "GET /admin/jsi18n/ HTTP/1.1" 200 3217 [16/Aug/2017 20:04:20] "POST /admin/retailFilters/filter/add/ HTTP/1.1" 302 0 [16/Aug/2017 20:04:20] "GET /admin/retailFilters/filter/ HTTP/1.1" 200 4391 [16/Aug/2017 20:04:20] "GET /admin/jsi18n/ HTTP/1.1" 200 3217 [16/Aug/2017 20:04:23] "GET /admin/retailFilters/filter/1/change/ HTTP/1.1" 200 5789 [16/Aug/2017 20:04:23] "GET /admin/jsi18n/ HTTP/1.1" 200 3217 [16/Aug/2017 20:04:25] "GET /admin/retailFilters/filter/1/change/media/images/2012-03-29_22.27.05.jpg/ HTTP/1.1" 302 0 [16/Aug/2017 20:04:25] "GET /admin/retailFilters/filter/1/change/media/images/2012-03-29_22.27.05.jpg/change/ HTTP/1.1" 302 0 [16/Aug/2017 20:04:25] "GET /admin/ HTTP/1.1" 200 5427 [16/Aug/2017 20:04:29] "GET /admin/retailFilters/filter/1/change/ HTTP/1.1" 200 5789 Sorry if this has been asked countless times but I've spent a solid 5 hours scouring the internet on this problem and am still unsuccessful. Can anyone point out what I'm missing? A: You just need to change the settings.py : MEDIA_ROOT = os.path.join(parent_dir, 'media/') MEDIA_URL = '/media/' #------------^
{ "pile_set_name": "StackExchange" }
Q: Regarding square-free integers and Euler's function Let $\phi$ be Euler's totient function. Prove that if $\text{gcd}(\phi(n), n) = 1$, then $n$ is a square free integer. A: Hey and welcome to MSE. I guess you might be aware of the multiplicative properties of φ(n). Start by writing $n=p_1^{r_1}...p_m^{r_m}$ It follows that $φ(n)=φ(p_1^{r_1})φ(p_2^{r_2})...φ(p_m^{r_m})$, and we have that $φ(p_i^{r_i})=p_i^{r_i-1}(p_i-1)$. This means that if the $gcd(n, φ(n))=1$, then it means that $r_i=1$ for all i, otherwise $p_i$ would be a common factor.
{ "pile_set_name": "StackExchange" }
Q: How to make long-requests node.js application on heroku I want to make an application on Heroku using node.js to display various statistics. This means that requests can take a long time to complete (more than standard 30 secs). 1. How can I increase the timeout interval so that my app wouldn't crash on request timeout? 2. How can I make long-poll requests to gradually stream data to client as long as it's being processed on server? Thank you. A: you can use http://socket.io for two-way server/client communication. according to https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku, Websockets is currently not supported on Heroku. but socket.io can handle various protocols which some are supported on Heroku.
{ "pile_set_name": "StackExchange" }
Q: Text remains wrapped inside it's parent div - CSS, React The question is pretty straight-forward and I have read lots and lots of posts about the same issue, though in my specific case all these solutions are not working because I am probably handling it wrong or making it over-complicated. Some of the solutions I tried: Why is this CSS nowrap not working? Let text go through a div CSS white-space nowrap not working Don’t wrap span elements Most of these posts come to the conclusion that you should use inline-block in combination with white-space: nowrap. Though after numerous trial and error tries, I actually kinda forgot what I did and did not try.. My specific case I have a React application in which I want to display an hours-bar. This bar has a (sort-of) table layout but just with 1 row. The bar consists out of 15 cells (div's). The problem Each cell should have a specific text above it when a certain condition is met. So for example, I want to show a text value on the starting cell div, and the ending cell div and then each 5th cell again. It should look something like this: I figured I could achieve this by making a 'Time' row inside the body of the time bar, however when I add it as a separate row, then the times / text will never be above the correct cells when the bar has multiple lines on the screen, you would then get something like this: So my next idea was to make 2 separate div's inside the row where 1 div (the top div) functions as the header and the second div functions as the actual bar: <TimeColumnBody> <TimeColumnHeader> {(() => { if (item.showtime === true) { return <Test>{item.name}</Test> } })()} </TimeColumnHeader> <TimeColumn key={item.key} name={item.name} > </TimeColumn> </TimeColumnBody> The above html get's rendered on each separate cell (time-step), so with the above example that would be 15 times (8:00 to 11:30 with steps of 15 minutes). The objects TimeColumnBody, TimeColumnHeader and TimeColumn are created inside the react file and they are simple custom div elements with styling (using styled-components) : const TimeColumnBody = styled.div` float: left; width: 100%; height: 100%; @media only screen and (min-width: 768px) { width: ${props => (props.span ? props.span / 44 * 100 : "2.27")}%; height: 100%; } `; const TimeColumnHeader = styled.div` display: flex; align-items: flex-end; height: 50%; background-color: blue; color: white; white-space: nowrap; `; const TimeColumn = styled.div` height: 50%; background-color: red; `; The creating of the entire table / time-bar happens in the React render part: render() { return ( <TimeContainer> <TimeRow> {this.renderTimeTable()} </TimeRow> </TimeContainer> ); } The renderTimeTable function is the part where the cells are being created (TimeColumnBody, TimeColumnHeader, TimeColumn elements). The text inside the TimeColumnHeader div remains wrapped inside the div even with the white-space: nowrap; property: I tried adding the white-space: nowrap; property to the TimeColumn div with no effect, then I added the display: inline-block property with no effect, then I tried adding it to some parent div's but also without result. The entire styling looks (currently) as follows (style added inline for easier reading): <div class="App" style="text-align: center; height: 100%; overflow: auto;"> <div class="Nav-LeftPane" style="width: 15%; height: 100%; position: fixed; box-sizing: border-box; overflow-y: auto; float: left;">...</div> <div class="content" style="width: 85%; height: 100%; text-align: center; overflow: hidden; float: right;"> <div class="content-timebar" style="padding-left: 1%; padding-right: 1%; padding-top: 3%; height: 100%;"> <!-- The actual Time Bar : --> <div class="TimeContainer" style="width: 100%; height: 10%;"> <div class="TimeRow" style="height: 100%;"> <!-- This div also has some :after logic: .TimeRow::after { content: ""; clear: both; display: table; } --> <!-- the cell part which gets generated 15 times --> <div class="TimeColumnBody" style="width: 2.222%; height: 100%; float: left;"> <div class="TimeColumnHeader" style="display: flex; align-items: flex-end; height: 50%; background-color: blue; color: white; white-space: nowrap;"> 08:00 </div> <div class="TimeColumn" style="height: 50%; background-color: red;"></div> </div> </div> </div> </div> </div> </div> I am now out of ideas and hope someone has a (better) solution to acheive this. UPDATE Added a CodePen: https://codepen.io/anon/pen/rqJgRx A: The problem initially appears to be related to overflow or wrapping, but it is actually a z-index issue - because you are floating .TimeColumnBody left, each subsequent element has a higher z-index than the last and thus overlaps the previous item. I was able to fix this simply by adding a span to the first time with: .TimeColumnHeader span { position: absolute; } See pen: https://codepen.io/anon/pen/NOyZOx
{ "pile_set_name": "StackExchange" }
Q: How to troubleshoot 'File...does not exist!' error (code 403) in gcloud I'm trying to execute some sample code from cloud.googe.com that converts a sample audio file to text, but I'm getting an error message that doesn't make sense. I've gone through all the steps indicated: Create Project Enable Speech to Text API Create a service account download private key as a JSON file I open up Terminal (Version 2.9.4 (421.1.1)) MacOS 10.14.4 I execute the following code in order to set the environment variable: export GOOGLE_APPLICATION_CREDENTIALS="[PATH]" (with path being the location of the JSON file I downloaded) I then create the JSON request file they say to create, which is basically the instructions to get to the sample audio file. Then I execute the following code after initializing gcloud and making sure I'm in the same directory that contains the JSON request file that I created: curl -s -H "Content-Type: application/json" \ -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \ https://speech.googleapis.com/v1/speech:recognize \ -d @sync-request.json So then, instead of getting the response that the tutorial page says I will get, I get an error message that is not on GCP's help page: ERROR: (gcloud.auth.application-default.print-access-token) File /pathofFile/nameofFile.json (pointed by GOOGLE_APPLICATION_CREDENTIALS environment variable) does not exist! { "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" } } This error is obviously not due to me failing to set the environment variable because the error message says "(pointed by GOOGLE_APPLICATION_CREDENTIALS environment variable)," and the error message is displaying the correct path of the correct JSON credential file. The JSON credential file is for sure there; I can see it in finder. What could be going wrong here? Edit: When I tried running gcloud auth application-default login or gcloud auth application-default print-access-token, I got the error message gcloud: command not found So it looks like I didn't have the Cloud SDK fully installed. Now I'm wondering which of the SDK's components I need to install in order to complete this task. Which of the following would I need to install? The latest available version is: 246.0.0 ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ Components │ ├──────────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬───────────┤ │ Status │ Name │ ID │ Size │ ├──────────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼───────────┤ │ Update Available │ BigQuery Command Line Tool │ bq │ < 1 MiB │ │ Update Available │ Cloud SDK Core Libraries │ core │ 10.5 MiB │ │ Not Installed │ App Engine Go Extensions │ app-engine-go │ 56.4 MiB │ │ Not Installed │ Cloud Bigtable Command Line Tool │ cbt │ 6.3 MiB │ │ Not Installed │ Cloud Bigtable Emulator │ bigtable │ 5.6 MiB │ │ Not Installed │ Cloud Datalab Command Line Tool │ datalab │ < 1 MiB │ │ Not Installed │ Cloud Datastore Emulator │ cloud-datastore-emulator │ 18.4 MiB │ │ Not Installed │ Cloud Datastore Emulator (Legacy) │ gcd-emulator │ 38.1 MiB │ │ Not Installed │ Cloud Firestore Emulator │ cloud-firestore-emulator │ 40.5 MiB │ │ Not Installed │ Cloud Pub/Sub Emulator │ pubsub-emulator │ 34.8 MiB │ │ Not Installed │ Cloud SQL Proxy │ cloud_sql_proxy │ 3.7 MiB │ │ Not Installed │ Emulator Reverse Proxy │ emulator-reverse-proxy │ 14.5 MiB │ │ Not Installed │ Google Cloud Build Local Builder │ cloud-build-local │ 5.9 MiB │ │ Not Installed │ Google Container Registry's Docker credential helper │ docker-credential-gcr │ 1.8 MiB │ │ Not Installed │ gcloud Alpha Commands │ alpha │ < 1 MiB │ │ Not Installed │ gcloud Beta Commands │ beta │ < 1 MiB │ │ Not Installed │ gcloud app Java Extensions │ app-engine-java │ 105.6 MiB │ │ Not Installed │ gcloud app PHP Extensions │ app-engine-php │ 21.9 MiB │ │ Not Installed │ gcloud app Python Extensions │ app-engine-python │ 6.0 MiB │ │ Not Installed │ gcloud app Python Extensions (Extra Libraries) │ app-engine-python-extras │ 28.5 MiB │ │ Not Installed │ kubectl │ kubectl │ < 1 MiB │ │ Installed │ Cloud Storage Command Line Tool │ gsutil │ 3.8 MiB │ └──────────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴───────────┘ To install or remove components at your current SDK version [245.0.0], run: $ gcloud components install COMPONENT_ID $ gcloud components remove COMPONENT_ID Edit: Thanks so much for the help everyone. I ended up reinstalling the SDK. Before I had installed the SDK by first downloading the files and then running ./google-cloud-sdk/install.sh But this time I deleted all of the SDK files on my computer and ran curl https://sdk.cloud.google.com | bash Besides that, I made sure to save the "google-cloud-sdk" directory to my root directory, which made it so I could use the default .rc file path. A: The cURL command uses gcloud tool for authentication: gcloud auth application-default print-access-token. Since you're using a local machine to run or submit the API requests, you would need to install and initialize the Cloud SDK (MAC) in your machine to utilize the gcloud tool.
{ "pile_set_name": "StackExchange" }
Q: How to implement a frontend view of a backend countup timer in java? Trying to implement a timer for my game that I'm making. I have a backend class Game that has an int timeElapsed() method. This gives me elapsed time since the start in milliseconds. I also have a front end view that needs an update of this elapsed time. What is the best way to synchronize these two values? I could set up a daemon to call game.timeElapsed() every second, but it seems that there must be a better way to do this. Another idea I had was to put some timekeeping in the frontend, but this seems like a violation of separation of responsibilities. The Stopwatch class that I'm using to keep track of time does not support callbacks. Thoughts? A: Use the java.util.Timer class, to periodically update the view. Call game.timeElapsed() in each iteration, don't keep two Stopwatch-objects around.
{ "pile_set_name": "StackExchange" }
Q: OAuth2 client that works on App Engine Can anyone advice me on a good library or else how to go about having a Python appengine based application using OAuth to authenticate to another server? I have an application on appengine that expects user input. I would like the user to be able to upload an image, which I would put in imgur.com and would be able to show to the user back on my page. To be able to do that, I need to be able to authenticate to api.imgur.com hence the question. A: Have a look to python-oauth2 project. A Client example: import oauth2 as oauth # Create your consumer with the proper key/secret. consumer = oauth.Consumer(key="your-twitter-consumer-key", secret="your-twitter-consumer-secret") # Request token URL for Twitter. request_token_url = "http://twitter.com/oauth/request_token" # Create our client. client = oauth.Client(consumer) # The OAuth Client request works just like httplib2 for the most part. resp, content = client.request(request_token_url, "GET") print resp print content
{ "pile_set_name": "StackExchange" }
Q: Regex optional matching Pseudo/dummy-code that will be matched against: RECOVERY: 'XXXXXXXXX' is UP PROBLEM: 'ABABABAB' on 'XXXXXXXXX' is WARNING PROBLEM: 'XXXXXXXXX' is DOWN RECOVERY: 'ABABABAB' on 'XXXXXXXXX' is OK PROBLEM: 'ABABABAB' on 'XXXXXXXXX' is DOWN Goal Capture XXXXXXXXX(without the single-quotes) but do NOT capture ABABABAB Best attempt so far: (M: \'|Y: \')(.*)(?:\' )(?:is) Is it even possible to achive the goal above, and if yes, then how? A: You can use a lookahead only to check if the string matched is before is: '([^']*)'\\s*(?=\\bis\\b) See regex demo Breakdown: ' - single apostrophe ([^']*) - capture group matching 0 or more characters other than ' '\\s* - a single apostrophe and 0 or more whitespace symbols (?=\\bis\\b) - a lookahead making sure there is a whole word is after the current position (after the ' with optional whitespaces) Java demo: Pattern ptrn = Pattern.compile("'([^']*)'\\s*(?=\\bis\\b)"); Matcher matcher = ptrn.matcher("RECOVERY: 'XXXXXXXXX' is UP"); if (matcher.find()) { System.out.println(matcher.group(1)); } UPDATE I used a lookahead only because you used a non-capturing group in your original regex : (?:is). A non-capturing group that has no quantifier set or any alternation inside seems reduntant and can be omitted. However, people often get misled by the name non-capturing thinking they can exclude the substring matched by this group from the overall match. To check for presence or absence of some text without matching, a lookaround should be used. Thus, I used a lookahead. Indeed, in the current scenario, there is no need in a lookahead since it makes sense in case you need to match subsequent substrings that start wiyh the same sequence of characters. So, a better alternative would be '([^']*)'\s*is\b Java: Pattern ptrn = Pattern.compile("'([^']*)'\\s*is\\b");
{ "pile_set_name": "StackExchange" }
Q: Show integral function is continuous and uniformly continuous Let $ -\infty \le a < b \le \infty $. Function $ f:(a,b) \rightarrow R $ can be integrated in the sense of Riemann on every dense $ [c,d] \subseteq (a,b) $. The integral $ \int_{a}^{b} f(x) dx $ is convergent. Show that $$ F(x) = \int_{a}^{x} f(x) dx $$ is continuous. Is it uniformly continuous? We have $F(a) = 0$. From the fundamental theory of calculus $F(x)$ is continuous on $[a,x], x<b$. We have a left-side sonvergence in $b$ from definition, so $F$ is continuous on $[a,b]$. Is it enough to prove continuity? How do I show uniform continuity? This is a homework assignment. A: Here are some suggestions: Since $f$ is Riemann integrable on any interval $[c,d] \subset (a,b)$ it is bounded locally. To prove uniform continuity of $F$, the easy case is where $f$ is bounded globally on $(a,b)$ with $|f(x)| \leqslant M$ for all $a < x < b$. The other case is where $f$ is unbounded at one or both of the endpoints. For example, suppose $f$ is unbounded at $x = b$ and bounded and Riemann integrable on $[a,c)$ for all $c < b$. By hypothesis, the improper integral over $(a,b)$ is convergent. By the Cauchy criterion, for any $\epsilon > 0$ there exists $C < b$ such that if $C \leqslant x < y < b$ we have $$|F(y) - F(x)| = \left|\int_x^y f(t) \, dt \right| < \frac{\epsilon}{2}.$$ On the interval $[a,C]$, $f$ is bounded and there exists $M_C > 0$ such that $|f(x)| \leqslant M_C $ for all $x \in [a,C]$. Now see if you can complete the proof by examining the three cases (1) $x < y < C$, (2) $x < C \leqslant y$, and (3) $C < x < y$.
{ "pile_set_name": "StackExchange" }
Q: how to highlight buttons in extjs when clicking on it items: [{ xtype: 'button', text: 'Today', ui:'default-toolbar', margin: '10 10 10 10' },{ xtype: 'button', text: 'Yesterday', ui:'default-toolbar', margin: '0 10 10 10' } },{ xtype: 'button', text:'Last 7 days', ui:'default-toolbar', margin: '0 10 10 10' }, { xtype: 'button', text: 'Last Month', ui:'default-toolbar', margin: '0 10 10 10' }] A: Ext.Button have a property enableToggle which if set to true will apply pressedCls to the button when clicked and remove the pressedCls when pressed again. Sample Code: Ext.application({ name: 'Fiddle', launch: function() { Ext.create('Ext.Container', { renderTo: Ext.getBody(), items: [{ xtype: 'button', text: 'My Button', enableToggle: true }] }); } }); <link rel="stylesheet" href="https://cdn.sencha.com/ext/gpl/4.1.1/resources/css/ext-all.css"> <script type="text/javascript" src="https://cdn.sencha.com/ext/gpl/4.1.1/ext-all-debug.js"></script> For Multiple Button: When we need to toggle pressedCls between mutiple button.We need to use toggleGroup property of button. It will toggle the pressedCls among multiple where same toggleGroup is given. Sample Code: Ext.application({ name: 'Fiddle', launch: function() { Ext.create('Ext.Container', { renderTo: Ext.getBody(), layout:'vbox', items: [{ xtype: 'button', text: 'Today', enableToggle: true, toggleGroup:'myButtonGroup' },{ xtype: 'button', text: 'Yesterday', enableToggle: true, toggleGroup:'myButtonGroup' }, { xtype: 'button', text: 'Last 7 days', enableToggle: true, toggleGroup:'myButtonGroup' }] }); } }); <link rel="stylesheet" href="https://cdn.sencha.com/ext/gpl/4.1.1/resources/css/ext-all.css"> <script type="text/javascript" src="https://cdn.sencha.com/ext/gpl/4.1.1/ext-all-debug.js"></script>
{ "pile_set_name": "StackExchange" }
Q: How to structure this SQL query. Combining multiple tables? NOTE: This is not a duplicate of my other question . I have changed the table structure and need new help with a new query. So basically I'm getting notifications of new content on my website. I have 4 tables - articles media updates comments Each table has a set of its own columns (I can include these if anyone wants). In my new notification system I am designing, I determine the newest content, by its timestamp. The timestamp value is an integer formatted to Unix Time. I have just changed my table structure, before, my tables all had columns that were similar. An example, both articles and media had the column id. The SQL code I was using was this - SELECT a.*,m.*,u.*,c.* from articles AS a LEFT JOIN media AS m ON (m.mediaTimestamp = a.timestamp) LEFT JOIN updates AS u ON (u.updateTimestamp = a.timestamp) LEFT JOIN comments AS c ON (c.commentTimestamp = a.timestamp) ORDER BY a.timestamp desc LIMIT 30 However when doing this, the code would return multiple iterations of a column in the same row (it would return an id column for articles and media!). Obviously when I tried to get the data via code, it would give me data for different tables (instead of giving me the article id, it would give me the media id). My solution to this was to 'pretty' up my code and name all columns in a table (such as articles) with their table prefix (so id would become articleID). However now the above SQL is producing errors. Could someone 'convert'/restructure this SQL for me. A: try this: SELECT a.*,m.*,u.*,c.* from articles AS a LEFT JOIN media AS m ON (m.mediaTimestamp = a.articleTimestamp) LEFT JOIN updates AS u ON (u.updateTimestamp = m.mediaTimestamp) LEFT JOIN comments AS c ON (c.commentTimestamp = u.updateTimestamp) ORDER BY a.articleTimestamp desc LIMIT 30
{ "pile_set_name": "StackExchange" }
Q: How to test ServerEndPoint, ClientEndPoint? I have implemented ServerEndPoint and ClientEndPoint, how can i test it? For example, i have Connection wrappers over Session and i want to test it behavior which depends on session data, also i want to test messaging between client and server. Note that i don't have any war or any of application configuration such as web.xml, web-sockets infrastructure going to be used in another place, all what i have is mapped ServerEndPoint and ClientEndPoint implementations. A: The Tyrus reference implementation has a test tools package which contains a test server that can be used with a client: http://mvnrepository.com/artifact/org.glassfish.tyrus.tests/tyrus-test-tools/1.10 The samples on Github are a good usage guide: https://github.com/tyrus-project/tyrus/blob/master/archetypes/echo/src/main/resources/archetype-resources/src/test/java/EchoTest.java
{ "pile_set_name": "StackExchange" }
Q: strange output of STL map C programmer trying to call a C++ map (to use the functionality of an associated array or hashing). The string is just a beginning, will go on to hash binary string. Got stuck on the first step. Wonder why the output of this program will only return 0. #include <string.h> #include <iostream> #include <map> #include <utility> #include <stdio.h> using namespace std; extern "C" { int get(map<string, int> e, char* s){ return e[s]; } int set(map<string, int> e, char* s, int value) { e[s] = value; } } int main() { map<string, int> Employees; printf("size is %d\n", sizeof(Employees)); set(Employees, "jin", 100); set(Employees, "joe", 101); set(Employees, "john", 102); set(Employees, "jerry", 103); set(Employees, "jobs", 1004); printf("value %d\n", get(Employees, "joe")); } Thanks. A: Two bugs found (yet): printf("size is %d\n", sizeof(Employees)); has to be printf("size is %d\n", Employees.size()); sizeof gives you the size of the object, not the count of elements within. int set(map<string, int> e, char* s, int value) has to be int set(map<string, int> &e, char* s, int value) otherwise you give a copy to the function, not the original (as in C).The copy will be discard after leaving the scope of the function. The original is not altered.
{ "pile_set_name": "StackExchange" }
Q: Beginner's query: unable to reverse char array in C First up: sincere apologies for bringing up such a basic problem requesting attention. I intend to reverse a char array with a user input string by using getchar() & display its reverse using putchar(). [I understand that there may be easier or more elegant ways using printf() & scanf(), but I am keen to find the flaw in my logic below with getchar() & putchar():] #include <stdio.h> #include <stdlib.h> #define EOL '\n'; /* Reversing a character array */ int main() { int arr_char[10]; int i=0; /* reading char elements into the array */ printf("Please input the array\n"); arr_char[0]= getchar(); while(arr_char[i]!= EOL && i<=9) { i=i+1; arr_char[i]=getchar(); printf("\ni=%d\n",i); } /* display reverse */ while(i>=0) { putchar(arr_char[i]); i--; } return 0; } 1) I get an error message: reversing char array\main.c|15|error: expected ')' before ';' token| ||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===| FYI: Line 15 is the while(arr_char[i]!= EOL && i<=9) 2) I am also trying to print the counter "i" as to see whether it is being incremented on pressing "Enter" after a character is input and it seems that it does. 3) I have defined the arr_char array as int arr_char[10]; with the intention that if someone inputs "-1" as EOF/EOL, then a char array will perhaps not be of much help. Am I right? Any explanations in helping get my bearings back on'll be greatly appreciated. Thanks! A: Remove the ; from the end of the #define. Macros are done using text substitution, so with the semicolon, while(arr_char[i]!= EOL && i<=9) will become: while(arr_char[i]!= '\n'; && i<=9) which is wrong. You also have an additional problem in that your code can write to arr_char[10], which is past the end of the array. You need to increase the array size, or change i<=9 to i<9.
{ "pile_set_name": "StackExchange" }
Q: LCD module with backlight I am using COG-C144MVGI. I am trying to turn it on with my Raspberry Pi. I am not sure if I am following the "power on sequence" correctly. Does this kind of LCD modules work without backlight? I am wondering if I am supposed to get some kind of reaction on the screen even without backlight. Thank you. Here is the datasheet : https://www.avrfreaks.net/sites/default/files/COG-C144MVGI-08%20Full%20Spec.pdf A: Probably you will see information on the display when the backlight is off, but not when it is dark (or not so light). (Also, there exist LCD displays without backlight). However, a reason to switch backlight off, is to preserve current (especially useful in a battery operated system). Page 6/7 show information about LED A/LED K how to control the backlight.
{ "pile_set_name": "StackExchange" }
Q: Can I use Amazon SQS as a delay queue before sending to SNS? My system run on an Amazon autoscaling group and one feature allows user to user messaging and I have the following use case to resolve. A new message is sent in my application between users. A message to notify the the user by e-mail is dropped into a queue with a 60 second delay. This delay allows time for a realtime chat client (faye/angularjs) to see the message and mark it as viewed. After the delay the message is picked up, the "read" status is checked and if it has not been read by the client an e-mail is dispatched. Originally I was going to use a cronjob on each application server poll the message queue however it occurs to me it would be more efficient to use SNS to call some kind of e-mail sending endpoint (perhaps in Lambda). I can't see any way to have SNS poll SQS however, can anybody suggest how this could be done? Essentially I want SNS with a delay so that I don't spam somebody in a "live" chat with e-mail alerts. Thanks A: Unfortunately this is not yet available out of the box. The missing part is the generation of Amazon SNS notifications on message arrival/visibility by an Amazon SQS queue, be it via push (similar to Amazon S3 notifications, or via poll similar to Amazon Kinesis subscriptions (see The Pull/Push Event Models for more on the difference), which would both allow to directly connect an AWS Lambda function to the resp. SQS delay queue events, see e.g.: Lambda with SQS That being said, you can work around this limitations in a few ways, for example: trigger your Lambda function on schedule (e.g. once per minute), and poll your SQS delay queue from there scheduled Lambda functions are an eagerly awaited missing Lambda feature in turn, but it is more easily worked around, be it either by a cron job of yours, or Eric Hammond's Unreliable Town Clock (UTC) for example The AWS Lambda team has delivered many/most similar feature requests over recent month' btw., so I would expect them to offer both SQS event handling and scheduled Lambda functions over the course of the year still.
{ "pile_set_name": "StackExchange" }
Q: html hyperlink download file issue I use absolute path <a href='N:\myName\test.xlsx'>download</a>to download file from file folder. However, when I click it, the file is open directly instead of downloading it. If I use relative path <a href='js/template/test.xlsx'>download</a>, the file is downloaded before opening it. My question is that how I can download the file instead of directly opening it using absolute path like <a href='N:\myName\test.xlsx'>download</a> Thanks, Peter A: That absolute path is stored on your computer, which means it's a link to that file. You can't download something that's stored on your computer - it has to be stored on the web to download.
{ "pile_set_name": "StackExchange" }
Q: Error(6,1): PLS-00103: Encountered the symbol "CREATE" Hi friends i am gettting this error my query is i tried by applying / after declaration of package Create or Replace Package PACKAGE1 as TYPE Page is REF CURSOR; Procedure GetPage(PageSize IN int, PageIndex IN INT, PageData OUT Page); End PACKAGE1; CREATE OR REPLACE package body PACKAGE1 as Procedure GetPage(PageSize IN int, PageIndex IN INT, PageData OUT Page) IS FirstIndex int; LastIndex int; BEGIN LastIndex := PageSize * (PageIndex +1); FirstIndex := LastIndex - PageSize +1; Open PageData for Select * from ( select a.*, rownum as rnum from (select * from MyTable) a where rownum <= LastIndex ) where rnum >= FirstIndex; END GetPage; END PACKAGE1; A: As the commentators pointed, '/' is need for both CREATE statements. Create or Replace Package PACKAGE1 as TYPE Page is REF CURSOR; Procedure GetPage(PageSize IN int, PageIndex IN INT, PageData OUT Page); End PACKAGE1; / CREATE OR REPLACE package body PACKAGE1 as Procedure GetPage(PageSize IN int, PageIndex IN INT, PageData OUT Page) IS FirstIndex int; LastIndex int; BEGIN LastIndex := PageSize * (PageIndex +1); FirstIndex := LastIndex - PageSize +1; Open PageData for Select * from ( select a.*, rownum as rnum from (select * from MyTable) a where rownum <= LastIndex ) where rnum >= FirstIndex; END GetPage; END PACKAGE1; /
{ "pile_set_name": "StackExchange" }
Q: WCF web service with CROSS Domian Ajax not working I am getting error when calling WCF Ajax Request using jsonp below is my web.config <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <services> <service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour"> <endpoint address="" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="web"></endpoint> <endpoint address="basic" binding="basicHttpBinding" name="HttpEndPoint" contract="RestService.IRestServiceImpl" ></endpoint> <endpoint address="Service1.svc" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehaviour"> <!-- To avoid disclosing metadata information, set the value below to false before deployment --> <serviceMetadata httpGetEnabled="true" /> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="web"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <bindings> <webHttpBinding> <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" /> </webHttpBinding> </bindings> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <!-- To browse web app root directory during debugging, set the value below to true. Set to false before deployment to avoid disclosing web app folder information. --> <directoryBrowse enabled="true"/> </system.webServer> </configuration> And my My Interface using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace RestService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IRestServiceImpl" in both code and config file together. [ServiceContract] public interface IRestServiceImpl { [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "getallemp")] [return: MessageParameter(Name = "success")] string GetAllEmployee(); } } and below is My Service Class using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using WebService.DataLayer; namespace RestService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "RestServiceImpl" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select RestServiceImpl.svc or RestServiceImpl.svc.cs at the Solution Explorer and start debugging. public class RestServiceImpl : IRestServiceImpl { public string GetAllEmployee() { cls_datalayer obj = new cls_datalayer(); DataTable dt = obj.getDataTableFromQuery("select usercode from users where empstatus='A'"); return ConvertDataTabletoString(dt); } public string ConvertDataTabletoString(DataTable dt) { System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); serializer.MaxJsonLength = 50000000; List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); Dictionary<string, object> row; foreach (DataRow dr in dt.Rows) { row = new Dictionary<string, object>(); foreach (DataColumn col in dt.Columns) { row.Add(col.ColumnName, dr[col]); } rows.Add(row); } return serializer.Serialize(rows); } } } When i call this from browser its give From Browser but when i try this from Ajax request using cross domain then i am getting error $.ajax({ type: "GET", url: 'http://localhost:59672/RestServiceImpl.svc/getallemp', contentType: "application/json", dataType: "jsonp", cache: false, jsonpCallback: 'callback', success: function (data) { alert(); }, error: function (xhr) { //console.log(xhr); var err = eval("(" + xhr.responseText + ")"); } }); then i get error please check attachments Attachment 01 Attachment 02 A: is worked better for me than the Web.config version: Create a Global.asax Add this code to the Global.asax.cs protected void Application_BeginRequest(object sender, EventArgs e) { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*"); if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); HttpContext.Current.Response.End(); } }
{ "pile_set_name": "StackExchange" }
Q: binding & pmap interaction change? There are several somewhat old blog posts out there advising caution when mixing dynamic variables, binding, and pmap, e.g. here, where we get the following code snippet: user=> (def *foo* 5) #'user/*foo* user=> (defn adder [param] (+ *foo* param)) #'user/adder user=> (binding [*foo* 10] (doseq [v (pmap adder (repeat 3 5))] (println v))) 10 10 10 nil But that's not what happens when I run that code (changing the first line to (def ^:dynamic *foo* 5)). I get three 15s as output (using Clojure 1.4), just as you would naïvely expect—that is, with the change in the binding form seen by the function passed to pmap. Have the way thread-local bindings and pmap interact changed? I can't find this documented anywhere. A: starting in 1.3 the set of local bindings are sent to pmap along with the function. So as long as you mark the var ^:dynamic this is no longer a problem. This feature it called Binding Conveyance and is included in the 1.3 changelog: from: https://github.com/clojure/clojure/blob/1.3.x/changes.txt Clojure APIs that pass work off to other threads (e.g. send, send-off, pmap, future) now convey the dynamic bindings of the calling thread: (def ^:dynamic *num* 1) (binding [*num* 2] (future (println *num*))) ;; prints "2", not "1"
{ "pile_set_name": "StackExchange" }
Q: Unable to launch Selenium with Python in Eclipse I'm getting Unresolved import: webdriver Found at: selenium.webdriver.__init__ 2.44.0 issue when i'm trying to launch selenium with python in Eclipse My sample code from selenium import webdriver from selenium.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") driver.close() Using Python 2.7 , Pydev 2.2 Installed Selenium through PIP pip install selenium Downloading/unpacking selenium Running setup.py (path:c:\users\ajay_t~1\appdata\local\temp\pip_build_ajay_talpur\selenium\setup.py) egg_info for package selenium Installing collected packages: selenium Running setup.py install for selenium Successfully installed selenium When updating Packages pip install -U selenium Requirement already up-to-date: selenium in c:\python27\lib\site-packages What else i missed please tell me so that i can start executions. A: Please update Environment variable by adding Python Directory path & site packages path.And retry : C:\Python27\Scripts;C:\Python27\Lib\site-packages;
{ "pile_set_name": "StackExchange" }
Q: Error in event creation using MySQL Am using the below code to create an EVENT in MYSQL. In this time i want to drop and create a table using a query. Drop Event if exists EVT_UP_TIMESHEET; CREATE EVENT EVT_UP_TIMESHEET ON SCHEDULE EVERY '1' Day STARTS '2012-08-01 12:00:00' DO Drop table if exists tbl_temp; create table tbl_temp as ( SELECT e.userid AS Employee_ID, e.memo AS Employee_Name, e.Department AS Department, ..... It returns the following error: ERROR : Table tbl_temp already exists. Please help me to do this. A: As a workaround - try to use TRUNCATE TABLE and INSERT...SELECT statements instead of DROP/CREATE TABLE.
{ "pile_set_name": "StackExchange" }
Q: why we can use code $this-> in system/library/customer.php Look at the codes below: public function __construct($registry) { $this->config = $registry->get('config'); $this->db = $registry->get('db'); $this->request = $registry->get('request'); $this->session = $registry->get('session'); My question is the properties $this->config, $this->db, $this->request and $this->session are not defined at this class. And the Customer class neither inherits from another class not implements __get(),__set() method... Can someone can explain to me why we can use $this-> here? A: That is just a variable which will be Declared and assigned value while Object is created, try class Test{ function __construct(){ $this->name = 'Ramesh'; } } print_r(new Test());
{ "pile_set_name": "StackExchange" }
Q: FIPS Certification for Android & iPhone Does anyone know the name of the cryptography libraries come with iPhone & Android SDKs ? I don't mean the name of the classes, functions etc. but the name of the provider and/or the library itself. Are they FIPS certified? Thanks A: I found out that for Android it's Bouncy Castle and it's not FIPS certified. As for the Apple it's their own implementation and in the process of being FIPS certified according to the NIST's website on the Modules In Process list.
{ "pile_set_name": "StackExchange" }
Q: Changing a property modifier when merging an interface The Window interface has a few properties that are readonly: interface Window extends ... { // ... readonly innerHeight: number; readonly innerWidth: number; // ... } I get that those cannot really be changed, but in my unit tests, I'm changing the values of the object to simulate the changes. And it's an object of that type. Is there a way I can augment that type in a custom d.ts file and change these properties modifiers? I tried to just create a .d.ts file with this: interface Window { innerHeight: number; innerWidth: number; } But the compiler is complaining with: All declarations of 'innerWidth' must have identical modifiers. A: (I'm pretty sure that) no, you can't change the modifiers or types of existing types. But as you're only using it for testing then it shouldn't be problematic to cast it to any: (window as any).innerWidth = 500; (window as any).innerHeight = 300; Edit There's a trick to make a type mutable: type Mutable<T extends { [x: string]: any }, K extends string> = { [P in K]: T[P]; } type MyWindow = Mutable<Window, keyof Window>; (window as MyWindow).innerWidth = 500; (window as MyWindow).innerHeight = 300; (code in playground) It was suggested in this issue: Mapped Types syntax to remove modifiers, but if it's for testing then this is probably an overkill and casting to any would do the trick (in my opinion).
{ "pile_set_name": "StackExchange" }
Q: Calculate average for specific date range in R I have two data frames: Date <- seq(as.Date("2013/1/1"), by = "day", length.out = 17) x <-data.frame(Date) x$discharge <- c("1000","1100","1200","1300","1400","1200","1300","1300","1200","1100","1200","1200","1100","1400","1200","1100","1400") x$discharge <- as.numeric(x$discharge) And: Date2 <- c("2013-01-01","2013-01-08","2013-01-12","2013-01-17") y <- data.frame(Date2) y$concentration <- c("1.5","2.5","1.5","3.5") y$Date2 <- as.Date(y$Date2) y$concentration <- as.numeric(y$concentration) What I am desperately trying to do is to the following: In data frame y the first measurement is for the period 2013-01-01 to 2013-01-07 Calculate the average discharge for this period in data frame x Return the average discharge to data frame y in a new column next to the first measurement and continue with the next measurement I was having a look into function such as dplyr or apply but was not able to figure it out. A: library(dplyr) x %>% mutate(period = cut(as.Date(Date), c(as.Date("1900-01-01"), as.Date(y$Date2[-1]), as.Date("2100-01-01")), c(1:length(y$Date2)))) %>% group_by(period) %>% mutate(meandischarge = mean(discharge, na.rm = T)) %>% right_join(y, by = c("Date" = "Date2")) Date discharge period meandischarge concentration <date> <dbl> <fctr> <dbl> <dbl> 1 2013-01-01 1000 1 1214.286 1.5 2 2013-01-08 1300 2 1200.000 2.5 3 2013-01-12 1200 3 1200.000 1.5 4 2013-01-17 1400 4 1400.000 3.5 If you only want the original y variables, you could do this: x %>% mutate(period = cut(as.Date(Date), c(as.Date("1900-01-01"), as.Date(y$Date2[-1]), as.Date("2100-01-01")), c(1:length(y$Date2)))) %>% group_by(period) %>% mutate(meandischarge = mean(discharge, na.rm = T)) %>% ungroup() %>% right_join(y, by = c("Date" = "Date2")) %>% select(Date2 = Date, concentration, meandischarge) Date2 concentration meandischarge <date> <dbl> <dbl> 1 2013-01-01 1.5 1214.286 2 2013-01-08 2.5 1200.000 3 2013-01-12 1.5 1200.000 4 2013-01-17 3.5 1400.000
{ "pile_set_name": "StackExchange" }
Q: Strophe MAM how to display the messages? I have managed to use Strophe MAM to get the archived messages into the RAWInput, and display the last message(but only the last one). How do i display all the messages from the RAWInput?? But not just the last one? And how do i extract who the message is from? I have limited the messages to the last 5. connection.mam.query("[email protected]", { "with": "[email protected]","before": '',"max":"5", onMessage: function(message) { console.log( $(message).text()); }, onComplete: function(response) { console.log("Got all the messages"); } }); A: You can get all the messages using the `strophe.mam.js plugin Here is my working code: // Retrives the messages between two particular users. var archive = []; var q = { onMessage: function(message) { try { var id = message.querySelector('result').getAttribute('id'); var fwd = message.querySelector('forwarded'); var d = fwd.querySelector('delay').getAttribute('stamp'); var msg = fwd.querySelector('message'); var msg_data = { id:id, with: Strophe.getBareJidFromJid(msg.getAttribute('to')), timestamp: (new Date(d)), timestamp_orig: d, from: Strophe.getBareJidFromJid(msg.getAttribute('from')), to: Strophe.getBareJidFromJid(msg.getAttribute('to')), type: msg.getAttribute('type'), body: msg.getAttribute('body'), message: Strophe.getText(msg.getElementsByTagName('body')[0]) }; archive.val(archive.val() + msg_data.from + ":" + msg_data.message + "\n" + msg_data.to + ":" + msg_data.message + "\n"); archive.scrollTop(archive[0].scrollHeight - archive.height()); console.log('xmpp.history.message',msg_data.message); } catch(err){ if(typeof(err) == 'TypeError'){ try { console.log(err.stack) } catch(err2){ console.log(err,err2); } } } return true; }, onComplete: function(response) { console.log('xmpp.history.end',{query:q, response:response}); } }; $(document).ready(function)(){ archive = $("#archive-messages"); archive.val(""); $("#to-jid").change(function() { $("#archive-messages").val(""); var to = {"with": $(this).val()}; $.extend(q, to, before, max); // It takes around 800ms to auto login. So after this timeout we have to retrieve the messages of particular User. setTimeout(function(){ connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q); }, 1000); }); });
{ "pile_set_name": "StackExchange" }
Q: Parâmetro na URL da página Caros, preciso criar uma aplicação pyramid para uso da API. 1 - “/quotes/< quote_number>” - Apresentar página contendo o quote retornado pela API correspondente ao < quote_number >. Já sei como criar uma página estatíca em Pyramid, mas não sei como criar uma página que recebe o parâmetro na url. A: Dado o conteúdo desta página, basta você definir o parâmetro na URL entre chaves, tal como {parametro} e utilizá-lo através de request.matchdict. Veja um exemplo: @view_config(route_name='quotes_number') def quotes_number(request): return Response(request.matchdict['quote_number']) config.add_route('quotes_number', 'quotes/{quote_number}')
{ "pile_set_name": "StackExchange" }
Q: What's the math for real world back-propagation? Considering a simple ANN: $$x \rightarrow f=(U_{m\times n}x^T)^T \rightarrow g = g(f) \rightarrow h = (V_{p \times m}g^T)^T \rightarrow L = L(h,y) $$ where $x\in\mathbb{R}^n$, $U$ and $V$ are matrices, $g$ is the point-wise sigmoid function, $L$ returns a real number indicating the loss by comparing the output $h$ with target $y$, and finally $\rightarrow$ represents data flow. To minimize $L$ over $U$ and $V$ using gradient descent, we need to know $\frac{\partial L}{\partial U_{ij}}$ and $\frac{\partial L}{\partial V_{ij}}$, I know two ways to do this: do the differentiation point wise, and having a hard time figuring out how to vectorize it flatten $U$ and $V$ into a row vector, and use multivariate calculus (takes a vector, yields a vector) to do the differentiation For the purpose of tutorial or illustration, the above two methods might be suffice, but say if you really want to implement back-prop by hand in the real world, what math will you use to do the derivative? I mean, is there a branch, or method in meth, that teaches you how to take derivative of vector-valued function of matrices? A: There is Matrix Calculus, (and I would recommend the very useful Matrix Cookbook as a bookmark to keep), but for the most part, when it comes to derivatives, it just boils down to pointwise differentiation and keeping your dimensionalities in check. You might also want to look up Autodifferentiation. This is sort of a generalisation of the Chain Rule, such that it's possible to decompose any composite function, i.e. $a(x) = f(g(x))$, and calculate the gradient of the loss with respect to $g$ as a function of the gradient of the loss with respect to $f$. This means that for every operation in your neural network, you can give it the gradient of the operation that "consumes" it, and it'll calculate its own gradient and propagate the error backwards (hence back-propagation)
{ "pile_set_name": "StackExchange" }
Q: JADClipse not working with Eclipse 3.6 Does Jadclipse work on Eclipse 3.6? I have installed Jadclipse 3.3.0 on my Eclipse 3.6 by copying the jar into the plugins directory and restated eclipse. Now I have the jadclipse menu under Windows->Preferences but when trying to de-compile any class it simply does not de-compile. I get the usual eclipse screen saying the source is unavailable. There are no errors in the Error Log. Any idea? A: I eventually found the answer here. Running eclipse with -clean switch and setting the file association between *.class and the jadclipse plug-in solved the problem. A: Set the JAD path correctly in Preferances>Java>Jad. Ex: D:\Jad\jad.exe If still not working then, Go to File extensions in Preferences. Select JadClipse as default editor for .class and .class with out source. A: The main reason is that you eclipse have default class viewer configured for class file which you have to change to your new class decompiler. go to preference > editor > choose "class without source" and select your tool and mark as default. will work for you :)
{ "pile_set_name": "StackExchange" }
Q: What logic does one use to solve this probability question? Bill, George, and Ross, in order, roll a die. The first one to roll an even number wins and the game is ended. What is the probability that Bill win the game ?. How I approached the question: Since Bill is the first one to roll the die, he has a $.5$ probability of winning the game, if he does win then the question is solved the probability is $.5$, however if he doesn't roll an even number he has still a probability of winning, this probability would be $(.5)^3$. It seems to me that the probability of him winning is $(0.5)^n$ where $n$ is the number of die rolls. Is my logic correct, if not how is the problem answered ?. A: Your logic is somehow not bad. However it is not complete, because Bill can win at the first roll, the 4th roll, the 7th roll, etc etc. Let $X_n$ be the event that Bill wins at the $n$-th roll. Clearly $P(X_1)=\frac{1}{2}$ (you know this). $P(X_2)=P(X_3)=0$ because then it is not his game. $P(X_4)$ then Bill must not win one time, George must not win one time, and Ross neither, that together gives $(\frac{1}{2})^3$ and then Bill must win the fourth roll so $P(X_4)=(\frac{1}{2})^4$. In general we have: \begin{align} P(\text{ Bill wins }) &= P(\text{ Bill wins at the first roll, fourth roll, seventh roll,..})\\ &=\sum_{n=0}^\infty \left( \frac{1}{2}\right)^{3n+1}\\ &=\frac{1}{2}\frac{1}{1-\frac{1}{8}}\\ &=\frac{4}{7} \end{align} So Bill wins with probability $4/7$. You can check that the probability that George and Ross win is $2/7$ and $1/7$ respectively.
{ "pile_set_name": "StackExchange" }
Q: Submission timestamp of custom Form using Google Apps Script I wanted to create a form for data collection that included a field for image upload. I tried Google Forms, which natively doesn't support file upload, but I found this example: Form and file upload with htmlService and app script not working I managed to configure it with image upload, BUT, native Google Forms does have a timestamp column on the Spreadsheet responses. I tried: var timestamp = theForm.getTimestamp(); But didn't work... How can I get the response timestamp? Code excerpt: function processForm(theForm) { var fileBlob = theForm.myFile; var folder = DriveApp.getFolderById(folderId); var doc = folder.createFile(fileBlob); // Fill in response template var template = HtmlService.createTemplateFromFile('Thanks.html'); var name = template.name = theForm.name; var email = template.email = theForm.email; var timestamp = template.timestamp = theForm.getTimestamp(); // Record submission in spreadsheet var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0]; var lastRow = sheet.getLastRow(); var targetRange = sheet.getRange(lastRow+1, 1, 1, 5).setValues([[timestamp,name,department,message,email,fileUrl]]); // Return HTML text for display in page. return template.evaluate().getContent(); } A: HTML forms do not automatically pass any timestamp to the server on submit, like Google Forms do. You will have to generate that timestamp yourself. new Date() will do what you want: var timestamp = template.timestamp = new Date(); If you need to output this date object to screen in your page, you will need to make it human-readable by formatting it. You can use Utilities.formatDate() method to do this.
{ "pile_set_name": "StackExchange" }
Q: How do I configure a Kendo Grid dataSource to use the parameterMap functionality? I have a Kendo Grid and I want to pass a parameter to my Controller Action. I am able to use the transports read.data successfully but I'm trying to learn how to use the parameterMap functionality. Here is what I have that works: <script> $(document).ready(function () { var employeeNumber = @(ViewBag.EmployeeNumber); //passed in from controller $("#ShoppingCartGrid").kendoGrid({ dataSource: { dataType: "json", type:"GET", transport: { read: { url:"../Requisitions/GetShoppingCartSummary/", data: { employeeNumber:employeeNumber //passing param this way works }, } }, schema: { ...... //omitted for brevity </script> Here is what does not work but I don't know what I should put here: <script> $(document).ready(function () { var employeeNumber = @(ViewBag.EmployeeNumber); $("#ShoppingCartGrid").kendoGrid({ dataSource: { dataType: "json", type:"GET", transport: { read: { url:"../Requisitions/GetShoppingCartSummary/" }, parameterMap:function(options,operation){ // here is where I'm if (operation == "read") { // running into issues- even return employeeNumber:"140412"; // hard coding param- no joy } }; }, schema: { ...... //omitted for brevity </script> I have looked for hours for a solution but I can't seem to find a post that explains this concept well enough for me to grasp. Please don't send links to Kendo's documentation, been there, have the mental scars to prove it. Thanks for any suggestions. A: Your transport datatype is Json, therefore you need to return valid Json parameters. Kendo appends result of function provided in parameterMap to the method name you defined in your url. In your case - employeeNumber:"140412" is not a valid Json, you need to provide parmas in following format { paramname : value , otherparamname : value }. It is very handy to use JSON.stringify(o) to get your params correct. Below structure for parameterMap works for me: parameterMap: function (o, operation) { var output = null; switch (operation) { case "create": output = '{ id: ' + JSON.stringify(o) + ' }'; break; case "read": output = '{ id: ' + globalVariable + ' , filters: ' + JSON.stringify(o) + '}'; break; case "update": output = '{ id:' + JSON.stringify(o) + '}'; break; case "destroy": output = '{ id : ' + o.param+ ' }'; break; } return output; } Bit more detail as per your comment : parameterMap: function (o, operation) { var output = null; switch (operation) { case "read": var txt1 = $('#myTextBox1').val(); var txt2 = $('#myTextBox2').val(); var txt3 = $('#myTextBox3').val(); output = '{ textBoxValue1: ' + txt1 + ', textBoxValue2: ' + txt2 + ',textBoxValue3: ' + txt3 + '}'; break; } return output; } Server side method signature should look like : GetShoppingCartSummary(string textBoxValue1, string textBoxValue2, textBoxValue3);
{ "pile_set_name": "StackExchange" }
Q: open a file in a non existing directory c versus c++ I tried to open a file in a non existing directory in C++ and for some reason my application didn't crash. I find that a bit "weird" because I'm used to C, where the equivalent program does crash. Here is my C++ version followed by the equivalent C version: $ cat main.cpp #include <fstream> int main(int argc, char **argv) { std::ofstream f("/home/oren/NON_EXISTING_DIR/file.txt"); f << "lorem ipsum\n"; f.close(); printf("all good\n"); } $ g++ main.cpp -o main $ ./main all good When I try the equivalent thing with C I get a segfault: $ cat main.c #include <stdio.h> int main(int argc, char **argv) { FILE *fl = fopen("/home/oren/NON_EXISTING_DIR/file.txt","w+t"); fprintf(fl,"lorem ipsum\n"); fclose(fl); printf("all good\n"); } $ gcc main.c -o main $ ./main Segmentation fault (core dumped) Why is that? A: "I'm used to C", but then "[...] in C++" - well, C++ is not C, but that's irrelevant here. First, have a look at this - writes to an unopened stream (which is the case here) are ignored after setting the failbit. In your C example, however, the problem is that if fopen fais, it returns a NULL pointer. Then you pass it to fprintf. That's where the Undefined Behaviour1 happens. No such thing in the C++ example. 1Do note that the C example is not guaranteed to SEGFAULT. Undefined behaviour is undefined.
{ "pile_set_name": "StackExchange" }
Q: Detecting Shift modifiers on MouseEvent generated from click in swing I'm handling some MouseEvent in a GUI application using Java Swing. Since now i was analyzing mouse events inside mousePressed method, only to determine if a left or right click happened. My code was: public void mousePressed(MouseEvent me) { if (me.getModifiers == InputEvent.BUTTON1_DOWN_MASK){ //left click }else if (me.getModifiers == InputEvent.BUTTON3_DOWN_MASK){ //right click } Now my application is becoming more complicated and I need also to check if Shift button was pressed while mouse was left clicking. I would like to do something like this: public void mousePressed(MouseEvent me) { if (me.getModifiers == InputEvent.BUTTON1_DOWN_MASK && me.isShiftDown()){ //left click } Now this doesn't work. In particular if I click the left button while holding SHIFT isShiftDown returns true (rigth. i was expecting that), but now seems that modifiers are also changed and the comparison with BUTTON1_DOWN_MASK fails. me.getModifiers == InputEvent.BUTTON1_DOWN_MASK //failed..modifiers are changed What am I doing wrong? How can I fix my code? A: Note that the method is called getModifier_s_(), with an "s", because it can return more than one modifier, combined using bitwise "or". It's technically never correct to use "==": you should use bitwise "&", like this: if ((me.getModifiers() & InputEvent.BUTTON1_DOWN_MASK) != 0) ... then you'll respond to that one modifier, even if others are present.
{ "pile_set_name": "StackExchange" }
Q: access each object stored in an array I just want to clear up how it is possible to use an object that is stored in an array? In Laravel I trigger a query. $accounts = Account::where('customer_no', '=', $customer->customer_no)->get(); this returns two objects in an array here is a die and dump: array(2) { [0]=> object(Account)#40 (5) { ["attributes"]=> array(11) { ["acc_no"]=> int(5) ["acc_type"]=> string(7) "CURRENT" ["start_date"]=> string(19) "2012-09-05 00:00:00" ["status"]=> int(1) ["balance"]=> string(5) "57.67" ["end_date"]=> NULL ["interest_rate"]=> string(4) "0.60" ["pin"]=> string(4) "1112" ["attempts"]=> int(2) ["bank_code"]=> int(1) ["customer_no"]=> int(10000003) } [1]=> object(Account)#43 (5) { ["attributes"]=> array(11) { ["acc_no"]=> int(6) ["acc_type"]=> string(7) "SAVINGS" ["start_date"]=> string(19) "2007-01-01 00:00:00" ["status"]=> int(1) ["balance"]=> string(7) "1002.01" ["end_date"]=> NULL ["interest_rate"]=> string(4) "0.80" ["pin"]=> string(4) "3427" ["attempts"]=> int(2) ["bank_code"]=> int(1) ["customer_no"]=> int(10000003) } So I want to access these objects individually so I can make use of them, instead of having to do a foreach to access them individually. How can I store these objects independently in PHP? A: You can just grab the object from an array index. $account_one = $accounts[0]; $account_two = $accounts[1]; Is there a reason you don't want to use a foreach though? You could also use a regular for loop and use $accounts[i] to refer to a specific account.
{ "pile_set_name": "StackExchange" }
Q: What's wrong with this Fluent NHibernate Configuration? What's wrong with the following setup? The Where filter on the AutoPersistanceModel does not appear to be working and the table name convention does not appear to be working either. The error I'm evenually getting is "The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'property' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, jcs-cache, cache, id, composite-id' in namespace 'urn:nhibernate-mapping-2.2'." Here's my code: public ISessionFactory BuildSessionFactory() { return Fluently.Configure() .Database( OracleConfiguration.Oracle9.ConnectionString( c => c.FromConnectionStringWithKey("ConnectionString"))) .Mappings(m => { m.AutoMappings.Add(GetAutoPersistanceModel); m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()); }) .BuildSessionFactory(); } public AutoPersistenceModel GetAutoPersistanceModel() { return AutoPersistenceModel.MapEntitiesFromAssemblyOf<User>() .Where(type => type.IsClass && !type.IsAbstract && type.Namespace == "Some.Namespace") .ConventionDiscovery.Add<IConvention>( Table.Is(x => "tbl" + x.EntityType.Name.Pluralize()) ); } A: The exception is saying NHibernate has encountered a <property /> element first, which is invalid. The first element in an NHibernate hbm file should (nearly) always be an Id, so it seems the AutoPersistenceModel isn't finding your identifiers. How are your Ids named in your entities? The AutoPersistenceModel expects them to be literally called Id, if they're anything different then it won't find them. You can use the FindIdentity configuration option to override how the AutoPersistenceModel finds Ids, which can be useful if you're unable to modify your entities. // if your Id is EntityId .WithSetup(s => s.FindIdentity = property => property.DeclaredType.Name + "Id" ) A: James is leading you correctly but his snippet is wrong. .WithSetup(s=> s.FindIdentity = p => p.Name == "ID")); Is what you're after! Replace "ID" with what ever your actual property is.
{ "pile_set_name": "StackExchange" }
Q: Helpful linux command for do some forensic on compromised linux web server What are helpful linux command for do some forensic on compromised linux web server for giving out sort of information/evidence/backtrace? for example checking log, checking last file edit, suspicious open port, and others usefull automatic command for forensic? A: dd. Take an image of your compromised machine, then wipe it and start over. You cannot trust anything your host is telling you any more. Once you have said disk image though, the question is very much 'what do you want to accomplish'? If it's evidence/legal, then you're going to have to be incredibly careful, and probably want to consult with a legal professional before you even start. If it's just to figure out what's happened to compromise it, then I'd start with: find (look for 'odd' permissions, especially setuid). look through binaries in common locations (e.g. search path). md5sum and verify the signature against the source. log files - look for 'odd' entries in logs, and especially things like process crashes. Segmentation Faults are a big alarm bell for a buffer overflow exploit. But at the end of the day, a really good compromise of a system is really hard to exhaustively backtrace. Logs will have been 'tidied up', timestamps corrected. The only reliable sources are off host monitoring, such as a remote syslog server, a firewall or an intrusion detection system... but these are things that if you don't have in advance, you're too late.
{ "pile_set_name": "StackExchange" }
Q: Units of eigenvalues Suppose you have the system $\bf x' = \bf Ax$, where $\bf x$ is a vector and $\bf A$ is a matrix. What are the units of the eigenvalues of $\bf A$? I think they should be $1/t$ but I'm not sure how to verify this. Can you give me a starting point? A: Your intuition is correct, they should be 1/(the dimension of what you are taking the derivative with respect to). If your derivative is with respect to time, then it should be $1/t$. If your derivative is with respect to something unitless, the eigenvalue will be unitless, too. Write it as $\frac {dx}{dt}=Ax$ The units of $A$ are then $1/t$ and so the eigenvalues will be, too. If you are taking derivatives with respect to time, maybe the question belongs at physics.
{ "pile_set_name": "StackExchange" }
Q: Convert html string to pdf with prawnto I have field which stores html content. I want to convert html strings in the pdf. I am using prawnto to generate pdf. Any idea ? How to convert specific html string to pdf string ? A: It's easy with PDFKit: @your_object = YourObject.find(params[:id]) respond_to do |format| format.pdf do #html = render_to_string(:action => "show.html.haml", :layout => "pdf.html.haml") html = @your_object.your_html_field content = PDFKit.new(html) send_data(content.to_pdf, :filename => "content.pdf", :type => 'application/pdf', :disposition => 'inline') end end It uses wkhtmltopdf in a background and it's pretty easy to install too. It has a lot of options allowing to customize a pdf generation. Ryan Bates has a screencast on it.
{ "pile_set_name": "StackExchange" }
Q: How to fix overlapping objects on the stage in AS3 I have a flash game where I have a picture designed to be the textbox for a prompt and textbox inside with the relevant text but the textbox is being hidden by the image. Anyone know how to make is so that the textbox is guaranteed to be on top or whatever I need to do to keep this from happening? A: The other answer using setChildIndex will definitely work, however, I think a different design approach is really what you should be doing to remove the headache altogether. For example in a game I might have different layers such as : backgroundLayer gameLayer interfaceLayer Those 3 Sprite layers would get added to the stage in that order. I would then add display objects to the appropriate layers. So anything I added to the backgroundLayer or gameLayer would ALWAYS be 'behind' my user interface on the interfaceLayer. That allows you to not have to worry about the layering constantly. The answer with setChildIndex will fix the problem for that moment, but should something else be added to the container it will overlap your textbox, which is something I don't assume you want. here's an example : var backgroundLayer:Sprite = new Sprite; var gameLayer:Sprite = new Sprite; var interfaceLayer:Sprite = new Sprite; addChild(backgroundLayer); addChild(gameLayer); addChild(interfaceLayer); now, whatever you add to interfaceLayer, will ALWAYS be on top of objects you add to gameLayer or backgroundLayer. So in the case of your text box, just add it to your interfaceLayer and any other objects you want behind it, you add to the gameLayer or backgroundLayer.
{ "pile_set_name": "StackExchange" }
Q: Read the request stream multiple times We have a Tomcat ValveBase class implementation that is doing the authentication for our servlet container apps. One way to authenticate our http REST calls is to sign them and then check the signature on the server side. We do this check in the ValveBase class. The problem is that after we consume the InputStream of the request (for validating the signature), we pass the request (org.apache.catalina.connector.Request) to the next valve implementation and by the time it hits the servlet, the inputStream is gone. No content to be delivered, since it was consumed at the signature verification procedure. In the javax.servlet api, you can use an HttpServletRequestWrapper to implement your own ServletRequest and pass the real request as a constructor argument. In that case, we were able to avoid the situation where the content was read only once, but in the case of the catalina Request, seemed to be more delicate than we thought. Any ideas? Thanks. A: There is a long standing enhancement request open against Tomcat to support wrappers for use in Valves in a similar manner to Filters. The bug includes a patch that is likely to need updating for Tomcat 7.0.x. Given that you are already using a custom valve adding the patch may not be too much of a leap. With that patch in place, you should be able wrap the internal Request object and solve this problem in a similar manner to the Filter solution (which I assume involves saving a copy of the request body - watch out for DoS issues). This is, of course, completely untested. As an incentive to try it, if it does work and you provide the updated patch (attach it to the Bugzilla report) I'll look at getting it included in Tomcat 8.0.x and 7.0.x (providing it doesn't require any changes to the existing API).
{ "pile_set_name": "StackExchange" }
Q: Can't load jrxml located in jar file via JRXmlLoader: getting java.io.FileNotFoundException I' m using JasperReports in my Java application. I have a package named "reports" to store all the reports generated. Here is the way I'm calling my jasper report in my application. JasperDesign jd = JRXmlLoader.load("C:\\Users\\Sandaru Weerathunga\\Desktop\\Dasatha Institute\\src\\reports\\teacherPay.jrxml"); This is working. Instead of giving the full path , I tried: JasperDesign jd = JRXmlLoader.load("/reports/teacherPay.jrxml"); But this is showing an Error while running the program: net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: /reports/teacherPay.jrxml (The system cannot find the path specified) at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:176) at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:156) It is not suitable to give the full path to the JRXmlLoader because if you are going to run this application in other computer you have to change all the coding according to the computer path. So help me on this A: /reports/teacherPay.jrxml is an absolute file path, meaning, go to the root of the current drive and find the file teacherPay.jrxml in the reports directory... Which, if I read your question correctly, isn't what you want Instead, try loading the report as a resource (given the fact that you state that it's within a package JasperDesign jd = JRXmlLoader.load(getClass().getResource("/reports/teacherPay.jrxml")); If the report isn't packaged within your application context, then you will need to use a relative path instead, for example. JasperDesign jd = JRXmlLoader.load("reports/teacherPay.jrxml"); Now, having said that. Unless you are making dynamic changes at runtime, you shouldn't be loading the jrxml file, but instead, should have pre-compiled the file and should be loading the .jasper file instead. This will be faster and generally less error prone...
{ "pile_set_name": "StackExchange" }
Q: What is the relationship between django cms and custom plugin models? I've been working with django cms recently for the first time and I've created a gallery plugin for uploading images. It's quite a simple plugin, using a ImageGalleryPlugin model which inherits from CMSPluginBase and then an Image model which has a ForeignKey to the gallery. The gallery plugin is attached to pages using a placeholder and then to view the images within a gallery I have created an apphook to link the plugin template to a view similar to; def detail(request, page_id=None, gallery_id=None): """ View to display all the images in a chosen gallery and also provide links to the other galleries from the page """ gallery = get_object_or_404(ImageGalleryPlugin, pk=gallery_id) # Then get all the other galleries to allow linking to those # from within a gallery more_galleries = ImageGalleryPlugin.objects.all().exclude(pk=gallery.id) images = gallery.images_set.all() context = RequestContext(request.context, { 'images': images, 'gallery': gallery, 'more_galleries': more_galleries }) return render_to_template('gallery-page.html', context) Now the problem I have with this method is when you publish a page in CMS it duplicates all of the ImageGalleryPlugin objects on that page, so when I'm viewing the images, I've got twice as many links to the other galleries because the query collects the duplicate objects. I haven't been able to properly understand this behaviour from the docs but I think the CMS is keeping the original objects which you've created and then creating the duplicates as 'live' versions of the galleries to display to users. Where in CMS does this happen and where are the ID's of my ImageGalleryPlugin objects stored so that I can only collect the right ones in this view instead of collecting all objects? A: I've finally solved my own problem. The association between my CMSPlugin object and the Page is myobj.placeholder.page so the solution to my filtering is; # Get the ImageGalleryPlugin object gallery = get_object_or_404(ImageGalleryPlugin, pk=gallery_id) # Get all other ImageGalleryPlugin objects galleries = ImageGalleryPlugin.objects.all().exclude(pk=gallery.id) # Get all the images in the chosen gallery images = gallery.image_field.images # Filter the list of other galleries so that we don't get galleries # attached to other pages. more_galleries = [ g for g in galleries if unicode(g.placeholder.page.id) == page_id ]
{ "pile_set_name": "StackExchange" }
Q: CSS Proper alignment next to image in a row I'm trying to align text to the right of an image but I can't seem to get it working, I've tried different methods of css but can't get it too work. Edit: Also, How would I adjust this if i were to put it at the top? If I mvoe it manually then the bottom row will mess up too. What it looks like (Default) What I want it too look like (Only the first one, the others mess up) Here is the css: .slider__contents { height: 100%; padding: 2rem; text-align: center; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; -webkit-flex-flow: column nowrap; -ms-flex-flow: column nowrap; flex-flow: column nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; } .slider__image { font-size: 2.7rem; color: #2196F3; } .slider__caption { font-weight: 300; top: 95px; margin-left: 80px !important; position: absolute; margin: 2rem 0 1rem; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1); text-transform: uppercase; vertical-align: text-bottom; } .slider__txt { color: #f00; margin-bottom: 3rem; max-width: 300px; position: absolute; top: 95px; margin-left: 10px; font-size: 17px; text-align: left; } Here is the html: <div class="row"> <div class="col-md-4"> <div class="slider__contents"> <img class="img-avatar1" src="/images/team/1.jpg"/> <h2 class="slider__caption">Matt Sowards</h2> <p class="slider__txt">Founder</p> <!-- <a href="#" target="_blank"><p class="slider__steam">Steam Profile</p></a> --> </div> </div> </div> A: Wrapping your text tags into extra markup and switching to proper flex usage will net you the result you're after. Using absolute positioning is not the way to go here. See the snippet below (I have removed some code, my additions are followed by a comment): .slider__contents { height: 100%; padding: 2rem; text-align: center; display: flex; flex: 1; align-items: center; justify-content: center; background: gray; } .slider__image { font-size: 2.7rem; color: #2196F3; display: block; width: 4rem; /* Supposed to be the default size of the avatar */ height: 4rem; /* Supposed to be the default size of the avatar */ padding: 4px; /* Just to replicate your styles */ border: 2px solid red; /* Just to replicate your styles */ border-radius: 50%; /* Just to replicate your styles */ background-color: white; /* Just to replicate your styles */ overflow: hidden; /* Just to replicate your styles */ } .slider__image img { width: 100%; /* Fit to container */ border-radius: 50%; /* Round image */ } .slider__copy { /* Added to wrap the text */ display: flex; flex-direction: column; margin-left: 10px; /* Avoids text sticking to the avatar */ } .slider__caption { font-weight: 300; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1); text-transform: uppercase; vertical-align: text-bottom; margin: 0; /* Removes default margins, season to taste */ } .slider__txt { color: #f00; max-width: 300px; font-size: 17px; text-align: left; margin: 0; /* Removes default margins, season to taste */ order: -1; /* Places it first in the current flex flow */ } <div class="row"> <div class="col-md-4"> <div class="slider__contents"> <div class="slider__image"><!-- Added this wrapper around your image, name as you wish --> <img class="img-avatar1" src="/images/team/1.jpg" alt="Avatar"/> </div> <div class="slider__copy"><!-- Added this wrapper around your text, name as you wish --> <h2 class="slider__caption">Matt Sowards</h2> <p class="slider__txt">Founder</p> <!-- <a href="#" target="_blank"><p class="slider__steam">Steam Profile</p></a> --> </div> </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: How to calculate logarithms by using a necklace? I have read that before the french revolution on various salons it was a popular trick to calculate logarithms just by using a necklace. Could someone from your community explain this trick? A: (a) Suspend a necklace from two horizontally aligned nails. Draw the horizontal through the endpoints, and the vertical axis through the lowest point. (b) Put a third nail through the lowest point and extend one half of the necklace horizontally. (c) Connect the endpoint to the midpoint of the drawn horizontal, and bisect the line segment. Drop the perpendicular through this point, draw the horizontal axis through the point where the perpendicular intersects the vertical axis, and take the distance from the origin of the coordinate system to the lowest point of the necklace to be the unit length. We will show below that the resulting graph now has the equation $y = \frac{(e^x + e^{-x})}{2}$ in this coordinate system. (d) To find $\text{log}(y)$, find $(y + 1/y )/2$ on the y-axis and measure the corresponding x-value (on the necklace returned to its original form). This assumes that $y > 1$. To find logarithms of negative values, use the fact that $log(1/y ) = − log(y)$. If you seek the logarithm of a very large value, then you may end up too high on the y-axis; in such cases you can either try hanging the endpoints closer together or using logarithm laws to express the desired logarithm in terms of those of lower values. SOURCE: https://www.maa.org/sites/default/files/pdf/awards/college.math.j.47.2.95.pdf
{ "pile_set_name": "StackExchange" }
Q: How to send cookie containing an unicode character in https GET request using poor windows sockets I'm creating win32 application and I work with one particular site. From previous requests I extracted some cookies and I want to implement them. But the problem is, one of these cookies contains unicode letter (latyn small letter e with dot above; 279 in ASCII table). It is the only cookie which is url-encoded. When decoding, I get char \u0117 and visual studio compiler gives me warning that it is unicode char and treats it as ? mark. This is url-encoded cookie: Set-Cookie: logged_user=%7B%22id%22%3A%22625936%22%2C%22email%22%3A%22vytautas.leveris%40gmail.com%22%2C%22display_name%22%3A%22Vytautas+L%5Cu0117veris%22%2C%22full_name%22%3A%22Vytautas+L%5Cu0117veris%22%2C%22photo%22%3A%22https%3A%5C%2F%5C%2Fwww.15min.lt%5C%2Fassets%5C%2Fimages%5C%2Fuser-default-icon.png%22%2C%22photo_small%22%3A%22https%3A%5C%2F%5C%2Fwww.15min.lt%5C%2Fassets%5C%2Fimages%5C%2Fuser-default-icon.png%22%2C%22photo_normal%22%3A%22https%3A%5C%2F%5C%2Fwww.15min.lt%5C%2Fassets%5C%2Fimages%5C%2Fuser-default-icon.png%22%2C%22staff%22%3Afalse%2C%22bookmarks%22%3A2%2C%22nb%22%3A1%7D; path=/ This is url-decoded cookie: Set-Cookie: logged_user={\"id\":\"625936\",\"email\":\"[email protected]\",\"display_name\":\"Vytautas L\u0117veris\",\"full_name\":\"Vytautas L\u0117veris\",\"photo\":\"https:\/\/www.15min.lt\/assets\/images\/user-default-icon.png\",\"photo_small\":\"https:\/\/www.15min.lt\/assets\/images\/user-default-icon.png\",\"photo_normal\":\"https:\/\/www.15min.lt\/assets\/images\/user-default-icon.png\",\"staff\":false,\"bookmarks\":2,\"nb\":1}; path=/ And finally, all http GET request: strcpy(request,"GET / HTTP/1.1\r\nHost: www.15min.lt\r\nCookie: PHPSESSID=652e6dd2ac78de5db5392e53b9a0355a; logged_user={\"id\":\"625936\",\"email\":\"[email protected]\",\"display_name\":\"Vytautas L\u0117veris\",\"full_name\":\"Vytautas L\u0117veris\",\"photo\":\"https:\/\/www.15min.lt\/assets\/images\/user-default-icon.png\",\"photo_small\":\"https:\/\/www.15min.lt\/assets\/images\/user-default-icon.png\",\"photo_normal\":\"https:\/\/www.15min.lt\/assets\/images\/user-default-icon.png\",\"staff\":false,\"bookmarks\":2,\"nb\":1}; remember_me=625936; device_token_625936=84c45e719fedc5949ced93ca0df54152\r\nUser-Agent: WindowsSockets2\r\n\r\n"); As I send message through winsock, I use char type. Do I need to convert everything to wchar_t*? But then what about sending wchar_t* to server? Or perhaps I could change this character representation \u0117 into UTF8 char sequence? Any help and comments would be welcom. A: I'd recommend to treat the data as opaque sequence of bytes, i.e., convert you custom data to UTF-8 bytes, run base 64 and use it as cookie value. See also: https://stackoverflow.com/a/49205256/696632. Then reverse the operation on the receiver side. You will probably require unsigned char*for the opaque byte data.
{ "pile_set_name": "StackExchange" }
Q: Unable to set Apache httpd.config for static content on Jboss App Server I have put alias with and without trailing slashes.Still no solution. Do we need to change Any attributes in jboss xml's also?Proxy is setting fine though. Alias /images/ "c:/images/" <Directory "c:/images"> Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all </Directory> <VirtualHost *> ServerName localhost <IfModule proxy_module> <Proxy *> Order allow,deny Allow from * </Proxy> ProxyPass /HelloWeb http://localhost:8080/HelloWeb ProxyPassReverse /HelloWeb http://localhost:8080/HelloWeb <Location /HelloWeb> Order allow,deny Allow from all </Location> </IfModule> </VirtualHost> A: Well i found the answer long back but forgot to answer it . (in case someone needs it) I used proxypass instead of alias. ProxyPass /HelloWeb/css http://localhost/Hello/css ProxyPassReverse /HelloWeb/js http://localhost/Hello/css <Location /HelloWeb/css> Order allow,deny Allow from all </Location>
{ "pile_set_name": "StackExchange" }
Q: How to start process, then stop later in PHP, MySQL with AJAX I want to send an AJAX call to a server that makes phone calls to our clients. However, I don't want the person who starts the process to have to leave their browser open. After some research, I've found that I can pass a header in php normally to allow the browser to disconnect without the php execution stopping. Will this work for AJAX as well? The relevent code is below. //jQuery 1.8.10 $('#start').click(function(){ $.post('/startcalling', { 'time_limit': 0 }); }); $('#stop').click(function(){ $.post('/stopcalling'); }); The important PHP function startCalling(){ echo "starting..."; header('Connection: close'); while(getFlagStatus()){ makeNextCall(); } } function stopCalling(){ if(!getFlagStatus()){ $query = "UPDATE cc_flags SET cc_on = 0"; mysql_query($query); } } I could package this into a CLI command, and accomplish my goal, but I feel like there has to be an easier way. If I've been confusing, let me know and I'll edit. EDIT: Does php execution stop after a user leaves the page? Does this apply here? A: I looks like you want the behavior of ignore_user_abort($bool). But this alone won't help you much as PHP usually have a time limit of 30 seconds. set_time_limit($seconds) probably will help you with this. Keep in mind that the script will run on your webserver and the user will not have any way to kill the script if they make a mistake, so don't forget to add extra checks so your users don't spawn the script 10 times and let it run, especially if it's making phone calls! I'd suggest making a server script that runs outside of the web server, so you can communicate with the daemon and start/stop jobs on it. It's faily easy to do with simple sockets.
{ "pile_set_name": "StackExchange" }
Q: Best way to compare input values to read values from files I am relatively new to c++ programming and I have hit one of my first major snags in all of this.. I am trying to figure out how to read a value/character from a generic ".txt" file that is on notepad. With that comparison I want to determine whether or not to read that entire line, but I can't seem to just read the single one or two digit number, I got it to read the whole line using { 'buffername'.getline(variable, size) } but when I try to change the 'size' to a specific number it gives me a comparison error saying that its invalid to switch to 'int' or 'char' (depending on how I declare the variable). Any help is appreciated. Thanks A: int length = 2; char * buffer; ifstream is; is.open ("test.txt", ios::binary ); // allocate memory: buffer = new char [length]; // read 2 char is.read (buffer,length); //Compare the character and decide delete[] buffer; return 0;
{ "pile_set_name": "StackExchange" }
Q: How to upload zip file to azure blob then unzip it there I have lot of zip files, which will have few folders and 50+ files in it. How can I upload those zip files to azure blob then unzip it there. Unzipping the file in server and uploading files in it one by one to azure blob will be a cumbersome process. Does azure has any easy way to achieve this or is there any workaround? I'm implementing this in PHP. A: Simple answer is Azure Blob Storage will not do the unzipping for you. This is something you would need to do on your own. How you do it is up to you. One possibility is (like you mentioned) that you upload zip files on your server, unzip them there and then upload individual files. Another possibility is to do this unzipping through a background process if you are concerned about the processing happening on the web server. In this approach, you will simply upload the zip files in blob storage. Then through some background process (could be WebJobs, Functions, Worker Roles, or Virtual Machines), you would download these zip files, unzip them and then re-upload these individual files. To trigger the background process on demand, once the zip file is uploaded you could simply write a message in a queue telling background process to download the zip file and start unzipping process. A: As you prob. already found all over the internet, it's no possible to run workloads INSIDE of the storage servers... but: You can write a azure function to FileWatch your storage account, and unzip files for you, then upload them
{ "pile_set_name": "StackExchange" }
Q: c++ one solution two projects (exe & dll) linking error I have one Visual Studio solution which consists of two win32 projects: 1) application (.exe) 2) functions wrapper (.dll). The solution is in prototyping stage so all classes/functionality are implemented under (.exe) project - dirty but quick and easy for debugging/testing. I've started to write a DLL wrapper to "play" with functionality in MSExcel/VBA and faced linking error error LNK2019: unresolved external symbol "public: __thiscall Date::Date(int,int,int)" (??0Date@@QAE@HHH@Z) referenced in function addNumbers DLL header file: #ifdef LIBRARYWRAP_EXPORTS #define LIBRARYWRAP_API __declspec(dllexport) #else #define LIBRARYWRAP_API __declspec(dllimport) #endif LIBRARYWRAP_API int _stdcall addNumbers(int a, int b); DLL source file: #include "..\applicationProject\Date.h" class Date; LIBRARYWRAP_API int _stdcall addNumbers(int a, int b){ Date dummyDate(12,1,2014); // <- Linker error LNK2019. return (a+b); } Class Date and constructor Date::Date(int,int,int) are defined in application project(.exe) within Date.h, Date.cpp. What I've tried to do already: for librarywrap project added new reference. Project -> Properties -> Common -> Add New Reference. Selected "applicationProject". added additional include directories: $(SolutionDir)\applicationProject Two questions: First, Is that legal/achievable what I'm trying to do? DLL links to application project, whereas usually it should be other way round - application links to DLL. Hypothetically if i have two application projects (.exe) & (.exe) will it be possible to link one to another? Second, If answer for first question is positive what should I add/change to make it work? Thanks very much! Nicholas A: Technically, it is possible to make a DLL to call all needed functions from another modules (even from .exe ones - LoadLibrary can do this), but it would be a great pain: you will have to export all needed methods explicitly in the .EXE (just like you export DLL functions) and import them into your DLL. So the answer to the first question is yes, but if the DLL wants to use a lot of entry points from the EXE then probably it is not the best option. I'd suggest a different approach: having a common code base for both .exe (application) and .dll projects. Then you will be able to test your code by running the application, and to use the functionality from other apps through the DLL (the DLL will contain all the necessary code itself).
{ "pile_set_name": "StackExchange" }
Q: Input and Output symbols in EAGLE (perhaps with Labels and XREF) I'd like to create arrows in my schematic. The solution (using XREF) to an older, related post gets me most of the way there: Arrows on connections in schematics BUT, with that approach, the net always connects to the pointy part of the label symbol, effectively making all labels look like inputs. Mirroring the label, or rotating it 180 degrees does not solve this problem. Does anybody have a work-around? e.g. is it possible to make a set of devices (INPUT, OUTPUT, INOUT, etc.) that have symbols and a pin to tie to a net, but no associated packages? Here is an example of what I'd like to have: And here is what I can do in EAGLE so far (notice that my OUTPUT is a mirrored version of the input, but the net is drawn through the label in order to connect to the vertex. What I'd like is for the net to connect to flat side of the output label (i.e. on the left side of the label, near the letter "O" in the example below, and as in the CE, CSN, MOSI and SCK labels in the image above). A: Just drag the output label over. It doesn't need to be touching the net at the label origin. Note: To remove those little origin markers, use the set Option.ShowTextOrigins 0; command. Also note that this does not disconnect the label from the net, they are still associated (renaming the net will change the label). This simply moves the origin to not be on top of the net, so the two must be selected with the selection tool before being moved.
{ "pile_set_name": "StackExchange" }
Q: In C++, how to declare a data structure in header file , while it is defined in source file? Say I want to use typedef to define a new set MyTypeSet with customized hash and comparator functions in a source file. I want to hide all the implementation details in the source file. typedef std::unordered_set<MyType, MyTypeHash, MyTypeKeyEqual> MyTypeSet; Then I want to declare MyTypeSet in header file for other modules to use. But I do not want to expose MyTypeHash and MyTypeKeyEqual Just can not figure out the right syntax. A: This can't be done with typedef. The user of MyTypeSet needs to be able to see complete definitions for MyType, MyTypeHash, and MyTypeKeyEqual in order to know how to compile MyTypeSet. There are a few approaches in use to demarcate the public interface of templated code from the implementation details: Put the implementation details in another header ("MyTypeImpl.hpp") that is included in the public header. Put the private implementation types in a namespace named detail, private, or similar. Mangle the private names with underscore characters, as in MyTypeHash_. (This can be seen a good bit in the MSVC standard library). If it is absolutely imperative to keep MyTypeHash and MyTypeKeyEqual secret, then one could declare MyTypeSet as a class that only has the methods needed by the end user. Then MyTypeSet could use the pImpl idiom to have a std::unordered_set as a member variable visible only in the source file. All of the methods of MyTypeSet would be implemented by calling into the std::unordered_set. Such a MyTypeSet cannot have exactly the same public interface as std::unordered_set, because std::unordered_set exposes its hash and key types as member types.
{ "pile_set_name": "StackExchange" }
Q: adding four lines before last line of the file in gvim IS there a way to add 4 lines before the last line of the file in vim? I'm new to vim and recently found out that vim does multiline search which is awesome. Now only if I could find how to add 4 lines before the last line in the file I would totally save immense amount of time A: G 4 O Esc
{ "pile_set_name": "StackExchange" }
Q: Unable to send Email through GoDaddy SMTP I am working on an ASP .Net MVC website and I've to send email through Godaddy smtp, Previously my site was developed in classic ASP and it was hosted on godaddy's web hosting (then it was working fine) but now I am hosting this site on IIS, I am using following code to send email but it is not working MailMessage msg = new MailMessage(); msg.From = new MailAddress(model.From); msg.To.Add(model.To); msg.Body = model.Body; msg.Subject = model.Subject; SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net",25); smtp.Credentials = new NetworkCredentials("support@{myCompanyName}.com",{password}); smtp.EnableSsl = False; smtp.Send(msg); I have also used dedrelay.secureserver.net instead of relay-hosting.secureserver.net host (as mentioned at https://pk.godaddy.com/help/what-is-my-servers-email-relay-server-16601) but both are not working A: GoDaddy does not allow relaying through their server unless you are on one of their hosting plans that includes SMTP.
{ "pile_set_name": "StackExchange" }
Q: stack overflow code in c for writing exploit I am attempting to launch a shell in my Linux environment (BT3) but it keeps seg faulting. The method that I'm using is out of The Shellcoder's HandBook. Note that all of this is straight out of the text. For more reference: http://www.backtrack-linux.org/forums/old-pentesting/15508-stuck-eip-buffer-overflow.html A: Many buffer overflow exploits have been fixed in modern operating system patches. It's likely you're seg faulting because the operating system is detecting a buffer overrun and killing your process.
{ "pile_set_name": "StackExchange" }
Q: Single summation with two variables Disclaimer: This is for homework, but I'm just stuck on this one small part of a larger problem. I'm having trouble figuring out how to get the following summation in closed form. $$\sum_{j=1}^i 4ij$$ Since the index is j, am I able to move the i out of the summation as a constant the way I am with the 4? If I do that, do I need to square the i because it is the stopping point of the summation? Am I able to separate the summation into two, like this? $$\left(\sum_{j=1}^i 4i\right)\left(\sum_{j=1}^i j\right)$$ A: The $i$ is indeed a constant, so you treat it exactly as like the $4$: $$\sum_{j=1}^i4ij=4i\sum_{j=1}^ij=4i\left(\frac{i(i+1)}2\right)=2i^2(i+1)\;.$$ It might help you to write out some terms: the sum is $$4i\cdot1+4i\cdot2+4i\cdot3+\ldots+4i\cdot i\;,$$ which clearly has a factor of $4i$ in each term that can be factored out to yield $$4i(1+2+3+\ldots+i)\;.$$
{ "pile_set_name": "StackExchange" }
Q: MongoDB hosted in Azure Cosmos DB: Sharding vs partitioning We want to use MongoDB for our database, and we want to use the MongoDB API to avoid to be "locked in" to Azure Cosmos DB hosting. We use .Net Core and the MongoDB.Driver package (to be able to easily switch between on-prem, Atlas, Azure Cosmos hsoting etc.) to communicate with the MongoDB instance, so far so good. To be able to handle future growth of data volumes (size and performance) I want to have my collections sharded. As I understand the strategy Cosmos DB use is partitioning with partition keys, but since we use the MongoDB.Driver I can not find anyway to specify partitionkeys in my queries. "Plain" MongoDB use sharding instead, and you can set up a document property that should be used as a delimiter for how your data should be sharded. So, my guess is that sharding is the way to go (since partionkeys is a Cosmos feature) but I can not manage to get it working. The "MongoDB shell" in Azure Portal do not understand the sh.shardCollection command and if I connect with a MongoDB shell from my client I get the following error: globaldb:PRIMARY> use sampledatabase switched to db sampledatabase globaldb:PRIMARY> sh.shardCollection("sampledatabase.Event", { TenantId: 1 } ) 2018-06-21T12:03:06.522+0200 E QUERY [thread1] Error: not connected to a mongos : How do I proceed to get sharding up and running in a MongoDB instance hosted in Azure Cosmos? A: The CosmosDB Mongo api endpoint exposes a MongoD interface with replica-set enabled instead of a MongoS interface. Hence, you will need to use db.runCommand instead of the "sh" sharding commands to create a sharded collection. You can find more details at https://docs.microsoft.com/en-us/azure/cosmos-db/partition-data#mongodb-api
{ "pile_set_name": "StackExchange" }
Q: Swapping the text with the function I am still a newbie with javascript and I wanted to know how to make it so that the function appears and the text next to that, What I mean by that is, it is now show loading and next to it the variable text but I what I want is that the variable text is in front of the static 'loading' text loader.text('Loading '+$(this).text()).show(); Thanks in advance A: It might be a good idea for you to check out some beginner Javascript resources. What you're trying to do is very basic, and is called "string concatenation". Best of luck.
{ "pile_set_name": "StackExchange" }
Q: Difference between symbolic execution and reachability analysis Now I am confused about symbolic execution (SE) and reachability analysis (RA). As I know, SE uses symbols to execute some code to reach each branch with branch conditions. And RA can be used to find the reachability of each branch, right? When RA is used, we can extract the branch condition for each branch. If so, what's the difference between them? Can they be swift? Are they all static analysis? A: Generally, reachability analysis is a goal (determine which points in the code are reachable), whereas symbolic execution is a specific algorithmic technique (a tool for analyzing code). You can use symbolic execution for reachability analysis, or for other goals. Conversely, you can use other algorithms for reachability analysis. Classically, symbolic execution was a static analysis. However, recently it has been widely used in a hybrid static-dynamic analysis: see, e.g., concolic execution. These hybrid methods seem to be very effective, but they are not purely static.
{ "pile_set_name": "StackExchange" }
Q: fontweight property has no effect on AnchoredText object? I'm trying to draw some text through an AnchoredText (see the code below) but the fontweight property does not seem to have any effect: I'm using Python 3.7.3 and matplotlib 3.1.0. What am I missing here? import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredText ax = plt.subplot(131) plt.plot([]) anchored_text = AnchoredText( "aaa bb ccc", loc=8, prop={'family': 'Ubuntu Condensed', 'size': 35, 'fontweight': 'normal'}, frameon=False) ax.add_artist(anchored_text) ax = plt.subplot(132) plt.plot([]) anchored_text = AnchoredText( "aaa bb ccc", loc=8, prop={'family': 'Ubuntu Condensed', 'size': 35, 'fontweight': 'bold'}, frameon=False) ax.add_artist(anchored_text) ax = plt.subplot(133) plt.plot([]) anchored_text = AnchoredText( "aaa bb ccc", loc=8, prop={'family': 'Ubuntu Condensed', 'size': 35, 'fontweight': 'light'}, frameon=False) ax.add_artist(anchored_text) plt.show() A: As per https://fonts.google.com/specimen/Ubuntu+Condensed there's only 'Regular' style for your choice of font, so using different fontweight parameters will not have any impact
{ "pile_set_name": "StackExchange" }
Q: How do I correctly subscribe to a bluetooth low energy device's GattCharacteristic.ValueChanged notification (indication) in a Windows UWP App? On my Linux machine I have successfully subscribed to a Timeular/ZEI Bluetooth LE Device using Java, the TinyB Library and BlueZ. However I do need the same functionality for Windows 10 (1709). I am using the most recent Windows SDK with Visual Studio 2017. My goal is to subscribe to a GattCharacteristic.ValueChanged event, so whenever someone is "rolling the dice", the BTLE device will send a notification to the Windows App and call my DiceOrientationChangeHandler. What I got so far is: const string DEVICE_MAC_ADDRESS = "ee:ab:17:be:37:20"; //Timeular's MAC address const string BLUETOOTH_LE_SERVICE_UUID = "c7e70010-c847-11e6-8175-8c89a55d403c"; //the service which contains Timeular's orientation change characteristic const string BLUETOOTH_LE_CHARACTERISTIC_UUID = "c7e70012-c847-11e6-8175-8c89a55d403c"; //the characteristic that allows subscription to notification (indication) for orientation change public async void SubscribeToOrientationChangeNotification() { BluetoothLEDevice bluetoothLEDevice = null; //loop through bluetooth devices until we found our desired device by mac address DeviceInformationCollection deviceInformationCollection = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); foreach (var deviceInformation in deviceInformationCollection) { String deviceInformationId = deviceInformation.Id; String mac = deviceInformationId.Substring(deviceInformationId.Length - 17); if (mac.Equals(DEVICE_MAC_ADDRESS)) { bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(deviceInformation.Id); Debug.WriteLine($"Found Bluetooth LE Device [{mac}]: {bluetoothLEDevice.ConnectionStatus}"); break; } } //Subscribe to the connection status change event bluetoothLEDevice.ConnectionStatusChanged += ConnectionStatusChangeHandler; //get the desired service Guid serviceGuid = Guid.Parse(BLUETOOTH_LE_SERVICE_UUID); GattDeviceServicesResult serviceResult = await bluetoothLEDevice.GetGattServicesForUuidAsync(serviceGuid); if (serviceResult.Status == GattCommunicationStatus.Success) { GattDeviceService service = serviceResult.Services[0]; Debug.WriteLine($"Service @ {service.Uuid}, found and accessed!"); //get the desired characteristic Guid characteristicGuid = Guid.Parse(BLUETOOTH_LE_CHARACTERISTIC_UUID); GattCharacteristicsResult characteristicResult = await service.GetCharacteristicsForUuidAsync(characteristicGuid); if (characteristicResult.Status == GattCommunicationStatus.Success) { GattCharacteristic characteristic = characteristicResult.Characteristics[0]; Debug.WriteLine($"Characteristic @ {characteristic.Uuid} found and accessed!"); //check access to the characteristic Debug.Write("We have the following access to the characteristic: "); GattCharacteristicProperties properties = characteristic.CharacteristicProperties; foreach (GattCharacteristicProperties property in Enum.GetValues(typeof(GattCharacteristicProperties))) { if (properties.HasFlag(property)) { Debug.Write($"{property} "); } } Debug.WriteLine(""); //subscribe to the GATT characteristic's notification GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); if (status == GattCommunicationStatus.Success) { Debug.WriteLine("Subscribing to the Indication/Notification"); characteristic.ValueChanged += DiceOrientationChangeHandler; } else { Debug.WriteLine($"ERR1: {status}"); } } else { Debug.WriteLine($"ERR2: {characteristicResult.Status}"); } } else { Debug.WriteLine($"ERR3: {serviceResult.Status}"); } } public void DiceOrientationChangeHandler(GattCharacteristic sender, GattValueChangedEventArgs eventArgs) { Debug.WriteLine($"Dice rolled..."); } public void ConnectionStatusChangeHandler(BluetoothLEDevice bluetoothLEDevice, Object o) { Debug.WriteLine($"The device is now: {bluetoothLEDevice.ConnectionStatus}"); } The output looks like: Found Bluetooth LE Device [ee:ab:17:be:37:20]: Connected Service @ c7e70010-c847-11e6-8175-8c89a55d403c, found and accessed! Characteristic @ c7e70012-c847-11e6-8175-8c89a55d403c found and accessed! We have the following access to the characteristic: None Read Indicate Subscribing to the Indication/Notification The device is now: Disconnected But whenever I change the device's orientation, nothing happens. The service uuid and characteristic uuid are the same that I am using in the Linux program, where the orientation change handler is working. After a short while, one last message will be printed to the console: The Thread 0x2b40 has exited with code 0 (0x0). What am I doing wrong subscribing to the Bluetooth LE device's notification? A: I finally found the issue: Using the linux library, it somehow automatically determined what type of notification the GATT Service is using. Using the Windows SDK I had to explicitly specify that the type of notification is an indication by using GattClientCharacteristicConfigurationDescriptorValue.Indicate. Now the event is fired once I "roll the dice".
{ "pile_set_name": "StackExchange" }
Q: Go concurrency with for loop and anonymous function behaves unexpectedly I have already found out a way for the code to behave as I want, but I would like to understand why it behaves like this so that my understanding of Go concurrency improves. I was testing out sync.WaitGroup to wait for some goroutines to finish because I plan on doing multiple uploads to Amazon S3 in this way. This was the code I had originally: func main() { var wg sync.WaitGroup for i := 1; i <= 5; i++ { wg.Add(1) go func() { fmt.Println(i) time.Sleep(time.Second * 1) wg.Done() }() } wg.Wait() } I was surprised to see that the output was: 6, 6, 6, 6, 6. Instead of something like: 2, 4, 1, 5, 3. Since the loop does not even go to 6, this made no sense to me. I later passed the i variable to the anonymous function as argument and then it behaved as I expected. Why does this happen? I don't understand it. A: This is covered in the faq: What happens with closures running as goroutines? In this case, none of the goroutines get scheduled until the for loop completes. In order for the for loop to break i must not be less than or equal to 5, therefore it is 6 at that point. When the goroutines run, they each print the value of the single variable i which is captured in the closures. When you pass i as an argument to the function, you copy the current value to a new variable, capturing the value at that moment.
{ "pile_set_name": "StackExchange" }
Q: In Django, how to use a list from html checkboxes to loop through elements, and go to element specific page I want to obtain a list from a HTML form with specific IDs in it: search.html: <form method='POST' action='/report/'> {% for o in obj %} <tbody> <tr> <td>{{o.sample}}</td> <td><input type="checkbox" name="Samples" value="{{o.sample}}</td> </tr> </tbody> {% endfor %} <input type="submit" value="Submit"> </form> This gives me a list of samples to my report view which takes me to /report/ in my URLs i have defined a regex so that it would be able to take me to a sample specific report URL: url(r'^report/Sam\d{1,5}_\d{2}/$', views.report), What I want is to be able to loop through this list sample IDs, so when I click the initial submit, it takes me to the first sample ID at: localhost:8000/report/H1_1/ then I process and make a report for this sample, I submit and it takes me to the next sample ID in my list: localhost:8000/report/H2_1/ etc. I have been racking my brain on how to do this and the only thing I came up with was: search.html: {% for o in obj %} <form method='POST' action='/report/{{o.sample}}'> <tbody> <tr> <td>{{o.sample}}</td> <td><input type="checkbox" name="Samples" value="{{o.sample}}</td> </tr> </tbody> {% endfor %} <input type="submit" value="Submit"> </form> but I cant work how to get to the next sample in the sample specific html page form. A: You probably want to close every form inside the loop, or you want a single form with all the entry, but what you have now is not so clean and could lead to errors. Something like this: {% for o in obj %} <form method="POST" action="/report/{{o.sample}}"> <tbody> <tr> <td>{{o.sample}}</td> <td><input type="checkbox" name="Samples" value="{{o.sample}}"></td> </tr> </tbody> <input type="submit" value="Submit" label="Submit {{o.sample}}"> </form> {% endfor %} Or like this for a single form: <form method="POST" action="/report/samples"> {% for o in obj %} <tbody> <tr> <td>{{o.sample}}</td> <td><input type="checkbox" name="Samples" value="{{o.sample}}"></td> </tr> </tbody> {% endfor %} <input type="submit" value="Submit" label="Submit"> </form> But I think, based on what you wrote, that the 1st example better fits your needs.
{ "pile_set_name": "StackExchange" }
Q: is it possible to have multiple image styles for one uploaded image in drupal 8 I have my main story pages. I have one image style set on the content type display page for 880 x 495. I also want to have a image style set for thumbnails sizes of these photos. But as I see it I can only have one or the other. Is there a way to apply multiple image styles to the same uploaded photo field in drupal 8? A: You can reuse images using different image sizes - as far as I am aware there isn't a way to do this using the Drupal Field UI - but you could (for example) override the node display using views for more customisation including the ability to use the same image field using multiple image styles.
{ "pile_set_name": "StackExchange" }
Q: Creating a flexmark extension in Clojure I'm trying to write a small extension to flexmark. I want to create a custom AttributeProvider and am trying to work through the example shown here. My issue is translating two classes into Clojure. I've separated the two relevant example classes into separate Java source files and translated the demonstration program into a clojure test. The SampleAttributeProvider in Java: package cwiki.util; import com.vladsch.flexmark.ast.Link; import com.vladsch.flexmark.ast.Node; import com.vladsch.flexmark.html.AttributeProvider; import com.vladsch.flexmark.html.AttributeProviderFactory; import com.vladsch.flexmark.html.IndependentAttributeProviderFactory; import com.vladsch.flexmark.html.renderer.AttributablePart; import com.vladsch.flexmark.html.renderer.LinkResolverContext; import com.vladsch.flexmark.util.html.Attributes; class SampleAttributeProvider implements AttributeProvider { @Override public void setAttributes(final Node node, final AttributablePart part, final Attributes attributes) { if (node instanceof Link && part == AttributablePart.LINK) { Link link = (Link) node; if (link.getText().equals("...")) { attributes.replaceValue("target", "_top"); } } } static AttributeProviderFactory Factory() { return new IndependentAttributeProviderFactory() { @Override public AttributeProvider create(LinkResolverContext context) { //noinspection ReturnOfInnerClass return new SampleAttributeProvider(); } }; } } The SampleExtension in Java. package cwiki.util; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.util.options.MutableDataHolder; public class SampleExtension implements HtmlRenderer.HtmlRendererExtension { @Override public void rendererOptions(final MutableDataHolder options) { // add any configuration settings to options you want to apply to everything, here } @Override public void extend(final HtmlRenderer.Builder rendererBuilder, final String rendererType) { rendererBuilder.attributeProviderFactory(cwiki.util.SampleAttributeProvider.Factory()); } public static SampleExtension create() { return new SampleExtension(); } } Translating the demonstraton program in the example is straightforward. The test file in Clojure: (ns cwiki.test.util.CWikiAttributeProviderTest (:require [clojure.test :refer :all]) (:import (com.vladsch.flexmark.util.options MutableDataSet) (com.vladsch.flexmark.parser Parser Parser$Builder) (com.vladsch.flexmark.html HtmlRenderer HtmlRenderer$Builder) (cwiki.util SampleExtension) (java.util ArrayList))) (defn commonmark [markdown] (let [options (-> (MutableDataSet.) (.set Parser/EXTENSIONS (ArrayList. [(SampleExtension/create)])) (.set HtmlRenderer/SOFT_BREAK "<br/>")) parser (.build ^Parser$Builder (Parser/builder options)) document (.parse ^Parser parser ^String markdown) renderer (.build ^HtmlRenderer$Builder (HtmlRenderer/builder options))] (.render renderer document))) (deftest cwiki-attribute-provider-test (testing "The ability of the CWikiAttributeProvider to place the correct attributes in wikilinks." (let [test-output (commonmark "[...](http://github.com/vsch/flexmark-java)")] (is (= test-output "<p><a href=\"http://github.com/vsch/flexmark-java\" target=\"_top\">...</a></p>\n"))))) The test runs and passes using the two Java classes above. I've been able to translate the SampleAttributeProvider to Clojure. It compiles and produces class files. I haven't been able to actually run and test it because... I'm having problems translating the extension class from the example. Here is what I've come up with so far. (Class names have been changed to avoid collisions.): (ns cwiki.util.CWikiAttributeProviderExtension (:gen-class :implements [com.vladsch.flexmark.html.HtmlRenderer$HtmlRendererExtension] :methods [^:static [create [] cwiki.util.CWikiAttributeProviderExtension]]) (:import (com.vladsch.flexmark.html HtmlRenderer$Builder) (com.vladsch.flexmark.util.options MutableDataHolder) (cwiki.util CWikiAttributeProvider CWikiAttributeProviderExtension))) (defn -rendererOptions [this ^MutableDataHolder options] ; Add any configuration option that you want to apply to everything here. ) (defn -extend [this ^HtmlRenderer$Builder rendererBuilder ^String rendererType] (.attributeProviderFactory rendererBuilder (CWikiAttributeProvider.))) (defn ^CWikiAttributeProviderExtension -create [this] (CWikiAttributeProviderExtension.)) Attempting to compile this with $ lein compile CWikiAttributeProviderExtension, it produces an error message starting with: Compiling cwiki.util.CWikiAttributeProviderExtension java.lang.ClassNotFoundException: cwiki.util.CWikiAttributeProviderExtension, compiling:(cwiki/util/CWikiAttributeProviderExtension.clj:1:1) Exception in thread "main" java.lang.ClassNotFoundException: cwiki.util.CWikiAttributeProviderExtension, compiling:(cwiki/util/CWikiAttributeProviderExtension.clj:1:1) at clojure.lang.Compiler.analyzeSeq(Compiler.java:7010) at clojure.lang.Compiler.analyze(Compiler.java:6773) at clojure.lang.Compiler.analyze(Compiler.java:6729) at clojure.lang.Compiler$BodyExpr$Parser.parse(Compiler.java:6100) at clojure.lang.Compiler$TryExpr$Parser.parse(Compiler.java:2307) at clojure.lang.Compiler.analyzeSeq(Compiler.java:7003) ... The IDE (Cursive on IntelliJ) shows a warning message about not being able to resolve the create method in the :gen-class section, but I can't see anything wrong with the declaration or implementation. This translation is similar to what I have used previously in other programs to build a Java class that adds a method to an object extending a Java interface. It is similar to what I used to create the other relevant class in the example. But clearly something is wrong. Attempting to just use the translated CWikiAttributeProvider without translating the extension class causes the tool chain to get confused about first compiling an object in Clojure, then the Java parts, then the rest of the Clojure program. So it seems I must translate both classes at once or not at all. Just for completeness, here's the translated attribute provider class in Clojure. (ns cwiki.util.CWikiAttributeProvider (:gen-class :implements [com.vladsch.flexmark.html.AttributeProvider] :methods [^:static [Factory [] com.vladsch.flexmark.html.AttributeProviderFactory]]) (:import (com.vladsch.flexmark.ast Node Link) (com.vladsch.flexmark.html AttributeProviderFactory IndependentAttributeProviderFactory) (com.vladsch.flexmark.html.renderer AttributablePart LinkResolverContext) (com.vladsch.flexmark.util.html Attributes) (cwiki.util CWikiAttributeProvider))) (defn -setAttributes [this ^Node node ^AttributablePart part ^Attributes attributes] (when (and (= (type node) Link) (= part AttributablePart/LINK)) (let [title (.getText ^Link node)] (println "node: " node) (println "title: " title) (when (= title "...") (.replaceValue attributes "target" "_top"))))) (defn ^AttributeProviderFactory -Factory [this] (proxy [IndependentAttributeProviderFactory] [] (create [^LinkResolverContext context] ;; noinspection ReturnOfInnerClass (CWikiAttributeProvider.)))) A: You need a forward declaration for the CWikiAttributeProvider as a return value in gen-class. Declare the class in two steps at the top of your file: 1) with constructors only, and 2) with a full declaration including (static) methods and state. (gen-class :name cwiki.util.CWikiAttributeProviderExtension :implements [com.vladsch.flexmark.html.HtmlRenderer$HtmlRendererExtension]) (gen-class :name cwiki.util.CWikiAttributeProviderExtension :implements [com.vladsch.flexmark.html.HtmlRenderer$HtmlRendererExtension] :methods (^:static [create [] cwiki.util.CWikiAttributeProviderExtension])) I was able to compile your example, using these gen-class statements, and following modifications: removing the class itself from import statements, referring to the class by its fully-qualified name (cwiki.util.CWikiAttributeProvider) in method implementations and type hints, and removing this reference from the static method (to match the gen-class declaration for the method). Note also that you need to compile the class ahead-of-time (AOT) when using it in a project.
{ "pile_set_name": "StackExchange" }
Q: Karma.js installation in WebStorm - bash: karma: command not found So I have installed node.js from nodejs.org and I have installed karma.js in my project using the Webstorm command tool: npm install karma. I have also added those 3 path variables (please tell me which one I don't need) in Webstorm->Settings->Path Variables. Name: nodejs Value: /usr/local/bin Name: npm Value: /usr/local/lib/node_modules/npm/bin Name: karma Value: /Users/maxime/Documents/WebStorm/icms/node_modules/karma/bin When I type init karma to get the karma config file, I get: bash: karma: command not found I search on the site for some answers, but all I found was to add those path variables... EDIT: I tried with sudo but it does not work EDIT: It works with /Users/maxime/Documents/WebStorm/icms-dev-39534/node_modules/karma/bin/karma init, but it's still not working with karma init. A: The command line interface is in a separate package. To install this use: npm install -g karma-cli
{ "pile_set_name": "StackExchange" }
Q: Adding items from the bottom up in listview I've currently got two lists I'm working with. One filled with items and the other one is empty. When the user double-clicks an item in the filled list it's supposed to add that item to the empty/second list, but instead of adding it to the top of that list I want the newly added item at the bottom. So the items should be added from the bottom up. I'm working with a datagridview, but am willing to use listview/listbox as long as it gets the job done. A: I added two list boxes to a windows form. listBox1 and listBox2 I added Seven Items to the first list box {One,Two,Three...} I added the double click event handler where I listBox2.Items.Add(listBox1.SelectedItem); The new Item added to the bottom of the list, which is what it sounds like you want. I know the same thing works with a DataGridView. Do you want them to be added physically to the bottom of the box leaving whitespace at the top until it is filled? Is that what you are trying to do? Sorry this isn't really an answer, I guess I don't have enough rep to reply as a comment. EDIT: ok I think I have your answer now Add a list box with your items, it doesn't have to be a list box your Datagridview would work fine. Try using a FlowControlPanel and change alignment to bottom up, sounds easy, well it is. Add labels to it, like this //add a label to the flow control panel when you double click on an item private void listBox1_DoubleClick(object sender, EventArgs e) { Label label = new Label(); label.Text = listBox1.SelectedItem.ToString(); label.Click += new EventHandler(label_Click); label.AutoSize = true; flowLayoutPanel1.Controls.Add(label); label.BringToFront(); } //Will remove the label if you click on it. void label_Click(object sender, EventArgs e) { ((Label)sender).Click -= new EventHandler(label_Click); ((Label)sender).Dispose(); } brining the label to the front puts the new one at the bottom.
{ "pile_set_name": "StackExchange" }
Q: ListBoxItem style query I am trying to set the background for my ListboxItem with the help of the ValueConverter. But the background is not applied. On debugging I found that the value converter returns correct values. Am I missing something in my code? Note: I don't want to use alternate index style XAML: <Style x:Key="listBoxItemAlternateStyle" TargetType="{x:Type ListBoxItem}"> <Setter Property="MinHeight" Value="20"/> <Setter Property="Focusable" Value="False"/> <Setter Property="Background"> <Setter.Value> <MultiBinding Converter="{StaticResource AlternateIndexConverter}"> <MultiBinding.Bindings> <Binding Path="IsVisible" /> <Binding Path="Index" /> </MultiBinding.Bindings> </MultiBinding> </Setter.Value> </Setter> <Style.Triggers> <DataTrigger Binding="{Binding Path=IsVisible}" Value="False"> <Setter Property="Visibility" Value="Collapsed" /> </DataTrigger> <DataTrigger Binding="{Binding Path=IsVisible}" Value="True"> <Setter Property="Visibility" Value="Visible" /> </DataTrigger> </Style.Triggers> </Style> Codebehind: public class AlternateIndexConverter : System.Windows.Data.IMultiValueConverter { public static uint count = 0; public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool isVisible = bool.Parse(values[0].ToString()); uint index = uint.Parse(values[1].ToString()); if (index == 0) count = 0; if (isVisible && count % 2 == 0) { count++; return "#C8C8C8"; //dark color } else if (isVisible && count % 2 == 1) { count++; return "#E1E1E1"; //light color } else return null; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } A: Return Brush from your Converter instead of String if (isVisible && count % 2 == 0) { count++; return new SolidColorBrush(Color.FromArgb(255,200,200,200)); //dark color } else if (isVisible && count % 2 == 1) { count++; return new SolidColorBrush(Color.FromArgb(255,225,225,225)); //light color }
{ "pile_set_name": "StackExchange" }
Q: jQuery mobile radio button changed event always fires even if already checked I'm using a radio button group containing two radio buttons to dynamically change the content of my page depending on which radio button is checked. The content should be updated, when the selected radio button changes. Therefor i added an event handler to the radio buttons. html: <fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center" > <input name="radio" id="radio-a" type="radio" > <label for="radio-a">a → b</label> <input name="radio" id="radio-b" type="radio"> <label for="radio-b">b → a</label> </fieldset> jQuery: $(document).ready(function() { $(":input[name= 'radio']").on('change', function(){ alert("DO SOMETHING"); }); }); If i use some radio buttons without jQuery mobile everything works as expected. The change event is only fired if i select the unchecked radio button. If i click on an already checked radio button, nothing happens. See this jsfiddle for demonstration: https://jsfiddle.net/6cnLgonk/21/ If i now include the js and css of jQuery mobile, the change event always fires, no matter if the radio button is already checked: https://jsfiddle.net/6cnLgonk/19/ Note that the code is exactly the same, i only linked the jQuery mobile files to let the radio buttons get styles automatically. The desired behavior is to only fire the change event if the radio button is not already checked. How do i accomplish this using jQuery mobile styled radio buttons? Is the jQuery mobile js somehow overriding the change event? Do i have to set the radio buttons checked somehow manually? Thanks for your answers. A: jQuery Mobile actually replaces the radio inputs with label dom elements, and it adds click handlers to these labels that then trigger the change event on the underlying radio buttons. You can add a value attribute to each radio button: <fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center" > <input name="radio" id="radio-a" type="radio" value="a" /> <label for="radio-a">a → b</label> <input name="radio" id="radio-b" type="radio" value="b" /> <label for="radio-b">b → a</label> </fieldset> Then you can save the current selection and then check it: var CurrentSelection; $(document).ready(function() { $(":input[name= 'radio']").on('change', function(){ var clicked = $(this).val(); if (clicked != CurrentSelection){ CurrentSelection = clicked; alert("DO SOMETHING"); } }); }); Updated FIDDLE
{ "pile_set_name": "StackExchange" }
Q: How could we prove that $(p \vee q) \wedge( \neg p \vee r )\rightarrow (q \vee r)$ is a tautology? How could we prove that $(p \vee q) \wedge( \neg p \vee r )\rightarrow (q \vee r)$ is a tautology? I am more interested in the algebraic method. We can use all the rules of inferences except the Resolution. A: We have \begin{align*} (p \vee q) \wedge( \neg p \vee r )\rightarrow (q \vee r) &\equiv (p \wedge \neg p) \vee (q \wedge \neg p) \vee (q \wedge r) \vee (p \wedge r) \to q \vee r\\ &\equiv \neg \bigl((q \wedge \neg p) \vee (q \wedge r) \vee (p \wedge r)\bigr) \vee q \vee r\\ &\equiv \bigl((\neg q \vee p) \wedge (\neg q \vee \neg r) \wedge (\neg p \vee \neg r)\bigr) \vee q \vee r\\ &\equiv (\neg q \vee p \vee q \vee r) \wedge (\neg q \vee \neg r \vee q \vee r) \wedge (\neg p \vee \neg r \vee q \vee r)\\ &\equiv \top \wedge \top \wedge \top \equiv \top. \end{align*}
{ "pile_set_name": "StackExchange" }
Q: How can I define f(x) = x/x in MATLAB (Symbolic Computation) I try with these commands x = sym('x'); f(x) = sym('f(x)'); f(x) = x/x; and f(x) = sym('x/x'); , but both of them produce f(x) = 1 (yes.. for every real x including 0) The question is how I can avoid the pre-evaluation in the command "sym", or there exists another way to handle this problem. Thank you very much! update 21.05.2014: Let me describe the problem a little bit. Consider f(x) = x/x and g(x) = 1 It is obvious that domains of f and g are R-{0} and R respectively. The automatic simplification in sym/syms may lead to lose some info. A: The answer from @pabaldonedo is good. It seems that the designers of MuPad and the Symbolic Toolbox made a choice as x/x is indeterminate. If you actually want 0, Inf, -Inf, or NaN, to result in NaN rather than 1 then you can use symbolic variables in conjunction with an anonymous function: f = @(x)sym(x)./sym(x); f([-Inf -1 0 1 Inf NaN]) which returns ans = [ NaN, 1, NaN, 1, NaN, NaN] Or, if the input is already symbolic you can just use this: f = @(x)x./x; f(sym([-Inf -1 0 1 Inf NaN]))
{ "pile_set_name": "StackExchange" }
Q: How do I use AJAX/JavaScript in Drupal 6 Normally, I love drupal and generally I do, but I want to know why it makes coding in JavaScript so hard? You see, I'm porting an existing page with an AJAX user interface into drupal. I would like to keep it AJAX but at the minute I can't see how - I can't even get a simple alert to work! A quick google search made me find out 2 things. 1) I need help from someone 2) because drupal has a wired way of handling javascript due to it being a CMS. All my script does is add to inputs to a mysql database in the following format, returning an error if the entry is alreading in the database: input1=input2. So if somebody could start me off with JavaScript in drupal; maybe give me a mysql example script (using AJAX), i'd be very grateful! Thanks in advance, Andy PS Googling did reveal some example scripts but I had 2 problems with them. 1) I didn't quite get them 2) due to the fact they were for modules. I need to create a page with an AJAX interface on, not a module! A: Maybe the solution to your problem IS a module. Other than that, the only thing I can think of is: JavaScript is parsed out of your "page node" (I suppose that's what you mean by creating a "page") due to the content-type settings... One thing you can do is to create a content-type where you can insert plain-text and hence execute javascript, php, whatever... Creating this kind of content-type, of course has security risks, depending on how you use it and who has permissions to use it... Update Take a look at this link and see if it helps http://groups.drupal.org/node/41866#comment-114744
{ "pile_set_name": "StackExchange" }
Q: Is the Vulcan ability to control emotions dictated by genetics? I've seen a few Vulcans lose control of their emotions in various Star Trek media. Primarily Spock, who is in fact half-Vulcan. I was under the impression that the ability to control emotions was down to training and ritual. Is it also linked to genetics? A: From the Memory Alpha article on Vulcans, The Vulcan brain has the ability to physically modify itself: Unlike most humanoid species, traumatic memories were not only psychologically disturbing to Vulcans, but had physical consequences as well. The Vulcan brain, in reordering neural pathways, could literally lobotomize itself. (VOY: "Flashback") Vulcans learned to gain conscious control of many of these functions, allowing them to regulate their bodies to a high degree by simple will power. When injured a Vulcan could go into a trance-like state, using this ability to concentrate all of his or her energy onto repairing the injury. (TOS: "A Private Little War") Knowing that, here's some extra information from the page on Emotions: Since Vulcans have the capability to exert a level of conscious control over virtually all of their body functions, they can actually manipulate the neural pathways that regulate and receive the balances of neurochemicals involved in emotion. This enables them to inhibit their brain from forming the neural impulses that create conscious emotional mental states, thereby actually suppressing their innate emotions. The psycho-suppression system in the Vulcan brain that endows Vulcans with this ability is located in the mesiofrontal cortex. (VOY: "Meld") The Vulcan ritual, known as the kolinahr, is designed to purge all remaining emotions in a Vulcan. (Star Trek: The Motion Picture) So no, the Vulcan ability to control emotions is not dictated by their genetics, but it is supported by their genetics. This is shown in VOY 3x14, Alter Ego, when Tuvok makes some progress in teaching Harry Kim to control his emotions.
{ "pile_set_name": "StackExchange" }
Q: Module not found when using scipy I have recently properly installed numpy and scipy. The following line runs without error. import scipy I am experiencing difficulty using scipy.io.wavefile. I have been trying to use the code from the "best answer" of this post. However, when I try the first line, from scipy.io import wavfile I receive the following error and traceback, Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from scipy.io import wavfile File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\__init__.py", line 97, in <module> from .matlab import loadmat, savemat, whosmat, byteordercodes File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\__init__.py", line 13, in <module> from .mio import loadmat, savemat, whosmat File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\mio.py", line 12, in <module> from .miobase import get_matfile_version, docfiller File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\miobase.py", line 22, in <module> from scipy.misc import doccer File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\misc\__init__.py", line 68, in <module> from scipy.interpolate._pade import pade as _pade File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\interpolate\__init__.py", line 175, in <module> from .interpolate import * File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\interpolate\interpolate.py", line 21, in <module> import scipy.special as spec File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\special\__init__.py", line 640, in <module> from ._ufuncs import * File "_ufuncs.pyx", line 1, in init scipy.special._ufuncs ImportError: DLL load failed: The specified module could not be found. I also receive an error and traceback if I try the following line instead, import scipy.io.wavfile receiving a different response, Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> import scipy.io.wavfile File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\__init__.py", line 97, in <module> from .matlab import loadmat, savemat, whosmat, byteordercodes File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\__init__.py", line 13, in <module> from .mio import loadmat, savemat, whosmat File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\mio.py", line 12, in <module> from .miobase import get_matfile_version, docfiller File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\io\matlab\miobase.py", line 22, in <module> from scipy.misc import doccer File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\misc\__init__.py", line 68, in <module> from scipy.interpolate._pade import pade as _pade File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\interpolate\__init__.py", line 175, in <module> from .interpolate import * File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\interpolate\interpolate.py", line 21, in <module> import scipy.special as spec File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\special\__init__.py", line 642, in <module> from .basic import * File "C:\Users\Me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\scipy\special\basic.py", line 15, in <module> from ._ufuncs import (ellipkm1, mathieu_a, mathieu_b, iv, jv, gamma, ImportError: cannot import name 'ellipkm1' from 'scipy.special._ufuncs' (unknown location) I do not understand why the module can not be found, if scipy is properly installed and can be imported by itself. I am using python 3.7.1. Could the code from the post be depreciated? Apologies in advance for the long post. A: Both error messages are complaining about the scipy.special._ufuncs module and a quick search revealed a few other posts, like this one, that suggest making sure you have the Visual C++ Redistributable Packages installed: https://www.microsoft.com/en-us/download/details.aspx?id=48145
{ "pile_set_name": "StackExchange" }
Q: Using a DATE field as primary key of a date dimension with MySQL I want to handle a date dimension in a MySQL datawarehouse. (I m a newbie in the DW world) I made some searches with google and saw a lot of table structures (most of) date dimension where the Primary Key is a simple UNSIGNED INTEGER. Why don't use a DATE field as primary key since with MySQL it is 3 Bytes VS 4 Bytes for INTEGER? Ex: CREATE TABLE dimDate id INTEGER UNSIGNED NOT NULL PRIMARY AUTOI_NCREMENT, date DATE NOT NULL, dayOfWeek ... VS CREATE TABLE dimDate date DATE NOT NULL PRIMARY, dayOfWeek ... A: Date dimension is kind of special -- having date (2011-12-07) or date-related integer (20111207) for a primary key is actually preferred. This allows for nice partitioning (by date) of fact tables. For other type of dimensions, surrogate (integer) keys are recommended. As a template, each dimension usually has entries for unknown, not entered, error, ... which are often matched with keys 0, -1, -2, ... Due to this, it is more common to find integer-formatted date (20111207) as a primary key instead of date -- it is a bit messy to represent unknown, not entered, error, ... with date-type key. A: If you have a table with a column that is of date type and where no two rows will ever have the same date, then you can surely use this column as PRIMARY KEY. You see a lot of examples where the Primary Key is a simple UNSIGNED INTEGER because there are many cases where there is no perfect candidate for Primary Key. The AUTO_INCREMENT allows this column to be automatically filled by the database (and be unique) during inserts .
{ "pile_set_name": "StackExchange" }
Q: How to use CPUID as a serializing instruction? CPUID can be used as a serializing instruction as described here and here. What is the minimal/simplest asm syntax to use it in that way in C++? // Is that enough? // What to do with registers and memory? // Is volatile necessary? asm volatile("CPUID":::); A: Is there a reason you're not using the fence operations? If the goal is to serialize a section of code you can do something like asm __volatile__ ( " mfence \n" " lfence \n" ); Your code asm __volatile__ ( " mfence \n" " lfence \n" );
{ "pile_set_name": "StackExchange" }
Q: DXL script to save all advanced filters I have found a script which lets the user write advanced filters; this script can load the current filter from each view but not all filters which exist in the Filtering dialog box. I'd like to be able to extract all of the current advanced filters, even if only as character strings (since I have the tools to parse those strings back into a Filter class object). If someone knows of a DXL function to retrieve that information, or where the filter strings are stored, I'd appreciate the info. Note: no luck chasing this down in the Rational forums. A: Here's my hack method. Basically, there's a few setup and operational lines, anda bunch of filter definitions and combinatorics in the middle. This does save the defined filter as part of the current View. // copypaste next block into DXL edit window string viewName = "My_View" filtering off // individual items first Filter head = attribute "_ObjectType" == "Heading" Filter req = attribute "_ObjectType" == "requirement" Filter inrev = attribute "_ReqStatus" == "In Review" Filter ApprListBob = includes(attribute "_ApprovalList","BobJones") Filter ApprListMary = includes(attribute "_ApprovalList","MaryContrary") // now combine as desired. examples shown // Filter ftwo = ((head && !freq) || inrev) Filter foofilt = (head ) || (req && inrev) //) && ApprListBob set foofilt filtering on // now write addFilter( foofilt) set( foofilt) refresh current // module... save view viewName //last arg is viewname // end of copypaste block For those new to DXL syntax, && for AND || for OR ! for NOT If an attribute can take only one value, use the attribute "atname" == "value" form. If it can take multiple values (e.g. checklist), use the includes(attribute "atname", "value") form.
{ "pile_set_name": "StackExchange" }
Q: how to intetrupt a form submission in drupal I have made a custom module where I create one page. In that page I load the existing form for creating a new content and also add a password field. In my loaded form I have an email field. I want before submitting the form to check if there exists a user with the username the value found in the email field and the password offered by the password field. Here I have 3 scenarios: if the user does not exist I take the email and password and create an account then create the content if the user exists and the password is correct , I create the content if the user exists but the password is incorrect I stop the form submission My problem is I don't know how to stop the form submission ( I am refering to scenario number 3). Any suggestions are most aprerciated Here are the callback for the page function: function add_new_article_simple_page() { module_load_include('inc', 'node', 'node.pages'); $node_form = new stdClass; $node_form->type = 'announcement'; $node_form->language = LANGUAGE_NONE; $form = drupal_get_form('announcement_node_form', $node_form); return $form; } the alter function to insert the password field : function add_new_article_form_alter(&$form, &$form_state, $form_id){ if($form_id=='announcement_node_form') { $form['#after_build'][] = 'add_new_article_after_build'; $form['account_password'] = array( '#title' => 'Parola', '#type' => 'password', '#required' => TRUE, ); $form['#submit'][] = 'add_new_article_form_submit'; return $form; } } and the form submit function function add_new_article_form_submit($form, &$form_state){ $email=$form_state['values']['field_email']['und'][0]['value']; $password=$form_state['values']['account_password']; //check if the email even exists if(!db_query("SELECT COUNT(*) FROM {users} WHERE name = '".$email."';")->fetchField()) //create the new account { $edit = array( 'name' => $email, 'pass' => $password, 'mail' => $email, 'init' => $email, 'roles' => array('4' => 'standard user'), 'status' => 0, 'access' => REQUEST_TIME, ); $loc_var=user_save(drupal_anonymous_user(), $edit); $GLOBALS['new_user']=$loc_var->uid; } else { //check if username + password are valid combination if($uid = user_authenticate($email,$password)) //log in user after account creation else //this is where I want to interrupt the submission of the form form_set_error('account_password', 'Parola nu este buna pentru acest email.'); } } UPDATE My bad , I forgot to explain what happens when i test the 3rd scenario. The content is created , the page jumps to that content page and that is where the error message appears UPDATE 2 I have followed D34dman suggestion and wrote a simple validation function which should always give an error. The problem is that the content is still submited and saved. It doesn't seem to even call hook_form_validate .. Here is the function : function add_new_article_form_validate($form, &$form_state) { $email=$form_state['values']['field_email']['und'][0]['value']; $password=$form_state['values']['account_password']; form_set_error('account_password',t('The form is being validated.'.$email.' and '.$password)); } Thank you, Cristi A: It is not a good practice to prevent a form from submitting. Instead use hook_form_validate as below. /** * Implements hook_form_validate(). */ function add_new_article_form_validate(&$form, &$form_state) { // Validate email address. $mail = $form_state['values']['personal']['email_address']; $password=$form_state['values']['account_password']; if (!valid_email_address($mail)) { form_set_error('personal][email_address', t('The email address appears to be invalid.')); } else if (user_load_by_mail($mail)) { if($uid = user_authenticate($email,$password)) { $account = user_load($uid); // Check if the user would have permission to create content after login!!! // not asked by OP, but just a suggestion. if (!user_access($string, $account)) { form_set_error('personal][email_address', t('You donot have sufficient priviledge to create the content.')); } } else { form_set_error('personal][email_address', t('Email or password incorrect.')); } } } NOTE: Please don't try to create a user in validate function. Do that in form submit function. Since there could be other validators which might fail, you may not be sure how many times your form would be submitted for validation.
{ "pile_set_name": "StackExchange" }
Q: How much water does a wave transport into a sea cave? How much water is transported (volume) as a wave travels into a sea cave? The wave has a height of 1 m and a period of 12 seconds. The average water depth at the cave mouth it 5 m and the width is 15 m. How do I calculate this? This is a real-world problem and if there is any other information needed for this problem I will happily collect it. This isn't a homework problem. This is a real cave and I assumed water is transported because it does pile up in the back of the cave until the wave is reflected and exits the cave in the opposite direction. Just as on beaches where waves push water up on to the beach and gravity pulls the water back to ocean creating the nearshore current. I understand that deep water waves have an almost circular orbit but due to Stokes drift a particle will be slightly displaced in the direction the swell is moving. In this cave we can assume the wave is well with in the shallow water wave criteria and almost at the critical depth in which the wave deformation is extreme and wave energy is about to be converted into turbulent kinetic energy as the wave breaks. The orbit therefore would be linear, as the wave moves in and out. The net change would be 0 m$^3$, but how much water flows in and then flows back out of the cave? A: The time-averaged material transport by water waves is quantified by Stokes drift, which is the residual Lagrangian drift due to sub-surface orbits not being closed: $$ u_{St} = \dfrac{\omega k^2 a \cosh[2k(z+d)]}{2\sinh(kd)^2} $$ where $\omega$ is the angular frequency, $k$ is the wavenumber, $a$ is the wave amplitude, $d$ is mean water depth, and $z$ is the displacement from water surface, positive upward. Because the cave is closed, there is build-up of water in the cave which results in pressure gradient-induced Eulerian backflow which opposes the Stokes drift. This backflow is barotropic in nature and equals: $$ u_E = -\dfrac{1}{d}\int_{-d}^{0}u_{St}(z)dz $$ The transport velocity is the sum of mean Eulerian velocity and Stokes drift: $$ u_L = u_E + u_{St} $$ For the case of $T = 12\ s$, $a = 1\ m$, and $d = 5\ m$, the resulting transport looks like this: Because the Stokes drift is not uniform in the vertical but compensating Eulerian backflow is, the resulting transport is into the cave in the upper 2 m, and out of the cave below that depth. Assumptions made: Inviscid ($\mu\nabla^2\mathbf{u}=0$), irrotational ($\nabla \times \mathbf{u} = 0$), and incompressible ($\nabla\cdot \mathbf{u}=0$) flow. Small amplitude for the linear wave theory to hold. All wave energy is dissipated at the cave wall (no reflection). If there is some reflection of waves out of the cave, then the Stokes drift and the corresponding Eulerian backflow would be reduced in magnitude, but the answer for the net transport would be qualitatively the same. Shallow water dispersion relationship ($\omega^2 = gk^2d$). And here is the Python code: import numpy as np import matplotlib.pyplot as plt T = 12. # wave period [s] d = 5. # mean water depth [m] a = 1. # wave amplitude [m] g = 9.8 # gravitational acceleration [m/s] omega = 2*np.pi/T # angular frequency [rad/s] k = np.sqrt(omega**2/(g*d)) # wavenumber [rad/m] z = np.linspace(0,-d,501.) # depth array [m] dz = -np.gradient(z) # depth increment [m] # Stokes drift in arbitrary depth ust = 0.5*omega*k*a**2*np.cosh(2*k*(z+d))/np.sinh(k*d)**2 # Eulerian backflow is the vertical integral of Stokes drift ue = -np.ones(z.size)*np.sum(ust*dz)/d fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111,xlim=(-0.2,0.2),ylim=(5,0)) ax.tick_params(axis='both',which='major',labelsize=16) plt.plot(ust,-z,'r-',lw=3,label='Stokes drift') plt.plot(ue,-z,'g-',lw=3,label='Eulerian backflow') plt.plot(ust+ue,-z,'k-',lw=3,label='Lagrangian velocity') plt.plot([0,0],[5,0],'k--') plt.legend(loc='lower left',shadow=True,fancybox=True) plt.grid(True) plt.xlabel('Velocity [m/s]',fontsize=16) plt.ylabel('Depth [m]',fontsize=16) plt.savefig('transport.png',dpi=100) plt.close(fig)
{ "pile_set_name": "StackExchange" }
Q: Travis CI android emulator can't be created with avdmanager I want to build and test an Android app using an emulator in Travis CI. On my local machine I can create emulator with both android and avdmanager tools, examples: echo no | android create avd --force --name test01 --package 'system-images;android-27;google_apis_playstore;x86' echo no | avdmanager create avd --force --name test02 --package 'system-images;android-27;google_apis_playstore;x86' But on Travis there's no avdmanager in $ANDROID_HOME/tools/bin When I tried to create emulator with android tool (which isn't desired because it's deprecated) it turned out that it's different from version installed on my mac and requires different parameters My .travis.yml file (vars and build steps removed for clarity): sudo: true os: linux dist: trusty language: android android: components: - build-tools-26.0.2 - android-26 before_script: - echo no | android create avd --force --name test --package 'system-images;android-27;google_apis_playstore;x86' #- echo no | avdmanager create avd --force --name test --package 'system-images;android-27;google_apis_playstore;x86' script: - echo "DEBUG searching for avdmanager" && ls -lAp $ANDROID_HOME/tools/bin So could you please advice how should I create Android emulator in Travis CI? A: After playing around the official ways, the simplest way I found to launch one emulator on travis has at least this in travis.xml before_install: # Install SDK license so Android Gradle plugin can install deps. - mkdir "$ANDROID_HOME/licenses" || true - echo "d56f5187479451eabf01fb78af6dfcb131a6481e" >> "$ANDROID_HOME/licenses/android-sdk-license" # Install the rest of tools (e.g. avdmanager) - sdkmanager tools # Install the system image. - sdkmanager "system-images;android-24;default;armeabi-v7a" # Create and start emulator for the script. Meant to race the install task. - echo no | avdmanager create avd --force -n emulatorApi24 -k "system-images;android-24;default;armeabi-v7a" - $ANDROID_HOME/emulator/emulator -avd emulatorApi24 -no-audio -no-window & before_script: - android-wait-for-emulator # Disable animations - adb shell settings put global window_animation_scale 0 & - adb shell settings put global transition_animation_scale 0 & - adb shell settings put global animator_duration_scale 0 & - adb shell input keyevent 82 & script: ./gradlew connectedAndroidTest # Run emulator tests Now my travis build takes 20 minutes :D As a reference, a good place to check a working example is the U+2020 project.
{ "pile_set_name": "StackExchange" }
Q: ElasticSearch - Delete an Index using Java HighLevel HTTP Client Previously using ElasticSearch Transport API, I have deleted an index and its data using the below line of program. DeleteByQueryAction.INSTANCE.newRequestBuilder(client).source(indexName).get(); We are migrated from Transport Client API to HTTP Client API now. Unfortunately this is not supported in ES HighLevel HTTP client API as for as I know. Is there a way to delete an index using HTTP client? Edited: I am using ES Rest client API version 5.6.4. Deleting an index is available in the latest 6.x versions. I am looking for deleting the index in version 5.6.4. Thanks A: Then I suggest simply making a DELETE call on your index using the low-level REST API, that'd do the trick Response response = restClient.performRequest("DELETE", "/" + indexName); Note that you don't need to use the Delete by query API for deleting an index.
{ "pile_set_name": "StackExchange" }
Q: Why do some pros play in 4:3? When i see footage from some CS:GO lan event i notice that a lot of the professional players play in 4:3 on a 16:9 screen with black bars on the sides. Why do they prefer 4:3 over 16:9? Is there any advantage here? A: Some people claim it offers a better field of view or gives you an advantage. But mostly it's just down to personal preference. In some cases, players may prefer playing in 4:3 because that's how they played earlier iterations of the Counter-Strike series (such as 1.6). FOV is not bigger, though. As noted by Decency in their comment, 16:9 offers you a wider FOV, the full 90 degrees, while 4:3 gives a FOV of ~74 degrees.
{ "pile_set_name": "StackExchange" }
Q: Restricting script execution in CSS I'm writing a rails app which allows user inputted CSS rules, and I want to restrict script execution. Is disallowing 'binding' (for -moz-binding) and 'behavior' enough? It would be implemented with a simple regex called before save. Are there other methods of including scripts into css stylesheets? A: It's been proven, time and time again, that blacklisting doesn't work. Keep a whitelist of CSS you can safely allow.
{ "pile_set_name": "StackExchange" }
Q: How to remove the Add to Cart button from Catalog pages in Magento 2? How to remove the Add to Cart button from Catalog pages only? A: In Magento 2 they've hardcoded them into the catalog product list template. This can be found around line 80 of app/code/Magento/Catalog/view/frontend/templates/product/list.phtml: <?php if ($_product->isSaleable()): ?> <?php $postParams = $block->getAddToCartPostParams($_product); ?> <form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post"> <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>"> <input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>"> <?php echo $block->getBlockHtml('formkey')?> <button type="submit" title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>" class="action tocart primary"> <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span> </button> </form> A few options exist to suppress them: Create an around plugin for the block and change $_product->isSaleable() to return false for the render of the template, and swap it back afterward Replace this template in your custom theme's layout Hide with CSS Honestly hiding via CSS isn't the worst option here: .catalog-category-view .action.tocart { display: none; }
{ "pile_set_name": "StackExchange" }
Q: Remove an instance of "SQL Server 2008 R2" after reinstalling "SQL Server 2008" I have installed "SQL Server 2008 R2" with an instance name "SQLEXPRESS". Then I found out it cannot restore from my older "SQL server 2008" backup files . So I uninstalled SQL Server 2008 R2 and installed back my older SQL server 2008 with an instance name "SQLEXPRESS2008". Now I could successfully restore my backup files. The problem is that for some reason I have now two SQL server instances (SQLEXPRESS and SQLEXPRESS2008). I would like to delete SQLEXPRESS. Following suggestions on the web, I tried going to "Control Panel"/"Programs and Features", asked to Remove "SQL SERVER 2008" (2008 R2 was not in the program list). A window opened which offered me to select an instance to remove. While the Installed Instances table did show both instances, the drop-down selection box only offered me to remove SQLEXPRESS2008. Any ideas how I can remove the SQLEXPRESS instance? A: Thanks yogirk, services.msc indeed showed both the SQL servers. I stopped and deleted the extra "SQL Server 2008 R2" and then erased its directory.
{ "pile_set_name": "StackExchange" }
Q: Generating Swagger 2.0 JSON from Restlet Using Restlet 2.3.3 I've declared my Restlet Application to derive from SwaggerApplication. When I visit the default /api-docs URI, I am observing that the Swagger version of the meta data is 1.2. Subsequently, I'm not able to load this into Swagger-UI without an error. How can I obtain Swagger 2.0 JSON from Restlet's Swagger extension? The documentation seems to suggest that it can output v2.0 JSON. Thanks! A: The class SwaggerApplication only supports Swagger 1.2. If you want to use Swagger 2.0, you must attach manually the corresponding restlet to generate the content based on the class Swagger2SpecificationRestlet as described below: public Restlet createInboundRoot() { Router router = new Router(getContext()); // Configuring Swagger 2 support Swagger2SpecificationRestlet swagger2SpecificationRestlet = new Swagger2SpecificationRestlet(this); swagger2SpecificationRestlet.setBasePath( "http://myapp.com/api/v1"); swagger2SpecificationRestlet.attach(router); return router; } With such configuration, the associated resource to get the Swagger content is attached on the path /swagger.json. You can notice that you can specify your own path with the method Swagger2SpecificationRestlet#attach(Router, String). Hope it helps you, Thierry
{ "pile_set_name": "StackExchange" }
Q: É errado postar um código no SO que estávamos falando no Telegram? Um colega de um grupo de Telegram que participo, postou nesse grupo um código obfuscado que continha algum problema. Ele recebeu esse código como um desafio para descobrir onde estava o problema e estava pedindo auxílio. Achei interessante o código e resolvi analisá-lo. No final achei que ficou bastante interessante e achei que talvez fosse útil para mais alguém e resolvi pedir a ele pra postar aqui no SO. Mas ele está recebendo vários votos negativos sem qq explicação. Alguém pode dizer se isso fere de alguma forma alguma regra do SO em português ou qual é o problema ? Até onde eu sei o SO (ao menos o em inglês que eu participo mais) encoraja os usuários a responderem suas próprias perguntas como forma de documentação de soluções. Peço que se eu estiver enganado me corrijam. A pergunta é essa aqui: Problema com o código em JavaScript Grato A: De forma geral não é um problema desde que seja pontual. A pergunta não está feita de forma muito boa, ela está jogada e é quase um enunciado, falta informações, e provavelmente só quem teve uma conversa em outro lugar consegue responder, então não é que algo começado no Telegram seja o problema, é que para responder adequadamente precisa ir nesse grupo e ver o que rolou lá. Inclusive para para analisar, votar tem que fazer isso, esse é o problema. Eu não negativei a pergunta, até porque tem limite de votos por dia e gasto todos eles quase todos os dias e tenho que escolher o que negativar, mas acho que esses problemas podem ser motivos para os negativos. Me deu mais vontade de negativar, mas também não o fiz, porque o código é terrível, uma complicação quase inexplicável e que provavelmente não precisa daquilo tudo. É um dos códigos mais escabrosos que vi na vida, e já vi muitos. Parece código para fazer graça, mas indica que nem é. Esse pode ser outro motivo. E aí a resposta acaba ficando complicada porque perpetua a ideia de que aquilo seria um bom código, ainda que pelo menos esteja mais legível. Eu também não negativei porque sem entender a pergunta seria difícil entender a resposta e nem quis analisar, e sem analisar eu não quis votar. A resposta não parece boa (não estou dizendo que ela está errada). Tem potencial para esse conjunto ser mais danoso para outras pessoas do que algo bom. Até poderia ter o mesmo conteúdo básico, com muitas ressalvas, com alternativas, com a indicação que talvez seja um problema XY, aí quem sabe, se a pergunta fosse melhor formulada, desse uma resposta boa ou até excelente, mas faltou pra chegar nisso.
{ "pile_set_name": "StackExchange" }
Q: Column misalignment in grid I am having difficulty aligning my columns in my grid. I just cant figure out why columns are not aligning. First i thought its due to scroll bar but even if i remove scroll bar i cant get columns to align. This is my html code <div> <div> <table class="gridHover" style="margin-bottom: 0; table-layout: fixed; border-bottom: 1px solid #000;" border="1"> <colgroup> <col style="width: 120px;"> <col style="width: 60px;"> <col style="width: 50px;"> <col style="width: 70px;"> <col style="width: 70px;"> <col style="width: 50px;"> <col style="width: 100px;"> <col style="width: 100px;"> <col> </colgroup> <thead> <tr> <th>First Col</th> <th>Second col</th> <th>Third col</th> <th>Fourth col</th> <th>Fift col</th> <th>Sixth col</th> <th>seventh col</th> <th>eigth col</th> </tr> </thead> </table> <div style="overflow-y: scroll; overflow-x: hidden; height: 480px;"> <table class="gridHover" id="gridData" border="1" style="table-layout:fixed"> <colgroup> <col style="width: 120px;"> <col style="width: 60px;"> <col style="width: 50px;"> <col style="width: 70px;"> <col style="width: 70px;"> <col style="width: 50px;"> <col style="width: 100px;"> <col style="width: 100px;"> <col> </colgroup> <tbody class="table table-hover"> <tr> <td> <span style="word-wrap: break-word">Tom cruise</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> </tbody> </table> </div> </div> This is my Fiddle which could be easy for you guys to help me out. You can see that output is different in chrome and IE and i really dont understand why is it like that. A: My last attempt on this topic. I have used fixed width and I think it works out. If you can't define a certain % value you might need to use different fix values for different screen resolutions / devices. Fiddle at the bottom of the post. CSS Code (Changed .gridHover {width: 640px;} .overflow { overflow-y: auto; overflow-x: hidden; height: 480px;" } .gridHover { width: 640px; margin-bottom: 20px; } .gridHover th, .gridHover td { padding: 8px; line-height: 20px; text-align: left; vertical-align: top; border-top: 1px solid #dddddd; } .gridHover th { font-weight: bold; } .gridHover thead th { vertical-align: bottom; } HTML CODE (changed it to the original 8 col layout again): <div> <div> <table class="gridHover" style="margin-bottom: 0; table-layout: fixed; border-bottom: 1px solid #000;" border="1"> <colgroup> <col style="width: 120px;"> <col style="width: 60px;"> <col style="width: 50px;"> <col style="width: 70px;"> <col style="width: 70px;"> <col style="width: 50px;"> <col style="width: 100px;"> <col style="width: 100px;"> </colgroup> <thead> <tr> <th style="width: 120px;">First Col</th> <th style="width: 60px;">Second col</th> <th style="width: 50px;">Third col</th> <th style="width: 70px;">Fourth col</th> <th style="width: 70px;">Fift col</th> <th style="width: 50px;">Sixth col</th> <th style="width: 100px;">seventh col</th> <th style="width: 100px;">eigth col</th> </tr> </thead> </table> <div class="overflow"> <table class="gridHover" id="gridData" border="1" style="table-layout:fixed"> <colgroup> <col style="width: 120px;"> <col style="width: 60px;"> <col style="width: 50px;"> <col style="width: 70px;"> <col style="width: 70px;"> <col style="width: 50px;"> <col style="width: 100px;"> <col style="width: 100px;"> </colgroup> <tbody class="table table-hover"> <tr> <td> <span style="word-wrap: break-word">Tom cruise</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> <tr> <td> <span style="word-wrap: break-word">Arnold</span> </td> <td> <span style="word-wrap: break-word">AB</span> </td> <td style="text-align: center;"> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word">7</span> </td> <td> <span style="word-wrap: break-word">1</span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word"></span> </td> <td> <span style="word-wrap: break-word">CCC </span> </td> </tr> </tbody> </table> </div> </div> You can check the result in this fiddle -> http://jsfiddle.net/4KB3C/56
{ "pile_set_name": "StackExchange" }
Q: Why class not found? I'm facing a little problem in JSP development. Why class not found in this code? <%@ page import="br.webi.amazon.AwsSns" %> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% AwsSns snsClient = new AwsSns(); %> </body> </html> Server answer: HTTP Status 500 - An exception occurred processing JSP page /webi.jsp at line 14 type Exception report message An exception occurred processing JSP page /webi.jsp at line 14 description The server encountered an internal error that prevented it from fulfilling this request. exception org.apache.jasper.JasperException: An exception occurred processing JSP page /webi.jsp at line 14 11: 12: <% 13: 14: AwsSns snsClient = new AwsSns(); 15: 16: %> 17: Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) root cause javax.servlet.ServletException: java.lang.NoClassDefFoundError: com/amazonaws/AmazonWebServiceRequest org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:912) org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:841) org.apache.jsp.webi_jsp._jspService(webi_jsp.java:88) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) The package name is correct and class name is ok. What's wrong in this code? Thanks in advance. A: I solved my problem. I'm using the Amazon Web Services library and it was in incorrect folder. I have move the libs to WEB-INF/lib folder and the problem was solved.
{ "pile_set_name": "StackExchange" }
Q: here-document gives 'unexpected end of file' error I need my script to send an email from terminal. Based on what I've seen here and many other places online, I formatted it like this: /var/mail -s "$SUBJECT" "$EMAIL" << EOF Here's a line of my message! And here's another line! Last line of the message here! EOF However, when I run this I get this warning: myfile.sh: line x: warning: here-document at line y delimited by end-of-file (wanted 'EOF') myfile.sh: line x+1: syntax error: unexpected end of file ...where line x is the last written line of code in the program, and line y is the line with /var/mail in it. I've tried replacing EOF with other things (ENDOFMESSAGE, FINISH, etc.) but to no avail. Nearly everything I've found online has it done this way, and I'm really new at bash so I'm having a hard time figuring it out on my own. Could anyone offer any help? A: The EOF token must be at the beginning of the line, you can't indent it along with the block of code it goes with. If you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code. Also make sure you have no whitespace after the EOF token on the line. A: The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat: cat -A myfile.sh Once you see the output from cat -A the solution will be obvious: remove the offending characters. A: Please try to remove the preceeding spaces before EOF:- /var/mail -s "$SUBJECT" "$EMAIL" <<-EOF Using <tab> instead of <spaces> for ident AND using <<-EOF works fine. The "-" removes the <tabs>, not <spaces>, but at least this works.
{ "pile_set_name": "StackExchange" }
Q: Laravel/Octobercms eager load relation with one record I am having a Main table "devices" each device has a oneToMany relation with "devicelogs" Device Model class Device extends Model { public $hasMany = [ 'devicelogs' => 'Myhome\Myplugin\Models\Devicelog' ]; } DeviceLog Model: class Devicelog extends Model { public $belongsTo = [ 'device' => 'Myhome\Myplugin\Models\Device' ]; } I want to eager load devicelogs relations with only one record in response with latest log for that relation. I've tried doing: $d = Device::with([ 'devicelogs' => function ($query) { $query->latest('created_at')->limit(1)->get(); } ])->get(); with this i only get one device with relation devicelogs having one latest record. I want all device with one device log. I tried following: $d = Device::with([ 'devicelogs' => function ($query) { $query->first(); } ])->get(); with this i only get one device with relation devicelogs having one first record. When I do : $d = Device::with([ 'devicelogs' => function ($query) { $query->orderBy('created_at','desc'); } ])->get(); I do get all devices loaded with relations collection in desc order. But issue is i dont want entire devicelogs, I just want latest/last one for each device. So I tried doing: $d = Device::with([ 'devicelogs' => function ($query) { $query->orderBy('created_at','desc')->limit(1); } ])->get(); This again only gets latest/last devicelogs with single record for only one device. rest all devices get empty devicelogs relation. In record I have atleast 2 or more devicelog for each device. What i want is to have onely one and last/latest devicelog to return for each device when i run eager loading. Im not sure where exactly im doing wrong. A: There is a way around this which you may benefit from. In Laravel you would simply define a new relation and make it a hasOne. Since OctoberCMS still has access to use the Laravel style relation methods. You could do something like the following; in your Device.php model public function latestDeviceLog() { return $this->hasOne('Myhome\Myplugin\Models\Devicelog')->latest(); } then you can access with. Device::with('latestDeviceLog')->get();
{ "pile_set_name": "StackExchange" }
Q: Переход на следующий таб при нажатии на ссылку Здравствуйте! Имеется код: <div class="section"> <ul class="tabs"> <li class="current">Первая вкладка</li> <li>Вторая вкладка</li> </ul> <div class="box"> <p><a href="этажеСтраница.php?god='.$param.'">$param</p> </div> <div class="box"> <?php if (isset($_GET['god'])) { echo' <p>Текст 1</p>'; } else { echo ' <p>Текст 2</p>'; } ?> </div> </div><!-- .section --> И соответственно файл js: (function($) { $(function() { $('ul.tabs').each(function(i) { var storage = localStorage.getItem('tab'+i); if (storage) $(this).find('li').eq(storage).addClass('current').siblings().removeClass('current') .parents('div.section').find('div.box').hide().eq(storage).show(); }) $('ul.tabs').on('click', 'li:not(.current)', function() { $(this).addClass('current').siblings().removeClass('current') .parents('div.section').find('div.box').eq($(this).index()).fadeIn(150).siblings('div.box').hide(); var ulIndex = $('ul.tabs').index($(this).parents('ul.tabs')); localStorage.removeItem('tab'+ulIndex); localStorage.setItem('tab'+ulIndex, $(this).index()); }) }) })(jQuery) Немогу понять, как сделать так, чтобы при нажатии на param автоматически открывало вторую вкладку с Текст 1. A: Узнаю знакомый по другому заданию код, js, мне кажется, почти такой же, как там. И в том задании я его переписал в более удобочитаемый вид, поэтому решил сделать решение на основе того переделанного кода, так как использовать текущий код для добавления нужного функционала, это разрыв мозга. Не очень понял, зачем вам в ссылке на следующий таб код PHP, что именно вы хотите передавать этим кодом. Если делать без PHP, то получается такой код на JS, все манипуляции с меню сохраняются в localStorage, что позволяет при обновлении страницы оставаться на том табе, который был активен перед обновлением: $(document).ready(function() { // Загрузка из localStorage сохранённого пункта меню и открытие его var storage = localStorage.getItem('item'); if (storage && storage !== "#") { $('.nav-tabs a[href="' + storage + '"]').tab('show'); } // Функция клика на произвольный пункт меню $('ul.nav').on('click', 'li:not(.active, .dropdown, .disabled, .divider)', function() { var itemId = $(this).find('a').attr('href'); localStorage.setItem('item', itemId); }); var list = $('ul.nav').find('li'); var length = list.length - 1; // Функция клика на кнопку Next $('.next').click(function() { list.each(function(i) { if($(this).hasClass('active') && !$(this).hasClass('dropdown')) { if (i != length) { $(this).removeClass('active'); searchValidItem(i); return false; } else { $(this).removeClass('active'); searchValidItem(-1); return false; } } }); }); }); // Функция для определения следующего подходящего пункта в меню var searchValidItem = function(index) { var list = $('ul.nav').find('li'); var nextIndex = index+1; var nextItem = list.eq(nextIndex); if (!nextItem.hasClass("disabled") && !nextItem.hasClass("dropdown") && !nextItem.hasClass("divider")) { nextItem.find("a").tab('show'); localStorage.setItem('item', nextItem.find('a').attr('href')); } else { searchValidItem(nextIndex); } }; Пример сделал на основе своего кода из задания по ссылке выше. Сделал также циклическое переключение табов, думаю, не помешает. :)
{ "pile_set_name": "StackExchange" }
Q: Proving the set $S:=\cup_{m,n\in\mathbb{Z}}T_{m,n},$ in $\mathbb{R^2},$ is dense The set $S:=\cup_{m,n\in\mathbb{Z}}T_{m,n},$ in $\mathbb{R^2},$ where $T_{m,n}$ is the straight line passing through the origin and the point $(m,n)$ is dense. How to prove it? I am thinking in the way that any line passing through origin and point $(m,n)$is simply $y=\frac{n}{m}x;(m\neq0)$ and $x=0$ if $m=0$. Therefore our set S looks: $$\{(x,y)\in\mathbb{R^2}|y=\frac{n}{m}x, (m,n)\in\mathbb{Z}\setminus \{0\}\times \mathbb{Z}\}\cup \{y-\textrm{axis}\}.$$ Now, here onward suppose we take any point $(a,b)\in\mathbb{R^2}$ and any $\epsilon>0$ , then we have to show that $B_{\epsilon}(a,b)\cap S \neq \phi \quad i.e. \quad |(a,b)-(x,\frac{n}{m}x)|<\epsilon$ for some $(m,n)\in\mathbb{Z}\setminus \{0\}\times \mathbb{Z}$ or $|(a,b)-(0,y)|<\epsilon$ for some $y\in\mathbb{R}$. Here I'm convinced that we can always choose such $m,n,x$ that $\frac{n}{m}x \rightarrow b $ but how will that ensure me $|a-x|<{\epsilon}^2.$ I confused here. A: It might be helpful to look at it this way: Each of the lines $$\{re^{i\arctan (m/n)}: r\in \mathbb R, m\in \mathbb Z, n\in \mathbb N\}$$ is contained in $S.$ The set of quotients $\{m/n\}$ is dense in $\mathbb R,$ hence the set $\{\arctan (m/n)\}$ is dense in $(-\pi/2, \pi/2).$
{ "pile_set_name": "StackExchange" }
Q: Probability of the union of $3$ events? I need some clarification for why the probability of the union of three events is equal to the right side in the following: $$P(E\cup F\cup G)=P(E)+P(F)+P(G)-P(E\cap F)-P(E\cap G)-P(F\cap G)+P(E\cap F\cap G)$$ What I don't understand is, why is the last term(intersection of all) added back just once, when it was subtracted three times as it appears from a Venn Diagram? Here on page 3, this is explained but not in enough details that I can understand it: http://www.math.dartmouth.edu/archive/m19w03/public_html/Section6-2.pdf A: One of the axioms of probability is that if $A_1, A_2, \dots$ are disjoint, then $$\begin{align} \mathbb{P}\left(\bigcup_{i=1}^{\infty}A_i\right) = \sum\limits_{i=1}^{\infty}\mathbb{P}\left(A_i\right)\text{.}\tag{*} \end{align}$$ It so happens that this is also true if you have a finite number of disjoint events. If you're interested in more detail, consult a measure-theoretic probability textbook. Let's motivate the proof for the probability of the union of three events by using this axiom to prove the probability of the union of two events. Theorem. For two events $A$ and $B$, $\mathbb{P}\left(A \cup B\right) = \mathbb{P}(A) + \mathbb{P}(B) - \mathbb{P}(A \cap B)$. Proof. Write $$A \cup B = \left(A \cap B\right) \cup \left(A \cap B^{c}\right) \cup \left(A^{c} \cap B\right)\text{.}$$ Notice also that $A = \left(A \cap B^{c}\right) \cup\left(A \cap B\right)$ and $B = \left(B \cap A^{c}\right) \cup \left(A \cap B\right)$. Since we have written $A$ and $B$ as disjoint unions of sets, applying (*) in the finite case, we have that $$\begin{align} \mathbb{P}\left(A\right) &= \mathbb{P}\left(A \cap B^{c}\right) + \mathbb{P}\left(A \cap B\right) \\ \mathbb{P}\left(B\right) &= \mathbb{P}\left(B \cap A^{c}\right) + \mathbb{P}\left(A \cap B\right) \\ \end{align}$$ Similarly, since $A \cup B = \left(A \cap B\right) \cup \left(A \cap B^{c}\right) \cup \left(A^{c} \cap B\right)$ is a disjoint union of sets, $$\begin{align} \mathbb{P}\left(A \cup B\right) &= \mathbb{P}\left[ \left(A \cap B\right) \cup \left(A \cap B^{c}\right) \cup \left(A^{c} \cap B\right) \right] \\ &= \overbrace{\mathbb{P}\left(A \cap B\right) + \mathbb{P}\left(A \cap B^{c}\right)}^{\mathbb{P}(A)} + \mathbb{P}\left(A^{c} \cap B\right) \\ &= \mathbb{P}\left(A\right) + \overbrace{\mathbb{P}\left(A^{c} \cap B\right)}^{\mathbb{P}(B)-\mathbb{P}(A \cap B)} \\ &= \mathbb{P}\left(A\right) + \mathbb{P}\left(B\right) - \mathbb{P}\left(A \cap B\right)\text{. } \square \end{align}$$ Now, armed with the result that we proved in the previous theorem, we can now prove the result for the probability of the union of three events. Theorem. $\mathbb{P}\left(A \cup B \cup C\right) = \mathbb{P}\left(A\right) + \mathbb{P}\left(B\right) + \mathbb{P}\left(C\right) - \mathbb{P}\left(A \cap B\right) - \mathbb{P}\left(A \cap C\right) - \mathbb{P}\left(B \cap C\right) + \mathbb{P}\left(A \cap B \cap C\right)$ Proof. Since $A \cup B \cup C = \left(A \cup B\right) \cup C$, by the previous theorem, $$\begin{align} \mathbb{P}\left(A \cup B \cup C\right) &= \mathbb{P}((A \cup B)\cup C) \\ &= \overbrace{\mathbb{P}\left(A \cup B\right) + \mathbb{P}\left(C\right) - \mathbb{P}\left[\left(A \cup B\right) \cap C\right]}^{\text{applying the previous theorem to }\mathbb{P}((A \cup B)\cup C)} \\ &= \overbrace{\mathbb{P}\left(A\right) + \mathbb{P}\left(B\right) - \mathbb{P}\left(A \cap B\right)}^{\mathbb{P}\left(A \cup B\right) \text{ from the previous theorem}} + \mathbb{P}\left(C\right) - \mathbb{P}\left[\overbrace{\left(A \cap C\right) \cup \left(B \cap C\right)}^{(A \cup B)\cap C\text{ (distributive property of sets)}}\right] \\ &= \mathbb{P}\left(A\right) + \mathbb{P}\left(B\right) - \mathbb{P}\left(A \cap B\right) + \mathbb{P}\left(C\right) \\ &\qquad- \overbrace{\Big[\mathbb{P}\left(A \cap C\right) + \mathbb{P}\left(B \cap C\right) - \mathbb{P}\left[\left(A \cap C\right) \cap \left(B \cap C\right) \right]\Big]}^{\text{applying the previous theorem to }\mathbb{P}\left(\left(A \cap C\right) \cup \left(B \cap C\right)\right)}\text{,} \end{align}$$ and since $\left(A \cap C\right) \cap \left(B \cap C\right) = A \cap B \cap C$, the result is proven. $\square$ A: Since in this formula you add this part 3 times(in the first 3 terms) and subtract it also 3 times(in the next 3 terms), you have to add it again. A: An interesting way to find the answer is by looking at the following Venn diagram: The numbers in red indicate how many times a certain section has been included/added by using $P(A) + P(B) + P(C)$. The sections which feature more than once must be subtracted from the total to find the final answer. The blank sections are added once. No subtraction required. The dashed (||) sections represent $P(A \cap B \cap C^c)$, $P(A \cap B^c \cap C)$, and $P(A^c \cap B \cap C)$. Each appears twice so each must be subtracted once. The dotted (::) section represents $P(A \cap B \cap C)$. Appears thrice so it must subtracted twice. This yields: $$P(A \cup B \cup C ) = P(A) + P(B) + P(C) - P(A \cap B \cap C^c) - P(A \cap B^c \cap C) - P(A^c \cap B \cap C) - 2P(A \cap B \cap C).$$ Observing from the figure that $$P(A \cap B \cap C^c) = P(A \cap B) - P(A \cap B \cap C),$$ $$P(A \cap B^c \cap C) = P(A \cap C) - P(A \cap B \cap C),$$ $$P(A^c \cap B \cap C) = P(B \cap C) -P(A \cap B \cap C),$$ The final answer is given by $$P(A \cup B \cup C ) = P(A) + P(B) + P(C) - P(A \cap B) - P(A \cap C) - P(B \cap C) + P(A \cap B \cap C).$$
{ "pile_set_name": "StackExchange" }