{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\nWhen hovering over the image the sound plays correctly but when I mouseout the sound continues playing? Not too sure why that is.\n\nA: Change from onmouseout=\"Start.pause;\"> to onmouseout=\"Start.pause();\">. You missed the parenthesis in the pause function\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/74141886\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22950,"cells":{"text":{"kind":"string","value":"Q: Persisting data on disk using Hazelcast I have installed HazelCast 2.5. I want to persist my records into disk. I learned that MapStore does this job. However i'm not sure how to implement MapStore.\nCode I've written so far:\npublic class MyMaps implements MapStore {\n\n public static Map mapCustomers = Hazelcast.getMap(\"customers\");\n\n public static void main(String[] args) {\n {\n mapCustomers.put(1, \"Ram\");\n mapCustomers.put(2, \"David\");\n mapCustomers.put(3, \"Arun\");\n\n }\n }\n}\n\nHow do i put all these entries into disk.\nIs it necessary to have a back-end like MySQL or PostgreSQL to use this class?\nI believe the following function can be used:\npublic void delete(String arg0);\npublic void deleteAll(String arg0);\npublic void store(String arg0);\npublic void storeAll(String arg0);\n\nI need a sample snippet of how to implement MapStore. \nPlease provide me with sample code.\n\nA: Yes, you can use MapStore and MapLoader to persist file to local storage. Read official documentation here. \nhttps://docs.hazelcast.org/docs/latest/manual/html-single/#loading-and-storing-persistent-data\n\nA: Hazelcast has two types of distributed objects in terms of their partitioning strategies:\n\n\n*\n\n*Data structures where each partition stores a part of the instance, namely partitioned data structures.\n\n*Data structures where a single partition stores the whole instance, namely non-partitioned data structures.\nPartitioned Hazelcast data structures persistence data to local file system is not supported,need a centralized system that is accessible from all hazelcast members,like mysql or mongodb.\nYou can get code from hazelcast-code-samples.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/15132946\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"12\"\n}"}}},{"rowIdx":22951,"cells":{"text":{"kind":"string","value":"Q: In C#, Loading large file into winform richtextbox I need to load a - 10MB range text file into a Winform RichTextBox, but my current code is freezing up the UI. I tried making a background worker do the loading, but that doesnt seem to work too well either.\nHere's my several loading code which I was tried. Is there any way to improve its performance? Thanks.\n private BackgroundWorker bw1;\n private string[] lines;\n Action showMethod;\n private void button1_Click(object sender, EventArgs e)\n {\n bw1 = new BackgroundWorker();\n bw1.DoWork += new DoWorkEventHandler(bw_DoWork);\n bw1.RunWorkerCompleted += bw_RunWorkerCompleted;\n string path = @\"F:\\DXHyperlink\\Book.txt\";\n if (File.Exists(path))\n {\n string readText = File.ReadAllText(path);\n lines = readText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);\n bw1.RunWorkerAsync();\n\n }\n }\n\n private void bw_DoWork(object sender, DoWorkEventArgs e)\n {\n Invoke((ThreadStart)delegate()\n {\n for (int i = 0; i < lines.Length; i++)\n {\n richEditControl1.Text += lines[i] + \"\\n\";\n }\n });\n }\n\nI Also Try:\nAction showMethod = delegate()\n {\n for (int i = 0; i < lines.Length; i++)\n {\n richEditControl1.Text += lines[i] + \"\\n\";\n }\n };\n\n\nA: It's about how you're invoking the UI update, check the AppendText bellow.\nprivate BackgroundWorker bw1;\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n bw1 = new BackgroundWorker();\n bw1.DoWork += new DoWorkEventHandler(bw_DoWork);\n bw1.RunWorkerCompleted += bw_RunWorkerCompleted;\n bw1.RunWorkerAsync();\n}\n\nprivate void bw_DoWork(object sender, DoWorkEventArgs e)\n{\n string path = @\"F:\\DXHyperlink\\Book.txt\";\n if (File.Exists(path))\n {\n string readText = File.ReadAllText(path);\n foreach (string line in readText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))\n {\n AppendText(line);\n Thread.Sleep(500);\n }\n }\n}\n\nprivate void AppendText(string line)\n{\n if (richTextBox1.InvokeRequired)\n {\n richTextBox1.Invoke((ThreadStart)(() => AppendText(line)));\n }\n else\n {\n richTextBox1.AppendText(line + Environment.NewLine);\n }\n}\n\nIn addition to that reading the whole file text is very inefficient. I would rather read chunk by chunk and update the UI. i.e.\nprivate void bw_DoWork(object sender, DoWorkEventArgs e)\n{\n string path = @\"F:\\DXHyperlink\\Book.txt\";\n const int chunkSize = 1024;\n using (var file = File.OpenRead(path))\n {\n var buffer = new byte[chunkSize];\n while ((file.Read(buffer, 0, buffer.Length)) > 0)\n {\n string stringData = System.Text.Encoding.UTF8.GetString(buffer);\n\n AppendText(string.Join(Environment.NewLine, stringData.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)));\n }\n }\n}\n\n\nA: You don't want to concatenate strings in a loop.\n\nA System.String object is immutable. When two strings are\n concatenated, a new String object is created. Iterative string\n concatenation creates multiple strings that are un-referenced and must\n be garbage collected. For better performance, use the\n System.Text.StringBuilder class.\n\nThe following code is very inefficient:\nfor (int i = 0; i < lines.Length; i++)\n{\n richEditControl1.Text += lines[i] + \"\\n\";\n}\n\nTry instead:\nprivate void bw_DoWork(object sender, DoWorkEventArgs e)\n{\n // Cpu intensive work happens in the background thread.\n var lines = string.Join(\"\\r\\n\", lines);\n\n // The following code is invoked in the UI thread and it only assigns the result.\n // So that the UI is not blocked for long.\n Invoke((ThreadStart)delegate()\n {\n richEditControl1.Text = lines;\n });\n}\n\n\nA: why do you want to split lines and join them again?\nstrings are immutable witch means cant be changed. So every time you do Text+= \"...\" it has to create new string and put it in Text. So for 10 mb string its not ideal way and it may take Centuries To complete such task for Huge strings.\nYou can see What is the difference between a mutable and immutable string in C#?\nIf you really want to split Them and Join them again. then StringBuilder is the right option for you.\n StringBuilder strb = new StringBuilder();\n\n for (int i = 0; i < lines.Length; i++)\n {\n strb.Append(lines[i] + \"\\n\");\n }\n\n richEditControl1.Text = strb.ToString();\n\nYou can see String vs. StringBuilder\nStructure of StringBuilder is List of characters. Also StringBuilder is Muttable. means can be changed.\nInside Loop you can do any extra task with string and Add the final result to the StringBuilder. Finally after the loop Your StringBuilder is Ready. You have to convert it to string and Put it in Text.\n\nA: It took me a while to nail this one..\nTest one & two:\nFirst I created some clean data:\nstring l10 = \" 123456789\";\nstring l100 = l10 + l10 + l10 + l10 + l10 + l10 + l10 + l10 +l10 + l10;\nstring big = \"\";\nStringBuilder sb = new StringBuilder(10001000);\nfor (int i = 1; i <= 100000; i++)\n // this takes 3 seconds to load\n sb.AppendLine(i.ToString(\"Line 000,000,000 \") + l100 + \" www-stackexchange-com \"); \n // this takes 45 seconds to load !!\n //sb.AppendLine(i.ToString(\"Line 000,000,000 \") + l100 + \" www.stackexchange.com \"); \nbig = sb.ToString();\n\nConsole.WriteLine(\"\\r\\nStringLength: \" + big.Length.ToString(\"###,###,##0\") + \" \");\n\nrichTextBox1.WordWrap = false;\nrichTextBox1.Font = new System.Drawing.Font(\"Consolas\", 8f);\nrichTextBox1.AppendText(big);\nConsole.WriteLine(richTextBox1.Text.Length.ToString(\"###,###,##0\") + \" chars in RTB\");\nConsole.WriteLine(richTextBox1.Lines.Length.ToString(\"###,###,##0\") + \" lines in RTB \");\n\nDisplaying 100k lines totalling in around 14MB takes either 2-3 seconds or 45-50 secods. \nCranking the line count up to 500k lines brings up the normal text load time to around 15-20 seconds and the version that includes a (valid) link at the end of each line to several minutes.\nWhen I go to 1M lines the loading crashes VS.\nConclusions: \n\n\n*\n\n*It takes a 10+ times longer to load a text with links in it and during that time the UI is freezing.\n\n*Loading 10-15MB of textual data is no real problem as such.\nTest three:\nstring bigFile = File.ReadAllText(\"D:\\\\AllDVDFiles.txt\");\nrichTextBox1.AppendText(bigFile);\n\n(This was actually the start of my investigation..) This tries to load a 8 MB large file, containing directory and file info from a large number of data DVDs. And: It freezes, too. \nAs we have seen the file size is not the reson. Nor are there any links embedded.\nFrom the first looks of it the reason are funny characters in some of the filenames.. After saving the file to UTF8 and changing the read command to..: \nstring bigFile = File.ReadAllText(\"D:\\\\AllDVDFiles.txt\", Encoding.UTF8);\n\n..the file loads just fine in 1-2 seconds, as expected..\nFinal conclusions:\n\n\n*\n\n*You need to watch out for wrong encoding as those characters can freeze the RTB during loading. \n\n*And, when you add links you must expect for the loading to take a a lot (10-20x) longer than the pure text. I have tried to trick the RTB by preparing a Rtf string but it didn't help. Seems that analyzing and storing all those links will always take such a long time.\n\n\nSo: If you really need a link on every line, do partition the data into smaller parts and give the user an interface to scroll & search through those parts.\nOf course appending all those lines one by one will always be way too slow, but this has been mentionend in the comments and other answers already.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/31214687\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":22952,"cells":{"text":{"kind":"string","value":"Q: Custom contour plot in MATLAB I want to create a contour plot in MATLAB, as in the second example on this page:\nContourPlot[Cos[x] + Cos[y] == 1/2, {x, 0, 4 Pi}, {y, 0, 4 Pi}]\n\nAs you can see, they are plotting only the lines for which f(X, Y) == some_value. Another issue I have is that I do not really have the function f, but only a collection of points of type [x, y, z] (read from a file), and some_value of course.\nIs it possible to do such a plot in MATLAB?\n\nA: Simply use the contour function with a 2nd argument of desired values (it is a vector of 2 elements instead of a scalar, to distinguish the function call from another mode):\nsome_value = .5;\n[x y] = meshgrid(linspace(0,4*pi,30),linspace(0,4*pi,30));\nz = cos(x)+cos(y);\ncontour(x, y, z, [some_value, some_value])\n\n\nA: It helped me.\ncontourf(aX, aY, NM(:, :, k+1), 'ShowText','on', 'LevelStep', 0.4);\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/9907415\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22953,"cells":{"text":{"kind":"string","value":"Q: Stripping text from one point to another in python I have a file textfile.txt:\n[X:Y:Z]\n\nHow would I strip \"X:\" and \":Z\" so that I am left with \"Y\"?\n\nA: Using str.strip and str.split:\n>>> '[X:Y:Z]'.strip('[]')\n'X:Y:Z'\n>>> '[X:Y:Z]'.strip('[]').split(':')\n['X', 'Y', 'Z']\n>>> '[X:Y:Z]'.strip('[]').split(':')[1]\n'Y'\n\nUPDATE\nAs Blender commented, stripping the brackets off is not necessary.\n>>> '[X:Y:Z]'.split(':')\n['[X', 'Y', 'Z]']\n>>> '[X:Y:Z]'.split(':')[1]\n'Y'\n\n\nA: Y = \"[X:Y:Z]\".split(':')[1]\nThat's a quick one liner for it. \n\nA: There are dozens of ways you could achieve this for the single example you've posted, e.g.:\nfull_string = '[X:Y:Z]'\nfirst, middle, last = full_string.split(':')\nprint(middle)\nOut[5]: 'Y'\n\nTo narrow down what will or won't work, you may have to post some more examples that make clearer how your data format looks, and what pieces of information you need to extract from it.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/20895958\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22954,"cells":{"text":{"kind":"string","value":"Q: Two arrays defining 2D coordinates, as array indices I have a 2D array, call it A. I have two other 2D arrays, call them ix and iy. I would like to create an output array whose elements are the elements of A at the index pairs provided by ix and iy. I can do this with a loop as follows:\nfor i=1:nx\n for j=1:ny\n output(i,j) = A(ix(i,j),iy(i,j));\n end\nend\n\nHow can I do this without the loop? If I do output = A(ix,iy), I get the value of A over the whole range of (ix)X(iy).\n\nA: This is the one-line method which is not very efficient for large matrices\nreshape(diag(A(ix(:),iy(:))),[ny nx])\n\nA clearer and more efficient method would be to use sub2ind. I've incorporated yuk's comment for situations (like yours) when ix and iy have the same number of elements:\nnewA = A(sub2ind(size(A),ix,iy));\n\nAlso, don't confuse x and y for i and j in notation - j and x generally represent columns and i and y represent rows.\n\nA: A faster way is to use linear indexing directly without calling SUB2IND:\noutput = A( size(A,1)*(iy-1) + ix )\n\n... think of the matrix A as a 1D array (column-wise order)\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/2435018\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"7\"\n}"}}},{"rowIdx":22955,"cells":{"text":{"kind":"string","value":"Q: ClassCastException when try to use loaded class Java Version: 6\nI have build an aotuloader which loads Classes out of a JAR and instances them. SO i get an ArrayList of all Instances which match to the specific path and Abstract Class.\npackage com.geNAZt.RegionShop.Util;\n\nimport com.geNAZt.RegionShop.RegionShopPlugin;\n\nimport java.io.IOException;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\n\npublic class Loader {\n public static ArrayList loadFromJAR(RegionShopPlugin plugin, String path, Class interf) {\n ArrayList returnObjects = new ArrayList();\n\n try {\n String pathToJar = Loader.class.getProtectionDomain().getCodeSource().getLocation().getPath();\n JarFile jarFile = new JarFile(pathToJar);\n Enumeration e = jarFile.entries();\n\n URL[] urls = { new URL(\"jar:file:\" + pathToJar +\"!/\") };\n ClassLoader cl = URLClassLoader.newInstance(urls);\n\n while (e.hasMoreElements()) {\n JarEntry je = (JarEntry) e.nextElement();\n\n if(je.isDirectory() || !je.getName().endsWith(\".class\") || !je.getName().substring(0,je.getName().length()-6).replace(\"/\", \".\").contains(path +\".\")){\n continue;\n }\n\n try {\n String className = je.getName().substring(0,je.getName().length()-6);\n className = className.replace('/', '.');\n Class c = cl.loadClass(className);\n\n if(!c.getSuperclass().getName().equals(interf.getName())) {\n continue;\n }\n\n Constructor[] cons = c.getDeclaredConstructors();\n\n for(Constructor con : cons) {\n try {\n returnObjects.add((T)con.newInstance(plugin));\n break;\n } catch (InvocationTargetException e1) {\n e1.printStackTrace();\n continue;\n } catch (InstantiationException e1) {\n e1.printStackTrace();\n continue;\n } catch (IllegalAccessException e1) {\n e1.printStackTrace();\n continue;\n } catch (IllegalArgumentException e1) {\n e1.printStackTrace();\n continue;\n }\n }\n } catch(ClassNotFoundException er) {\n er.printStackTrace();\n continue;\n }\n\n }\n } catch(IOException e) {\n e.printStackTrace();\n\n return null;\n }\n\n return returnObjects;\n }\n}\n\nIt works fine an i get the right Objects with:\nprivate ArrayList loadedCommands = new ArrayList();\nloadedCommands = loadFromJAR(pl, \"com.geNAZt.RegionShop.Command.Shop\", ShopCommand.class);\n\nIf i make a log all Objects seem to be fine:\n\n12:24:40 [INFO] [RegionShop] Loaded ShopCommands: [com.geNAZt.RegionShop.Command.Shop.ShopAdd@3b39c41d, com.geNAZt.RegionShop.Command.Shop.ShopBuy@4d7a6a4b, com.geNAZt.RegionS\n hop.Command.Shop.ShopDetail@1fd889aa, com.geNAZt.RegionShop.Command.Shop.ShopEquip@4136083b, com.geNAZt.RegionShop.Command.Shop.ShopList@42567aef, com.geNAZt.RegionShop.Comman\n d.Shop.ShopName@3ba102ef]\n\nBut then i want to use them. In case to use them i wanted to cast them into the ShopCommand Class. But then i get this error: \n\n12:24:40 [SCHWERWIEGEND] Error occurred while enabling RegionShop v1.1.0b3 (Is it up to date?)\n java.lang.ClassCastException: com.geNAZt.RegionShop.Command.Shop.ShopAdd cannot be cast to com.geNAZt.RegionShop.Command.ShopCommand\n at com.geNAZt.RegionShop.Command.ShopExecutor.(ShopExecutor.java:40)\n at com.geNAZt.RegionShop.RegionShopPlugin.onEnable(RegionShopPlugin.java:80)\n at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)\n at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:457)\n at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:383)\n at org.bukkit.craftbukkit.v1_5_R3.CraftServer.loadPlugin(CraftServer.java:305)\n at org.bukkit.craftbukkit.v1_5_R3.CraftServer.enablePlugins(CraftServer.java:287)\n at net.minecraft.server.v1_5_R3.MinecraftServer.j(MinecraftServer.java:310)\n at net.minecraft.server.v1_5_R3.MinecraftServer.e(MinecraftServer.java:289)\n at net.minecraft.server.v1_5_R3.MinecraftServer.a(MinecraftServer.java:249)\n at net.minecraft.server.v1_5_R3.DedicatedServer.init(DedicatedServer.java:152)\n at net.minecraft.server.v1_5_R3.MinecraftServer.run(MinecraftServer.java:388)\n at net.minecraft.server.v1_5_R3.ThreadServerApplication.run(SourceFile:573)\n\nIs it possible to cast the Objects into the abstract class so i get the api from the Class ? Or is there another way to get the API from the Class ?\n\nA: This exception is the result of class identity crisis . You cannot cast between class loaders. As mentioned this site:\n\nOther types of confusion are also possible when using multiple class\n loaders. Figure 2 shows an example of a class identity crisis that\n results when an interface and associated implementation are each\n loaded by two separate class loaders. Even though the names and binary\n implementations of the interfaces and classes are the same, an\n instance of the class from one loader cannot be recognized as\n implementing the interface from the other loader.\n\nEDIT\nAlthough the solution is found out by the OP but I would like to give my two cents.\nThe confusion which is leading to the nonrecognition of instance of the class from other ClassLoader could easily be resolved if that class is moved into the System class loader's space. And making System Class Loader to be the parent of newly created ClassLoaders. This would cause the different ClassLoaders to share the same class. This could be achieved by URLClassLoader(URL[] urls,ClassLoader parent) in following way:\nURL[] urls = { new URL(\"jar:file:\" + pathToJar +\"!/\") };\nClassLoader cl = new URLClassLoader(urls,ClassLoader.getSystemClassLoader());\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/17132365\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22956,"cells":{"text":{"kind":"string","value":"Q: Converting floats to and displaying Binary Numbers in C So I'm just diving into C during my first few days of classes. My professor proposed a question/ more of a challenge for us so I thought I'd propose it here. \nfloat x,y,z;\nx = 0.0;\ny = 1.0;\nz = -2.5;\n\nHe wanted us to display these numbers in binary and hexadecimal without using %x etc. He also hinted to use a union:\nunion U {\nfloat y;\nunsigned z;\n};\n\nThank you for your time in advance. I'm just looking for help/ an explanation on how to develop such conversion.\n\nA: The correct way, not violating the strict aliasing rule would be to alias the float with a char array, which is allowed by the C standard.\nunion U {\n float y;\n char c[sizeof (float)];\n};\n\nThis way you will be able to access the individual float y; bytes using the c array, and convert them into binary/hex using the very simple algorithm that can be easily found around (I will leave it up to you, as it is your assignment). \n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/39393361\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-1\"\n}"}}},{"rowIdx":22957,"cells":{"text":{"kind":"string","value":"Q: Qt: How to know when a QMdiSubWindow is closed? Is there any way I can get notified when a user closes a QMdiSubWindow? I cannot find any signal in QMdiArea nor in QMdiSubWindow that suggests I can.\nI think my only chance is by subclassing QMdiSubWindow and overriding the close event, but is there any other way?\n\nA: Yes, there is another way : you can install an event-filter on the QMdiSubWindow you create :\nMdiSubWindowEventFilter * p_mdiSubWindowEventFilter;\n\n...\n\nQMdiSubWindow * subWindow = mdiArea->addSubWindow(pEmbeddedWidget);\nsubWindow->installEventFilter(p_mdiSubWindowEventFilter);\nsubWindow->setAttribute(Qt::WA_DeleteOnClose, true); // not mandatory, depends if you manage subWindows lifetime\n\nwith\nbool MdiSubWindowEventFilter::eventFilter(QObject * obj, QEvent * e)\n{\n switch (e->type())\n {\n case QEvent::Close:\n {\n QMdiSubWindow * subWindow = dynamic_cast(obj);\n Q_ASSERT (subWindow != NULL);\n\n //\n // do what you want here\n //\n\n break;\n }\n default:\n qt_noop();\n }\n return QObject::eventFilter(obj, e);\n}\n\n\nA: I had the same trouble, but in my case the task was more specific: \"How to hide a subwindow when I press the close button instead of closing\". So I solved this with the following:\nsubwindow->setAttribute(Qt::WA_DeleteOnClose, false);\n\nPerhaps it's not a relevant answer but it may be useful for someone.\n\nA: I don't think there is any other way than as you describe (overriding the close event) to do precisely what you're asking.\nThere might be other ways of achieving what you want without doing that depending on why you want to know when its closed. Other options could be the use of the destroyed signal, checking QApplication::focusWidget(), or perhaps having the parent inspect its children.\nEdit in response to comment:\nSignals and slots are disconnected automatically upon destruction of QObjects, and I would suggest looking at using QSharedPointers or QScopedPointers to handle your QObjects' lifespans instead. By applying these techniques, you shouldn't need a signal from a closed window.\n\nA: Here is what I ended coding.\n#ifndef __MYSUBWINDOW_H\n#define __MYSUBWINDOW_H\n\n#include \n#include \n#include \n\nclass MyQMdiSubWindow : public QMdiSubWindow\n{\n Q_OBJECT\n\nsignals:\n void closed( const QString );\n\nprotected:\n void closeEvent( QCloseEvent * closeEvent )\n {\n emit closed( this->objectName() );\n closeEvent->accept();\n }\n};\n#endif\n\nNote that for my problem I need a way to identify which subwindow user is closing, and objectName does the work for me.\n\nA: You can create QWidget based class like:\nclass CloseWatcher : public QWidget\n{\n Q_OBJECT\n\nprivate:\n QString m_name;\n\nsignals:\n void disposing( QString name );\n\npublic\n CloseWatcher( QWidget * p )\n : QWidget( p )\n , m_name( p->objectName() )\n {}\n\n ~CloseWatcher()\n {\n emit disposing( m_name );\n }\n};\n\nand just use it:\n// anywhere in code\nQMdiSubWindow * wnd = getSomeWnd();\nCloseWatcher * watcher = new CloseWatcher( wnd );\n\nconnect( watcher, SIGNAL( disposing( QString ) ), reveiver, SLOT( onDispose( QString ) ) );\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/8818297\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"6\"\n}"}}},{"rowIdx":22958,"cells":{"text":{"kind":"string","value":"Q: Unexpected parameter: id While writing the Python code for Twitter extraction in Jupyter notebook I am getting the error as Unexpected parameter: id. Can anyone please help me with it?\n\nA: You need to provide the relevant code and/or full traceback for anyone to know what exactly is going on, but that's likely just a warning that you're passing an id parameter to an API method that doesn't expect it.\nTweepy v4.0.0 changed many API methods to no longer accept id parameters.\n\nA: You need to use screen_name instead of id parameter.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/69565273\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-2\"\n}"}}},{"rowIdx":22959,"cells":{"text":{"kind":"string","value":"Q: Chef Configuration setting I am trying to configure for copying files through chef.However,we have a requirement to push configuration only for couple of servers. Is there any parameter or setting for that ?\nElaborated a little more .....\nOur standard deployment through Chef requires that the latest build be deployed to all servers.\nHowever, individual developers also submit experimental builds that are deployed to 1-2 servers per developer only as opposed to the entire stack.\nOur objectives are as follows:\n1. Be able to deploy experimental builds through Chef to a specified set of servers. \n2. Prevent experimental builds from being deployed to the servers that already host experimental builds – perhaps have the Chef server mark those servers as unavailable somehow(?)\n3. Be able to deploy full builds to either all servers or only those servers that are not used for experimental builds at the moment.\nI’m sure it’s a fairly common scenario and would like to know if there is an elegant/effective/dynamic way to keep Chef server informed of where each build/experiment should be deployed to.\n\nA: If you use a cloud provider, the answer is to use Packer to create an image for each build, and then deploy images as needed. If you use bare metal, then you can easily use either normal attributes or roles to setup the versions. I'd suggest attributes.\n\n\n*\n\n*Set node['myapp']['test_version'] = 'some version' on the nodes to be updated\n\n*In your recipe, check the value of that attribute. If set, then install that version, otherwise install your master version.\n\n\nTo remove a node from the experiment, you can just reset that attribute to nil on the node. The next chef run will result in that node going back to the master version.\nIf you want a way to install the master version on ALL nodes, including ones that are in experiments, you can either write a second recipe that ignores the setting, or you can add an override attribute like node['myapp']['force_master'] or such. You could then set that on the environment to override the experiments. But you'd need to remember to reset it at a later time.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/30381170\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22960,"cells":{"text":{"kind":"string","value":"Q: ModelForm and Model validation playing together I have the following Model :\nclass Advertisement(models.Model):\n\n slug = models.UUIDField(default=uuid4, blank=True, editable=False)\n\n advertiser = models.ForeignKey(Advertiser)\n position = models.SmallIntegerField(choices=POSITION_CHOICES)\n share_type = models.CharField(max_length=80)\n country = CountryField(countries=MyCountries, default='DE')\n postal_code = models.CharField(max_length=8, null=True, blank=True)\n\n date_from = models.DateField()\n date_to = models.DateField()\n\nBased on Advertiser, position, type country and postal code this stores adverisements with range date_from and date_to.\nadvertiser, position, share_type, country and postal_code\n\nare coming from the request and are fetched in \nclass CreateAdvertisment(LoginRequiredMixin, CreateView):\n\n # Some usefull stuff\n\n def dispatch(self, request, *args, **kwargs):\n\n self.advertiser = Advertiser.objects.get(user=self.request.user)\n self.share_type = self.kwargs.get('share_type', None)\n self.country = self.kwargs.get('country', None)\n self.postal_code = self.kwargs.get('postal_code', None)\n self.position = int(self.kwargs.get('position', None))\n self.position_verbose = verbose_position(self.position)\n\n ret = super(CreateAdvertisment, self).dispatch(request, *args, **kwargs)\n\n return ret\n\nWithout any validation for checking date_from, date_to. I can simply do\ndef form_valid(self, form):\n\n form.instance.advertiser = self.advertiser\n form.instance.share_type = self.share_type\n form.instance.country = self.country\n form.instance.postal_code = self.postal_code\n form.instance.position = self.position\n\n ret = super(CreateAdvertisment, self).form_valid(form)\n return ret\n\nand I am done. Unfortunatly I cannot do this as I do have to check for valid time Frames for the Advertisment to avoid Double Bookings of the same time. I do this in the model with the following :\ndef clean(self):\n ret = super(Advertisement, self).clean()\n print (\"country [%s] position [%s] share_type [%s] postal_code [%s]\" % (self.country,\n self.position, self.share_type, self.postal_code))\n if self.between_conflict():\n raise ValidationError(\"Blocks between timeframe\")\n elif self.end_conflict():\n raise ValidationError(\"End occupied\")\n elif self.during_conflict():\n raise ValidationError(\"Time Frame complete occupied\")\n elif self.start_conflict():\n raise ValidationError(\"Start Occupied\")\n return ret\n\ndef start_conflict(self):\n\n start_conflict = Advertisement.objects.filter(country=self.country,\n position=self.position,\n share_type=self.share_type,\n postal_code=self.postal_code).filter(\n date_from__range=(self.date_from, self.date_to))\n\n return start_conflict\n\nThis works well and I filter out any Conflict for the given period. Problem is that I do not have the instance variables as they are set in view.form_valid() and model.clean() is called by the form validation process.\nI do have an chicken egg problem here. I am thinking about setting the requests parameters to the form kwargs in \ndef get_form_kwargs(self, **kwargs):\n kwargs = super(CreateAdvertisment, self).get_form_kwargs()\n kwargs['advertiser'] = self.advertiser\n kwargs['position'] = self.position\n ....\n\nand then putting them into the form instance in form.init()\ndef __init__(self, *args, **kwargs):\n advertiser = kwargs.pop('advertiser')\n position = kwargs.pop('position')\n # .. and so on\n super(AdvertismentCreateForm, self).__init__(*args, **kwargs)\n\nFor some reasons I do not think this is very pythonic. Does anybody have a better idea? I will post my solution.\n\nA: I think that overriding get_form_kwargs is ok. If all the kwargs are instance attributes, then I would update the instance in the get_form_kwargs method. Then you shouldn't have to override the form's __init__, or update the instance's attributes in the form_valid method.\ndef get_form_kwargs(self, **kwargs):\n kwargs = super(CreateAdvertisment, self).get_form_kwargs()\n if kwargs['instance'] is None:\n kwargs['instance'] = Advertisement()\n kwargs['instance'].advertiser = self.advertiser\n ...\n return kwargs\n\nIn the model's clean method, you can now access self.advertiser.\n\nA: alasdairs proposal works fine I have the following now :\ndef get_form_kwargs(self, **kwargs):\n kwargs = super(CreateAdvertisment, self).get_form_kwargs()\n\n if kwargs['instance'] is None:\n kwargs['instance'] = Advertisement()\n\n kwargs['instance'].advertiser = self.advertiser\n kwargs['instance'].share_type = self.share_type\n kwargs['instance'].country = self.country\n kwargs['instance'].postal_code = self.postal_code\n kwargs['instance'].position = self.position\n\n return kwargs\n\ndef form_valid(self, form):\n\n ret = super(CreateAdvertisment, self).form_valid(form)\n return ret\n\nOf course there is no need to override form_valid anymore. I have just included here in order to display that we do not set the instance fields anymore as this is done in get_form_kwargs() already\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/43495526\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22961,"cells":{"text":{"kind":"string","value":"Q: How to check if items repeat in pandas column with multiple lists? I have this pandas df:\n Name\n0 [MARCIO, HAMILTON, FERREIRA]\n1 [NILSON, MARTINIANO, FERREIRA]\n2 [WALTER, MALIENI, JUNIOR]\n3 [CARLOS, ALBERTO, ARAUJO, NETTO]\n\nIf one of the items appear in another list I want to tag it. In this case the output should be like this:\n Name Check\n0 [MARCIO, HAMILTON, FERREIRA] True\n1 [NILSON, MARTINIANO, FERREIRA] True\n2 [WALTER, MALIENI, JUNIOR] False\n3 [CARLOS, ALBERTO, ARAUJO, NETTO] False\n\nIs there a pythonic way to do that or I will need to apply a set of for sentences? (for i in object: for k in list...). Since my file is quite large I'm afraid it will be very heavy.\n\nA: We can do explode then do transform with nunqiue find the index duplicated with same value \ns=df.Name.explode().reset_index()\nv=(s.groupby('Name')['index'].transform('nunique')>1).groupby(s['index']).any()\nOut[465]: \nindex\n0 True\n1 True\n2 False\n3 False\nName: index, dtype: bool\ndf['Check']=v\n\n\nA: Similar to Ben's answer but using duplicated instead of groupby().nunique():\ns = series.explode().reset_index()\ndf['Check'] = (s.drop_duplicates()\n .duplicated('Name', keep=False)\n .groupby(s['index']).any()\n )\n\nOutput:\n Name Check\n0 [MARCIO, HAMILTON, FERREIRA] True\n1 [NILSON, MARTINIANO, FERREIRA] True\n2 [WALTER, MALIENI, JUNIOR] False\n3 [CARLOS, ALBERTO, ARAUJO, NETTO] False\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/62051281\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":22962,"cells":{"text":{"kind":"string","value":"Q: how to reload the current page when twitter bootstrap modal's cancel button clicked? Is it possible to reload/refresh the current page when clicking on the twitter bootstarp modal popup window? \n\nA: Assuming you're using the standard Bootstrap modal markup, you could handle the modal 'hidden' event like this..\n$('#myModal').on('hidden', function () {\n document.location.reload();\n})\n\nDemo: http://www.bootply.com/62174\n\nA: For BS3 it Should be something like\n$('body').on('hidden.bs.modal', '.modal', function () {\n document.location.reload();\n});\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/17389189\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":22963,"cells":{"text":{"kind":"string","value":"Q: How to logging all queries after execution in codeigniter? I have try to insert all codeigniter queries after execute the mysql query. Unable to insert all query anyone can help me resolve this issue\n\nA: Try this for logging specific query in log file: \nCreate a logFile.log file then write your query in this file.\n$sql_query = \"insert into tablename (column1, column2) values(value1, value2)\";\nfile_put_contents('logFile.log', json_encode($sql_query , true), FILE_APPEND);\n\nHope this will help you a bit.\nOr you can follow the duplication question here: logging all queries after execution in codeigniter\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/58724879\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22964,"cells":{"text":{"kind":"string","value":"Q: No JWT created from JSON Web Tokens using Spring Security I'm using spring security and JSON Web Tokens for email verification.\nI noticed that there is no JWT created when I register a new employee.\nI use email for login, not username. I don't know if that problem with the Userdetalis interface.\nwhen I'm trying to login into Postman, I get this error.\n\nMy code :\nEmployeeController :\n@CrossOrigin(origins = {\"http://localhost:3000\"})\n@Tag(name = \"Employee\", description = \"Employee API\")\n@RestController\n@RequestMapping(EmployeeController.BASE_URL)\npublic class EmployeeController {\n public static final String BASE_URL = \"/api/v1/employees\";\n private final EmployeeService employeeService;\n private final ConfirmationTokenService confirmationTokenService;\n\n@Autowired\nAuthenticationManager authenticationManager;\n\n@Autowired\nRoleRepository roleRepository;\n\n@Autowired\nPasswordEncoder encoder;\n\n@Autowired\nJwtUtils jwtUtils;\n\npublic EmployeeController(EmployeeService employeeService, ConfirmationTokenService confirmationTokenService) {\n this.employeeService = employeeService;\n this.confirmationTokenService = confirmationTokenService;\n}\n\n@GetMapping\n@ResponseStatus(HttpStatus.OK)\npublic EmployeeListDTO getEmployeeList() {\n return employeeService.getAllEmployees();\n}\n\n\n@PostMapping(\"/signin\")\npublic ResponseEntity authenticateUser(@Valid @RequestBody EmployeeDTO loginRequest) {\n System.out.println(\"Hei\");\n\n Authentication authentication = authenticationManager.authenticate(\n new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));\n\n System.out.println(\"Hei2\");\n\n SecurityContextHolder.getContext().setAuthentication(authentication);\n String jwt = jwtUtils.generateJwtToken(authentication);\n System.out.println(jwt);\n\n UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();\n List roles = userDetails.getAuthorities().stream()\n .map(item -> item.getAuthority())\n .collect(Collectors.toList());\n\n return ResponseEntity.ok(new JwtResponse(jwt,\n userDetails.getId(),\n userDetails.getEmail(),\n roles));\n}\n\n\n@GetMapping({\"/{id}\"})\n@ResponseStatus(HttpStatus.OK)\npublic EmployeeDTO getEmployeeById(@PathVariable Long id) {\n return employeeService.getEmployeeById(id);\n}\n\n@PostMapping(\"/signup\")\n@ResponseStatus(HttpStatus.CREATED)\npublic EmployeeDTO createNewEmployee(@RequestBody EmployeeDTO employeeDTO) {\n return employeeService.createNewEmployee(employeeDTO);\n}\n\n\n@PutMapping({\"/{id}\"})\n@ResponseStatus(HttpStatus.OK)\npublic EmployeeDTO updateEmployee(@PathVariable Long id, @RequestBody EmployeeDTO employeeDTO){\n return employeeService.saveEmployeeByDTO(id, employeeDTO);\n}\n\n@DeleteMapping({\"/{id}\"})\n@ResponseStatus(HttpStatus.OK)\npublic void deleteEmployee(@PathVariable Long id){\n employeeService.deleteEmployeeDTO(id);\n}\n\n}\n> package com.tietoevry.bookorabackend.security.jwt;\n> \n> import com.tietoevry.bookorabackend.services.UserDetailsServiceImpl;\n> import org.slf4j.Logger; import org.slf4j.LoggerFactory; import\n> org.springframework.beans.factory.annotation.Autowired; import\n> org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\n> import\n> org.springframework.security.core.context.SecurityContextHolder;\n> import org.springframework.security.core.userdetails.UserDetails;\n> import\n> org.springframework.security.web.authentication.WebAuthenticationDetailsSource;\n> import org.springframework.util.StringUtils; import\n> org.springframework.web.filter.OncePerRequestFilter;\n> \n> import javax.servlet.FilterChain; import\n> javax.servlet.ServletException; import\n> javax.servlet.http.HttpServletRequest; import\n> javax.servlet.http.HttpServletResponse; import java.io.IOException;\n> \n> \n> public class AuthTokenFilter extends OncePerRequestFilter {\n\n\n@Autowired\nprivate JwtUtils jwtUtils;\n\n@Autowired\nprivate UserDetailsServiceImpl userDetailsService;\n\nprivate static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);\n\n@Override\nprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)\n\n throws ServletException, IOException {\n\n try {\n String jwt = parseJwt(request);\n\n\n if (jwt != null && jwtUtils.validateJwtToken(jwt)) {\n String username = jwtUtils.getUserNameFromJwtToken(jwt);\n\n UserDetails userDetails = userDetailsService.loadUserByUsername(username);\n UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(\n userDetails, null, userDetails.getAuthorities());\n authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));\n\n SecurityContextHolder.getContext().setAuthentication(authentication);\n } else {\n System.out.println(\"No JWT yet\");\n }\n } catch (Exception e) {\n logger.error(\"Cannot set user authentication: {}\", e);\n }\n\n filterChain.doFilter(request, response);\n}\n\nprivate String parseJwt(HttpServletRequest request) {\n String headerAuth = request.getHeader(\"Authorization\");\n\n if (StringUtils.hasText(headerAuth) && headerAuth.startsWith(\"Bearer\")) {\n return headerAuth.substring(7, headerAuth.length());\n }\n\n return null;\n} }\n\n\nimport java.util.List;\n\npublic class JwtResponse {\n private String token;\n private String type = \"Bearer\";\n private Long id;\n private String email;\n private List roles;\n\n public JwtResponse(String accessToken, Long id, String email, List roles) {\n this.token = accessToken;\n this.id = id;\n this.email = email;\n this.roles = roles;\n }\n\n public String getAccessToken() {\n return token;\n }\n\n public void setAccessToken(String accessToken) {\n this.token = accessToken;\n }\n\n public String getTokenType() {\n return type;\n }\n\n public void setTokenType(String tokenType) {\n this.type = tokenType;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n\n public List getRoles() {\n return roles;\n }\n}\n\n\n//generate Token\n@Component\npublic class JwtUtils {\n private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);\n\n @Value(\"${bezkoder.app.jwtSecret}\")\n private String jwtSecret;\n\n @Value(\"${bezkoder.app.jwtExpirationMs}\")\n private int jwtExpirationMs;\n\n public String generateJwtToken(Authentication authentication) {\n\n UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();\n\n return Jwts.builder()\n .setSubject((userPrincipal.getEmail()))\n .setIssuedAt(new Date())\n .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))\n .signWith(SignatureAlgorithm.HS512, jwtSecret)\n .compact();\n }\n\n public String getUserNameFromJwtToken(String token) {\n return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();\n }\n\n public boolean validateJwtToken(String authToken) {\n try {\n Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);\n return true;\n } catch (SignatureException e) {\n logger.error(\"Invalid JWT signature: {}\", e.getMessage());\n } catch (MalformedJwtException e) {\n logger.error(\"Invalid JWT token: {}\", e.getMessage());\n } catch (ExpiredJwtException e) {\n logger.error(\"JWT token is expired: {}\", e.getMessage());\n } catch (UnsupportedJwtException e) {\n logger.error(\"JWT token is unsupported: {}\", e.getMessage());\n } catch (IllegalArgumentException e) {\n logger.error(\"JWT claims string is empty: {}\", e.getMessage());\n }\n\n return false;\n }\n}\n\n\n\n@Configuration\n@EnableWebSecurity\n@EnableGlobalMethodSecurity(\n // securedEnabled = true,\n // jsr250Enabled = true,\n prePostEnabled = true)\npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {\n @Autowired\n UserDetailsServiceImpl userDetailsService;\n\n @Autowired\n private AuthEntryPointJwt unauthorizedHandler;\n\n @Bean\n public AuthTokenFilter authenticationJwtTokenFilter() {\n return new AuthTokenFilter();\n }\n\n @Override\n public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {\n authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());\n }\n\n @Bean\n @Override\n public AuthenticationManager authenticationManagerBean() throws Exception {\n return super.authenticationManagerBean();\n }\n\n @Bean\n public PasswordEncoder passwordEncoder() {\n return new BCryptPasswordEncoder();\n }\n\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n\n\n\n http.authorizeRequests()\n .antMatchers(\"/\").permitAll()\n .antMatchers(\"/h2-console/**\").permitAll();\n\n http.csrf().disable();\n http.headers().frameOptions().disable();\n http.cors().and().csrf().disable()\n .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()\n .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()\n .authorizeRequests().antMatchers(\"/api/v1/employees/**\").permitAll()\n .antMatchers(\"/api/test/**\").permitAll()\n .anyRequest().authenticated();\n\n http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);\n }\n\n\nand in intellj I get :\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/64295612\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22965,"cells":{"text":{"kind":"string","value":"Q: Loading array file with other numbering format I am trying to load a file in which the numbers are in the following form:\n 0.0000000D+00 -0.1145210D-16 0.1262408D-16\n 0.1000000D+00 -0.4697286D-06 0.1055963D-06\n 0.2000000D+00 -0.1877806D-05 0.4220493D-06\n 0.3000000D+00 -0.4220824D-05 0.9482985D-06\n\nI am trying the numpy.loadtext function, but apparently it's not in its recognized numbering format as I'm getting the following error:\nValueError: could not convert string to float: b'0.0000000D+00'\nAny idea?\nThanks\n\nA: You can use a converter with numpy.loadtxt that converts the value to a parsable float. In this case we trivially replace Dwith E;\nimport numpy as np\n\nnumconv = lambda x : str.replace(x.decode('utf-8'), 'D', 'E')\nnp.loadtxt('test.txt', converters={0:numconv, 1:numconv, 2:numconv}, dtype='double')\n\n# array([[ 0.00000000e+00, -1.14521000e-17, 1.26240800e-17],\n# [ 1.00000000e-01, -4.69728600e-07, 1.05596300e-07],\n# [ 2.00000000e-01, -1.87780600e-06, 4.22049300e-07],\n# [ 3.00000000e-01, -4.22082400e-06, 9.48298500e-07]])\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/36134183\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22966,"cells":{"text":{"kind":"string","value":"Q: If - Else on Pirates Un-resolved Could you someone show me how to create an if - else statements with two sets of R.drawable.images pirates?\nI've tried, but I got an error code saying pirates is un-resolved.\nBitmap icon = BitmapFactory.decodeResource(getResources(),pirates[i]);\nThis is what I have in the preferences:\n\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\nandroid:key=\"wallpaper_settings\"\nandroid:title=\"@string/wallpaper_settings\" > \n\n \n\n\n \n\n\nMain Activity:\n public class main_activity extends WallpaperService {\n\n public static final String SHARED_PREFS_NAME=\"settings_menu\";\n\n\n @Override\n public void onCreate() {\n super.onCreate();\n}\n\n @Override\npublic void onDestroy() {\n super.onDestroy();\n}\n\n @Override\npublic Engine onCreateEngine() {\n return new wallpaperEngine(); \n}\n\nclass wallpaperEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener{\n\n\n private final Handler mhandler = new Handler();\n\n\n //defines variables\n\n\n private final Runnable drawrunnable = new Runnable() \n {\n public void run() {\n drawFrame();\n }\n };\n private int i = 0;\n private boolean mVisible;\n private SharedPreferences mPrefs;\n private boolean mcheckbox = false;\n public int mSpeed = 10;\n\n int[] pirates = {\n R.drawable.image_1,\n R.drawable.image_2,\n R.drawable.image_3,\n R.drawable.image_4\n\n };\n\n //For Nature Pictures\n int[] pirates = {\n R.drawable.image_a1,\n R.drawable.image_a2,\n R.drawable.image_a3,\n R.drawable.image_a4\n\n };\n\n .......\n ......\n\n Bitmap icon = BitmapFactory.decodeResource(getResources(),pirates[i]);\n\n i++;\n\n if (i == 14) {\n i = 0;\n\nThank you very much\n\nA: Seems like you are trying to create two arrays of int, holding different set of images. But you are using the same variable name pirates. I would suggest you define two different variables int[] pirates and int[] piratesNatural and then switch between those two arrays when you need one and the other.\nBitmap icon; \nif(natural) \n icon = BitmapFactory.decodeResource(getResources(),piratesNatural[i]); \nelse\n icon = BitmapFactory.decodeResource(getResources(),pirates[i]);\n\n\nA: you doing animation?\nint frame=0;\nint frametime=24;\n\nBitmap icon1 BitmapFactory.decodeResource(getResources(), R.drawable.image_1,);\nBitmap icon2 BitmapFactory.decodeResource(getResources(), R.drawable.image_2,);\nBitmap icon3 BitmapFactory.decodeResource(getResources(), R.drawable.image_3,);\nBitmap icon4 BitmapFactory.decodeResource(getResources(), R.drawable.image_4,);\n\n\n\n//in update\nframetime--;\nif(frametime<=0){\nframe++;\nframetime=24;\n}\nif(frame>3){\nframe=0;\n}\n\n\n\n//in onDraw\n\nswitch(frame){\n\ncase 0:\ncanvas.drawBitmap(icon1,x,y,null);\nbreak;\ncase 1:\ncanvas.drawBitmap(icon2,x,y,null);\nbreak;\ncase 2:\ncanvas.drawBitmap(icon3,x,y,null);\nbreak;\ncase 3:\ncanvas.drawBitmap(icon4,x,y,null);\nbreak;\ndefault:\ncanvas.drawBitmap(icon1,x,y,null);\nbreak;}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/22643685\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22967,"cells":{"text":{"kind":"string","value":"Q: Method Swizzling - How to assure methods are swizzled before they are called I'm method swizzling a third party applications creation of NSMenuItems with SIMBL, but 50/50 of the time the menu-items are created before my method swizzling is initialized. \nWhat is a clean way to make sure my swizzling always comes first? I guess I could swizzle applicationDidFinishLaunching: and continue my swizzling there. But I'm afraid I'm going to run in to the same error there, where applicationDidFinishLaunching will be called before my actual swizzle is in place.\nJohn\n\nA: You'd want the swizzle to happen as soon as the libraries are loaded. You can do that via +initialize, +load, or a constructor function.\n@bbum's answer to this question has a bit more information, along with one of his blog posts on the caveats of using these special class methods.\n(And I'm purposely not questioning the wisdom of what you're doing ;) )\n\nA: You can use constructor functions like this:\n__attribute__((constructor)) static void do_the_swizzles()\n{\n // Do all your swizzling here.\n}\n\nFrom GCC documentation:\n\nThe constructor attribute causes the function to be called\n automatically before execution enters main().\n\nNote: Although this is originally from GCC, it also works in LLVM.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/4675546\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22968,"cells":{"text":{"kind":"string","value":"Q: Multiple Timers counting down are not working properly | SwiftUI I have an auction app running. I need several timers counting down in the UI, these timers have different end Dates, and the end seconds can be updated when SignalR receives a new value.\nI have implemented running timers in my current solution, but sometimes and suddenly, they start having delays between counting down a second.\nThe timers are inside these components called LotCard within the ForEach\nForEach($lotService.getLotListDto) { $item in\n LotCard(lotCardViewModel: $item.lotCardViewModel,\n lotDto: item,\n fnStartLotConnection: { value in lotService.initSingleLotCard(uID: value)})\n\n}\n\nThis is the necessary code within these components:\n//MARK: Timer\n@State var timeRemaining = 9999\nlet timerLotCard = Timer.publish(every: 1, on: .main, in: .common).autoconnect()\n\nHStack(spacing: 3){\n Image(systemName: \"stopwatch\")\n if(lotCardViewModel.showTimer){\n Text(\"\\(timeRemaining.toTimeString())\")\n .font(.subheadline)\n .onReceive(timerLotCard){ _ in\n if self.timeRemaining > 0 {\n self.timeRemaining -= 1\n \n if(self.timeRemaining <= 0){\n self.timerLotCard.upstream.connect().cancel()\n }\n }else{\n self.timerLotCard.upstream.connect().cancel()\n }\n }\n }\n}\n\nI guess it's a problem with threads and using many timers simultaneously with the same Instance but I am not an experienced developer using SwiftUI/Swift.\nThis is how my interface looks like:\n\nThanks for your help.\n\nA: I came up with this approach thanks to the comments in my question.\nI hope it works and suits your problems.\nFirst, I created a Published Timer, meaning every component will run the same Timer.\nimport Foundation\nimport Combine\n\nclass UIService : ObservableObject {\n \n static let shared = UIService()\n\n //MARK: Timer to be used for any interested party\n @Published var generalTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()\n\n}\n\nFinally, I am using that Timer wherever I want to use it. In this case, I use it in every LotCard component.\nstruct LotCard: View {\n\n//MARK: Observable Class\n@EnvironmentObject var UISettings: UIService\n\n//MARK: Time for the counting down\n@State var timeRemaining = 9999\n\nvar body: some View {\n HStack{\n \n Text(timeRemaining.toTimeString())\n .onReceive(UISettings.generalTimer){ _ in\n if self.timeRemaining > 0 {\n self.timeRemaining -= 1\n }\n }\n }\n}\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/73134381\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22969,"cells":{"text":{"kind":"string","value":"Q: Override a method and make it behave static I have an existing framework, which I can't change, it reads 2 properties\n\n\n*\n\n*ClassA=somepackage.AnImplementationOfInterfaceA\n\n*ClassB=somepackage.AnImplementationOfInterfaceB\nWhich calls public methodA on a new ClassA(), public methodB on a new ClassB() in that order\nI want to make a class C which implements interfaces A, B and provides hooks methodC1, methodC2 for class D to override (methodA & methodB contain a lot of boilerplate and complex to implement - methodC1 & methodC2 would encapsulate the business logic) . Then my properties would be\n\n\n*\n\n*ClassA=somepackage.classD \n\n*ClassB=somepackage.classD\nThe problem is that the person who implements class D might be tempted to write something like:\nclass D extends class C\n{\n private int foo; //must be non-static due to multi-threaded new Class D() calls going on\n int methodC1() {this.foo = read number from network}\n methodC2(int x) {y = this.foo;} //methodC2 is always called after methodC1\n\n //methodA, methodB implementation inherited from C\n}\n\nBut this wouldn't work as expected since the framework would actually create a new object of class D each time before invoking methodA, methodB and thus can't rely on using the \"this\" reference.\nDefining methodC1, methodC2 as static wouldn't work either because then the call to methodC1 is tied to the implementation in C, not the overriden one in D. \nWhen really what ought to be written is:\nclass D extends class C\n{\n int methodC1() {return number from network;}\n methodC2(int x) {y = x} //here y is using the return value of methodC1\n\n //methodA, methodB implementation inherited from C\n}\n\nI would also like only methodC1, methodC2 to be overridable i.e. programmers working on D can't mess with methodA\nThe ideal design would have\n\n\n*\n\n*the properties refer to one class only\n\n*methodC1, methodC2 to be in that class\n\n\nSummary of challenges\n\n\n*\n\n*no this in methodC1, methodC2\n\n*can't make methodC1, methodC2 static\n\n*properies takes only a instantiable class\n\n\nHow do I design this framework? Is this even solvable? You can change the signature of methodC1, methodC2.\n\nA: Composition! Establish an interface that you are okay with people extending.\nThis class would contain the logic for MethodD1 and D2, and for everything else just a simple call to the other methods in your currently existing class. People won't be able to modify the calls to change the underlying logic.\n\nA: The static methods can not be overridden!\nIf a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding has important implications.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/10492372\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22970,"cells":{"text":{"kind":"string","value":"Q: Set counting javascript program to two decimal places Please see this code:\n\n\nWhat it does is take a piece of html like this: \n
10
\n\nAnd it will count by 10 every second. How do I make the following code work:\n
10.02
\n\nBasically, I want to have this program count by up to two decimal places. \n\nA: Use parseFloat instead of parseInt. And toFixed(2) for limiting two decimal points.\nsetInterval(function() {\n var counters = document.getElementsByClassName(\"count\");\n\n for (var i = 0; i < counters.length; i++) {\n counters[i].innerHTML = parseFloat(counters[i].innerHTML).toFixed(2) + parseFloat(counters[i].dataset.increment).toFixed(2);\n }\n}, 1000);\n\n\nA: JSFIDDLE\n You need to use parseFloat to covert string to float.\n and toFixed on float to truncate extra decimal. toFixed return string you need to use parseFloat again so that it became float addition not string concatenation.\n\n\nvar counters = document.getElementsByClassName(\"count\");\r\n \r\n setInterval(function () {\r\n for(var i = 0 ; i < counters.length ; i++) {\r\n \r\n counters[i].innerHTML = (parseFloat(parseFloat(counters[i].innerHTML).toFixed(2)) + parseFloat(parseFloat(counters[i].dataset.increment).toFixed(2))).toFixed(2);\r\n }\r\n }, 1000);\n
10
\r\n\r\n
10.02
\n\n\n\nA: Try wrapping addition within String() , .innerHTML , .dataset within Number() , Number() within expression () chained to .toFixed(2) ; set counters[i].innerHTML to result derived within String((Number(/* innerHTML */) + Number(/* dataset *)).toFixed(2))\n\n\nvar interval = setInterval(function() {\r\n var counters = document.getElementsByClassName(\"count\");\r\n\r\n for (var i = 0; i < counters.length; i++) {\r\n counters[i].innerHTML = String((Number(counters[i].innerHTML) \r\n + Number(counters[i].dataset.increment)).toFixed(2));\r\n\r\n }\r\n}, 1000);\n
10.02
\n\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/31117995\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":22971,"cells":{"text":{"kind":"string","value":"Q: How to get the fingers count in the InkCanvas? I am trying to zoom the InkCanvas when the finger counts greater than 1, but I can't get the finger count in the InkCanvas.Anyone Please help me how to get the finger count in InkCanvas.\n\nA: I don't have touch screen to test but maybe this will work:\n int count;\n\n private void InkCanvas_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)\n {\n count++;\n }\n\n private void InkCanvas_PointerExited(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)\n {\n count--;\n }\n\nIf it doesn't help. Try to use PinterPressed and PointerReleased. You may grab point Id from event args and handle them.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/46842244\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22972,"cells":{"text":{"kind":"string","value":"Q: React Native init Project which ruby\noutputs -> /Users/User/.rbenv/shims/ruby\nruby -v\noutputs -> ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21]\nwhich bundle\noutputs -> /Users/User/.rbenv/shims/bundle\nbundle -v\noutputs -> Bundler version 2.1.4\nbut the problem is that npx react-native init MyProject\noutputs -> ✖ Installing Bundler\nerror Bundler::RubyVersionMismatch: Your Ruby version is 2.6.10, but your Gemfile specified 2.7.5\n\nA: What's likely happening is that npx react-native init MyProject is sub-shelling into Bash where you do not have rbenv configured. When it tries to run ruby from Bash it looks in $PATH and finds the default macOS version of Ruby -- 2.6.10 -- and errors out.\nThis is discussed thoroughly in the react-native repo where there are many solutions, but what it boils down to is react-native init is not finding the right version of Ruby, for whatever reason. You can bypass that by completing the failing part of the init process yourself with:\ncd MyProject\nbundle install\ncd ios && bundle exec pod install\n\nThe longer version of the solution is to configure rbenv for Bash as well, but this isn't necessary as you can likely use just the workaround above:\necho 'eval \"$(~/.rbenv/bin/rbenv init - bash)\"' >> ~/.bash_profile\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/74942404\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22973,"cells":{"text":{"kind":"string","value":"Q: Assign to specific characters within CSS style I am new to CSS and web development in general. Hopefully there is a way to accomplish what I am trying to do. What I am trying to do is simple to explain, but I need to give some background info first, sorry for the length of the post.\nI have created a webpage that is in the Tibetan language. Tibetan does not have spaces between words, it only has a character called a \"tsheg\" (་ - U+0F0B) that is used to separate every syllable. It also has a mark called a \"shey\" (། - U+0F0D) that comes at the end of phrases and clauses and sentences. Although sometimes it is doubled, after a shey is generally a space before the next line of text. When typing in Tibetan this space is represented not as a normal space (U+0020) but instead U+00A0, however when it comes to browsers and HTML/coding in general these two seem to behave the same. \nIn any Tibetan writing, the ideal aesthetic is for full justification. Traditionally there would be slight spaces placed between the tsheg marks and the shey marks to achieve a perfectly flush left and right alignment. (The exception would be the last line of a text, or a paragraph in contemporary formatting, does not need to be justified). It is acceptable for lines to break mid-word or mid-sentence, but never mid syllable. So the last character on any line is going to be either a tsheg or a shey. It is also not acceptable to start a line with a shey. In the last few years this has been easy to achieve for desktop publishing using MS Word, using \"Thai Justification.\" However that option is not available even in other Office products, never mind outside of the Office environment. Other work-arounds have been to add invisible width characters after every tsheg and shey, allowing for wrapping at any point.\nNow comes the question and difficulty. I am using distributed justification, and that seems to be the best option. It does not break syllables up, which is important. But it only wants to break at those spaces after shey marks, and it breaks elsewhere when there is a long string of text without a space, but if there is a space then it breaks there, sometimes stretch one or two syllables across an entire line, which is obviously not ideal. \nNow, when coding the HTML of the text I can use the same work-around that is used for desktop publishing pre \"Thai justification,\" I can add a after every single tsheg, and this will not be visible to the end user and should allow cleaner breaking. However, there are two problems with this. But inserting that many characters I am essentially doubling, or close to doubling, my character count, which can make the page take twice as long to load, even if half of those characters are invisible. However, more important is that it disrupts search functionality. Although you may see the word that has the syllables \"AB\" for instance, if you tried searching for AB you wouldn't find it, because the HTML sees \"AB\". And being able to search is kind of critical. Enough so that an ugly formatting is preferable to losing the ability to search and to be indexed properly. Obviously, since I need the site to be responsive and I do not know what size screens will be used I cannot have forced line breaks, either, another trick used when publishing.\nSo, finally, my question. Is there a way I can define a style or function or some sort of element that automatically associates a certain character--in my case the tsheg character--as having a command after it without actually needing to input that command into my HTML? So when the text is justified it treats every tsheg as a ? I have a class .Tibetan in my stylesheet that defines the font and the justification and so forth, is there some way I can add some code there that achieves what I am looking for?\nThe one other thing I tried was replacing all of the spaces with &nbsp; which gave a beautiful justified appearance but it also caused the browser to disregard the tsheg marks entirely and it allowed for the cutting in half of syllables.\nIf you want to see an example of what I am talking about you can visit this page of my site: http://publishing.simplebuddhistmonk.net/index.php/downloads/critical-editions/ and next to the word \"English\" click the Tibetan characters and that will bring up a paragraph of prose, or you can look here: http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/essence-of-dispelling-errors-tib/ (though the formatting on that latter page is less egregious than the former, at least on my screen).\nEDIT It looks like the solution this person used might be able to be adapted for my use: Dynamically add tag before punctuation however I do not actually understand what I would need to add, and where, to make that work for me. Anyone think that might apply to this scenario? And if so, what code would I add where?\nNEW EDIT So, I think the problem might be with the search function that comes from my WordPRess theme. I used my workaround as mentioned above, adding the tag after every tsheg, on this page: http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/essence-of-dispelling-errors-tib/ and as you can see, it displays perfectly. But if you search for any phrase from that page using the search function that is up in my header, it will not find it. If you do a Ctrl+F and search on the page, though it will find it. Even if you copy the text from the page and paste it into the search box it still does not find it. Copy the text into a word editor doesn't reveal any hidden or invisible characters. However, if you search for a term from this page http://publishing.simplebuddhistmonk.net/index.php/downloads/tibetan/beautiful-garland-ten-innermost-jewels-tib/ which I have not added the tags to, you will see that it finds it no problem.\nSo, that leads me to believe the error is in the search function. Any experience with this? Because search is important but I can quite possibly find alternative earch widgets to replace the one that comes with the theme. What is most important though is if you search for a line of text on Google it needs to be found. My site has not been indexed fully by any search engine so I cannot yet confirm if this does or does not affect them.\nSo.... At this point I wil take any advice I can get. Any advice regarding the original question (is there a way to tell the style guide \"if your are displaying X then treat it like X\" ) or any idea about this issue with the search functionality, and how the tag may or may not affect search, both from within the site and also from search engines.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/48222501\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22974,"cells":{"text":{"kind":"string","value":"Q: Trying to add an alert to detection model \"ssd_mobilenet_v2\", throws an error Using \"ssd_mobilenet_v2_fpn_keras\" i am trying to add an alert system\nThe detection model is loaded in to the below function\n def detect_fn(image):\n image, shapes = detection_model.preprocess(image)\n prediction_dict = detection_model.predict(image, shapes)\n detections = detection_model.postprocess(prediction_dict, shapes)\n return detections\n\nThe image is converted to a tensor\ninput_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)\n\nThe the tensor is fead to the detection model\ndetections = detect_fn(input_tensor)\nThe output of the detection model is a dictionary, with the following keys:\ndict_keys(['detection_boxes', 'detection_scores', 'detection_classes', 'raw_detection_boxes', 'raw_detection_scores', 'detection_multiclass_scores', 'detection_anchor_indices', 'num_detections'])\n\ndetections[detection_classes], gives the following output ie 0 is ClassA, 1 is ClassB\n[0 1 1 0 0 1 0 0 1 0 1 1 0 0 1 0 1 1 0 1 0 1 1 0 0 1 0 0 1 0 1 0 0 1 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 1 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 1 0 1]\n\ndetections['detection_scores'] gives the score for each box detected (a few shown below)\n[0.988446 0.7998712 0.1579772 0.13801616 0.13227147 0.12731305 0.09515342 0.09203091 0.09191579 0.08860824 0.08313078 0.07684237\n\nI am trying to Print(\"Attention needed\"), if detection classB ie 1 is observed\nfor key in detections['detection_classes']:\nif key==1:\n print('Alert')\n\nWhen i try to do that i get an error\n`ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\n\nHow do make it work?\nI want the code to print \"Attention needed\" is Class =1 or A and detection_scores >= 14\nCode Explained, a bit further\n\nlinks for the complete code are below :\n\n*\n\n*Tutorial on YouTube\n\n*GitHub sources repository\n\nA: As mentioned in the error message, you should use .any(). like:\nif (key == 1).any():\n print('Alert')\n\nAs key == 1 will be an array with [False, True, True, False, ...]\nYou might also want to detect ones that exceeds certain score, say 0.7:\nfor key, score in zip(\n detections['detection_classes'],\n detections['detection_scores']):\n if score > 0.7 and key == 1:\n print('Alert')\n break\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/70208626\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22975,"cells":{"text":{"kind":"string","value":"Q: Android - How to open an associated file to an application from main activity \nPossible Duplicate:\nAndroid intent filter: associate app with file extension \n\nI've associated an XML file with extensions .x to my application. I would like to click on .x file, my associated application should start, and I would like to open the file, passed in some way, from inside onCreate() of activity. There is a way to do this ?\nThanks in advance.\n\nA: Add this intent filter in your manifest to your activity\n\n \n \n \n \n\n\non your onCreate files are passed on as:\nUri uri = this.getIntent().getData();\nif(uri!=null){\n Log.v(getClass().getSimpleName(), \"importing uri:\"+uri.toString());\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/12411660\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22976,"cells":{"text":{"kind":"string","value":"Q: Crop raster plot in r I am trying to read a hospital floor plan map (a higher resolution version than the one here in .PNG form) http://www.alfredicu.org.au/assets/Miscellaneous-Downloads/newicufloorplan.pdf \nSo that I can then place points onto it representing OHS incidents. My problem is that I need to be able to cut down the map so that I am only looking at a subset of the area so the x-axis (which represents mm of the A2 page) is 10:300 and the y axis is 10:380.\nI have read in the array and plot but do not know how to subset this plot. If you can advise how to change the dimensions of the plot so that I can 'zoom in' on the relevant part of the map that would be greatly appreciated. \n#Read PNG into raster array\nr <- readPNG(\"ICU-map.png\")\n\n#Set up the plot area as A2 with mm as the dimensions\nicu <-plot(0, type='n', main=\"ICU\", xlab=\"x\", ylab=\"y\", xlim=c(0, 594), ylim=c(0, 420))\n\n#Get the plot information so the image will fill the plot box, and draw it\nlim <- par()\nrasterImage(r, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])\ngrid()\nlines(c(1, 1.2, 1.4, 1.6, 1.8, 2.0), c(1, 1.3, 1.7, 1.6, 1.7, 1.0), type=\"b\", lwd=5, col=\"white\")\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/38177141\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22977,"cells":{"text":{"kind":"string","value":"Q: Broken Adobe Air Installers, Do I Need a Certificate This is a multi-part question, but all to resolve the same issue.\nI'm trying to publish a project I've been working on but get intermittent problems with .air files that are generated. \nI always get the following warning when publishing my project: \n\"There was an error connecting to the timestamp server. You may not have a connection to the network, or the server itself may have a problem. \nIf you choose to disable timestamping, the AIR application will fail to install when the digital signature expires.\"\nSo I have had no choice but to disable timestamping.\nI do have a working internet connection, but I'm working from my company network, could this be an issue, and if so, is there a work around (Opening a specific port or something)? Also, how long do the above-mentioned digital signatures have before expiring?\nAlso, I am creating my own certificate. Do I need to purchase some kind of certificate/license to install my application on another computer? I've done some research, but the information is hard to find, and what I do find is kind of cryptic at best. Currently, I only need to deploy to machines within the company.\nSometimes the installer works fine and without issue (on the computer that generated it at least), other times I get \"The application could not be installed because the installer file is damaged. Try obtaining a new installer file from the application author.\" as an error message. Other times I get an error stating that certificates or signatures or something do not match (Sorry, I couldn't replicate the error so am paraphrasing).I have yet to get an install to work on a separate machine.\nI've tried using Air 2.5 and 2.6.\nAlso, as an extra while I'm here: Can I embed AIR applications to be run INSIDE a browser like a traditional Flash project?\n\nA: About certificate, you can use a self signed certificate, the only difference is that the users will see a big warning when installing that the publisher is unknown.\nAbout timestamping, I only know that the adt tool that packages the app is attempting to connect to a timestamping server, I am not sure what protocol is used, you will need to check this and unblock this.\nIf the installer is not timestamped then the issue is that after the certificate expires you can continue using this installer and need to do a new one with a certificate that is not expired.\nAs an example, if I use a certificate that expires tomorrow today and the installer is not timestamped then it will not work after tomorrow but if it was timestamped then it will continue to work after the certificate expired because it was created before the expiration\nI seen the installer is damaged erors a few times on our customers machine, usually on Windows, sometimes uninstalling and reinstalling AIR helped but not always, the problem is that the error message is not detailled enough to fix this, in rare cases I had to create .exe installers for those customers but I suggest to try the installers on a few machines first and use the native .exe installers if anything else is not working.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/30189212\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-1\"\n}"}}},{"rowIdx":22978,"cells":{"text":{"kind":"string","value":"Q: Javascript variable inside qoute (double inside single qoute) I am trying to use a variable in nodejs. It giving me errors whatever I try. \nHow can I use a variable in this string\n let txt= 'some unknown texts'\n \"MATCH (productName) AGAINST ('txt')\"\n\nHere I need to replace txt.\nNote: I cannot use ``\nEdit\nHere is the query I am using \nawait Product.query().whereRaw(\"MATCH (productName) AGAINST ('txt')\").select('productName')\n\nThank you.\n\nA: In ES6 you need to do the following to use a var in string\n`MATCH (productName) AGAINST ${txt}`\n\nIF you cannot use ``\nJust go for the old way with string concatanation, \n\"MATCH (productName) AGAINST '\" +txt + \"'\"\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/50997423\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22979,"cells":{"text":{"kind":"string","value":"Q: How to make past date unselectable in fullcalendar? Problem is, how to disable selectable on PAST DATES in fullcalendar's month/week view.\nI want to user not allowed to click/select the on past dates.\n\nHere is some googled code snippet I am trying to implement on event rendering: \nselectable: true,\nselectHelper: false,\nselect: function(start, end, allDay) {\n var appdate = jQuery.datepicker.formatDate('', new Date(start));\n jQuery('#appdate').val(appdate);\n jQuery('#AppFirstModal').show();\n },\n eventRender: function(event, element, view)\n {\n var view = 'month' ;\n if(event.start.getMonth() !== view.start.getMonth()) { return false; }\n },\n\nBut its not working though.\nI tried bellow CSS too and this help me to hide past date text only, but selectable is still working on pastdate box.\n.fc-other-month .fc-day-number {\n display:none;\n}\n\nI am really stuck with this problem. Please someone help me out. \nThanks...\n\nA: The old answers to this question are ok...\nHowever, the official documentation suggests a new, more concise solution:\nFirst set the day you want to be the lower bound\n var today = new Date().toISOString().slice(0,10);\n\nThen include the range using validRange. Simply omit the end date.\n validRange: {\n start: today\n }\n\n\nA: In FullCalendar v3.0, there is the property selectAllow:\nselectAllow: function(info) {\n if (info.start.isBefore(moment()))\n return false;\n return true; \n}\n\n\nA: In fullcalendar 3.9, you might prefer the validRange function parameter :\nvalidRange: function(nowDate){\n return {start: nowDate} //to prevent anterior dates\n},\n\nDrawback: this also hides events before that datetime\n\nA: You can combine:\n-hide text by CSS as mentioned in question\n-disable PREV button on current month\n-check date on dayClick/eventDrop etc:\ndayClick: function(date, allDay, jsEvent, view) {\n var now = new Date();\n if (date.setHours(0,0,0,0) < now.setHours(0,0,0,0)){\n alert('test');\n }\n else{\n //do something\n }\n}\n\n\nA: I have done this in my fullcalendar and it's working perfectly.\nyou can add this code in your select function.\n select: function(start, end, allDay) {\n var check = $.fullCalendar.formatDate(start,'yyyy-MM-dd');\n var today = $.fullCalendar.formatDate(new Date(),'yyyy-MM-dd');\n if(check < today)\n {\n // Previous Day. show message if you want otherwise do nothing.\n // So it will be unselectable\n }\n else\n {\n // Its a right date\n // Do something\n }\n },\n\nI hope it will help you.\n\nA: I like this approach:\nselect: function(start, end) {\n if(start.isBefore(moment())) {\n $('#calendar').fullCalendar('unselect');\n return false;\n }\n}\n\nIt will essentially disable selection on times before \"now\".\nUnselect method\n\nA: This is what I am currently using \nAlso added the .add() function so the user cannot add an event at the same hour\nselect: function(start, end, jsEvent, view) {\n if(end.isBefore(moment().add(1,'hour').format())) {\n $('#calendar').fullCalendar('unselect');\n return false;\n }\n\n\nA: You can use this:\nvar start_date= $.fullCalendar.formatDate(start,'YYYY-MM-DD');\n\nvar today_date = moment().format('YYYY-MM-DD');\n\nif(check < today)\n{\n alert(\"Back date event not allowed \");\n $('#calendar').fullCalendar('unselect');\n return false\n}\n\n\nA: Thanks to this answer, I've found the solution below:\n$('#full-calendar').fullCalendar({\n selectable: true,\n selectConstraint: {\n start: $.fullCalendar.moment().subtract(1, 'days'),\n end: $.fullCalendar.moment().startOf('month').add(1, 'month')\n }\n});\n\n\nA: I have tried this approach, works well.\n$('#calendar').fullCalendar({\n defaultView: 'month',\n selectable: true,\n selectAllow: function(select) {\n return moment().diff(select.start, 'days') <= 0\n }\n})\n\nEnjoy!\n\nA: below is the solution i'm using now:\n select: function(start, end, jsEvent, view) {\n if (moment().diff(start, 'days') > 0) {\n $('#calendar').fullCalendar('unselect');\n // or display some sort of alert\n return false;\n }\n\n\nA: No need for a long program, just try this.\ncheckout.setMinSelectableDate(Calendar.getInstance().getTime()); \nCalendar.getInstance().getTime() \n\nGives us the current date.\n\nA: I have been using validRange option.\nvalidRange: {\n start: Date.now(),\n end: Date.now() + (7776000) // sets end dynamically to 90 days after now (86400*90)\n}\n\nA: In Fullcalendar i achieved it by dayClick event. I thought it is the simple way to do it.\nHere is my code..\n dayClick: function (date, cell) {\n var current_date = moment().format('YYYY-MM-DD')\n // date.format() returns selected date from fullcalendar\n if(current_date <= date.format()) {\n //your code\n }\n }\n\nHope it helps past and future dates will be unselectable..\n\nA: if any one of answer is not work for you please try this i hope its work for you.\n select: function(start, end, allDay) { \n\n var check = formatDate(start.startStr);\n var today = formatDate(new Date());\n\n if(check < today)\n {\n console.log('past'); \n }\n else\n { \n console.log('future');\n }\n}\n\nand also create function for date format as below \nfunction formatDate(date) {\n var d = new Date(date),\n month = '' + (d.getMonth() + 1),\n day = '' + d.getDate(),\n year = d.getFullYear();\n\n if (month.length < 2) month = '0' + month;\n if (day.length < 2) day = '0' + day;\n\n return [year, month, day].join('-');\n }\n\ni have tried all above question but not work for me \nyou can try this if any other answer work for you.\nthanks\n\nA: just add this if statement\n\n\n select(info) {\n if (moment(info.start).format() > moment().format()) {\n //your code here\n } else {\n toast.error(\"Please select valid date\");\n }\n },\n\n\n\nA: For FullCalendar React (Disable past day completely):\nselectAllow={c => (moment().diff(c.start, 'hours') <= 0)}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/14978629\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"29\"\n}"}}},{"rowIdx":22980,"cells":{"text":{"kind":"string","value":"Q: How to catch when user close a console application via “X” button I have to write data in memory to in a file to close my console application. How can i detect console closing event ? \n\nA: When the terminal is closed, your program will get a SIGHUP, which kill it by default. add a signal handler to handle the SIGHUP do whatever you want. and if you program write to the console after it has been close, you may also get SIGPIPE, handle it properly\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/17471949\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":22981,"cells":{"text":{"kind":"string","value":"Q: How will you design memory for 1GB memory with each page size being 4K I was asked this question in a job interview recently. I answered that I wud use a hash data structure to begin with designing the system. But couldn't answer that well. I think the interviewer was looking for answers like how will i design a page table for this. \nI would like to know how to answer this question. Like for each page size being 4K how many pages would be needed for 1Gb? Also, what other considerations I should keep in my mind to design it efficiently.\n\nA: This question makes sense in the context of CPUs where the TLBs are\n\"manually\" loaded and there are no predetermined page table\nstructures, like some models of MIPS, ARM, PowerPC.\nSo, some rough thoughts:\n1G is 2^30 bytes or 2^18 = 256K 4K pages\nSay, 4-byte entry per page, that's 1M for a single level page\ntable. Fast, but a bit wasteful on memory.\nWhat can we do to reduce memory and still make it reasonably fast.\nWe need 18 bits per page frame number, cannot squeeze it in 2 bytes,\nbut can use 3-bytes per PTE, with 6 bits to spare to encode - access\nrights, presence, COW, etc. That's 768K.\nInstead of the whole page frame number we can keep only 16-bits of it,\nwith the remaining two determined by a 4-entry upper level page table\nwith a format like this:\n\n\n*\n\n*2 MSB of the physical page number\n\n*21 bits for second level page table (30 bit address, aligned on 512K\nboundary)\n\n*spare bits\n\n\nNo place for per-page bits though, so lets move a few more address\nbits to the upper level table to obtain\nSecond level page table entry (4K 2-byte entries = 8K)\n\n\n*\n\n*4 bits for random flags\n\n*12 LSB of the page frame address\n\n\nFirst level page table entry format (64 4-byte entries = 256 bytes):\n\n\n*\n\n*6 MSB of the page frame address\n\n*17 bits for second level page table address (30-bit address aligned\nat 8K)\n\n*spare bits\n\n\nA: Looks like an open end question to me. The main idea may be to know how much you know about memory and how much deep you can think of the cases to handle. Some of them could be:\n\n\n*\n\n*Pagination - How many pages you want to keep in memory for a process and how many on disk to optimize paging.\n\n*Page Tables\n\n*Security\n\n*Others, if you can relate and think Of\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/8158456\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22982,"cells":{"text":{"kind":"string","value":"Q: How to override span-columns at different breakpoint in SUSY I think I must be missing something fundamental with how susy works, and the documentation has too few examples to understand how this works.\nI want different layouts at different breakpoints. I can make it that far, but I want my elements to span different number of columns depending on what breakpoint is triggered. So if I have a general stylesheet for mobile ('mobile-first') like:\n .wrapper{\n .element1{\n @include span-columns(4);\n }\n\n .element2{\n @include span-columns(2 omega);\n }\n}\n\nBut once the width changes to my 'tablet' and it changes to an 8 column layout, I want to be able to change this to:\n @include at-breakpoint($tablet-break $tablet-layout){\n .wrapper{\n @include set-container-width;\n .element1{\n @include span-columns(5);\n }\n\n .element2{\n @include span-columns(3 omega);\n }\n }\n}\n\nIt seems like this not only doesn't 'overwrite' the mobile settings, but it appears, upon firebug inspection, that the elements do not match up with my new tablet columns. I think it is still using a 6 column layout. Adding @include set-container-width doesn't seem to fix the problem; however, if I comment out the mobile layout it works. So it's almost as if these include statements don't overwrite, so I think I'm not understanding how susy works. Here's an example of firebug showing the element not matching the layout:\n\n(Also I'm not sure of any SUSY best practices (except for don't nest more than 4 deep). I could define all my sass with nested @at-breakpoint statements for all my changes, or I could define my default (mobile) css and then create a separate sass block all nested within at-breakpoint. I don't know if this is causing a problem.)\nUPDATE\nIt appears, that if I include at-breakpoint includes after the original (mobile) declaration, it seems to work. Though it does seem to require code repetition:\n .element1{\n @include span-columns(2 omega);\n text-indent: -1em;\n text-align: center;\n @include at-breakpoint($tablet-break $tablet-layout){\n @include span-columns(3 omega);\n text-indent: 0; \n text-align: left; \n }\n @include at-breakpoint($desktop-break $desktop-layout){\n @include span-columns(3 omega);\n text-indent: 0;\n text-align: left; \n }\n }\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/17940363\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22983,"cells":{"text":{"kind":"string","value":"Q: fftw shift zero-frequency to image center I am struggling on the result of FFTW applied on image. \nI can do the Fourier transform and inverse Fourier transform on image, I am sure the two functions are working. Now I am trying to analyze the result of Fourier transform and try to apply a filter on it, etc.\nCurrently I am confusing on the FT result. As I know the the zero-frequency should be on the top-left corner. I should shift it to the image center if I want to check frequency friendly. There are at least two way I have tested. one method is described on the FFTW FAQ webpage, all the pixels in the image were multiplied by (-1)^(i + j) before Fourier transform, where i, and j are the pixel's index. \nimage was multiplied by (-1)^(i+j), then its magnitude is\n \nbut actually ,it should be like this (which I did in imagej) Fourier transform in imagej:\n\nI also tried using my code to switch them after calculating its magnitude, but got the similar wrong result.\nvoid ftShift2D(double * d, int w, int h)\n{\n\n int nw = w/2;\n int nh = h/2;\n if ( w%2 != 0) {nw++;}\n if ( h%2 != 0) {nh++;}\n\n printf(\"%d, %d\\n\", nw, nh);\n for (int i = 0; i < nh ; i++)\n {\n for(int j = 0; j < nw; j++)\n {\n int t1 = i * w + j;\n int t2 = (i + nh + 1) * w + j + nw;\n swapXY(d[t1], d[t2]);\n }\n\n for (int k = nw; k < w; k++)\n {\n int t1 = i * w + k;\n int t2 = (i + nh + 1 ) * w + k - nw;\n swapXY(d[t1], d[t2]);\n }\n }\n}\n\nI understood the layout of FT result in FFTW, as is described in their website.\nI also checked the output, this layout can be confirmed, only top half have data, the rest is 0. therefore, it seems explain why the two methods used above cannot work. I am trying to design new method to shift the zero-frequency to image center. could you give me a better way to do it?\nI insist on this, aim to use the filter, it will be easier to understand. if the zero-frequency did not be shifted to center, could you guys give me another suggestion that I can, for example, apply a high Gaussian filter on it in frequency domain.\nthanks a lot.\nthe input image is:\n\nThe FT and IFT code are\n void Imgr2c(double * d, fftw_complex * df, int w, int h)\n{\n fftw_plan p = fftw_plan_dft_r2c_2d(h, w, d, df, FFTW_ESTIMATE);\n fftw_execute(p);\n\n fftw_destroy_plan(p);\n\n}\n\n\nvoid Imgc2r(fftw_complex * in, double * ftReverse, int w, int h)\n{\n fftw_plan p = fftw_plan_dft_c2r_2d(h, w, in, ftReverse, FFTW_ESTIMATE);\n fftw_execute(p);\n\n int l = w * h;\n for (int i = 0; i < l; i++)\n {\n ftReverse[i] /= l;\n }\n\n fftw_destroy_plan(p);\n}\n\n[Edit by Spektre]\nThis is how it should more or less look like:\n\n\nA: You may want to check out how I did it here:\nhttps://github.com/kvahed/codeare/blob/master/src/matrix/ft/DFT.hpp\nThe functions doing the job are at the bottom. If there are any issues, feel free to contact me personally. \n\nA: I found what is my problem! I did not understand the output layout of DFT in FFTW deeply. After some tests, I found the the dimension in width should w/2 + 1, and the dimension in height did not changed. the code to do FT, IFT, and shift the origin have no problem. what I need to do is changing the dimension when try to access it.\nmagnitude after DFT\nmagnitude after shifting the origin\nCheers, \nYaowang\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/46178586\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":22984,"cells":{"text":{"kind":"string","value":"Q: Is it possible to show blog view counter with information Google Analytics I have a static blog using Jekyll hosted on GitHub. I have set up Google Analytics for it and works well enough.\nNow I want to show how many people viewed each post in my blog. I found Google Analytics JavaScript API to get the information. But it seems that this API uses OAuth for data access. So I think this might not be the API I needed.\nIs it possible to do so with Google Analytics? I don't have any server since it's hosted on GitHub.\n\nA: I finally solved this problem by Google Analytics superProxy as suggested in the comment of @EikePierstorff. \nI wrote a blog on it.\nHere's the main idea.\nI first build a project on Google App Engile, with which I authenticate for the access of my Google Analytics. Then a URL of query (which can be pageview of certain pages) is generated in JSON format. I can set the refresh rate on this GAE project so that the JSON file can be updated from Google Analytic.\nSounds almost perfect to me. Thank you all guys for help!\n\nA: You can't query the Google Analytics API without authorization by someone, that's the most important thing to remember.\nIt's certainly possible to display Google Analytics data on your website to users who don't have access to your account, but in order to do that, someone with access to the account needs to authorize and get an access token in order to run queries.\nNormally this is done server side, and once you have a valid access token you can query the API client side (to display charts and graph, etc.). Access tokens are typically valid for 1 hour, so if you want to have your website up all the time, you'll also have to deal with refreshing the access token once it expires.\nNow, since you're using Github Pages and don't have a back end, which means all the authorization will need to happen client side. While it's technically possible to do the same thing client side as server side, it's generally not a good idea because private data like your client secret, refresh token, etc. will be visible in the source code.\nApplications that do auth client side typically don't authorize on behalf of a user. They require the users themselves to go through an auth flow for security reasons (as I just explained), but that would mean those users 1) have to log in, and 2) can only see the analytics data they have access to, which probably isn't what you want.\n--\nWhat you can do is run reports periodically yourself and export that data to a Google Spreadsheet. Google Spreadsheets allow you to embed charts and graphs of data as an