{ // 获取包含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\nYou only need to 'contain' the right hand column to stop the 'stacked column' flowing incorrectly.\n\nA: CSS3 actually allows you to make several columns automatically without having to have all those classes. Check out this generator: http://www.generatecss.com/css3/multi-column/\nThis is however only if you are trying to make your content have multiple columns like a newspaper.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/20598741\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23005,"cells":{"text":{"kind":"string","value":"Q: Pathos multiprocessing pool CPickle error When i tried to run the following code:\nfrom pathos.multiprocessing import ProcessingPool as Pool\nlist1 = [1,2,3,4,5]\nlist2 = [6,7,8,9,10]\ndef function1(x,y):\n print x\n print y\nif __name__ == '__main__':\n pool = Pool(5)\n pool.map(function1, list1, list2)\n\nIt gets the followwing error:\nTraceback (most recent call last):\n File \"test.py\", line 9, in \n pool.map(function1, list1, list2)\n File \"C:\\Python27\\lib\\site-packages\\pathos\\multiprocessing.py\", line 136, in map\n return _pool.map(star(f), zip(*args)) # chunksize\n File \"C:\\Python27\\lib\\site-packages\\multiprocess\\pool.py\", line 251, in map\n return self.map_async(func, iterable, chunksize).get()\n File \"C:\\Python27\\lib\\site-packages\\multiprocess\\pool.py\", line 567, in get\n raise self._value\ncPickle.PicklingError: Can't pickle : attribute lookup __builtin__.function failed\n\nIsn't pathos.multiprocessing is designed to solve this problem?\n\nA: I'm the pathos author. When I try your code, I don't get an error. However, if you are seeing a CPickle.PicklingError, I'm guessing you have an issue with your install of multiprocess. You are on windows, so do you have a C compiler? You need one for multiprocess to get a full install of multiprocess.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/44094924\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23006,"cells":{"text":{"kind":"string","value":"Q: Why does slice not work directly on arguments? Tested it out on this fiddle after looking at underscore.\nThis seems like a hack to call slice on arguments when it is not on the prototype chain.\nWhy is it not on the prototype chain when it obviously works on arguments.\nvar slice = Array.prototype.slice;\nfunction test () {\n return slice.call(arguments,1);\n // return arguments.slice(1)\n}\nvar foo = test(1,2,3,4);\n_.each(foo, function(val){\n console.log(val)\n});\n\n\nA: >>> Object.prototype.toString.call(arguments)\n<<< \"[object Arguments]\"\n>>> Array.isArray(arguments) //is not an array\n<<< false\n>>> arguments instanceof Array //does not inherit from the Array prototype either\n<<< false\n\narguments is not an Array object, that is, it does not inherit from the Array prototype. However, it contains an array-like structure (numeric keys and a length property), thus Array.prototype.slice can be applied to it. This is called duck typing.\nOh and of course, Array.prototype.slice always returns an array, hence it can be used to convert array-like objects / collections to a new Array. (ref: MDN Array slice method - Array-like objects)\n\nA: arguments is not a \"real\" array.\n\nThe arguments object is a local variable available within all\n functions; arguments as a property of Function can no longer be used.\nThe arguments object is not an Array. It is similar to an Array, but\n does not have any Array properties except length. For example, it does\n not have the pop method. However it can be converted to a real Array.\n\nYou could do:\nvar args = Array.prototype.slice.call(arguments);\n\n\nA: Arguments is not an Array. It's an Arguments object.\nFortunately, slice only requires an Array-like object, and since Arguments has length and numerically-indexed properties, slice.call(arguments) still works.\nIt is a hack, but it's safe everywhere.\n\nA: Referring to MDN: »The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:«\nhttps://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments\nIn order to call slice, you have to get the slicefunction, from the Array-prototype.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/16345747\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23007,"cells":{"text":{"kind":"string","value":"Q: Create Watchkit notification programmatically I'm looking to push a notification to the Apple Watch at a specific time. I was able to display a static message on the simulator using an apns file, but I'd like to set the data and time of the notification in the controller.\nI heard I might not be able to do this on a simulator, but if I got a real phone and watch, how would it work?\n\nA: So, you want to do something in the watch app extension and based on the results, schedule a UILocalNotification that will be sent to the phone at some point? \nYou cannot directly schedule a UILocalNotification from the watch because you don't have access to the UIApplication object. See Apple staff comment here. However, using Watch Connectivity, you could send a message from the watch to the phone and have the phone app create and schedule it in the background. The watch will display the notification iff the phone is locked at the trigger time. The watch's notification scene will be invoked in that case.\n\nA: Assuming you want to send the notification from the phone to the watch: You can use UILocalNotification to send a notification to the watch - but the watch must be locked to receive it. There's also no guarantee when the Watch OS will turn on the watch to run the code that receives your notification, so your notification may arrive minutes or hours after it's sent.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/33759489\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23008,"cells":{"text":{"kind":"string","value":"Q: How to create an object in a class by passing a token to a constructor? What I am attempting to do is to take a .txt file that has multiple lines of people's information (Last name, First name, phone number, email) and display the information into a listbox so that a user could select a name in the listbox and display all of the selected person's information in a second form. The instructions for my assignment say that the next thing I should do is Create your object by passing these tokens to your constructor. (Don’t pass the array but rather each element individually.) I have created a class called PersonEntry that constructs 4 strings containing the 4 pieces of information that's included in the .txt file. Here is where I'm at(the first one is my form1.cs code and the second is my PersonEntry.cs class code) and I don't know what to do next. Any help would be much appreciated!\nnamespace ChalabiMichaelProgram10\n{\n public partial class chalabiMichaelProgram10 : Form\n {\n List personsList = new List;\n\n public chalabiMichaelProgram10()\n {\n InitializeComponent();\n }\n\n private void chalabiMichaelProgram10_Load(object sender, EventArgs e)\n {\n try\n {\n StreamReader inputfile;\n string line;\n int count;\n\n inputfile = File.OpenText(\"contacts.txt\");\n\n while (!inputfile.EndOfStream)\n {\n line = inputfile.ReadLine();\n char[] delimiters = { ',' };\n string[] tokens;\n tokens = line.Split(delimiters);\n\n for( count = 0; count < 4; count++)\n {\n tokens[count] = tokens[count].Trim();\n\n }\n }\n }\n }\n }\n}\n\n\nnamespace ChalabiMichaelProgram10\n{\n class PersonEntry\n {\n //Constructor.\n public PersonEntry()\n {\n lastName = \"\";\n firstName = \"\";\n phoneNumber = \"\";\n email = \"\";\n }\n public string lastName { get; set; }\n public string firstName { get; set; }\n public string phoneNumber { get; set; }\n public string email { get; set; }\n }\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/62768590\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":23009,"cells":{"text":{"kind":"string","value":"Q: array used the same memory space? i have an array in the main program like this: (i am using C# to program in asp.net)\ndouble[][] example= new double[][];\n\nfor this example lets imagine is an array of 10*2.\nso next thing i will do is send this array to another function like this:\nusedarray(example);\npublic double[][] usedarray(double[][]examplearray)\n{\n\n}\n\ni know that a double array in each space has only 64 bit floating point number, so the array will have a 1280 bits for this example used memory, but when is send to the function it used the same space of memory? or it use a complete new set of memory space?\n\nA: Arrays are reference types, not value types. That means that the variable, examplearray doesn't actually contain 1280 bits of data, it just contains a reference (sometimes also referred to as a pointer) to the actual data, which is stored elsewhere (for the purposes of this post, it doesn't matter where \"elsewhere\" actually is). Passing that variable to a method, as you have done there, is only copying that reference (which is 32 or 64 bits, depending on the system), not the underlying 1280 bits of data.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/13074824\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23010,"cells":{"text":{"kind":"string","value":"Q: onRestart() and onRefresh() Act Different with Same Code I have the exact same methods and calls in onRefresh() and onRestart(), but for some reason onRestart() does what I want exactly, yet onRefresh() acts differently. What I want to happen is for app to understand when the location is disabled while running. \nonRestart() does this: I start the app, get the Forecast data, disable location from status bar, press the home button and open the app again. As expected, onRestart() tries to check for GPS status(with gpsTracker.getIsGPSEnabled()), sees that location is disabled, and sends the according Toast message. \nonRefresh() does this: I start the app, get the Forecast data, disable location from status bar, even wait few seconds and then refresh the app. Unexpectedly, onRefresh() gives sends the \"Data Refreshed\" toast, even though it gets \"null, null\" as location latitude and longitude. \nI could provide other codes as well, but if there was a problem with the rest of the code, why would onRestart() act the way I want? I'm not getting any errors. Any help would be highly appreciated. Thanks.\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ButterKnife.bind(this);\n final GPSTracker gpsTracker = new GPSTracker(this);\n\n\n mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);\n mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {\n @Override\n public void onRefresh() {\n new Handler().postDelayed(new Runnable() {\n @Override\n public void run() {\n mSwipeRefreshLayout.setRefreshing(false);\n if (gpsTracker.getIsGPSTrackingEnabled()) {\n gpsTracker.getLocation();\n getForecast(gpsTracker);\n Toast.makeText(MainActivity.this, \"Data Refreshed\", Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(MainActivity.this, \"Location is not enabled\", Toast.LENGTH_LONG).show();\n }\n }\n }, 3000);\n }\n });\n}\n\n@Override\nprotected void onRestart() {\n super.onRestart();\n final GPSTracker gpsTracker = new GPSTracker(this);\n new Handler().postDelayed (new Runnable ()\n @Override public void run() {\n gpsTracker.getLocation();\n if (gpsTracker.getIsGPSTrackingEnabled()) {\n getForecast(gpsTracker);\n Toast.makeText(MainActivity.this, \"Data Refreshed\", Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(MainActivity.this, \"Location is not enabled\", Toast.LENGTH_LONG).show();\n }\n }\n}, 3000);\n}\n\n\nA: onRestart you create a new instance of GPSTracker. try updating your GPSTracker handler in onRefresh.\ngive it a try\n\nA: @Override\n public void onRefresh() {\n final GPSTracker gpsTracker = new GPSTracker(MainActivity.this);\n new Handler().postDelayed(new Runnable() {\n @Override\n public void run() {\n mSwipeRefreshLayout.setRefreshing(false);\n if (gpsTracker.getIsGPSTrackingEnabled()) {\n gpsTracker.getLocation();\n getForecast(gpsTracker);\n Toast.makeText(MainActivity.this, \"Data Refreshed\", Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(MainActivity.this, \"Location is not enabled\", Toast.LENGTH_LONG).show();\n }\n }\n }, 3000);\n }\n});\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/34661858\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23011,"cells":{"text":{"kind":"string","value":"Q: How to use jdt.ast to resolve polymorphism I'm working to get the override method binding through eclipse-jdt-ast.\nJust like when we using eclipse, press Ctrl and click the method ,we can jump to the method implenmentation.\nAlthough it's dynamic binging in java, but the following works well:\npublic class Father{\npublic void test(){}\n}\n\nAnd Son:\npublic class Son extends Father{\n@Override\npublic void test(){}\n\n public static void main (String[] arg){\n Father f=new Son();\n f.test();\n }\n}\n\nWhen we click the test in main, we can correctly jump to the Son.java \nAnd I'm wondering how to do it. I tried to see the sources but didn't find the location because the code is too many.\nAnd my code now is :\npublic class Main {\nstatic String filep=\"example/Son.java\";\nstatic String[] src={\"example/\"};\nstatic String[] classfile={\"example/\"};\n\npublic static void main(String[] args) throws IOException,Exception{\n\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n parser.setSource(Files.toString(new File(filep), Charsets.UTF_8).toCharArray());\n // only setEnvironment can we get bindings from char[]\n parser.setEnvironment(classfile, src, null, true);\n parser.setUnitName(filep);\n parser.setResolveBindings(true);\n parser.setKind(ASTParser.K_COMPILATION_UNIT);\n CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);\n if (compilationUnit.getAST().hasResolvedBindings()) {\n System.out.println(\"Binding activated.\");\n }\n else {\n System.out.println(\"Binding is not activated.\");\n }\n ASTNode node=compilationUnit.findDeclaringNode(\"f\");\n compilationUnit.accept(new Myvisitor(compilationUnit));\n}\n}\n\nAnd my visitor is:\npublic class Myvisitor extends ASTVisitor {\nint i=0;\nCompilationUnit compilationUnit;\nMyvisitor(CompilationUnit compilationUnit){\n this.compilationUnit=compilationUnit;\n}\n\n\n@Override\npublic boolean visit(MethodInvocation node) {\n i++;\n System.out.println(i);\n IMethodBinding binding=node.resolveMethodBinding();\n\n ASTNode astNode=compilationUnit.findDeclaringNode(binding);\n System.out.println(astNode);\n return true;\n}\n\n}\n\nIt's a little long but simple, hope u can read here. Personally I guess the\nfindDeclaringNode method may do it. However, it returns null when I pass the binding. So do u have any ideas?\nThanks a lot\n\nA: When looking for all implementations of a given super method, the AST is of little help, as even with its bindings it only has references from sub to super but not the opposite direction.\nSearching in the opposite direction uses the SearchEngine. If you look at JavaElementImplementationHyperlink the relevant code section can be found around line 218 (as of current HEAD)\nYou will have to first find the IMethod representing the super method. Then you prepare a SearchRequestor, an IJavaSearchScope, and a SearchPattern before finally calling engine.search(..). Search results are collected in ArrayList links.\nA good tradition of Eclipse plug-in development is \"monkey see, monkey do\", so I hope looking at this code will get you started on your pursuit :)\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/41176592\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23012,"cells":{"text":{"kind":"string","value":"Q: Close a MSI file handle after being downloaded from a website I have a vsto add-in for outlook. There is a code where I download a MSI file from a website:\nPublic Sub DownloadMsiFile()\n Try\n Dim url As String = \"https://www.website.com/ol.msi\"\n Dim wc As New WebClient()\n wc.Headers.Add(HttpRequestHeader.UserAgent, \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;\")\n If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & \"\\ol.msi\") Then\n System.IO.File.Delete(My.Computer.FileSystem.SpecialDirectories.Temp & \"\\ol.msi\")\n End If\n wc.DownloadFile(url, My.Computer.FileSystem.SpecialDirectories.Temp & \"\\ol.msi\")\n wc.Dispose()\n Catch ex As Exception\n MessageBox.Show(\"File couldn't be downloaded: \" & ex.Message)\n End Try\nEnd Sub\n\nAnd then I get the MSI version using the following function:\nFunction GetMsiVersion() As String\n Try\n Dim oInstaller As WindowsInstaller.Installer\n Dim oDb As WindowsInstaller.Database\n Dim oView As WindowsInstaller.View\n Dim oRecord As WindowsInstaller.Record\n Dim sSQL As String\n oInstaller = CType(CreateObject(\"WindowsInstaller.Installer\"), WindowsInstaller.Installer)\n DownloadMsiFile()\n If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & \"\\ol.msi\") Then\n oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & \"\\ol.msi\", 0)\n sSQL = \"SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'\"\n oView = oDb.OpenView(sSQL)\n oView.Execute()\n oRecord = oView.Fetch\n Return oRecord.StringData(1).ToString()\n Else\n Return Nothing\n End If\n Catch ex As Exception\n MessageBox.Show(\"File couldn't be accessed: \" & ex.Message)\n End Try\nEnd Function\n\nAnd then I do the comparison with the current dll version to see if there is a need to download a newer version or not:\nPublic Sub CheckOLUpdates()\n Dim remoteVersion As String = GetMsiVersion()\n Dim installedVersion As String = Assembly.GetExecutingAssembly().GetName().Version.ToString\n If Not String.IsNullOrEmpty(remoteVersion) Then\n Try\n If String.Compare(installedVersion, remoteVersion) < 0 Then\n Dim Result As DialogResult = MessageBox.Show(\"A newer version is available for download, do you want to download it now?\", \"OL\", System.Windows.Forms.MessageBoxButtons.OKCancel, MessageBoxIcon.Question)\n If Result = 1 Then\n System.Diagnostics.Process.Start(\"http://www.website.com/update\")\n Else\n Exit Sub\n End If\n Else\n MessageBox.Show(\"You have the latest version installed!\", \"OL\", MessageBoxButtons.OK, MessageBoxIcon.Information)\n End If\n Catch ex As Exception\n\n End Try\n\n End If\n\nEnd Sub\n\nThis works pretty well if this ran once. However if I try again to check for update, I would get the following error which happens while trying to delete the file in DownloadMsiFile() :\n\nThe process cannot access the file %temp%\\ol.msi because it is being used by another process\n\nIf I use the sysinternals handle.exe utility to check the handles on this file I get the outlook process having a handle lock on this file:\nhandle.exe %temp%\\ol.msi\nNthandle v4.30 - Handle viewer\nCopyright (C) 1997-2021 Mark Russinovich\nSysinternals - www.sysinternals.com\n\nOUTLOOK.EXE pid: 25964 type: File 4FC8: %temp%\\ol.msi\n\nI was wondering how can I close the handle to avoid this error? Any help is really appreciated\n\nA: So here is what I have to do to close the handle. I have added the following lines after opening the MSI file:\n Marshal.FinalReleaseComObject(oRecord)\n oView.Close()\n Marshal.FinalReleaseComObject(oView)\n Marshal.FinalReleaseComObject(oDb)\n oRecord = Nothing\n oView = Nothing\n oDb = Nothing\n\nSo my final code looked like the following:\nFunction GetMsiVersion() As String\n Try\n Dim oInstaller As WindowsInstaller.Installer\n Dim oDb As WindowsInstaller.Database\n Dim oView As WindowsInstaller.View\n Dim oRecord As WindowsInstaller.Record\n Dim sSQL As String\n Dim Version As String\n oInstaller = CType(CreateObject(\"WindowsInstaller.Installer\"), WindowsInstaller.Installer)\n DownloadMsiFile()\n If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & \"\\ol.msi\") Then\n oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & \"\\ol.msi\", 0)\n sSQL = \"SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'\"\n oView = oDb.OpenView(sSQL)\n oView.Execute()\n oRecord = oView.Fetch\n Version = oRecord.StringData(1).ToString()\n Marshal.FinalReleaseComObject(oRecord)\n oView.Close()\n Marshal.FinalReleaseComObject(oView)\n Marshal.FinalReleaseComObject(oDb)\n oRecord = Nothing\n oView = Nothing\n oDb = Nothing\n Else\n Version = Nothing\n End If\n Return Version\n Catch ex As Exception\n MessageBox.Show(\"File couldn't be accessed: \" & ex.Message)\n End Try\nEnd Function\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/67393101\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23013,"cells":{"text":{"kind":"string","value":"Q: What does this line of code means in javascript? function delay(n){\nn = n || 2000\n//other stuff\n} \n\nwhat does the first line do?\nThanks.\n\nA: It means that if n, the argument passed to the function, is falsey, 2000 will be assigned to it.\nHere, it's probably to allow callers to have the option of either passing an argument, or to not pass any at all and use 2000 as a default:\n\n\nfunction delay(n){\n n = n || 2000\n console.log(n);\n} \n\ndelay();\ndelay(500);\n\n\nBut it would be more suitable to use default parameter assignments in this case.\n\n\nfunction delay(n = 2000){\n console.log(n);\n} \n\ndelay();\ndelay(500);\n\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/65545634\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23014,"cells":{"text":{"kind":"string","value":"Q: Setting tensorflow rounding mode I am working with small numbers in tensorflow, which sometimes results in numerical instability.\nI would like to increase the precision of my results, or at the very least determine bounds on my result.\nThe following code shows a specific example of numerical errors (it outputs nan instead of 0.0, because float64 is not precise enough to handle 1+eps/2):\nimport numpy as np\nimport tensorflow as tf\n\n# setup\neps=np.finfo(np.float64).eps\nv=eps/2\nx_init=np.array([v,1.0,-1.0],dtype=np.float64)\n\nx=tf.get_variable(\"x\", initializer=tf.constant(x_init))\nsquare=tf.reduce_sum(x)\nroot=tf.sqrt(square-v)\n\n# run\nwith tf.Session() as session:\n init = tf.global_variables_initializer()\n session.run(init)\n\n ret=session.run(root)\n print(ret)\n\nI am assuming there is no way to increase the precision of values in tensorflow. But maybe it is possible to set the rounding mode, as in C++ using std::fesetround(FE_UPWARD)? Then, I could force tensorflow to always round up, which would make sure that I am taking the square root of a non-negative number.\n\nWhat I tried: I tried to follow this question that outlines how to set the rounding mode for python/numpy. However, this does not seem to work, because the following code still prints nan:\nimport numpy as np\nimport tensorflow as tf\n\nimport ctypes\nFE_TONEAREST = 0x0000 # these constants may be system-specific\nFE_DOWNWARD = 0x0400\nFE_UPWARD = 0x0800\nFE_TOWARDZERO = 0x0c00\nlibc = ctypes.CDLL('libm.so.6') # may need 'libc.dylib' on some systems\n\nlibc.fesetround(FE_UPWARD)\n\n# setup\neps=np.finfo(np.float64).eps\nv=eps/2\nx_init=np.array([v,1.0,-1.0],dtype=np.float64)\n\nx=tf.get_variable(\"x\", initializer=tf.constant(x_init))\nsquare=tf.reduce_sum(x)\nroot=tf.sqrt(square-v)\n\n# run\nwith tf.Session() as session:\n init = tf.global_variables_initializer()\n session.run(init)\n ret=session.run(root)\n print(ret)\n\n\nA: Replace\nret=session.run(root)\n\nwith\nret = tf.where(tf.is_nan(root), tf.zeros_like(root), root).eval()\n\nRefer tf.where\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/48344974\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"10\"\n}"}}},{"rowIdx":23015,"cells":{"text":{"kind":"string","value":"Q: Getting \"Error: Invalid or corrupt jarfile corda.jar\" while bootstrapping the Corda netwrok While trying to bootstrap the Corda network getting below error.\n\nError: Invalid or corrupt jarfile corda.jar\n\nPlease find more details below.\nroot@domestic-lc:/home/POC_DomesticLC# java -jar corda-tools-network-bootstrapper-4.0.jar --dir build/nodes\nBootstrapping local test network in /home/POC_DomesticLC/build/nodes\nUsing corda.jar in root directory\nGenerating node directory for PartyB\nGenerating node directory for BankB\nGenerating node directory for Notary\nGenerating node directory for BankA\nGenerating node directory for PartyA\nNodes found in the following sub-directories: [PartyA, PartyB, BankB, BankA, Notary]\nFound the following CorDapps: []\nNot copying CorDapp JARs as --copy-cordapps is set to FirstRunOnly, and it looks like this network has already been bootstrapped.\nWaiting for all nodes to generate their node-info files...\n#### Error while generating node info file /home/POC_DomesticLC/build/nodes/PartyA/logs ####\nError: Invalid or corrupt jarfile corda.jar\n#### Error while generating node info file /home/POC_DomesticLC/build/nodes/PartyB/logs ####\nError: Invalid or corrupt jarfile corda.jar\n#### Error while generating node info file /home/POC_DomesticLC/build/nodes/BankA/logs ####\nError: Invalid or corrupt jarfile corda.jar\n#### Error while generating node info file /home/POC_DomesticLC/build/nodes/BankB/logs ####\nError: Invalid or corrupt jarfile corda.jar\n#### Error while generating node info file /home/POC_DomesticLC/build/nodes/Notary/logs ####\nError: Invalid or corrupt jarfile corda.jar\nError while generating node info file. Please check the logs in /home/POC_DomesticLC/build/nodes/PartyA/logs.\n\n\nA: Did you get over this issue?\nI've tried with bootstrap 4.0 but I didn't see any issue, so my suggestions are:\n\n\n*\n\n*check your java version, make sure it is 1.8.171+\n\n*make sure the corda.jar (in your build /nodes/notary/corda.jar) is correct because bad network may cause the incomplete corda.jar downloaded\n\n*make sure you've got the tools from official website instead of copying from other way where the bootstrap jar file might be broken\n\n*last, as always, please try to use the latest version bootstrap: 4.3, to utilise the best Corda:\nhttps://software.r3.com/artifactory/corda-releases/net/corda/corda-tools-network-bootstrapper/4.3/\n\nA: I had a similar problem (not with that particular JAR file, but I'm using that file's name in my examples). Here's how I worked out what was wrong.\nThese troubleshooting steps may help others who find this issue (but not the OP as the dates show it can't be this issue).\nI started by trying to validate the JAR file by inspecting its contents:\n$ jar -tf corda.jar\n\nThis showed me that it was indeed invalid. In my case, I saw:\njava.util.zip.ZipException: error in opening zip file\n at java.util.zip.ZipFile.open(Native Method)\n at java.util.zip.ZipFile.(ZipFile.java:225)\n at java.util.zip.ZipFile.(ZipFile.java:155)\n at java.util.zip.ZipFile.(ZipFile.java:126)\n at sun.tools.jar.Main.list(Main.java:1115)\n at sun.tools.jar.Main.run(Main.java:293)\n at sun.tools.jar.Main.main(Main.java:1288)\n\nI then looked at the size of the file:\n$ ls -alh corda.jar\n\nIn my case, it was 133 bytes, which seems a bit small for a JAR file, so I cated it and saw this:\n$ cat corda.jar\n\n501 HTTPS Required. \nUse https://repo1.maven.org/maven2/\nMore information at https://links.sonatype.com/central/501-https-required\n\nIt turned out that my script (a Dockerfile in fact) was downloading the file with curl -o but from a URL which was no longer supported. As https://links.sonatype.com/central/501-https-required says:\n\nEffective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.\nIf you're receiving this error, then you need to replace all URL references to Maven Central with their canonical HTTPS counterparts:\nReplace http://repo1.maven.org/maven2/ with https://repo1.maven.org/maven2/\nReplace http://repo.maven.apache.org/maven2/ with https://repo.maven.apache.org/maven2/\nIf for any reason your environment cannot support HTTPS, you have the option of using our dedicated insecure endpoint at http://insecure.repo1.maven.org/maven2/\nFor further context around the move to HTTPS, please see https://blog.sonatype.com/central-repository-moving-to-https.\n\nThis is fairly specific, but may help someone.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/59247439\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":23016,"cells":{"text":{"kind":"string","value":"Q: how to add facebook comment to single page application? i have website news (single page application )\nthis code woks well in aspx page\n
\n
\n \n\n\n
\n
\n\nbut how to do in View in SPA \nwhich doesn't contain html or body tags just div \ni use durandal in single page application \n\nA: Late answer, but maybe it will help someone. For me the key to getting unique fb comments to render on a single page application was FB.XFBML.parse(); \nEach time I want to render unique comments:\n\n\n*\n\n*Change the url, each fb comments thread is assigned to the specific url\nSo I might have www.someurl.com/#123, www.someurl.com/#456, www.someurl.com/#789, each with its own fb comment thread. In AngularJs this can be done with $location.hash('123');\n\n*Create a new fb-comments div, where 'number' equals '123', '456' or '789'\n
\n
\n\n*Call a function that executes the fb SDK \nfunction FBfun(path) {\n setTimeout(function() { // I'm executing this just slightly after step 2 completes\n window.fbAsyncInit = function() {\n FB.init({\n appId : '123456789123',\n xfbml : true,\n version : 'v2.2'\n });\n };\n\n (function(d, s, id){\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) {return;}\n js = d.createElement(s); js.id = id;\n js.src = \"//connect.facebook.net/en_US/sdk.js\";\n fjs.parentNode.insertBefore(js, fjs);\n }(document, 'script', 'facebook-jssdk'));\n\n FB.XFBML.parse(); // This is key for all this to work!\n }, 100);\n}\n\n\nA: i added the script to app.js like \n initializeFB: function () {\n if (!isFBInitialized.isInitialized) {\n\n FB.init({\n appId: 'xxxxxxxxxxxx',\n appSecret: 'xxxxxxxxxxxxxxx',\n // App ID from the app dashboard\n channelUrl: '//mysite//channel.html', // Channel file for x-domain comms\n status: true, // Check Facebook Login status\n cookie: true, // enable cookies to allow the server to access the session\n xfbml: true // Look for social XFBML plugins on the page to be parsed\n });\n\n\n\n (function (d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) { return; }\n js = d.createElement(s); js.id = id;\n js.src = \"//connect.facebook.net/en_US/all.js\";\n fjs.parentNode.insertBefore(js, fjs);\n }(document, 'script', 'facebook-jssdk'));\n\n // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired\n // for any auth related change, such as login, logout or session refresh. This means that\n // whenever someone who was previously logged out tries to log in again, the correct case below \n // will be handled. \n FB.Event.subscribe('auth.authResponseChange', function (response) {\n // Here we specify what we do with the response anytime this event occurs. \n if (response.status === 'connected') {\n // The response object is returned with a status field that lets the app know the current\n // login status of the person. In this case, we're handling the situation where they \n // have logged in to the app.\n testFBAPI();\n } else if (response.status === 'not_authorized') {\n // In this case, the person is logged into Facebook, but not into the app, so we call\n // FB.login() to prompt them to do so. \n // In real-life usage, you wouldn't want to immediately prompt someone to login \n // like this, for two reasons:\n // (1) JavaScript created popup windows are blocked by most browsers unless they \n // result from direct user interaction (such as a mouse click)\n // (2) it is a bad experience to be continually prompted to login upon page load.\n FB.login();\n } else {\n // In this case, the person is not logged into Facebook, so we call the login() \n // function to prompt them to do so. Note that at this stage there is no indication\n // of whether they are logged into the app. If they aren't then they'll see the Login\n // dialog right after they log in to Facebook. \n // The same caveats as above apply to the FB.login() call here.\n FB.login();\n }\n });\n\n isFBInitialized.isInitialized = true;\n }\n },\n\nand call it in viewattached \nas\n app.initializeFB();\n\nthen it works well \n\nA: Step 3 for my React app become (more linter friendly):\ncomponentDidMount() {\n window.fbAsyncInit = () => {\n window.FB.init({\n appId: '572831199822299',\n xfbml: true,\n version: 'v4.0',\n });\n };\n\n (function (d, s, id) {\n const fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) { return; }\n const js = d.createElement(s);\n js.id = id;\n js.src = '//connect.facebook.net/ru_RU/sdk.js';\n fjs.parentNode.insertBefore(js, fjs);\n }(document, 'script', 'facebook-jssdk'));\n\n setTimeout(() => {\n window.FB.XFBML.parse();\n }, 100);\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/19975902\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":23017,"cells":{"text":{"kind":"string","value":"Q: Variable \"Name\" is not readable, how can I fix it? I was inserting some code to make a registration form, but iIfound this\nclass User {\n\n private String Nama;\n private String Kelas;\n private int NIM;\n \n public String getNama{\n return Nama;\n }\n public String setNama{\n \n }\n}\n\nThe error message was all \"variable is never read\". Can someone explain why there is a message on this, and how I can fix it?\n\nA: Though it is not clear where you use your codes, but the following is a java model class, with setter and getter method. Even it is not the direct answer of you question, but I have used this types of model class in my projects, one can find the idea of setter and getter from the following user class.\nFor using in various purposes You can create your User class as follows with constructors and setter and getter methods :\npublic class User {\n\n private String Nama;\n private String Kelas;\n private int NIM;\n\n public User() {\n }\n\n public User(String nama, String kelas, int NIM) {\n Nama = nama;\n Kelas = kelas;\n this.NIM = NIM;\n }\n\n\n public String getNama() {\n return Nama;\n }\n\n public void setNama(String nama) {\n Nama = nama;\n }\n\n public String getKelas() {\n return Kelas;\n }\n\n public void setKelas(String kelas) {\n Kelas = kelas;\n }\n\n public int getNIM() {\n return NIM;\n }\n\n public void setNIM(int NIM) {\n this.NIM = NIM;\n }\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/71616728\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23018,"cells":{"text":{"kind":"string","value":"Q: Run a javascript on regex pattern match url (Blogger) I'm trying to load a javascript on several pages but I only on pages which the url matches with a specific pattern.\nThe following code works for specific pages but it doesn't accept any wildcard or regex\n\n\n\nI've two main concerns:\n\n\n*\n\n*if the regex is correct\n\n*between the brackets I've to execute some code which includes Blogger conditional statements, div and plain JavaScript. Does this code need some special attention?\n\n\nThanks\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/42323018\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23019,"cells":{"text":{"kind":"string","value":"Q: Split string using SUBSTR or SPLIT? I'm at a loss and hoping to find help here. What I'm trying to accomplish is the following:\nI have a .csv file with 8 columns. The third column contains phone numbers formatted like so:\n+45 23455678\n+45 12314425\n+45 43631678\n+45 12345678\n(goes on for a while) \n\nWhat I want is:\n+45 2345 5678\n+45 1231 4425\n+45 4363 1678\n+45 1234 5678\n(etc)\n\nSo just a whitespace after the 8th position (inc the + and whitespace). I've tried various things but it's not working. First I tried it with substr but couldn't get it to work. Then looked at the split function. And then I got confused! I'm new to perl so I'm not sure what I'm looking for but I've tried everything. There's 1 condition, all the numbers begin with (let's say) +45 and then a whitespace and a block of numbers. But not all the numbers have the same length, some have more than 10 digits. What I want it to do is take the first bit \"+45 1234\" (/+43\\s{1}\\d{4}/) and then the second part no matter how many digits it has. I figured setting LIMIT to 1 so it just adds the last bit no matter if its 4 digits or 8 long.\nI've read http://www.perlmonks.org/?node_id=591988, but the part \"Using split versus Regular Expressions\" got me confused.\nI've been trying for 3 days now and not getting anywhere. I guess it should be simple but I'm just now getting to know the basics of perl. I do have an understanding of regular expression but I don't know what statement to use for a certain task. This is my code:\n@ARGV or die \"Usage: $0 input-file output-file\\n\";\n\n$inputfile=$ARGV[0];\n$outputfile=$ARGV[1];\n\nopen(INFILE,$inputfile) || die \"Bestand niet gevonden :$!\\n\";\nopen(OUTFILE,\">$outputfile\") || die \"Bestand niet gevonden :$!\\n\";\n\n$i = 0;\n\n@infile=;\n\nforeach ( @infile ) {\n $infile[$i] =~ s/\"//g; \n @elements = split(/;/,$infile[$i]); \n\n @split = split(/\\+43\\s{1}\\d{4}/, $elements[2], 1);\n\n @split = join ???\n\n @elements = join(\";\",@elements); # Add ';' to all elements\n print OUTFILE \"@elements\";\n $i = $i+1;\n}\n\nclose(INFILE);\nclose(OUTFILE);\n\n\nA: There are several issues with your code, but to address your question on how to add a space after the 8th position in a string, I'm going to assume you have stored your phone numbers in an array @phone_numbers. This is a task well suited for a regex:\n#!/usr/bin/env perl\nuse strict;\nuse warnings;\nuse Data::Dumper;\n\nmy @phone_numbers = (\n '+45 23455678',\n '+45 12314425',\n '+45 43631678',\n '+45 12345678'\n);\n\ns/^(.{8})/$1 / for @phone_numbers;\n\nprint Dumper \\@phone_numbers;\n\nOutput:\n$VAR1 = [\n '+45 2345 5678',\n '+45 1231 4425',\n '+45 4363 1678',\n '+45 1234 5678'\n ];\n\nTo apply the pattern to your script, just add:\n$elements[2] =~ s/^(.{8})/$1 /;\n\nor alternatively\nmy @chars = split//, $elements[2];\nsplice @chars, 8, 0, ' ';\n$elements[2] = join\"\", @chars;\n\nto alter phone numbers within your foreach loop.\n\nA: Here is a more idiomatic version of your program.\nuse strict;\nuse warnings;\n\nmy $inputfile = shift || die \"Need input and output file names!\\n\";\nmy $outputfile = shift || die \"Need an output file name!\\n\";\n\nopen my $INFILE, '<', $inputfile or die \"Bestand niet gevonden :$!\\n\";\nopen my $OUTFILE, '>', $outputfile or die \"Bestand niet gevonden :$!\\n\";\n\nmy $i = 0;\n\nwhile (<$INFILE>) {\n # print; # for debugging\n s/\"//g;\n my @elements = split /;/, $_;\n print join \"%\", @elements;\n $elements[2] =~ s/^(.{8})/$1 /;\n my $output_line = join(\";\", @elements);\n print $OUTFILE $output_line;\n $i = $i+1;\n}\n\nclose $INFILE;\nclose $OUTFILE;\n\nexit 0;\n\n\nA: use substr on left hand side:\nuse strict;\nuse warnings;\n\nwhile () {\n my @elements = split /;/, $_;\n substr($elements[2], 8, 0) = ' ';\n print join(\";\", @elements);\n}\n\n__DATA__\ncol1;col2;+45 23455678\ncol1;col2;+45 12314425\ncol1;col2;+45 43631678\ncol1;col2;+45 12345678\n\noutput:\ncol1;col2;+45 2345 5678\ncol1;col2;+45 1231 4425\ncol1;col2;+45 4363 1678\ncol1;col2;+45 1234 5678\n\n\nA: Perl one liner which you can use for multiple .csv files also.\nperl -0777 -i -F/;/ -a -pe \"s/(\\+45\\s\\d{4})(\\d+.*?)/$1 $2/ for @F;$_=join ';',@F;\" s_infile.csv\n\n\nA: This is the basic gist of how its done. The \"prefix\" to the numeric string is \\+45, which is hard coded, and you may change it as needed. \\pN means numbers, {4} means exactly 4.\nuse strict;\nuse warnings;\n\nwhile () {\n s/^\\+45 \\pN{4}\\K/ /;\n print;\n}\n\n__DATA__\n+45 234556780\n+45 12314425\n+45 436316781\n+45 12345678\n\nYour code has numerous other problems:\nYou do not use use strict; use warnings;. This is a huge mistake. It's like riding a motorcycle and protecting your head by putting on a blindfold instead of a helmet. Often, it is an easy piece of advice to overlook, because it is explained very briefly, so I am being more verbose than I have to in order to make a point: This is the most important thing wrong. If you miss all the rest of your errors, it's better than if you miss this part.\n\nYour open statements are two-argument, and you do not verify your arguments in any way. This is very dangerous, because it allows people to perform arbitrary commands. Use the three-argument open with a lexical file handle and explicit MODE for open:\nopen my $in, \"<\", $inputfile or die $!;\n\n\nYou slurp the file into an array: @infile= The idiomatic way to read a file is:\nwhile (<$in>) { # read line by line\n ...\n}\n\nWhat's even worse, you loop with foreach (@infile), but refer to $infile[$i] and keep a variable counting upwards in the loop. This is mixing two styles of loops, and even though it \"works\", it certainly looks bad. Looping over an array is done either:\nfor my $line ( @infile ) { # foreach style\n $line =~ s/\"//g;\n ...\n}\n\nfor my $index ( 0 .. $#infile ) { # array index style\n $infile[$index] =~ ....\n}\n\nBut neither of these two loops are what you should use, since the while loop above is much preferred. Also, you don't actually have to use this method at all. The *nix way is to supply your input file name or STDIN, and redirect STDOUT if needed:\nperl script.pl inputfile > outputfile\n\nor, using STDIN\nsome_command | perl script.pl > outputfile\n\nTo achieve this, just remove all open commands and use \nwhile (<>) { # diamond operator, open STDIN or ARGV as needed\n ...\n}\n\n\nHowever, in this case, since you are using CSV data, you should be using a CSV module to parse your file:\nuse strict;\nuse warnings;\nuse ARGV::readonly; # safer usage of @ARGV file reading\n\nuse Text::CSV;\n\nmy $csv = Text::CSV->new({\n sep_char => \";\",\n eol => $/,\n binary => 1,\n });\n\nwhile (my $row = $csv->getline(*DATA)) { # read input line by line\n if (defined $row->[1]) { # don't process empty rows\n $row->[1] =~ s/^\\+45 *\\pN{4}\\K/ /;\n }\n $csv->print(*STDOUT, $row);\n}\n\n__DATA__\nfooo;+45 234556780;bar\n1231;+45 12314425;\noh captain, my captain;+45 436316781;zssdasd\n\"foo;bar;baz\";+45 12345678;barbarbar\n\nIn the above script, you can replace the DATA file handle (which uses inline data) with ARGV, which will use all script argument as input file names. For this purpose, I added ARGV::readonly, which will force your script to only open files in a safe way.\nAs you can see, my sample script contains quoted semi-colons, something split would be hard pressed to handle. The specific print statement will enforce some CSV rules to your output, such as adding quotes. See the documentation for more info.\n\nA: To add a space after the eighth character of a string you can use the fourth parameter of substr.\nsubstr $string, 8, 0, ' ';\n\nreplaces a zero-length substring starting at offset 8 with a single space.\nYou may think it's safer to use regular expressions so that only data in the expected format is changed\n$string =~ s/^(\\+\\d{2} \\d{4})/$1 /;\n\nor\n$str =~ s/^\\+\\d{2} \\d{4}\\K/ /;\n\nwill achieve the same thing, but will do nothing if the number doesn't look as it should beforehand.\nHere is a reworking of your program. Most importantly you should use strict and use warnings at the start of your program, and declare variables with my at the point of their first use. Also use the three-paramaeter form of open and lexical filehandles. Lastly it is best to avoid reading an entire file into an array when a while loop will let you process it a line at a time.\nuse strict;\nuse warnings;\n\n@ARGV == 2 or die \"Usage: $0 input-file output-file\\n\";\n\nmy ($inputfile, $outputfile) = @ARGV;\n\nopen my $in, '<', $inputfile or die \"Bestand niet gevonden: $!\";\nopen my $out, '>', $outputfile or die \"Bestand niet gevonden: $!\";\n\nwhile (<$in>) {\n tr/\"//d; \n my @elements = split /;/;\n substr $elements[2], 8, 0, ' ';\n print $out join ';', @elements;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/11099174\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23020,"cells":{"text":{"kind":"string","value":"Q: DOM reload after ajax form injection Ive tried similar questions to no avail.\nMy question is simply how to reload the DOM after an ajax request has been made?\nIts not a question regarding event delegation, rather one concerning jquery selectors.\nsample:\neditUser : function(){\n var editItem = $(\"a.edit\");\n\n\n editItem.on('click', function(e){\n e.preventDefault();\n\n //click the users tab & the edit tab\n var usersjq = $(\"li#users-jq\");\n usersjq.find(\"a\").eq(0).click();\n $(\"ul.tabs\").find(\"a\").eq(2).click();\n\n\n var uid = $(this).attr('id').split('_')[1];\n $(\".three #users-edit\").empty();\n\n $(\".three #users-edit\").load(BASE_PATH + 'users/admin/users/edit/' + uid, function(){\n //loads a form with id of #form-users-edit\n\n }, 'html');\n\n\n\n });\n },\nformEditUsers : function(){\n\n //#form-users-edit is not selectable\n\n //all of these just return jQuery ( ) \n console.log($(\".three #users-edit\").find(\"#form-users-edit\"));\n console.log($(document.forms));\n console.log($(\"form#form-users-edit\"));\n\n }\n\nRegards.\n\nA: Passing formEditUsers() into the ajax success callback seems to work fine.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/9270403\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23021,"cells":{"text":{"kind":"string","value":"Q: Not full binding in knockout Knockout doesn't work as expected, im my interface.\nI suppose my mistake. But I cannot understand it.\nI have an album with genres included tracks with genres:\nvar initialData = [{\n title: 'Danny',\n genres: [\n {id: 21,\n title: 'Noise'},\n {id: 22,\n title: 'EBM'}],\n tracks: [\n {title: 'Pony',\n genres: [\n {id: 21,\n title: 'Noise'},\n {id: 22,\n title: 'EBM'}]},\n {title: 'Hungry',\n genres: [\n {id: 21,\n title: 'Noise'},\n {id: 22,\n title: 'EBM'}]}\n ]\n\n}];\n\nI want to create 1-way sync between album genres to tracks genres:\n\n\n*\n\n*If i add genre to album, this genre would be added to all tracks.\n\n*If i delete genre from album, this genre would be deleted from all tracks.\n\n*If i add genre to track, this genre would be added only to this track.\n\n*If i delete genre from track, this genre would be deleted only from this track.\n\n\nMy sync works fine (except one case) with this functions:\nself.addGenre = function(album) {\n var id = rand(),\n item = {\n id: id,\n title: ' genre #' + id\n };\n album.genres.push(item);\n\n if (album.tracks()) {\n $.each(album.tracks(), function (index, track) {\n track.genres.push(item);\n });\n }\n};\n\nself.removeGenre = function(genre) {\n $.each(self.albums(), function() {\n this.genres.remove(genre);\n if (this.tracks()) {\n $.each(this.tracks(), function (index, track) {\n track.genres.remove(genre);\n });\n }\n });\n};\n\nException is if I want to delete default (Noise, EBM, see initialData above ) genre from albums. it doesn't work.\nI created an jsFiddle to show this case and include in it a lot of console.log() to debug\n\nA: The problem is that when you use ko-mapping, it turns every property into an observable. The new genres you create are not the same kind of object as the initial objects, because they are just standard vanilla objects. So the genre you are trying to remove from the track is not the same one you removed from the album.\nA simple way to fix your issue is to alter the remove function, as in this fiddle.\n$.each(this.tracks(), function(index, track) {\n var toRemove = ko.utils.arrayFirst(track.genres(), function(item) {\n return ko.utils.unwrapObservable(genre.id) == ko.utils.unwrapObservable(item.id);\n });\n track.genres.remove(toRemove);\n});\n\nA better way would be to be a little more thorough in generating your initial viewmodel, the new genres, or both. This won't be easy.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/13171144\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23022,"cells":{"text":{"kind":"string","value":"Q: Transitioning Between Index Paths in a DetailViewController? Swift So using the code below, I've segued my CollectionViewCell indexPath into the new DetailViewController. now each `DetailViewController displays what is contained in the array of the indexPath selected.\nfunc collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {\n\n let animal: Animal!\n let anims: [Animal] = dataSource.anims\n\n animal = anims.filter{ $0.isDefault }[indexPath.row]\n\n DispatchQueue.main.async {\n self.performSegue(withIdentifier: \"DetailVC\", sender: animal)\n }\n}\n\nSo that means the new DetailVCwill be able to pull the data from the array that corresponds with the selected indexPath.row, which it does.\nNow here's the issue. Once I'm in the DetailVC, I want to make a button that lets me switch the displayed data to the previous or next indexPath.row. To explain it better, below is some Pseudo-Code that explains what I'm trying to do\n@IBAction func nextIndex(_ sender: Any) {\n self.view.indexPath.row = self.view.indexPath.row +1\n or\n self.datasource = next datasource index\n}\n\nNow what would I need to do to transition between these indexPaths from inside the DetailViewController? Such as a \"go to next\" or \"go to previous\" or \"go to [selected path]\" button?\nI feel there may be a simple answer to this that I'm not getting.\n\nA: Easy solution: You can implement singleton, manager that will be responsible for this. e.g. \nclass AnimalManager: NSObject {\n\n static let shared = AnimalManager()\n\n private var animals = [Animal]()\n private var currentIndex: Int?\n\n .....\n}\n\nNow you can implement such methods like: current animal, next animal, revious, etc.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/41434270\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23023,"cells":{"text":{"kind":"string","value":"Q: Colour newly added bar in bar chart automatically when new data is received Following code basically put a colour in my bar graph based on cell D112 value. Now is there a way to automatically put colour as new data is available and new bar is added to my bar chart? For example, Cell D112 is the value for the month of Jan, now when i get value in cell D113 for the month of Feb, how do i colour the bar of that month automatically? I'm guessing there has to be some kind of a loop here right?\nSub ColorGraphs()\n\nDim ChrtObj As ChartObject\nDim Ser As Series\nDim SerPoint As Point\n\n\nSet ChrtObj = ActiveSheet.ChartObjects(\"Chart 18\")\n\n\nSet Ser = ChrtObj.Chart.SeriesCollection(1)\n\n\nSet SerPoint = Ser.Points(3)\n\n\nWith SerPoint.Format.Fill\n .Visible = msoTrue\n .Transparency = 0\n .Solid\nEnd With\n\nSelect Case Range(\"D112\").Value\n Case Is < 0.96\n SerPoint.Format.Fill.ForeColor.RGB = RGB(204, 0, 51)\n Range(\"P8\").Interior.Color = RGB(204, 0, 51)\n\n Case 0.96 To 0.98\n SerPoint.Format.Fill.ForeColor.RGB = RGB(255, 102, 0)\n Range(\"P8\").Interior.Color = RGB(255, 102, 0)\n\n Case Else ' larger than 0.98\n SerPoint.Format.Fill.ForeColor.RGB = RGB(0, 153, 102)\n Range(\"P8\").Interior.Color = RGB(0, 153, 102)\n\nEnd Select\n\nEnd Sub\n\n\nA: Try putting your code in Private Sub Worksheet_Change(ByVal Target as Range).\nThis Sub runs te code every time a cell is changed.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/49498952\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23024,"cells":{"text":{"kind":"string","value":"Q: Is there a data structure for a list ordered by value? I've got a JTable which shows the top 10 scores of a game. The data structure looks like the following:\n // {Position, Name, Score}\nObject[][] data = {\n {1, \"-\", 0},\n {2, \"-\", 0},\n {3, \"-\", 0},\n {4, \"-\", 0},\n {5, \"-\", 0},\n {6, \"-\", 0},\n {7, \"-\", 0},\n {8, \"-\", 0},\n {9, \"-\", 0},\n {10, \"-\", 0}\n};\n\nI want to be able to add a new score to this array in the correct order (so if it was the 3rd highest, it would be put at index 2). I'll then truncate this list down to the top 10 again and update the table.\nI know this is trivial to do by looping through and checking, but I'd like to know if there is an appropriate data structure that is better suited for data ordered by a value? Or is the simple two-dimensional array the only/best?\n\nA: Use a TreeSet with a custom comparator.\nAlso, you should not work with Multi-dimensional arrays, use Maps (Name -> Score) or custom Objects\n\nA: Hey, if your array is sorted, u can use the Collections.binarySearch() or Arrays.binarySearch() method to guide u at what index to make the insertion. The way these method work is to make a binary search after an existing element, and if the element cannot be found in the collection it will return a value related to the insertion point.\nMore info here Collections.binarySearch\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/5384093\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23025,"cells":{"text":{"kind":"string","value":"Q: How to validate status code in robot framework i about to make a validation status code in robot framework. i create value in json with wrong password and i want to make validation code 400 bad request with this code.\nlogin_negative_user\n\n${json} Load JSON From File ${CURDIR}/../json/negativeuser.json\n# Set Test Variable ${JSON_SCHEMA} ${json}\n${resp}= POST ${base_url}/horde/v1/auth/login json=${json}\n${data} Convert To String ${resp.json()}\nStatus Should Be 400 ${resp}\nShould Be Equal As Strings ${resp.status_code} 400\n${jsondata} evaluate ${data}\n${poselang}= Set Variable ${jsondata['data']['token']}\n\nSet Global Variable ${poselang}\nlog to console Get poselang token\n\nBut my log is this\nlogin negativeuser | FAIL |\n\nHTTPError: 400 Client Error: Bad Request for url: {secret api}\nam i wrong to make validation with that code? sorry i cant tell the api because it is secret\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/72373112\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23026,"cells":{"text":{"kind":"string","value":"Q: Is there a way to rename a similarly named column from two tables when performing a join? I have two tables that I am joining with the following query...\nselect * \n from Partners p \ninner join OrganizationMembers om on p.ParID = om.OrganizationId \nwhere om.EmailAddress = 'my_email@address.com' \n and om.deleted = 0\n\nWhich works great but some of the columns from Partners I want to be replaced with similarly named columns from OrganizationMembers. The number of columns I want to replace in the joined table are very few, shouldn't be more than 3. \nIt is possible to get the result I want by selectively choosing the columns I want in the resulting join like so...\nselect om.MemberID, \n p.ParID, \n p.Levelz, \n p.encryptedSecureToken, \n p.PartnerGroupName, \n om.EmailAddress, \n om.FirstName, \n om.LastName \n from Partners p \ninner join OrganizationMembers om on p.ParID = om.OrganizationId \n where om.EmailAddress = 'my_email@address.com' \n and om.deleted = 0\n\nBut this creates a very long sequence of select p.a, p.b, p.c, p.d, ... etc ... which I am trying to avoid.\nIn summary I am trying to get several columns from the Partners table and up to 3 columns from the OrganizationMembers table without having a long column specification sequence at the beginning of the query. Is it possible or am I just dreaming?\n\nA: select om.MemberID as mem\n\nUse th AS keyword. This is called aliasing.\n\nA: Try this:\np.*,\nom.EmailAddress, \nom.FirstName, \nom.LastName \n\nYou should never use * though. Always specifying the columns you actually need makes it easier to find out what happens.\n\nA: You are dreaming in your implementation.\nAlso, as a best practice, select * is something that is typically frowned upon by DBA's.\nIf you want to limit the results or change anything you must explicitly name the results, as a potential \"stop gap you could do something like this.\nSELECT p.*, om.MemberId, etc..\n\nBut this ONLY works if you want ALL columns from the first table, and then selected items.\n\nA: \nBut this creates a very long sequence\n of select p.a, p.b, p.c, p.d, ... etc\n ... which I am trying to avoid.\n\nDon't avoid it. Embrace it!\nThere are lots of reasons why it's best practice to explicity list the desired columns.\n\n\n*\n\n*It's easier to do searches for where a particular column is being used.\n\n*The behavior of the query is more obvious to someone who is trying to maintain it.\n\n*Adding a column to the table won't automatically change the behavior of your query.\n\n*Removing a column from the table will break your query earlier, making bugs appear closer to the source, and easier to find and fix.\n\n\nAnd anything that uses the query is going to have to list all the columns anyway, so there's no point being lazy about it!\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/2418528\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":23027,"cells":{"text":{"kind":"string","value":"Q: can not read some string from struts.properties I have define variable error in struts.properties as follows:\nerror=this is an error\n\nNow I can call this error as follows:\nErrorMsg = \"\";\n\nand it works, the result is: ErrorMsg=this is an error\nHow to get the text of variable instead of string?\nI tried the following: \nvar m=\"error\";\n error1 = \"\";\n error2 = \"\";\n\nI use firebug debugger and error1 and error2 are displyed as follows:\nerror1=\"\"\nerror2=\"\"\n\nAny Idea?\nthank you in advance\n\nA: You appear to be mixing server side and client side code. \nThe s:property tags will be evaluated first on the server side, long before any value of m is valid, as that is client side JavaScript code.\nIf you post what you're trying to achieve then I or someone else may be able to help further.\nHTH\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/10020352\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23028,"cells":{"text":{"kind":"string","value":"Q: 'boost/multi_array.hpp' file not found error while building on Mac I am trying to build using Cmake on macOS Big Sur. Following is the makefile.\nCMAKE_MINIMUM_REQUIRED(VERSION 3.5)\n\n#------------------------------------------------------------------------------#\n# Compiler setup\n#------------------------------------------------------------------------------#\n\nIF(CMAKE_SYSTEM_NAME=Windows)\n SET(ADDITIONAL_FLAGS \"-DWIN32\")\nENDIF(CMAKE_SYSTEM_NAME=Windows)\n\nSET(CMAKE_CXX_COMPILER \"g++\")\nSET(CMAKE_CXX_FLAGS \"-std=c++17 -g -Wall -Wno-uninitialized\")\nSET(CMAKE_CXX_FLAGS_DEBUGALL \"${CMAKE_CXX_FLAGS} -fsanitize=address,undefined -pthread\" )\nSET(CMAKE_CXX_FLAGS_DEBUG \"${CMAKE_CXX_FLAGS} -O3 -DOPTIMIZE -pthread\" ${ADDITIONAL_FLAGS} )\nSET(CMAKE_CXX_FLAGS_RELEASE \"${CMAKE_CXX_FLAGS} -O3 -DNDEBUG -DOPTIMIZE -pthread\" ${ADDITIONAL_FLAGS} )\nSET(CMAKE_CXX_FLAGS_RELWITHDEBINFO \"${CMAKE_CXX_FLAGS} -O3 -g -DNDEBUG -DOPTIMIZE -pthread\" ${ADDITIONAL_FLAGS} )\n\n#SET(CMAKE_BUILD_TYPE Debug)\nIF(NOT CMAKE_BUILD_TYPE)\n SET(CMAKE_BUILD_TYPE Release CACHE STRING \"Choose the type of build: Debug Release RelWithDebInfo\" FORCE)\nENDIF(NOT CMAKE_BUILD_TYPE)\n\n#------------------------------------------------------------------------------#\n# Required libraries\n#------------------------------------------------------------------------------#\n\nSET(Boost_DEBUG \"ON\")\nSET(Boost_USE_STATIC_LIBS \"ON\")\nSET(HOME_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL \"\")\nSET(CMAKE_MODULE_PATH ${HOME_DIR}/CMake)\n\nFIND_PACKAGE(Boost COMPONENTS filesystem program_options timer chrono REQUIRED)\nSET(EXTERNAL_INCLUDES ${Boost_INCLUDES})\nSET(EXTERNAL_LIBRARIES ${Boost_LIBRARIES})\n\nFIND_PACKAGE(Eigen3 3.3.4)\nINCLUDE_DIRECTORIES(${EIGEN3_INCLUDE_DIRS})\n\n#------------------------------------------------------------------------------#\n# Directories for compiled libraries\n#------------------------------------------------------------------------------#\n\nINCLUDE_DIRECTORIES(src/Mesh)\nINCLUDE_DIRECTORIES(src/Quadrature)\nINCLUDE_DIRECTORIES(src/Common)\nINCLUDE_DIRECTORIES(src/HybridCore)\nINCLUDE_DIRECTORIES(src/Plot)\nINCLUDE_DIRECTORIES(src/DDRCore)\n\nADD_SUBDIRECTORY(src/Mesh)\nADD_SUBDIRECTORY(src/Quadrature)\nADD_SUBDIRECTORY(src/Common)\nADD_SUBDIRECTORY(src/HybridCore)\nADD_SUBDIRECTORY(src/Plot)\nADD_SUBDIRECTORY(src/DDRCore)\n\n#------------------------------------------------------------------------------#\n# Directories for schemes\n#------------------------------------------------------------------------------#\n\nINCLUDE_DIRECTORIES(Schemes)\nADD_SUBDIRECTORY(Schemes)\n\nWhile running make command I am getting\nfatal error: 'boost/multi_array.hpp' file not found\n#include \n\nI have boost installed with the help of brew. I also tried this https://stackoverflow.com/a/32929012/8499104 to verify my path is correct. Still not able to figure out why this is not able to find this library.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/69711110\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23029,"cells":{"text":{"kind":"string","value":"Q: Redirecting in react-router-dom v6 in a non-JSX context I'm trying to redirect a user from the route they are currently looking at to another route programatically. In my case, I am not in a JSX environment, and cannot use any kind of React hooks. How would I go about this?\nI tried to use the code block below to redirect (tried using JSX), only to realize that it wouldn't work as it isn't in the context of the root router.\nReactDOM.render(
\n \n
, document.getElementById(\"redirect\"));\n\nI also want to try and redirect without using window.location.href = as that would cause the whole page to refresh, something I don't want to happen.\nEDIT: As requested, I am trying to redirect to a page from an event that is emitted by Tauri and is handled by some TypeScript code on the front end. Using window.location.href isn't an issue in any case.\nHere is an example of what I'm trying to do:\n/**\n * Sets up event listeners.\n */\nexport async function setupListeners() {\n console.log(\"Setting up link event listeners...\");\n await listen(\"deeplink\", onLinked);\n}\n \n/**\n * Invoked when a deep link call is received.\n * @param event The event.\n */\nasync function onLinked(event: Event) {\n const { payload } = event;\n if (payload == \"test:\")\n // redirect(\"/testPage\");\n}\n\n\nA: See redirect:\nimport { redirect } from \"react-router-dom\";\n\nconst loader = async () => {\n const user = await getUser();\n if (!user) {\n return redirect(\"/login\");\n }\n};\n\n(from the docs)\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/75024625\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23030,"cells":{"text":{"kind":"string","value":"Q: How does Doctrine generate:entities create getters and setter in symfony I have class User likr this\nclass user implements UserInterface {\n\nprotected id ,\nprotected username;\n\nThen i have \nclass student extends user {\n\n\nprotected id ,\nprotected rollno;\n\nNow when i run this\nphp app/console doctrine:generate:entities myBundle\n\nThen propery username gets inserted in class student.\nI want to know that is this ok or its error. Because then whats the use of extending from base class if my lass is going to be populated with all stuff\n\nA: This isn't an error.\nSymfony threats all classes as entities and if you're \"mapping\" them with doctrine you'll create the corrisponding tables onto database.\nNow inheritance have to be taken into account: every \"field\" (property) into parent classe, will be extended or inherited by child.\nSo is perfectly clear that the corresponding parent field will be created into database. \nTo me the best way for solve this is to create a parent class and to migrate all commons (fields,methods and so on...) into it.\nThen, you'll extend that new parent calss into user with specific fields (in that case username) aswell into student with student's specific fields.\n\nA: Yeah, that's probably not an error, although I agree it can be annoying.\nTo see how exactly are they generated you can look into the command class.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/11464227\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23031,"cells":{"text":{"kind":"string","value":"Q: Double buffering with C# has negative effect I have written the following simple program, which draws lines on the screen every 100 milliseconds (triggered by timer1). I noticed that the drawing flickers a bit (that is, the window is not always completely blue, but some gray shines through). So my idea was to use double-buffering. But when I did that, it made things even worse. Now the screen was almost always gray, and only occasionally did the blue color come through (demonstrated by timer2, switching the DoubleBuffered property every 2000 milliseconds).\nWhat could be an explanation for this?\nusing System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1 {\n public partial class Form1 : Form {\n public Form1() {\n InitializeComponent();\n }\n\n private void Form1_Paint(object sender, PaintEventArgs e) {\n Graphics g = CreateGraphics();\n Pen pen = new Pen(Color.Blue, 1.0f);\n Random rnd = new Random();\n for (int i = 0; i < Height; i++)\n g.DrawLine(pen, 0, i, Width, i);\n }\n\n // every 100 ms\n private void timer1_Tick(object sender, EventArgs e) {\n Invalidate();\n }\n\n // every 2000 ms\n private void timer2_Tick(object sender, EventArgs e) {\n DoubleBuffered = !DoubleBuffered;\n this.Text = DoubleBuffered ? \"yes\" : \"no\";\n }\n }\n}\n\n\nA: I would just draw all of your items to your own buffer, then copy it all in at once. I've used this for graphics in many applications, and it has always worked very well for me:\n public Form1()\n {\n InitializeComponent();\n }\n private void timer1_Tick(object sender, EventArgs e)\n {\n Invalidate();// every 100 ms\n }\n private void Form1_Load(object sender, EventArgs e)\n {\n DoubleBuffered = true;\n }\n private void Form1_Paint(object sender, PaintEventArgs e)\n {\n Bitmap buffer = new Bitmap(Width, Height);\n Graphics g = Graphics.FromImage(buffer);\n Pen pen = new Pen(Color.Blue, 1.0f);\n //Random rnd = new Random();\n for (int i = 0; i < Height; i++)\n g.DrawLine(pen, 0, i, Width, i);\n BackgroundImage = buffer;\n }\n\nEDIT: After further investigation, it looks like your problem is what you're setting your Graphics object to:\nGraphics g = CreateGraphics();\n\nneeds to be:\nGraphics g = e.Graphics();\n\nSo your problem can be solved by either creating a manual buffer like I did above, or simply changing you Graphics object. I've tested both and they both work.\n\nA: Try setting the double buffered property to true just once in the constructor while you're testing.\nYou need to make use of the back buffer. Try this:\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace DoubleBufferTest\n{\n public partial class Form1 : Form\n {\n private BufferedGraphicsContext context;\n private BufferedGraphics grafx;\n\n public Form1()\n {\n InitializeComponent();\n\n this.Resize += new EventHandler(this.OnResize);\n DoubleBuffered = true;\n\n // Retrieves the BufferedGraphicsContext for the \n // current application domain.\n context = BufferedGraphicsManager.Current;\n\n UpdateBuffer();\n }\n\n private void timer1_Tick(object sender, EventArgs e)\n {\n this.Refresh();\n\n }\n\n private void OnResize(object sender, EventArgs e)\n {\n UpdateBuffer();\n this.Refresh();\n }\n\n private void UpdateBuffer()\n {\n // Sets the maximum size for the primary graphics buffer\n // of the buffered graphics context for the application\n // domain. Any allocation requests for a buffer larger \n // than this will create a temporary buffered graphics \n // context to host the graphics buffer.\n context.MaximumBuffer = new Size(this.Width + 1, this.Height + 1);\n\n // Allocates a graphics buffer the size of this form\n // using the pixel format of the Graphics created by \n // the Form.CreateGraphics() method, which returns a \n // Graphics object that matches the pixel format of the form.\n grafx = context.Allocate(this.CreateGraphics(),\n new Rectangle(0, 0, this.Width, this.Height));\n\n // Draw the first frame to the buffer.\n DrawToBuffer(grafx.Graphics);\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n grafx.Render(e.Graphics);\n }\n\n private void DrawToBuffer(Graphics g)\n {\n //Graphics g = grafx.Graphics;\n Pen pen = new Pen(Color.Blue, 1.0f);\n //Random rnd = new Random();\n for (int i = 0; i < Height; i++)\n g.DrawLine(pen, 0, i, Width, i);\n }\n }\n}\n\nIt's a slightly hacked around version of a double buffering example on MSDN.\n\nA: No need to use multiple buffers or Bitmap objects or anything.\nWhy don't you use the Graphics object provided by the Paint event? Like this:\nprivate void Form1_Paint(object sender, PaintEventArgs e)\n{\n Graphics g = e.Graphics;\n Pen pen = new Pen(Color.Blue, 1.0f);\n Random rnd = new Random();\n for (int i = 0; i < Height; i++)\n g.DrawLine(pen, 0, i, Width, i);\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/2566126\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":23032,"cells":{"text":{"kind":"string","value":"Q: OnNotifyPropertyChanged not firing get I have a class which has an ObservableCollection called Items. That list should fill up a RadGridView. Even though the OC contains data, the list stays empty, and after a bit of debuggingg I noticed it has some odd behavior. I have a breakpoint in the Get and Set of the property. First it hits the Get. Then the Set, but it never hits the Get again. Shouldn't the NotifyChanged also trigger the get after that then, so it updates the list in the view?\nHere is the code below of the class I am talking about:\npublic class PagedCollection where TEntity : class, INotifyPropertyChanged\n{\n internal WorkflowEntities Context;\n internal DbSet DbSet;\n\n private ObservableCollection _items;\n public ObservableCollection Items\n {\n get\n {\n return _items;\n }\n set\n {\n SetField(ref _items, value, nameof(Items));\n }\n }\n\n public PagedCollection()\n {\n Context = new WorkflowEntities();\n DbSet = Context.Set();\n }\n\n public virtual IEnumerable Get(Expression> filter = null,\n Func, IQueryable> query = null,\n string includeProperties = \"\")\n {\n IQueryable value = DbSet;\n\n if (filter != null)\n {\n value = value.Where(filter);\n }\n\n value = includeProperties.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Aggregate(value, (current, includeProperty) => current.Include(includeProperty));\n\n return query?.Invoke(value).ToList() != null ? query(value).ToList() : value.ToList();\n }\n\n // boiler-plate\n public event PropertyChangedEventHandler PropertyChanged;\n protected virtual void OnPropertyChanged(string propertyName)\n {\n PropertyChangedEventHandler handler = PropertyChanged;\n if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));\n }\n protected bool SetField(ref T field, T value, string propertyName)\n {\n if (EqualityComparer.Default.Equals(field, value)) return false;\n field = value;\n OnPropertyChanged(propertyName);\n return true;\n }\n}\n\nThe public virtual IEnumerable Get(...) is being triggered by another class, which fills up the Items. Like this: PagedCollection.Items = PagedCollection.Get();. This in turn fires the get, set, but not a get anymore, so my list stays empty in the view, even though there is data in PagedCollection.Items\n\nA: Your class, PagedCollection, doesn't implement INotifyPropertyChanged.\npublic class PagedCollection where TEntity : class, INotifyPropertyChanged\n\nWhat this says is that TEntity must be a class and implement INotifyPropertyChanged.\nTry this instead:\npublic class PagedCollection : INotifyPropertyChanged where TEntity : class, INotifyPropertyChanged\n\n\nA: You can't call PagedCollection.Get(); like that you have to instantiate something.\n\nA: A change in a property of an object within a regular ObservableCollection does not trigger the CollectionChanged event. \nMaybe you could use the TrulyObservableCollection class, derived from the former:\nObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)\n\nA: One thing is the ObservableCollection property itself.\nWhen you run the program, it is get once when the view is loaded, and it is set once when you first initialize that property.\nAfter that, when you populate the list, it's not the PropertyChanged event that is fired, since it would be fired only if you assign the whole OC property to another value (usually via Items = new ObservableCollection());\nThus, the event you should be watching is CollectionChanged, which is fired every time you add, remove, swap or replace elements.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/41855741\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23033,"cells":{"text":{"kind":"string","value":"Q: How can I color a graph (vertices and edges) with excel data? I'm have an excel file with mostly 0's and 1's and I want to use this information to color the vertices and edges of a graph. So like if a cell is 0, color the edge gray, but if the cell is 1, color it blue. And similarly for vertices.\nCan anyone give me a suggestion for how to go about this? What should I use to make the graph? And how do I tell it how to color it?\nTHANKS!\n\nA: Try using D3 graph. Visit https://d3js.org/ \nD3 uses javascript language. You can refer to multiple graphs. \nEven you can take input data from excel file to create dynamic graphs.\nYou can refer to D3 network graph to understand how to change colour of vertex and edges of graph from given data http://christophergandrud.github.io/d3Network/ \n\nA: If you have the x and y values you can plot them directly on a worksheet. The following is an example that randomly generates x and y coordinates for 5 points. A small filled circle is drawn at each point. A line is drawn between the previous and the next point forming a closed loop.\nTo demonstrate how you can select the line colors I alternately color them gray and blue to give you an idea of how to selectively color them based on some other criteria.\nvbBlue is one of a preset color pallet (see this link) which is why it doesn't have to be declared - unlike vbGray.\nOption Explicit\n\n\nSub drawALine(xFrm As Double, yFrm As Double, xTo As Double, yTo As Double, c As Long)\n With ActiveSheet.Shapes.AddLine(xFrm, yFrm, xTo, yTo).Line\n .DashStyle = msoLineDashDotDot\n .ForeColor.RGB = c\n End With\nEnd Sub\n\n\nSub drawNode(r As Double, x As Double, y As Double, c As Long)\n With ActiveSheet.Shapes.AddShape(msoShapeOval, x - r / 2, y - r / 2, r, r)\n .Fill.ForeColor.RGB = c\n End With\nEnd Sub\n\n\nSub ConnectedOverLappingLoop()\n Dim xMax As Double, yMax As Double, x1 As Double, y1 As Double\n Dim xFrm As Double, yFrm As Double, xTo As Double, yTo As Double\n Dim radius As Double\n Dim vbGray As Long, clr As Long\n\n xMax = 200\n yMax = 200\n radius = 5\n vbGray = RGB(150, 150, 150)\n\n xFrm = Rnd() * xMax\n yFrm = Rnd() * yMax\n x1 = xFrm\n y1 = yFrm\n clr = vbBlue\n\n drawNode radius, x1, y1, vbBlue\n\n Dim i As Integer\n For i = 1 To 5:\n xTo = Rnd() * xMax\n yTo = Rnd() * yMax\n\n drawNode radius, xTo, yTo, vbBlue\n drawALine xFrm, yFrm, xTo, yTo, clr\n xFrm = xTo\n yFrm = yTo\n\n If clr = vbBlue Then\n clr = vbGray\n Else\n clr = vbBlue\n End If\n\n Next\n drawALine xFrm, yFrm, x1, y1, clr\n\nEnd Sub\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/43160006\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":23034,"cells":{"text":{"kind":"string","value":"Q: PHP sanitization question I was wondering how would you sanitize the $_SERVER['REQUEST_URI'], $_POST['email'] and $url code in the code snippets below using PHP.\nI'm using PHP Version 5.2.14\nCode Snippets.\n
\">\n
\n\n$email = $_POST['email']; //Grabs the email address\n\n$page_url = $url; //Grabs the pages url address.\n\n\nA: Use filter_var functions.\n // url\n filter_var($url, FILTER_VALIDATE_URL)\n // email\n filter_var('me@example.com', FILTER_VALIDATE_EMAIL)\n\n\nA: Except in some very particular cases you should never 'sanitize' input - only ever validate it. (Except in the very particular cases) the only time you change the representation of data is where it leaves your PHP - and the method should be appropriate to where the data is going (e.g. htmlentities(), urlencode(), mysql_real_escape_string()....).\n(the filter functions referenced in other posts validate input - they don't change its representation)\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/4343825\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23035,"cells":{"text":{"kind":"string","value":"Q: How does Nutch's plug-in system work? I am new to Nutch, but I know Nutch uses Lucene for indexing, which only understands text format.\nNutch has many plug-ins that are used for crawling documents with a particular format.\nMy doubt is: how does actually the Nutch plug-in system?\nI seen the Team wiki page for nutch\nI'd like some information like how actually Nutch works with Lucene.\n\nA: All Lucene does is provide a way for \"Documents\" to be added into a structured index and for queries to be executed against that index.\nThe Nutch crawler (I assume that's what you mean by nutch) just provides an easy way to get unstructured data (ie a website) to get pushed into the index. Just like you can use Solr to easily push xml data into a lucene index.\nNutch plugins simply provide a hook were you can put customer logic. For instance the \"parse-pdf\" can convert a binary PDF file into one of these \"lucene Documents\". Basically all it does is use an API that can read PDF documents (pdfbox) to extract the text (this is similar to what \"parse-html\" does since html has a lot of parts that isn't text, for example all html tags).\nSo regarding your concern about binary formats, its not difficult to parse, just difficult to get something useful. For instance we can write a \"parse-image\" plugin that could extract a lot of info about the image (ie name, format, size), it's just that parsing the \"face\" or the \"dog\" in the picture is difficult.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/1448329\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23036,"cells":{"text":{"kind":"string","value":"Q: Convert Raw png data to a usable img src in javascipt Getting raw png data from an api I am using, from the docs it is supposedly base64 png but it does not look like it to me. The data comes back in either of 2 forms\nPNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00�%00%00%00�%08%06%00%00%00=�%062%00%00%00%09pHYs%00%00%0E�%00%00%0E�%01�+%0E%1B%00%00 %00IDATx%01%00��q~%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00\n\nor like\nPNG IHDR��=�2 pHYs���+ IDATx��q~J@7J@7�ɭ� IDATJ@72.*D2.*D������'$ �2-($J@7����.)&j��������6 6��n����J@7����(%!R���M���H� ���$�������N�����>�0����J����M+(���������J@7����/*&���< ���\"������ ����������� ��� ����\"�D#!-����2-\n\ncould someone help me identify what this is being returned, and how can I decode it to be used as a img src?\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/71025374\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23037,"cells":{"text":{"kind":"string","value":"Q: How to delete file and its folder if there is one, in shell? I have a shell script that is copying some files for a S3 bucket (aws) on local, then it is copying it to another place (it cannot do it directly, because of some authorization), but the idea is that the image may be in some folder and the shell is creating it locally, but it is deleting just the image and I found that after execution I have some empty folders. So my question is how to delete the folder too, if it is present in the name?\nMy shell part that copies and deletes:\naws s3 cp s3://$SRC_BUCKET/$PHOTO_NAME $PHOTO_NAME --profile $SRC_PROFILE\n# copy to other place\nrm $PHOTO_NAME # here PHOTO_NAME may have the parent folder in it (a.jpg, \n # or b/a.jpg) and I would like to delete the b folder too\n\n\nI have updated my code, based on the answer below, but it seems not to do what expected: the temporary directory is created, but all is done outside of it... My code looks like this:\ndir=\"$(mktemp aws-sync-XXXXX)\"\npushd \"$dir\"\nCOUNT=1\nuntil [ $COUNT -gt $MAX_COUNT ]; do\n aws s3 cp s3://$SRC_BUCKET/$PHOTO_NAME $PHOTO_NAME --profile $SRC_PROFILE\n # copy to other place\n rm $PHOTO_NAME\n\n (( MESSAGES_COUNT+=1 ))\n fi\ndone\npopd\nrm -rf \"$dir\"\n\n\nA: fundamentally, you're setting yourself up for some race conditions (what if the folder already existed, &c). A better way to do this is creating a fresh folder before you run this script, then run it inside there. So:\ndir=\"$(mktemp aws-sync-XXXXX)\"\npushd \"$dir\"\n\n# do stuff\n\npopd\nrm -rf \"$dir\"\n\nThat will ensure you delete everything your temporary command created, and nothing more.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/32780888\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23038,"cells":{"text":{"kind":"string","value":"Q: How do I authenticate using MSXML2.XMLHTTP and VBA? I need to authenticate on the endpoint https://graph.microsoft.com/v1.0/me/drive/root/children using MSXML2.XMLHTTP and VBA.\nI have the access token already but I am struggling to find out the string to be used on:\nsetRequestHeader method.\nThank you,\n\nA: After searching I found the solution:\nsetRequestHeader \"Authorization\", \"Bearer \" + accessToken\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/55767687\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23039,"cells":{"text":{"kind":"string","value":"Q: Rapid json, c++, json, modify empty json array I have a json file, which contains two object. The first object is an array of objects. Each of these objects has an element \"key\" and empty array. I need to fill the array with 4 numbers and I need to save back the json. I am checking the tutorial, but probably I am missing something. May somebody help me please?\nHere is my code, that doesn't work:\nvoid BimObjectsToProjection::modifyViewBoxForProjection(std::string projectionName, long long minX, long long minY, long long Xlen, long long Ylen)\n{\n Value& projections = md_FilesJsonDocument[\"ProjectionImages\"];\n for (Value::ValueIterator projectionsIterator = projections.Begin(); projectionsIterator != projections.End(); ++projectionsIterator)\n {\n rapidjson::Value& projectionJson = *projectionsIterator;\n string name = projectionJson[\"Name\"].GetString();\n if (projectionName == name)\n {\n Document::AllocatorType& allocator = md_FilesJsonDocument.GetAllocator();\n rapidjson::Value& viewBox = (*projectionsIterator)[\"BB\"];\n\n viewBox.PushBack((int)minX, allocator);\n viewBox.PushBack((int)minY, allocator);\n viewBox.PushBack((int)Xlen, allocator);\n viewBox.PushBack((int)Ylen, allocator);\n \n rapidjson::StringBuffer strbuf;\n rapidjson::Writer writer(strbuf);\n md_FilesJsonDocument.Accept(writer);\n break;\n }\n }\n}\n\nThe json looks like this:\n{\n \"ProjectionImages\": [\n {\n \"Id\": \"33c75d31-7ccd-4daf-814a-56250cdee42f\",\n \"Name\": \"Projection_Image_Architectural_First Floor_Zone 1.png\",\n \"Discipline\": \"Architectural\",\n \"LevelName\": \"First Floor\",\n \"BB\": [],\n \"SheetFileName\": null,\n \"ProjectionLineFileId\": \"36bb6683-c6d3-43c2-bbdc-aedf3203ea86\",\n \"ProjectionLineFileName\": \"Projection_Image_Architectural_First Floor_Zone 1.pdf\",\n \"ZoneName\": \"Zone 1\"\n },\n...\n\nEven if I try to add new array member, this code doesn't work. Is it because of my writing approch?\nvoid BimObjectsToProjection::modifyViewBoxForProjection(std::string projectionName, long long minX, long long minY, long long Xlen, long long Ylen)\n{\n Value& projections = md_FilesJsonDocument[\"ProjectionImages\"];\n for (Value::ValueIterator projectionsIterator = projections.Begin(); projectionsIterator != projections.End(); ++projectionsIterator)\n {\n rapidjson::Value& projectionJson = *projectionsIterator;\n string name = projectionJson[\"Name\"].GetString();\n if (projectionName == name)\n {\n Document::AllocatorType& allocator = md_FilesJsonDocument.GetAllocator();\n \n Value a(kArrayType);\n a.PushBack((int)minX, allocator);\n a.PushBack((int)minY, allocator);\n a.PushBack((int)Xlen, allocator);\n a.PushBack((int)Ylen, allocator);\n (*projectionsIterator).AddMember(\"AA\", a, allocator);\n \n rapidjson::StringBuffer strbuf;\n rapidjson::Writer writer(strbuf);\n md_FilesJsonDocument.Accept(writer);\n break;\n }\n }\n}\n\n\nA: This part of the code doesn't do anything:\nrapidjson::StringBuffer strbuf;\nrapidjson::Writer writer(strbuf);\nmd_FilesJsonDocument.Accept(writer);\n\nstrbuf contains the json string but it is discarded. I would move this into a separate function and print the conents with std::cout << strbuf;.\nTo write directly to a file:\nstd::ofstream ofs(\"out.json\", std::ios::out);\nif (ofs.is_open()) {\n rapidjson::OStreamWrapper osw(ofs);\n rapidjson::Writer writer(osw);\n md_FilesJsonDocument.Accept(writer);\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/65024226\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23040,"cells":{"text":{"kind":"string","value":"Q: jpegoptim: error creating temp file: mkstemps() failed jpegoptim gives me this error: error creating temp file: mkstemps() failed\njpegoptim -o *.jpg\nimage1.jpg 2000x1333 24bit P JFIF [OK] 442829 --> 451511 bytes (-1.96%), skipped.\nimage2.jpg 1500x1124 24bit P Exif XMP IPTC ICC JFIF [OK] 582748 --> 583528 bytes (-0.13%), skipped.\nimage3.jpg 2000x1501 24bit P Exif XMP IPTC ICC JFIF [OK] 630262 --> 634146 bytes (-0.62%), skipped.\nimage4.jpg 1620x846 24bit P JFIF [OK] 316664 --> 319702 bytes (-0.96%), skipped.\nimage5.jpg 1280x855 24bit N Exif XMP Adobe [OK] 66306 --> 66279 bytes (0.04%), optimized.\njpegoptim: error creating temp file: mkstemps() failed\n\n\nA: If you haven't figured out the issue yet, it's likely that you don't have write permissions to the directory the image is in.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/42972084\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":23041,"cells":{"text":{"kind":"string","value":"Q: speeding up (rewriting?) a not in sub select query From a table I'm trying to get \na) users who fulfil certain criteria which is held in a key/value combination in a table\nOR\nb) users who do not have that key/value combination at all\nSo, for example, to try and find users who live in France or who have not yet added their location, I'm using this (simplified) query:\nSELECT *\nFROM\n current_users\n JOIN current_users um_location ON current_users.id = um_location.id\nWHERE\n (\n ( um_location.meta_key = 'location' AND um_location.meta_value = 'France' )\n OR \n ( current_users.id NOT IN \n (SELECT current_users.id FROM current_users WHERE current_users.meta_key = 'location' ) \n )\n )\n\nThe problem is, of course, that running the OR sub-select query (if that's what it's called) is slowing down the query hugely. And since the full query has about 5 or 6 of these sub-selects, it's slowing things down far too much.\nIs there another way of doing this perhaps? A faster way?\n\nA: Change your OR condition as a UNION query instead of OR\nSELECT * FROM\n current_users\n JOIN current_users um_location ON current_users.id = um_location.id\nWHERE\n um_location.meta_key = 'location' AND um_location.meta_value = 'France' \nUNION\nSELECT * FROM\n current_users\n JOIN current_users um_location ON current_users.id = um_location.id\nWHERE\n current_users.id NOT IN \n (SELECT current_users.id FROM current_users WHERE \n current_users.meta_key='location' ) \n\n\nA: This should be the most succinct possible:\nSELECT *\nFROM current_users\nLEFT JOIN current_users AS um_location \n ON current_users.id = um_location.id\n AND um_location.meta_key = 'location' \nWHERE um_location.meta_value = 'France' \n OR um_location.meta_value IS NULL\n;\n\n...but as isaace answer hints, MySQL does not handle OR conditions ideally.\nSo, this might perform better.\nSELECT *\nFROM current_users\nLEFT JOIN current_users AS um_location \n ON current_users.id = um_location.id\n AND um_location.meta_key = 'location' \nWHERE um_location.meta_value = 'France' \nUNION\nSELECT *\nFROM current_users\nLEFT JOIN current_users AS um_location \n ON current_users.id = um_location.id\n AND um_location.meta_key = 'location' \nWHERE um_location.meta_value IS NULL\n;\n\n..but it will probably only make a difference if you have meta_value indexed; as the issue is that MySQL tends to ignore indexes when presented with OR.\n\nEdit: Due to the type of schema design begin used, there might be some weird issues with these queries using \"location\" entries as rows on the left side of the join; try this instead.\nSELECT *\nFROM current_users AS non_location\nLEFT JOIN current_users AS um_location \n ON current_users.id = um_location.id\n AND um_location.meta_key = 'location' \nWHERE non_location.meta_key != 'location'\n AND (um_location.meta_value = 'France' \n OR um_location.meta_value IS NULL\n )\n;\n\n\nA: First off, thank you both for your suggestions. Unfortunately I couldn't get them to work as the join\nLEFT JOIN current_users AS um_location \nON current_users.id = um_location.id\nAND um_location.meta_key = 'location'\n\ndid not return the records of those users who hadn't yet entered their location.\nHowever, after a lot of work I managed to solve the issue. It's not elegant but it works:\n\n\n*\n\n*Create a temporary table with a subset of the users who fulfil some basic criteria.\n\n*Do a simple INSERT IGNORE INTO ... SELECT DISTINCT ... FROM current_users adding in the missing 'location' with dummy information.\n\n\nThen the final query includes this:\num_location.meta_value = 'France'\nor\num_location.meta_value = 'dummyinfo'\n\nIt's not blisteringly fast but since this is a process which acts in the back end for admin users only they can afford to wait... ;)\nAgain, thanks for your help!\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/46060494\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23042,"cells":{"text":{"kind":"string","value":"Q: How to generate a QR code and a downloadable link in php I would like to create a program that generates a QR code based on a URL (data from a database).\nThe QR code will not be stored or saved, but only downloadable via a link on the page displaying the QR code.\nAll in PHP :)\nCould someone help me ?\nI haven't found my answer for the downloadable link :)\n\nA: This works for me in creating the QR code use API:-\nhttps://chart.googleapis.com/chart?chs=300x300&cht=qr&chl={data}\nIn place of data use the data which you want to convert into a QR code.\n\nCode:-\n
\n
\n';\n?>\n
\n
\n\n\n\nScript For the Downloading the QR code image:-\n\n`enter code here`\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/67456506\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23043,"cells":{"text":{"kind":"string","value":"Q: How do I create a circuit based on this truth table? So this is the truth table\n In_1 In_2 In_3 Out\n 0 0 0 0\n 0 0 1 1\n 0 1 0 1\n 0 1 1 1\n 1 0 0 1\n 1 0 1 1\n 1 1 0 1\n 1 1 1 0\n\nI would like to create a circuit based on this truth table.\nThis is what I have tried, but failed\n\n\nA: A Karnaugh map as suggested by paddy, will give you a set of minterms which fulfil the expression. That is the classical way to tackle such problems.\nBy inspection of the truth-table you can convince yourself, that the output is true whenever In_1 is unequal In_3 or In_1 is unequal In_2:\nf = (In_1 xor In_2) or (In_1 xor In_3)\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/74844748\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-1\"\n}"}}},{"rowIdx":23044,"cells":{"text":{"kind":"string","value":"Q: Woocommerce - Remove Only one Unit of a product from cart I am working on this woocommerce search function that uses AJAX to fetch products on every keystroke and that gives the possibility to add or remove units of a certain product to cart right from the instant search results modal.\nIn each search result there is this group of two buttons that allow the client to add 1 or remove 1 product from cart at a time. I managed to make the add to cart button work but can't seem to find a good solution to remove just one single unit from cart instead of all of them at once.\n\nI have tried this:\nfunction remove_product_from_cart_programmatically() {\n   if ( is_admin() ) return;\n   $product_id = 282;\n   $product_cart_id = WC()->cart->generate_cart_id( $product_id );\n   $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );\n   if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );\n}\n\nbut it removes all products with that ID at once.\nI want to be able to remove unit by unit in case there are items in cart with that ID.\nThis is the code I have right now for the remove from cart button:\nadd_action('wp_ajax_search_remove_from_cart', 'search_remove_from_cart');\nadd_action('wp_ajax_nopriv_search_remove_from_cart', 'search_remove_from_cart');\n\n// handle the ajax request\nfunction search_remove_from_cart()\n{\n $product_id = $_REQUEST['product_id'];\n WC()->cart->remove_cart_item($product_id);\n\n $products_in_cart = WC()->cart->get_cart_item_quantities($product_id);\n $updated_qty = $products_in_cart[$product_id];\n\n // in the end, returns success json data\n wp_send_json_success([\"Product removed from cart Successfuly!\", $updated_qty]);\n\n // or, on error, return error json data\n wp_send_json_error([\"Could not remove the product from cart\"]);\n}\n\nIs there any function to remove only one unit of a certain product from cart?\nThank you all !\n\nA: You have to change the quantity instead of removing the product. Number of product units in the cart = quantity.\nTry something like this:\nfunction remove_from_cart(){\n $product_id = 47;\n $cart = WC()->cart;\n $product_cart_id = $cart->generate_cart_id( $product_id );\n $cart_item_key = $cart->find_product_in_cart( $product_cart_id );\n if ( $cart_item_key ){\n $quantity = $cart->get_cart_item($cart_item_key)['quantity'] - 1;\n $cart->set_quantity($cart_item_key, $quantity);\n }\n}\n\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/74874720\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23045,"cells":{"text":{"kind":"string","value":"Q: Implementing a C++ calling convention in ASM x86 I've written a simple program that obfuscates a string using ASM x86. User must input their desired string, and then choose a key (Ekey) for the string to be obfuscated. (I know you can emulate left and right bit rotations with shift operators or table lookups, I'm just trying to familiarize myself with ASM)\nI'm trying to alter the program so that it adopts an accepted C++ standard calling procedure such as Cdecl for passing parameters (EKey & tempChar) into the sub-routine obfuscate.\nDespite numerous hours of research I've been unsuccessful so I have come here in hope that somebody with a little more experience would be kind enough to offer some guidance. \nHere's the relevant function:\nvoid obfusc_chars (int length, char EKey)\n{ char tempChar; // char temporary store\n\n for (int i = 0; i < length; i++) // encrypt characters one at a time\n {\n tempChar = OChars [i]; //\n __asm { //\n push eax // save register values on stack to be safe\n push ecx // pushes first string on stack\n //\n movzx ecx,tempChar // set up registers (Nb this isn't StdCall or Cdecl)\n lea eax,EKey //\n call obfuscate // obfuscate the character\n mov tempChar,al //\n //\n pop ecx // restore original register values from stack\n pop eax //\n }\n EChars [i] = tempChar; // Store encrypted char in the encrypted chars array\n }\n return;\n\nAnd the obfuscate subroutine:\n// Inputs: register EAX = 32-bit address of Ekey,\n// ECX = the character to be encrypted (in the low 8-bit field, CL).\n\n// Output: register EAX = the encrypted value of the source character (in the low 8-bit field, AL).\n\n __asm {\n\n obfuscate: push esi\n push ecx\n mov esi, eax\n and dword ptr [esi], 0xFF\n ror byte ptr [esi], 1\n ror byte ptr [esi], 1\n add byte ptr [esi], 0x01\n mov ecx, [esi]\n pop edx\n x17:ror dl, 1\n dec ecx\n jnz x17\n mov eax, edx\n add eax, 0x20\n xor eax, 0xAA\n pop esi\n ret\n }\n\nThanks in advance for taking the time to read. \n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/29729208\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23046,"cells":{"text":{"kind":"string","value":"Q: not getting radiobutton 'value' from other function(def) in tkinter, how to achieve this without using class? Not getting radiobutton 'value' from other function(def) in tkinter, how to achieve this without using class?\nIn this case a=a1.get() is not taking value from command (of sub1 button) in ques1() function.\nfrom tkinter import *\nglobal root\nroot=Tk()\nroot.geometry(\"500x500\")\na1=StringVar()\nans1=StringVar()\n\ndef ans1():\n a=a1.get() #not getting it from ques1()\n print(a)\n\ndef ques1():\n root.destroy()\n global window1\n window1=Tk()\n window1.geometry(\"500x500\")\n question1=Label(window1, text=\"How many Planets are there in Solar System\").grid()\n q1r1=Radiobutton(window1, text='op 1', variable=a1, value=\"correct\").grid()\n q1r2=Radiobutton(window1, text='op 2', variable=a1, value=\"incorrect\").grid()\n sub1=Button(window1, text=\"Submit\", command=ans1).grid()\n next1But=Button(window1, text=\"Next Question\", command=ques2).grid()\n\ndef ques2():\n window1.destroy()\n window2=Tk()\n window2.geometry(\"500x500\")\n question2=Label(window2, text=\"How many Planets are there in Solar System\").grid()\n next2But=Button(window2, text=\"Next Question\")\n\n\nbutton=Button(root,text=\"Start Test\", command=ques1).grid()\n\n\nA: This is a side effect from using Tk more than once in a program. Basically, \"a1\" is tied to the \"root\" window, and when you destroy \"root\", \"a1\" will no longer work. \nYou have a couple options: \n\n\n*\n\n*Keep the same window open all the time, and swap out the Frames instead. \n\n*Use Toplevel() to make new windows instead of Tk. \n\n\nOption 1 seems the best for you. Here it is: \nfrom tkinter import *\n\nroot=Tk()\nroot.geometry(\"500x500\")\na1=StringVar(value='hippidy')\nans1=StringVar()\n\ndef ans1():\n a=a1.get() #not getting it from ques1()\n print(repr(a))\n\ndef ques1():\n global frame\n frame.destroy() # destroy old frame\n frame = Frame(root) # make a new frame\n frame.pack()\n\n question1=Label(frame, text=\"How many Planets are there in Solar System\").grid()\n q1r1=Radiobutton(frame, text='op 1', variable=a1, value=\"correct\").grid()\n q1r2=Radiobutton(frame, text='op 2', variable=a1, value=\"incorrect\").grid()\n sub1=Button(frame, text=\"Submit\", command=ans1).grid()\n next1But=Button(frame, text=\"Next Question\", command=ques2).grid()\n\ndef ques2():\n global frame\n frame.destroy() # destroy old frame\n frame = Frame(root) # make a new frame\n frame.pack()\n\n question2=Label(frame, text=\"How many Planets are there in Solar System\").grid()\n next2But=Button(frame, text=\"Next Question\")\n\nframe = Frame(root) # make a new frame\nframe.pack()\nbutton=Button(frame,text=\"Start Test\", command=ques1).grid()\n\nroot.mainloop()\n\nAlso, don't be scared of classes. They are great. \nAlso, the way you have a widget initialization and layout on the same line is known to cause bugs. Use 2 lines always. So instead of this\nbutton=Button(frame,text=\"Start Test\", command=ques1).grid()\n\nUse this:\nbutton=Button(frame,text=\"Start Test\", command=ques1)\nbutton.grid()\n\n\nA: You need to use a single instance of Tk. Variables and widgets created in one cannot be accessed from another. \n\nA: Your code has some common mistakes. You are creating a new window on each question. It is not a good idea. You can use Toplevel but I will suggest you to use the root. You can destroy all of your previous widgets and place new ones. When the first question, both radiobuttons are unchecked and return 0 when none is selected. You are creating the buttons in Window1 so you will have to tie it with your var. \nfrom tkinter import *\nglobal root\nroot=Tk()\nroot.geometry(\"500x500\")\na1=StringVar(root)\na1.set(0) #unchecking all radiobuttons\nans1=StringVar()\n\ndef ans1():\n a=a1.get()\n print(a)\n\ndef ques1():\n for widget in root.winfo_children():\n widget.destroy() #destroying all widgets\n question1=Label(root, text=\"How many Planets are there in Solar System\").grid()\n q1r1=Radiobutton(root, text='op 1', variable=a1, value=\"correct\").grid()\n q1r2=Radiobutton(root, text='op 2', variable=a1, value=\"incorrect\").grid()\n sub1=Button(root, text=\"Submit\", command=ans1).grid()\n next1But=Button(root, text=\"Next Question\", command=ques2).grid()\ndef ques2():\n for widget in root.winfo_children():\n widget.destroy()\n question2=Label(root, text=\"How many Planets are there in Solar System\").grid()\n next2But=Button(root, text=\"Next Question\")\n\n\nbutton=Button(root,text=\"Start Test\", command=ques1)\nbutton.grid()\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/49904137\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23047,"cells":{"text":{"kind":"string","value":"Q: Nhibernate entity with multiple Many-To-Many lists of the same type? Does anybody know how I would map an entity with two many-to-many collections of the same child type.\nMy database structure is this....\nThe \"normal\" relationship will be....\ntbl_Parent\n col_Parent_ID\n\ntbl_Parent_Child_Xref\n col_Parent_ID\n col_Child_ID\n\ntbl_Child\n col_Child_ID\n\n\nThe alternative relationship is...\ntbl_Parent\n col_Parent_ID\n\ntbl_Include_ParentChild_Xref\n col_Parent_ID\n col_Child_ID\n\ntbl_Child\n col_Child_ID\n\n\nThe entity and mapping look like this...\npublic partial class ParentEntity : AuditableDataEntity\n{\n public virtual IList Children { get; set; }\n public virtual IList IncludedChildren { get; set; }\n}\n\npublic partial class ParentMap : IAutoMappingOverride\n{\n public void Override(AutoMapping mapping)\n {\n mapping.Table(\"tbl_Parent\");\n\n mapping.HasManyToMany(x => x.Children)\n .Table(\"tbl_Parent_Child_Xref\")\n .ParentKeyColumn(\"col_Parent_ID\")\n .ChildKeyColumn(\"col_Child_ID\")\n .Inverse()\n .Cascade.All();\n\n mapping.HasManyToMany(x => x.IncludedChildren)\n .Table(\"tbl_Include_ParentChild_Xref\")\n .ParentKeyColumn(\"col_Parent_ID\")\n .ChildKeyColumn(\"col_Child_ID\")\n .Inverse()\n .Cascade.All();\n }\n}\n\n\nThe error that I'm getting is \n\"System.NotSupportedException: Can't figure out what the other side of the many-to-many property 'Children' should be.\"\nI'm using NHibernate 2.1.2, FluentNhibernate 1.0.\n\nA: It seems FNH is confused because you seem to map the same object (ChildEntity) to two different tables, if I'm not mistaken.\nIf you don't really need the two lists to get separated, perhaps using a discriminating value for each of your lists would solve the problem. Your first ChildEntity list would bind to the discriminationg value A, and you sesond to the discriminating value B, for instance.\nOtherwise, I would perhaps opt for a derived class of your ChildEntity, just not to have the same name of ChildEntity.\nIList ChildEntities\nIList IncludedChildEntities\n\nAnd both your objects classes would be identitical.\nIf you say it works with NH, then it might be a bug as already stated. However, you may mix both XML mappings and AutoMapping with FNH. So, if it does work in NH, this would perhaps be my preference. But think this workaround should do it.\n\nA: You know I'm just shooting in the dark here, but it almost sounds like your ChildEntity class isn't known by Hibernate .. that's typically where I've seen that sort of message. Hibernate inspects your class and sees this referenced class (ChildEntity in this case) that id doesn't know about.\nMaybe you've moved on and found the issue at this point, but thought I'd see anyway.\n\nA: Fluent is confused because you are referencing the same parent column twice. That is a no-no. And as far as I can tell from the activity i have seen, a fix is not coming any time soon.\nYou would have to write some custom extensions to get that working, if it is possible.\n\nA: To my great pity, NHibernate cannot do that. Consider using another ORM.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/1915947\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"7\"\n}"}}},{"rowIdx":23048,"cells":{"text":{"kind":"string","value":"Q: Wrap input with submit tag in one div Let's say I have these fields generated by simple_form_for:\n= f.input :amount, label: false, required: true\n= f.submit \"✓\", class: \"btn btn-primary\"\n\nI want to wrap them in one div and none of them should be nested inside any other div.\n(it should look like this):\n
\n
\n \n \n
\n
\n\nnow it looks like this:\n
\n
\n \n
\n \n
\n\nHow to achieve this?\n\nA: According to the Simple Form documentation, you can skip use of the wrapper html tags by using input_field instead of input. So, if this is just a one-off case then you could define your own wrapper div tag and turn off the auto-generated wrapper:\n.inputFields\n = f.input_field :amount, label: false, required: true\n = f.submit \"✓\", class: \"btn btn-primary\"\n\nOr, if this is not a one-off case and is a common thing, you could create your own wrapper... See the custom wrapper documentation for help.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/25247120\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23049,"cells":{"text":{"kind":"string","value":"Q: cordova websocket plugin showing error code 1006 and angular websocket plugin showing isTrusted true error Angular websocket plugin is working in the browser. But after generating apk in the mobile it is not working, it is showing error. Cordova websocket plugin also not working, it is showing error code 1006. Can any one help me. I am new to ionic. \n document.addEventListener('deviceready', function () {\n var ws = new WebSocket('ws://197.164.1.12:8080/example/2');\n\n ws.onopen = function () {\n alert('open');\n this.send('hello'); \n };\n\n ws.onmessage = function (event) {\n alert(event.data); \n this.close();\n };\n\n ws.onerror = function (event) {\n alert('error occurred!'+JSON.stringify(event));\n };\n\n ws.onclose = function (event) {\n alert('onclose code=' + event.code);\n };\n ws.close = function (event) {\n alert('close code=' + JSON.stringify(event));\n alert('onclose code=' + event.code);\n };\n}, false);\n\n\nA: Your browser is not allow CORS Origin api access. So you can add the plugin \nCORS Plugin for chrome\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/41181539\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23050,"cells":{"text":{"kind":"string","value":"Q: PHP / JpGraph - Memory not freed on completion of function My application needs to generate a pdf file with a bunch of graphs in it.\nThe situation: I'm using FPDF for pdf generation and JpGraph for the graphs. My code gets the graph data from a database and iterates through, calling a function for each graph that contains all the JpGraph code for setting up, styling the graph and caching it as a png file in a cache folder on the server. FPDF then places these images in the pdf, which is served to browser.\nThe problem: I'm getting PHP out of memory errors when the number of graphs exceeds a certain number. AFAICT this is not an FPDF problem: in trying to diagnose the problem I have generated much larger documents with many more (pre-generated) graphs and images of equivalent size. The problem seems to be that the memory used to render the graph in the graph rendering function is not freed when the function is completed. This is based on the fact that if I call memory_get_peak_usage in the function I get a bunch of increasing numbers, one from each time the function is called, up to the limit of 64MB where it stops.\nMy graph generation script looks something like this:\nfunction barChart($filename, $ydata, $xdata){\n\n// Create the graph. These two calls are always required\n$graph = new Graph(900,500);\n$graph->SetScale('textlin');\n\n//(bunch of styling stuff)\n\n// Create the bar plot\n$bplot=new BarPlot($ydata);\n\n// Add the plot to the graph\n$graph->Add($bplot);\n\n//(more styling stuff)\n\n\n// Display the graph\n$graph->Stroke($filename);\n\n$graph = null;\n$bplot = null;\n\nunset($graph);\nunset($bplot);\n\necho \"

\".(memory_get_peak_usage(true)/1048576).\"

\";\n}\n\nAs you can see, I've tried unsetting and nullifying the graph and bplot objects, although my understanding is that this shouldn't be necessary. Shouldn't all the memory used by the Graph and Bplot instances be freed up when the function finishes? Or is this perhaps a JpGraph memory leak? (I've searched high and low and can't find anyone else complaining about this). This is my first remotely resource-heavy PHP project, so I could be missing something obvious.\n\nA: I had the same problem and found the solution after just an hour or so.\nThe issue is that jpgraph loads a default set of font files each time a Graph is created. I couldn't find a way to unload a font, so I made a slight change so that it only loads the fonts one time. \nTo make the fix for your installation, edit \"gd_image.inc.php\" as follows:\nAdd the following somewhere near the beginning of the file (just before the CLASS Image):\n// load fonts only once, and define a constant for them\ndefine(\"GD_FF_FONT0\", imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT0.gdf\"));\ndefine(\"GD_FF_FONT1\", imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT1.gdf\"));\ndefine(\"GD_FF_FONT2\", imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT2.gdf\"));\ndefine(\"GD_FF_FONT1_BOLD\", imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT1-Bold.gdf\"));\ndefine(\"GD_FF_FONT2_BOLD\", imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT2-Bold.gdf\"));\n\nthen at the end of the Image class constructor (lines 91-95), replace this:\n$this->ff_font0 = imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT0.gdf\");\n$this->ff_font1 = imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT1.gdf\");\n$this->ff_font2 = imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT2.gdf\");\n$this->ff_font1_bold = imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT1-Bold.gdf\");\n$this->ff_font2_bold = imageloadfont(dirname(__FILE__) . \"/fonts/FF_FONT2-Bold.gdf\");\n\nwith this:\n$this->ff_font0 = GD_FF_FONT0;\n$this->ff_font1 = GD_FF_FONT1;\n$this->ff_font2 = GD_FF_FONT2;\n$this->ff_font1_bold = GD_FF_FONT1_BOLD;\n$this->ff_font2_bold = GD_FF_FONT2_BOLD;\n\nI didn't test this with multiple versions of php or jpgraph, but it should work fine. ymmv.\n\nA: You could try using PHP >= 5.3 Garbage collection\ngc_enable() + gc_collect_cycles()\nhttp://php.net/manual/en/features.gc.php\n\nA: @bobD's answer is right on the money and helped solved my same question. \nHowever there is also one other potential memory leak source for those still looking for an answer to this very old problem.\nIf you are creating multiple charts with the same background image, each load of the background image causes an increase in memory with each chart creation.\nSimilar to bobD's answer to the font loading issue, this can be solved by making the background image(s) global variables instead of loading them each time.\nEDIT: It looks like there is a very small memory leak when using MGraph() as well.\nSpecifically the function Add(). Perhaps it also loads a font library or something similar with each recursive call.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/13253185\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23051,"cells":{"text":{"kind":"string","value":"Q: In bash/sed, how do you match on a lowercase letter followed by the SAME letter in uppercase? I want to delete all instances of \"aA\", \"bB\" ... \"zZ\" from an input string.\ne.g.\necho \"foObar\" |\nsed -Ee 's/([a-z])\\U\\1//'\n\nshould output \"fbar\"\nBut the \\U syntax works in the latter half (replacement part) of the sed expression - it fails to resolve in the matching clause.\nI'm having difficulty converting the matched character to upper case to reuse in the matching clause.\n\nIf anyone could suggest a working regex which can be used in sed (or awk) that would be great. \nScripting solutions in pure shell are ok too (I'm trying to think of solving the problem this way). \nWorking PCRE (Perl-compatible regular expressions) are ok too but I have no idea how they work so it might be nice if you could provide an explanation to go with your answer.\nUnfortunately, I don't have perl or python installed on the machine that I am working with.\n\nA: You may use the following perl solution:\necho \"foObar\" | perl -pe 's/([a-z])(?!\\1)(?i:\\1)//g'\n\nSee the online demo.\nDetails\n\n\n*\n\n*([a-z]) - Group 1: a lowercase ASCII letter\n\n*(?!\\1) - a negative lookahead that fails the match if the next char is the same as captured with Group 1\n\n*(?i:\\1) - the same char as captured with Group 1 but in the different case (due to the lookahead before it).\n\n\nThe -e option allows you to define Perl code to be executed by the compiler and the -p option always prints the contents of $_ each time around the loop. See more here.\n\nA: This might work for you (GNU sed):\nsed -r 's/aA|bB|cC|dD|eE|fF|gG|hH|iI|jJ|kK|lL|mM|nN|oO|pP|qQ|rR|sS|tT|uU|vV|wW|xX|yY|zZ//g' file\n\nA programmatic solution:\nsed 's/[[:lower:]][[:upper:]]/\\n&/g;s/\\n\\(.\\)\\1//ig;s/\\n//g' file\n\nThis marks all pairs of lower-case characters followed by an upper-case character with a preceding newline. Then remove altogether such marker and pairs that match by a back reference irrespective of case. Any other newlines are removed thus leaving pairs untouched that are not the same.\n\nA: Here is a verbose awk solution as OP doesn't have perl or python available:\necho \"foObar\" |\nawk -v ORS= -v FS='' '{\n for (i=2; i<=NF; i++) {\n if ($(i-1) == tolower($i) && $i ~ /[A-Z]/ && $(i-1) ~ /[a-z]/) {\n i++\n continue\n }\n print $(i-1)\n }\n print $(i-1)\n}'\n\n\nfbar\n\n\nA: Note: This solution is (unsurprisingly) slow, based on OP's feedback:\n\"Unfortunately, due to the multiple passes - it makes it rather slow. \"\n\nIf there is a character sequence¹ that you know won't ever appear in the input,you could use a 3-stage replacement to accomplish this with sed:\n\necho 'foObar foobAr' | sed -E -e 's/([a-z])([A-Z])/KEYWORD\\1\\l\\2/g' -e 's/KEYWORD(.)\\1//g' -e 's/KEYWORD(.)(.)/\\1\\u\\2/g'\n\ngives you: fbar foobAr\nReplacement stages explained:\n\n\n*\n\n*Look for lowercase letters followed by ANY uppercase letter and replace them with both letters as lowercase with the KEYWORD in front of them foObar foobAr -> fKEYWORDoobar fooKEYWORDbar\n\n*Remove KEYWORD followed by two identical characters (both are lowercase now, so the back-reference works) fKEYWORDoobar fooKEYWORDbar -> fbar fooKEYWORDbar\n\n*Strip remaining² KEYWORD from the output and convert the second character after it back to it's original, uppercase version fbar fooKEYWORDbar -> fbar foobAr\n¹ In this example I used KEYWORD for demonstration purposes. A single character or at least shorter character sequence would be better/faster. Just make sure to pick something that cannot possibly ever be in the input.\n² The remaining occurances are those where the lowercase-versions of the letters were not identical, so we have to revert them back to their original state\n\nA: There's an easy lex for this,\n%option main 8bit\n #include \n%%\n[[:lower:]][[:upper:]] if ( toupper(yytext[0]) != yytext[1] ) ECHO;\n\n(that's a tab before the #include, markdown loses those). Just put that in e.g. that.l and then make that. Easy-peasy lex's are a nice addition to your toolkit.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/53729122\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"2\"\n}"}}},{"rowIdx":23052,"cells":{"text":{"kind":"string","value":"Q: EPPlus next row I am using Epplus to write out a collection into an excel file. Currently I am incrementing rows by manually manipulating the cell number.(ws is an instance of ExcelWorkSheet)\n int i = 1;\n foreach (var item in items)\n {\n ws.Cells[\"A\"+i.ToString()].Value =item.Text; \n i++;\n }\n\nInstead of adding number to cell name is there a better way to handle this? Something like\n int i = 1;\n foreach (var item in items)\n {\n ws.Row[i].Cells[0]=item.Text; \n i++;\n }\n\n\nA: There's an [int Row, int Col] indexer on Cells (type ExcelRange), so you can use ws.Cells[i, 0].\n int i = 1;\n foreach (var item in items)\n {\n ws.Cells[i, 0].Value =item.Text; \n i++;\n }\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/18744135\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23053,"cells":{"text":{"kind":"string","value":"Q: How to determine current status of web video (playing | stopped) How can I determine when a user starts or stops playing a video on a web page? For instance, the video on this page:\nhttp://www.novamov.com/video/exm71hcwt1aly\nI need to be able to determine this from a separate .NET application running on the client.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/11038894\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23054,"cells":{"text":{"kind":"string","value":"Q: How to create HTML in angular? I have been working on React for a year. Now, I am writing angular. How can I create a piece of html code in ts.file?\nIn react, I do it that way:\nconst example = (item: string): React.ReactNode => {\n return

something.... {item}

\n}\n\nI want to do same thing in Angular8+\nI know some way to do it. For example:\nconst example2= (name: string): string => {\n return `\n
\n

heyyy ${name}

\n
\n `;\n};\n\nAre there any other ways to do it?\n\nA: In Angular, there are a couple of ways to do this. If you need to generate HTML in the typescript and then interpolate it into the template, you can use a combination of the DomSanitizer and the innerHTML attribute into other elements (for example a span).\nBelow would be an example of what I suggested above:\nhello-world.component.ts:\n@Component({\n selector: \"hello-world\",\n templateUrl: \"./hello-world.component.html\",\n styleUrls: [\"./hello-world.component.scss\"]\n})\nexport class HelloWorld {\n innerHTML: string = `

Hello, world!

`;\n}\n\nsanitze.pipe.ts:\n@Pipe({\n name='sanitize'\n})\nexport class SanitizePipe {\n constructor(private sanitizer: DomSanitizer) { }\n transform(value: string): SafeHtml {\n return this.sanitizer.bypassSecurityTrustHtml(value);\n }\n}\n\nhello-world.component.html:\n
\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/68712302\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23055,"cells":{"text":{"kind":"string","value":"Q: Javassist - How to add line number to method I am a newbie to java bytecode and javassist. I created a new class file with using javassist. Although I added fields and methods, I couldn't achieve to add line number to method. Result of my research, I understand that I need to add linenumberattribute to codeattribute of method info. Moreover, linenumberattribute consists of linenumbertable. I don't know how can I create a new linenumberattribute with javassist.\n\nA: I am writing a compiler that produces JVM code. I need line numbers in the output. I do it this way.\nI build up a list of objects similar to this:\npublic class MyLineNum {\n public final short pc;\n public final short lineNum;\n}\n\nThen I add the line number table:\nfinal ClassFile classFile = ...;\nfinal ConstPool constPool = classFile.getConstPool();\nfinal MethodInfo minfo = new MethodInfo( ... );\nfinal Bytecode code = new Bytecode( constPool );\n... code that writes to 'code'\n\nfinal List lineNums = new ArrayList<>();\n... code that adds to 'lineNums'\n\nfinal CodeAttribute codeAttr = code.toCodeAttribute();\nif ( !lineNums.isEmpty() ) {\n // JVM spec describes method line number table thus:\n // u2 line_number_table_length;\n // { u2 start_pc;\n // u2 line_number;\n // } line_number_table[ line_number_table_length ];\n final int numLineNums = lineNums.size();\n final byte[] lineNumTbl = new byte[ ( numLineNums * 4 ) + 2 ];\n\n // Write line_number_table_length.\n int byteIx = 0;\n ByteArray.write16bit( numLineNums, lineNumTbl, byteIx );\n byteIx += 2;\n\n // Write the individual line number entries.\n for ( final MyLineNum ln : lineNums) {\n // start_pc\n ByteArray.write16bit( ln.pc, lineNumTbl, byteIx );\n byteIx += 2;\n // line_number\n ByteArray.write16bit( ln.lineNum, lineNumTbl, byteIx );\n byteIx += 2;\n }\n\n // Add the line number table to the CodeAttribute.\n @SuppressWarnings(\"unchecked\")\n final List codeAttrAttrs = codeAttr.getAttributes();\n codeAttrAttrs.removeIf( ( ai ) -> ai.getName().equals( \"LineNumberTable\" ) ); // remove if already present\n codeAttrAttrs.add( new AttributeInfo( constPool, \"LineNumberTable\", lineNumTbl ) );\n}\n\n// Attach the CodeAttribute to the MethodInfo.\nminfo.setCodeAttribute( codeAttr );\n\n// Attach the MethodInfo to the ClassFile.\ntry {\n classFile.addMethod( minfo );\n}\ncatch ( final DuplicateMemberException ex ) {\n throw new AssertionError( \"Caught \" + ex, ex );\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/21164289\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"5\"\n}"}}},{"rowIdx":23056,"cells":{"text":{"kind":"string","value":"Q: Is a function return necessary to be called a Closure Hey i came across this video on youtube http://www.youtube.com/watch?v=KRm-h6vcpxs\nwhich basically explains IIFEs and closures. But what I am not understanding is whether i need to return a function in order to call it a closure.\nE.x.\nfunction a() {\n var i = 10;\n function b() {\n alert(i);\n }\n}\n\nin this case can i call it a closure as it is accessing the 'i' variable from the outer function's scope or do i need to return the function like this \nreturn function b(){alert(i);}\n\n\nA: A closure is simply a function which holds its lexical environment and doesn't let it go until it itself dies.\nThink of a closure as Uncle Scrooge:\n\nUncle Scrooge is a miser. He will never let go of his money.\nSimilarly a closure is also a miser. It will not let go of its variables until it dies itself.\nFor example:\nfunction getCounter() {\n var count = 0;\n\n return function counter() {\n return ++count;\n };\n}\n\nvar counter = getCounter();\n\nSee that function counter? The one returned by the getCounter function? That function is a miser. It will not let go of the count variable even though the count variable belongs to the getCounter function call and that function call has ended. Hence we call counter a closure.\nSee every function call may create variables. For example a call to the getCounter function creates a variable count. Now this variable count usually dies when the getCounter function ends.\nHowever the counter function (which can access the count variable) doesn't allow it to die when the call to getCounter ends. This is because the counter function needs count. Hence it will only allow count to die after it dies itself.\nNow the really interesting thing to notice here is that counter is born inside the call to getCounter. Hence even counter should die when the call to getCounter ends - but it doesn't. It lives on even after the call to getCounter ends because it escapes the scope (lifetime) of getCounter.\nThere are many ways in which counter can escape the scope of getCounter. The most common way is for getCounter to simply return counter. However there are many more ways. For example:\nvar counter;\n\nfunction setCounter() {\n var count = 0;\n\n counter = function counter() {\n return ++count;\n };\n}\n\nsetCounter();\n\nHere the sister function of getCounter (which is aptly called setCounter) assigns a new counter function to the global counter variable. Hence the inner counter function escapes the scope of setCounter to become a closure.\nActually in JavaScript every function is a closure. However we don't realize this until we deal with functions which escape the scope of a parent function and keep some variable belonging to the parent function alive even after the call to the parent function ends.\nFor more information read this answer: https://stackoverflow.com/a/12931785/783743\n\nA: Returning the function changes nothing, what's important is creating it and calling it. That makes the closure, that is a link from the internal function to the scope where it was created (you can see it, in practice, as a pointer. It has the same effect of preventing the garbaging of the outer scope, for example).\n\nA: By definition of closure, the link from the function to its containing scope is enough. So basically creating the function makes it a closure, since that is where the link is created in JavaScript :-)\nYet, for utilizing this feature we do call the function from a different scope than what it was defined in - that's what the term \"use a closure\" in practise refers to. This can both be a lower or a higher scope - and the function does not necessarily need to be returned from the function where it was defined in.\nSome examples:\nvar x = null;\n\nfunction a() {\n var i = \"from a\";\n function b() {\n alert(i); // reference to variable from a's scope\n }\n function c() {\n var i = \"c\";\n // use from lower scope\n b(); // \"from a\" - not \"c\"\n }\n c();\n\n // export by argument passing\n [0].forEach(b); // \"from a\";\n // export by assigning to variable in higher scope\n x = b;\n // export by returning\n return b;\n}\nvar y = a();\nx(); // \"from a\"\ny(); // \"from a\"\n\n\nA: The actual closure is a container for variables, so that a function can use variables from the scope where it is created.\nReturning a function is one way of using it in a different scope from where it is created, but a more common use is when it's a callback from an asynchronous call.\nAny situation where a function uses variables from one scope, and the function is used in a different scope uses a closure. Example:\nvar globalF; // a global variable\n\nfunction x() { // just to have a local scope\n\n var local; // a local variable in the scope\n\n var f = function(){\n alert(local); // use the variable from the scope\n };\n\n globalF = f; // copy a reference to the function to the global variable\n\n}\n\nx(); // create the function\nglobalF(); // call the function\n\n(This is only a demonstration of a closure, having a function set a global variable which is then used is not a good way to write actual code.)\n\nA: a collection of explanations of closure below. to me, the one from \"tiger book\" satisfies me most...metaphoric ones also help a lot, but only after encounterred this one...\n\n\n*\n\n*closure: in set theory, a closure is a (smallest) set, on which some operations yields results also belongs to the set, so it's sort of \"smallest closed society under certain operations\". \n\n\na) sicp: in abstract algebra, where a set of elements is said to be closed under an operation if applying the operation to elements in the set produces an element that is again an element of the set. The Lisp community also (unfortunately) uses the word \"closure\" to describe a totally unrelated concept: a closure is an implementation technique for representing procedures with free variables. \nb) wiki: a closure is a first class function which captures the lexical bindings of free variables in its defining environment. Once it has captured the lexical bindings the function becomes a closure because it \"closes over\" those variables.”\nc) tiger book: a data structure on heap (instead of on stack) that contains both function pointer (MC) and environment pointer (EP), representing a function variable; \nd) on lisp: a combination of a function and a set of variable bindings is called a closure; closures are functions with local state;\ne) google i/o video: similar to a instance of a class, in which the data (instance obj) encapsulates code (vtab), where in case of closure, the code (function variable) encapsulates data.\nf) the encapsulated data is private to the function variable, implying closure can be used for data hiding.\ng) closure in non-functional programming languages: callback with cookie in C is a similar construct, also the glib \"closure\": a glib closure is a data structure encapsulating similar things: a signal callback pointer, a cookie the private data, and a destructor of the closure (as there is no GC in C).\nh) tiger book: \"higher-order function\" and \"nested function scope\" together require a solution to the case that a dad function returns a kid function which refers to variables in the scope of its dad implying that even dad returns the variables in its scope cannot be \"popup\" from the stack...the solution is to allocate closures in heap.\ni) Greg Michaelson ($10.15): (in lisp implementation), closure is a way to identify the relationship betw free variables and lexical bound variables, when it's necessary (as often needed) to return a function value with free variables frozen to values from the defining scope.\nj) histroy and etymology: Peter J. Landin defined the term closure in 1964 as having an environment part and a control part as used by his SECD machine for evaluating expressions. Joel Moses credits Landin with introducing the term closure to refer to a lambda expression whose open bindings (free variables) have been closed by (or bound in) the lexical environment, resulting in a closed expression, or closure. This usage was subsequently adopted by Sussman and Steele when they defined Scheme in 1975, and became widespread.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/16586950\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"5\"\n}"}}},{"rowIdx":23057,"cells":{"text":{"kind":"string","value":"Q: C# change the first 32bit Int of a GUID I have a GUID which I created with GUID.NewGUID(). Now I want to replace the first 32 bit of it with a specific 32-bit Integer while keeping the rest as they are.\nIs there a function to do this?\n\nA: You can use ToByteArray() function and then the Guid constructor.\nbyte[] buffer = Guid.NewGuid().ToByteArray();\nbuffer[0] = 0;\nbuffer[1] = 0;\nbuffer[2] = 0;\nbuffer[3] = 0;\n\nGuid guid = new Guid(buffer);\n\n\nA: Since the Guid struct has a constructor that takes a byte array and can return its current bytes, it's actually quite easy:\n//Create a random, new guid\nGuid guid = Guid.NewGuid();\nConsole.WriteLine(guid);\n\n//The original bytes\nbyte[] guidBytes = guid.ToByteArray();\n//Your custom bytes\nbyte[] first4Bytes = BitConverter.GetBytes((UInt32) 0815);\n\n//Overwrite the first 4 Bytes\nArray.Copy(first4Bytes, guidBytes, 4);\n\n//Create new guid based on current values\nGuid guid2 = new Guid(guidBytes);\nConsole.WriteLine(guid2);\n\nFiddle\n\nKeep in mind however, that the order of bytes returned from BitConverter depends on your processor architecture (BitConverter.IsLittleEndian) and that your Guid's entropy decreases by 232 if you use the same number every time (which, depending on your application might not be as bad as it sounds, since you have 2128 to begin with).\n\nA: The question is about replacing bits, but if someone wants to replace first characters of guid directly, this can be done by converting it to string, replacing characters in string and converting back. Note that replaced characters should be valid in hex, i.e. numbers 0 - 9 or letters a - f.\nvar uniqueGuid = Guid.NewGuid();\nvar uniqueGuidStr = \"1234\" + uniqueGuid.ToString().Substring(4);\nvar modifiedUniqueGuid = Guid.Parse(uniqueGuidStr);\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/42527016\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23058,"cells":{"text":{"kind":"string","value":"Q: BeautifulSoup doesn't seem to parse anything I've been trying to learn BeautifulSoup by making myself a proxy scraper and I've encountered a problem. BeautifulSoup seems unable to find anything and when printing what it parses, It shows me this :\n\n \n \n \n \n&gt;\n \n \n\n\nI have tried changing the website I parsed and the parser itself (lxml, html.parser, html5lib) but nothing seems to change, no matter what I do I get the exact same result. Here's my code, can anyone explain what's wrong ?\nfrom bs4 import BeautifulSoup\nimport urllib\nimport html5lib\n\nclass Websites:\n\n def __init__(self):\n self.header = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36\"}\n\n def free_proxy_list(self):\n print(\"Connecting to free-proxy-list.net ...\")\n\n url = \"https://free-proxy-list.net\"\n req = urllib.request.Request(url, None, self.header)\n content = urllib.request.urlopen(req).read\n soup = BeautifulSoup(str(content), \"html5lib\")\n\n print(\"Connected. Loading the page ...\")\n\n print(\"Print page\")\n print(\"\")\n print(soup.prettify())\n\n\nA: You are calling urllib.request.urlopen(req).read, correct syntax is: urllib.request.urlopen(req).read() also you are not closing the connection, fixed that for you.\nA better way to open connections is using the with urllib.request.urlopen(url) as req: syntax as this closes the connection for you.\nfrom bs4 import BeautifulSoup\nimport urllib\nimport html5lib\n\nclass Websites:\n\n def __init__(self):\n self.header = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36\"}\n\n def free_proxy_list(self):\n print(\"Connecting to free-proxy-list.net ...\")\n\n url = \"https://free-proxy-list.net\"\n req = urllib.request.Request(url, None, self.header)\n content = urllib.request.urlopen(req)\n html = content.read()\n soup = BeautifulSoup(str(html), \"html5lib\")\n\n print(\"Connected. Loading the page ...\")\n\n print(\"Print page\")\n print(\"\")\n print(soup.prettify())\n content.close() # Important to close the connection\n\nFor more info see: https://docs.python.org/3.0/library/urllib.request.html#examples\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/47336456\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23059,"cells":{"text":{"kind":"string","value":"Q: Is there a way to import a react component without using 'import' statement I'm new to React. Just trying out things.\nSo far I have been using CDNs for React, React-DOM, and React-Bootstrap. I had no trouble using components of React-Bootstrap using the example code below:\nvar Alert = ReactBootstrap.Alert;\n\nNow my problem is I want to use a component that is not provided by React-Bootstrap so I tried to look for components available in Github. I found a lot of the components that I am looking for but all of them are available for installation via npm which I am avoiding since I'm using React thru CDN. I know it is recommended to use npm or create-react app, but that's not how I started my application.\nSo is there a way to import components like how I did in React-Bootstrap components? For example:\nvar Select = React.Select; // import Select from 'react-select';\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/59854647\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23060,"cells":{"text":{"kind":"string","value":"Q: Android: Send Longitude and Latitude after 60 seconds to the localhost server(WAMP) I want to send the Longitude, Latitude, TimeStamp and the stonest wifi access point as JSON format to the server (WAMP- localhost) after every 60 seconds what is the best approach to do that? I would use AsyncTask but AsyncTasks should ideally be used for short operations (a few seconds at the most.) can someone give short example for sending this data with another approach than AsyncTask?\n\nA: start with these tutorials \nhttp://www.tutorialspoint.com/android/android_php_mysql.htm\nhttp://www.tutorialspoint.com/android/android_php_mysql.htm\nafter that here is how to repeate every 60 seconds\n boolean run=true; \n Handler mHandler = new Handler();//sorry forgot to add this\n...\n...\n public void timer() {\n new Thread(new Runnable() {\n @Override\n public void run() {\n while (run) {\n try {\n Thread.sleep(60000);//60000 milliseconds which is 60 seconds\n mHandler.post(new Runnable() {\n\n @Override\n public void run() {\n //here you send data to server\n }\n });\n } catch (Exception e) {\n }\n }\n }\n }).start();}\n\ncall it like this to start it\n timer()\n\nand to stop it just do \nrun=false;\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/29804032\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23061,"cells":{"text":{"kind":"string","value":"Q: \"error_description\": \"Invalid Value\" for token google sign in every time using flutter I am new in flutter trying to access auth token from google for my backend server but every time token is invalid.\ni am using FirebaseUser user await user.getIdToken() I give me a token but when I am trying to validate that token using my backend server as well as https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=mytoken and https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=mytoken this link it gives me \"error_description\": \"Invalid Value\".\nI am not sure await user.getIdToken() this method is right for getting token.\nOther think everything ok I am getting all user information except right token.\nplease let me know if any other way. \nBelow is my code:\nclass LoginScreen extends StatefulWidget {\n @override\n _LoginScreenState createState() => new _LoginScreenState(); \n}\n\nclass _LoginScreenState extends State {\n final FirebaseAuth auth = FirebaseAuth.instance;\n final GoogleSignIn googleSignIn = new GoogleSignIn();\n Future socailLogin(String authToken) async {\n var url = \"http://api.ourdomain.com/user/social/login/google\";\n final response = await http.post(url,\n body: json.encode({\"auth_token\": authToken}),\n headers: {HttpHeaders.CONTENT_TYPE: \"application/json\"});\n return response;\n }\n\n Future googleSignin() async {\n final GoogleSignInAccount googleSignInAccount = await \n googleSignIn.signIn();\n\n final GoogleSignInAuthentication googleSignInAuthentication =\n await googleSignInAccount.authentication;\n\n final FirebaseUser firebaseUser = await auth.signInWithGoogle(\n accessToken: googleSignInAuthentication.accessToken,\n idToken: googleSignInAuthentication.idToken);\n return firebaseUser;\n }\n\n@override\nWidget build(BuildContext context) {\nfinal logo = Hero(\n tag: 'hero',\n child: CircleAvatar(\n backgroundColor: Colors.transparent,\n radius: 48.0,\n child: Image.asset('assets/logo.png'),\n ),\n);\n\n\nfinal googleloginButton = Padding(\n padding: EdgeInsets.symmetric(vertical: 5.0),\n child: Material(\n borderRadius: BorderRadius.circular(30.0),\n // shadowColor: Colors.lightBlueAccent.shade100,\n // elevation: 5.0,\n child: MaterialButton(\n minWidth: 200.0,\n height: 42.0,\n onPressed: () async {\n FirebaseUser user = await googleSignin();\n String idToken = await user.getIdToken();\n if (idToken != null) {\n\n final http.Response response = await socailLogin(idToken);\n if (response.statusCode == 200) {\n var authToken = json.decode(response.body)['token'];\n if (authToken != null) {\n storedToken(authToken);\n }\n } else {\n print(\"Response status: \" + response.statusCode.toString());\n print(\"Response body: \" + response.body);\n print(\"errror while request\");\n }\n } else {\n print(\"in else part not get token id from google\");\n }\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => HomeScreen(),\n ),\n );\n },\n color: Colors.red,\n child: Row(\n mainAxisAlignment: MainAxisAlignment.center,\n mainAxisSize: MainAxisSize.min,\n children: [\n Icon(\n Icons.bug_report,\n color: Colors.white,\n ),\n Text('Connect with Google',\n style: TextStyle(color: Colors.white)),\n ],\n ),\n ),\n ),\n);\n\n return Scaffold(\n backgroundColor: Colors.white,\n appBar: new AppBar(\n centerTitle: true,\n title: new Text(\"Login\"),\n ),\n body: Center(\n child: ListView(\n shrinkWrap: true,\n padding: EdgeInsets.only(left: 24.0, right: 24.0),\n children: [\n // logo,\n googleloginButton,\n facebookloginButton,\n ],\n ),\n ),\n );\n }\n}\n\nPleases help me.\n\nA: For backend server-side validation, you must use verifiable ID tokens to securely get the user IDs of signed-in users on the server side.\nref. : https://developers.google.com/identity/sign-in/web/backend-auth\nSeems that the current flutter google sign in plugin does not support getting AuthCode for backend server-side OAuth validation.\nref. : https://github.com/flutter/flutter/issues/16613\nI think the firebaseUser.getIdToken() cannot be used for Google API.\nFor https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=mytoken\n, you may need to pass the googleSignInAuthentication.idToken\nFor https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=mytoken\n, you may need to pass the googleSignInAuthentication.accessToken\nGetting user information like user id and pass it to backend server-side is vulnerable to hackers. You should verify the idToken in backend server-side by Google API Client Libraries.\n\nA: I recently had a similar problem.\nthis was my code:\nFuture googleLogin() async {\nfinal googleUser = await googleSignIn.signIn();\nif (googleUser == null) {\n print('no google user??');\n return;\n}\n_user = googleUser;\n\nfinal googleAuth = await googleUser.authentication;\nfinal credential = GoogleAuthProvider.credential(\n accessToken: googleAuth.accessToken);\n\ntry {\n await FirebaseAuth.instance.signInWithCredential(credential);\n \n} catch (e) {\n print('could not sign in with goodle creds, and heres why: \\n $e');\n}\n\n}\nI was not providing all the information in the credential variable. So all I had to do was to add the accessTokenId there. So replace the:\nfinal credential = GoogleAuthProvider.credential(\n accessToken: googleAuth.accessToken);\n\nwith:\nfinal credential = GoogleAuthProvider.credential(\n idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);\n\nand when that got passed to FirebaseAuth.instance, it worked! How this helps.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/51320271\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":23062,"cells":{"text":{"kind":"string","value":"Q: Using SmtpAppender to only send emails when logging an error or fatal I'm using log4net to log different types of messages.\nI have added the SmtpAppender to email specific user when logging messages.\nHowever, what I would like to achieve is to be able to only send emails if an error or fatal is logged.\nAccroding to my current configuration in the web.config file, I get two emails, one for the error and another one for the rest of the logs.\nGlobal.asax.cs:\nlogger.Info(\"Info\");\nlogger.Warn(\"Warning\");\nlogger.Fatal(\"Fatal\");\nlogger.Error(\"exception\");\n\nweb.config:\n\n \n \n \n \n \n \n \n \n \n \n \n \n\n\n\nA: I have found the solution, I should just add this tag to the SmtpAppender:\n\n \n \n\n\n\nA: Try using:\n\n ...\n \n ...\n\n\n(or threshold value=\"ERROR\" since you say you want to limit to Error and Fatallevels) rather than:\n\n ...\n \n \n \n ...\n\n\nThe log4net documentation or this message in the log4net user mailing list explains the difference.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/41564833\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23063,"cells":{"text":{"kind":"string","value":"Q: Android make a dialog scrollable I'm showing a dialog when the user clicks a button. When the dialog appears and you click an EditText to enter some text, you can't see the bottom buttons (and the lowest EditText) anymore. So you have to click the keyboard down, then select the button or EditText. I searched for the answer for a while now, but i can't find it. \nSo: How do i make my dialog scrollable? Apparently my code doesnt do the trick:\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n \n\n \n\n \n \n\n\n\n\nThis is how i call for the dialog:\nbtnAdd.setOnClickListener(new OnClickListener() {\n\n @Override\n public void onClick(View arg0) {\n\n // custom dialog\n dialog = new Dialog(context);\n dialog.setContentView(R.layout.addklant_layout);\n dialog.setTitle(\"Klant toevoegen\");\n\n Button BTNannuleren = (Button) dialog.findViewById(R.id.dialogAnnuleren);\n // if button is clicked, close the custom dialog\n BTNannuleren.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n dialog.dismiss();\n }\n });\n\n Button BTNtoevoegen = (Button) dialog.findViewById(R.id.dialogToevoegen);\n // if button is clicked, close the custom dialog\n BTNtoevoegen.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n StoreKlantInDatabase task = new StoreKlantInDatabase(); \n task.execute(urlInsertKlant);\n dialog.dismiss();\n }\n }); \n dialog.show();\n }\n });\n\nanyone can help me out here?\n\nA: GeertG... now im emotionally involved :) try the link i found... it might do the trick as far as using a scrollview with more than a single child...I dont know if it solves your issue but...\nIf ScrollView only supports one direct child, how am I supposed to make a whole layout scrollable?\nor \nhow to add multiple child in horizontal scroll view in android\nThose solutions should work as creating a scrollview with more than 1 child... will it solve your problem? IDK...\nalso look in to \nHow to hide soft keyboard on android after clicking outside EditText?\nbut having the keyboard closed and re-opened seems kinda reasonable to me... dont linger on it for too long:)\n\nA: The guidelines for what you are asking are can be found here. As you can see. there are a number of ways to achieve what you are asking.\nFurther to this, you could consider changing default action of the 'Enter' button on the keyboard to select the next EditText and finally to submit the form when you are done (read up about it here):\nandroid:imeOptions=\"actionDone\"\n\n\nA: Use LinearLayout Height match_parent. And try if its working or not.\n\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/19109576\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":23064,"cells":{"text":{"kind":"string","value":"Q: Hbase Pagination Filter returning more keys I am using Hbase pagination Filter to iterate over all the rows in table using following code\nScan scan=new Scan(Bytes.toBytes(key))\nFilter filter=new PageFilter(10000);\nscan.setFilter(pageFilter);\nscan.setCaching(100000);// 1lakh i know it should be 10K but this should not be the reson for scanner to return more keys as i commented out the line still getting more keys\nResultScanner resultScanner=htable.getScanner(scan);\n\nBut i am getting more than 10000 value for a specific key in most of the cases it is working fine and returning 10000 keys that is equal to pagination factor but in a specific case it returns more than 10000 key. \nAny point in the direction to understand this behavior will be of a great help\n\nA: OK,It is clear from HBase Api Pagination doc that the pagination filter does not guarantee to give rows <= pagination factor since the filter is applied for each region server\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/26562014\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23065,"cells":{"text":{"kind":"string","value":"Q: how to overwrite User model I don't like models.User, but I like Admin view, and I will keep admin view in my application. \nHow to overwirte models.User ?\nMake it just look like following:\nfrom django.contrib.auth.models import User\n\nclass ShugeUser(User) \n username = EmailField(uniqute=True, verbose_name='EMail as your \nusername', ...) \n email = CharField(verbose_name='Nickname, ...) \n\nUser = ShugeUser \n\n\nA: That isn't possible right now. If all you want is to use the email address as the username, you could write a custom auth backend that checks if the email/password combination is correct instead of the username/password combination (here's an example from djangosnippets.org).\nIf you want more, you'll have to hack up Django pretty badly, or wait until Django better supports subclassing of the User model (according to this conversation on the django-users mailing list, it could happen as soon as Django 1.2, but don't count on it).\n\nA: The answer above is good and we use it on several sites successfully. I want to also point out though that many times people want to change the User model they are adding more information fields. This can be accommodated with the built in user profile support in the the contrib admin module.\nYou access the profile by utilizing the get_profile() method of a User object.\nRelated documentation is available here.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/1231943\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23066,"cells":{"text":{"kind":"string","value":"Q: How to change Bool value within a function in javascript? Based on this tutorial: link\nHere is my example code:\nfunction modifyVar(obj, val) {\n obj.valueOf = obj.toSource = obj.toString = function(){ return val; };\n}\n\nfunction setToFalse(boolVar) {\n modifyVar(boolVar, 'false');\n}\n\nvar isOpen = true;\nsetToFalse(isOpen);\nconsole.log('isOpen ' + isOpen); \n\nHow can I change the bool variable value within a function?\nIs it possible to pass the bool value by reference?\nthanks in advance\n\nA: We can use that.\nvar myBoolean = { value: false }\n\n//get\nmyBoolean.value;\n\n//set\nmyBoolean.value = true;\n\n\nA: Several problems there:\n\n\n*\n\n*'false' is not false.\n\n*Variables are passed by value in JavaScript. Always. So there is no connection whatsoever between the boolVar in setToFalse and the isOpen you're passing into it. setToFalse(isOpen) is processed like this:\n\n\n*\n\n*The value of isOpen is determined\n\n*That value (completely disconnected from isOpen) is passed into setToFalse\n\n\n*JavaScript has some interesting handling around primitive types: If you try to use them like object types (var a = 42; a.toFixed(2); for instance), the value gets promoted to a temporary object, that object is used, and then the object is discarded. So if obj is false, obj.anything = \"whatever\" ends up being a no-op, because the object that temporarily exists ends up getting released as soon as the line finishes.\nYou could do something like what you're doing by promoting isOpen to an object via new Boolean, but beware that it will then act like an object, not a boolean:\n\n\nfunction modifyVar(obj, val) {\r\n obj.valueOf = obj.toSource = obj.toString = function(){ return val; };\r\n}\r\n\r\nfunction setToFalse(boolVar) {\r\n modifyVar(boolVar, false);\r\n}\r\n\r\nvar isOpen = new Boolean(true); // An object\r\nsetToFalse(isOpen);\r\nsnippet.log('isOpen ' + isOpen);\n\r\n\n\n\nThat works because the value in isOpen is a reference to an object. So when that value is passed into setToFalse as boolVar, boolVar's value is a copy of that reference, and so refers to the same object. So that sorts out issue #2 above. Issue #3 is solved by creating an object explicitly, rather than relying on the implicit behavior.\nBut, remember my warning above about how it will act like an object (because it is one), not like a boolean? Here's an example:\n\n\nfunction modifyVar(obj, val) {\r\n obj.valueOf = obj.toSource = obj.toString = function(){ return val; };\r\n}\r\n\r\nfunction setToFalse(boolVar) {\r\n modifyVar(boolVar, false);\r\n}\r\n\r\nvar isOpen = new Boolean(true); // An object\r\nsetToFalse(isOpen);\r\nsnippet.log('isOpen ' + isOpen);\r\nif (isOpen) {\r\n snippet.log(\"isOpen is truthy, what the...?!\");\r\n} else {\r\n snippet.log(\"isOpen is falsey\");\r\n}\n\r\n\n\n\nWe see:\n\nisOpen false\nisOpen is truthy, what the...?!\n\n...because isOpen contains a non-null object reference, and non-null object references are always truthy.\n\nA: You are passing boolean primitive variable isObject. For primitive types it doesn't make sense to try to set toString method, because it's not needed (and used), since in ECMAScript spec there are already defined rules for to String conversion. \nIf you really want to use modifyVar function like you are trying, you can work with Boolean object instead of primitive: \nfunction modifyVar(obj, val) {\n obj.valueOf = obj.toSource = obj.toString = function(){ return val; };\n}\n\nfunction setToFalse(boolVar) {\n modifyVar(boolVar, 'false');\n}\n\nvar isOpen = new Boolean(true);\nsetToFalse(isOpen);\nconsole.log('isOpen ' + isOpen); \n\nSo the answer: use new Boolean(true) or Object(true).\n\nA: I am not sure but you are assigning false in single quote, value withing single/double quotes will be considered as string. Just use modifyVar(boolVar, false); and try.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/26829207\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":23067,"cells":{"text":{"kind":"string","value":"Q: How to use correctly isalnum function in C? I tried to check if a character of a string is alnum and then if the string contains only alnum characters to print the string. When I run the program nothing happens. I have another program with whom I read from the input the text I want and I send it with FIFO. If i don;t include in the program the \"check\" function it works, after that it doesn't. \nvoid put_alphanum(char *str)\n{\nwhile (*str)\n{\n if (*str >= '0' && *str <= '9')\n write(1, str, 1);\n else if (*str >= 'A' && *str <= 'Z')\n write(1, str, 1);\n else if (*str >= 'a' && *str <= 'z')\n write(1, str, 1);\n str++;\n}\nwrite(1,\"\\n\",1);\n}\n\nThis is the function I used to print the string. If I don't put it together with the check function the program works.\nint check(char *str)\n{\n\nwhile(*str)\n{\nif(isalnum(*str)==0)\nreturn 0;\n\nstr++;\n}\n\nreturn 1;\n\n}\n\nThis is the function I use to check if a string contains just alnum characters. But if I don;t include this function in my program, the program works. I think here is the problem. And the main function()\nint main()\n{\nint fd;\nint len;\nchar buf[BUFF_SIZE + 1];\n\nmkfifo(FIFO_LOC, 0666);\nfd = open(FIFO_LOC, O_RDONLY);\nwhile(1)\n{\n while((len = read(fd, buf, BUFF_SIZE)))\n {\n buf[len] = '\\0';\n if(check(buf)==1)\n put_alphanum(buf);\n\n }\n}\nreturn (0);\n}\n\n\nA: The Input text contains '\\n' and that means that the string is not an alphanumeric string. When I read I push the enter button and that means one more character in the string.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/44017907\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"3\"\n}"}}},{"rowIdx":23068,"cells":{"text":{"kind":"string","value":"Q: Are there any web based email clients written in python? I need to integrate a email client in my current python web app.\nAnything available?\nL.E.: I'm building my app on top of CherryPy\n\nA: For others who might find this thread, check out Mailpile. I haven't used it yet, it is a python-based mail client, and I am sure it could be modified to work as a webmail app as well.\n\nA: You could try Quotient. It's a somewhat unusual webmail system, and it definitely won't fit into the same process as CherryPy - but it is in Python ;).\n\nA: You can build one, using email for generating and parsing mail, imaplib for reading (and managing) incoming mail from your mail server, and smtplib for sending mail to the world.\n\nA: Looking up webmail on pypi gives Posterity.\nThere is very probably some way to build a webmail with very little work using Zope3 components, or some other CMS.\nI guess if you are writing a webapp, you are probably using one of the popular frameworks. We would need to know which one to give a more specific answer.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/236205\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"4\"\n}"}}},{"rowIdx":23069,"cells":{"text":{"kind":"string","value":"Q: Fast tcp server availability check I want to make an Unity3D app that has a tcp/ip client. It should check regularly if there is an available server, and if there is one, tries to connect to it. I tried this as following\n _client = new TcpClient(_tcpAddress, _tcpPort);\n if (!_client.Connected)\n {\n return false;\n }\n\nBut every time it calls the constructor, it lags badly. Is there any faster method that checks if there is a server at the specified port?\n\nA: Looking at the specific constructor you're using it states (emphasis mine):\n\nThis constructor creates a new TcpClient and makes a synchronous connection attempt to the provided host name and port number. The underlying service provider will assign the most appropriate local IP address and port number. TcpClient will block until it either connects or fails. This constructor allows you to initialize, resolve the DNS host name, and connect in one convenient step.\n\nYour code isn't \"lagging\", it's actively waiting for the connection to succeed or fail.\nI would suggest instead using the default constructor and either call the BeginConnect and corresponding EndConnect methods, or if you can use the async/await pattern in Unity, perhaps try using ConnectAsync.\nAlthough in Unity, I think a simpler method might be to just use a coroutine (I'm not a Unity programmer so this might not be 100% right):\nStartCoroutine(TestConnectionMethod());\n\nprivate IEnumerator TestConnectionMethod()\n{\n _client = new TcpClient(_tcpAddress, _tcpPort);\n yield return _client.Connected;\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/62143387\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-1\"\n}"}}},{"rowIdx":23070,"cells":{"text":{"kind":"string","value":"Q: How to use AWS Cognito's adaptive authentication security heuristics in custom auth lambda trigger? I’m using AWS Cognito Custom Authentication flow. I do not rely on Cognito for MFA. I want to make use of the adaptive authentication security heuristics in Cognito’s advanced security features. Unfortunately, the event in trigger does not include this information. Is it possible to have different set of custom challenges based on the risk level from adaptive authentication?\n\nA: Here is a workaround until Cognito includes this information in the event passed to trigger.\n
Configure different rules for advanced security features based on the app client id. For App client id 1, configure adaptive authentication to block users from login on detection of risk. And for App client id 2, configure to always allow login.\nIn the custom auth trigger lambda, decide the challenges based on the app client id. So when app client is 1, use normal login challenges. And when app client id is 2, send extra challenges to client.

 The client should log in with app client id 1, and if it fails to login with the reason Unable to login because of security reasons, then log in using app client id 2. \nUnfortunately, Cognito does not have separate error codes, so had to look for error string in response.\nThis approach does require that client whose request is deemed risky, to make a second cognito request. This will take longer time for that client, but atleast most users will not see slower logins.\n
One option that was explored and dropped was to use Cognito admin api from lambda. There are two issues with this. First, every login would be slowed down by this additional http request to Cognito. Secondly, You can get last n events, but there is no way to ensure we request the right event. In case of simultaneous logins attempts, 1 no risk and 1 high risk, and admin api returns the no risk as last event, then both logins would pass through as no risk.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/59919373\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23071,"cells":{"text":{"kind":"string","value":"Q: Equivalent of Nashorn's importPackage in graal.js script engine I am migrating old code from JDK 8 to JDK 12.\nIn the process, I have noticed importPackage does not exist when using the \"graal.js\" script engine. It exists when using \"javascript\" for the script engine.\nIs there any way to achieve the same functionality with \"graal.js\"? The Nashorn migration doc on the GraalJS repository does not cover this.\n\nA: importPackage is originally from Rhino. Even Nashorn supports it when Rhino/Mozilla compatibility is requested explicitly using load(\"nashorn:mozilla_compat.js\"); only, see Rhino Migration Guide in the documentation of Nashorn.\nGraal.js has Nashorn compatibility mode and it supports load(\"nashorn:mozilla_compat.js\"); in this mode.\nSo, you can use something like\nSystem.setProperty(\"polyglot.js.nashorn-compat\", \"true\");\nScriptEngine engine = new ScriptEngineManager().getEngineByName(\"graal.js\");\nSystem.out.println(engine.eval(\"load('nashorn:mozilla_compat.js'); importPackage('java.awt'); new Point();\"));\n\n(it prints java.awt.Point[x=0,y=0] which shows that the package java.awt was imported successfully).\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/57456476\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23072,"cells":{"text":{"kind":"string","value":"Q: Check if product available in Shopify using javascript I have a javascript that handles the product listing on the collection page. Is there a way to ensure that the product is available and not out of stock. I need something similar to {% if product.available %}. But I don't want to change the .liquid file. I need it in Javascript.\n\nA: You can get the JSON representation of an arbitrary product in your store by fetching data from /products/.js. When using the .js endpoint, the product object will include a number of aggregate parameters, including product.available which will be true if at least 1 variant in the product is available.\nNote that Shopify has 2* different product representations, one at the /products/.js endpoint and one at the /products/ Fields { get; set; }\n\n}\n\nMy WCF method is as such:\npublic MyItem GetItemXML(string id)\n{\n MyItem mi = new MyItem();\n\n //do some stuff to populate mi\n\n return mi; \n}\n\nI expect the XML output of this to be something like this:\n\n\n \n \n \n \n FR\n \n ......\n \n \n \n \n \n\n\nHowever, the output that is coming out is as follows - without the directive at the top:\n\n\n \n \n \n FR\n \n ......\n \n \n \n \n\n\nWhat am I missing?\n\nA: If I recall correctly it all depends on how your [OperationContract] is defined. you may have to use Message Contracts to get your desired behavior. Take a look at http://msdn.microsoft.com/en-us/library/ms730255.aspx\n\nA: // The Model Object\n\n[Serializable]\n[XmlRoot(\"OutputItem\")]\n[DataContractAttribute]\npublic class MyObject\n{\n [XmlElement(\"ItemName\")]\n [DataMemberAttribute] \n public string Name { get; set; }\n\n [XmlArray(\"DummyItems\")]\n [XmlArrayItem(\"DummyItem\", typeof(MyItemField))]\n public List DummyItem { get; set; }\n}\n\n\n\n// The Class that implement the contract\n[DataContract]\npublic class ConsumptionService : IAnyContract\n{\n public MyObject GetItemXML(string id)\n {\n MyObject mo = new MyObject();\n //do some stuff to populate mi\n MyObject mo; \n }\n }\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/12504046\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23080,"cells":{"text":{"kind":"string","value":"Q: generic type XMLexception in catel I try to use the properties CATEL who generic type.\nAnd I have XmlException in Model attribute.\n[Serializable]\npublic class TDS : SavableModelBase\n{\n public TestType Tds\n {\n get { return GetValue>(TdsProperty); }\n set { SetValue(TdsProperty, value); }\n }\n public static readonly PropertyData TdsProperty = RegisterProperty(\"Tds\", typeof(TestType));\n\n\n public TDS(TestType tds)\n {\n Tds = tds;\n }\n}\n\nViewModel when i use catel prop\npublic class MainWindowViewModel : ViewModelBase\n{\n [Model]\n public TDS Xxx //when assigning XMLException The '`' character, hexadecimal value 0x60, cannot be included in a name.\n {\n get { return GetValue(XxxProperty); }\n set { SetValue(XxxProperty, value); }\n }\n public static readonly PropertyData XxxProperty = RegisterProperty(\"Xxx\", typeof(TDS));\n}\n\nclass modelBase in main struct, where catel prop\n[Serializable]\npublic class TestType : ModelBase\n{\n public TestType(ushort val)\n {\n Val = val;\n }\n\n public ushort Val\n {\n get { return GetValue(ValProperty); }\n set { SetValue(ValProperty, value); }\n }\n public static readonly PropertyData ValProperty = RegisterProperty(\"Val\", typeof(ushort));\n\n}\n\nI think that the problem, in a generic catel prop\nHelp me!!!\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/28711367\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23081,"cells":{"text":{"kind":"string","value":"Q: Recursion for matrix in JavaScript I'm using recursion for finding neighbors of neighbors in a matrix (in a minesweeper game). Right now my function is finding and marking neighbors only from left till bottom right. What am I doing wrong?\nJavascript:\nfunction openAllZeroCount(elcell, i, j) {\n for (var idxi = i - 1; idxi <= i + 1; idxi++) {\n\n for (var idxj = j - 1; idxj <= j + 1; idxj++) {\n if (idxi < 0 || idxi >= gSize || idxj < 0 || idxj >= gSize) continue;\n if (gBoard[idxi][idxj].isMine === false && gBoard[idxi][idxj].minesAroundCount === 1) {\n\n var elCountZero = document.getElementById('cell-' + idxi + '-' + idxj)\n elCountZero.style.opacity = '0.8'\n elCountZero.innerText = gBoard[idxi][idxj].minesAroundCount\n }\n if (gBoard[idxi][idxj].isMine === false && gBoard[idxi][idxj].minesAroundCount === 0) {\n var elCountZero = document.getElementById('cell-' + idxi + '-' + idxj)\n elCountZero.style.opacity = '0.8'\n }\n }\n }\n if (idxi < 0 || idxi >= gSize || idxj < 0 || idxj >= gSize) return;\n if (gBoard[idxi][idxj].isMine === false) {\n\n console.log('gboard i j:', gBoard[idxi][idxj])\n\n openAllZeroCount(null, idxi, idxj)\n }\n}\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/52539935\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23082,"cells":{"text":{"kind":"string","value":"Q: How should I size my Spinner Image Size in Android app for different screen size/resolutions? I'm trying to develop my first app for the play store which should resize for different screen sizes/resolutions. For some reason the spinner images are showing up extremely small for mdpi virtual device & huawei 9 on firebase. Please see attached file. The other images are very large currently because I removed the ldpi, mdpi, hdpi, xhdpi, xxhdpi and xxhdpi folders to see how it would appear with just xxhdpi images. I have spinner widths in the layout xml files at 40dp, 50dp, 80dp and 180dp for small, normal, large and xtra large screens respectively.Screenshot of low res mdpi virtual devise\nAny ideas why the images would appear so tiny! \n\nA: In case anyone has sizing/layout issues with Android apps for different screen sizes/display dpis - I highly recommend this sdk https://github.com/intuit/sdp/commits?author=elhanan-mishraky which solved my problem above!\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/58942110\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"-1\"\n}"}}},{"rowIdx":23083,"cells":{"text":{"kind":"string","value":"Q: What causes inhibited conditional statements? There are three options that the user can input in this program. He can choose to login, create an account, or restore an account using his email.\nif user_ == 1:\n loginf.main()\nif user_ == 2:\n createnewaccount.main()\nif user_ == 3:\n restoreaccount.main()\n\nEach option calls a function from a different module. And then returns back to main when the user is done.\nFor example, my code in the loginf module:\ndef login_information():\n login = input(\"Enter your username: \\n\")\n password = input(\"Enter your password: \\n\")\n if os.path.isfile('accountinfo.txt'): # Checking to see if accountinfo text file is created.\n pass # If not, then called back to mainf module.\n else:\n print(\"You don't have an account on file.\")\n import mainf\n mainf.main()\n\n chobi = open('accountinfo.txt')\n particular_text = chobi.read().strip().split()\n if login and password not in particular_text:\n login_error()\n else:\n print(\"You've logged into your account.\")\n chobi.close()\n return_back_to_main() \ndef main():\n while True:\n login_information()\n\nI've used a similar set-up for my other two modules. \nHowever, this is my output:\nC:\\Users\\raamis\\PycharmProjects\\TicTacToe\\venv\\Scripts\\python.exe C:/Users/raamis/PycharmProjects/scratchProject/mainf.py\n------------------------\nLOGIN - 1\nCREATE NEW ACCOUNT - 2\nRESTORE ACCOUNT - 3\n------------------------\nSelect an option 1-3: \n1\nEnter your username: \nLuke\nEnter your password: \nRoboCop123!\nYou've logged into your account.\n------------------------\nLOGIN - 1\nCREATE NEW ACCOUNT - 2\nRESTORE ACCOUNT - 3\n------------------------\nSelect an option 1-3: \n1\nEnter your username: \nLuke\nEnter your password: \nRoboCop123!\nYou've logged into your account.\n------------------------\nLOGIN - 1\nCREATE NEW ACCOUNT - 2\nRESTORE ACCOUNT - 3\n------------------------\nSelect an option 1-3: \n2\nEnter your username: \n\nThe functions are appropriately called for the first 2 iterations. But then when an option is selected on the third iteration, the program still refers back to the loginf module.\nI've also had to import locally to avoid circular imports.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/59938511\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23084,"cells":{"text":{"kind":"string","value":"Q: Cleaning an older swift application project using storyboards I have been assigned a \"new\" old app project from my company, where there is a mix of older swift code and newer swift code. I am slowly getting comfortable with deleting and refactoring parts of the code, trying to remove the Xcode warnings and making the code safer in general... But since I am new to swift (especially storyboards), I am not sure when an @IBOutlet or @IBAction can be removed.\nI have some @IBOutlets and @IBActions, where there are no 'dots' next to them:\nthe circles to the left-side of the outlets don't have a dot\nDoes this mean it is safe to change these from outlets to \"regular\" views? and is this also true for @IBActions?\nIs this simply straight forward, no dot = No @IBOutlet/@IBAction needed?\nOr is it trial and error: Try and remove, build & run, see if broken, redo...?\nOr are there smarter ways to check these things?\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/73611885\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23085,"cells":{"text":{"kind":"string","value":"Q: Complex data.table subset and manipulation I am trying to combine a lot of data.table manipulations into a some faster code. I am creating an example with a smaller data.table and I hopeful someone has a better solution than the clunky (embarrassing) code I developed.\nFor each group, I want to:\n1) Verify there is both a TRUE and FALSE in column w, and if there is:\n2) Subtract the value of x corresponding to the highest value of v from each\nvalue of x in the same group and put that that number in a new column\nSo in group 3, if the highest v value is 10, and in the same row x is 0.212,\nI would subtract 0.212 from every x value corresponding to group 3 and put that number in a new column\n3) Remove all rows corresponding to groups without both a TRUE and a FALSE in column w.\nset.seed(1)\ntest <- data.table(v=1:12, w=runif(12)<0.5, x=runif(12),\ny=sample(2,12,replace=TRUE), z=sample(letters[1:3],12,replace=TRUE) )\nsetkey(test,y,z)\ntest[,group:=.GRP,by=key(test)]\n\n\nA: A chained version can look like this without needing to set a table key:\nresult <- test[\n # First, identify groups to remove and store in 'rowselect'\n , rowselect := (0 < sum(w) & sum(w) < .N)\n , by = .(y,z)][\n # Select only the rows that we need\n rowselect == TRUE][\n # get rid of the temp column\n , rowselect := NULL][\n # create a new column 'u' to store the values\n , u := x - x[max(v) == v]\n , by = .(y,z)]\n\nThe result looks like this:\n> result\n v w x y z u\n1: 1 TRUE 0.6870228 1 c 0.4748803\n2: 3 FALSE 0.7698414 1 c 0.5576989\n3: 7 FALSE 0.3800352 1 c 0.1678927\n4: 10 TRUE 0.2121425 1 c 0.0000000\n5: 8 FALSE 0.7774452 2 b 0.6518901\n6: 12 TRUE 0.1255551 2 b 0.0000000\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/34957130\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23086,"cells":{"text":{"kind":"string","value":"Q: How to add second data source to xslt / dataview in SharePoint? I'm trying to create a bar chart using dataview formated using xsl. The list to chart contains data about number of hours spend on certain project. The project column is of type lookup, which points to a list on the other subsite (simpler: cross site lookup column). The fist data source that I connected to dataview points to the first list.\nHow to add second datasource?\n(I know it's maybe not the best explanaition so here's some code) \n\n \n \n\n \n \n\n \n \n \n \n \n \n \n \n
\n\n
\n\nSo I need to: \n\n\n*\n\n*somehow populate Projects variable\n\n*figure out how to use fore-each variable from new datasource in xl:with-param :P\n\n\nI'm completely new to xsl so it's possible there are obvious mistakes in code. Any constructive input is highly appreciated. \n\nA: Use the document() function to load and leverage an external XML file within your XSLT. \n \n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/1721813\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23087,"cells":{"text":{"kind":"string","value":"Q: Why return from child is getting undefined in Parent in my Vue application I am building an Vue Application. In my child component I have a function say getName() and I am returning name but when I try to access this function in my parent I am not able to use that getting undefined. But when I emit name in the parent and Use the emit obj it is working. Can Anyone knows why I am facing this problem.\nParent.vue\nexport default defineComponent({\n name: 'App',\n components: {\n HelloWorld\n },\n mixins: [HelloWorld],\n data() : { let value !: string return { value} }\n\n methods: {\n fetchval(){\n let x = this.value.getVal();\n console.log(x);\n }\n }\n});\n\n\nChild.vue\nexport default defineComponent({\n name: 'HelloWorld',\n dat(){\n let val!: string;\n return{\n val,\n }\n },\n computed: {\n value: {\n get() {\n return this.val as string;\n },\n set(newval) {\n val = newval;\n }\n }\n },\n methods: {\n getVal(){\n return this.value as string;\n }\n }\n});\n\n\nWhen I try to console.log x I am getting undefined but when i emit this.value and use it in parent working fine. What am i missing?\n\nA: The \"fetchval\" method in your parent is not referencing your child but the \"value\" property in your data function. \"this\" refers to your parent component. Basically, you are trying to call a \"getVal\" function on a string in your parent.\nIf you want to call a function on your child component, you need a reference to the child and call that function on that reference. You need to add a ref to your child component. If you're not familiar with refs, I suggest starting here: Template Refs\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/73148608\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23088,"cells":{"text":{"kind":"string","value":"Q: Internal Exception: java.sql.SQLSyntaxErrorException: 'EMAIL' is not a column in table I am running a JAVA EE Application using Maven and Netbeans\nApparently my column \"email\" is not getting detected? what I am doing wrong?\nThis is in my Entity class Customers\npackage com.mycompany.carsales;\n\nimport java.io.Serializable;\nimport java.util.List;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.*;\n\n@Entity\npublic class Customer implements Serializable {\n private static final long serialVersionUID = 1L;\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id ;\n private String firstName;\n private String lastName;\n private String email; //email address\n private String phone; //phone number\n @JoinColumn(name=\"order_of\")\n @OneToMany (cascade = {CascadeType.PERSIST, CascadeType.REMOVE})\n\nprivate List customerT;\n\npublic List getCustomerT() {\n return customerT;\n}\n\npublic void setCustomerT(List customerT) {\n this.customerT = customerT;\n}\n\npublic String getEmail() {\n return email;\n}\n\npublic void setEmail(String email) {\n this.email = email;\n}\n\npublic String getPhone() {\n return phone;\n}\n\npublic void setPhone(String phone) {\n this.phone = phone;\n}\n\npublic String getFirstName() {\n return firstName;\n}\n\npublic void setFirstName(String firstName) {\n this.firstName = firstName;\n}\n\npublic String getLastName() {\n return lastName;\n}\n\npublic void setLastName(String lastName) {\n this.lastName = lastName;\n}\n\n\npublic Long getId() {\n return id;\n}\n\npublic void setId(Long id) {\n this.id = id;\n}\n\n\n\n\n\n@Override\npublic String toString() {\n return \"com.mycompany.carsales.Customer[ id=\" + id + \" ]\";\n}\n\n}\nThis is in my Main\n package com.mycompany.carsales;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.EntityTransaction;\nimport javax.persistence.Persistence;\nimport com.mycompany.carsales.Customer;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport javax.persistence.*;\n/**\n *\n * @author carlos\n */\npublic class Main {\n\n public static void main (String[] args){\n // Gets an entity manager and a transaction\n Cars car = new Cars(); //creating Games object and passing values to all it\n car.setBrand(\"Toyota\");\n car.setDescription(\"Manual, Red color\");\n car.setType(\"Truck\");\n car.setcYear(\"2014\");\n\n Automobile auto = new Automobile();\n auto.setPrice(20000);\n auto.setPlate(\"88PLATE\");\n\n CustomerTransaction transaction1 = new CustomerTransaction(); //first CustomerOrder object with Games object passed in\n transaction1.setCarPlate(auto.getPlate());\n transaction1.setCarPrice(auto.getPrice());\n transaction1.setTransactionID(auto.getId());\n transaction1.setBuyDate(new Date());\n\n CustomerTransaction transaction2 = new CustomerTransaction(); //first CustomerOrder object with Games object passed in\n transaction2.setCarPlate(auto.getPlate());\n transaction2.setCarPrice(auto.getPrice());\n transaction2.setTransactionID(auto.getId());\n transaction2.setBuyDate(new Date());\n\n ArrayList tList = new ArrayList(); //The arrayList is created\n tList.add(transaction1); //here the previous orders are added one by one\n tList.add(transaction2);\n\n Customer customer = new Customer();\ncustomer.setFirstName(\"Homer\");\ncustomer.setLastName(\"Simpson\");\ncustomer.setEmail(\"Homer.Simpson@fakeemail.com\");\ncustomer.setPhone(\"0404944165\");\ncustomer.setCustomerT(tList);\n\n\n\n\n\nEntityManagerFactory emf = Persistence.createEntityManagerFactory(\"MyPU\");\n EntityManager em = emf.createEntityManager(); //creation of Entity manager\n EntityTransaction tx = em.getTransaction(); //beginning the Entity Transaction\n tx.begin();\n //persistence performed\n em.persist(auto);\n em.persist(customer);\n //commiting transaction and closing Manager\n tx.commit();\n em.close();\n emf.close();\n System.out.println(\"Persistance is successfull\");\n }\n}\n\nMy persistence xml\n\n\n \n org.eclipse.persistence.jpa.PersistenceProvider\n com.mycompany.carsales.Customer\n com.mycompany.carsales.Cars\n com.mycompany.carsales.Automobile\n com.mycompany.carsales.CustomerTransaction\n \n \n \n \n \n \n \n \n\n\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/38957506\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"0\"\n}"}}},{"rowIdx":23089,"cells":{"text":{"kind":"string","value":"Q: What does this typedef statement do? I was going through some code and am not able to understand the following piece of code. What does it do? What does it mean?\ntypedef void*(*fun)[2];\nfun new_array;\n\n\nA: Following the clockwise/spiral rule, fun is a pointer to an array of two pointers to void.\n\nA: OK, basically, this is how typedef works: first imagine that the typedef isn't there. What remains should declare one or more variables. What the typedef does is to make it so that if you would declare a variable x of type T, instead it declares x to be an alias for the type T.\nSo consider:\nvoid*(*fun)[2];\n\nThis declares a pointer to an array of void* of size 2. Therefore,\ntypedef void*(*fun)[2];\n\ndeclares fun to be the type \"pointer to array of void* of size 2\". And fun new_array declares new_array to be of this type.\n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/25499612\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23090,"cells":{"text":{"kind":"string","value":"Q: Unable to install laravel using composer I installed composer successfully.\nNow i am trying to install laravel using this command composer global require \"laravel/installer\" in command prompt but i can't able to install laravel. \nThis show me something like below image.\n\nWhen i use composer create-project --prefer-dist laravel/laravel blog in command prompt then it will show me something like below image.\n\nWhat should i do? any suggestion?\n\nA: This problem is caused due to many possible reasons, like:\n\n\n*\n\n*You are behind the firewall and firewall block it.\n\n*Your internet is too slow. (Hope it is not the case)\n\n*You are using VPN or PROXY. (Not all VPN causes this error.)\n\n*You have both ipv4 and ipv6 enabled (Not sure about this case.)\n\n\nI cannot confirm about the main reason that is caused for you to not being able to create project from composer but you could try some methods like:\n\n\n*\n\n*Changing to different ISP.\n\n*Try running composer -vvv: This helps to check what actually is doing behind the scene and helps in further more debug.\n\n*Try updating composer to latest version.\n\n*Try creating some older version of Laravel or any other packages\ncomposer create-project laravel/laravel blog \"5.1.*\"\n\n*Try using some VPN.\nThis is only for testing and doesn't have fully confirmed solution.\nIf there is any other reason we could edit this solution.\n\nA: If are installing the composer make sure that,you must have to set environment variable for PHP. If your using xampp control panel ->go to xampp installed path->PHP. Then copy location and set in the environment location.Then try to install composer. \n"},"meta":{"kind":"string","value":"{\n \"language\": \"en\",\n \"url\": \"https://stackoverflow.com/questions/43316695\",\n \"timestamp\": \"2023-03-29T00:00:00\",\n \"source\": \"stackexchange\",\n \"question_score\": \"1\"\n}"}}},{"rowIdx":23091,"cells":{"text":{"kind":"string","value":"Q: Adding html table row with jquery can not set as marked I wrote a HTML file with a table. This table has about 7 entries (rows with data) by default. When the user clicks on one of these row the background color changes and it becomes marked, I did it with the jquery toggle function.\nI also have a button which adds further rows in this table, also with jquery. My problem: When I (user) add some rows with that button and click on those new added rows the background color doesn't change but the background color of default rows change. \n\n\n\nMy Page\n\n\n\n