texts
list
tags
list
[ "Is it possible to select a java.awt.Frame with Robot Framework in conjunction with SwingLibrary?", "I've been testing a Java Swing based application with Robot Framework in conjunction with Swing Library for some time. I'm stuck in one of the test cases because the Select Window keyword does not find the desired window on the screen, although it is visible. \n\nHere's a code snippet showing the relevant keywords of this test case:\n\n...\nSelect Window Main Window\nPush Button Add Person\nList Windows\nSelect Window Person Manager\n\n\nThe first three lines are working fine, but the Select Window Person Manager fails with the following rather short message:\n\n14:24:40 FAIL Frame with name or title 'Person Manager'\n\n\nAfter debugging the application under test I identified the source of the problem: the window not being found is instance of java.awt.Frame.\n\nInterestingly, it is listed by List Windows.\n\nIs there a known workaround or existing extension of Swing Library to be able to focus on a java.awt.Frame?" ]
[ "java", "swing", "robotframework", "gui-testing" ]
[ "XSL - Cannot add a namespace to the root node", "I have a html, I want to parse it to xml using html-agility-pack library. Here's the xsl:\n\n<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<xsl:stylesheet version=\"2.0\"\nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"> \n <xsl:template match=\"/\">\n <BusinessDetail>\n <Name>\n <xsl:value-of select=\"//span[@class='pp-place-title']/span\" />\n </Name>\n <Address>\n <xsl:value-of select=\"//span[@class='pp-headline-item pp-headline-address']/span\"/>\n </Address>\n ...\n </BusinessDetail>\n </xsl:template>\n</xsl:stylesheet>\n\n\nI just want to add a namespace to the root node. The expected output is:\n\n<BusinessDetail xmlns:g=\"http://myurl.com\">\n <Name>\n ...\n </Name>\n ..\n</BusinessDetail>\n\n\nSo change my xls to:\n\n<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<xsl:stylesheet version=\"2.0\"\nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"> \n <xsl:template match=\"/\">\n <BusinessDetail xmlns:g=\"http://myurl.com\">\n <Name>\n <xsl:value-of select=\"//span[@class='pp-place-title']/span\" />\n </Name>\n <Address>\n <xsl:value-of select=\"//span[@class='pp-headline-item pp-headline-address']/span\"/>\n </Address>\n ...\n </BusinessDetail>\n </xsl:template>\n</xsl:stylesheet>\n\n\nBut the namespace does not appear in the output. Is there something wrong?" ]
[ "xslt", "html-agility-pack" ]
[ "How to fetch the data in the mongodb", "How to fetch the data from the json file using mongoshell\n\nI want to fecch the Data by policyID \nSay in the json file I sent the PolicyID is 3148\n\nI tried could of ways to write the command but say 0 rows fetched.\n\ndb.GeneralLiability.find({\"properties.id\":\"21281\"})\ndb.GeneralLiability.find({properties:{_id:\"21281\"}})\n\n\nDo i need to set any thing else?index,cursors etc?\n\nSample json\n\n{\n \"session\": {\n \"data\": {\n \"account\": {\n \"properties\": {\n \"userName\": \"abc.com\",\n \"_dateModified\": \"2014-10-01\",\n \"_manuscript\": \"Carrier_New_Rules_2_1_0\",\n \"_engineVersion\": \"2.0.0\",\n \"_cultureCode\": \"en-US\",\n \"_cultureName\": \"United States [english]\",\n \"_context\": \"Underwriter\",\n \"_caption\": \"Carrier New Rules (2.1.0)\",\n \"_id\": \"p1CEB08012E51477C9CD0E89FE77F5E51\"\n },\n \"properties\": {\n \"_xmlns:xsd\": \"http://www.w3.org/2001/XMLSchema\",\n \"_xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\n \"_id\": \"3148\",\n \"_HistoryID\": \"5922\",\n \"_Type\": \"onset\",\n \"_Datestamp\": \"2014-10-01T04:46:33\",\n \"_TransactionType\": \"New\",\n \"_EffectiveDate\": \"2014-01-01\",\n \"_Charge\": \"1599\",\n \"_TransactionGroup\": \"t4CE4FA751F9C400D9007E692A883DA66\",\n \"_PolicyID\": \"3148\",\n \"_Index\": \"1\",\n \"_Count\": \"1\",\n \"_Sequence\": \"1\"\n }\n}\n}" ]
[ "json", "mongodb" ]
[ "why override prepareForSegue will show override can only be specified on class member", "This is part of my code. I was trying to override prepareForSegue, so when I click a cell, it can into my another view controller and show different content based on the cell I clicked . But I cannot override prepareForSegue.\n\nimport Foundation\nimport UIKit\nclass CategoryListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate\n{\nfunc numberOfSectionsInTableView(tableView: UITableView) -> Int {\n return 1\n}\nfunc tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return 5\n}\nfunc tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {\n\n\n\n let cell:UITableViewCell\n cell = tableView.dequeueReusableCellWithIdentifier(\"firstrow\", forIndexPath: indexPath)\n\n cell.textLabel?.text = \"test\"\n\n cell.detailTextLabel?.text = \"try\"\n\n override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)\n {\n switch segue.identifier {\n case .Some(\"DetailSegue\"):\n let indexPath = tableView.indexPathForSelectedRow!\n let viewController = segue.destinationViewController\n viewController.navigationItem.title = \"Row \\(indexPath.row)\"\n\n tableView.deselectRowAtIndexPath(indexPath, animated: false)\n default:\n super.prepareForSegue(segue, sender: sender)\n }\n }\n\n\n\n return cell\n}\n}\n\n\nXcode tells me that override can only be specified on class member,but I need to override prepareForSegue. What's wrong with my code? This function can be override in my teacher's code, but it seems cannot be override in my code." ]
[ "ios", "swift", "class", "overriding" ]
[ "Trouble Returning WCS from FITS Image", "I am using astropy to load a FITS image and retrieve the WCS from it.\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\n\nwith fits.open('hst_A2744_f606w_drz.fits') as hdul:\n wcs = WCS(hdul[1])\n print(wcs)\n\n\nWhich Returns\nWCS Keywords\n\nNumber of WCS axes: 2\nCTYPE : 'RA---TAN' 'DEC--TAN'\nCRVAL : 3.587755699764648 -30.39711750881429\nCRPIX : 3000.4999999998081 2989.499999999809\nCD1_1 CD1_2 : -1.3888888888888e-05 0.0\nCD2_1 CD2_2 : 0.0 1.3888888888889599e-05\nNAXIS : 6000 5978\n\nMy goal is to return CRVAL as either a string, tuple, or array like this:\n(3.587755699764648, -30.39711750881429)\nI've tried accessing it as wcs['CTYPE'] and wcs[CTYPE], and wcs.CTYPE but all return errors." ]
[ "python", "astropy", "wcs" ]
[ "Incorrect results from Md5 sum in bash shell script", "I'm missing some images that should have been archived when this script runs. I think this may be to do with my indentations or my Md5 sum. I have tried everything I can think of.\n\nhere is the code with out the correct indentations:\n\n#!/bin/sh\n\nif [ ! -d \"$1\" ]; then\n echo Directory \"$1\" cannot be found. Please try again.\n exit\nfi\n\nif [ $# -eq 1 ]; then\n echo \"usage: Phar image_path archive_path\"\n exit\nfi\n\nif [ -d \"$2\" ]; then\n echo \"archive exists\"\nelse\n echo \"the directory 'archive' does't exist. Creating directory 'archive'.\"\n mkdir -p ~/archive \nfi\n\nfind $1 -iname \"IMG_[0-9][0-9][0-9][0-9].JPG\" | cat > list.txt\n\n[ -f ~/my-documents/md5.txt ] && rm md5.txt || break \nwhile read line;\n do md5sum $line | xargs >> md5.txt \ndone < list.txt \n\nsort -k 1,1 -u md5.txt | cat > uniquemd5.txt \ncut -d \" \" -f 2- uniquemd5.txt > uniquelist.txt \n\nsort uniquelist.txt -r -o uniquelist.txt\nfor line in $(cat uniquelist.txt)\ndo\n file=$(basename $line) path=\"$2/file\"\n\n if [ ! -f $path ];\n then \n cp $line $2 \n else \n cp $line $path.JPG \n fi \n\n rm uniquelist.txt md5.txt uniquemd5.txt list.txt\n\ndone" ]
[ "linux", "bash", "shell", "md5" ]
[ "group by count with expression", "I have a spark data frame where 2 columns can represent the id: first_id, second_id.\nI want to count rows where the grouping will be : \n\na.first_id = b.first_id OR a.second_id = b.second_id\n\n\nI couldn't find examples of that, and I understand that the problem is that the grouping key is not deterministic (2 unrelated rows might end up in the same group since there is a third row connecting them). my questions are :\n\n\nMathematically what is the algorithm to solve this? (graph query? something else?) \nIs there a spark implementation for that?" ]
[ "apache-spark", "graph" ]
[ "Hide the input field div class using javascript", "I have a payment form,in which when I click on the internet banking ,all the input field be disabled and instead show some images. this is the fiddle upto which i have done http://jsfiddle.net/f8Fd3/4/ No where I cant hide the input text field using their class id.\n\nthis is the js\n\nfunction cc()\n{\n $('#cards.credit-card').removeClass(\"visa mastercard\").addClass(\"visa\");\n\n}\n\nfunction dc()\n{\n $('#cards.credit-card').removeClass(\"visa mastercard\").addClass(\"mastercard\");\n}\nfunction ib()\n{\n\n}\n\n\nplease check the fiddle to get a clear picture" ]
[ "javascript", "jquery", "html", "css" ]
[ "Find lines that have partial matches", "So I have a text file that contains a large number of lines. Each line is one long string with no spacing, however, the line contains several pieces of information. The program knows how to differentiate the important information in each line. The program identifies that the first 4 numbers/letters of the line coincide to a specific instrument. Here is a small example portion of the text file.\n\nexample text file \n\n 1002IPU3...\n POIPIPU2...\n 1435IPU1...\n 1812IPU3...\n BFTOIPD3...\n 1435IPD2...\n\n\nAs you can see, there are two lines that contain 1435 within this text file, which coincides with a specific instrument. However these lines are not identical. The program I'm using can not do its calculation if there are duplicates of the same station (ie, there are two 1435* stations). I need to find a way to search through my text files and identify if there are any duplicates of the partial strings that represent the stations within the file so that I can delete one or both of the duplicates. If I could have BASH script output the number of the lines containing the duplicates and what the duplicates lines say, that would be appreciated. I think there might be an easy way to do this, but I haven't been able to find any examples of this. Your help is appreciated." ]
[ "bash", "duplicates" ]
[ "C# Threading and multi-user program", "I have a program that works as a back end for a serial terminal. This id intended to be a Fallout prop. I have this working fine with one serial port and one main program.\n\nI would however like to make this is a functional, multi-user environment that opens on a selection on serial ports and has each one running in a seperate thread.\n\nI'm not asking for a Blue Peter mirracle and \"heres one I made earlier\". I just some help understanding how Treading works properly.\n\nSo far I have had one simple threaded application that moved the cursor on the terminal, wrote the current time and the moved the cursor back once every minute.\n\nThe code for that is here:\n\nstatic void StartClock()\n{\nTimerCallback tmCallback = WriteTime;\nTimer timer = new Timer(tmCallback, null, 60000, 60000);\n}\n\nstatic void WriteTime(object WT)\n{\nstring TimeDate = DateTime.Now.ToString();\nchar[] TimeDateArr = TimeDate.ToCharArray();\nstring test = \"\";\nArray.Reverse(TimeDateArr);\nArray.Resize(ref TimeDateArr, 8);\nArray.Reverse(TimeDateArr);\nArray.Resize(ref TimeDateArr, 5);\nforeach (char c in TimeDateArr)\n{\ntest = test + c.ToString();\n}\nPositionCursor(75, 1);\nwrite(test);\nPositionCursor(2, 23);\n}\n\n\nMy issue is not fully understanding how treading works.\n\nIf anyone could properly explain what parts of this are doing and maybe how I would look at starting what I want to do.\n\nThanks in advance" ]
[ "c#", "multithreading", "serial-port" ]
[ "setting up facebook api login with php authorization", "Currently I have the facebook api working. I have included scope string to grab extra permissions. \n\nI am lacking the ability to authorize access to restricted pages on my site. How can I set it up so when facebook logs the user in they are also logged in to my site?\n\n<?php \ninclude 'src/facebook.php';\n\n// Create our Application instance (replace this with your appId and secret).\n$facebook = new Facebook(array(\n 'appId' => '****************',\n 'secret' => '****************',\n 'cookie' => true\n));\n\n\n// Get User ID\n$user = $facebook->getUser();\n\n// We may or may not have this data based on whether the user is logged in.\n//\n// If we have a $user id here, it means we know the user is logged into\n// Facebook, but we don't know if the access token is valid. An access\n// token is invalid if the user logged out of Facebook.\n\nif ($user) {\n try {\n // Proceed knowing you have a logged in user who's authenticated.\n $user_profile = $facebook->api('/me');\n } catch (FacebookApiException $e) {\n error_log($e);\n $user = null;\n }\n}\n\n// Login or logout url will be needed depending on current user state.\nif ($user) {\n $logoutUrl = $facebook->getLogoutUrl();\n echo \"<a href='$logoutUrl'>Logout</a>\";\n} else {\n $statusUrl = $facebook->getLoginStatusUrl();\n $loginUrl = $facebook->getLoginUrl(array(\n 'scope' => 'user_checkins, user_location, friends_checkins')\n );\n echo \"<a href='$loginUrl'>Login</a>\";\n}\n\n?>\n\n\n<h3>Welcome to your profile</h3>\n <?php\n echo $user_profile['first_name'];\n echo ' <span> </span> ';\n echo $user_profile['last_name'];\n ?>\n\n\nThis is the basic php api from facebook." ]
[ "facebook", "api" ]
[ "Getting the average price of products in a category", "My database looks like:\n\nTable - Products\nproducts_id \nproducts_price \n\nTable - Products_to_Categories\ncategories_id\nproducts_id \n\nTable - Products_Descriptions\nproducts_name\n\nTable - Categories_Descriptions\ncategories_name\n\n\nThere's a bunch other columns but these are the ones I need.\n\nI want to select all the above columns but I also want to end up with an average product price for each category \n\nI know it's probably going to include the AVG() function but I've tried a bunch of different queries (I'm a bit of a learner) and I'm buggered if I can figure out something that works. Is it even possible to do this with just one query? I just can't get my head around it at the moment.\n\nAny help would be most gratefully received. :(" ]
[ "mysql", "sql" ]
[ "In Python, changing inherited behavior without rewriting the parent class", "In Python, I have a class ParentClass. It defines method ParentClass.process(), among the others. ParentClass is inherited by two child classes: ChildA and ChildB. This is a part of the system which goes as a pip wheel. The user should not be able to change the code of the package.\n\nDuring the execution, the system creates objects of ChildA and ChildB.\n\nNow, I want to give the user of the system ability to change the behavior of .process() method for objects of both ChildA and ChildB. \n\nObviously, she can do that by redefining ChildA.process() and ChildB.process() but that would be copying of identical behavior twice and overall seems like a very odd approach.\n\nThe user could possible inherit her own class from ParentClass and redefine .process() there but that means I need somehow dynamically tell ChildA and ChildB what to inherit. \n\nAlso, all classes (ParentClass, ChildA and ChildB) have other methods, apart from .process(), which need to be retained without changes.\n\nPlease help me figuring out the most convenient for the user (and the most \"pythonic\", probably) way of solving this." ]
[ "python", "class", "oop", "inheritance" ]
[ "{kdenlive} How do I join two adjacent clips into one in kdenlive?", "Suppose I made a mistake: I cut a clip into two using the scissor tool, and I did it off by a few frames. I want to undo the mistake and join the clips together again and split them at the right frame.\n\nPlease assume the case where a simple Undo won't work due to how broken the undo functionality is in kdenlive.\n\nI have searched high and low, and found lots of answers that boil down to \"you don't really need this, because for each and every thing you could possibly need it for, you can achieve the same goal without joining the clips together\". Yes, it's possible, but its cumbersome and workaroundy and every subsequent operation on the affected time range requires twice as many clicks and twice as many attention registers.\n\nI will accept an authoritative negative answer to the effect of \"this is just not possible, full stop\", coming from an expert who knows kdenlive through and through. Knowledge of impossibility is valuable. I will then know that I must be more careful to avoid the problem. For example, whenever I split a clip, I could back the uncut version on an unused track: a manually maintained undo stack. STILL better than constantly grouping and ungrouping and having to remember what must be grouped and what not." ]
[ "video-editing" ]
[ "Getting string in between delimiters", "Good day everyone,\n\nI have problems with breaking down string (\"cutting\" and using part of string which is in between delimiters).\n\nSo far this is was what I managed to do:\n\n std::string begin_processed_received_DATA = \"&7?@670*/5#^\";\n std::string end_processed_received_DATA = \"*8d4a#%\";\n\n processed_received_DATA = receive_DATA;\n\n //Checks if delimiter exists in message (by setting NO_DELIMITER to represent number where END DELMITER is in string array)\n std::size_t NO_DELIMITER = processed_received_DATA.find(end_processed_received_DATA);\n\n if (NO_DELIMITER != std::string::npos) {\n //Deletes string from end\n processed_received_DATA.resize(processed_received_DATA.find(end_processed_received_DATA));\n\n //Deletes string from begining (starting at string[0])\n processed_received_DATA.erase(0, processed_received_DATA.find(begin_processed_received_DATA) + begin_processed_received_DATA.size());\n }\n\n else {\n return 201502;\n }\n\n\nDoes anyone have any ideas how I should approach this problem ?\n\nExample receive_DATA would be somthing like this: 984GE#$% 534'694 4685)_(9357uf0 di,stre89/4&7?@670*/5#^nulter.dd/se 895/68.476*8d4a#%897 R#3t746+- @1\n\nI must notify that my receive_DATA string consists many symbols, numbers, whitespaces, letters and is approximately 20000 symbols long.\nHere is the picture to get an idea what kind of string it is.\n(I remember solving such problem with way shorter string in similar manner)" ]
[ "c++", "string", "delimiter" ]
[ "Mule Soft Data Weave", "I want to write a Data Weave Code wherein if the data is null then it should route to 400. How do I write this in Mule Soft?\n\nMy flow is as follows:\nHTTP -->Transfomer-->Logger\n\nTranformer DW code\n{\n event_ops_type: payload.EDM_generic_consumer_message.event_meta_data.event_operation_type\n}\n\nNow what I want to implement is if \"event_ops_type\" is null then route to 400(Exception Handling)?" ]
[ "mule", "anypoint-studio", "dataweave", "mule-esb" ]
[ "How is this Checksum calculated?", "Good day friends.\nI'm using Qt C++ and I've ran into a issue calculating a checksum for a serial communication protocol. I'm very new to serial programming and this is a little above my knowledge atm\nPer their documentation.\nCommunication format\n\nHead Address CID Datalength Data Check Tail\n\n0x7E 0x01~0x0e 0x01 - - checksum 0x0D \n\nthe head never changes, the address can change, the CID is a command\nI don't understand how the data length is to be calculated\nthe checksum I'm not clear on how they calculate it. Are they taking the first 5 bytes then calculating the checksum then adding the tail ? or only the "command" which to me is the CID byte. but that doesn't make sense.\nThe function they use to calculate the checksum\nbyte check(byte* buf, byte len)\n{\n byte i, chk= 0;\n int sum = 0;\n for(i = 0; i < len; i++)\n {\n chk ^= buf[i];\n sum += buf[i];\n }\n return ((chk^sum)&0xFF);\n}\n\nWhich I Wrote in Qt as\nunsigned char MainWindow::Checksum_Check(char* buf, char len)\n{\n unsigned char i, chk = 0;\n int sum = 0;\n for(i = 0; i < len; i++)\n {\n chk ^= buf[i];\n sum += buf[i];\n }\n return ((chk^sum)&0xFF);\n}\n\nSo sending a hexidecimal command using QBytearray\n QByteArray Chunk("\\x7E\\x01\\x01\\x00");\n\n char *TestStr = Chunk.data();\n unsigned char Checksum = Checksum_Check(TestStr, Chunk.length()); // tried sizeof(char) even tried sizeof(Chunk.size())\n\n const char cart[] = {'\\x7E', '\\x01', '\\x01', '\\x00', checksum, '\\x0D'};\n QByteArray ba4(QByteArray::fromRawData(cart, 6));\n SerialPort->write(ba4.toHex()); // Tried write(ba4); as well. \n SerialPort->waitForBytesWritten(1000);\n\nWhat i get in qDebug() is\nChecksum "FE"\nCommand "7E010100FE0D"\nWhich looks correct but the device ignores the request.\nMy question is. Is the checksum calculated correctly by me or am I missing something crucial ?\nAny advice or help would be most welcome as I am stuck.\nIve checked it with one of their example commands:\n7E 01 F2 02 FF FF FE 0D\n\nwhich if i do this:\nQByteArray Chunk("\\x7E\\x01\\xF2\\x02\\xFF\\xFF");\n\nchar *TestStr = Chunk.data();\nunsigned char Checksum = Checksum_Check(TestStr, Chunk.length());\n\nconst char cart[] = {'\\x7E', '\\x01', '\\xF2', '\\x02','\\xFF', '\\xFF', Checksum, '\\x0D'};\nQByteArray ba4(QByteArray::fromRawData(cart, 8));\n\nQString hexvalue;\nhexvalue = QString("%1").arg(CRC, 0, 16, QLatin1Char( '0' ));\n\nqDebug() << "Checksum " << hexvalue.toUpper();\nqDebug() << "Command " << ba4.toHex().toUpper();\n\nSerialPort->write(ba4.toHex());\n\nGives me\nChecksum "FE"\nCommand "7E01F202FFFFFE0D"\n\nwhich is correct. By the looks of things. But the device still doesn't respond\nSo I just wanna verify that the checksum is in fact generated correctly.\nAlso in the documentation is an example\nPC software Command:\nbuf[0] = 0x7E; //head\nbuf[1] = 0x01; //addr\nbuf[2] = 0x01; //CID\nbuf[3] = 0x00; //data length\nbuf[4] = CHK; //Check code\nbuf[5] = 0x0D; //tail\n\nAnd here is another question. How can a checksum buf[4] be generated while the ByteArray is still being constructed. It doesn't make sense to me at this point. I dont know/understand which bytes they use for the checksum\nAnyone? thanks" ]
[ "c++", "qt", "io", "serial-port" ]
[ "How do I get href from a tag in a table?", "I have a webmethod like,\n\npublic List<List<string>> HelloWorld() {\n\n WebClient webClient = new WebClient();\n string page = webClient.DownloadString(\"http://www.deu.edu.tr/DEUWeb/Guncel/v2_index_cron.html\");\n\n HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n doc.LoadHtml(page);\n\n List<List<string>> table = doc.DocumentNode.SelectSingleNode(\"//table\")\n .Descendants(\"tr\")\n .Skip(1)\n .Select(tr => tr.Elements(\"td\").Select(td => td.InnerText.Trim()).ToList())\n .ToList();\n\n return table;\n}\n\n\nI've got the information inside the table but I want to get also <a href=\"Link\"> link information of the table.\n\nWhat should I add to the method? I need both information at the same time.\n\nHTML\n\n<table>\n <tr>\n <td>\n <img/>\n </td>\n <td>\n <a href=\"what I want\">Text</a>\n </td>\n </tr>\n .....\n</table>" ]
[ "c#", "web-services", "html-agility-pack" ]
[ "Selenium grid 2 internet explorer is really slow", "I have been trying out Selenium Grid 2 and I have noticed that Internet Explorer is really slow with Grid 2 (no problem with Chrome or Firefox). I know that in general Internet Explorer is slow with Selenium but with Grid 2, there are significant delay between each key being sent to the text box like 4,5 seconds delay. I'm not sure if it is because of the configuration. Here are how I start a node with 1 instance of IE:\n\njava -jar selenium-server-standalone-2.32.0.jar -role node -hub http://localhost:4444/grid/register -port 5553 -nodeTimeout 120 -maxSessions 1 -browser browserName=iexplore,maxInstances=1 -Dwebdriver.ie.driver=C:\\grid2\\drivers\\IEDriverServer.exe\n\n\nI'm currently testing grid2 with IWebDriver and C#" ]
[ "c#", "internet-explorer", "selenium" ]
[ "Twitter Bootstrap Carousel Random load 5 items", "I have the following Twitter bootstrap carousel with 20 items, how can I randomly only load 5 of the items on load? I found another script that hid the items however this wouldnt work due to it being a slideshow.\n\n<div id=\"myCarousel\" class=\"carousel slide\">\n<!-- Carousel items -->\n<div class=\"carousel-inner\">\n<div class=\"active item\"><img src=\"img/slider/1.jpg\"></div>\n<div class=\"item\"><img src=\"img/slider/2.jpg\"></div>\n<div class=\"item\"><img src=\"img/slider/3.jpg\"></div>\n<div class=\"item\"><img src=\"img/slider/4.jpg\"></div>\n<div class=\"item\"><img src=\"img/slider/5.jpg\"></div>\n</div>\n<!-- Carousel nav -->\n<a class=\"carousel-control left\" href=\"#myCarousel\" data-slide=\"prev\">‹</a>\n<a class=\"carousel-control right\" href=\"#myCarousel\" data-slide=\"next\">›</a>\n</div></div>\n\n<script type='text/javascript'>\n$(document).ready(function() {\n $('.carousel').carousel({\n interval: 8000\n })\n });\n </script>" ]
[ "jquery", "html", "twitter-bootstrap" ]
[ "ASP.NET MVC: relationship between models and MembershipUsers", "I have a model, Docs, with a guid column, author_id, which should reference a MembershipUser.\n\nI'm using the standard MembershipProvider (I only changed the db name), and of course I haven't a model for MembershipUsers.\n\nI can easily define some methods in class Docs to get MembershipUser for a Doc and all Docs for a MembershipUser, but some things are tricky (listing users, show how many docs each user has); furthermore, I feel I'm using MVC in an odd way: it seems to me that it would be easier if I had a MembershipUsers model...\n\nHow can I implement this relationship? Should I implement a model for MembershipUsers?\n\nthanks\n\nupdate: I realize I wasn't clear at all.\n\nSay I want to list all my users and their docs.\nOne way to do this is:\n\nViewModel model = new ViewModel()\n{\n Users = from MembershipUser user in Membership.GetAllUsers(page, pagesize, out totalusers)\n select new UserWithDocs\n {\n User = user,\n Docs = context.Docs.Where(c => c.author_id == (Guid) user.ProviderUserKey)\n },\n UsersCount = totalusers\n};\n\n\nThis works, but generates one separate query for each user.\n\nI could get an array of users' guids and then query for Docs where author_id IN list_of_guids, but then I should manually associate each doc to its author.\n\nWhat is a better solution?" ]
[ "asp.net-mvc", "asp.net-membership" ]
[ "Matplotlib \"ValueError: x and y must be the same size\"", "I'm trying to create a scatter plot very similar to . \n\nMy code is below. I'm comparing two groups of schools, one in a system and the other group is that system's peers. \nThis was modeled after the directions found here. \n\nplt.figure(figsize=(10,8))\nplt.scatter(sys_peers_sat_earning['MD_EARN_WNE_P6'][sys_peers_sat_earning['SystemorPeer'] == 'USM'],\n sys_peers_sat_earning['SAT_AVG'][sys_peers_sat_earning['SystemorPeer'] == 'USM'],\n marker='x',\n color='b',\n alpha=0.7,\n s = 124,\n label='USM Schools')\nplt.scatter(sys_peers_sat_earning['MD_EARN_WNE_P6'][sys_peers_sat_earning['SystemorPeer'] == 'Peer'],\n sys_peers_sat_earning['SAT_AVG'][sys_peers_sat_earning['SystemorPeer'] == 'Peer'],\n marker='x',\n color='b',\n alpha=0.7,\n d = 124,\n label='USM Peers')\nplt.title('SATs and Earnings of Students Not Enrolled 6 Yrs. After Entry')\nplt.ylabel('Median earnings of students working and not enrolled 6 years after entry')\nplt.xlabel('Average SAT equivalent score of students admitted')\nX_train[:,0]\nplt.legend(loc='upper right')\n\n\nerrors both with and without the line of X_train[:,0] mentioned here came as follows: ValueError: x and y must be the same size\n\nCan someone talk to me like I'm two with steps on how to edit this?" ]
[ "python", "matplotlib" ]
[ "Jenkins build failing with 0: command not found", "I am trying to build a Jenkins pipeline to find if any files are present in the folder and delete them. But whenever I tried to run the build, it fails with below command :\n\nscript.sh: line 2: 0: command not found\n\nWhat could be the possible problem with this Jenkins pipeline script?\nnode("name") {\ntry{\n def files\n stage('Check if files are present'){\n sshagent (credentials: ['cred']) {\n files = sh('''\n $(ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null user@server "cd /path/ && find . -name 'file-0.0.*' | wc -l;")\n ''')\n }\n }\n stage('Delete files'){\n echo files\n if(files != 0) {\n sshagent (credentials: ['cred']) {\n sh 'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null user@server "cd /path/ && find 'file-0.0.*' -maxdepth 0 -mindepth 0 -mtime +14 -type d -exec rm -r {} \\\\;"'\n }\n }\n }\n \n}finally{\n stage('Clean up') {\n cleanWs()\n }\n}\n\n}" ]
[ "jenkins" ]
[ "How can I adjust load balancing rule by feign in spring cloud", "As I know, feign include ribbon's function, and I prove it in my code.\n\nWhen I use feign, the default rule is Round Robin Rule.\nBut how can I change the rule in my feign client code, is ribbon the only way?\n\nHere is my code below, so please help.\n\nConsumerApplication.java\n\n@SpringBootApplication\n@EnableDiscoveryClient\n@EnableFeignClients\n@EnableCircuitBreaker\npublic class ConsumerApplication {\n public static void main(String[] args) {\n SpringApplication.run(ConsumerApplication.class, args);\n }\n}\n\n\nUserFeignClient .java\n\n@FeignClient(name = \"cloud-provider\", fallback = UserFeignClient.HystrixClientFallback.class)\npublic interface UserFeignClient {\n @RequestMapping(\"/{id}\")\n BaseResponse findByIdFeign(@RequestParam(\"id\") Long id);\n\n @RequestMapping(\"/add\")\n BaseResponse addUserFeign(UserVo userVo);\n\n @Component\n class HystrixClientFallback implements UserFeignClient {\n private static final Logger LOGGER = LoggerFactory.getLogger(HystrixClientFallback.class);\n\n @Override\n public BaseResponse findByIdFeign(@RequestParam(\"id\") Long id) {\n BaseResponse response = new BaseResponse();\n response.setMessage(\"disable\");\n return response;\n }\n\n @Override\n public BaseResponse addUserFeign(UserVo userVo) {\n BaseResponse response = new BaseResponse();\n response.setMessage(\"disable\");\n return response;\n }\n }\n}\n\n\nFeignController.java\n\n@RestController\npublic class FeignController {\n\n @Autowired\n private UserFeignClient userFeignClient;\n\n @GetMapping(\"feign/{id}\")\n public BaseResponse<Date> findByIdFeign(@PathVariable Long id) {\n BaseResponse response = this.userFeignClient.findByIdFeign(id);\n return response;\n }\n\n @GetMapping(\"feign/user/add\")\n public BaseResponse<Date> addUser() {\n UserVo userVo = new UserVo();\n userVo.setAge(19);\n userVo.setId(12345L);\n userVo.setUsername(\"nick name\");\n BaseResponse response = this.userFeignClient.addUserFeign(userVo);\n return response;\n }\n}" ]
[ "spring", "spring-cloud", "netflix-feign", "netflix-ribbon" ]
[ "How to limit choices to Foreign keys in Django admin", "I run into a problem when using the Django admin. I'm building a small ScrumBoard. It has projects, with statuses, stories and tasks.\n\nConsider the following model:\n\n@python_2_unicode_compatible\nclass Project(models.Model):\n name = models.CharField(max_length=100)\n\n class Meta:\n verbose_name = _('Project')\n verbose_name_plural = _('Projects')\n\n def __str__(self):\n return self.name\n\n@python_2_unicode_compatible\nclass Status(models.Model):\n name = models.CharField(max_length=64) # e.g. Todo, In progress, Testing Done\n project = models.ForeignKey(Project)\n\n class Meta:\n verbose_name = _('Status')\n verbose_name_plural = _('Statuses')\n\n def __str__(self):\n return self.name\n\n\n@python_2_unicode_compatible\nclass Story(models.Model):\n \"\"\"Unit of work to be done for the sprint. Can consist out of smaller tasks\"\"\"\n project = models.ForeignKey(Project)\n name=models.CharField(max_length=200)\n description=models.TextField()\n status = models.ForeignKey(Status)\n\n class Meta:\n verbose_name = _('Story')\n verbose_name_plural = _('Stories')\n\n # represent a story with it's title\n def __str__(self):\n return self.name\n\n\nThe problem: when an admin user creates a story he will see statuses from all the projects instead of the status from one project." ]
[ "django", "foreign-keys", "admin" ]
[ "unable to generate app-specific shared secret", "iTunesconnect post on 6/21/17 states that an app offering auto-renewable subscriptions can be transferred to a different developer by generating an app-specific shared secret. I followed the instructions up to \"5. Click Generate App-Specific Shared Secret.\" I got a message flashing on the screen that says \"We cannot process your request.\" itunesconnect toll-free number is not answering because it is the weekend. I will try on Monday but meanwhile I wonder if anyone has had this problem and resolved it?" ]
[ "ios", "app-store-connect" ]
[ "Dynamically add RealtimeDatabaseTriggers", "Is it possible to dynamically add RealtimeDatabaseTriggers?\nIn my use case, I need to add (and remove) new RealtimeDatabaseTriggers as a result of previous write operation. \n\nDocs state only how to add triggers on functions deployment (via exports)\nhttps://firebase.google.com/docs/functions/database-events" ]
[ "firebase", "firebase-realtime-database" ]
[ "Wrapping STL container return types using Pybind11", "I'm tying to wrap a C++ function (using Pybind11) that returns an STL container which is itself wrapped in a smart pointer. An example is shown below. The function is overloaded so I have to specify the signature.\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include \"my_class.h\"\n\ntypedef std::array<std::complex<double>, 4> ArrayComplex4;\nPYBIND11_MAKE_OPAQUE(ArrayComplex4);\n\nnamespace py = pybind11;\nusing namespace my_namespace;\n\nPYBIND11_MODULE(my_module, m) {\n py::class_<MyClass>(m, \"MyClass\", py::dynamic_attr())\n .def(\"my_function\", (std::unique_ptr<ArrayComplex4> (MyClass::*)(double)) &MyClass::my_function)\n .def(\"my_function\", (std::unique_ptr<ArrayComplex4> (MyClass::*)(double, double)) &MyClass::my_function);\n}\n\n\nThe module will compile but it will give an error when I try to use the function in Python:\n\n\n TypeError: Unable to convert function return value to a Python type! \n\n\nI'm sure I'm just setting something up wrong for Pybind11. Thanks for any help!\n\nEDIT\n\nThe problem was definitely in my attempt to bind the std::Array data type. I ended up modifying the code to use std::Vector and then Pybind11 had no issues. See AS Mackey's answer below for how one might bind the std::Array containers." ]
[ "python", "c++", "pybind11" ]
[ "bind event on element before its fired", "I have a search results div that I want to be hidden if the user clicks anywhere outside of it. It is not a child of the search criteria div.\nThe problem I'm having is that .show() does not seem to be firing at all. I would have thought that the .hide() only fires after the initial click on the search button. Obviously when the search results div is closed I .unbind() the event.\n\nKinda stumped on this one so any help would be greatly appreciated.\n\nHere's some sample code.\n\nfunction search(){\n $('#criteria').bind('click',function(){$('#results').hide();});\n $('#results').show();\n $('#results').html('some html from ajax call');\n}\n\n\n\n\n<div id=criteria>\n <input id=criteria1 /><input id=criteria2 /><input id=criteria3 />\n <!-- a whole page of input elements and a ajax lookup -->\n <input type=text id=lookup /><input type=\"button\" onclick=\"search()\" value=\"search\" />\n</div>\n<div id=results></div>" ]
[ "javascript", "jquery", "event-handling", "bind" ]
[ "Flash: gradient fill disappears when it's drawn outside the bounds of its parent?", "I'm trying to draw a gradient in Flash using beginGradientFill and drawRect, but when the rect being drawn is partially outside the bounds of the parent, the gradient isn't drawn at all.\n\nFor example, consider the code below:\n\nfunction testGradient():void {\n var g:Graphics = container.graphics;\n var width:Number = container.width;\n var height:Number = container.height;\n var y:Number = 0;\n var x:Number = 0;\n var ratios:Array = [255 * y / height, 255 * (y + height) / height];\n g.beginGradientFill(GradientType.LINEAR, [0xFF, 0xFF], [0.6, 0], \n ratios, null);\n g.lineStyle(1, 0xFF0000);\n g.drawRect(x, y, width, height);\n g.endFill(); \n}\n\n\nWhen the rectangle being drawn lies within the bounds of container, everything works:\n\n\n\nHowever, if the rectangle lies outside of the bounds of the container, the gradient isn't drawn at all. For example, if the code is changed to:\n\n...\nvar x:Number = 10;\nvar y:Number = 10;\n...\n\n\nThen the gradient disappears:\n\n\n\nShort of doing the math required to draw the box inside the bounds of the parent (and fixing up the gradient so it looks correct), is there any way to deal with this?" ]
[ "flash", "gradient" ]
[ "Symfony 3 - Images not updating instantly", "Currently working on a Symfony 3 application. I created a service that lets users upload an image, then choose a crop section, and finally saves the avatar with a specific height and width. Avatars are saved in the /web/img/uploads/avatar/ folder. I'm using the user id to name the file. So the user with the id 13 will have his avatar saved at /web/img/uploads/avatar/13.png.\n\nMy problem is that, when an user updates his avatar, the file is correctly replaced in the folder, but on the actual website the avatar displayed remains the old one for a while.\nIn dev environment this takes something like a few minutes before the new avatar replaces the old one. Even if I go to the avatar url (localhost/app_dev.php/img/uploads/avatar/xxx.png) I still see the old avatar for a while before it's eventually replaced by the new one. Tho, the avatar in the filesystem is instantly replaced, as expected.\n\nI figured this might come from the cache. I tried searching for solutions on google but all I found was related to the LiipImagineBundle and its cache manager, but I'm not using this bundle...\n\nI tried deleting the old avatar if it exists after figuring out its name, and before actually croping and saving the image. As follows.\n\nif(file_exists($dst)) {\n unlink($dst);\n}\n\n\nBut it doesn't work. At all.\n\nAny ideas?" ]
[ "php", "image", "file", "caching", "symfony" ]
[ "Select element corresponding to maximum/minimum value in different column", "I am trying to find the value corresponding to maximum value in another column in my array, but get an error with the present code saying Unable to cast object of type WhereSelectArrayIterator2[Main.AllClasses.MaxMin,System.Int32] to type 'System.IConvertible'.`\n\nI am assigning a list of type MaxMin to an array and then trying to calculate the maxima and its corresponding element in the second column.\nHere's the code: \n\nMaxMin finalMax = new MaxMin();\nif (maxima.Count != 0)\n{\n MaxMin[] maxArray = maxima.ToArray();\n finalMax.val = maxArray.Select(x => x.val).Max();\n finalMax.cnt = Convert.ToInt32(maxArray.Where(x => x.val.Equals(finalMax.val)).Select(x => x.cnt));\n}\n\n\nHere's the full code:\n\npublic MaxMin Maxima(float[] values, MaxMin drop)\n {\n float[] T = new float[5] { 0, 0, 0, 0, 0 };\n float[] dT = new float[4] { 0, 0, 0, 0 };\n int count = 0;\n List<MaxMin> maxima = new List<MaxMin>();\n\n\n count = values.Length;\n\n\n try\n {\n for (int i = 99; i < count - 100; i++)\n {\n MaxMin max = new MaxMin();\n\n T[0] = values[i - 1];\n T[1] = values[i];\n T[2] = values[i + 1];\n T[3] = values[i + 2];\n T[4] = values[i + 3];\n\n dT[0] = T[1] - T[0];\n dT[1] = T[2] - T[1];\n dT[2] = T[3] - T[2];\n dT[3] = T[4] - T[3];\n\n\n if (i > drop.cnt) //cutoff time above which calculation of minima will be initiated\n {\n if (dT[1] > 0 && dT[3] < 0)\n {\n float[] diff = new float[8] { 0, 0, 0, 0, 0, 0, 0, 0 };\n diff[0] = (values[i + 1] - values[i - 19]);\n diff[1] = (values[i + 1] - values[i + 19]);\n diff[2] = (values[i + 1] - values[i - 49]);\n diff[3] = (values[i + 1] - values[i + 49]);\n diff[4] = (values[i + 1] - values[i - 69]);\n diff[5] = (values[i + 1] - values[i + 69]);\n diff[6] = (values[i + 1] - values[i - 99]);\n diff[7] = (values[i + 1] - values[i + 99]);\n\n if (diff[0] < 20 && diff[1] < 20 && diff[2] < 20 && diff[3] < 20 && diff[2] > 0 && diff[3] > 0 && diff[4] > 0.5 && diff[5] > 0.5 && diff[6] > 2 && diff[7] > 2)\n {\n max.cnt = i + 1;\n max.val = values[i + 1];\n maxima.Add(max);\n }\n\n }\n }\n }\n\n\n MaxMin finalMax = new MaxMin();\n\n if (maxima.Count != 0)\n {\n MaxMin[] maxArray = maxima.ToArray();\n finalMax.val = maxArray.Select(x => x.val).Max();\n finalMax.cnt = Convert.ToInt32(maxArray.Where(x => x.val.Equals(finalMax.val)).Select(x => x.cnt));\n }\n\n else\n {\n finalMax.val = values.Max();\n finalMax.cnt = Array.IndexOf(values, values.Max());\n }\n\n\n return finalMax;\n }\n\n catch (Exception ex)\n {\n throw ex;\n }\n }" ]
[ "c#", "linq" ]
[ "Is there a Javascript equivalent to the Python string constants?", "I was looking for a Javascript equivalent to the constant string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz', but I haven't been able to find any.\nIt is no trouble to implement it myself. I found it useful in Python and now that I am working with Javascript I'd be happy to discover if something similar exists, and where to find it." ]
[ "javascript", "python" ]
[ "Searching SQL server 2005 for string value across all tables get table name in addition to record", "Found this on Server Fault:\n\n\n I've found this script to be helpful...\n\n\nBEGIN TRAN\n\ndeclare @search nvarchar(100)\nset @search = 'string to search for'\n\n-- search whole database for text\nSET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED\n\nIF nullif(object_id('tempdb..#tmpSearch'), 0) IS NOT NULL DROP TABLE #tmpSearch\nCREATE TABLE #tmpSearch (\n ListIndex int identity(1,1),\n CustomSQL nvarchar(2000)\n)\nPrint 'Getting tables...'\nINSERT #tmpSearch (CustomSQL)\nselect 'IF EXISTS (select * FROM [' + TABLE_NAME + '] WHERE [' + COLUMN_NAME + '] LIKE ''%' + @search + '%'') BEGIN PRINT ''Table ' + TABLE_NAME + ', Column ' + COLUMN_NAME + ''';select * FROM [' + TABLE_NAME + '] WHERE [' + COLUMN_NAME + '] LIKE ''%' + @search + '%'' END' FROM information_schema.columns\nwhere DATA_TYPE IN ('ntext', 'nvarchar', 'uniqueidentifier', 'char', 'varchar', 'text')\nand TABLE_NAME NOT IN ('table_you_dont_want_to_look_in', 'and_another_one') \n\n\nPrint 'Searching...\n\n'\ndeclare @index int\ndeclare @customsql nvarchar(2000)\nWHILE EXISTS (SELECT * FROM #tmpSearch)\nBEGIN\n SELECT @index = min(ListIndex) FROM #tmpSearch\n\n SELECT @customSQL = CustomSQL FROM #tmpSearch WHERE ListIndex = @index\n\n IF @customSql IS NOT NULL\n EXECUTE (@customSql)\n\n SET NOCOUNT ON\n DELETE #tmpSearch WHERE ListIndex = @index\n SET NOCOUNT OFF\nEND\n\nprint 'the end.'\nROLLBACK\n\n\nBut I'm curious how I could modify this script to also give the table name, as it only returns the record(s) with the search string....\n\nWasn't able to comment on the original answer due to 1 Rep on that version of Stack Exchange." ]
[ "sql-server" ]
[ "GDI objects leaks using Direct 2D GdiInteropRenderTarget", "I'm trying to render a bitmap using both Gdi and Direct 2D on a compatible render target.\nI create the compatible target with D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_GDI_COMPATIBLE option and then I do as follows:\n\nHDC hdc=NULL;\nID2D1GdiInteropRenderTarget *gdiTarget=NULL;\ntarget->QueryInterface(__uuidof(ID2D1GdiInteropRenderTarget), (void**)&gdiTarget);\ntarget.BeginDraw();\nHRESULT hr=gdiTarget->GetDC(D2D1_DC_INITIALIZE_MODE_CLEAR, &hdc);\nif(SUCCEEDED(hr))\n{\n /* Gdi drawing code(hdc)*/\n\ngdiTarget->ReleaseDC(NULL);\n}\n/* Direct2D drawing code\ntarget->EndDraw();\ngdiTarget->Release();\n\n\nBut it seems that something goes wrong, because every time I call this render method I get many GDI objects leaks. I try doing this too:\n\nHDC hdc=NULL;\nID2D1GdiInteropRenderTarget *gdiTarget=NULL;\ntarget->QueryInterface(__uuidof(ID2D1GdiInteropRenderTarget), (void**)&gdiTarget);\ntarget.BeginDraw();\nHRESULT hr=gdiTarget->GetDC(D2D1_DC_INITIALIZE_MODE_CLEAR, &hdc);\nif(SUCCEEDED(hr))\ngdiTarget->ReleaseDC(NULL);\ntarget->EndDraw();\ngdiTarget->Release();\n\n\nand i get leaks as well.\nI also try with DeleteDC() or ReleaseDC() on HDC created by ID2D1GdiInteropRenderTarget but have no success.\n\nAny suggestion? \nThanks in advance!" ]
[ "interop", "gdi", "memory-leaks", "direct2d" ]
[ "How to detect modifications in an object?", "Say I have a collection of items, for example a List<Item>, and I need to check if any of the items is modified from a wrapper class, for example, a value of any of an item's propery is changed through a setter:\n\nList<Item> items = itemsWrapper.getItems(); // itemsWrapper contains a list of items\nItem anItem = items.get(index);\nitem.setProperty(property);\nitemsWrapper.hasChanged(); // ??????\n\n\nI am trying to figure out a way of achieving the last statement, or something similar.\n\nI can see there are similar questions, like this one where using Hibernate is suggested but the answer is very vague, and my question is not DB related. It also mentions setting up a list of listeners, but I am not sure howt his could be done.\n\nOr this other question, where the chosen answer suggests using a dirty flag that you need to rise every time you modify a property. However, my class would actually get dirtier, paradoxically, and I would need to modify dozens of methods that modify item's properties.\n\nIs there another approach, best if it's transparent?" ]
[ "java" ]
[ "How \"Pass Against All Base\" Criteria work in SpatialFIlter. in FME?", "I tried to find out any example or details about pass criteria shown in "Pass against All base" in Spatial filter but no luck. Can anyone explain how its work ? If example Base is Parcel shape file and candidate is building centroid." ]
[ "gis", "geospatial", "fme" ]
[ "How do I convert an ISO 8601 date time String to java.util.LocalDateTime?", "I am reading data from Wikidata. They represent their point in time property, P585 using ISO 8601 spec. However, the same beings with a +. \n\nIf I were using Joda then converting the String to joda dateTime would have been very simple. \n\nnew DateTime(dateTime, DateTimeZone.UTC);\n\n\nHowever, when I do LocalDateTime.parse(\"+2017-02-26T00:00:00Z\") I get an error saying can't parse the character at index 0. Is there a reason for this in Java 8. Joda does it pretty easily without any errors. \n\nI also tried LocalDateTime.parse(\"+2017-02-26T00:00:00Z\", DateTimeFormatter.ISO_DATE_TIME) but in vain. \n\nHow do we get around the Plus sign without having to remove it by string manipulation?" ]
[ "java", "datetime", "java-8" ]
[ "Spring, prototypes, and MBeanExporter", "I am using Spring in conjunction with its MBeanExporter. I have a prototype bean definition which should only be instantiated when a call to ApplicationContext.getBean() is made. However, the MBeanExporter is (incorrectly) instantiating an instance of the prototype bean when bootstrapping the container.\n\nI found this bug report from ages ago, with no notable response.\n\nThis seems to me like it must be a common scenario, so I feel like I must be missing something. It's important that my prototype not be instantiated ahead of time, and that I can use MBeanExporter to make my JMX integration simpler. Can anyone explain what I'm doing wrong?\n\nFor reference, my spring config looks like this:\n\n<bean id=\"foo\" class=\"MyPrototypeClassName\" scope=\"prototype\"/>\n\n<bean id=\"namingStrategy\" class=\"org.springframework.jmx.export.naming.IdentityNamingStrategy\"/>\n\n<bean id=\"exporter\" class=\"org.springframework.jmx.export.MBeanExporter\">\n <property name=\"namingStrategy\" ref=\"namingStrategy\"/>\n <property name=\"autodetect\" value=\"true\"/>\n</bean>" ]
[ "java", "spring", "jmx" ]
[ "httplib2.SSLHandshakeError - Google Cloud Storage Python application", "We are trying to download the data transfer files from our bucket, using the python cloud storage sample application chunked_transfer.py available at the below link \n\nhttps://code.google.com/p/google-cloud-platform-samples/source/browse?repo=storage#git%252Ffile-transfer-json\n\nBut when i execute the application it fails with the below exception. please help me fix this, i need to fix this very fast...\n\nAuthenticating...\nConstructing Google Cloud Storage service...\nstorage\nTraceback (most recent call last):\n File \"chunked_transfer.py\", line 216, in <module>\n download(sys.argv)\n File \"chunked_transfer.py\", line 172, in download\n service = get_authenticated_service(RO_SCOPE)\n File \"chunked_transfer.py\", line 104, in get_authenticated_service\n return discovery_build('storage', 'v1beta1', http=http)\n File \"/home/z062743/Venky_Google/oauth2client/util.py\", line 132, in positional_wrapper\n return wrapped(*args, **kwargs)\n File \"/home/z062743/Venky_Google/apiclient/discovery.py\", line 194, in build\n resp, content = http.request(requested_url)\n File \"/home/z062743/Venky_Google/oauth2client/util.py\", line 132, in positional_wrapper\n return wrapped(*args, **kwargs)\n File \"/home/z062743/Venky_Google/oauth2client/client.py\", line 490, in new_request\n redirections, connection_type)\n File \"/home/z062743/Venky_Google/httplib2/__init__.py\", line 1571, in request\n (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)\n File \"/home/z062743/Venky_Google/httplib2/__init__.py\", line 1318, in _request\n (response, content) = self._conn_request(conn, request_uri, method, body, headers)\n File \"/home/z062743/Venky_Google/httplib2/__init__.py\", line 1253, in _conn_request\n conn.connect()\n File \"/home/z062743/Venky_Google/httplib2/__init__.py\", line 1045, in connect\n raise SSLHandshakeError(e)\nhttplib2.SSLHandshakeError: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed" ]
[ "python", "google-app-engine", "google-cloud-storage", "httplib2" ]
[ "Best way to set few types of accounts in ZendFramework?", "I would like to start first serious project with ZF.\n\nNeeded 3 types of account with different privileges.\n\nAdmin (1 acc)\nManagers\nSalesman\n\nHow do do it? 3 tables in DB, 3 models and 3 login forms? \n\nHow is possible to check via php code if user is admin, or manager, or salesman?" ]
[ "php", "zend-framework", "frameworks" ]
[ "how to get path text from CMFCEditBrowseCtrl?", "I'm working on MFC win32 project. I have dialog with 2 CMFCEditBrowseCtrl controls. After user specifies files on these controls, how to get file paths from these controls?\n\nUpdate: here is my code \n\nSpecifyInputDialog dlg; // this is my dialog inherited from CDialogEx\ndlg.DoModal();\nCString strText;\ndlg.inFileCtrl.GetWindowTextA(strText.GetBuffer(), 500); // inFileCtrl is CMFCEditBrowseCtrl object\n\n\nResults in \"Debug Assertion Failed\" error on last line...\n\nUpdate 2:\n\nCString strText;\ndlg.inFileCtrl.GetWindowText(strText);\n\n\nThe same \"Debug Assertion Failed\" error. I will try to get text while dialog not dissmissed.\n\nUpdate 3 (solved):\n\nI managed to get path text by implementing callback\n\nBEGIN_MESSAGE_MAP(SpecifyInputDialog, CDialogEx)\n ON_EN_CHANGE(IDC_MFCEDITBROWSE1, &SpecifyInputDialog::OnEnChangeMfceditbrowse1)\nEND_MESSAGE_MAP() \n\n\nAnd in handler method:\n\nvoid SpecifyInputDialog::OnEnChangeMfceditbrowse1()\n{\n this->inFileCtrl.GetWindowText(this->inFileString);\n}\n\n\nSo your thought about getting text while dialog are not closed yet was right. Please update your answer thus I could mark it as solution." ]
[ "c++", "visual-studio-2010", "winapi", "mfc" ]
[ "error as \"ORA:00900:Invalid SQL Statement,Vendor code 900\" ,", "Trying to Debug one proc in SQL developer and getting error as "ORA:00900:Invalid SQL Statement,Vendor code 900" ,\nif anyone has faced this error before please suggest what could be issue and how we can fix it ?" ]
[ "sql", "debugging", "compiler-errors", "sqlplus" ]
[ "Can ViewModel class conforms to UITableviewDelegate and UITableViewDataSource in iOS as per MVVM", "I have a viewcontroller which displays a table view with complex UI and different type of data depending on certain conditions/usertype. This involves logic to segregate and process data on user selection and hide/unhide expand/close section. As I am using MVVM pattern, can my viewmodel class conform to UITableviewDelegate and UITableViewDataSource, so that I have a thinner viewcontroller? \n\nSomething like -\n\nclass HomeViewController: UIViewController {\n\n .\n .\n\n let viewModel = HomeViewModel()\n\n @IBOutlet weak var tableView: UITableView!\n\n .\n .\n\n tableView.delegate = viewModel\n tableView.dataSource = viewModel\n}\n\nclass HomeViewModel: UITableViewDataSource, UITableViewDelegate {\n\n//Implement delegates\n\n}" ]
[ "ios", "swift", "mvvm" ]
[ "Upload multiple files with additional information (Spring RestController)", "I know that there are plenty of questions covering the topic, but I cannot figure out how to achieve the following requirement.\n\nI would like to upload a list of files, each one containing some extra information.\nIn the java world this would mean the following:\n\n@NoArgsConstructor\n@Getter\npublic class SkillsVerificationData {\n\n String type; // this information is related to the file \n MultipartFile file;\n}\n\n\nQuestion 1:\nIs this possible for a RestController to achieve such a mapping using a wrapper object? (See first answer of the referenced question- @ModelAttribute)\n\nQuestion 2:\nUsing the following controller method answered in the question referenced above\n\n@RequestMapping(value = \"/upload\", method = RequestMethod.POST, consumes = { \"multipart/form-data\" })\npublic void upload(@RequestPart(\"type\") @Valid String type,\n @RequestPart(\"file\") @Valid @NotNull @NotBlank MultipartFile file) {\n}\n\n\nI assume that it applies for a single file. How should the request parts be defined/described to achieve uploading a List<SkillsVerificationData> or SkillsVerificationData[] ? \n\nNote that the client sends the information using FormData.\n\nThanks in advance!" ]
[ "java", "spring", "spring-boot", "http" ]
[ "Function to remove all the entries of specific duplicate number in the list", "How to delete all the entries of specific number from list.\nHowever the way i followed below is just removing one time\nnewList = [1,2,3,4,5,2,6,7,5,8]\nfor num in newList:\n if newList.count(num) > 1:\n newList.remove(num)\nprint(newList)\n\nResult\n[1, 3, 4, 2, 6, 7, 5, 8]" ]
[ "python-3.x" ]
[ "Initialize FirebaseFirestore in Unity C#", "So I've been working with FireStore for awhile for applications(Typescript/Javascript).\nWorking on something in Unity and and I just finished installing all the proper packages and dependencies for FireStore for unity.\nI have no clue how to initialize a FireStore object to connect it with my Firebase FireStore.\nFirebase with unity seem relatively new as there is little documentation.\nFireStore with unity documentation seems almost non-existent.\nC# firestoreTest\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing Firebase;\nusing Firebase.Analytics;\nusing Firebase.Database;\nusing Firebase.Unity.Editor;\nusing Firebase.Firestore;\n\n\npublic class firestoreTest : MonoBehaviour\n {\n void Start()\n {\n FirebaseFirestore db = FirebaseFirestore.DefaultInstance; // <- Not sure if this is how you properly initialize it.\n\n //\n //The follow code is from the official Firebase Firestore site for C#.\n //Link\n //https://firebase.google.com/docs/firestore/manage-data/add-data#c_5\n\n DocumentReference docRef = db.Collection("TestUnity").Document("XsAaTp9dJ6vz33ngzUah");\n Dictionary<string, object> city = new Dictionary<string, object>\n {\n { "name", "Los Angeles" },\n { "state", "CA" },\n { "country", "USA" }\n };\n await docRef.SetAsync(city); // <- this throws an error for async problems.\n }\n\n }\n\nWhat I'm trying to do is save some variables to FireStore from Unity.\nShould be able to do handle everything else myself, just don't know the proper syntax to do so.\nIssues: Not knowing how to initialize a 'FirebaseFirestore db' to my database properly and having errors with async syntax and I'm not too familiar with C#.\nNote* I do know how to save information from Unity to Firebase's 'Realtime-Database' but all my other applications run off Firebase Firestore and I wish for all the applications to have an easy time communicating with each other." ]
[ "c#", "firebase", "unity3d", "google-cloud-firestore" ]
[ "removing a dynamic html in a if condition", "i have a problem in a dynamic html block that i use for showing an error in an if condition. \n\nin constructor:\n\nconstructor() {\n\nthis.body = $(\".contact-block-header\");\nthis.ErrorMasage = this.body.find(\".error-masage\");\nthis.events();\n}\n\n\nand here are the codes:\n\n if (addressData != '') {\n newContactObject = {\n 'value': {\n \"address\" : addressData,\n },\n 'type': 'address'\n };\n } else {\n this.ErrorMasage.fadeOut(1000);\n this.ErrorMasage.html('Please add a valid address..');\n this.ErrorMasage.fadeIn(1000);\n return 0;\n }\n\n\nin these codes i said if the address data is empty, an error appears. The problem is when in the first time, i leave address input empty, the error comes up, as i want, but when i add information in the address input and save it, the error box is still there, i could not find a way to remove it after adding data in the address input. \nI will be appreciated if anyone helps me on that." ]
[ "javascript", "html" ]
[ "How to programmatically take screenshot of an android application without notification and navigation bars", "I am using the below code for taking screenshot in my application.\n\nView rootView = findViewById(android.R.id.content).getRootView();\nrootView.setDrawingCacheEnabled(true);\nrootView.buildDrawingCache(true);\nBitmap bitmap = rootView.getDrawingCache();\n\n\nBut I am getting an image with two black portion in the top and bottom by the notification and navigation bars. I need to remove those black areas. I need not to replace those area with the notification and navigation bars. But i need the toolbar." ]
[ "android" ]
[ "How to fill a vector by a while loop", "I´m starting to learn R.\n\nI would be glad if someone could help me with filling myVec by a while loop.\n\nHere is my (wrong) code:\n\na <- 0\nb <- 10\nmyVec <- c(x)\nwhile(a < b) {\na <- a+1\nx <- a\nprint(a)\n}" ]
[ "r", "vector", "while-loop" ]
[ "trouble installing phpmyadmin in amazon linux AMI", "I am installing a LAMP enviornment using amazon docs\n\nI enabled epel after that when i try to install phpmyadmin using command\nsudo yum install -y phpMyAdmin. It installs something maybe phpmyadmin but in the end it shows some errors like this:\n\n--> Finished Dependency Resolution\nError: php70-common conflicts with php-common-5.3.29-1.8.amzn1.x86_64\nError: php56-common conflicts with php-common-5.3.29-1.8.amzn1.x86_64\nError: php56-process conflicts with php-process-5.3.29-1.8.amzn1.x86_64\nYou could try using --skip-broken to work around the problem\nYou could try running: rpm -Va --nofiles --nodigest\n\n\nAfter that when I run this command\n\nsudo sed -i -e 's/127.0.0.1/your_ip_address/g' /etc/httpd/conf.d/phpMyAdmin.conf\n\n\nit shows\n\nsed: can't read /etc/httpd/conf.d/phpmyadmin.conf: No such file or directory\n\n\nwhat is the solution?" ]
[ "linux", "amazon-web-services" ]
[ "Change Nextprops in componentWillReceiveProps", "I'm testing but all the time these tests fail and don't know how to do it correctly\n\nTest\n\nconst mockProps = {\n object: {\n objectId: '12',\n }\n}\ntest('should call reloadObjectDetails when objectId has changed', () => {\n mockProps.fetchObjectDetails.mockClear()\n const objectId = '123'\n instance.componentWillReceiveProps({ object: objectId })\n expect(mockProps.fetchObjectDetails).toHaveBeenCalledWith(objectId)\n })\n\n\nComponent\n\ncomponentWillReceiveProps (nextProps) {\n const { object: newObject } = nextProps\n const { object } = this.props\n if (object.objectId !== newObject.objectId) {\n this.reloadObjectDetails(newObject.objectId)\n}\nreloadObjectDetails (objectId) {\n const { fetchObjectDetails } = this.props\n if (objectId && objectId !== '-1') {\n fetchObjectDetails(objectId)\n }\n }\n\n\nThe question is how to put the new Object, nextProps in order to enter the if of componentWillReceiveProps" ]
[ "reactjs", "jestjs", "enzyme" ]
[ "How can I tell if I have Service Pack 1 for Visual Studio 2010 installed?", "How can I tell if a computer has Service Pack 1 for Visual Studio 2010 Ultimate?\n\nI assume it is by version number, but I don't know what version means what. (The version I am looking at is 10.0.30319.1 RTMRel.)" ]
[ "visual-studio", "visual-studio-2010" ]
[ "Losing type precision from module signature", "Let's say I had a simple module MyFoo that looks something like this\n\nmodule MyFoo = struct\n type t =\n | A of string\n | B of int\n\n let to_string thing =\n match thing with\n | A str -> str\n | B n -> string_of_int n\nend\n\n\nWith this definition, it works great and as expected — I can do something like \n\nlet _ = MyFoo.A \"\";;\n- : MyFoo.t = MyFoo.A \"\"\n\n\nwithout any problems.\n\nNow maybe I want to create a functor that consumes modules with this structure, so I define a module signature that describes generally what this looks like and call it BaseFoo\n\nmodule type BaseFoo = sig\n type t\n val to_string : t -> string\nend\n\n\nIf I redefine MyFoo the same way but giving it this signature like\n\nmodule MyFoo : BaseFoo = struct\n type t =\n | A of string\n | B of int\n\n let to_string thing =\n match thing with\n | A str -> str\n | B n -> string_of_int n\nend\n\n\nI lose the precision of its type t (is there a better way to describe what happens here?) — for example:\n\nlet _ = MyFoo.A \"\";;\nError: Unbound constructor MyFoo.A\n\n\nWhat exactly is going on here and why does it happen? Is there a canonical way for dealing with this kind of problem (besides just leaving off the signature)?\n\nI've tried manually including the signature and the specific type type definition too but get a different kind of error (this probably isn't the right approach).\n\nmodule MyFoo : sig\n include BaseFoo\n type t = | A of string | B of int\nend = struct\n type t =\n | A of string\n | B of int\n let to_string thing =\n match thing with\n | A str -> str\n | B n -> string_of_int n\nend\n\nlet _ = MyFoo.A \"test\";;\nError: Multiple definition of the type name t.\n Names must be unique in a given structure or signature." ]
[ "ocaml" ]
[ "Calculating Floating Point Powers (PHP/BCMath)", "I'm writing a wrapper for the bcmath extension, and bug #10116 regarding bcpow() is particularly annoying -- it casts the $right_operand ($exp) to an (native PHP, not arbitrary length) integer, so when you try to calculate the square root (or any other root higher than 1) of a number you always end up with 1 instead of the correct result.\n\nI started searching for algorithms that would allow me to calculate the nth root of a number and I found this answer which looks pretty solid, I actually expanded the formula using WolframAlpha and I was able to improve it's speed by about 5% while keeping the accuracy of the results.\n\nHere is a pure PHP implementation mimicking my BCMath implementation and its limitations:\n\nfunction _pow($n, $exp)\n{\n $result = pow($n, intval($exp)); // bcmath casts $exp to (int)\n\n if (fmod($exp, 1) > 0) // does $exp have a fracional part higher than 0?\n {\n $exp = 1 / fmod($exp, 1); // convert the modulo into a root (2.5 -> 1 / 0.5 = 2)\n\n $x = 1;\n $y = (($n * _pow($x, 1 - $exp)) / $exp) - ($x / $exp) + $x;\n\n do\n {\n $x = $y;\n $y = (($n * _pow($x, 1 - $exp)) / $exp) - ($x / $exp) + $x;\n } while ($x > $y);\n\n return $result * $x; // 4^2.5 = 4^2 * 4^0.5 = 16 * 2 = 32\n }\n\n return $result;\n}\n\n\nThe above seems to work great except when 1 / fmod($exp, 1) doesn't yield an integer. For example, if $exp is 0.123456, its inverse will be 8.10005 and the outcome of pow() and _pow() will be a bit different (demo):\n\n\npow(2, 0.123456) = 1.0893412745953\n_pow(2, 0.123456) = 1.0905077326653\n_pow(2, 1 / 8) = _pow(2, 0.125) = 1.0905077326653\n\n\nHow can I achieve the same level of accuracy using \"manual\" exponential calculations?" ]
[ "php", "algorithm", "math", "pow", "bcmath" ]
[ "Rake test suddenly stopped working", "I have been working with my rails application and since today I have not been able to run rake test:units\n\nI though maybe my Ruby installation is broken or something, so I tried creating a new application, created a new model quickly, wrote a couple of unit test and then ran them. Everything seems to be running fine with the new app.\n\nPlease check the error log generated here http://pastebin.com/jgNXpXE3" ]
[ "ruby-on-rails", "ruby", "unit-testing", "ruby-on-rails-3" ]
[ "GoJS undo a change of category property that is binding to the shape fill property", "I need to change the category value dinamically.\n\nThe code:\n\ndiagram.startTransaction('changing state: ' + node.data.text);\nmodel.setDataProperty(node.data, 'category', 'stateInitial'); \ndiagram.commitTransaction('changing state: ' + node.data.text);\n\n\nNode Template:\n\n$(go.Shape, 'RoundedRectangle',\n { stroke: null , strokeWidth: 0 },\n new go.Binding(\"fill\", \"category\", function(category){\n\n if( category == 'stateInitial'){\n return '#99AE3B';\n }\n else if(category == 'stateFinal'){\n return '#E53935';\n }\n return '#6699CC';\n })\n ), . . .\n\n\nThis works OK, the node change its colour dinamcally.\n\nBut, After doing this: \n\ndiagram.undoManager.undo(); \n\n\nThe node switch to previous category in the model (this is OK) but I don't see the change of colour back to the previous colour.\nOnly diagram.rebuildParts() method works, but I can't use it.\n\nAny idea?" ]
[ "bind", "categories", "fill", "undo", "gojs" ]
[ "How to embed an image to a cover image by selecting random pixels in cover image?", "def embedding(hideImagePath,coverImagePath):\n img1 = cv2.imread(coverImagePath, 0)\n img2 = cv2.imread(hideImagePath, 0)\n for i in range (img2.shape[0]):\n for j in range(img2.shape[1]):\n #convert pixel to binary \n pixels_cover = format(img1[i][j], '08b')\n pixels_hide = format(img2[i][j], '08b')\n #replace the last 2 LSB from cover image with 2 MSB from hide image\n stegoImage = pixels_cover[:6] + pixels_hide[:2]\n img1[i][j] = int(stegoImage, 2)\n cv2.imwrite('StegoImage.png', img1)\n\n\nAbove is the code that I done so far. It hide pixels in cover image sequentially but I need it to hide the image to the cover image by selecting random pixels from the cover image." ]
[ "python", "steganography" ]
[ "Python PIL: color index to RGB", "following this link i was able to load and read pixels from a .gif. That question specifically askes for a RGB value, but the accepted (and most voted answer) that I used as reference gets me to get an int as value. What is it? I guess some sort of index, but how to convert it to a proper rgb value? Thanks\n\n[..]\nimg = Image.open(GIF_FILENAME)\npix = img.load()\nfor i in range(5):\n print img.getpixel((i, 0))\n # this returns me like 78, 65.. how to get RGB?\n[..]" ]
[ "python", "image" ]
[ "Dial digits (1 or 2) when call active/answered from custom Default Dialer in Android programmatically?", "Im making a Default Dialer App in Android replacing built-in phone dialer. Everything is working fine, call is attending as well as rejecting.\nBut when the call attends: When suppose operator asks to press \"1\" for this and \"2\" for this. How can I send these (1 or 2) commands to operator programmatically without interrupting my custom calling screen and without going out of my custom call screen. Things I have tried for pressing button 3: Intent intent = Intent(Intent.ACTION_CALL, Uri.parse(\"tel://3\"))\nstartActivity(intent) But the above code prompt me a dialog \"Unable to make conference call.\"Thank you." ]
[ "android", "android-studio", "android-dialer" ]
[ "How to Add button or label to iwatch programatically", "I was tinkering with the WKInterface and Apple Watch apps and was just wondering how to add a subview like a UIButton or UILabel.\n\nIt seems that \n\nUIButton *whatever = [[UIButton alloc]init];\n[self.view addsubview:whatever];\n\n\ndoes not work for the iWatch extension. Mainly the [self.view addsubview: ] part doesnt seem to work.\n\nDoes anyone know how to add a view programatically for apple watch or do I have to use the interface builder and drag and drop these objects." ]
[ "ios", "uibutton", "apple-watch" ]
[ "Using enum item to call a method", "I have an enum with 30 items in it. Each item has a corresponding function with the same name. I would like to be able to call the function by referencing the enum at a certain position.\nSo if the value at enum[0] = Foo, I would like to be able to call Foo(string bar) by using something like enum(0)("foobar")\nIn the end the point is I am running each function as a task like so:\nenum Test { AA, BB, CC, DD ....}\ntasks[0] = Task.Run(() => { prices[0] = AA("a string"); });\ntasks[1] = Task.Run(() => { prices[1] = BB("a string"); });\ntasks[2] = Task.Run(() => { prices[2] = CC("a string"); });\n//for 30 tasks\n\nWhat I would like to do is something along the lines of:\nenum Test { AA, BB, CC, DD ....}\nfor (int i = 0; i < 30; i++)\n{\n tasks[i] = Task.Run(() => { prices[i] = (Test)i("a string"); });\n}\nTask.WaitAll(tasks.ToArray());\n\nIs this something that is even possible?\nEDIT:\nThe enum relates to controls on a form so i have an array of textboxs, label and a array of prices that is populated with the results of the functions:\nenum Dealers { Dealer1, Dealer2 ... Dealer29, Dealer30 };\n\nstatic int noOfDealers = Enum.GetNames(typeof(Dealers)).Length;\ndecimal[] prices = new decimal[noOfDealers];\nTextBox[] textBox = new TextBox[noOfDealers];\nLabel[] boxes = new Label[noOfDealers];\n\nfor (int i = 0; i < noOfDealers; i++)\n{\n textBox[i] = Controls.Find("txt" + (Dealers)i, true)[0] as TextBox;\n boxes[i] = Controls.Find("box" + (Dealers)i, true)[0] as Label;\n prices[i] = 0;\n}\n\n//RUN 30 TASKS TO POPULATE THE PRICES ARRAY\n\nfor (int i = 0; i < noOfDealers; i++)\n{\n textBox[i].Text = "£" + prices[i].ToString();\n}\n\n//LOOP THROUGH PRICES ARRAY AND FIND CHEAPEST PRICE, THEN COLOUR THE LABEL BACKGROUND GREEN FOR THE TEXT BOX WITH THE NAME AT ENUM VALUE WHATEVER I IS\n\nI guess i am just trying to make my code as concise as possible, there is the potential for the amount of tasks to double and didn't want to end up with 60 lines to populate the tasks array" ]
[ "c#", "enums" ]
[ "Thrown object cannot be caught in a multi-threaded solution", "I have a RAII class that solves a problem in an inner thread:\n\n#include <iostream>\n#include <thread>\nusing namespace std;\n\nstruct solution_using_thread {\n solution_using_thread()\n : alive_(true), thread_() {\n thread_ = thread([this]() {\n while(alive_);\n });\n }\n ~solution_using_thread() {\n alive_ = false;\n thread_.join();\n }\nprivate:\n bool alive_;\n thread thread_;\n};\n\nint main() {\n cout << 0 << endl;\n try {\n solution_using_thread solution;\n throw 1;\n } catch (int i ) {\n cout << i << endl;\n }\n cout << 2 << endl;\n}\n\n\nAfter creating an instance of it, the main happens to throw an exception. The problem is in some of the executions, the output is:\n\n0\n\n\nwhen it always should have been:\n\n0\n1\n2\n\n\nIn coliru, it is always only 0.\n\nWhat am I missing here?\n\nPS: Sorry, for the ambiguous title. Please do not hesitate to suggest a better one for this question." ]
[ "exception", "c++11", "constructor", "raii", "stdthread" ]
[ "I don't know why curs.execute not working", "i'm studying about mysql connection with python(pycharm)\ni have question about curs.execute()\nwhen it work and when it not work...\nin my code i write remarks about not working point\nimport pymysql\n\ntry:\n conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')\n conn.set_charset('utf8')\n\n curs = conn.cursor(pymysql.cursors.DictCursor) #Dictionary cursor 생성\n # curs = conn.cursor()\n print("Connected to MySQL")\n\n sql = "SELECT sno, midterm, final from db_score where midterm >= 20 and final >= 20 order by sno"\n # sql = "select* from db_score"\n curs.execute(sql)\n #this point not work :(\n\n\nexcept Exception as e:\n print(str(e))\n\nfinally:\n if conn:\n curs.close()\n conn.close()\n print("MySql connection is closed")\n\nand fetchall() didnt work :(\\\nimport pandas as pd\nimport pymysql\n\nxl_file = 'db_score.xlsx'\ndf = pd.read_excel(xl_file)\ntp = list(df.itertuples(index=False, name=None))\n\n# ('sno', 'attendance', 'homework', 'discussion', 'midterm', 'final', 'score', 'grade')\n\ntry:\n conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')\n conn.set_charset('utf8')\n #curs = conn.cursor(pymysql.cursors.DictCursor)\n curs = conn.cursor()\n print("Connected to MySQL")\n\n sql = "INSERT INTO db_score VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"\n\n for i in range(0, len(df.index)):\n # print('hi')\n curs.execute(sql, tp[i])\n #why work i dont know because other part is not working\n\n # sql2 = "SELECT* from db_score"\n # curs.execute(sql2)\n # try execute, but not work\n\n records = curs.fetchall()\n\n for row in records:\n print("why didn't work")\n print(row)\n #print not work :(\n\n conn.commit()\n\nexcept Exception as e:\n print(str(e))\n conn.rollback()\n\nfinally:\n if conn:\n curs.close()\n conn.close()\n print("MySql connection is closed")\n\nplease comment why work and why not work please...\nthanks for watching\ndb connection is so hard:(" ]
[ "python", "mysql" ]
[ "Converting a Frege List to a Java Array", "Suppose I have a small, somewhat redundant bridge function defined in Frege\n\nlistToArray :: (PrimitiveArrayElement α) => [α] -> JArray α\nlistToArray = arrayFromList\n\n\nand some Java code that passes an already obtained TList<Long> to it\n\nTList<Long> tl_results = ...\nLong[] results = FregeStuffies.listToArray(IPrimitiveArrayElement_Long.it, Thunk.lazy(results));\n\n\nEclipse complains that the arguments passed to FregeStuffies.listToArray are not applicable to what it is\n\nlistToArray(PreludeArrays.CPrimitiveArrayElement<α[],α>, Lazy<PreludeBase.TList<α>>)\n\n\nAm I passing in the wrong {context}/{instance of PrimitiveArrayElement}?" ]
[ "java", "arrays", "list", "interop", "frege" ]
[ "How to copy a HTML tag parameter value into another parameter of the same tag (for every tag in the source text)?", "I have got a huge HTML form where all the inputs have the name parameters set. I would like to also set id (to be equal to the name) for every input. Manual copying and pasting would be nasty as there are too many inputs actually. Of course I can write a program that would parse the tags and do just this but this looks a bit overkill too. Any suggestions?\n\nUPDATE: I mean doing it at the HTML source code level rather than in the run time.\n\nUPDATE2: The task actually means replacing every occurrence of the name=\"my-field\" pattern (where there can be anything reasonable in place of my-field (but will contain the minus usually, so supporting just letters is not enough)) with name=\"my-field\" id=\"my-field\". I believe this can be done with something like sed but to my shame I am hardly proficient in regular expressions." ]
[ "html", "xml", "regex", "refactoring", "editor" ]
[ "primefaces p:messages are not displayed", "I have a button in a form and I want an error message to be displayed when I click on this button. It is a step I want to complete before coding something similar. My code does not work because the error message is not displayed when I click on the button.\n\nMy form is:\n\n<h:form id=\"myForm\">\n <p:messages id=\"errorMessage\" for=\"myForm\" autoUpdate=\"true\" />\n <p:fieldset id=\"myFieldSet\"\n style=\"margin-left:auto ; margin-right:auto ; width:98% ; height:90px;\">\n <p:outputLabel for=\"numSi\"\n value=\"Value :\"\n style=\"margin-left:31px;margin-top:25px;\" />\n <p:inputText id=\"numSi\"\n value=\"#{suppSiBean.researchValue}\"\n maxlength=\"9\" required=\"true\">\n </p:inputText>\n <p:commandButton id=\"suppSignaButton\" type=\"submit\" ajax=\"true\"\n value=\"Launch\"\n style=\"text-align: center ; height:45px; width:150px ; margin-top:20px;\"\n action=\"#{suppSiBean.lancerRequete()}\" />\n </p:fieldset>\n</h:form>\n\n\nExcerpt of my bean :\n\npublic void lancerRequete() {}\n FacesContext context = FacesContext.getCurrentInstance();\n //I'm intentionally hide the values of the three following variables because it's confidential\n ResourceBundle bundle = ...\n String message = ...\n String messageFormat = ...\n FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageFormat.toString(), \"\");\n FacesContext.getCurrentInstance().addMessage(getClientId(\"myForm\"), facesMessage);\n}\n\npublic String getClientId(String id) {\n FacesContext context = FacesContext.getCurrentInstance();\n UIViewRoot root = context.getViewRoot();\n UIComponent c = findComponent(root, id);\n LOGGER.info(\"c.getClientId(context) vaut :\" + c.getClientId(context));\n return c.getClientId(context);\n}\n\nprivate UIComponent findComponent(UIComponent c, String id) {\n if (id.equals(c.getId())) {\n return c;\n }\n Iterator<UIComponent> kids = c.getFacetsAndChildren();\n while (kids.hasNext()) {\n UIComponent found = findComponent(kids.next(), id);\n if (found != null) {\n return found;\n }\n }\n return null;\n}" ]
[ "jsf", "primefaces" ]
[ "Vue-router page refresh or URL access", "I have a landing page with register/login from that redirects to main page with content. After successful login I redirect like this:\n\nthis.$router.push({ name: 'main' })\n\n\nAnd this works, but if I refresh the page or try to access it from url for example like http://testapp.test/main I get error: Page does not exists 404.\nCurrently I don’t have any protection against access to pages that are only for logged in users, I also added ‘*’ path in router for undefined routes and it also just throws 404 instead of loading home page. Here are my router settings:\n\nimport Vue from 'vue'\nimport VueRouter from 'vue-router'\nimport BootstrapVue from 'bootstrap-vue'\nimport {store} from './store/store'\n\nVue.use(BootstrapVue);\nVue.use(VueRouter);\n\nwindow.Vue = require('vue');\n\n\nimport Home from './components/LandingPage.vue'\nimport Main from './components/MainPage.vue'\nimport Logout from './components/Logout.vue'\n\nconst router = new VueRouter({\n mode: 'history',\n routes: [\n {\n path: '/',\n name: 'home',\n component: Home,\n },\n {\n path: '/main',\n name: 'main',\n component: Main,\n },\n {\n path: '/logout',\n name: 'logout',\n component: Logout,\n },\n {\n path :'*',\n name: 'home',\n component: Home,\n }\n ],\n});\n\n\nconst app = new Vue({\n el: '#app',\n components: { Home, Main, Logout },\n router,\n store,\n});\n\n\nI tried with https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations but I am not sure if I did it right. What I did is copied code for apache configuration and replaced existing code in .htaccess with it. But then even route from login stops working and if I access /main it gives me 404 error." ]
[ "vue.js", "vue-router" ]
[ "Improve two similar queries", "I have these queries :\n\ninitial_date = NewUser.joins(:interactions)\n .where('interactions.interaction_sub_type in (?)', types)\n .where('interactions.interaction_type in (?)', actions)\n .limit(1000).order('users.id asc').minimum(:updated_at)\n\nlast_date = NewUser.joins(:interactions)\n .where('interactions.interaction_sub_type in (?)', types)\n .where('interactions.interaction_type in (?)', actions)\n .limit(1000).order('users.id asc').maximum(:updated_at)\n\n\nThey are almost the same, except for the minimum and maximum.\nI'm trying to improve this code, but I have no idea on how to change this.\nI thought of something like \n\nbase = NewUser.joins(:interactions)\n .where('interactions.interaction_sub_type in (?)', types)\n .where('interactions.interaction_type in (?)', actions)\n .limit(1000).order('users.id asc')\ninitial_date = base.minimum(:updated_at)\n\n\nbut for some reason, this doesn't work. Seems like ActiveRecord execute the query for the base and then executes again on initial_date." ]
[ "ruby-on-rails", "ruby", "ruby-on-rails-4", "activerecord" ]
[ "Why response.write() is printing only the first row in node.js?", "I am new in node.js . I am facing a problem with a GET request . I am using 2 mysql query. First one is returning some ids , I am using those Ids in my 2nd query . \nIn the console all the rows are successfully printing but in the browser only the first row.\n\nMy Code structure is like :\n\nfunction userProjects(request, response) {\n\n connection.query(\"1st query\", function(err, first_output, fields) {\n response.writeHead(200, {\n \"Content-Type\": \"application/json\"\n });\n\n for (var i in first_output) {\n var obj = first_output[i];\n connection.query(\"select * from table where parent_id=\" + obj.id, function(err, apartmentRows, fields) {\n console.log(apartmentRows);\n response.write(\"apartments are : \" + JSON.stringify(apartmentRows));\n response.end();\n });\n }\n });\n}\n\n\nSo far I have understood by surfing various contents ,due to response.end() it is stopping to get remaining rows here . That's why all are not printing . But I failed to figure out the solution to solve it . \n\nThanks in advance." ]
[ "mysql", "node.js" ]
[ "Element not visible error, I tried all Xpath ,css selector, id, class and name also but nothing work. i tried previous solution but still not solve", "I tried all Xpath, css selector, id, class, and name also, but nothing works. I tried previous solution but it did not solve the problem:\n\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\n\npublic class Frontend {\n\n public static void main(String args[])\n {\n\n System.setProperty(\"webdriver.chrome.driver\", \"D:\\\\chromedriverlatest.exe\");\n WebDriver driver=new ChromeDriver();\n driver.get(\"https://genba.online\");\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.manage().window().maximize();\n driver.findElement(By.xpath(\"//*[@id='en-btn']\")).click();//translate to english language\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.findElement(By.xpath(\"/html/body/div/div[1]/div/div/div[1]/div[1]/div/div[2]/div/a[2]\")).click();//click on access button\n driver.findElement(By.xpath(\"//*[@id='email']\")).sendKeys(\"[email protected]\");\n driver.findElement(By.xpath(\"//*[@id='password']\")).sendKeys(\"123456\");\n driver.findElement(By.xpath(\"//*[@id='rememberme']\")).click();\n driver.findElement(By.xpath(\"//*[@id='user_detail']/div[2]/div[2]/button\")).click();\n\n }\n\n}" ]
[ "automated-tests" ]
[ "What am I doing wrong in localhost Facebook app development?", "App Domains: localhost\nWebsite with Facebook login: http://localhost/auth\n\n\nI go to http://localhost/auth/ and in my Chrome developer console I see the error: Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.\n\nI do a view-source to see the following:\n\n\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\n<title>Insert title here</title>\n</head>\n<body>\n<div id=\"fb-root\"></div>\n<script>\n // Additional JS functions here\n window.fbAsyncInit = function() {\n FB.init({\n appId : 'myappidremovedfromstackoverflowquestion', // App ID\n channelUrl : '//localhost/auth/channel.html', // Channel File\n status : true, // check login status\n cookie : true, // enable cookies to allow the server to access the session\n xfbml : true // parse XFBML\n });\n\n // Additional init code here\n\n };\n\n // Load the SDK Asynchronously\n (function(d){\n var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];\n if (d.getElementById(id)) {return;}\n js = d.createElement('script'); js.id = id; js.async = true;\n js.src = \"//connect.facebook.net/en_US/all.js\";\n ref.parentNode.insertBefore(js, ref);\n }(document));\n</script>\n<p>hello</p>\n</body>\n</html>\n\n\nI go to http://localhost/auth/channel.html and view source to see the single line:\n\n<script src=\"//connect.facebook.net/en_US/all.js\"></script>" ]
[ "facebook", "oauth-2.0", "facebook-javascript-sdk", "facebook-oauth" ]
[ "Openshift 3.11 How to setup permenant token for pulling from integrated docker registry", "I'm using openshift 3.11 and I have a very hard time figuring out how to setup permenant token for image pull and push.\nAfter I do docker login it is ok, but eventually that token expires.\nBy the documentation it seems that services account : default ,builder should have access.\n\nAs you can see each of them have some default dockercfg:\nLabels: \nAnnotations: \nImage pull secrets: default-dockercfg-ttjml\nMountable secrets: default-token-q4x4w\n default-dockercfg-ttjml\nTokens: default-token-729xq\n default-token-q4x4w\nEvents: \n\ndefault-dockercfg-ttjml, Which has really weird username and password. Read the documentation many times and still I can't understand how to setup a permanent token. Can someone explain me in a plain manner what is the procedure?" ]
[ "kubernetes", "openshift" ]
[ "mssql_fetch_object text character limit?", "I'm fetching some data from an MSSQL table using the mssql_fetch_object, but the text appears to cut off on the page.\n\nThe data is all there in the table, but it seems to cut off in the view page.\n\nHas anyone else encountered this problem and perhaps knows of a workaround? Here is my code;\n\n<?php include('includes/session.php');\n$query = \"SELECT content FROM pages WHERE id = '11'\";\n$result = mssql_query($query);\n$page = mssql_fetch_object($result);\n?>\n\n<div id=\"leftcol\">\n<?php echo stripslashes($page->content) ?>\n</div>" ]
[ "php", "sql", "fetch" ]
[ "@PathParam getting null value", "Thank you for your help even if you just read it.\n\nProblem: return value is null why?\nHave checked many forums and everything seems to be fine, but isn't.\n\npackage pack.bb;\n\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\n\n@Path(\"path\")\npublic class test {\n @GET\n @Path(\"{sorted}\")\n public String getsortedContactList(@PathParam(\"list\") String list) //throws SQLException\n {\n System.out.println(\"GET list: \" + list);\n return \"get \" + list;\n }\n}\n\n\nI am using this using localHost 8080 \n\n\"localHost:8080/testCap/api/path/aaaa\"\n\n\nThis is web.xml file. I think it is correct because I was using it in other projects\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\" id=\"WebApp_ID\" version=\"2.5\">\n <display-name>Factorial_RESTapp</display-name>\n <welcome-file-list>\n <welcome-file>index.html</welcome-file>\n <welcome-file>index.htm</welcome-file>\n <welcome-file>index.jsp</welcome-file>\n <welcome-file>default.html</welcome-file>\n <welcome-file>default.htm</welcome-file>\n <welcome-file>default.jsp</welcome-file>\n </welcome-file-list>\n\n <servlet>\n <servlet-name>Jersey REST Service</servlet-name>\n <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>\n <init-param>\n <param-name>com.sun.jersey.config.property.packages</param-name>\n <param-value>pack.bb</param-value>\n </init-param>\n <load-on-startup>1</load-on-startup>\n </servlet>\n <servlet-mapping>\n <servlet-name>Jersey REST Service</servlet-name>\n <url-pattern>/api/*</url-pattern>\n </servlet-mapping>\n</web-app>\n\n\nAfter running I get this result in console:\n\nGET list: null" ]
[ "java", "web-services", "rest" ]
[ "Load data infile with blob field", "Given I have to dump a lot amount of inserts in a short period managed to dump all records to a file and then loading them by the load data infile sentence of mysql. This was working fine but now I compress a little more the values into a blob field to make less inserts. The problem is that I cant find a way to dump the blob field into the file so when loading data inserts the correct values. I've tried different ways but no happy ending and want to avoid inserting one by one.\n\nHas anyone knows how to do this properly?" ]
[ "mysql", "load-data-infile" ]
[ "iexplore.exe.config is ignored", "I need to override some settings for .NET components hosted inside Internet Explorer. I've created an iexplore.exe.config file and placed it in c:\\program files\\internet explorer.\n\nBelow is the config file:\n\n<configuration>\n <system.net>\n <webRequestModules>\n <remove prefix=\"http:\"/>\n <remove prefix=\"https:\"/>\n <add prefix=\"http:\" type=\"MyHttpRequestCreator, MyRequestModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bee8bd1bab54ad99\" />\n <add prefix=\"https:\" type=\"MyHttpRequestCreator, MyRequestModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bee8bd1bab54ad99\" />\n </webRequestModules>\n </system.net> \n</configuration> \n\n\nUnfortunately, this seems to be completely ignored by IE. Even if I put invalid text in the file, no errors are logged.\n\nThis same configuration works perfectly if I added it to the machine.config, but I wanted to limit my overrides to IE if possible.\n\nI tried enabling the IEHostLogFile (see: http://support.microsoft.com/kb/313892), and this gave me some interesting entries. It suggests that a remote configuration file is being loaded:\n\nMicrosoft.IE.SecureFactory: Added configuration file: DotNetConfig.xml\nMicrosoft.IE.SecureFactory: Application base: http://someserver/dotnet/\nMicrosoft.IE.SecureFactory: Private Bin Path: bin\nMicrosoft.IE.IDKey: Created key\nMicrosoft.IE.SecureFactory: Trying to create instance of type http://someserver/dotnet/\nSomeApp.DLL#SomeApp.SomeClass\n...\n\n\nI examined that config file, and it doesn't override the system.net section, so I should still be able to provide my overrides. I could try modifying that file, but this solution wouldn't work for me as I don't want everybody who uses this application to be affected, just specific machines.\n\nIdeas?" ]
[ ".net", "internet-explorer", "app-config" ]
[ "Multithreading with a global variable: if only one thread is changing the variable, is it necessary to lock it?", "As titled, several thread accessing one variable, and only one thread will change the variable, and all the others will just read its value. Like this:\n\nThread 1:\n\nwhile True:\n a += 1\n\n\nThread 2, 3, 4,...:\n\nprint a\n\n\nIn this case, only Thread 1 is changing variable a. Will any serious problems happen?\n\nI found a similar C/C++ tagged question titled \"in which cases do I need to lock a variable from simultaneous access?\", and it seems from the answer, that the only thing I need to worry about is that the a acquired from the other thread might not be as updated.\n\nI'm asking, other than that I might not get the newest a value, is it possible something more serious will happen and crush the code if I don't lock the variable while accessing it?\n\nI don't think this is language related, but if it matters, I'm specifically interested in the case for Python." ]
[ "python", "multithreading", "thread-safety" ]
[ "Scala: self-type does not conform to parent selftype with Int", "I was referring to the generic numeric programming post here. However I am getting compilation error with this code:\n\nobject V1 {\n trait Addable[A] {\n self: A =>\n def +(that: A): A\n }\n\n def add[A <: Addable[A]](x: A, y: A): A = x + y\n\n implicit class MyInt(x: Int) extends Addable[Int] {\n y: Int =>\n override def +(y: Int): Int = x + y\n }\n\n def main(args: Array[String]) = {\n add(1, 2)\n }\n}\n\n\nErrors are as shown below:\n\nV1.scala:9: error: `implicit' modifier can be used only for values, variables and methods\n implicit class MyInt(x: Int) extends Addable[Int] {\n ^\nV1.scala:15: error: inferred type arguments [Int] do not conform to method add's type parameter bounds [A <: V1.Addable[A]]\n add(1, 2)\n ^\ntwo errors found\n\n\nHow can I fix the self type?\n\nEDIT: Updated the code and errors.\n\nEssentially, I want to create a generic method that can add two numbers ( Int, Double etc, )." ]
[ "scala", "generics", "self-type" ]
[ "Python module for storing and querying geographical coordinates", "Is there a Python module where I can create objects with a geographical location coordinate (latitude and longitude), and query all the objects for ones which are within a 5km distance (i.e. radius) of a given coordinate?\n\nI've been trying to store the latitude and longitude as keys in dictionaries (as they're indexed by key) and use some distance finding algorithms to query them. But this feels like a horrible hack.\n\nEssentially something like PostGIS for PostgreSQL, but all within my Python app's memory." ]
[ "python", "geolocation", "coordinates", "geospatial", "geographic-distance" ]
[ "Will async recursive function without parameters leak memory or get stack overflow?", "I have a asynchronous task that takes a lot of time and it needs to be executed repeatedly.\n\nThe easy solution is:\n\nconst timeoutPromise = delay => new Promise(resolve => setTimeout(resolve, delay));\n\nasync function infiniteRecursiveLoop() {\n await longLastingWork();\n await timeoutPromise(10000); // each time work is done, wait 10s and then run it again\n infiniteRecursiveLoop();\n}\n\n\nSince I don't use any parameters and I don't await the result of the recursive call, this should not leak any memory nor get stack overflow, right? Because I'm not sure at all.\n\nI need this for recent Firefox and Chrome.\n\nEDIT:\nActually I can just use while(true) {...}, there is no need for recursion :). But still I would like to know.\n\nEDIT 2:\nAfter testing more intensive version:\n\n(async function infiniteRecursiveLoop() {\n await Promise.resolve();\n infiniteRecursiveLoop();\n})();\n\n\nIt seems that this is specific to environment: \n\n\nNodeJS 12 - ok \nChrome 77 - ok \nFirefox 70 - memory leak, no stack overflow\n\n\nBut why...?" ]
[ "javascript" ]
[ "Entity framework, DataGridView: InvalidOperationException when adding an item", "I can't get rid of an exception that I'm getting when adding an item to a DataGridView with the AllowUserToAddRows set to true. I already figured out this all is happening because there's a row focused and ready to be filled in (so setting the property to false or disabling the grid fixes the problem), but I'm still wondering: Is it a bug or an expected behavior and I'm doing it wrong?\n\nExample code (a Button and a DataGridView on a Form):\n\nnamespace test\n{\n public partial class MainForm : Form\n {\n public class Entity\n {\n public string Text { get; set; }\n }\n\n BindingList<Entity> list = new ObservableCollection<Entity>().ToBindingList();\n\n public MainForm()\n {\n InitializeComponent();\n dataView.DataSource = list;\n }\n\n private void clickMeButton_Click(object sender, EventArgs e)\n {\n list.Add(new Entity\n {\n Text = \"Hello\"\n });\n }\n }\n}\n\n\nClicking the button causes the InvalidOperationException to be thrown." ]
[ "c#", "winforms", "entity-framework", "datagridview", "entity-framework-6" ]
[ "Basic search function with Strapi & Mongodb Atlas (NEXT JS)", "Would someone please help to give an example of building a search function with Strapi CMS (Mongodb Atlas database)?\nI am using Next js.\nI don't get the query idea: https://strapi.io/documentation/developer-docs/latest/concepts/queries.html\nThank you!!" ]
[ "search", "next.js", "strapi" ]
[ "Azure DevOps multi-stage pipeline, trigger specific stage by specific artifact change", "The multi stage pipeline looks like this.\nA->B->C\nStage A consume artifact a\nStage B consume artifact b\nStage C consume artifact c\nArtifact can be repository/pipeline...\nHow to trigger only Stage B when b artifact change ?" ]
[ "azure-devops", "yaml" ]
[ "Space between custom taxonomy terms in wordpress", "I am using the following to list the terms within my custom taxonomy\n\n<?php $application_terms = wp_get_object_terms($post->ID, 'application');\n if(!empty($application_terms)){\n if(!is_wp_error( $application_terms )){\n\n foreach($application_terms as $application){\n echo $application->slug; \n }\n }\n } \n?>\n\n\nThe code works fine and it displays the terms however, if a post type has two \"application\" terms assigned to it, the two terms appear without space in betweeen them e.g ig apple and banana it appears applebanana. How do you change the code so that there is space in between the terms?\n\nThanks" ]
[ "php", "wordpress" ]
[ "Cut files to clipboard in C#", "I'm looking for a way to programmatically cut a file to the clipboard, for example, some call to a function in C# that does the same as selecting a file in the Windows Explorer and pressing Ctrl + X.\n\nAfter running the program and pressing Ctrl + V in some other folder on the hard drive, the original file would be moved to the new folder. By looking at Stack Overflow question Copy files to clipboard in C#, I know that it's easy to do the copy job, but cutting seems to work different. How can I do this?" ]
[ "c#", ".net", "file", "clipboard" ]
[ "Dynamic title and sliders using manipulate package in Rstudio", "Using the package manipulate in Rstudio, I'm trying to create a scatterplot in which I can select among several data frames using a picker and then using sliders I control the columns I'd like to plot for each axis. For example, using these two datasets: mtcars and iris.\n\nlibrary(manipulate) \nmanipulate( \n plot(dataset[, xaxis] ~ dataset[, yaxis], \n dataset, \n xlab = colnames(dataset)[xaxis],\n ylab = colnames(dataset)[yaxis], \n main = title),\n xaxis = slider(1, 10), \n yaxis = slider(1, 10), \n dataset = picker(\"mtcars\" = mtcars, \"iris\" = iris),\n title = picker(\"mtcars\", \"iris\")\n ) \n\n\nIt works ok, however, I'm struggling with two questions:\n\n\nHow to change dynamically the title of the plot based on the selected dataset (mtcars or iris) instead of manually using another picker as I do in the example above. I'm unable to get the name of the selected data frame and pass it as a character title.\nHow can I determine dynamically the max argument of the sliders, instead of hardcoding in the sliders from 1 to 10. For example mtcars has 11 columns and iris 5. Or better still, select the columns for each axis by name. I've tried many different ways but I think the problem is that I can't pass variables used in a control (dataset) to others (sliders). For example, this generates an error:\n\nxaxis = slider(1,as.numeric(dim(dataset)[2]))" ]
[ "r", "rstudio" ]
[ "How to change ACE TypeGuessRows Registry Value for Access 2007 to Determine Field Data Type Properly When Importing From Excel File Using VBA", "I have an Access database that imports data from an external Excel spreadsheet that contains a column of data called Date Delivered. While most data in this column is actually a date type, sometimes entries like 4/5/15,5/1/15 will be made to indicate two delivery dates. \n\nThis trips up Access when importing the data using: \n\nDoCmd.TransferSpreadsheet acImport, 5, \"Delivery Data\", \"\\\\File\\Path.xlsx\", True \n\n\nThis causes it to make the column the date type rather than a string which drops any value from those fields which is problematic. I found what appeared to be a helpful solution here that suggested changing the TypeGuessRows registry value to 0 to make Jet look at all rows when determining the field data type. \n\nI created and changed the registry value using the following code:\n\nDim RegLoc As String\nDim myWS As Object\n\n'Writes registry value to make Jet check all rows (0) not just first 25 (Default value = 8) to determine type\nRegLoc = \"HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Jet\\4.0\\Engines\\Excel\\TypeGuessRows\"\nSet myWS = CreateObject(\"WScript.Shell\")\nmyWS.RegWrite RegLoc, 0, \"REG_DWORD\"\n\n\nUnfortunately this did not seem to work as the problem persisted after changing the value and restarting Access and Excel. \n\nIs there a separate registry value for Access vs Excel Jet engine or does this simply not do what I think it should?\n\nEdit:\n\nLooks like for Excel 2007 and newer (I am using 2007), the registry value should be: \n\nHKEY_CURRENT_USER\\Software\\Microsoft\\Office\\12.0\\Access Connectivity Engine\\Engines\\Excel\\TypeGuessRows\n\n\nHowever it still isn't working.\n\nEdit 2:\n\nHere is the code to do what @PractLogical suggested:\n\nSQL = \"CREATE TABLE [Delivery Data Import] ([F1] TEXT, [F2] TEXT,[F3] TEXT, ...)\"\nCurrentDb.Execute SQL\n\nDoCmd.TransferSpreadsheet acImport, 5, \"Delivery Data Import\", \"\\\\File\\Path.xlsx\", False\n\nSQL = \"INSERT INTO [Delivery Data] ( Buyer, [PO #], [Receipt Status],...) SELECT [Delivery Data Import].F1, [Delivery Data Import].F2, [Delivery Data Import].F3,...] WHERE (Get rid of headers);\"\nCurrentDb.Execute SQL\n\n\nI am still looking for a one and done solution for all imports via registry key if it exists (knowing it doesn't exist would also be useful)." ]
[ "excel", "vba", "ms-access", "registry", "ms-access-2007" ]
[ "Mocking constructors using node and chai/sinon", "I have a function like this\n\nfunction buildToSend(repo) {\n const {\n name, ...data\n } = repo;\n return {\n msg: {\n application: data.name,\n date: new Date(),\n },\n };\n}\n\n\nAnd I need to test it but i really can't find out how to mock/stub the new Date()\n constructor.\n\nAny ideas?\n\nI already tried somethings like this but it didn't work.\n\n const date = new Date();\n const myStub = sinon.stub(Date.prototype, 'constructor').returns(date);\n const input = {\n name: 'name',\n };\n expect(utils.buildToSend(input)).to.deep.equal({msg: {name: 'name', date: 'THE DATE'}});\n\n\nI'm missing something but i really don't know what. (of course, date is not getting called that way)" ]
[ "node.js", "unit-testing", "testing", "chai", "sinon" ]
[ "IMEI REQUEST in J2ME", "How can I programmatically display the IMEI number of J2ME? I used System.getProperty(\"com.nokia.mid.imei\"), and it shows it's running but displays nothing. My device is a Nokia 210 model. Is there any code for this model phone?" ]
[ "java-me" ]
[ "Use switch with type Class in generic method", "Is it possible to use the switch when comparing Classes in a generic method?\nExample:\n\nswitch (typeof(T))\n{\n case typeof(Class1):\n // ...\n break;\n\n case typeof(Class2):\n // ...\n break;\n\n default:\n break;\n}\n\n\nThe idea is not to use the name but the Class object.\nAt moment I'm using:\n\nif (typeof(T) == typeof(Class1))\n{\n // ...\n}\nelse if (typeof(T) == typeof(Class2))\n{\n // ...\n}\n\n\nFor simplicity, it would be good to use the switch." ]
[ "c#", ".net-4.5", "c#-5.0" ]
[ "Current time in IO monad", "If I have the following, for example:\n\nimport Data.Time.Clock.POSIX\n\nt = getPOSIXTIME\n\n\nThen t :: IO POSIXTime. That means it is in the IO monad, this much I understand. Is there any way to get the value out of the monad to use in other functions in the program? I don't want to output the value to the terminal.\n\nI apologise for such a newbie question, but the more monad tutorials I read the less I understand any of it. This is essentially more a question about monads than specifically about time." ]
[ "haskell" ]
[ "Why Pylint is too slow while pep8 just takes a second to check the same code?", "I do not understand why pylint takes about 5 minutes to check my code, where pep8 takes only 1 sec. \n\nI use Mac and I have pylint 1.8.4 installed through conda install -c conda-forge pylint. Pylint is very slow either I use Terminal or the Spyder editor. I tried creating a config file .pylintrc but it didn't make a difference to the speed. \n\nHow can I accelerate the Pylint speed? Thank you." ]
[ "performance", "pylint" ]
[ "Currency amount must be non-negative number, may optionally contain exactly 2 decimal places separated by '.'", "When I use the vue-paypal-check:\n\n <PayPal amount=\"amount\"\n currency=\"USD\"\n :client=\"credentials\"\n env=\"sandbox\"\n >\n </Paypal> \n...\ncomputed: {\n amount() {\n\n var total_price = Number(this.product_physical_session_storage_from_before.total_price_local)\n\n var abs_total_price = Math.abs(total_price.toFixed(2))\n\n return abs_total_price // there is Number `120.00`\n }\n},\n\n\nI get bellow error:\n\n\n {\"name\":\"VALIDATION_ERROR\",\"details\":[{\"field\":\"transactions[0].amount.total\",\"issue\":\"Currency amount must be non-negative number, may optionally contain exactly 2 decimal places separated by '.', optional thousands separator ',', limited to 7 digits before the decimal point\"}],\"message\":\"Invalid request - see details\",\"information_link\":\"https://developer.paypal.com/webapps/developer/docs/api/#VALIDATION_ERROR\",\"debug_id\":\"efa7b058ad30e\"}" ]
[ "paypal", "vue.js", "vue-paypal-check" ]
[ "Publish a script online", "I have a Python script written up and the output of this script is a list. \n\nRight now I need to get it online and make it accessible to others. I looked at Django , but then I realized that it may be kind of hard to create the UI. Is there any simple way to create a UI in Django and map it to an existing Python script.\n\nRight now I using nltk, numpy, sqlite3 and things like that. Or is there a simpler way by which I can proceed?" ]
[ "python" ]
[ "Execute handlers when DOM ready as the inserted order", "I want to to execute the handlers I pass to the "ready" function in the order there were inserted.\nI saw with a jsFiddle that the order is opposite- LIFO - like a stack.\nIs there a way to execute in order of FIFO like a queue?\n(obviously I can't just insert the handlers in opposite order...)" ]
[ "javascript", "jquery", "domready" ]
[ "Playing MIDI in Java Applet pauses the Applet", "I´m writing a Java Applet containing an animation which triggers a MIDI-sound to be played. The sound is played by the following class - which starts its own Thread - anyway the animation in the Applet is paused while the sound plays. I don´t see what i did wrong here, I would expect the animation not to pause due to the newly assigned Thread...\n\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.sound.midi.MidiChannel;\nimport javax.sound.midi.MidiSystem;\nimport javax.sound.midi.MidiUnavailableException;\nimport javax.sound.midi.Synthesizer;\n\npublic class ChromaticSynth implements Runnable{\n //vars\n private Synthesizer synth;\n private MidiChannel mchannel;\n private int playNote;\n private Thread myThread;\n\n //constructor\n public ChromaticSynth(int playNote){\n try {\n synth=MidiSystem.getSynthesizer();\n synth.open();\n mchannel=synth.getChannels()[0];\n this.playNote=playNote;\n\n myThread=new Thread(this);\n myThread.start();\n } catch (MidiUnavailableException ex) {\n Logger.getLogger(ChromaticSynth.class.getName()).log(Level.SEVERE, null, ex);\n }\n\n\n }\n\n //play sound\n public void run(){\n mchannel.noteOn(playNote,50);\n }\n}\n\n\nThe ChromaticSynth class is used in the following way (in reduced the code to the relevant part):\n\nimport chromatic.ChromaticSynth;\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport javax.swing.JPanel;\n\npublic class ChromaticPanel extends JPanel{\n //vars\n ...\n\n //constructor\n public ChromaticPanel(){\n super();\n ...\n }\n\n //paint\n protected void paintComponent(Graphics g){\n\n super.paintComponent(g);\n\n //draw something\n g.setColor(Color.white);\n g.draw(...);\n\n if(noteshouldbeplayed)\n ChromaticSynth cs=new ChromaticSynth(playNote); \n\n }\n\n\n}\n\n\nThe Panel's repaint()-Method is called repeatedly by a javax.swing.Timer in the JFrame containing the ChromaticPanel to paint the animation.\n\nthx for your help!" ]
[ "java", "multithreading", "midi" ]
[ "non-jar SVN dependency management", "Hypothetically there were two software companies, A & B. Both companies have about a couple of hundred Eclipse projects. Both have a few application end-products. Each end-product project has a dependency different from the others.\n\nA relies on maven for dependency management. It practices code freezing and therefore decouples projects from each other and hence is able to mavenize dependencies.\n\nB relies on Eclipse Subversive plugin. For any particular end-product project, all projects it depends on will be checked out of SVN and included in the Eclipse project build path. If a project has dependencies on 50 projects, all 50 projects will be subject to source code modification and that is why they do not use Maven.\n\nThe two companies merged into AB. The desire is to have a maven like dependency management that would also work on SVN repositories. That is, the hypothetical POM should be able to specify either jar dependency (company A style) or SVN source-code dependency (company B style). If the dependency is a jar, it should pull the dependency from the repository into the developer's workstation's maven cache. If the dependency is source code in SVN, it should check it out into the SVN working directory.\n\nHow should company AB proceed with their vision unifying the two build attitudes, technologically? I specify \"technologically\" to avert answers that would deal with micromanaging or modifying the philosophical attitudes of developers of the merged company.\n\nWould Gradle be of any help? If so, how and why? What other alternatives?" ]
[ "eclipse", "svn", "maven-2", "gradle" ]
[ "How to test soft deletion event listner without setting up NHibernate Sessions", "I have overridden the default NHibernate DefaultDeleteEventListener according to this source: http://nhibernate.info/blog/2008/09/06/soft-deletes.html\n\nso I have \n\n protected override void DeleteEntity(\n IEventSource session,\n object entity,\n EntityEntry entityEntry,\n bool isCascadeDeleteEnabled,\n IEntityPersister persister,\n ISet transientEntities)\n {\n if (entity is ISoftDeletable)\n {\n var e = (ISoftDeletable)entity;\n e.DateDeleted = DateTime.Now;\n CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities);\n CascadeAfterDelete(session, persister, entity, transientEntities);\n }\n else\n {\n base.DeleteEntity(session, entity, entityEntry, isCascadeDeleteEnabled, persister, transientEntities);\n }\n }\n\n\nHow can I test only this piece of code, without configuring an NHIbernate Session?" ]
[ "unit-testing", "nhibernate", "moq", "soft-delete" ]
[ "How to replace strings in a list by numbers based on their endings?", "Assume I have a list like this \n\nmyList = ['A_x1', 'B_x2', 'C_x1', 'D_x3', 'E_x1']\n\n\nand a dictionary like this\n\nmyDict = {'_x1': 0.1, '_x2': 0.5, '_x3': 0.7}\n\n\nNow I would like to replace all strings in myList by the value stored in myDict associated to the ending of this string. I can of course achieve that by using the following:\n\nfor ind, l in enumerate(myList):\n for k in myDict.iterkeys():\n if l.endswith(k):\n myList[ind] = myDict[k]\n\n\nwhich gives me the desired output:\n\n[0.1, 0.5, 0.1, 0.7, 0.1].\n\n\nBut how could this be done using e.g. map or anything else more efficient?" ]
[ "python", "regex", "dictionary", "replace" ]