texts
list | tags
list |
---|---|
[
"Add condition in xml tag for xDocument in vb.net",
"I wanted to add condition to get to my xml tag and do something within the tag.\n\nThese are the sample of my xml file\n\n<ROOT>\n <FILE1>\n <ENGLISH_LANGUAGE>\n <ANOTHER_TAG></ANOTHER_TAG>\n </ENGLISH_LANGUAGE>\n <MANDARIN_LANGUAGE>\n <ANOTHER_TAG></ANOTHER_TAG>\n </MANDARIN_LANGUAGE>\n </FILE1>\n</ROOT>\n\n\nUsing the sample of xml tags as given above, I would like to add some if else condition for tag.. \n\nI'm reading the file in xDocument..\nbelow are the sample of codes I've written.\n\n Dim xmlFile As String = \"XmlFile.xml\"\n Dim xdoc As XDocument = xDocument.Load(xmlFile)\n Dim root As String = xdoc.Root.Name.ToString\n\n Dim strAll As String\n strAll = File.ReadAllText(xmlFile)\n\n\n\nHow can I add the if else condition to get tag? and do something within the tag.. Thanks in advance.."
]
| [
"xml",
"vb.net"
]
|
[
"Can't add a second tab bar to tab bar controller view",
"I am trying to add a second tab bar at the top of the first view of a tab bar controller but for some reason it is taking control of the tab bar at the bottom and adding everything to the first tab button. I can't see what I am doing wrong, any help would be appreciated.\n\nMainViewController *controller = self.storyboard.instantiateInitialViewController;\n\n//************ Add Tab Bar ***********************************\nself.tabsController = [[SGTabsViewController alloc] init];\nself.tabsController.delegate = self;\nself.window.rootViewController = self.tabsController;\n\n[self.tabsController setToolbarHidden:NO animated:NO];\n\n[self.tabsController addViewController:controller];\n\ndouble delayInSeconds = 3.;\ndispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));\ndispatch_after(popTime, dispatch_get_main_queue(), ^(void){\n [self.tabsController setToolbarHidden:NO animated:YES];\n});\n\nself.textTabField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 240.0, 30.0)];\nself.textTabField.autoresizingMask = UIViewAutoresizingFlexibleWidth;\nself.textTabField.backgroundColor = [UIColor whiteColor];\nself.textTabField.borderStyle = UITextBorderStyleRoundedRect;\nself.textTabField.text = @\"http://www.google.com\";\nself.textTabField.clearButtonMode = UITextFieldViewModeAlways;\nself.textTabField.keyboardType = UIKeyboardTypeURL;\nself.textTabField.autocorrectionType = UITextAutocorrectionTypeNo;\nself.textTabField.delegate = self;\n\n\nUIBarButtonItem *urlBar = [[UIBarButtonItem alloc] initWithCustomView:self.textTabField];\n\nUIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace\n target:nil action:nil];\nUIBarButtonItem *reload = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh\n target:self action:@selector(reload:)];\nUIBarButtonItem *add = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd\n target:self\n action:@selector(add:)];\n\n\nself.tabsController.toolbarItems = [NSArray arrayWithObjects:space,urlBar,space,reload,add,nil];\nself.tabsController.title = @\"Loading...\";"
]
| [
"ios",
"iphone",
"tabs",
"uitabbarcontroller"
]
|
[
"C# dllimport'ing complex datatypes across platforms?",
"So I'm writing a wrapper in C# for a C dll. The problem is several of the functions use complex datatypes e.g.:\n\nComplexType* CreateComplexType(int a, int b);\n\n\nIs there a way I can declare a valid C# type such that I can use dllimport?\nIf I were doing a Windows-only solution I'd probably use C++/CLI as a go-between the native complex type and a managed complex type.\n\nI do have access to the source code of the C dll, so would it be possible to instead use an opaque type (e.g. handles)?"
]
| [
"c#",
".net",
"c++-cli",
"native",
"dllimport"
]
|
[
"xamarin android player resolution",
"I have some problem with XAP resolution: as you can see in the attached image the resolution is so poor that is not possible to read the text.\nI triyed to put the maximun scale (Player -> Scale -> 100%) but it haven't solved the problem.\nCould you help me?\nThank you.\n\nXamarin Android Player 0.6.5 (1)\nOSX El Capitan vers. 10.11.6\nCompare the resolution in Xamarin Android Player"
]
| [
"xamarin",
"xamarin-android-player"
]
|
[
"need query syntax to fetch latest by PKID after joining multiple tables",
"I have 3 tables:\n\nselect * from company\nselect * from emp_profile\nselect * from emp_salary_upgrade_tracker\n\n\ntable 1, company_pkid, company_code, company_name\n\ntable 2, emp_profile_pkid,company_fk_id, emp_number, emp_name, salary\n\ntable 3, salary_pk_id,emp_profile_fk_id,emp_number, old_salary, current salary\n\n\nwhenever an employee's salary is changed, its tracked in emp_salary_upgrade_tracker.\n\nI need to write a query to fetch \ncompany_code, emp_number, emp_name, old_salary, current salary\n\nHere the result should have the latest entry ,ie latest salary change from emp_salary_upgrade_tracker.\n\nAfter joining the tables, i need to fetch the latest from emp_salary_upgrade_tracker(order by pkid may be).\n\nBut am clueless of the query syntax. Please help"
]
| [
"sql",
"oracle"
]
|
[
"Create an arraylist in mule and iterate over it",
"I want to create an arrayList and iterate over its entries to check if my message has the set properties\n\n <set-variable variableName=\"ex\" value=\"#[{'A', 'User-Agent', 'Application-ID', 'API-Key', 'P', 'Organization-ID'}]\" doc:name=\"Set Variable\" />\n <for-each collection=\"#[ex]\" doc:name=\"Foreach\">\n <choice doc:name=\"Choice\">\n <when expression=\"#[message.inboundProperties.contains([payload]) == false]\">\n <set-variable variableName=\"isRequestValid\" value=\"false\" doc:name=\"Variable\"/>\n </when>\n </choice>\n </for-each>\n\n\nI am getting an error at the for-each expression (Invalid content was found starting with element 'for-each'). Further can we use choice block without otherwise option?"
]
| [
"list",
"mule",
"mule-studio",
"mule-component"
]
|
[
"Plot multiple graphs using pyplot in python",
"I want to plot the scatter plot between all the combinations of the features in the data. For this I am using the following code, but I am getting overlapping graphs.\n\n#importing the important libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn import metrics\nfrom sklearn import datasets\n\nwine_data = datasets.load_wine()\n\n#exploring the ralationship between the data by visualizing it.\ni = 1\nplt.figure(figsize=(15,15))\nfor feature_x_pos,feature_x in enumerate(wine_data.feature_names):\n for feature_y_pos,feature_y in enumerate(wine_data.feature_names):\n if feature_x_pos != feature_y_pos:\n plt.subplot(60,3,i)\n plt.scatter(wine_data.data[:,feature_x_pos],wine_data.data[:,feature_y_pos],c = wine_data.target, cmap = 'jet')\n plt.xlabel(feature_x)\n plt.ylabel(feature_y)\n i=i+1\n\n\nThe wine data contains 13 features. I want to plot the scatter plot between all the pairs of feature.\nThe output of the above code looks like below:\n\n\n\nI am doing code on google colab.\n\nPlease help in avoiding the overlapping of the graphs."
]
| [
"python",
"matplotlib",
"scikit-learn"
]
|
[
"MongoDB Upsert not working in PHP",
"I am trying to run an update on my documents, I'm using upsert true but its still overwriting?\n\n$col = \"A\" . $user->agencyID;\n$db = $m->rules;\n$collection = $db->$col;\n\n$validValue = $_POST['validValue'];\n$id = $_POST['ruleID'];\n\n$document = array(\n 'tags' => array(\n $validValue\n )\n );\n\n\n$collection->update(\n array(\n '_id' => new MongoId($id)\n ),\n array('$set' => $document),\n array('upsert'=>true)\n);\n\n\n$validValue is like - Foo Bar\n\nThe first value goes in fine but when I try adding a different value it overwrites the first one?"
]
| [
"php",
"mongodb"
]
|
[
"How to force display of that banner message in Julia's REPL?",
"Just out of sheer curiosity, is there a way to intentionally display that banner message that one sees at startup of the Julia REPL?\n\nWhen querying help? I got this:\n\nhelp?> banner\nsearch: AbstractChannel\n\nCouldn't find banner\nPerhaps you meant base, Channel, Range, range or Base\nERROR: \"banner\" is not defined in module Main\n in error at error.jl:21"
]
| [
"julia",
"read-eval-print-loop"
]
|
[
"how to use multilanguage in yii2?",
"How to create multilanguage app in yii2?\nIs there any preinstall message in yii2?\n\nconfig: \n\n'language' => 'es',\n'components' => [\n 'i18n' => [\n 'translations' => [\n 'app*' => [\n 'class' => 'yii\\i18n\\PhpMessageSource',\n //'basePath' => '@app/messages',\n 'sourceLanguage' => 'ru-RU',\n\n 'fileMap' => [\n 'app' => 'app.php',\n 'app/error' => 'error.php',\n ],\n ],\n ],\n ],\n\n\nview : \n\necho \\Yii::t('app', 'I am a message!');\n$username = 'Alexander';\necho \\Yii::t('app', 'Hello, {username}!', [\n 'username' => $username,\n]);"
]
| [
"php",
"yii2",
"multilingual"
]
|
[
"Edit data InputBox, Html, JavaScript",
"given that they are in the beginning in using the \"html\" interface and the Js language.... I'd have a little problem to solve..... I tried to take a look at the sequence of control characters (pattern), but I couldn't solve...... I would need to eliminate the initial \"zero\", in front of other possible numbers (only numbers, positives and decimals)..... (example: 045(no) ; 45(ok) ; 0450.85(no) ; 450.85(ok) ; 04500(no) ; 4500(ok).... Etc... inserting into an \"inputBox\" with type:\"text\".......Thank you..... Joseph."
]
| [
"javascript",
"html"
]
|
[
"Javascript from processor - unable to debug issues",
"I have a form that I'm trying to submit and process with javascript using the code outlined below:\n\nForm:\n\n<form id=\"my_form_id\" method=\"POST\" action=\"my_processor_script.php\">\n\n <input type=\"text\" id=\"form_id_1\" name=\"form_field_1\">\n\n <input type=\"text\" id=\"form_id_2\" name=\"form_field_2\">\n\n <input type=\"text\" id=\"form_id_3\" name=\"form_field_3\">\n\n<input class=\"cbp-mc-submit\" type=\"submit\" name=\"save_settings_button\" id=\"save_settings\" value=\"Save Settings\" />\n</form>\n\n\nScript: \n\n<script>\n$(document).ready(function(){\n var $form = $('form');\n $form.submit(function(){\n $.post($(this).attr('action'), $(this).serialize(), function(response){\n // do something here on success\n alert(\"Form Processed\");\n },'json');\n return false;\n });\n}); \n</script>\n\n\nProcessor:\n\n <?php if (isset($post_data['save_settings_button']))\n\n {\n $form_field_1 = $_POST['form_field_1'];}\n $form_field_2 = $_POST['form_field_2'];} \n $form_field_3 = $_POST['form_field_3'];}\n }\n\n ?>\n\n\nOnce I have the variables I then store them in a database.\n\nThe form works great if I just post from the form to the processor script without using the javascript however when I use the javascript nothing happens. I'm obviously doing something very wrong but can work this out at all as I cant see what is being received by the processor. Has anyone got any ideas on how i can get this to work?\n\nIt would also be great if I can return the data so that I can see what is being passed to the script as this would help me to debug any issues?"
]
| [
"javascript",
"php"
]
|
[
"Convert XML string to org.w3c.dom.Document?",
"I have the following XML string, I want to convert this string to org.w3c.dom.Document in order to get the value of 'CallPaySecureResult' element.\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Body xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <ns2:CallPaySecureResponse xmlns:ns2=\"https://paysecure/merchant.soap/\">\n <CallPaySecureResult>&amp;lt;status&amp;gt;success&amp;lt;/status&amp;gt;&amp;lt;errorcode&amp;gt;0&amp;lt;/errorcode&amp;gt;&amp;lt;errormsg /&amp;gt;&amp;lt;guid&amp;gt;d785f819-6fc1-1c68-8edf-bbb65cba5412&amp;lt;/guid&amp;gt;&amp;lt;/paysecure&amp;gt;</CallPaySecureResult>\n </ns2:CallPaySecureResponse>\n</S:Body>\n\n\nI have tried the following code\n\npublic String processIssuerResultParameters(String strXML)throws Exception\n {\n\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); \n DocumentBuilder builder; \n Document doc=null;\n String CallPaySecureResult =\"\";\n try \n { \n builder = factory.newDocumentBuilder(); \n doc = builder.parse( new InputSource( new StringReader( strXML ) ) ); \n logger.severe(doc.getTextContent());\n } catch (Exception e) { \n return \"1:\"+e.toString()+doc.getTextContent(); \n } \n }\n\n\nI have tried this:\n\nInputSource is= new InputSource(new StringReader(strXML));\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n builder = null;\n builder = factory.newDocumentBuilder();\n doc = builder.parse(is);\n\n\nand this :\n\nSource source = new StreamSource(new StringReader(strXML));\n DOMResult result = new DOMResult();\n TransformerFactory.newInstance().newTransformer().transform(source , result);\n doc = (Document) result.getNode();\n\n\nBut in all the cases variable 'doc' is null.\n\nHow can I parse the XML(string) to Document and get the value in <CallPaySecureResult>?"
]
| [
"javascript",
"java",
"xml"
]
|
[
"Is Text.concordance() in nltk available for pyspark as distributed method",
"I'm working on Natural Language Processing using NLTK on spark. where tried to implement 3.1 Accessing Text from the Web and from Disk part from http://www.nltk.org/book/ch03.html. For this I followed How to do Natural Language Processing (https://docs.continuum.io/anaconda-cluster/howto/spark-nltk ). I tried to implement text.concordance('gene') method but ended with result [None, None, None, None, None]. Here is my complete code. Any help will be greatly appreciated.\n\nfrom pyspark import SparkConf\nfrom pyspark import SparkContext\n\n\nconf = SparkConf()\nconf.setMaster('yarn-client')\nconf.setAppName('spark-nltk')\nsc = SparkContext(conf=conf)\n\ndata = sc.textFile('/user/test/2554.txt')\n\ndef word_tokenize(x):\n import nltk\n return nltk.word_tokenize(x)\n\ndef pos_tag(x):\n import nltk\n return nltk.pos_tag([x])\n\n\nwords = data.flatMap(word_tokenize)\nprint words.take(10)\n\n\nfrom nltk.text import Text \ntext = words.map(lambda x : Text(x).concordance('gene'))\nprint text.take(5)\n\n\n\npos_word = words.map(pos_tag)\nprint pos_word.take(5)"
]
| [
"python",
"apache-spark",
"nlp",
"nltk",
"pyspark"
]
|
[
"Is it correct to initialize state of child component via props?",
"I need to initialize state of child component from parent one. So I do it by the following way:\n\nvar Timer = React.createClass({\n getInitialState: function () {\n return {timer: this.props.timer};\n },\n render () {\n return <div>{this.state.timer}</div>\n }\n});\n\nvar App = React.createClass({\n getInitialState: function () {\n return {timer: 1000};\n },\n render () {\n return <Timer timer={this.state.timer}>\n }\n});\n\n\nIs it correct to initialize state of Timer component this way?"
]
| [
"javascript",
"reactjs"
]
|
[
"Decoding a binary signal",
"I'm reading the following binary signal off a gpio pin on my Raspberry Pi (it's the output from a weather station).\n\nThe 1st column is binary high or binary low. The second column is how long (seconds) it spends in the state.\n\nHow can I convert this signal to hexadecimal?!\n\n...\n0 14.929292\n1 0.002127\n0 0.006867\n1 0.001393\n0 0.005303\n1 0.001274\n0 0.006126\n1 0.001361\n0 0.007541\n1 0.001417\n0 0.005062\n1 0.001474\n0 0.005119\n1 0.001565\n0 0.004906\n1 0.001587\n0 0.004916\n1 0.002031\n0 0.006007\n1 0.001479\n0 0.003678\n1 0.001485\n0 0.000994\n1 0.004142\n0 0.000865\n1 0.006277\n0 0.003858\n1 0.001288\n0 0.001028\n1 0.001468\n0 0.000945\n1 0.004138\n0 0.003327\n1 0.001303\n0 0.001174\n1 0.001318\n0 0.001017\n1 0.001510\n0 0.001485\n1 0.001080\n0 0.001907\n1 0.002782\n0 0.001083\n1 0.002012\n0 0.000712\n1 0.003984\n0 0.001785\n1 0.001291\n0 0.003149\n1 0.001185\n0 0.001020\n1 0.001719\n0 0.000993\n1 0.003965\n0 0.001157\n1 0.001346\n0 0.001762\n1 0.001353\n0 0.003219\n1 0.001090\n0 0.001106\n1 0.001475\n0 0.001160\n1 0.001079\n0 0.003874\n1 0.001387\n0 0.001015\n1 0.001168\n0 0.001092\n1 0.001336\n0 0.002504\n1 0.001466\n0 0.006063\n1 0.001391\n0 0.001196\n1 0.001460\n0 0.001082\n1 0.001237\n0 0.005049\n1 0.001654\n0 0.004914\n1 0.001410\n0 0.002722\n1 0.001601\n0 47.818081\n1 0.001452\n0 0.007532\n1 0.001438\n0 0.007975\n1 0.001494\n0 0.003077\n1 0.002131\n0 0.003056\n1 0.001254\n0 0.002685\n1 0.001372\n0 0.005003\n1 0.002051\n0 0.006997\n1 0.001608\n0 0.004868\n1 0.001524\n0 0.002524\n1 0.001397\n0 0.003103\n1 0.001211\n0 0.002434\n1 0.001328\n0 0.003475\n1 0.001469\n0 0.003672\n1 0.001384\n0 0.003847\n1 0.001101\n0 0.001133\n1 0.001352\n0 0.003504\n1 0.002133\n0 0.003257\n1 0.001070\n0 0.001182\n1 0.001511\n0 0.003301\n1 0.001482\n0 0.003779\n1 0.001210\n0 0.001099\n1 0.001396\n0 0.001127\n1 0.001433\n0 0.001697\n1 0.001434\n0 0.003132\n1 0.001175\n0 0.001754\n1 0.001520\n0 0.002905\n1 0.001425\n0 0.003625\n1 0.001155\n0 0.001036\n1 0.001469\n0 0.001041\n1 0.001422\n0 0.001251\n1 0.001275\n0 0.003414\n1 0.001446\n0 0.001734\n1 0.001653\n0 0.000435\n1 0.002349\n0 0.000974\n1 0.005346\n0 0.003247\n1 0.001265\n0 0.001192\n1 0.001213\n0 0.001404\n1 0.001349\n0 0.000963\n1 0.003732\n0 0.001186\n1 0.001220\n0 0.002529\n1 0.001357\n0 0.002573\n1 0.001700\n0 0.001158\n1 0.001058\n0 0.002571\n1 0.001314\n0 0.001164\n1 0.001364\n0 0.124659\n1 0.001485\n0 0.007492\n1 0.002176\n0 0.006881\n1 0.002083\n0 0.005526\n1 0.001351\n0 0.005029\n1 0.001528\n0 0.001726\n1 0.001366\n0 0.002089\n1 0.001258\n0 0.002579\n1 0.001463\n0 0.001262\n1 0.001487\n0 0.000975\n1 0.003736\n0 0.002321\n1 0.002073\n0 0.004412\n1 0.001433\n0 0.002619\n1 0.001390\n0 0.002817\n1 0.001201\n0 0.003475\n1 0.001512\n0 0.000906\n1 0.003958\n0 0.003492\n1 0.001581\n0 0.000985\n1 0.004103\n0 0.001370\n1 0.001046\n0 0.001162\n1 0.001534\n0 0.001080\n1 0.001510\n0 0.003077\n1 0.002124\n0 0.003046\n1 0.001293\n0 0.003908\n1 0.001406\n0 0.001002\n1 0.001109\n0 0.001524\n1 0.001009\n0 0.001347\n1 0.001448\n0 0.000950\n1 0.003651\n0 0.001133\n1 0.002038\n0 0.002838\n1 0.001991\n0 0.002866\n1 0.001291\n0 0.003824\n1 0.001191\n0 0.001163\n1 0.001447\n0 0.000970\n1 0.004059\n0 0.000972\n1 0.006388\n0 0.001252\n1 0.001262\n0 0.001345\n1 0.001329\n0 0.004930\n1 0.001273\n0 0.003556\n1 0.001570\n0 0.003431\n1 0.001550\n0 0.001256\n1 0.001461\n0 0.001098\n1 0.001005\n0 0.002555\n1 0.001503\n0 0.005044\n1 0.002070\n0 0.004427\n1 0.001499\n...\n\n\nAs you can see, it's zero for ~48 seconds and then fires a load of 1's and 0's and goes back to zero again.\n\nI need to figure out the protocol. I can't tell what it is. The only information I do have is that the current temperature is 21 degrees celcius, wind speed is zero and wind direction is null. Any insight is greatly appreciated,\n\n\n\nAbove is a plot of some binary data for two different transmissions."
]
| [
"c",
"binary",
"protocols",
"reverse-engineering",
"gpio"
]
|
[
"Mongoid to date in aggregation framework",
"I am creating a projection and am trying to figure out how to convert a mongoid to a timestamp IN THE projection. It is apparent that we can use .getTimestamp() to just get the timestamp of a mongoid, but I don't know how to make a new field in a projection. I tried this and it fails. \n\ndb.collection.aggregate( \n[\n {$unwind: \n \"$arrayToUnwind\"\n },\n {$project: \n {\n timeOfId: \"$_id\".getTimeStamp()\n }\n },\n]\n\n\n)\n\nAny help please?! I want to make an ISO timestamp out of this projection.\n\nThanks!"
]
| [
"mongodb",
"time",
"collections",
"aggregation-framework",
"database"
]
|
[
"Adjust height and weight of a box according to windows size in shiny",
"I am trying this code for automatically adjust height and weight of a box according to windows size i.e., while maximizing the window, the box in my shiny app should also adjust its size. \n\ntabitems(\n tabItem(tabName = \"plot1\", \n box( width = \"100%\" , height = \"100%\", solidHeader = FALSE, status = \"primary\",\n plotOutput(\"plot\"))\n)\n\n\nThe width of the box is changing its size according to the app window size but the height isn't?"
]
| [
"shiny",
"rstudio"
]
|
[
"MVC3/T4 Custom Scaffolder Gives File Exists Error Even When File Doesn't Exist",
"I have written a custom scaffolder for MVC3 using T4 templates to scaffold a delete stored procedure for a database and table passed to the scaffolder as parameters. When I run the scaffolder the output file is created in the correct place, but I get the following error:\n\n\n Invoke-ScaffoldTemplate : Unable to add 'UpdateCustomerCoupon.sql'. A\n file with that name already exists. At line:1 char:23\n + param($c, $a) return . <<<< $c @a\n + CategoryInfo : NotSpecified: (:) [Invoke-ScaffoldTemplate], COMException\n + FullyQualifiedErrorId : T4Scaffolding.Cmdlets.InvokeScaffoldTemplateCmdlet\n\n\nIt doesn't matter if the file exists at the output location or not. I get this error every time.\n\nHere is the PowerShell script for the scaffolder:\n\n[T4Scaffolding.Scaffolder(Description = \"Enter a description of DeleteSQL here\")][CmdletBinding()]\nparam(\n [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)][string]$DatabaseName,\n [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)][string]$TableName,\n [string]$Project,\n [string]$CodeLanguage,\n [string[]]$TemplateFolders,\n [switch]$Force = $true\n)\n\n$outputPath = \"Scripts/SQL/$TableName/Delete$TableName\"\n\nAdd-ProjectItemViaTemplate $outputPath -Template DeleteSQLTemplate `\n -Model @{ TableName = $TableName; DatabaseName = $DatabaseName; Project = $Project } `\n -SuccessMessage \"Added DeleteSQL output at {0}\" `\n -TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force\n\nWrite-Host \"Scaffolded DeleteSQL\"\n\n\nAnd here is the T4 Template code:\n\n<#@ Template Language=\"C#\" HostSpecific=\"True\" Inherits=\"DynamicTransform\" Debug=\"True\" #>\n<#@ Output Extension=\"sql\" #>\n<#@ assembly name=\"System.Collections\" #>\n<#@ assembly name=\"System.Configuration\" #>\n<#@ assembly name=\"System.Data\" #>\n<#@ assembly name=\"System.Web\" #>\n<#@ import namespace=\"System.Collections.Generic\" #>\n<#@ import namespace=\"System.Configuration\" #>\n<#@ import namespace=\"System.Data\" #>\n<#@ import namespace=\"System.Data.SqlClient\" #>\n<#@ import namespace=\"System.Web\" #>\nUSE [<#= Model.DatabaseName #>]\nGO\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nALTER PROCEDURE [dbo].[Delete<#= Model.TableName #>] (\n @P<#= Model.TableName #>ID AS BIGINT,\n @PChangedByUserID BIGINT,\n @PChangedByURL VARCHAR(1024),\n @PChangedByIpAddress varchar(16)\n)\nAS\n SET NOCOUNT ON\n\n BEGIN TRY\n BEGIN TRANSACTION\n -- update user history\n DECLARE @userHistoryID BIGINT = 0;\n DECLARE @details VARCHAR(4096) = '[<#= Model.TableName #>] ID ''' + CAST(@P<#= Model.TableName #>ID AS VARCHAR) + ''' was deleted.'\n EXEC InsertUserHistory @PChangedByUserID, @details, @PChangedByURL, @PChangedByIpAddress, @userHistoryID OUTPUT\n\n -- Rollback transaction if user history was not created\n IF(@userHistoryID = 0) BEGIN\n ROLLBACK\n SELECT CAST(-1 AS INT)\n RETURN\n END\n\n DELETE FROM\n [<#= Model.TableName #>]\n WHERE\n [ID] = @P<#= Model.TableName #>ID\n COMMIT\n\n SELECT CAST(1 AS INT)\n END TRY\n BEGIN CATCH\n ROLLBACK\n SELECT CAST(-2 AS INT)\n END CATCH\n\n RETURN\n\n\nI invoke the scaffolder by typing \"Scaffold DeleteSQL -DatabaseName $DatabaseName -TableName $TableName\" into the Package Manager Console.\n\nI have also tried invoking the scaffolder with the -Force option like this: \"Scaffold DeleteSQL -DatabaseName $DatabaseName -TableName $TableName -Force\". I have also used \"-Force true\" and \"-Force:true\" with no luck. Also notice that the $Force parameter is set to true anyway, so I think it should overwrite by default, right?\n\nWhat do I need to do to get rid of this error?\n\nThanks for the help."
]
| [
"asp.net-mvc-3",
"t4",
"scaffolding",
"asp.net-mvc-scaffolding",
"t4scaffolding"
]
|
[
"mySQL list profiles and movies using complex joins in one query but three tables",
"Overview:\nI want to get a list of profiles and the movies they like. All the output to be shown on one page. I am using mySQL and PHP, at moment running on localhost. Ideally i want this to be in one query, for speed.\n\nDatabase table overview in mySQL as follow:\n\nprofile_tbl:\n> id\n> username\n> about me\n> gender\n> hobbies\n> profile_pic\n> last_login\n\n\nmovies_tbl:\n> id\n> movie_name\n> genre\n> length\n> rating\n> description\n\n\nprofile_movies_rel_tbl\n> id\n> movie_id\n> profile_id\n\n\nOutput:\n\nI want to show 10 profiles and list of the all the movies they like. I was thinking following query:\n\nSELECT profile_tbl.*, movies_tbl.* FROM profile_tbl\nLEFT JOIN profile_movies_rel_tbl\nON profile_movies_rel_tbl.movie_id = movies_tbl.id\nLEFT JOIN profile_tbl\nON profile_tbl.id= profile_movies_rel_tbl.profile_id LIMIT 10\n\n\nI also have a second issue, where I want to lists all the profile that have selected movie has favorite, again the page should list profiles and movies together.\nIn this case, i was thinking of using the above query and adding following:\n\nWHERE profile_movies_rel_tbl.movie_id = 4\n\n\nAny one need more info, please leave comment.\n\nthanks"
]
| [
"php",
"mysql",
"subquery",
"left-join",
"inner-join"
]
|
[
"Python - Using GridSearchCV with NLTK",
"I'm a little unsure as to how I can apply SKLearn's GridSearchCV to a random forest I'm using with NLTK. How to use GridSearchCV normally is discussed here, however my data is formatted differently to the standard x and y split. Here is my code:\n\nimport nltk\nimport numpy as np\nfrom nltk.classify.scikitlearn import SklearnClassifier\nfrom nltk.corpus.reader import CategorizedPlaintextCorpusReader\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\n\n\nreader_train = CategorizedPlaintextCorpusReader('C:/Users/User/Documents/Sentiment/machine_learning/amazon/amazon/', r'.*\\.txt', cat_pattern=r'(\\w+)/*', encoding='latin1')\n\ndocuments_train = [ (list(reader_train.words(fileid)), category)\n for category in reader_train.categories()\n for fileid in reader_train.fileids(category) ]\n\nall_words = []\n\nfor w in reader_train.words():\n all_words.append(w.lower())\n\nall_words = nltk.FreqDist(all_words)\n\nword_features = list(all_words.keys())[:3500]\n\ndef find_features(documents):\n words = set(documents)\n features = {}\n for w in word_features:\n features[w] = (w in words)\n\nreturn features\n\nfeaturesets_train = [(find_features(rev), category) for (rev, category) in documents_train]\n\nnp.random.shuffle(featuresets_train)\n\ntraining_set = featuresets_train[:1600]\ntesting_set = featuresets_train[:400]\n\nRandFor = SklearnClassifier(RandomForestClassifier())\nRandFor.train(training_set)\nprint(\"RandFor accuracy:\", (nltk.classify.accuracy(RandFor, testing_set)) *100)\n\n\nThis code, instead of producing a conventional x and y split, produces a list of tuples, where each tuple is in the following format:\n\n({'i': True, 'am': False, 'conflicted': False ... 'about': False}, neg)\n\n\nIs there a way to apply GridSearchCV to data in this format?"
]
| [
"performance",
"scikit-learn",
"nltk",
"random-forest",
"hyperparameters"
]
|
[
"Anti Forgery Token Axios Asp .Net Core",
"Hi i am able to send a post using vue js axios to a controller in Asp .NET Core 2.2 like this\n\n axios({\n url: '/Parametros/Create',\n method: 'post', \n ContentType: 'application/json',\n data: formData \n })\n\n\nhowever for this to work i have to remove from my action in controller\n\n[ValidateAntiForgeryToken]\n\n\nAlso the token is generated in razor pages as input \n\n<input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"CfDJ8GwWLSmGzLVOqfs-yISjocyQshOjT98BeCqxo14sO91JGUZPe_IstyK9DWZyu0rCr0bxdx3lBlwminvxm7q0zXVWcUkAZIH8NwKDYGdNCiY-Z_BgMzLt_1PyNEHxfpmTouJgMu3il8N4fMjbI0ohwElXGK-eVLXGuzj_J5N_uQ3A4f-9ijmTKGk8p3BC7hrB1A\">\n\n\nI tried\n\naxios({\n url: '/Parametros/Create',\n method: 'post',\n headers: { \n \"__RequestVerificationToken\": $('input[name=\"__RequestVerificationToken\"]').val();\n } \n ContentType: 'application/json',\n data: formData \n})\n\n\nand\n\naxios({\n url: '/Parametros/Create',\n method: 'post', \n ContentType: 'application/json',\n data: {\n \"__RequestVerificationToken\": $('input[name=\"__RequestVerificationToken\"]').val(),\n formData \n }\n})\n\n\nNone work, I keep getting bad request... Using ajax the 2nd approach works fine but axios not. How can i handle this?"
]
| [
"javascript",
"vuejs2",
"axios",
"asp.net-core-2.2"
]
|
[
"Play Framework 2: Best way of validating individual model fields separately",
"For this example, lets assume the user would like to update just the first name of his online profile.\n\nForm:\n\n<form data-ng-submit=\"updateFirstName()\">\n <label for=\"firstName\">First name<label>\n <input type=\"text\" name=\"title\" data-ng-model=\"firstName\">\n <button type=\"submit\">Update first name</button>\n</form>\n\n\nController:\n\npublic class UsersController {\n public static Result updateFirstName() {\n Form<User> filledForm = Form.form(User.class).bindFromRequest();\n\n // TODO: Validate firstName\n\n // if hasErrors() return bad request with errors as json\n\n // else save and return ok()\n }\n}\n\n\nModel:\n\n@Entity\npublic class User extends Model {\n @Id\n public Long id;\n @Constraints.Required\n public String firstName;\n @Constraints.Required\n public String lastName;\n}\n\n\nHow would one validate just one field at a time against the models constraints and return any resulting error messages back as json? This is quite a simple example, the real thing will have many fields (some very complex) together with a form for each."
]
| [
"java",
"forms",
"playframework",
"playframework-2.2"
]
|
[
"Emacs matlab mode key binding for running tests",
"I am using Emacs + matlab-mode as my Matlab development environment. I also have MTEST installed together with Matlab to run my unit tests - what I want to do now is to have a key binding that runs the tests from the current file in the matlab-shell I constantly have opened around (M-x matlab-shell).\n\nWhat I have until now is:\n\n; Runs the unit tests available in the current buffer\n(defun run-matlab-test ()\n(interactive)\n(matlab-shell-run-command (concat \"runtests \"\n (car (split-string (buffer-name) \"\\\\.\")))))\n\n; Bind \"C-c l\" to running unit tests in matlab-mode\n(defun map-run-matlab-test-keys ()\n (local-set-key (kbd \"C-c l\") 'run-matlab-test))\n\n(add-hook 'matlab-mode-hook 'map-run-matlab-test-keys)\n\n\nWhat I need to do is in the run-matlab-test function to have a way of calling the runtests command with the parameter provided by the (buffer-name) command and all this should happen in the matlab shell I mentioned above. Any hints ?\n\nEdit: I managed to get it working by calling matlab-shell-run-command. The caveat here is that it only works if the starting sequence is: open your unit-test.m file, from that file run M-x matlab-shell (this way matlab starts with the current working directory in the tests directory) and then you can use the above binding."
]
| [
"unit-testing",
"matlab",
"emacs"
]
|
[
"PHP DomXPath encoding issue after xpath",
"If I use echo $doc->saveHTML(); It will show the characters accordingly , but once it reaches the xml? at xpath to extract the element , the issues are back again. \n\nI cant seem to display the characters properly. How do i convert it properly. I'm getting:\n\n婢跺繐顒滈拺鍙ョ瀵偓鐞涱偊鈧繑妲戦挅鍕綍婢舵牕顨� 闂€鍌溾敄缂侊綀濮虫稉濠呫€� 娑擃叀顣荤純鎴犵綍閺冭泛鐨绘總鍏呯瑐鐞涳綀鏉藉▎\n\n\nInstead of proper Chinese:\n\n<head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta charset=\"gbk\"/></head>\n\n\nMy PHP code:\n\n$html = file_get_contents('http://item.taobao.com/item.htm?spm=a2106.m874.1000384.41.aG3Kbi&id=20811635147&_u=o1ffj7oi9ad3&scm=1029.newlist-0.1.16&ppath=&sku=');\n$doc = new DOMDocument();\n\n// Based on Article http://stackoverflow.com/questions/11309194/php-domdocument-failing-to-handle-utf-8-characters/11310258#11310258\n$searchPage = mb_convert_encoding($html,\"HTML-ENTITIES\",\"GBK\");\n$doc->loadHTML($searchPage);\n// echo $doc->saveHTML(); \n\n$xpath = new DOMXpath($doc);\n$elements = $xpath->query(\"//*[@id='detail']/div[1]/h3\");\n\nforeach ($elements as $e) {\n //echo $e->nodeValue;\n echo mb_convert_encoding($e->nodeValue,\"utf-8\",\"gbk\");\n}"
]
| [
"php",
"html",
"dom",
"xpath"
]
|
[
"how to reply jsonp in cakephp without resorting to .json",
"In CakePHP, the framework detects what data type to return in using either the url with the extension .json OR they search for the Accepts http header.\n\nIn JSONP, I cannot modify the hTTP header. https://stackoverflow.com/a/19604865/80353\n\nI want to avoid using .json\n\nI then tried to set the viewClass using the code below:\n\n if ($this->request->is('ajax')) {\n $this->log('enter here');\n $this->viewClass = 'Json';\n }\n\n\nSubsequently, I realized that the request will not work because the header does not contain the XMLHTTPRequest.\n\nMy questions are: \n\n1) how do I return Json data for jsonp requests without resorting to the extension in the url?\n\n2) is there a way for cakephp to detect a jsonp request? My gut says this is not possible."
]
| [
"javascript",
"json",
"cakephp",
"jsonp"
]
|
[
"Access query results in Facebook C# SDK v6",
"In previous versions I was able to retrieve the results from a query using:\n\n var facebookClient = new Facebook.FacebookClient(accessToken);\n const string fqlQuery = \"select pic_big from user where uid=me()\";\n dynamic result = facebookClient.Query(fqlQuery);\n\n var profilePhotoUrl = result[0].pic_big.ToString();\n\n\nIn version 6, I can accomplish the same, but using:\n\n var facebookClient = new Facebook.FacebookClient(accessToken);\n const string fqlQuery = \"select pic_big from user where uid=me()\";\n dynamic result = facebookClient.Get(\"fql\", new { q = fqlQuery });\n\n var profilePhotoUrl = result.data[0].pic_big.ToString(); //v6.0 requires us to add \".data[0]\" field \n\n\nThe new way work, but I just want to make sure that: result.data[0].pic_big.ToString() is correct."
]
| [
"facebook-c#-sdk"
]
|
[
"Creating a program that will run before and after compilation in Eclipse",
"I am currently working on a small program that should comment out some code used for testing.\nI want it to auto run before the compiler while compiling the release version and another program that will comment the code back in after compilation was over.\n\nThe program works the only thing I am missing is to add it to the build process.\nThanks to all helpers!"
]
| [
"java",
"eclipse",
"compilation",
"builder",
"precompiled"
]
|
[
"Git: Who has modified this line?",
"If I found a bug in my application, sometimes I need to know which commits have affected to the bug source code line. I'm wondering which is the best approach to do it with Git."
]
| [
"git"
]
|
[
"How to pass state object/data to an (async) ajax callback?",
"I am doing ajax call in a loop scope, and I need the success callback to use the correct \"i\" in which it was called.\n\nlike so (Pseudo JavaScript code):\n\nfor (i = 1 ; i <= 10 ; ++i)\n{\n $.ajax( { ....,\n success : function(data) {\n // I want to use the correct i HERE\n }\n });\n}\n\n\nObviously it doesn't work since by the time the success callback is called, the i value is out of sync with the callback..."
]
| [
"javascript",
"jquery",
"ajax"
]
|
[
"C# Entering string into external process console",
"I am trying to find a way to input strings into a console of an external program that is already running on my pc of which I have no control over the code.\nBut I simply have no clue where to look for something like this.\nI've looked into pipes as someone told me he used them for a similar purpose to mine but for all I can find they don't really make sense for what I'm trying, but I might be wrong.\nI would like to have a way that can run fully in the background, so it's not simply a bot that types manually.\n\nWhat would be a good/simple method of doing what I'm trying?"
]
| [
"process",
"pipe",
"external"
]
|
[
"hex value in field/row terminator for bulk insert",
"I'm running SQL Server 2005 Express. And I'm trying to do a bulk insert/import of a data file with a field/row terminator that uses a hexadecimal value 0x001. How should I represent it in a bulk insert command?\n\nI have something like: \n\nbulk insert xxx.dbo.[yyy]\nfrom 'D:\\zzz\\zzz.dat'\nwith (\n CODEPAGE='RAW',\n FIELDTERMINATOR = '=|=',\n ROWTERMINATOR = '=|=\\001\\n',\n KEEPNULLS\n); \n\n\nwhich results in \n\nMsg 4863, Level 16, State 1, Line 7\nBulk load data conversion error (truncation) for row 1, column 3 (code).\n\n\nColumn 3 is the last column. And removing the hex value from the string lets it load properly in SQL Server, however, I want to know if it's possible to represent/use a hex value in a terminator."
]
| [
"sql-server-2005"
]
|
[
"How to disable sidemenu on Ionic React by routing through certain page?",
"I have an Ionic-React application which has a sidemenu on the main page. I am using IonicSplitPane and IonReactRouter to achieve this. However, I couldn't disable the sidemenu when routing through the login page. I tried the following code and it worked but the routing in the sidemenu is now not working. How do I fix this?\nimport Menu from './components/Menu';\nimport Page from './pages/Page';\nimport React from 'react';\nimport { IonApp,IonRouterOutlet, IonSplitPane } from '@ionic/react';\nimport { IonReactRouter } from '@ionic/react-router';\nimport { Redirect, Route } from 'react-router-dom';\nimport Home from './pages/Home';\nimport Login from './pages/Login';\n\n/* Core CSS required for Ionic components to work properly */\nimport '@ionic/react/css/core.css';\n\n/* Basic CSS for apps built with Ionic */\nimport '@ionic/react/css/normalize.css';\nimport '@ionic/react/css/structure.css';\nimport '@ionic/react/css/typography.css';\n\n/* Optional CSS utils that can be commented out */\nimport '@ionic/react/css/padding.css';\nimport '@ionic/react/css/float-elements.css';\nimport '@ionic/react/css/text-alignment.css';\nimport '@ionic/react/css/text-transformation.css';\nimport '@ionic/react/css/flex-utils.css';\nimport '@ionic/react/css/display.css';\n\n/* Theme variables */\nimport './theme/variables.css';\n\nconst App: React.FC = () => {\n\n return (\n <IonApp>\n <IonSplitPane contentId="main">\n <IonReactRouter>\n {/*<!-- Side Menu -->*/}\n <Menu />\n {/*<!-- Main Content -->*/} \n <IonRouterOutlet id="main">\n <Route path="/page/:name" component={Page} exact />\n <Redirect from="/" to="/page/home/gallery" exact />\n <Route path="/page/home/gallery" component={Home} exact />\n </IonRouterOutlet>\n \n </IonReactRouter>\n </IonSplitPane>\n\n {/*<!-- No Sidemenu -->*/} \n <IonReactRouter>\n <IonRouterOutlet>\n <Route path="/page/login" component={Login} exact />\n </IonRouterOutlet>\n </IonReactRouter>\n\n </IonApp>\n );\n}\n\nexport default App;"
]
| [
"reactjs",
"ionic-framework"
]
|
[
"How can I change the auto formatting positioning of curly braces?",
"From this: \n\nif (condition == true)\n{\n // do something\n}\n\n\nto this: \n\nif (condition == true) {\n // do something\n}\n\n\nIn School the PC's are used to the second, and I prefer it more. Thought my Visual Studio automaticlly uses the first. How can I change it?"
]
| [
"c#",
"visual-studio"
]
|
[
"MuleSoft Anypoint Studio- DataSense not working for Salesforce Connector",
"I have a problem with Datasense for querying in Salesforce connector. By clicking on 'Query Builder' for 'Datasense Query Language', the popup window doesn't have the required data in the left/right panel. Also by clicking on add filter respective dropdown has no value to apply the filter. \n\nBelow is the screenshot for reference: \n\n\n\nNote: I have checked the Datasense option in connector configuration."
]
| [
"mule",
"datamapper",
"mule-studio"
]
|
[
"Example of a while loop that can't be written as a for loop",
"I know a while loop can do anything a for loop can, but can a for loop do anything a while loop can?\n\nPlease provide an example."
]
| [
"loops",
"for-loop",
"while-loop",
"control-flow"
]
|
[
"How to combine text values from multiple rows into a single cell in Access query",
"I have a table for added discount or motivation for employee salaries each month in the year. This table contains a field that can contain only the words \"Discount\" or \"Motivation\" using lookup.\n\nEvery month I can add more than one discount or motivation, so when I want to pay the salaries in the end of the month, I want these data grouped in one row for each employee.\n\nThis is the table that takes the discount and motivation during the month. The table name is Table1:\n\n\nThe desired query result:"
]
| [
"sql",
"ms-access",
"group-by"
]
|
[
"How to use Shamir Secret Sharing Class in Crypto++",
"I tried to use the SecretSharing Class in Crypto++, but I couldn't make it work.\n\nHere is my code:\n\nusing namespace CryptoPP;\n\nvoid secretSharing(){\n AutoSeededRandomPool rng;\n SecretSharing shamir(rng, 4, 6); \n byte test[] = {'a', 'b', 'c', 'd'};\n shamir.Put(test, 4); \n //shamir.MessageEnd();\n\n //cout << shamir.TotalBytesRetrievable() <<endl;\n}\n\n\nAfter compile and run, I will get:\n\n./main \nterminate called after throwing an instance of 'CryptoPP::BufferedTransformation::NoChannelSupport'\n what(): unknown: this object doesn't support multiple channels\n[1] 3597 abort (core dumped) ./main\n\n\nThe declaration of SecretSharing::SecretSharing() is:\n\nSecretSharing (RandomNumberGenerator &rng, int threshold, int nShares, BufferedTransformation *attachment=NULL, bool addPadding=true)\n\nShould I give it a BufferedTransformation*, but exactly which class should I use? \n\nAre there any Secret Sharing example code in Crypto++?"
]
| [
"c++",
"cryptography",
"crypto++"
]
|
[
"Can't release pushed docker image in heroku",
"I am pretty new to Heroku. \n\nIssue Description\n\nAfter successfully pushing a docker image to Heroku Container Registry using JIB I am struggling to release it.\n\nWhat I did:\n\nPushed docker image using JIB:\n\n[INFO] Built and pushed image as hamzablm/timesheet\n[INFO] Executing tasks:\n[INFO] [=========================== ] 88.9% complete\n[INFO] > launching layer pushers\n[INFO] \n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 51.106 s\n[INFO] Finished at: 2020-04-20T11:16:20Z\n[INFO] ------------------------------------------------------------------------\n\n\nBy now the image should be in the registry.\nBut when I want to release it:\nheroku container:release hamzablm/timesheet It fails:\n\n › Error: Missing required flag:\n › -a, --app APP app to run command against\n › See more help with --help\n\n\nI'm probably missing something simple here, but any help would be appreciated."
]
| [
"docker",
"heroku",
"heroku-cli"
]
|
[
"Perform linear regression with sunspot dataset",
"I'm trying to perform a linear regression using k-fold validation, in the sunspost dataset.\nIn this exercise I need to take the last 10 years as test and use the rest for tranning, further I should measure the model accuracy using RMSE.\nAlso, I need to test k-values from 1 to 24 in order to identify the better k value (lower RMSE)\nHowever, Im obtaining very strange RMSE values for k (ranging from -6 to -1) while it should stay closer to 16 I think, considering that sunspot values are not normalized.\n(PS: For the following script I've generated the day_count column imagining that the regression model does not accept date values.)\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn import linear_model\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom numpy import reshape\nimport datetime\nimport random\nimport sys\nfrom sklearn.utils import shuffle\n\ndf= pd.read_csv("sunspots2.csv", sep =";")\n\n\nimport pandas as pd\ndf['Date'] = pd.to_datetime(df['Date'])\ndf = df.set_index(df['Date'])\ndf = df.sort_index()\n\n\n# create train test partition\ntrain = df['1979-01-31':'2009-12-31']\ntest = df['2010-01-01':]\nprint('Train Dataset:',train.shape)\nprint('Test Dataset:',test.shape)\n\nX_train = np.array(train[["day_count"]])\nX_test = np.array(test[["day_count"]])\n\ny_train = np.array(train[["Sunspot"]])\ny_test = np.array(test[["Sunspot"]])\n\nfrom sklearn.linear_model import LinearRegression\n# Create model\nlinreg = LinearRegression()\nlinreg.fit(X_train, y_train)\n# Calculate our y hat (how our model performs against the test data held off)\ny_hat_test = linreg.predict(X_test)\n\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n# See our Squared Mean Error score and Root Mean Squared Error:\ntest_mse = mean_squared_error(y_test, y_hat_test)\ntest_rmse = np.sqrt(test_mse)\nprint(test_rmse)\n# See our Mean Absolute Error\ntest_mae = mean_absolute_error(y_test, y_hat_test)\nprint(test_mae)\n\n#See the RMSE values for each K (Rangin from 1 to 24)\nfrom sklearn.model_selection import cross_val_score\n\nlista_k = []\nfor i in list(range(27)):\n if i > 2:\n cv_4_results = cross_val_score(linreg, X_test, y_test, cv=i, scoring='neg_mean_squared_error')\n lista_k.append(cv_4_results)\n\nfor a in lista_k:\n print("Accuracy: %0.2f (+/- %0.2f)" % (a.mean(), a.std() * 2))\n\n\n\nThank you all very much!"
]
| [
"python",
"machine-learning",
"scikit-learn",
"linear-regression",
"sklearn-pandas"
]
|
[
"Representing integer as a linked list",
"Writing a function in C that represents an integer as a singly linked list, the minus sign for negative integers does not show up. What am I doing wrong? Can you suggest any improvements in the algorithm, and the fastest way to solve it? C noob here.\n\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n char info;\n struct Node *link;\n} Node;\n\nNode* add_front (Node* head, char info)\n{\n Node* t = malloc(sizeof(struct Node));\n t->info = info;\n t->link = head;\n return t;\n}\n\nvoid display (Node* head)\n{\n while(head != NULL) {\n printf(\"%d \", head->info);\n head = head->link;\n }\n}\n\nNode* number_list (int n)\n{\n int digit, minus = (n < 0 ? 1 : 0);\n Node* list = NULL;\n\n if (minus) n *= -1;\n\n do {\n digit = n % 10;\n list = add_front(list, (char)digit);\n n = n / 10;\n } while(n > 0);\n\n if (minus) add_front(list, '-');\n\n return list;\n}\n\nint main()\n{\n int n = -1024;\n Node* l = number_list(n);\n display(l);\n return 0;\n}"
]
| [
"c",
"integer",
"linked-list"
]
|
[
"closing socket in BSD sockets",
"My code is :\n\nint main(int argc, char *argv[])\n{\n int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */\n struct sockaddr_in my_addr; /* my address information */\n struct sockaddr_in their_addr; /* connector's address information */\n socklen_t sin_size;\n\n /* generate the socket */\n if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {\n perror(\"socket\");\n exit(1);\n }\n\n /* generate the end point */\n my_addr.sin_family = AF_INET; /* host byte order */\n my_addr.sin_port = htons(MYPORT); /* short, network byte order */\n my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */\n /* bzero(&(my_addr.sin_zero), 8); ZJL*/ /* zero the rest of the struct */\n\n /* bind the socket to the end point */\n if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) \\\n == -1) {\n perror(\"bind\");\n exit(1);\n }\n\n /* start listnening */\n if (listen(sockfd, BACKLOG) == -1) {\n perror(\"listen\");\n exit(1);\n }\n\n printf(\"server starts listnening %d...\\n\",sockfd);\n\n /* repeat: accept, send, close the connection */\n /* for every accepted connection, use a sepetate process or thread to serve it */\nwhile(1) { /* main accept() loop */\n sin_size = sizeof(struct sockaddr_in);\n if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \\\n &sin_size)) == -1) {\n perror(\"accept\");\n continue;\n }\n printf(\"server: got connection from %s\\n\", \\\n inet_ntoa(their_addr.sin_addr));\n\n if ((numbytes=recv(new_fd, buf, MAXDATASIZE, 0)) == -1) {\n perror(\"recv\");\n exit(1);\n }\n\n buf[numbytes] = '\\0';\n\n printf(\"Received: %s\",buf);\n\n if (send(new_fd, \"Hello, world!\\n\", MAXDATASIZE, 0) == -1)\n perror(\"send\");\n close(new_fd);\n exit(0);\n\n close(new_fd); /* parent doesn't need this */\n\n while(waitpid(-1,NULL,WNOHANG) > 0); /* clean up child processes */\n}\nreturn 0;\n}\n\n\nSo whenever I execute this server, after one client uses that it terminates. But If I want to execute it again lets say within 60 seconds, then it gives an error of bind: Address already in use I thought the close() function actually releases the socket so that it would be available to use it again instantly. So what am I missing here?"
]
| [
"c",
"sockets"
]
|
[
"Does rake task limit functionality of my class to call external API?",
"AllegroAPI is a class in the /models directory that calls an external API. It works as I wish when I test in somewhere else not by running rake task.\n\nExample working code: \n\nrequire \"./AllegroAPI\"\n\nallegro = AllegroAPI.new(login: 'LOGIN', \n password: File.read('XXXX.txt'),\n webapikey: File.read('XXX.txt')\n )\nputs allegro.do_search({\"search-string\"=>\"nokia\", \n \"search-price-from\"=>300.0, \n \"search-price-to\"=>500.0, \n \"search-limit\"=>50}).to_s\n\n\nAs I've said it works correctly. It calls the API and prints out the result. \n\nFile allegro.rb is also in the models directory and it's a file I'm executing by running this task:\n\nnamespace :data do\n desc \"Update auctions table in database\"\n task update_auctions: :environment do\n Allegro.check_for_new_auctions\n end\nend\n\n\nallegro.rb:\n\nmodule Allegro\n require 'AllegroAPI'\n def self.check_for_new_auctions\n allegro = AllegroAPI.new(login: 'LOGIN', \n password: File.read('app/models/ignore/XXXX.txt'),\n webapikey: File.read('app/models/ignore/XXX.txt')\n )\n looks = Look.all\n looks.each do |l|\n hash_to_ask = ActiveSupport::JSON.decode(l[:look_query]).symbolize_keys\n hash_to_ask = hash_to_ask.each_with_object({}) do |(k,v), h|\n if v.is_number?\n h[k.to_s.split('_').join('-')] = v.to_f\n else\n h[k.to_s.split('_').join('-')] = v \n end\n end\n results = allegro.do_search(hash_to_ask)\n #do something with data \n end\n end\nend\n\n\nThe problem is that it doesn't return anything. var result is not nil, but it does not hold anything.\n\nWhen I'm trying to debug it and call API from the inside do_search function it's calling API, doesn't raise a error but response is nothing. AllegroAPI works correctly. There is no problem with var \"hash_to_ask\", it's exactly the same hash as in working example.\n\nEDIT:\n\nI've commented out check_for_new_auctions and used \"puts\", it works fine when I run it by executing rake task. Then I've used exactly the same code which I used in normal file which have ran properly:\n\nclass Allegro\n def self.check_for_new_auctions\n allegro = AllegroAPI.new(login: 'LOGIN', \n password: File.read('app/models/ignore/XXXX.txt'),\n webapikey: File.read('app/models/ignore/XXXX.txt')\n )\n hash_to_ask = {\"search-string\"=>\"nokia\", \n \"search-price-from\"=>300.0, \n \"search-price-to\"=>500.0, \n \"search-limit\"=>50}\n allegro.do_search(hash_to_ask).to_s\n end\nend\n\n\nIt have not worked;/ The returned value from allegro.do_search(hash_to_ask) is hash, not empty, not nil but when I try to print it, it's nothing, empty place. \n\nEDIT:\n\nEverything have worked properly, waste like 15 hours total debugging the problem which have not existed. I'm not sure why it have not worked but it couldn't print to the console after converting to string, so I tried writing it down to file blindly. What I have found in the text file? Data. \nI don't know why it couldn't print out everything in the console."
]
| [
"ruby-on-rails",
"rake"
]
|
[
"Python: Analyze output on application screen",
"I am trying to automate my login in an application on windows, however the challenge is the application is dynamic at one place while logging in. The following is the code that work fine sometime. Now after the first enter I want python to analyze what is on the screen and then it should either press 1 or skip the step.\nAlso I would like the people in this community to tell me how do I get more information about the usage of syntax for any module. Is there any website that I could use to increase my knowledge about python? \n\nfrom pywinauto import Application\nimport time\napp = Application().Start(cmd_line=u'\"C:\\\\Program Files (x86)\\\\MEDITECH\\\\Workstation3.x\\\\T.exe\"')\nmrw = app.MRW\nmrw.Wait('ready')\ntime.sleep(2)\nmrw.TypeKeys(\"{ENTER}\")\ntime.sleep(1) # This step is not always required\nmrw.TypeKeys(\"1\")\ntime.sleep(0.5)\nmrw.TypeKeys(\"{ENTER}\")\ntime.sleep(0.5)\nmrw.TypeKeys(\"psingh1\")\ntime.sleep(0.5)\nmrw.TypeKeys(\"{ENTER}\")\ntime.sleep(0.5)\nmrw.TypeKeys(\"1234567\")\ntime.sleep(0.5)\nmrw.TypeKeys(\"{ENTER}\")\ntime.sleep(0.5)\nmrw.TypeKeys(\"4\")\ntime.sleep(0.5)\nmrw.TypeKeys(\"{ENTER}\")\ntime.sleep(0.5)"
]
| [
"python"
]
|
[
"Changing CSS properties from Javascript",
"Not able to do that. \n\nBeen trying things like: \n\n document.getElementById(\"sharebar\").innerHTML=\"\"; //This works\n alert(document.getElementById(\"sharebar\").toString());\ndocument.getElementById(\"sharebar\").setAttribute(\"width\", \"0px\"); //To remove formatting but this doesnt"
]
| [
"javascript",
"css"
]
|
[
"MDT Module Updating Media through JEA Endpoint fails adding BCD entry",
"I am running into an issue with remotely updating MDT offline media on a JEA endpoint. The error has something to do with permissions passed to BCDEdit and the virtual account created by JEA (WinRM User...). BCDEdit returns \n\n\n An error occurred while attempting the specified create operation. This security ID may not be assigned as the owner of this object.\n\n\nwhen trying to update the BCD file with the x64 boot config.\n\nCommand:\n\nInvoke-Command -ComputerName $DeploymentServerName -ConfigurationName MDTUpdate -ScriptBlock { \n New-PSDrive -Name \"DS002\" -PSProvider MDTProvider -Root \"$Using:LocalDeploymentShareFolder\" -ErrorAction Stop\n Update-MDTMedia -Path \"DS002:\\Media\\MEDIA001\" -Verbose\n } -Credential $MDTCreds -ErrorAction Stop\n\n\nCommand that MDT module runs:\n\n'C:\\Program Files (x86)\\Windows Kits\\10\\Assessment and Deployment Kit\\Deployment Tools\\AMD64\\BCDBoot\\bcdedit.exe' -store \"C:\\MyVMs\\MDT\\USB\\Content\\Boot\\bcd\" /create \"{f31cce1a-e314-4481-9ac9-e519f65dff65}\" -d \"Litetouch Boot [MEDIA001] (x64)\" -application OSLOADER\n\n\nError from JEA Transcript:\n\nVERBOSE: Error detected running command: 'C:\\Program Files (x86)\\Windows Kits\\10\\Assessment and Deployment Kit\\Deployment Tools\\AMD64\\BCDBoot\\bcdedit.exe -store \"C:\\MyVMs\\MDT\\USB\\Content\\Content\\Boot\\bcd\" /create \"{f31cce1a-e314-4481-9ac9-e519f65dff65}\" -d \"Litetouch Boot [MEDIA001] (x64)\" -application OSLOADER' Exit code is: 1\nVERBOSE: Error text is: An error occurred while attempting the specified create operation. This security ID may not be assigned as the owner of this object.\nUpdate-MDTMedia : BcdEdit returned an error.\nAt line:5 char:9\n+ Update-MDTMedia -Path \"DS002:\\Media\\MEDIA001\" -Verbose\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : InvalidOperation: (MEDIA001:String) [Update-MDTMedia], DeploymentPointException\n + FullyQualifiedErrorId : BcdEditError,Microsoft.BDD.PSSnapIn.GenerateMDTMedia\n\n\nRelevant information from session config:\n\n@{\n SchemaVersion = '2.0.0.0'\n SessionType = 'Default'\n ExecutionPolicy = 'Unrestricted'\n LanguageMode = 'FullLanguage'\n TranscriptDirectory = 'C:\\JEA\\Transcripts'\n RunAsVirtualAccount = $true\n RoleDefinitions = @{\n 'ExampleDomain\\ExampleUserOrGroup' = @{\n 'RoleCapabilities' = 'MDTUpdate' \n } \n }\n}\n\n\nRelevant content from role config:\n\n@{\nModulesToImport = 'C:\\Program Files\\Microsoft Deployment Toolkit\\Bin\\MicrosoftDeploymentToolkit.psd1'\nVisibleCmdlets = 'Get-Command','Out-Default','Exit-PSSession','Measure-Object','Select-Object','Get-FormatData','Start-Transcript','Stop-Transcript','Import-Module','Get-Module','New-PSDrive','Write-Output','Update-MDTDeploymentShare','Remove-Item','Update-MDTMedia','New-Item','Remove-PSDrive'\nVisibleProviders = 'FileSystem', 'MDTProvider'\nVisibleExternalCommands = 'bcdedit.exe'\n}\n\n\nHow can I give BCDEdit the proper permissions when running under the virtual account? Or do I have to drop JEA and give a service account local admin rights and run it under the default PSSession?"
]
| [
"powershell",
"mdt"
]
|
[
"Sign in with Twitter and Security for a Zend Framework App",
"I'm trying to replicate the functionality i've seen on a couple of sites:\n\n\nhttp://todaslistas.heroku.com\nhttp://endor.se\n\n\nThe idea is you sign up and log in with Twitter using Oauth. Once you have authed the app at twitter you then return to their site and they keep you logged in. In the case of each one they obviously base this on cookies as i can return to the site after closing my browser and i am still logged in. This seems inherently insecure, what are they doing here to maintain the login?\n\nI will be using Zend Framework but i guess that doesnt really matter."
]
| [
"php",
"security",
"zend-framework",
"twitter",
"oauth"
]
|
[
"why curl time out does not work",
"I am developing this application that connects(using NUSOAP) to a web service in order to retrieve the content.\nWhen i submit the XML to the web service i get connected but the response take more than 30 seconds to reply. I have tried couple changes but the script still ends at 30 seconds mark with the following message(from the Nusoap object):\ncURL ERROR: 28: Operation timed out after 30015 milliseconds with 0 bytes received\n\nthis is the code(part of it) i am using:\n\n$ch = curl_init();\n curl_setopt($ch, CURLOPT_TIMEOUT, 0);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);\n $client = new nusoap_client ( $this->getCreditcheckUrl(), true,false, false, false, false, 0, 300);\n\n $client->soap_defencoding = 'utf-8';\n $client->decode_utf8 = false;\n $client->operation = 'contentOrder';\n $client->useHTTPPersistentConnection (); // Uses http 1.1 instead of\n // 1.0\n $client->setUseCurl ( true );\n $client->loadWSDL ();\n $client->portName = \"PrepareOrderPort\";\n\n $client->setCredentials ( \"\", \"\", \"certificate\", array (\n // \"cainfofile\" => $sslPath . $caPath , //OPTIONAL\n \"sslcertfile\" => self::sslPath . self::sslcert,\n \"sslkeyfile\" => self::sslPath . self::sslcert,\n \"passphrase\" => \"xxxxxxxxx\",\n \"certpassword\" => \"xxxxxxxx\", // OPTIONAL\n \"verifypeer\" => False, // OPTIONAL\n \"verifyhost\" => 1 // OPTIONAL\n ) );\n $client->send($xmlRequest);\n\n $contentRaw = $client->responseData;\n\n\nIs there a way to force to only stop when it gets a response?\n\nAny help is greattly appreciated, i have been fighting this for weeks.\n\nthank you."
]
| [
"php",
"curl",
"nusoap"
]
|
[
"Stop a recursive function Python",
"import sys\n\nsys.setrecursionlimit(10)\ndef bounce(n):\n if n <= 0:\n print(n,)\n bounce(n+1)\n\n\n else:\n print(n)\n bounce(n - 1)\n if (n==0 ):\n n==False\n\n\nI'm trying to create a countdown and countup program. I only have the option to use one function and I have to use a recursive function. But every time I run the program it wont do anything the this: \n\n4\n3\n2\n1\n0\n1\n0\n1\n0\n1\n0\n1\n0\n1\n0\n1 \n\n\nWhat can I do to make the countup work like it is supposed to? It's supposed to look like this:\n\n>>> bounce(4)\n4\n3\n2\n1\n0\n1\n2\n3\n4\n>>> bounce(0)"
]
| [
"python",
"function",
"recursion"
]
|
[
"Programmatically created spinner doesn't open",
"I created a spinner programmatically:\n\nArrayAdapter<ServiceObject> medicineArrayAdapter = new ArrayAdapter<ServiceObject>(MedicineActivity.this, android.R.layout.simple_spinner_dropdown_item, medicines);\nmedicineArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n\nSpinner spinner = new Spinner(MedicineActivity.this, getSpinnerAttrs(), 0);\nspinner.setAdapter(medicineArrayAdapter);\nspinner.setLayoutParams(new ViewGroup.LayoutParams(\nViewGroup.LayoutParams.MATCH_PARENT,\nViewGroup.LayoutParams.WRAP_CONTENT));\n\nspinner.setVisibility(View.VISIBLE);\nbuttonLayout.addView(spinner, index);\n\n\nWhere getSpinnerAttrs():\n\nAttributeSet as = null;\nResources r = getResources();\nXmlResourceParser parser = r.getLayout(R.layout.fragment_medicine);\n\nint state = 0;\ndo {\n try {\n state = parser.next();\n } catch (XmlPullParserException xppe) {\n xppe.printStackTrace();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n if (state == XmlPullParser.START_TAG) {\n if (parser.getName().equals(\"Spinner\")) {\n as = Xml.asAttributeSet(parser);\n break;\n }\n }\n} while(state != XmlPullParser.END_DOCUMENT);\n\nreturn as;\n\n\nand Spinner in fragment_medicine is:\n\n<Spinner\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:background=\"@android:drawable/btn_dropdown\"\n android:spinnerMode=\"dropdown\"\n android:visibility=\"invisible\"/>\n />\n\n\nIt shows normally But when I click on it, it doesn't open . . ."
]
| [
"java",
"android",
"android-spinner",
"programmatically-created"
]
|
[
"left join without explicit relationship in nhibernate 3.3.1.4000",
"I have these two simplified entities:\n\npublic class Measurement : Entity\n{\n public virtual float DisplayValue { get; set; }\n private DateTime _timeStamp;\n public virtual DateTime TimeStamp\n {\n get { return _timeStamp; }\n set { _timeStamp = value.ToUniversalTime(); }\n }\n}\n\npublic class TimeStamp : Entity\n{\n public virtual DateTime TimeStampEntry { get; set; }\n}\n\n\nAnd I am using this (my)sql code to determine missing values over a range:\n\nSET time_zone='+0:00'; \nselect \n a.TimeStampEntry,\n b.DisplayValue\nfrom timestamps as a \nleft outer join \n(\n select\n TimeStamp,\n DisplayValue\n from measurements \n) as b on a.TimeStampEntry = b.TimeStamp\nwhere a.TimeStampEntry>='2010-01-01 00:00:00' and a.TimeStampEntry<'2010-01-31 23:59:59' and b.DisplayValue is null\norder by a.TimeStampEntry asc\n\n\nI am just wondering how I could achieve this in Nhibernate 3.x, preferably in Linq.\n\nBTW, I have not tried anything serious as the relationship between the datetime fields is not defined in fluent nhibernate. Not sure whether I have to define this to be able to use ICriteria, Linq, HQL or whatever. Any feedback would be very much appreciated. Thanks.\n\nPS: \n\nI have made a start with this (not working code):\n\nvar x = (from ts in NHibernateSession.Current.Query<TimeStamp>()\n join m in NHibernateSession.Current.Query<Measurement>()\n on ts.TimeStampEntry equals m.TimeStamp into ps\n from m in ps.DefaultIfEmpty()\n select new { m.TimeStamp }).ToList();\n\n\nPPS:\n\nstacktrace:\n\nat NHibernate.Linq.Visitors.QueryModelVisitor.VisitGroupJoinClause(GroupJoinClause groupJoinClause, QueryModel queryModel, Int32 index)\n at Remotion.Linq.Clauses.GroupJoinClause.Accept(IQueryModelVisitor visitor, QueryModel queryModel, Int32 index)\n at Remotion.Linq.QueryModelVisitorBase.VisitBodyClauses(ObservableCollection`1 bodyClauses, QueryModel queryModel)\n at Remotion.Linq.QueryModelVisitorBase.VisitQueryModel(QueryModel queryModel)\n at NHibernate.Linq.Visitors.QueryModelVisitor.Visit()\n at NHibernate.Linq.Visitors.QueryModelVisitor.GenerateHqlQuery(QueryModel queryModel, VisitorParameters parameters, Boolean root)\n at NHibernate.Linq.NhLinqExpression.Translate(ISessionFactoryImplementor sessionFactory)\n at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory)\n at NHibernate.Engine.Query.HQLExpressionQueryPlan.CreateTranslators(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)\n at NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)\n at NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)\n at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters)\n at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow)\n at NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression)\n at NHibernate.Linq.DefaultQueryProvider.PrepareQuery(Expression expression, IQuery& query, NhLinqExpression& nhQuery)\n at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)\n at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression expression)\n at Remotion.Linq.QueryableBase`1.GetEnumerator()\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)"
]
| [
"linq",
"nhibernate"
]
|
[
"jquery performing a selector on an element variable",
"I'm having difficulty with performing a selector operation on an element variable. First I'm selecting my table element in my page using jquery. \n\nvar $popup = null;\n$popup = $(\"#popup_List\");\n\n<div id=\"popup\" class=\"popup_block\">\n <table id=\"popup_List\"><tr><td>Name</td></tr></table>\n</div>\n\n\nI'm trying to perform a selector operation on the $popup variable. The following does not work \n\n$popup(\"tr:last\").after(\"<tr><td>Name</td></tr\");\n\n\nI'd like to use the variable approach because $(\"#popup_List\") would have to be referenced numerous times in the code otherwise."
]
| [
"jquery",
"variables",
"element",
"selector"
]
|
[
"Difference between setting Heap memory in terms of jvm and Tomcat",
"I have Java 8 installed in my system and am able to view and set the initial and max heap size for JVM from command line. Am using tomcat 7 and while going through some of the tutorials I found a way to change the heap size for tomcat as well using setenv.bat file. \n\nMy question here is how are the above two things different? The start up script or batch file of tomcat uses the java 8 installed in the system using JAVA_HOME environment variable. \n\nIf my JVM heap space is 1024 M and I set 512 M heap space for tomcat, does it mean that my tomcat application can use up to 512 M of heap from 1024 M heap of the JVM?"
]
| [
"java",
"jvm",
"tomcat7"
]
|
[
"Stored procedure access from form",
"I have the following code:\n\nstring connectionString = \"<REDACTED>\";\n\n\n\n using (SqlConnection invoiceConnection = new SqlConnection(connectionString))\n {\n SqlCommand command = new SqlCommand(\"dbo.sInvoiceBySchool\", invoiceConnection);\n\n command.Parameters.AddWithValue(\"@School\", SqlDbType.Int);\n command.Parameters[\"@School\"].Value = schoolNumber.Value;\n\n invoiceConnection.Open();\n command.ExecuteNonQuery();\n\n }\n\n\nThe output consistently returns error 201, \"Message = Procedure or function 'sInvoiceBySchool' expects parameter '@School', which was not supplied.\". I am supplying the value that the procedure wants using a numericupdown, then use a button to run the code. \n\nI've also tried writing the value directly into the code, with the same result. Have I formatted the parameters properly?"
]
| [
"c#",
"sql",
"stored-procedures"
]
|
[
"Why does implicit conversion not work in accumulate?",
"This is the C++ program:\n\n#include <iostream>\n#include <vector>\n#include <numeric>\nusing namespace std;\n\nint test_string(const string & str) {\n return str.size();\n}\n\nvoid main() {\n test_string(\"\"); //can compile\n vector<string> v;\n string sum = accumulate(v.cbegin(), v.cend(), \"\"); //cannot compile\n}\n\n\nI want to use implicit conversion from const char * to string in the call of generic STL function accumulate. I know that conversion from const char * to string is not explicit, so we can pass const char * parameter to calls in which a string type is required. This can be proved by the above test_string function. But when I did the same thing in accumulate, the compiler complain:\n\n\nerror C2440: '=': cannot convert from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *'\n\n\n\nThe code works only when I replaced \"\" with string(\"\"). I don't understand why the implicit conversion works for my custom function but does not work in accumulate. Can you explain that? Thanks a lot.\n\nPS: I am using Visual Studio 2015."
]
| [
"c++",
"string",
"templates",
"implicit-conversion"
]
|
[
"With asp.net MVC4, how can I make my root index.html be executed by default?",
"For much of my web site, I want normal routing to occur the MVC way. However, when the app first launches, I don't want the route to go to /Home/Index.cshtml. I want it to go to simply /Index.html\n\nMy current RegisterRoutes looks like this (and does not achieve my goal)\n\n public static void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n routes.IgnoreRoute(\"index.html\");\n\n routes.MapRoute(\n name: \"Default\",\n url: \"{controller}/{action}/{id}\",\n defaults: new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }\n );\n }"
]
| [
"asp.net-mvc-4",
"asp.net-mvc-routing"
]
|
[
"pyroCMS and codeigniter add-ons",
"Greetings I will just ask very simple question. I'm very new to PyroCMS and I was wondering \nif is possible use same modules, add-ons, widgets and plugins created in Codeigniter for PyroCMS?"
]
| [
"php",
"codeigniter",
"frameworks",
"pyrocms"
]
|
[
"Could not load file or assembly ... or one of its dependencies. An attempt was made to load a program with an incorrect format (.resx file)",
"I am getting the following error message when compiling or attempting to run my application on Windows 7 64 bit. I've scoured the Internet and many people have the same error message. However, none of the solutions address my problem or situation. I am using Visual Studio 2010.\nError message\n\nError 38 Could not load file or assembly 'file:///D:/Projects/Windows Projects/Weld/Components/FileAttachments/FileAttachments/FileAttachments/bin/x86/Debug/FileAttaching.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format. Line 1212, position 5. D:\\Projects\\Windows Projects\\Weld\\Weld\\Weld.UI\\frmMain.resx 1212 5 Weld.UI\n\nDescription\nOK, so I have two projects, a UI project and a FileAttachment project. The UI project has a reference to the FileAttachment project. When I compile the UI project in "Any CPU" mode, everything works fine, and it runs. I assume 'Any CPU' will run in 64-bit mode when I compile as that is the platform I am using.\nI want to run/compile as x86, so I try to do that. I change the configuration for all projects to x86 and verify that these configurations are compiling to x86. I compile and get the error as stated above.\nI find it odd that it compiles and works fine in 64-bit but not 32-bit. However, when compiled and deployed to users as 'Any CPU', if these users have x86 it still works for them without any problems. I just can't compile or run as x86 on my PC. Again, I can compile as Any CPU and deploy to a 32-bit PC without any problems.\nNeither projects are referencing any 64-bit-only DLL files. Both projects are verified to be targeting 32-bit DLL files and .NET Framework assemblies.\nI need to compile and run this locally under 32-bit mode. I need JIT edit/continue, among other things.\nHere is the line of code in the resx file that is causing the problem:\n <data name="ImageList1.ImageStream" mimetype="application/x-microsoft.net.object.binary.base64">\n....{mime data}....\n </data>\n\nThe resx file is verified to be generated for .NET 2.0 and is only referencing .NET 2.0 assemblies and not .NET 4.0 versions.\nHow can I fix this problem? I've searched the Internet and have found hundreds of people with the same error message, but a different problem."
]
| [
".net",
"visual-studio-2010",
"visual-studio"
]
|
[
"Call to a member function fetchAll() on a non-object-",
"So, there's quite a few instances of this exact problem on this website.\n\nBut most of them have a bunch of other things mixed in wtih them, such as classes, numerous parameters, etc.\n\nI have some very basic code, no, really, probably as basic as it gets:\n\ntry {\n\n $connection = new PDO(\"mysql:host=localhost;dbname=desertstormweb_mybb\", $mysql_user, $mysql_pass);\n\n $test = 'SELECT * from mybb_users';\n $statement = $connection->prepare($test);\n $statement = $statement->execute();\n $result = $statement->fetchAll();\n print($result);\n\n} catch(PDOException $e) {\n echo $e->getMessage();\n}\n\n\nBasically, I'm just trying to return the rows in a table, now I've used PDO numerous times before, and I've never had this problem.\n\nI even started referencing other scripts I've done in the past and can't quite figure it out...\n\nWhat's going on?"
]
| [
"php",
"mysql",
"pdo"
]
|
[
"Cocos2d Sprite performance with bitplanes",
"Is it possible to improve performance drawing sprites by reducing the number of bit planes used in their image file? For example if you only used 4 colours and hence image was 2 bitplanes, would cocos2d show and manipulate these quicker than a 24 bit colour sprite?"
]
| [
"ipad",
"cocos2d-iphone",
"sprite"
]
|
[
"why laravel shows random results for downloading files?",
"At first I want to show FileDownload statics and numbers to User...so I made a Model named FileDownload:\n\n protected $guarded = ['id'];\n protected $dates = [\n 'download_date'\n ];\n public $timestamps = false;\n\n\nthen I write the code below for Model File.php :\n\n public function updateDownloadCounts() {\n\n $isDownloadExistForToday = FileDownload::where('file_id',$this->file_id)->\n whereDate('download_date',Carbon::today())->first();\n if($isDownloadExistForToday && $isDownloadExistForToday instanceof FileDownload)\n {\n $isDownloadExistForToday->increment('download_count');\n }else{\n FileDownload::create([\n 'file_id' => $this->file_id,\n 'download_count' => 1,\n 'download_date' => Carbon::now()\n ]);\n }\n\n}\n\n\nAnd it is my FileController using download files:\n\n public function download(Request $request, int $file_id)\n{\n $current_user = Auth::user();\n if (!\\App\\Utility\\File::user_can_download($current_user->id)) {\n return view('frontend.files.access');\n }\n $fileItem = File::find($file_id);\n if (!$fileItem) {\n return redirect()->back()->with('FileError', 'requested file is invalid!');\n }\n $basePath = public_path('files\\\\');\n $filePath = $basePath . $fileItem->file_name;\n $currentUserSubscribe = $current_user->currentSubscribe()->first();\n $currentUserSubscribe->increment('subscribe_download_count');\n $fileItem->increment('file_download_num');\n $fileItem->updateDownloadCounts();\n return response()->download($filePath);\n}\n\n\nnow i'v expected to every download adds 1 number to column download_count but 1 filedownload adds 5 and others adds nothing to database!\nfor example downloading file number 1 for 3 times adds 15 numbers to Download_count column!but other files add 1 number to same column or add nothing at all!\n\nI hope you can help me figure this out!"
]
| [
"database",
"laravel",
"model-view-controller"
]
|
[
"Exclude directories in find that don't contain a specific filename?",
"Let's say I have a directory containing a number of subdirectories, each with a number of files in them. I wish to check which of these directories do not contain a specific file. For example, if these are my directories:\n\ndir/A:\n foo\n bar\ndir/B:\n bar\ndir/C:\n foo\ndir/D:\ndir/E:\n foo\n bar\n\n\nIf I wanted to list all directories not containing foo, I would get:\n\ndir/B\ndir/D\n\n\nIs it possible to do this with unix find, or do I need to use some alternate tool?"
]
| [
"unix",
"find"
]
|
[
"List all Articles on a page Drupal 8",
"I am new to Drupal. I've created different articles and now I want to show them on one of my pages (Let's say the \"Articles\" page). How do I do this? Some other sites suggest to use \"views\" for this, but isn't there a more easy solution?"
]
| [
"drupal-8"
]
|
[
"Scaling results in gaps between CSS shapes",
"I have a series of CSS hexagons. I would like to apply CSS scale transform for different viewport widths, though gaps are appearing within my hexagon shapes.\n\nThis problem is most evident on Firefox at any scale value. It also appears in Chrome if scaled to non-integer values. Firefox additionally shows baffling horizontal lines in the :before and :after pseudo elements, though these lines are in the centre of a border and not at the edge of any shape.\n\nSnippets\n\nA simplified version of my markup and styles is below, and also on JS Fiddle.\n\nHTML:\n\n<div class=\"scale\">\n <div class=\"hex\"></div>\n</div>\n\n\nStyles:\n\n.scale {\n margin: 8em auto;\n text-align: center;\n -webkit-transform:scale(2.5, 2.5);\n -moz-transform:scale(2.5, 2.5);\n -ms-transform:scale(2.5, 2.5);\n -o-transform:scale(2.5, 2.5);\n transform:scale(2.5, 2.5);\n}\n.hex {\n position: relative;\n display: inline-block;\n margin: 0 30px;\n width: 60px;\n height: 104px;\n background-color: #000;\n &:before, &:after {\n position: absolute;\n width: 0;\n border: 1px solid transparent;\n border-width: (52px) (30px);\n content: \"\";\n }\n &:before {\n border-right-color: #000;\n right: 100%;\n }\n &:after {\n border-left-color: #000;\n left: 100%;\n }\n}\n\n\nScreenshots (Linux Mint)\n\nChrome: scaled at x2 (no gaps evident at integer values)\n\n\nFirefox: scaled at x2 (gaps, plus horizontal lines)\n\n\nIs there help?\n\nMy guess is that these lines are appearing because of some numerical rounding, but I really am out of ideas. Is it possible to fix this? Is there another approach I could use for this scaling? Thanks in advance for any responses."
]
| [
"css",
"transform",
"scale",
"scaletransform"
]
|
[
"jQuery FullCalendar event drag and drop not working in mobile,tab",
"I am developing webapplication using jsp,servlet,jquery fullcalender.\n\n\nIt is working smoothly on desktop browser(drag and drop).but testing on android,ipad tab or mobile I am not able to drag and drop event in calender. \n\n\nI just wanted to working(drag and drop using touch) in android/ipad tab or mobile devices."
]
| [
"javascript",
"jquery"
]
|
[
"I need to run query \"USE database\", everytime i call a new function",
"Every time i call a new function it shows an error that \n\n\n \"No database is selected\".\n\n\nPreviously it was not the case, i only had to call \"USE database\" once.\n\nI have replaced DriverManager with MySqlDataSource.\n\nI am running \"USE database\" query at the starting of program by calling InitializeData();\n\npublic class Database {\n\npublic static MysqlDataSource dataSource;\n\nstatic void InitializeData()\n{\n dataSource = new MysqlDataSource();\n dataSource.setUser(\"root\");\n dataSource.setPassword(\"zxcvbnm@123\");\n\n try{\n Connection con = Main.getConnection();\n Statement existence = con.createStatement();\n boolean q1 = existence.execute(\"CREATE DATABASE IF NOT EXISTS votingdata\");\n\n Statement st = con.createStatement();\n st.execute(\"USE votingdata\");\n ...........................................continue.........\n\n\nThis is Main.getConnection() function\n\npublic static Connection getConnection(){\n Connection con=null;\n try {\n con = Database.dataSource.getConnection();\n }\n catch(SQLException e){\n System.out.print(\"Connection lost \"+e.getMessage());\n }\n return con;"
]
| [
"java",
"mysql",
"database",
"jdbc"
]
|
[
"Choose jdk location for NetBeans",
"I want to install NetBeans but I need the location of jdk where that's Installed. I installed it by dnf in fedora 25. Can anyone help me to how find the location of installed package jdk???"
]
| [
"java",
"openjdk"
]
|
[
"JTable does not show columns",
"The columns on my JTabel arnt showing up :/\nI cant find out why, aslo, my scrollbar isnt showing up. Being novice I cant find out why.\n\nHere is my code:\n\n String [] columnNames = {\"From\", \"Depature\",\"To\",\"Arrvial\",};\n Object[][] data = {\n {\"Orlando, FL\", \"3/15/2014 @ 8:00 AM\", \"Atlanta, GA\", \"3/15/2014 @ 9:05 AM\"},\n {\"Atlanta, GA\", \"3/16/2014 @ 11:49 AM\", \"Chicago, IL\", \"3/16/2014 @ 1:05 PM\"},\n {\"Chicago, IL\", \"3/17/2014 @ 1:25 PM\", \"San Francisco, CA\", \"3/17/2014 @ 6:05 PM\"},\n {\"San Francisco, CA\", \"3/18/2014 @ 2:10 PM\", \"Seattle, WA\", \"3/18/2014 @ 5:35 PM\"},\n {\"Seattle, WA\", \"3/19/2014 @ 4:35 PM\", \"Atlanta, GA\", \"3/19/2014 @ 10:45 PM\"},\n {\"Orlando, FL\", \"3/15/2014 @ 8:00 AM\", \"Atlanta, GA\", \"3/15/2014 @ 9:05 AM\"},\n {\"Atlanta, GA\", \"3/16/2014 @ 11:49 AM\", \"Chicago, IL\", \"3/16/2014 @ 1:05 PM\"},\n {\"Chicago, IL\", \"3/17/2014 @ 1:25 PM\", \"San Francisco, CA\", \"3/17/2014 @ 6:05 PM\"},\n {\"San Francisco, CA\", \"3/18/2014 @ 2:10 PM\", \"Seattle, WA\", \"3/18/2014 @ 5:35 PM\"},\n {\"Seattle, WA\", \"3/19/2014 @ 4:35 PM\", \"Atlanta, GA\", \"3/19/2014 @ 10:45 PM\"},\n {\"Orlando, FL\", \"3/15/2014 @ 8:00 AM\", \"Atlanta, GA\", \"3/15/2014 @ 9:05 AM\"},\n {\"Atlanta, GA\", \"3/16/2014 @ 11:49 AM\", \"Chicago, IL\", \"3/16/2014 @ 1:05 PM\"},\n {\"Chicago, IL\", \"3/17/2014 @ 1:25 PM\", \"San Francisco, CA\", \"3/17/2014 @ 6:05 PM\"},\n {\"San Francisco, CA\", \"3/18/2014 @ 2:10 PM\", \"Seattle, WA\", \"3/18/2014 @ 5:35 PM\"},\n {\"Seattle, WA\", \"3/19/2014 @ 4:35 PM\", \"Atlanta, GA\", \"3/19/2014 @ 10:45 PM\"},\n {\"Orlando, FL\", \"3/15/2014 @ 8:00 AM\", \"Atlanta, GA\", \"3/15/2014 @ 9:05 AM\"},\n {\"Atlanta, GA\", \"3/16/2014 @ 11:49 AM\", \"Chicago, IL\", \"3/16/2014 @ 1:05 PM\"},\n {\"Chicago, IL\", \"3/17/2014 @ 1:25 PM\", \"San Francisco, CA\", \"3/17/2014 @ 6:05 PM\"},\n {\"San Francisco, CA\", \"3/18/2014 @ 2:10 PM\", \"Seattle, WA\", \"3/18/2014 @ 5:35 PM\"},\n {\"Seattle, WA\", \"3/19/2014 @ 4:35 PM\", \"Atlanta, GA\", \"3/19/2014 @ 10:45 PM\"},\n };\n\n\n flightTable = new JTable(data, columnNames);\n scrollPane = new JScrollPane(flightTable);\n borderLayout = new BorderLayout();\n setLayout(borderLayout);\n add(scrollPane, BorderLayout.CENTER);\n flightTable.setFillsViewportHeight(true);\n add(flightTable, BorderLayout.CENTER);"
]
| [
"java",
"swing",
"layout",
"jtable"
]
|
[
"How to enter a password to a password protected key file from Command prompt?",
"I need to checkout a project from SVN, but every time I open the project, Visual Studio 2017 asks me to enter a password to a key file. The password is to access to assembly files. I've found a manually workaround, but I need to do this as a command line with command Prompt. Someone know how ? Thx."
]
| [
"command-line",
"command",
"command-prompt"
]
|
[
"EWS Schema information not found",
"I am trying to connect an Xamarin.Android C# program to an Exchange 2013 server via Exchange WebService (EWS). I send the following XML file (dynamically created using XmlTextWriter):\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n <t:RequestServerVersion Version=\"Exchange2007_SP1\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" />\n </soap:Header>\n <soap:Body>\n <m:GetRoomLists xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" />\n </soap:Body>\n</soap:Envelope>\n\n\nand receive this answer (minus formatting):\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <s:Body>\n <s:Fault>\n <faultcode xmlns:a=\"http://schemas.microsoft.com/exchange/services/2006/types\">a:ErrorSchemaValidation</faultcode>\n <faultstring xml:lang=\"de-DE\">Fehler bei der Schemaüberprüfung der Anforderung: Die Schemainformationen für das Element 'http://schemas.microsoft.com/exchange/services/2006/messages:GetRoomLists' konnten nicht gefunden werden.</faultstring>\n <detail>\n <e:ResponseCode xmlns:e=\"http://schemas.microsoft.com/exchange/services/2006/errors\">ErrorSchemaValidation</e:ResponseCode>\n <e:Message xmlns:e=\"http://schemas.microsoft.com/exchange/services/2006/errors\">Fehler bei der Schemaüberprüfung der Anforderung.</e:Message>\n <t:MessageXml xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\">\n <t:LineNumber>7</t:LineNumber>\n <t:LinePosition>6</t:LinePosition>\n <t:Violation>Die Schemainformationen für das Element 'http://schemas.microsoft.com/exchange/services/2006/messages:GetRoomLists' konnten nicht gefunden werden.</t:Violation>\n </t:MessageXml>\n </detail>\n </s:Fault>\n </s:Body>\n</s:Envelope>\n\n\nThe error texts translate roughly to \"Error while checking request scheme\" (<e:Message>) and \"Scheme information for element '<URL>:GetRoomLists' could not be found\" (<t:Violation>); <faultstring> is the combination of both.\n\nI don't understand where the error lies. Is my request XML bad, is the Exchange Server misconfigured or is a module missing (if so, which one?), is there some other error?\n\nI've tried several other things in the SOAP body, e.g. <GetRooms><RoomList><EmailAddress>room@server</EmailAddress></RoomList></GetRooms>, with the same error message (complaining about GetRooms)."
]
| [
"c#",
"xml",
"soap",
"exchangewebservices"
]
|
[
"Problem with Icon.png (Icon specified in the Info.plist not found under the top level app wrapper: Icon.png (-19007))",
"I'm putting together a universal app and I have the icons in my project, but I keep getting a warning from the compiler in regards to Icon.png.\n\nI followed the instructions at http://developer.apple.com/library/ios/#qa/qa2010/qa1686.html but still get the above error.\n\nI've tried doing the following:\n\nPutting the icons in the Shared group and adding them according to the plist according to the tech note.\nChanging the icon paths to add Shared/ to them to point to the shared folder.\n\nCreating a Resources group (which the tech note fails to point out that XCode doesn't create a Resources Group for a universal app) and moving them into that (I removed the \"Shared/\" prefixes from the plist.)\n\nMoving the icons to the top level of the project.\n\nI've also double-checked the icon sizes and they are all correct, as well as the names of each.\n\nAnything I might have missed?"
]
| [
"ios4",
"icons",
"packaging"
]
|
[
"parsing recursive XML with SAX",
"The last couple days I tried to parse a XML file but I got no success. Im using SAX parser but the XML is recursive and I don't know you to control de parsing.\n\nThe XML is quite extense, but below you can see a sample of how it is.\n\n<root>\n <prop1>teste</prop1>\n <items>\n <item>\n <prop1>teste1</prop1>\n <items> \n <item>\n <prop1>teste1.1</prop1>\n <items null />\n </item>\n </items>\n </item>\n <item>\n <prop1>teste1</prop1>\n <items null />\n </item>\n </items>\n</root>\n\n\nI don't know how to handle the loop inside the startElement and the endElement methods.\nAny help would be cool... thanks in advance."
]
| [
"android",
"xml",
"parsing",
"sax"
]
|
[
"Why I get HashMap cannot be resolved to a type error?",
"Here is my Java code:\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n\n public class Polynomial<K> {\n Map<Integer, Object> polynomial;\n\n public Polynomial(){\n polynomial = new HashMap<K, V>();\n }\n public Polynomial(int numberOfMembers){\n polynomial = new HashMap<K, V>(numberOfMembers);\n }\n public void addElm(int power, int coefficient){\n if (power < 0) {\n power = Math.abs(power);\n throw new RuntimeException(\"ERROR: The power must be an absolute number, converting to absolute\");\n }\n for (Map.Entry m : polynomial.entrySet()) {\n if ((Integer) m.getKey() == power){\n polynomial.put(power,m.getValue());\n }\n }\n }\n\n }\n\n\nOn this two rows:\n\npolynomial = new HashMap<K, V>();\n\n\nand this:\n\npolynomial = new HashMap<K, V>(numberOfMembers);\n\n\nI get this error:\n\nHashMap<K,V> cannot be resolved to a type\n\n\nAny idea what cause to the error above and how to fix it?"
]
| [
"java"
]
|
[
"Multiple transactions lines to base table SAS",
"I am new to sas and are trying to handle some customer data, and I'm not really sure how to do this. \nWhat I have:\n\ndata transactions; \ninput ID $ Week Segment $ Average Freq; \ndatalines; \n1 1 Sports 500 2\n1 1 PC 400 3\n1 2 Sports 350 3\n1 2 PC 550 3\n2 1 Sports 650 2\n2 1 PC 700 3\n2 2 Sports 720 3\n2 2 PC 250 3\n; \nrun; \n\n\nWhat I want:\n\ndata transactions2;\ninput ID Week1_Sports_Average Week1_PC_Average Week1_Sports_Freq \nWeek1_PC_Freq\nWeek2_Sports_Average Week2_PC_Average Week2_Sports_Freq Week2_PC_Freq;\ndatalines;\n1 500 400 2 3 350 550 3 3 \n2 650 700 2 3 720 250 3 3\n;\nrun; \n\n\nThe only thing I got so far is this:\n\n Data transactions3;\n SET transactions;\n if week=1 and Segment=\"Sports\" then DO; \n Week1_Sports_Freq=Freq; \n Week1_Sports_Average=Average;\n END;\n else DO;\n Week1_Sports_Freq=0; \n Week1_Sports_Average=0;\n END;\n run; \n\n\nThis will be way too much work as I have a lot of weeks and more variables than just freq/avg. \n\nReally hoping for some tips are, as I'm stucked."
]
| [
"sas",
"base"
]
|
[
"click any UIImage and open an UIImageView in objective-c",
"I got this solution on this site: Click an UIImage and open an UIImageView in Objective-c \n\nAdd UITapGestureRecognizer to your UIImageView: \n\nUITapGestureRecognizer *tapRecognizer;\ntapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yourSelector)];\n[thumbnail addGestureRecognizer:tapRecognizer];\n[tapRecognizer release];\n\nthumbnail.userInteractionEnabled = YES; // very important for UIImageView\n\n\nThis is working very fine for single ImageView, but I am adding more than one (about to 20) to my scrollView then How can I differentiate which ImageView will tapped or selected by user. I tried to set my own @selector(imageClicked), but it only returns tag for last imageView.\n\nI am adding addGestureRecognizer in a loop, as I load 20 static images dynamically in an imageView."
]
| [
"iphone",
"objective-c",
"ios",
"uiimageview",
"uitapgesturerecognizer"
]
|
[
"Generics - get value from Class",
"I've a class that converts my jpa entities into TO and vice versa.\n\nWhen i do the conversion in the method convertEntityListInTOList, the List returned is List<Class<T>> and i need that be List<T>.\n\nIs possible iterate over this collection (List<Class<T>>) and get the \"TO\" value?\n\nConverter\n\n public class MyConverter<E, T> implements Serializable {\n\n private Class<E> myEntity;\n private Class<T> myTO;\n\n public MyConverter(Class<E> myEntity, Class<T> myTO) {\n this.myEntity = myEntity;\n this.myTO = myTO;\n }\n\n public List<T> convertEntityListInTOList(List<E> entityList) {\n List<T> listTO = new ArrayList<T>();\n for(E obj : entityList) {\n myTO = convertEntityInTO(obj);\n listTO.add(myTO);\n } \n return listTO;\n }\n\n public List<E> convertTOListInEntityList(List<T> listTOs) {\n List<E> entityList = new ArrayList<E>();\n for(T to : listTOs) {\n myEntity = convertTOInEntity(to);\n entityList.add(myEntity);\n } \n return entityList;\n }\n\n public T convertEntityInTO(Object myEntity) {\n T myTO = createInstanceTO();\n if(myEntity != null) {\n try {\n BeanUtils.copyProperties(myTO, myEntity);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n }\n return myTO;\n }\n\n public E convertTOInEntity(T myTO) {\n E myEntity = createInstanceEntity();\n if(myTO != null) {\n try {\n BeanUtils.copyProperties(myEntity, myTO);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n } \n return myEntity; \n }\n\n/**\n * \n * @return\n */\n public T createInstanceTO() {\n try {\n return getMyTO().newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n /**\n * \n * @return\n */\n public E createInstanceEntity() {\n try {\n return getMyEntity().newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n}\n\n\nConverter producer\n\n@Produces\npublic MyConverter create(InjectionPoint ip) {\n ParameterizedType type = (ParameterizedType) ip.getType();\n Class myEntity = (Class) type.getActualTypeArguments()[0];\n Class myTO = (Class) type.getActualTypeArguments()[1];\n return new MyConverter(myEntity, myTO);\n}"
]
| [
"java",
"generics",
"jpa",
"reflection"
]
|
[
"What is the code generator for computed goto?",
"example of computed goto:\n ...\n GO TO ( 10, 20, 30, 40 ), N\n ... \n10 CONTINUE \n ... \n20 CONTINUE \n ... \n40 CONTINUE \n\nIf N equals one, then go to 10.\nIf N equals two, then go to 20.\nIf N equals three, then go to 30.\nIf N equals four, then go to 40.\nWhat is the code generator of goto in the final state of compiling?"
]
| [
"compilation",
"compiler-construction"
]
|
[
"how to combine / /g and /]+>/gm, with angularJs?",
"how to combine /&nbsp;/g and /<[^>]+>/gm, with angularJs?\nthis is my code:\n\n.filter('htmlToPlaintext',function(){\n return function(text) {\n return text ? String(text).replace(/<[^>]+>/gm, '') : '';\n }\n })"
]
| [
"angularjs"
]
|
[
"Calling SharedPrefences in Fragments",
"I have a class with the name of SharePrefManager. Here is the code\npackage com.example.lms02;\n\npublic class SharedPrefManager {\n\nprivate static final String SHARED_PREF_NAME = \"volleyregisterlogin\";\nprivate static final String KEY_USERNAME = \"keyusername\";\nprivate static final String KEY_EMAIL = \"keyemail\";\nprivate static final String KEY_GENDER = \"keygender\";\nprivate static final String KEY_ID = \"keyid\";\nprivate static final String KEY_STDID = \"keystdid\";\nprivate static final String KEY_USER_STATUS = \"keyuserstatus\";\nprivate static SharedPrefManager mInstance;\nprivate static Context ctx;\n\nprivate SharedPrefManager(Context context) {\n ctx = context;\n}\npublic static synchronized SharedPrefManager getInstance(Context context) {\n if (mInstance == null) {\n mInstance = new SharedPrefManager(context);\n }\n return mInstance;\n}\n\n//this method will store the user data in shared preferences\npublic void userLogin(User user) {\n SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = sharedPreferences.edit();\n editor.putInt(KEY_ID, user.getId());\n editor.putString(KEY_STDID,user.getStdid());\n editor.putString(KEY_USERNAME, user.getName());\n editor.putString(KEY_EMAIL, user.getEmail());\n editor.putString(KEY_GENDER, user.getGender());\n editor.putString(KEY_USER_STATUS, user.getStatus());\n editor.apply();\n}\n\n//this method will checker whether user is already logged in or not\npublic boolean isLoggedIn() {\n SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);\n return sharedPreferences.getString(KEY_USERNAME, null) != null;\n}\n\n//this method will give the logged in user\npublic User getUser() {\n SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);\n return new User(\n sharedPreferences.getInt(KEY_ID, -1),\n sharedPreferences.getString(KEY_STDID, null),\n sharedPreferences.getString(KEY_USERNAME, null),\n sharedPreferences.getString(KEY_EMAIL, null),\n sharedPreferences.getString(KEY_GENDER, null),\n sharedPreferences.getString(KEY_USER_STATUS, null)\n );\n}\n\n//this method will logout the user\npublic void logout() {\n SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = sharedPreferences.edit();\n editor.clear();\n editor.apply();\n ctx.startActivity(new Intent(ctx, LoginActivity.class));\n}\n}\n\n\nI am using Fragments. Here is the code of my Fragment\n\npublic class HomeFragment extends Fragment {\n\nTextView txtvwuserid;\nUser user = SharedPrefManager.getInstance(getContext()).getUser();\npublic HomeFragment() {\n // Required empty public constructor\n}\n\n@Override\npublic void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n}\n\n@Override\npublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n // Inflate the layout for this fragment\n return inflater.inflate(R.layout.fragment_home, container, false);\n}\n\n@Override\npublic void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n txtvwuserid = getActivity().findViewById(R.id.txtvwstdid);\n txtvwuserid.setText(\"Hy\");\n}\n}\n\n\nThe problem occurs in HomeFragment here\n User user = SharedPrefManager.getInstance(getContext()).getUser();\n\nThe Error shown is:\n java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences \n android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference\n\nMy Problem is how can i access the values of SharedPrefManager and what does the error means"
]
| [
"android-studio",
"android-fragments",
"sharedpreferences"
]
|
[
"Why is my method not being called?",
"Why is my method not being called?\n\nMy UIViewController should be calling a method in my UIView called myMethod. \n\nIt only works on the inital UIView viewDidLoad. \n\nAfter the view is loaded, I can't call the \"myMethod\" from someOtherMethod. And I don't understand why? XCode recognizes that the method exists and the method is exposed in my header.\n\nMyViewController.h\n\n#import “MyView.h”\n@interface MyViewController : UIViewController {\n MyView *mv;\n}\n\n\nMyViewContoller.m\n\n#import “MyView.h”\n- (void)viewDidLoad\n{\n mv = [[MyView alloc] initWithFrame:self.view.frame];\n [self.view addSubview:mv];\n\n //THIS WORKS IF CALLED FROM viewDidLoad\n [mv myMethod];\n}\n\n- (void) someOtherMethod {\n\n //THIS DOESN’T WORK IF CALLED LATER\n [mv myMethod];\n}\n\n\nMyView.h\n\n- (void) myMethod;\n\n\nMyView.m\n\n- (void) myMethod {\n NSLog(@\"My Method\");\n}"
]
| [
"uiview",
"methods",
"uiviewcontroller"
]
|
[
"Singleton EJB , JPA Concurrent Access",
"I have a MDB which calls Singleton EJB for maintaining hourlyTotals using JPA. I am getting StaleObjectStateException: Row was updated or deleted by another transaction \n\nEntity Bean Code\n\n@Entity\n@Table(name = \"hour_db\")\npublic class HourlyTotalEntity {\n @Id\n private Date transactionTime;\n\n @Column(name=\"success_count\")\n private long successCount;\n\n @Version int version;\n\n\n public Date getTransactionTime() {\n return transactionTime;\n }\n\n public void setTransactionTime(Date transactionTime) {\n this.transactionTime = transactionTime;\n }\n\n public void setSuccessCount(long successCount)\n {\n this.successCount = successCount;\n }\n public long getSuccessCount()\n {\n return successCount;\n }\n\n public int getVersion() {\n return version;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n}\n\n\nEJB Code\n\n@Singleton\n@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)\n@Lock(LockType.READ)\npublic class HourlyTotalEJB {\n @PersistenceContext (unitName=\"DashboardJPA\")\n private EntityManager em;\n\n public void create(Date transactionTime) throws Exception\n {\n transactionTime = trim(transactionTime);\n HourlyTotalEntity entity = em.find(HourlyTotalEntity.class, transactionTime,LockModeType.OPTIMISTIC_FORCE_INCREMENT);\n if(entity == null)\n {\n entity = new HourlyTotalEntity();\n entity.setTransactionTime(transaction);\n entity.setSuccessCount(0);\n }\n\n entity.setAuthSuccessCount(entity.getAuthSuccessCount() + 1);\n em.persist(entity);\n em.flush();\n em.clear();\n }\n\n private Date trim(Date date) \n {\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.set(Calendar.MINUTE, 0);\n calendar.set(Calendar.MILLISECOND, 0);\n calendar.set(Calendar.SECOND, 0);\n return calendar.getTime();\n }\n}\n\n\nThe MDB call the create(transactionTime) on onMessage(Message message) method. During high volume of transcations the method create(transcationTime) will be called concurrently by MDBs and results in StaleObjectStateException: Row was updated or deleted by another transaction\n\nHow to resolve the above issue?"
]
| [
"jpa",
"singleton",
"ejb"
]
|
[
"Pandas Nth last row slice",
"I'm looking to slice a number of dataframes to obtain the (lets say) 5th last row of data from each df. Each of the df have varying lengths, depending of the duration sample data is taken. For example, of df is 264 rows, another is 237.\nI currently can see a way to get a result using a two step process whereby the first step obtains the tail, and then I can extract the first row from there, but I figure there is likely to be a better way.\nMy current first step is df = data.iloc[-5:,2:128:2] and then I can simply remove the first row from there to give me the aggregate for the data I'm after. Any suggestions?"
]
| [
"python",
"pandas"
]
|
[
"Is there a way to retrieve a list of document IDs from a collection in Firestore?",
"I've been researching efficient ways to retrieve data and one way is to set up what's basically a batch read (not sure if this is possible) from a list of document IDs.\n\nI can probably store the document IDs in a field with an array, but curious if getting the list of document IDs (not all of the data within them) is possible in the Javascript library. I see it's possible with the REST API but so far I'm just using the client SDK so not sure I want to get started adding that.\n\nFor reference: https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents/list"
]
| [
"google-cloud-firestore"
]
|
[
"AWS textract - UnsupportedDocumentException",
"While implementing aws textract using boto3 for python.\n\nCode:\n\nimport boto3\n\n# Document\ndocumentName = \"/home/niranjan/IdeaProjects/amazon-forecast-samples/notebooks/basic/Tutorial/cert.pdf\"\n\n# Read document content\nwith open(documentName, 'rb') as document:\n imageBytes = bytearray(document.read())\n\nprint(type(imageBytes))\n\n# Amazon Textract client\ntextract = boto3.client('textract', region_name='us-west-2')\n\n# Call Amazon Textract\nresponse = textract.detect_document_text(Document={'Bytes': imageBytes})\n\n\nbelow are credential and config files of aws\n\nniranjan@niranjan:~$ cat ~/.aws/credentials\n[default]\naws_access_key_id=my_access_key_id\naws_secret_access_key=my_secret_access_key\n\nniranjan@niranjan:~$ cat ~/.aws/config \n[default]\nregion=eu-west-1\n\n\nI am getting this exception:\n\n---------------------------------------------------------------------------\nUnsupportedDocumentException Traceback (most recent call last)\n<ipython-input-11-f52c10e3f3db> in <module>\n 14 \n 15 # Call Amazon Textract\n---> 16 response = textract.detect_document_text(Document={'Bytes': imageBytes})\n 17 \n 18 #print(response)\n\n~/venv/lib/python3.7/site-packages/botocore/client.py in _api_call(self, *args, **kwargs)\n 314 \"%s() only accepts keyword arguments.\" % py_operation_name)\n 315 # The \"self\" in this scope is referring to the BaseClient.\n--> 316 return self._make_api_call(operation_name, kwargs)\n 317 \n 318 _api_call.__name__ = str(py_operation_name)\n\n~/venv/lib/python3.7/site-packages/botocore/client.py in _make_api_call(self, operation_name, api_params)\n 624 error_code = parsed_response.get(\"Error\", {}).get(\"Code\")\n 625 error_class = self.exceptions.from_code(error_code)\n--> 626 raise error_class(parsed_response, operation_name)\n 627 else:\n 628 return parsed_response\n\nUnsupportedDocumentException: An error occurred (UnsupportedDocumentException) when calling the DetectDocumentText operation: Request has unsupported document format\n\n\nI am bit new to AWS textract, any help would be much appreciated."
]
| [
"amazon-web-services",
"aws-textract"
]
|
[
"Can we have absolute namespace in function definition if return type is an object in C++?",
"Let us consider a function bar declared in namespace foo which returns a std::vector< float > (but also works with other objects).\n\n// header.h\n#include <vector>\n\nnamespace foo\n{\n ::std::vector< float > bar();\n}\n\n\nCompiling its definition using relative namespace works.\n\n#include \"header.h\"\n\n::std::vector< float > foo::bar()\n{\n}\n\n\nHowever, compiling its definition using absolute namespace does not work.\n\n#include \"header.h\"\n\n::std::vector< float > ::foo::bar()\n{\n}\n\n\nReturn error from GCC is\n\nfunction.cpp:3:26: error: ‘foo’ in ‘class std::vector<float>’ does not name a type\n::std::vector< float > ::foo::bar()\n\n\nIt turns out that spaces are allowed in namespacing, so, ::std::vector< float > ::foo::bar() is equivalent to ::std::vector< float >::foo::bar(). How can I use absolute namespace in function definition when return type is an object?"
]
| [
"c++",
"object",
"namespaces",
"return",
"declaration"
]
|
[
"How can I configure IdentityServer4 (DotNet Core) to work in Nginx reverse proxy",
"I've published my API, ID server STS and web ui on separate docker containers and I'm using a nginx container to act as the reverse proxy to serve these app. I can browse to each one of them and even open the discovery endpoint for the STS. Problem comes when I try to login into the web portal, it tries to redirect me back to the STS for logging in but I'm getting ERR_CONNECTION_REFUSED the url looks okay I think it's the STS that is not available from the redirection from the Web UI. \n\nMy docker-compose is as below:\n\nversion: '3.4'\n\nservices:\n reverseproxy:\n container_name: reverseproxy\n image: nginx:alpine\n volumes:\n - ./nginx.conf:/etc/nginx/nginx.conf\n - ./proxy.conf:/etc/nginx/proxy.conf\n - ./cert:/etc/nginx\n ports:\n - 8080:8080\n - 8081:8081\n - 8082:8082\n - 443:443\n restart: always\n links:\n - sts\n sts:\n container_name: sts\n image: idsvrsts:latest\n links:\n - localdb\n expose:\n - \"8080\"\n\n kernel:\n container_name: kernel\n image: kernel_api:latest\n depends_on:\n - localdb\n links:\n - localdb\n\n portal:\n container_name: portal\n image: webportal:latest\n environment:\n - TZ=Europe/Moscow\n depends_on:\n - localdb\n - sts\n - kernel\n - reverseproxy\n\n localdb:\n image: mcr.microsoft.com/mssql/server\n container_name: localdb\n environment:\n - 'MSSQL_SA_PASSWORD=password'\n - 'ACCEPT_EULA=Y'\n - TZ=Europe/Moscow\n ports:\n - \"1433:1433\"\n volumes:\n - \"sqldatabasevolume:/var/opt/mssql/data/\"\n\nvolumes:\n sqldata:\n\n\nAnd this is the nginx.config:\n\nworker_processes 1;\n\nevents { worker_connections 1024; }\n\nhttp {\n\n sendfile on;\n upstream docker-sts {\n server sts:8080;\n }\n upstream docker-kernel {\n server kernel:8081;\n }\n upstream docker-portal {\n server portal:8081;\n }\n ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;\n ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n ssl_session_cache shared:SSL:10m;\n ssl_session_timeout 10m;\n ssl_certificate cert.pem;\n ssl_certificate_key key.pem;\n ssl_password_file global.pass;\n proxy_http_version 1.1;\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection keep-alive;\n proxy_cache_bypass $http_upgrade;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Host $server_name;\n proxy_set_header X-Forwarded-Proto $scheme;\n\n server {\n listen 8080;\n listen [::]:8080;\n server_name sts;\n\n location / {\n proxy_pass http://docker-sts;\n # proxy_redirect off;\n }\n }\n\n server {\n listen 8081;\n listen [::]:8081;\n server_name kernel;\n\n location / {\n proxy_pass http://docker-kernel;\n }\n }\n\n server {\n listen 8082;\n listen [::]:8082;\n server_name portal;\n\n location / {\n proxy_pass http://docker-portal;\n }\n }\n}\n\n\nThe web ui redirects to the below url, which works okay if I browse to it using the STS server without nginx.\n\nhttp://localhost/connect/authorize?client_id=myclient.id&redirect_uri=http%3A%2F%2Flocalhost%3A22983%2Fstatic%2Fcallback.html&response_type=id_token%20token&scope=openid%20profile%20kernel.api&state=f919149753884cb1b8f2b907265dfb8f&nonce=77806d692a874244bdbb12db5be40735"
]
| [
"docker",
"nginx",
".net-core",
"docker-compose",
"nginx-reverse-proxy"
]
|
[
"Animations are clipped to ViewGroup bounds in Android 4.3 and below?",
"I'm working on a custom ViewGroup which draws some animations in the dispatchDraw() method.\n\nI came across this in my Google search: https://groups.google.com/forum/#!topic/android-developers/dZ0Yxjz3v7o\n\nAnd I have set clipChildren=\"false\" inside my XML to both the parent and the grandparent view of my custom ViewGroup. However, this fixed the clipping of the animations drawing on Android 4.3 and above. Android 4.0 - 4.3 still clips the View animations to its bounds.\n\nAny help would be appreciated."
]
| [
"android",
"animation",
"android-animation",
"viewgroup",
"android-viewgroup"
]
|
[
"ListView onItemClick not called",
"I have a ListView with a custom adapter and list items containing TextView(s) only. The list items have an OnItemClick method set in the onCreate callback method.\n\n templatesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n @Override\n public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n Log.d(DEBUG_TAG, \"templatesListView onClick()\");\n //item is selected from the cursor to get necessary data\n Log.d(DEBUG_TAG, \"ListView count: \" + templatesListView.getCount());\n\n Log.d(DEBUG_TAG, \"messagesCursor count: \" + messagesCursor.getCount());\n\n if (position >= messagesCursor.getCount()) {\n Log.d(DEBUG_TAG, \"Unable to access element \" + position + \", it does not exist in the messagesCursor. Cursor count: \" + messagesCursor.getCount());\n }\n\n messagesCursor.moveToPosition(position);\n final String selectedItemName = messagesCursor.getString(1);\n\n AlertDialog.Builder builder = new AlertDialog.Builder(SendMessageActivity.this);\n builder.setTitle(selectedItemName).setMessage(\"Do you want to use template: \"+selectedItemName+\"?\");\n\n //Use template onClick\n builder.setPositiveButton(\"Use\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dlg, int x) {\n messageEditText.setText(selectedItemName);\n }\n });\n\n //Cancel onClick\n builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dlg, int x) {\n }\n });\n builder.show();\n }\n });\n\n\nThe ListView in the activity layout file is defined as:\n\n <ListView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/templatesListView\"\n android:layout_alignParentRight=\"true\"\n android:clickable=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\"\n android:layout_below=\"@+id/sendButton\" />\n\n\nThe list item is defined in a separate layout file as:\n\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nandroid:orientation=\"vertical\" android:layout_width=\"match_parent\"\nandroid:layout_height=\"match_parent\"\nandroid:weightSum=\"1\">\n\n\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\"\n android:text=\"Medium Text\"\n android:id=\"@+id/name_textView\" />\n\n\n\n\nThe onClick method is called correctly when I run the app on Android 4.4.4, but when I run it on Android 5.1.1 it is not called at all.\n\nThe list item layout has been also created for v21+ separately, please find the code below:\n\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nandroid:orientation=\"vertical\" android:layout_width=\"match_parent\"\nandroid:layout_height=\"match_parent\"\nandroid:weightSum=\"1\">\n\n\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textAppearance=\"?android:attr/textAppearanceLarge\"\n android:text=\"Medium Text\"\n android:id=\"@+id/name_textView\"\n android:singleLine=\"true\"\n android:textColor=\"@color/foreground_material_light\"\n android:theme=\"@android:style/Widget.Material.Light.Button.Borderless\" />\n\n\n\n\nDo you guys know what should I change to make it work on API level 21+ ? Is that a matter of the xml file only (attributes?) or should I change the implementation? Cheers!"
]
| [
"android",
"android-layout",
"listview",
"listitem"
]
|
[
"Shell access to Persistent Volume in Google Cloud",
"I would like to get shell access to the Persistent Volume I created on the Google Cloud Platform. \n\nI tried using Google Cloud Shell for this. But to be able to do that I need to attach the Persistent Volume through the gcloud commands, and the command requires the instance name. But I don't see the instance name of the Google Cloud Shell when I list the instance names (in gcloud). \n\nIs it possible to get shell access over Google Cloud Shell to the persistent disks? If not how can I get access to the Persistent Volume that I created?"
]
| [
"kubernetes",
"google-cloud-platform",
"google-compute-engine"
]
|
[
"Performance orientated message callback solution in c++",
"I am trying to develop a p2p distributed concurrent programming solution in C++. For higher throughput I have observed that \"to and fro\" concurrent and scalable network solution is required as in actor model provided by AKKA. Unfortunately there is no reliable solution for actor model available in C++. libcppa is available but only in Beta quality. Is there any scalable and concurrent solution do same in zeroMQ or Boost.asio etc? Programatically I want to do following very fast and in scalable fashion.\n\nSuppose I have a cluster of N nodes which contain separate set of objects. When a node require a remote object it sends a request and get backs a object as a response. Currently I do it in following manner:\n\nRequest req = Network.request(Node x, objectId id);\nreq.waitforResponse( ); //Implemented through Conc-Hashmap of requests and wait & signal\nObject obj = req.response().getObject();\n// Do sth with object.\n\n\nI don't want to implement last two lines of codes myself. I want it to be done by networking library itself. Best solution will be if I can get \"req\" object in some sort of \"Future\" data structure which will block only on calling getObject(). I think it is a very generic problem and there should be some good open source solution available for it. If not please suggest some more efficient solution other than Concurrent hashmap (C++ Intel threads) based approach. Unfortunately my good amount of googling on it did not pay much."
]
| [
"c++",
"concurrency",
"boost-asio",
"actor",
"zeromq"
]
|
[
"How to console id from JSON objects using reactjs",
"My objective is to get the id's from JSON array like {id: 123456}. but i couldn't able to get in this way. \n\nhere is a some JSON data:\n\n var categoryArray = [\n {id: '1', name: 'Category_1'},\n {id: '2', name: 'Category_2'},\n {id: '3', name: 'Category_3'},\n {id: '4', name: 'Category_4'}\n ];\n\n\nwhen i console res.data then it is showing {id: ......} but when i do res.data.id it is showing as undefined. Can anyone help me in this?"
]
| [
"reactjs"
]
|
[
"find unique items in a set of arrays and remove non-uniques from arrays found",
"Givven an object with Key as an Array (of position) and Value as an Array as well:\n\n// Example Object\n0,2 : [6, 8, 9]\n0,3 : [1, 6, 8]\n0,4 : [6, 8]\n0,5 : [6, 8]\n0,6 : [4, 5, 8, 9]\n0,7 : [5, 8]\n0,8 : [4, 5, 7, 9]\n\n\n(it was created like this:\n\nx = {};\nx[[0,2]] = [6, 8, 9];\nx[[0,3]] = [1, 6, 8];\n...\n\n\nNow, I want to narrow down my object to this, by checking if any number in an Array appears only inside this array, and not in others value's arrays, then eliminating all the other numbers inside the specific array which holds the unique number.(Rule: no duplicated inside a given array, so no need to check that):\n\n// Result Object\n0,2 : [6, 8, 9]\n0,3 : [1]\n0,4 : [6, 8]\n0,5 : [6, 8]\n0,6 : [4, 5, 8, 9] // now 4 becomes also a \"loner\"\n0,7 : [5, 8]\n0,8 : [7]\n\n\nso here in Key [0,3] the Value's array was narrowed down to just [1] because 1 is a unique number not showing up in the other array.\n\nI'm having trouble thinking of an efficient pattern for this..."
]
| [
"javascript"
]
|
[
"When main exits, do goroutines run defer()?",
"If I have a goroutine, can I close a channel I have open on that goroutine using something like this?\n\ndefer(close())\n\nOr are defer statements not run for goroutines when main exits?"
]
| [
"go",
"channel",
"deferred",
"goroutine"
]
|
[
"External link to Google Map direction, back to app does not work",
"Using current user's location and restaurant location (geo-coordinates), user can tap a link to open Google Maps and get direction to the desired place. However when I use the back button of Android, it fails to return to the app, and then app is \"stuck\" within Google maps without the possibility to browse back in the app. How do I solve the problem ? - Working with AngularJS and Ionic.\n\nHere is the hTML: \n\n<ion-list>\n <ion-item ng-controller=\"loadingCtrl\" bindonce ng-repeat= \"restaurant in restaurantList | orderBy: 'distance' \" href=\"#\">\n\n <article class=\"item_frame\">\n <div class=\"marker_left_container\">\n <img class=\"venue_rest_marker\" ng-src=\"{{restaurant.icon}}\"> \n <span class=\"venu_type_text\">{{restaurant.venueType}}</span>\n <span class=\"distance_from_user_rest\"> {{distanceTo(restaurant)}} km</span>\n <span class=\"distance_from_user_rest2\">from current location</span>\n </div>\n <div class=\"restaurant_details_container\">\n <h1 class=\"restaurant_name_inlist\">{{restaurant.Name}}</h1>\n <span class=\"restaurant_detail_inlist2\">{{restaurant.subCuisine}}<br> {{restaurant.subsubCuisine}}</span>\n <span class=\"restaurant_address\">{{restaurant.address}}, <br> </span>\n <span class=\"restaurant_address\">{{restaurant.cp}}, {{restaurant.city}} <br><br></span>\n <span class=\"restaurant_others\">{{restaurant.phoneNumber}}<br> </span>\n <span class=\"restaurant_others\">{{restaurant.website}}<br> <br></span> \n <div class=\"get_dir_container\"><a href=\"https://www.google.com/maps/dir//{{restaurant.lat}},{{restaurant.long}}/\">\n <img src=\"img/get_direction_v3.png\" class=\"get_dir_icon\">\n <span class=\"get_dir_text\">Get direction on Google Maps</span>\n </a></div>\n </div>\n\n </article><!--main article frame 1 --> \n\n </ion-item>\n</ion-list>"
]
| [
"angularjs",
"ionic-framework"
]
|
[
"Launching QWS3270 using python py3270 package and error throws \"WinError 10061 : No conn could be made because the target machine actively refused it\"",
"I am trying to access QWS3270 session via python package using py3270 from jupyter notebook\nfrom py3270 import Emulator em = Emulator(visible=True) em = Emulator() em.connect('3270host.example.com')\nwhile running this above statement getting popup like "windows can not find 'wc3270' Make sure you typed the name correctly and try again: and below error follows in Jupyter notebook\n"WinError 10061 : No connection could be made because the target machine actively refused it"\nIn my system QWS3270 secure software installed and path is configured in system environment variables too.\n1.How to launch QWS3270 application using code ?\n2.Should i provide port number along with hostname too?\n3.Does py3270 package work for QWS3270s or not and want to know the difference between wc3270 and QWS3270 ..Hope your help is appreciated. Thanks"
]
| [
"python",
"automation"
]
|
[
"Recycle a vector of characters in negative and positive direction",
"I have vector of characters, letters and symbols:\n\nvec <-c(letters, 0:9, LETTERS, c(\"!\",\"§\",\"$\",\"%\",\"&\"))\n\n\nI would like to build a function recycle that can recycle the vector vec so that recycle(vec, 68) would be similar to vec[68] (an 'a') and recycle(vec, -1) would give an '&'."
]
| [
"r",
"vector"
]
|
[
"Changing reference cell in a function",
"So, this is my formula: =IF(E137=\"013\";C105+1;\"\")\n\nI want to change C105 cell to cell when the \"if\" formula is true for the first time and later over and over again. Basically make C105 a variable. Is there a way without using VBA? \n\n\n\nThanks!"
]
| [
"excel-formula"
]
|
[
"Random Forest Error in na.fail.default: missing values in object",
"I am running an RF model, which runs with no errors with most variables; however, when I include one variable: duration_in_program, and the following code:\n\n```{r Random Forest Model}\n## Run a Random Forest model\nmod_rf <-\n train(left_school ~ job_title \n + gender + \n + marital_status + age_at_enrollment + monthly_wage + educational_qualification + cityD + educational_qualification + cityC.\n + cityB +cityA + duration_in_program, # Equation (outcome and everything else)\n data=train_data, # Training data \n method = \"ranger\", # random forest (ranger is much faster than rf)\n metric = \"ROC\", # area under the curve\n trControl = control_conditions,\n tuneGrid = tune_mtry\n )\nmod_rf\n\n\nI get the following error:\n\nError in na.fail.default(list(left_welfare = c(1L, 2L, 2L, 2L, 2L, 2L, : missing values in object"
]
| [
"machine-learning",
"random-forest",
"r-caret",
"feature-selection"
]
|
[
"Count the number of elements in a string separated by comma",
"I am dealing with text strings such as the following:\nLN1 2DW, DN21 5BJ, DN21 5BL, ...\n\nIn Python, how can I count the number of elements between commas? Each element can be made of 6, 7, or 8 characters, and in my example there are 3 elements shown. The separator is always a comma.\n\nI have never done anything related to text mining so this would be a start for me."
]
| [
"python",
"text",
"text-mining",
"comma"
]
|
[
"Notify/Wait Issue When Using Two Threads To Sequentially Call Two Different Functions",
"I'm having an issue synchronizing functions on the same object. In my main class, I have a button that when pressed, should fire two functions sequentially from a different class. The first thread runs fine. I'm thinking the second is getting caught in a deadlock, but idk how. However, when I specify a timeout for the second thread, it fires. Can somebody help me understand what's going on with the notify/wait?\n\npublic void actionPerformed(ActionEvent ae)\n {\n t = new Thread () \n {\n public void run ()\n {\n synchronized(this)\n {\n one();\n notify();\n }\n }\n };\n thr = new Thread () \n {\n public void run ()\n {\n synchronized (this)\n {\n try\n {\n wait();\n two();\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n }\n };\n thr.start();\n t.start();\n }"
]
| [
"java",
"multithreading",
"synchronization"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.