texts
sequence | tags
sequence |
---|---|
[
"How to get commits from another user in git and apply on top of mine?",
"I have 2 users in git working from a common repository but then making separate changes in their own local machine.\n\nUser 1 : --- Commit 1 --> Commit 2 --> Commit 3\n\nUser 2 : --- Commit 1a ---> Commit 2b --> Commit 3b\n\nIf I am user 2, How do I apply all of User 1's commits on top of my commits and bring my copy up to date ?"
] | [
"git",
"github"
] |
[
"Question about OpenMP sections and critical",
"I am trying to make a fast parallel loop. In each iteration of the loop, I build an array which is costly so I want it distributed over many threads. After the array is built, I use it to update a matrix. Here it gets tricky because the matrix is common to all threads so only 1 thread can modify parts of the matrix at one time, but when I work on the matrix, it turns out I can distribute that work too since I can work on different parts of the matrix at the same time.\n\nHere is what I currently am doing:\n\n#pragma omp parallel for\nfor (i = 0; i < n; ++i)\n{\n ... build array bi ...\n #pragma omp critical\n {\n update_matrix(A, bi)\n }\n}\n\n...\n\nsubroutine update_matrix(A, b)\n{\n printf(\"id0 = %d\\n\", omp_get_thread_num());\n #pragma omp parallel sections\n {\n #pragma omp section\n {\n printf(\"id1 = %d\\n\", omp_get_thread_num());\n modify columns 1 to j of A using b\n }\n\n #pragma omp section\n {\n printf(\"id2 = %d\\n\", omp_get_thread_num());\n modify columns j+1 to k of A using b\n }\n }\n}\n\n\nThe problem is that the two different sections of the update_matrix() routine are not being parallelized. The output I get looks like this:\n\nid0 = 19\nid1 = 0\nid2 = 0\nid0 = 5\nid1 = 0\nid2 = 0\n...\n\n\nSo the two sections are being executed by the same thread (0). I tried removing the #pragma omp critical in the main loop but it gives the same result. Does anyone know what I'm doing wrong?"
] | [
"parallel-processing",
"openmp"
] |
[
"C# class serialization mapping",
"I'm looking for hints, ideas on how to implement and/or change class serialization behavior of following classes in general.\n\nSimplified (incomplete) sample classes :\n\n[Serializable]\npublic class Choobakka\n{\n public string Name { get; set; }\n public VariableList<Item> Stuff { get; set; }\n}\n[Serializable]\npublic class Item\n{\n public string Name { get; set; }\n public string Value { get; set; }\n}\n[Serializable]\npublic sealed class VariableList<T> : AVariableList<T>\n{\n public new ItemList<T> Items { get { return _items; } set { _items = value; } }\n public new bool IsNull { get { return Items == null; } }\n public new bool IsEmpty { get { return IsNull || Count <= 0; } }\n public new int Count { get { return IsNull ? 0 : this.Items.Count; } }\n public new string CountAsString { get { return Count.ToString(); } }\n public VariableList()\n {\n _items = new ItemList<T>();\n }\n}\n\n\nAnd this is how I fill-in and serialize Choobakka's stuff\n\nvar choobakka = new Choobakka() { Name = \"CHOO-BAKKA\", Stuff = new VariableList<Item>() }; \nchoobakka.Stuff.Items.Add( new Item() { Name = \"passport\", Value = \"lv\" } );\nchoobakka.Stuff.Items.Add( new Item() { Name = \"wallet\", Value = \"50euro\" } );\nStringBuilder sb = new StringBuilder();\nusing (TextWriter tw = new StringWriter(sb))\n{\n XmlSerializer xs = new XmlSerializer(typeof(Choobakka));\n xs.Serialize(tw, choobakka);\n}\n\n\nSerialized XML looks like:\n\n<Choobakka>\n <Name>CHOO-BAKKA</Name>\n <Stuff>\n <Items>\n <Item>\n <Name>passport</Name>\n <Value>lv</Value>\n </Item>\n <Item>\n <Name>wallet</Name>\n <Value>50euro</Value>\n </Item>\n </Items>\n </Stuff>\n</Choobakka>\n\n\nNow the question is how would you suggest to get rig of <Items> tag (if possible) to something like \n\n<Choobakka>\n <Name>CHOO-BAKKA</Name>\n <Stuff>\n <Item>\n <Name>passport</Name>\n <Value>lv</Value>\n </Item>\n <Item>\n <Name>wallet</Name>\n <Value>50euro</Value>\n </Item>\n </Stuff>\n</Choobakka>\n\n\nHaving said that I cannot change the structure of VariableList<T> class, except applying some XML serialization attributes.\n\nThe reason for this is not just simplifying the resulting XML, but also desearializing XML generated by SQL Server queries. I have thoughts of attributes, xsd/xslt transformations..."
] | [
"c#",
"xml",
"xslt",
"serialization",
"xsd"
] |
[
"where to find Microsoft.SqlServer.Dts.Pipeline",
"I'm opening a 2005 SSIS pakage and also an old C# project..both are in this solution here. I'm missing namespaces and I can't find the assemblies to add back to my references folder for my C# Project\n\nMicrosoft.SqlServer.Dts.Pipeline\n\nfor example is not one I find in the list of references in the .NET references tab. So how the hell do I get these SQL Server assemblies? Do I have to install the SQL Server 2008 sdk?\n\nLost."
] | [
"sql-server",
"visual-studio-2010",
"ssis"
] |
[
"Better way to extract duration list from datetime list",
"I have a list of datetimes. I want to convert this into a list where the durations are shown between the datetimes. The following code works fine, however if I look at it it seems overkill. First I convert the list to a numpy array, then I create the dureation array and convert it back into a list of seconds. I come across this many times, therefore it would be great if somebody tells me what the most efficient way would be to do this. \n\nimport datetime;\nfrom numpy import *\n\ntimes = [datetime.datetime(2014, 6, 23, 18, 56, 30),\n datetime.datetime(2014, 6, 23, 18, 57),\n datetime.datetime(2014, 6, 23, 18, 57, 30),\n datetime.datetime(2014, 6, 23, 18, 58),\n datetime.datetime(2014, 6, 23, 18, 58, 30),\n datetime.datetime(2014, 6, 23, 18, 59),\n datetime.datetime(2014, 6, 23, 18, 59, 30)]\n\nseconds = array(times)\nstart = times[0]\nduration = seconds - start\n\nsecs = [];\nfor item in duration:\n secs.append(item.seconds);\n\n# result: secs = [0, 30, 60, 90, 120, 150, 180]"
] | [
"python",
"list",
"numpy"
] |
[
"Create a pipeline view in jquery or bootstrap",
"I want to create a view similar to this: https://www.pipedrive.com/en/features/see-your-sales-pipeline\n\nwhere a user can drag and drop a task from one side to another. JIRA also provides a similar view.\n\nCan somebody please suggest a plugin of jquery or bootstrap which can be used in this case (preferably with django)?"
] | [
"jquery",
"django",
"twitter-bootstrap"
] |
[
"Angular bindins - property is visible in template but undefined in controller function",
"I want to Google Maps API in my Angular app. I am using ngMapAutocomplete (https://github.com/iazi/ngMapAutocomplete). I have problem with binding properties from ngMapAutocomplete to my controller. Here is my code.\n\nPug template:\n\n form(name='venueForm', ng-submit=\"vm.submit(venueForm)\", novalidate)\n md-toolbar\n .md-toolbar-tools\n h2(translate=\"VENUE.TITLE\")\n span(flex='')\n md-button.md-icon-button(ng-click='vm.cancel()')\n md-icon(md-svg-icon='mdi:close', aria-label='Close dialog')\n\n md-dialog-content(layout-padding)\n .md-dialog-content.venue-form-content\n span {{vm.nameDetails}}\n div(layout=\"row\")\n md-input-container\n label(translate='VENUE.FORM.NAME')\n input(required, type='text', ng-model='vm.venue.name',\n ng-map-autocomplete, options=\"{}\"\n details=\"vm.nameDetails\", maps-input-change,\n placeholder=\"Zadejte název venue\")\n\n md-dialog-actions(layout='row')\n span(flex='')\n md-button.md-raised(translate=\"BUTTONS.CANCEL\", ng-click=\"vm.cancel()\",\n aria-label='Cancel')\n md-button.md-raised.md-primary(type=\"submit\", translate=\"BUTTONS.SAVE\",\n ng-click=\"vm.save()\", aria-label='Save venue')\n\n\nJS code:\n\n function VenueFormController($scope) {\n this.$onInit = function () {\n this.nameDetails = {};\n this.cityDetails = {};\n this.addressDetails = {};\n this.cityOptions = {\n types: '(cities)',\n };\n this.addressOptions = {\n types: 'address',\n };\n };\n\n $scope.$on('GOOGLE_MAPS_AUTOCOMPLETE', function () {\n console.log(this);\n console.log(this.nameDetails);\n }.bind(this));\n\n this.cancel = function() {\n this.onCancel();\n };\n\n this.submit = function(form) {\n console.log(this.nameDetails);\n if (form.$invalid) {\n return;\n }\n\n this.onSave(this.selectedVenue);\n };\n\n }\n\n\n\n\n angular.module('gugCZ.webAdmin.venue.form', [\n 'hc.marked',\n 'ngMapAutocomplete',\n 'gugCZ.webAdmin.events.form.orgs',\n 'gugCZ.webAdmin.events.form.dates',\n 'gugCZ.webAdmin.events.form.venue'\n ])\n .component('venueForm', {\n controller: VenueFormController,\n controllerAs: 'vm',\n bindings: {\n venue: '=',\n onCancel: '&',\n onSave: '&'\n },\n templateUrl: 'app/venue/form/form.html'\n\n })\n .directive('mapsInputChange', function() {\n return {\n restrict: 'A',\n link: function ($scope, element) {\n element.bind('change', () => {\n $scope.$emit('GOOGLE_MAPS_AUTOCOMPLETE', \n {details: element.details, value: element.value});\n });\n }\n };\n });\n\n\nI have to use custom directive which takes care about changes. Angular ng-change didn't work for some reason. In $scope.$on I have two console logs. First prints all properties of controller with nameDetails and its values. But the second ones prints undefined. And if I tried to put nameDetails to template, object with properties is shown. I added console.log(this.nameDetails) on button click and object with properties is shown. What am I doing wrong? I looked to ng-autocomplete-source code and I found this in bindings: details: '=?'. Isn't that a problem?"
] | [
"javascript",
"angularjs",
"google-maps",
"ecmascript-6"
] |
[
"How to line tables up nicely in html/css on a webpage",
"I'm having problem aligning my tables the same on one page: http://sites.northwestern.edu/mrsec/people/faculty/\nThe first table is the long row of people, but then I made another table, and it shifted to the right a little and the table after that shifted to th right. I want the tables to be aligned the same, have one directly underneath the other without any indentation.\n\nHere is my code for the table and it's the same for each table minus changes in urls. \n\n<table style=\"border: 1px solid #ffffff;\" margin-left:-20px; border=\"0\" \n width=\"400\" cellspacing=\"0\" cellpadding=\"0\"> \n <tbody> <tr> \n <td style=\"border:none\"> <a href=\"\"> <img src=\"\" alt=\"\" /> </a> \n </td> \n <td style=\"border: 1px solid #ffffff;text-align:left;vertical- \n align:middle;margin-left:-10px\"> <a href=\"\" target=\"_blank\"> Gabriela \n Gonzalez Aviles</a> | <em>Physics</em></td> </tr> </tbody> </table>"
] | [
"html",
"css",
"wordpress",
"html-table"
] |
[
"Find End of Current Billing Period",
"I've found an answer to this based on quarters but need to extend it to other billing periods. I've been going in circles and can't find a way out!\n\nI'm writing a C# console app working with Dynamics 365 (Online) but I suppose it's more a maths question.\n\nI have a company that has a renewal day set in the future, e.g. 01/02/2018 (1st Feb).\n\nThe billing period for a new order could be monthly, quarterly, biannual or annual.\nI need to calculate the date of the end of the current billing period working backwards from the renewal date.\n\nHere is what I have so far\n\nDateTime contractRenewal = new DateTime(2018, 02, 01);\nint MonthsInBillPeriod = getBillingPeriod() //returns 1 for monthly, 3 for quarterly etc.\nint currQuarter = (DateTime.Now.Month - contractRenewal.Month) / MonthsInBillPeriod + 1;\nint month = currQuarter * MonthsInBillPeriod + contractRenewal.Month;\nwhile (month > 12)\n month = month - MonthsInBillPeriod;\nrenewal = new DateTime(DateTime.Now.AddMonths(month).Year, month, 1).AddDays(-1); //should return 30/09/2017 for monthly. 31/10/2017 for quarterly. 31/01/2018 for biannual and annual given contractRenewal date"
] | [
"c#",
"datetime",
"date-arithmetic"
] |
[
"Receiving \"Query was empty\" error when loading log visitor collection in Magento",
"How does one retrieve a collection of visitors using the Log/Visitor model? I've tried using the following code....\n\n<?php \nerror_reporting(E_ALL);\nini_set('display_errors',TRUE);\n$root = $_SERVER['DOCUMENT_ROOT'];\nrequire_once $root.'/app/Mage.php';\nMage::app('default');\n\n$visitors = Mage::getModel('log/visitor')->getCollection()->load();\n?>\n\n\nBut it returns an error, an excerpt from which is...\n\nSQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty\n\n\nThe query doesn't throw any errors until I add the 'load()' method to the chain. My question is similar to magento visitor logs, but that code example was missing the load() and the only answer resorted to using the resource model directly, which I don't think should be necessary.\n\nUpdate:\n\nMagento version being used is 1.4.1.1. Full exception trace:\n\nFatal error: Uncaught exception 'Zend_Db_Statement_Exception' with message 'SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty' in /home/dev_fluid/public_html/lib/Zend/Db/Statement/Pdo.php:234 Stack trace: #0 /home/dev_fluid/public_html/lib/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array) #1 /home/dev_fluid/public_html/lib/Zend/Db/Adapter/Abstract.php(468): Zend_Db_Statement->execute(Array) #2 /home/dev_fluid/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('', Array) #3 /home/dev_fluid/public_html/lib/Varien/Db/Adapter/Pdo/Mysql.php(333): Zend_Db_Adapter_Pdo_Abstract->query('', Array) #4 /home/dev_fluid/public_html/lib/Zend/Db/Adapter/Abstract.php(706): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select), Array) #5 /home/dev_fluid/public_html/lib/Varien/Data/Collection/Db.php(707): Zend_Db_Adapter_Abstract->fetchAll(Object(Varien_Db_Select), Array) #6 /home/dev_fluid/public_html/lib/Varien/Data/Collection/Db.php(620): Varien_Data_Collect in /home/dev_fluid/public_html/lib/Zend/Db/Statement/Pdo.php on line 234\n\nNew trace, using's Jurgen's getTraceAsString() approach:\n\n#0 /home/dev_fluid/public_html/lib/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array) \n#1 /home/dev_fluid/public_html/lib/Zend/Db/Adapter/Abstract.php(468): Zend_Db_Statement->execute(Array) \n#2 /home/dev_fluid/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('', Array) \n#3 /home/dev_fluid/public_html/lib/Varien/Db/Adapter/Pdo/Mysql.php(333): Zend_Db_Adapter_Pdo_Abstract->query('', Array) \n#4 /home/dev_fluid/public_html/lib/Zend/Db/Adapter/Abstract.php(706): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select), Array) \n#5 /home/dev_fluid/public_html/lib/Varien/Data/Collection/Db.php(707): Zend_Db_Adapter_Abstract->fetchAll(Object(Varien_Db_Select), Array) \n#6 /home/dev_fluid/public_html/lib/Varien/Data/Collection/Db.php(620): Varien_Data_Collection_Db->_fetchAll(Object(Varien_Db_Select)) \n#7 /home/dev_fluid/public_html/lib/Varien/Data/Collection/Db.php(590): Varien_Data_Collection_Db->getData() \n#8 /home/dev_fluid/public_html/app/code/core/Mage/Log/Model/Mysql4/Visitor/Collection.php(300): Varien_Data_Collection_Db->load(false, false) \n#9 /home/dev_fluid/public_html/andy/visitor.php(11): Mage_Log_Model_Mysql4_Visitor_Collection->load() \n#10 {main}"
] | [
"magento",
"logging",
"collections",
"model",
"visitor"
] |
[
"How can I optimize this expensive (0.5seconds+) binding?",
"Any suggestions on how I can optimize this binding? It will never be set to, but I'm not sure how to convert it to oneWay bindings. What it does is keep track of all the colours that are used in an artwork. Colours can come from text or images (colours in an image are detected serverside, but that happens concurrently and does not affect the timing of this property).\n\ncoloursUsed: function() {\n var colours = new Ember.Set();\n var arts = [this.get('frontArt'), this.get('backArt')];\n arts.forEach(function(art) {\n if(Ember.isNone(art)){\n return;\n }\n if(! Ember.isEmpty(art.get('textArts'))) {\n colours.addEach(art.get('textArts').mapBy('colour')); \n colours.addEach(art.get('textArts').mapBy('strokeColour'));\n }\n if(! Ember.isEmpty(art.get('imageArts'))) {\n var img_colours = art.get('imageArts').mapBy('colours');\n img_colours.forEach(function(img_colour_array){\n colours.addEach(img_colour_array); \n })\n }\n });\n return colours.toArray();\n}.property('[email protected]', '[email protected]',\n '[email protected]', '[email protected]',\n '[email protected]', '[email protected]'),"
] | [
"binding",
"properties",
"ember.js"
] |
[
"Is it possible to calculate LUB on type level?",
"I need to get least upper bound of two types given as parameters. Something like that:\n\nclass Holder[T] {\n type Shrink[S] = ???\n}\n\n\nwhere ??? generates some type expression that produces least upper bound for the T and S types. Something that looks like LUB_Magic[T,S].\n\nI tried many things but couldn't find any way to express it.\n\nFor example, if types A and B predefined then\n\nfinal case class Solve() {\n val query = (x : Any) => x match {\n case a : A => a\n case b : B => b\n }\n type Q = query.type\n}\n\n\nwould produce type based on the least upper bound.\n\nBut if I try to parametrize it like class Solve[A,B]() then the type would be Any instead of the least upper bound. Same goes with the gist solution\n\nIs it ever possible to get least upper bound on type level?"
] | [
"scala",
"types"
] |
[
"Time to live for a Mule message whilst in a VM queue",
"Is it possible for a Mule message to expire (i.e. the container will discard the message) after a configured amount of time (like the JMS TTL property)?\nIf there is please can you point me to the documentation or example?\n\nCan we use the attribute queueTimeout (see http://www.mulesoft.org/documentation/display/current/VM+Transport+Reference) to achieve this? \n\nCheers"
] | [
"mule",
"mule-cluster"
] |
[
"How can i get last letter from edit text and put it in adapter",
"I have a delete button which deletes text in an EditText, and the value of the EditText is the item clicked in a RecyclerView. Now when I delete text from edit text it disappears from the adapter. Now how can I return it back to adapter after clicking on delete? \n\n@Override\npublic void onItemClick(View view, int position) {\n edit.setText(edit.getText() + adapter.getItem(position).toString().toUpperCase());\n edit.toString().toUpperCase();\n\n MediaPlayer mediaPlayer2=MediaPlayer.create(Ridles.this,R.raw.zagonetkebutonklik);\n mediaPlayer2.start();\n suggestSource.remove(adapter.getItem(position));\n\n simpleArray = new String[suggestSource.size()];\n suggestSource.toArray(simpleArray);\n recyclerView = findViewById(R.id.recyclerView);\n int numberOfColumns = 5;\n recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));\n adapter = new MyRecyclerViewAdapter(this, simpleArray);\n adapter.setClickListener(this);\n recyclerView.setAdapter(adapter);\n adapter.notifyItemRemoved(position);\n adapter.notifyItemChanged(position);\n adapter.notifyItemRangeChanged(position,suggestSource.size());\n lvl.setText(\"lvl: \" +String.valueOf(curquestion));\n\n}\npublic void obrisi(){\n String text=edit.getText().toString();\n if(text.length()>=1){\n edit.setText((text.substring(0, text.length() - 1)));\n edit.setVisibility(View.VISIBLE);"
] | [
"android",
"android-edittext",
"android-arrayadapter"
] |
[
"PHP Multidimensional Array Length",
"This is a multidimensional PHP array. \n\n$stdnt = array(\n array(\"Arafat\", 12210261, 2.91),\n array(\"Rafat\", 12210262, 2.92),\n array(\"Marlin\", 12210263, 2.93),\n array(\"Aziz\", 12210264, 2.94),\n);\n\n\nI can find out the length of the array. That means\n\ncount($stdnt); // output is 4\n\n[\n array(\"Arafat\", 12210261, 2.91),\n array(\"Rafat\", 12210262, 2.92),\n array(\"Marlin\", 12210263, 2.93),\n array(\"Aziz\", 12210264, 2.94)\n] ` \n\n\nBut can't get the internal array length.\n\nHow can I ?"
] | [
"php",
"arrays"
] |
[
"Having issues using the cURL libraries for Dev-C++ in Windows 7",
"I reciently installed the cURL libraries in Dev-C++ using the Packman.exe which is included in the Dev-C++ install. When I try to use #include <curl/curl.h> I do not get an error, so I am assuming that it installed correctly. However, when I try and compile an example from the cURL website, I get the following errors:\n\n[Linker error] undefined reference to _imp__curl_easy_init\n[Linker error] undefined reference to _imp__curl_easy_setopt\n[Linker error] undefined reference to _imp__curl_easy_perform\n[Linker error] undefined reference to _imp__curl_easy_cleanup\n\n\nThe source code I am using is as follows:\n\n#include <stdio.h>\n#include <curl/curl.h>\nint main(void)\n{\n CURL *curl;\n CURLcode res;\n curl = curl_easy_init();\n if(curl) {\n curl_easy_setopt(curl, CURLOPT_URL, \"http://example.com\");\n res = curl_easy_perform(curl);\n curl_easy_cleanup(curl);\n }\n return 0;\n}\n\n\nThank you! :)"
] | [
"c++",
"curl",
"libcurl",
"dev-c++"
] |
[
"MySQL transactions vs locking",
"Quick question/clarification required here. I have a DB table that will quite possibly have simultaneous updates to a record. I am using Zend Framework for the application, and I have read about two directions to go to avoid this, first being table locking (LOCK TABLES test WRITE) or something like that, will go back and re-read how to do it exactly if that is the best solution. The second being transactions: $db->beginTransaction(); ... $db->commit();\n\nNow 'assuming' I am using a transactional storage engine such as InnoDB, transactions seem like the more common solution. However does that avoid the following scenario:\n\nUser A is on a webpage -> submits data -> begin transaction -> read row -> calculate new value -> update row -> save -> commit\n\nUser B is on the same webpage at the same time and submits data at the same time, now lets just say it is almost simultaneous (User B calls the update function at a point between begin transaction and commit for User A's transaction) User B relies on the committed data from User A's transaction before it can achieve the accurate calculation for updating the record.\n\nIE: \n\n\n Opening value in database row : 5 User A submits a value of 5. (begin\n transaction -> read value (5) -> add submitted value (5+5=10) -> write\n the updated value -> save -> commit)\n \n User B submits the value of 7. I need to make sure that the value of\n User B's transaction read is 10, and not 5 (if the update isn't done\n before read).\n\n\nI know this is a long winded explanation, I apologize, I am not exactly sure of the correct terminology to simplify the question.\n\nThanks"
] | [
"mysql",
"zend-framework",
"transactions",
"rowlocking"
] |
[
"NSView -dataWithPDFInsideRect: and layer borders",
"I'm using -dataWithPDFInsideRect: with an NSView that has many subviews. It works fine but doesn't render any of the subview's layer properties like borders. Is there a way to get that to work?"
] | [
"objective-c",
"nsview"
] |
[
"Modules I've installed with pip and conda are not importable in Sublime or Atom, but can be imported using Jupyter Notebook (and sometimes Terminal)",
"The problem:\nWhen I run the following code using Atom or Sublime:\n\nimport quandl\ndf = quandl.get('WIKI/GOOGL')\nprint(df)\n\n\nI get the following error:\n\nTraceback (most recent call last):\nFile \"/Users/patrick/Desktop/Untitled.py\", line 1, in <module>\nimport quandl\nImportError: No module named quandl\n[Finished in 0.3s with exit code 1]\n[shell_cmd: python -u \"/Users/patrick/Desktop/Untitled.py\"]\n[dir: /Users/patrick/Desktop]\n[path: /Library/Frameworks/Python.framework/Versions/3.7/bin:/anaconda3/bin:/anaconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]\n\n\n*I removed my last name wherever it appeared in the output.\nYet when I run that same code in Terminal (the file is named Untitled.py) via the following code: \n\n$ cd Desktop\n$ python Untitled.py\n\n\nI get a data frame printed (as desired), so quandl was apparently imported. Another potentially helpful fact is that when I tried to install nibabel via pip install nibabel, it seemed to install. But when I wrote a program that simply said import nibabel it was not importable using Terminal or Sublime. Here's the error code in Terminal:\n\nTraceback (most recent call last):\n File \"Untitled.py\", line 1, in <module>\n import nibabel\nModuleNotFoundError: No module named 'nibabel'\n\n\nAnd here was the error code in Sublime (last name removed):\n\nTraceback (most recent call last):\n File \"/Users/patrick/Desktop/Untitled.py\", line 1, in <module>\n import nibabel\nImportError: No module named nibabel\n[Finished in 0.3s with exit code 1]\n[shell_cmd: python -u \"/Users/patrick/Desktop/Untitled.py\"]\n[dir: /Users/patrick/Desktop]\n[path: /Library/Frameworks/Python.framework/Versions/3.7/bin:/anaconda3/bin:/anaconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]\n\n\nHowever, when I opened up Anaconda Navigator, selected Jupyter Notebook, and then ran the same code In [1]: import nibabel it worked and didn't throw any errors.\n\nIn summary, importing quandl with pip and conda allowed me to use Jupyter Notebook and Terminal but not Atom or Sublime. However, importing nibabel with pip only (it's not available from conda) allowed me to import it in Jupyter Notebook, but not Terminal, Atom, or Sublime.\n\nForum posts that seem relevant & solutions I've tried:\nI found what appears to be a Windows version of my problem, but I wasn't sure how to adapt the solution to the Mac file system. @Biker_Coder (Mani) seemed to think the problem was with the path that python looks for packages in.\nWindows version of my problem\nThere are a few other forum posts with similar looking problems and some people suggested that the problem might be that the author was running two versions of Python. That doesn't sound like my problem because I got started pretty recently with Python and don't think I downloaded two versions of it. In a few other forums, people have had luck changing \"quandl\" to \"Quandl\" or vice versa. This didn't work for me. In fact, I'm pretty sure it has nothing to do with quandl because installing and importing nibabel lead to the same problems.\nTHANKS to everyone who read all this, whether or not you know the solution. \n\n\n\nPotentially Useful System Information:\nThat's the entirety of my question, but here's some additional information in case it's helpful.\nWhen I open IDLE and run >>> import sys and then >>>print(sys.path), I get the following output (again I removed my last name wherever it appeared):\n\n['', '/Users/patrick/Documents', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']\n\n\nWhen I type $ python --version into Terminal, it outputs Python 3.7.2 \nMy computer is running \"MacOS Mojave Version 10.14.2\"."
] | [
"python",
"package",
"anaconda",
"python-idle"
] |
[
"Creating an extension method against a generic interface or as a generic constraint?",
"I'm not really sure if there is any real difference here in the two signatures:\n\npublic static class MyCustomExtensions\n{\n public static bool IsFoo(this IComparable<T> value, T other)\n where T : IComparable<T>\n {\n // ...\n }\n\n public static bool IsFoo(this T value, T other)\n where T : IComparable<T>\n {\n // ...\n }\n}\n\n\n\n\nI think these will essentially operate almost identically, but I'm not quite sure... what am I overlooking here?"
] | [
"c#",
"generics",
"interface",
"extension-methods",
"generic-constraints"
] |
[
"SwiftUI how to delete from ForEach by ID, not index",
"The following code makes me uncomfortable.\n\nstruct HistoryView: View {\n\n @ObservedObject var history: History\n\n var body: some View {\n List {\n ForEach(history.getSessions()) { sess in\n Text(\"Duration: \\(sess.duration)\")\n }.onDelete(perform: self.onDelete)\n }\n }\n\n private func onDelete(_ indexSet: IndexSet) {\n ...\n }\n}\n\n\nThe problem is that History is a very asynchronous thing. It's a model connected to CloudKit. It could be getting updates in the background. Ideally, if it updates, this View would update immediately and the indexes would still be accurate, but I much prefer to get a set of the identifiers to delete, not set of indexes. Is there a way to do this? Note: those \"history sessions\" conform to Identifiable as required by ForEach, so they all have IDs. In my case they are UUIDs."
] | [
"swiftui"
] |
[
"How can I load a local HTML file into the UIWebView?",
"How can we load our own html file into the UIWebView?"
] | [
"iphone",
"ios",
"uiwebview"
] |
[
"Use of local in Racket/Scheme",
"In Exercise 18.1.12 from htdp, I've re-written the maxi function using \"local\". \n\n;; maxi : non-empty-lon -> number\n;; to determine the largest number on alon\n(define (maxi alon)\n (cond\n [(empty? (rest alon)) (first alon)]\n [else (local ((define m (maxi (rest alon))))\n (cond\n [(> (first alon) m) (first alon)]\n [(> m (first (rest alon))) m]\n [else (first (rest alon))]))]))\n\n\nI'm not sure why I would do this in \"real life\" as it seems the book's version is shorter, clearer and probably faster as well.\n\n(define (maxi alon)\n (cond\n [(empty? (rest alon)) (first alon)]\n [else (cond\n [(> (first alon) (maxi (rest alon))) (first alon)]\n [else (maxi (rest alon))])]))\n\n\nWas it meant to be a purely pedagogical exercise? Could an experienced Schemer comment on the code above? Thank you."
] | [
"scheme",
"racket",
"htdp"
] |
[
"Dynamic ImageView with PNGs and OutOfMemory exception?",
"I know there is plenty of questions already resolved with the same name as mine, but none of them gave me an answer. Here is what I do : \n\nI have a big multidimensionnal array containing items, each with name, image path, and other stuff. I have a ListView listing all these items from that array, using their names, and when we click on one of these, it opens a new Activity showing the details of the item, and the image. It actually works, the image is well scaled, all loaded things match with the user's click, this part is 100% ok. \n\nBut after several clicks, I got OutOfMemory exception. In my previous version of the app, there was no images, and I could click on all the items in a row (almost a hundred items), without any trouble. Now there is images, and out of memory exception. So I assume that images are the problem. Here is how I do to dynamically select an image after a click : \n\nItemArray items = new ItemArray(itemID); //clicked item ID to match with the array\n setContentView(R.layout.activity_show_item);\n ImageView itemImage = (ImageView) findViewById(R.id.itemImageView);\n Resources res = getResources();\n int resID = res.getIdentifier(items.ArrayToPrint[1], \"drawable\", getPackageName()); //ArrayToPrint = the selected lines matching the item, verification is made in the ItemArray class and is working properly\n itemImage.setImageResource(resID);\n\n\nWith this code, the image appears as I want it to. But as I said earlier, I got OutOfMemory exception. I tried several things to flush caches, but none worked, I still got this problem, and don't know how to deal with it. \n\nAny clues ? Thanks in advance !"
] | [
"java",
"android",
"imageview",
"out-of-memory"
] |
[
"Syntax Error on function definition when using emcee",
"I'm trying to use the emcee module to recreate a distribution. Here is my code:\n\nfreq,asd = np.loadtxt('noise.csv',delimiter=',',unpack=True)\n\n\npsd = asd**2\n\nSNRth = 4.5\n\nd = 600\n\ndm = 0.9\n#interpolate!\n\nS = interpolate.interp1d(freq,psd)\n\ndef SNR2(chirp,f): \n return 5*np.pi**(-4/3)*chirp**(5/3)/(96*d**2)*integrate.quad(lambda f: f**(-7/3)/S(f), 20, 1500, limit=1000)[0]\n\ndef mp(SNR2, x):\n return integrate.quad(lambda x: np.exp(-0.5*(x+SNR2))*special.iv(0,np.sqrt(x*SNR2)),0,SNRth**2)\n\ndef pp(SNR2, x):\n return 0.5*np.exp(-0.5*(SNRth**2+SNR2))*special.iv(0,np.sqrt(x*SNR2))\n\ndef mm(SNR2, x):\n return 1-np.exp(-SNRth**2/2)\n\ndef pm(SNR2, x):\n return (1/(2*dm**2))*np.exp(-SNRth**2/2)\n\n#global variables for the sampler\nnwalkers = 500\nndim = 2 \nnmcmc = 500 #number of mcmc steps...make it a factor of 2\n\n#variables for the population\nmupop = 0.4 #mean\nsigpop = 0.1 #standard deviation\n\n#variables for individual events\nNtrig = 37 #number of individual events.\nNnoise = 11\nNsamp = 100 #number of sample points for each individual event\nstdmin = 1e-50 #smallest possible standard deviation\nstdmax = 0.2 #largest possible standard deviation\n\n#enforce uniform prior on the mean and the variance between (0,1)\ndef lnprior(theta):\n mu, sig = theta\n if 0 < mu < 1 and 0 < sig < 1:\n return 0\n return -np.inf\n\n#log likelihood for the population\n#seps are single event posteriors\ndef lnlike(theta,*seps):\n mu, sig= theta\n seps = np.asarray(seps).reshape((Ntrig,Nsamp)) #TODO: find a better way to pass a variable number of arguments to emcee\nreturn np.prod(pp(SNR2(chirp,f),seps)+pm(SNR2(chirp,f),seps))*np.prod(mp(SNR2(chirp,f),seps[:Nnoise])+mm(SNR2(chirp,f),seps[:Nnoise])\n\ndef lnpop(theta,*seps):\n lp = lnprior(theta)\n if not np.isfinite(lp):\n return -np.inf\n seps = np.asarray(seps).reshape((Ntrig,Nsamp)) #TODO: find a better way to pass a variable number of arguments to emcee\n return lp + lnlike(theta,seps)\n\n\nIt gives me a syntax error when I def lnpop. Any Idea what the problem may be? I thought that this was the correct way to define functions....."
] | [
"python",
"numpy",
"scipy",
"emcee"
] |
[
"Core data only storing last object of JSON feed",
"I´m using Core Data as local storage in my app. I´ve set it up properly and made subclasses of NSManagedObject for each entity. However, when I´m trying to insert values into my store, it only inserts the last object from my JSON feed.\n\nres = [JSONHandler requestJSONResponse:jsonString];\nshows = [res valueForKeyPath:@\"Show.Name\"];\nNSUInteger showIndex = 0;\nfor(NSString *showName in shows){\n showObject = [NSEntityDescription insertNewObjectForEntityForName:@\"Show\" inManagedObjectContext:managedObjectContext_];\n showObject.name = showName;\n showObject.iD = [[res valueForKeyPath:@\"Show.Id\"]objectAtIndex:showIndex];\n showObject.desc = [[res valueForKeyPath:@\"Show.Description\"]objectAtIndex:showIndex];\n showObject.activityType = [[res valueForKeyPath:@\"Show.ActivityType\"]objectAtIndex:showIndex];\n\n showIndex++;\n}\n\n\nThis only stores the last object from my JSON feed. Any idea why?\n\nEDIT: It works fine when I do this:\n\nres = [JSONHandler requestJSONResponse:jsonString];\n\nshows = [res valueForKeyPath:@\"Show.Name\"];\n\nNSUInteger index = 0;\n\nfor(NSString *showName in shows){\n show = [NSEntityDescription insertNewObjectForEntityForName:@\"Show\" inManagedObjectContext:managedObjectContext_];\n [show setValue:showName forKey:@\"name\"];\n [show setValue:[[res valueForKeyPath:@\"Show.Id\"]objectAtIndex:index] forKey:@\"iD\"];\n [show setValue:[[res valueForKeyPath:@\"Show.Description\"]objectAtIndex:index] forKey:@\"desc\"];\n [show setValue:[[res valueForKeyPath:@\"Show.ActivityType\"]objectAtIndex:index] forKey:@\"activityType\"];\n\n index++;\n}\n\n\nIt´s basically the same thing, isn´t it? But I want to use subclasses of NSManagedObject instead of doing like I did above. Because in the snippet above show is NSManagedObject *show instead of what it should be: Show *show."
] | [
"iphone",
"objective-c",
"xcode",
"json",
"core-data"
] |
[
"I am not being able to display cartItem data to the recyclerview. how to fix this",
"I want to display cartItem to the recyclerview. The code doesnot throw any error.It goes to the CartActivity class but data is not displayed on recyclerview.\nWhat is wrong with this code?\nThis is my CartActivity\npublic class CartActivity extends AppCompatActivity {\n\n private AppData cartItem;\n private CartAdapter cartAdapter;\n private RecyclerView recyclerView;\n private RecyclerView.LayoutManager layoutManager;\n private Button payBtn;\n private TextView txtTotalAmount;\n private int totalPrice =0;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_cart);\n recyclerView = findViewById(R.id.cart_list);\n recyclerView.setHasFixedSize(true);\n layoutManager = new LinearLayoutManager(this);\n recyclerView.setLayoutManager(layoutManager);\n cartItem = new AppData();\n cartAdapter = new CartAdapter(this,cartItem);\n recyclerView.setAdapter(cartAdapter);\n\n payBtn = findViewById(R.id.pay_btn);\n txtTotalAmount= findViewById(R.id.total_price);\n\n }\n\n @Override\n protected void onStart() {\n super.onStart();\n\n\n }\n \n}\n\nThis is my AppData class where i have defined arraylist\npublic class AppData {\n private ArrayList<Cart> cartItem;\n private static AppData instance = null;\n\n public AppData() {\n cartItem = new ArrayList<>();\n }\n\n public static AppData getInstance(){\n if(instance == null){\n instance = new AppData();\n }\n\n return instance;\n }\n\n public ArrayList<Cart> getCartItem(){\n return cartItem;\n }\n\n public void addItemToCart(Cart cartItem){\n this.cartItem.add(cartItem);\n }\n}\n\nThis is cartAdapter class where i have use the AppData object and passed to the constructor.\npublic class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> implements \nView.OnClickListener{\n private final Context current;\n private final AppData data;\n public ItemClickListner listner;\n\n public void setOnClickListner(ItemClickListner listner){\n this.listner = listner;\n }\n\n public CartAdapter(Context current,AppData data) {\n this.current = current;\n this.data =data;\n notifyDataSetChanged();\n }\n\n\n\n @NonNull\n @Override\n public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout, parent, false);\n return new CartViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(@NonNull CartViewHolder holder, int position) {\n\n holder.txtCartProductName.setText(data.getCartItem().get(holder.getAdapterPosition()).getName());\n holder.TxtCartProductPrice.setText(data.getCartItem().get(holder.getAdapterPosition()).getPrice());\n holder.TxtCartProductQuantity.setText(data.getCartItem().get(holder.getAdapterPosition()).getCount());\n System.out.println("cart name"+data.getCartItem().get(holder.getAdapterPosition()).getName());\n\n }\n\n\n\n @Override\n public int getItemCount() {\n return data.getCartItem().size();\n }\n\n @Override\n public void onClick(View v) {\n\n }\n class CartViewHolder extends RecyclerView.ViewHolder{\n View cartwrapper;\n TextView txtCartProductName,TxtCartProductPrice,TxtCartProductQuantity;\n\n public CartViewHolder(@NonNull View itemView) {\n super(itemView);\n cartwrapper = itemView.findViewById(R.id.cartwrapper);\n txtCartProductName = itemView.findViewById(R.id.cart_product_name);\n TxtCartProductPrice = itemView.findViewById(R.id.cart_product_price);\n TxtCartProductQuantity = itemView.findViewById(R.id.cart_product_quantity);\n }\n }\n\n}"
] | [
"android"
] |
[
"How to signify to the compiler that a function always throws?",
"When calling functions that always throw from a function returning a value, the compiler often warns that not all control paths return a value. Legitimately so.\n\nvoid AlwaysThrows() { throw \"something\"; }\n\nbool foo()\n{\n if (cond)\n AlwaysThrows();\n else\n return true; // Warning C4715 here\n}\n\n\nIs there a way to tell the compiler that AlwaysThrows does what it says?\n\nI'm aware that I can add another throw after the function call:\n\n{ AlwaysThrows(); throw \"dummy\"; }\n\n\nAnd I'm aware that I can disable the warning explicitly. But I was wondering if there is a more elegant solution."
] | [
"c++",
"exception",
"visual-c++"
] |
[
"PHP Curl encoding from arabic",
"I'm tring to get a webpage in arabic and english using curl and php.\n\n<p>الوكالة</p>\n<p>Agency</p>\n\n\nThe result (immediatly after the curl call) is:\n\n<p>???????</p>\n<p>Agency</p>\n\n\nI think it's a multi byte problem but I don't know how fix this problem."
] | [
"php",
"curl",
"character-encoding"
] |
[
"Angular route issue with new created electron-forge project",
"Environment\n\n\nelectron-forge, 5.1.1\nelectron-compile, 6.4.2\nangular, 5.2.9\n\n\nSteps\n\n\nCreated the electron project with forge template. And everything works.\n\n\nnpm install -g electron-forge\nelectron-forge init my-new-project --template=angular2\ncd my-new-project\nnpm start\n\nCreated the angular project with cli in separate folder, and angular is up and running in browser.\nMigrated the angular files under the src folder in electron project.\nAdded angular related denpendencies in electron project, such like @angular/router.\nBy now with these files under src folder, the electron app runs great.\nindex.ts\nindex.html\nbootstrap.ts\napp.component.ts\napp.component.html\napp.component.css\napp.module.ts\nThen I just added these files\n\n\napp-routing.module.ts\nroles\n\n\nroles.module.ts\nroles-routing.module.ts\nroles.component.ts\nroles.component.html\n\n\nUpdate these files\n\n\nindex.html with <base href=\"\"> in the head section.\napp-routing.module.ts with loadChildren property.\nconst routes: Routes = [\n {\n path: 'roles',\n loadChildren: 'roles/roles.module#RolesModule'\n },\n {\n path: '',\n redirectTo: 'roles',\n pathMatch: 'full'\n }\n ];\nroles-routing.module.ts\nconst routes: Routes = [\n {\n path: '',\n component: RolesComponent,\n }\n ];\n\n\n\nAll these changes all working with angular along in the browser but error in electron app.\n\nError: Reference error. System is not defined.\n\nAny help would be appreciated."
] | [
"angular",
"electron"
] |
[
"Change value of TextView on Item Click inside a RecyclerView?",
"I am developing an app for restaurant management, but stuck at a point where i need to update value of textview(outside of RecyclerView) on item click inside the RecyclerView.\n\nThis is my adapter, Consider a textView outside this adapter and set a value on item click of Plus and Minus ImageViews as shown in below code...\n\npublic class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyHolder> {\n\nArrayList<MenuItem> MenuDetailList;\nTypeface font;\n\npublic MyRecyclerAdapter(ArrayList<MenuItem> MenuDetailArray){\n this.MenuDetailList = MenuDetailArray;\n}\n\n@Override\npublic MyRecyclerAdapter.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n\n View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_menu_row_item, null);\n return new MyHolder(v);\n}\n\n@Override\npublic void onBindViewHolder(final MyRecyclerAdapter.MyHolder holder, final int position) {\n\n holder.txtSubMenuTitle.setText(MenuDetailList.get(position).getTitle());\n holder.txtSubMenuPrice.setText(MenuDetailList.get(position).getPrice());\n holder.txtSubMenuCount.setText(\"\"+MenuDetailList.get(position).getItemCount());\n setCustomTypeface(holder.txtSubMenuTitle, font);\n setCustomTypeface(holder.txtSubMenuPrice,font);\n\n holder.ImgViewSubMenuMinus.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n //holder.OrderCount = Integer.parseInt(holder.txtSubMenuCount.getText().toString());\n int ItemCount = MenuDetailList.get(position).getItemCount();\n if (ItemCount > 0) {\n ItemCount = ItemCount - 1;\n holder.txtSubMenuCount.setText(\"\" + ItemCount);\n MenuDetailList.get(position).setItemCount(ItemCount);\n notifyDataSetChanged();\n }\n }\n });\n\n holder.ImgViewSubMenuPlus.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n //holder.OrderCount = Integer.parseInt(holder.txtSubMenuCount.getText().toString());\n\n int ItemCount = MenuDetailList.get(position).getItemCount();\n if (ItemCount < 20) {\n ItemCount = ItemCount + 1;\n holder.txtSubMenuCount.setText(\"\" + ItemCount);\n MenuDetailList.get(position).setItemCount(ItemCount);\n notifyDataSetChanged();\n }\n });\n}\n\n@Override\npublic int getItemCount() {\n return MenuDetailList.size();\n}\n\npublic static class MyHolder extends RecyclerView.ViewHolder {\n TextView txtSubMenuTitle;\n TextView txtSubMenuPrice;\n ImageView ImgViewSubMenuMinus;\n ImageView ImgViewSubMenuPlus;\n TextView txtSubMenuCount;\n\n private MyHolder(View row) {\n super(row);\n this.txtSubMenuTitle = (TextView) row.findViewById(R.id.list_txt_sub_menu_title);\n this.txtSubMenuPrice = (TextView) row.findViewById(R.id.list_txt_sub_menu_price);\n this.txtSubMenuCount = (TextView) row.findViewById(R.id.list_txt_sub_menu_count);\n this.ImgViewSubMenuMinus = (ImageView) row.findViewById(R.id.list_img_sub_menu_minus);\n this.ImgViewSubMenuPlus = (ImageView) row.findViewById(R.id.list_img_sub_menu_plus);\n }\n}\nprivate void setCustomTypeface(TextView textView, Typeface font) {\n textView.setTypeface(font);\n}\n}\n\n\nThanks in advance..."
] | [
"android",
"android-recyclerview",
"android-adapter"
] |
[
"Why showing path instead of icon in table cell",
"I am newbie on java-swing. I am trying to add icon in table cell. but when i add ImageIcon in cell then it's showing only path instead of icon. \n\nHere is my code. \n\n public void createGUI(ArrayList<String> params, String type) {\n\n try {\n DefaultTableModel model = new DefaultTableModel();\n model.addColumn(\"ParameterName\");\n model.addColumn(\"ParameterType\");\n model.addColumn(\"Operation\");\n for (int i = 0; i < params.size() - 4; i++) {\n String param_name = params.get(i).toString().substring(0, params.get(i).toString().indexOf(\"[\"));\n String param_type = params.get(i).toString().substring(params.get(i).toString().indexOf(\"[\") + 1, params.get(i).toString().indexOf(\"]\"));\n //URL url = ClassLoader.getSystemClassLoader().getResource(\"\");\n ImageIcon image = new ImageIcon(\"/com/soastreamer/resources/delete_idle.png\");\n // JLabel label = new JLabel(image);\n model.addRow(new Object[]{param_name, param_type.toUpperCase(),image});\n\n }\n\n\n Action delete = new AbstractAction() {\n\n public void actionPerformed(ActionEvent e) {\n JTable table = (JTable) e.getSource();\n int modelRow = Integer.valueOf(e.getActionCommand());\n ((DefaultTableModel) table.getModel()).removeRow(modelRow);\n }\n };\n\n\nHere is image for clear understanding. \n\n \n\nPlease give me hint or any reference. \nThank you."
] | [
"java",
"swing",
"icons",
"tablecell"
] |
[
"How to store many rows of long strings in mySQL",
"I need to store 100 URL addresses + 100 text labels. I would like to have a default value for both. The problem that I have run into is that I have set the URL fields as VARCHAR, length = 1024 and the text labels as VARCHAR, length = 30. while building my table I've encountered the error, \"Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. You have to change some columns to TEXT or BLOBs\"\n\nHow else might I go about accomplishing my objective? I can't use TEXT b/c it does not allow me to store a default value for that field."
] | [
"php",
"mysql"
] |
[
"SQLite database not getting updated unless I manually uninstall and then install the new apk",
"This is my Database Helper Class : \n\npackage tabswipe;\n\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\n\nimport android.content.Context;\nimport android.database.SQLException;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport android.util.Log;\n\npublic class ExternalDbOpenHelper extends SQLiteOpenHelper {\n\n public static String DB_PATH;\n public static String DB_NAME;\n public SQLiteDatabase database;\n public final Context context;\n\n public SQLiteDatabase getDb() {\n return database;\n }\n\n public ExternalDbOpenHelper(Context context, String databaseName) {\n super(context, databaseName, null, 93);\n this.context = context;\n String packageName = context.getPackageName();\n DB_PATH = String.format(\"//data//data//%s//databases//\", packageName);\n DB_NAME = databaseName;\n openDataBase();\n }\n\n public void createDataBase() {\n boolean dbExist = checkDataBase();\n if (!dbExist) {\n this.getReadableDatabase();\n try {\n copyDataBase();\n } catch (IOException e) {\n Log.e(this.getClass().toString(), \"Copying error\");\n throw new Error(\"Error copying database!\");\n }\n } else {\n Log.i(this.getClass().toString(), \"Database already exists\");\n }\n }\n private boolean checkDataBase() {\n SQLiteDatabase checkDb = null;\n try {\n String path = DB_PATH + DB_NAME;\n checkDb = SQLiteDatabase.openDatabase(path, null,SQLiteDatabase.OPEN_READONLY);\n } catch (SQLException e) {\n Log.e(this.getClass().toString(), \"Error while checking db\");\n }\n if (checkDb != null) {\n checkDb.close();\n }\n return checkDb != null;\n }\n\n private void copyDataBase() throws IOException {\n\n InputStream externalDbStream = context.getAssets().open(DB_NAME);\n\n\n String outFileName = DB_PATH + DB_NAME;\n\n\n OutputStream localDbStream = new FileOutputStream(outFileName);\n\n\n byte[] buffer = new byte[1024];\n int bytesRead;\n while ((bytesRead = externalDbStream.read(buffer)) > 0) {\n localDbStream.write(buffer, 0, bytesRead);\n }\n\n localDbStream.close();\n externalDbStream.close();\n\n }\n\n public SQLiteDatabase openDataBase() throws SQLException {\n String path = DB_PATH + DB_NAME;\n if (database == null) {\n createDataBase();\n database = SQLiteDatabase.openDatabase(path, null,SQLiteDatabase.OPEN_READWRITE);\n }\n return database;\n }\n @Override\n public synchronized void close() {\n if (database != null) {\n database.close();\n }\n super.close();\n }\n\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n\n //createDataBase();\n openDataBase();\n\n }\n\n\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n // on upgrade drop older tables\n db.execSQL(\"DROP TABLE IF EXISTS perception_database\");\n // create new tables\n onCreate(db);\n\n }\n}\n\n\nI'm not sure as to what I should put inside the OnCreate and onUpgrade functions so as to facilitate updating of the database without first clearing data and uninstalling.\n\nI am using a prepopulated sqlite database\n\nThe database name is umangdb.db\n\nIt contains many tables,one of which is perception_database which i am trying to drop and recreate.\n\nI don't mind dropping and recreating all tables as the database is very small.\nI was unable to completely understand this database helper class which I sourced from a friend."
] | [
"android",
"database",
"sqlite"
] |
[
"php split a day into number of times?",
"need a php function to split a day with number of times and get the right time.\nfor example if i split a day into 2 times\n\n00:00:00\n12:00:00\n\n\nif I split a day ( 24 hours) in to 4 times it will show following\n\n00:00:00\n06:00:00\n12:00:00\n18:00:00\n\n\nand if i split into 6 times output will be like\n\n00:00:00\n04:00:00\n08:00:00\n12:00:00\n16:00:00\n20:00:00\n\n\nI need a function something like this\n\n <?php \n function split_times ($interval) {\n //code\n return arry;\n } ?>"
] | [
"php"
] |
[
"Simple thread issue with Android animation",
"I'm trying to implement a thread with some simple Android animation. I'm just getting an error with sleep() - It says I need a method for it. I know there is probably an obvious solution. My app just places a ball that moves in a circle at a random location. What I want is to continue placing shapes at random locations. Anyway, can someone please tell what I'm doing wrong with my thread? Thanks.\n\npublic class DrawingTheBall extends View {\n\nBitmap bball; \nRandom randX, randY;\ndouble theta;\nHandler m_handler;\nRunnable m_handlerTask; //for some reason I get a syntax error here\nm_handler = new Handler();\n\npublic DrawingTheBall(Context context) {\n super(context);\n // TODO Auto-generated constructor stub\n bball = BitmapFactory.decodeResource(getResources(), R.drawable.blueball); \n //randX = 1 + (int)(Math.random()*500); \n //randY = 1 + (int)(Math.random()*500);\n randX = new Random();\n randY = new Random();\n theta = 45;\n new Thread(this).start();\n}\n\npublic void onDraw(Canvas canvas){\n super.onDraw(canvas);\n //Radius, angle, and coordinates for circle motion \n float a = 50;\n float b = 50;\n float r = 50;\n int x = 0;\n int y = 0;\n theta = theta + Math.toRadians(2);\n\n //move ball in circle\n if(x < canvas.getWidth()){\n x = randX.nextInt() + (int) (a +r*Math.cos(theta));\n }else{\n x = 0;\n }\n if(y < canvas.getHeight()){\n y = randY.nextInt() + (int) (b +r*Math.sin(theta));\n }else{\n y = 0;\n }\n Paint p = new Paint();\n\n}\n\n m_handlerTask = new Runnable()\n {\n @Override \n public void run() {\n\n // do something \n m_handler.postDelayed(m_handlerTask, 1000); \n invalidate();\n }\n };\n m_handlerTask.run(); \n\n\n}\n}"
] | [
"java",
"android",
"multithreading",
"animation",
"android-canvas"
] |
[
"Can we have a dispatcher that you can add things todo asynchronously but will be executed in that order synchronously?",
"As a \"branch\" question from my other question (see Edit 4) How to convert a png base64 string to pixel array without using canvas getImageData?\n\nI wonder what happens when you have a set of functions like this:\n\nfunction convertTileToRGB(tile,whatToDoNext){\n tile.img.onload = function() {\n //async code returns pixels\n whatToDoNext(pixels);\n }\n\n}\n\nfunction doSomethingWithTile(tile,params){\n convertTileToRGB(tile,function(pixels){\n //manipulate pixels in tile\n });\n}\n\nfunction doSomethingWithTile2(tile,params){\n convertTileToRGB(tile,function(pixels){\n //manipulate pixels in a different way\n });\n}\n\n\nIs there a way a arbitrary call sequence like this, \n\nvar tile = initialize_tile();\n\ndoSomethingWithTile(tile,params1)\ndoSomethingWithTile2(tile,params2)\ndoSomethingWithTile(tile,params3) \n...\n\n\nthat is dynamic and not known in advance, in other words added asynchronously to a dispatcher while the program is running and then the dispatcher is invoking them synchronously, to be solved somehow?\n\nIf we don't have a dispatcher and we use callbacks we can see that the methods act separately on the initialized tile but their actions are not accumulated to the tile. In that example order is preserved but essentially the result of the previous async method is not used in the next one.\n\nThanks in advance for any help\n\nEDIT:\nthanks for the answers. yeah order matters but this list of things is being changed throughout the time(more things are added) and is not known before hand. It would be nice if there was a way to have a dispatcher object that will have what is to be done in a specific order being added asynchronously but it will invoke them in that order synchronously. I changed my question accordingly because most of the people were confused.\n\nEDIT2:\nTrying to change my code:\nThe dispatcher would look like below. The tile and sample could be different for each invocation but could be the same for some. Other actions will be applied except for addSample. If the same tile is used the invocations changes should be accumulated in the tile in that order. And most importantly the dispatcher should be able to get more to do actions asynchronously.\n\nvar sample = [[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f],[0x7f,0x7f,0x7f]]\nvar tile = initialize_tile({width: 7,height: 7,defaultColor: [0x00,0xAA,0x00], x: 1, y: 2, zoomLevel: 1});\nvar dispatcher = { \n 0:{\n func: addSample, \n tile: tile,\n sample: sample, \n num_samples: 6, \n which_sample: 1\n },\n 1:{\n func: addSample, \n tile: tile,\n sample: sample, \n num_samples: 6, \n which_sample: 2\n },\n 2:{\n func: render,\n tile: tile,\n }\n};\nvar disp = dispatcher[0];\ndisp.func(disp.tile,disp.sample,disp.num_samples,disp.which_sample); \ndisp = dispatcher[1];\ndisp.func(disp.tile,disp.sample,disp.num_samples,disp.which_sample);\n\n\nWith that code the order is not preserved and what happens to the tile is not kept for the next invocation."
] | [
"javascript",
"asynchronous"
] |
[
"Infinite scroll cancel the highlight",
"I'm using the infinite scrolling for the search result page. The problem I'm having is that when you do a search for something like 'Android', the word is highlighted in the results you see on the first page, but if you scroll to the bottom of the page and see more results, those entries do not have the search term highlighted.\nSo the pages which are loaded with infinite scrolling have no the search terms highlighted. The script for highlighting is here \n\n$(document).ready(function() {\n jQuery.ias({\n container : '.articles',\n item: '.article',\n pagination: '#pagination',\n next: '.next_page',\n triggerPageThreshold: 1003,\n loader: '<img src=\"loader.gif\"/>'\n\n }); \n\n }); \n\n\nto execute the highlight:\n\n\n $('p').highlight('android');\n\n\nin firebug it works fine when I run the script. How can I implemmented inside of the infinite scrolling so it's triggered with it?"
] | [
"javascript",
"jquery",
"infinite-scroll"
] |
[
"Only inline template works, how to do it right",
"I wrote myself a StringHelper in cpp to convert. But it won't compile if I put the sourceode in an external cpp-file (included in the Codeblocks-projectfile) or I don't understand the errors:\n\nHPP:\n\n#ifndef _INPUT_STRINGHELPER_HPP\n #define _INPUT_STRINGHELPER_HPP\n\n #include <string>\n #include <sstream>\n #include <deque>\n\n namespace FiveDimension\n {\n void SplitStream(std::stringstream& s, char c, std::deque<std::string>& ret);\n void SplitString(std::string s, char c, std::deque<std::string>& ret);\n template<typename T> T StringToAll(std::string val);\n template<typename T> bool TryStringToAll(std::string val, T &ret);\n template<typename T> std::string AllToString(T val);\n }\n\n#endif\n\n\nCPP:\n\n#include \"StringHelper.hpp\"\n\nvoid FiveDimension::SplitStream(std::stringstream& s, char c, std::deque<std::string>& ret)\n{\n std::string line;\n\n while(std::getline(s, line, c))\n ret.push_back(line);\n}\nvoid FiveDimension::SplitString(std::string s, char c, std::deque<std::string>& ret)\n{\n std::string line;\n std::stringstream ss(s);\n\n while(std::getline(ss, line, c))\n ret.push_back(line);\n}\ntemplate<typename T> T FiveDimension::StringToAll(std::string val)\n{\n std::stringstream s(val);\n T ret;\n s >> ret;\n return ret;\n}\ntemplate<typename T> bool FiveDimension::TryStringToAll(std::string val, T &ret)\n{\n std::stringstream s(val);\n return (s >> ret);\n}\ntemplate<typename T> std::string FiveDimension::AllToString(T val)\n{\n std::stringstream s;\n s << val;\n return s.str();\n}\n\n\nI also tried for example:\n\ntemplate<typename T> std::string FiveDimension::AllToString<T>(T val)\n{\n std::stringstream s;\n s << val;\n return s.str();\n}\n\n\nbut this doesn't even compile this file and make me feel I don't know anything about templates so I came here.\nI read the answer by Aaron on this topic: "Undefined reference to" template class constructor . After that I understood a lot more. But how can I predefine a function ?"
] | [
"c++",
"function",
"templates",
"codeblocks"
] |
[
"Flutter: FirebaseAuth, Firebase Database - Add profile picture error",
"i have a Profile Picture "System" on my App. But when I upload a picture, it works. But when I upload a picture from an other Account it doesn't work. And when I delete the Database File from the old Account and try it from new on the current account, it works.\nI think the Problem is that, that the document name is the same when i upload a new picture. But I don't know.\nThis is my Add Picture Code:\n addProfilePic(user, context) {\nFirebaseFirestore.instance.collection('/profilbild').add({\n 'uid': FirebaseAuth.instance.currentUser.uid,\n 'photoUrl': photoUrl,\n}).then((value) {\n //Navigator.of(context).pop();\n //Navigator.of(context).pushReplacementNamed('/selectpic');\n}).catchError((e) {\n print(e);\n});\n\nAnd that is my Change Profil Picture Code:\n Future updateProfilePic(picUrl) async {\nvar userInfo = new UserUpdateInfo();\n\nawait FirebaseAuth.instance.currentUser\n .updateProfile(photoURL: picUrl)\n .then((val) {\n getUserCurrent().then((user) {\n FirebaseFirestore.instance\n .collection('/profilbild')\n .where('uid', isEqualTo: FirebaseAuth.instance.currentUser.uid)\n .get()\n .then((QuerySnapshot querySnapshot) => {\n querySnapshot.docs.forEach((doc) {\n FirebaseFirestore.instance\n .doc('/profilbild/$doc')\n .set({'photoUrl': picUrl}).then((val) {\n print('Profilbild aktualisiert');\n });\n })\n });\n\nMy Code first add the document on Database with an uid and the Profil Picture = null. After that I change the Profil Picture with my Code to the Storage Link.\nWhen I only add the Picture (Code: addProfilePic) the database make following document:\n\nAnd when I update the Picture (Code: updateProfilPic) following came out: (Look at the name of the document!)\n\nAnd when I want to add a Profile Picture from an other Account I add the Profile Picture (Code: addProfilePic) than it works. It make a document like on Picture 1.\nAnd after I want to update the Picture (Code: updateProfilePic) it doesn't work. The document is the same as before. (Like Picture 1) Nothing adds and nothing changes.\nHow can I fix that?"
] | [
"firebase",
"flutter",
"firebase-realtime-database",
"firebase-authentication"
] |
[
"Command-line to compile Win32 \"hello world\" in Visual Studio 2005",
"The following basic Win32 program compiles just fine in Dev-C++.\n\n#include <windows.h>\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){\n MessageBox(NULL,\"Hello, world!\",\"My app\", MB_OK ) ;\n}\n\n\nBut now I'm trying to compile it using Visual Studio 2005. I open the Visual Studio command prompt and type:\n\ncl test.cpp\n\n\nBut I get the following errors:\n\ntest.cpp\ntest.obj : error LNK2019: unresolved external symbol __imp__MessageBoxA@16 referenced in function _WinMain@16\ntest.exe : fatal error LNK1120: 1 unresolved externals\n\n\nI thought the problem might be the path for the linker, but according to this MSDN page, the linker looks for it in the enviromental variable LIB which is already set in the Visual Studio prompt to:\n\nC:\\Program Files\\Microsoft Visual Studio 8\\VC\\ATLMFC\\LIB;\nC:\\Program Files\\Microsoft Visual Studio 8\\VC\\LIB;\nC:\\Program Files\\Microsoft Visual Studio 8\\VC\\PlatformSDK\\lib;\nC:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\lib;\n\n\nWhat else is needed to compile a Win32 program in the command line?\n\nI'm using Visual Studio 2005 SP1 update for Vista."
] | [
"c++",
"windows",
"winapi",
"visual-studio-2005"
] |
[
"How to launch vscode debug configuration from the browser?",
"I have a test case reporting scheme delivered in HTML that is complex in its own right and not easily ported to a VSCode extension. I would like to launch a Debug Configuration for each failing test case from the browser displaying the report. I have already been able to modify the report and have added a copy/paste widget for each test case's associated command. However I would like to do something to the effect of:\n\n\nLaunch a service as a VSCode extension that can handle requests\nFormulate those requests in a way that can dynamically create launch configurations\n\n\nIt may be that I am stuck writing a Debug Adapter without the bells and whistles of interacting with the report.\n\nThat being said, if this is a solved problem or has a framework for solving with VSCode (and I realize remote execution could be a Very Bad Thing for VSCode to allow), I have not been able to find it through an existing extension.\n\nI welcome your ideas.\n\nThis is perhaps not as open ended as it sounds...my question ultimately is: can VSCode operate as a service to be requested by web interfaces? Even if it could be done via Localhost this would be a boon. If it can be done over ssh with authentication, that would also be a bonus."
] | [
"visual-studio-code",
"vscode-extensions"
] |
[
"How to determine when finalize() method is called",
"class Example {\n @Override\n protected void finalize() {\n System.out.println(\"Object getting garbage collected\"); \n } \n}\n\npublic class GarbageCollectionDemo {\n public static void main(String [] args) {\n Example e1 = new Example();\n {\n Example e2 = new Example();\n }\n e1.finalize(); \n }\n}\n\n\nI wanted to check whether the output shows when the finalize() is called, and when the objects are actually getting removed. But I could not track, is it because its according to the JVM that the object will be garbage collected? What happens if we override the finalize() method? Do we have to explicitly call it ourselves? Then why does Netbeans suggest to add the finally block with super.finally()?"
] | [
"java",
"finalizer"
] |
[
"Optimizing js -Saving values from checkboxes in object",
"i'm rather new to js and i'd like to optimize my code.\nI have a group of checkboxes and their boolean values are saved in an object for further calculations.\n\nHTML:\n\n<fieldset>\n <input type=\"checkbox\" id=\"checkbox1\" onchange=\"checkbox1Changed()\" value=\"checkbox1\">\n\n <input type=\"checkbox\" id=\"checkbox2\" onchange=\"checkbox2Changed()\" value=\"checkbox2\">\n\n <input type=\"checkbox\" id=\"checkbox3\" onchange=\"checkbox3Changed()\" value=\"checkbox3\">\n</fieldset>\n\n\nJS:\n\n//store values for further computation\n\nvar boxValues = {\n box1: false,\n box2: false,\n box3: false,\n}\n\n//get checkboxvalues from view\n\nvar checkbox1 = document.getElementById(\"checkbox1\");\nvar checkbox2 = document.getElementById(\"checkbox2\");\nvar checkbox3 = document.getElementById(\"checkbox3\");\n\n//update values in boxValues\n\nfunction checkbox1Changed() {\n if (checkbox1.checked) {\n boxValues.box1 = true;\n } else {\n boxValues.box1 = false;\n }\n}\n\nfunction checkbox2Changed() {\n if (checkbox2.checked) {\n boxValues.box2 = true;\n } else {\n boxValues.box2 = false;\n }\n}\n\nfunction checkbox3Changed() {\n if (checkbox3.checked) {\n boxValues.box3 = true;\n } else {\n boxValues.box3 = false;\n }\n}\n\n\nSince i plan on having approximately 20 checkboxes in the view there would be a lot of repeating code. \nDoes anyone know a smarter way to do that?\n\nThanks in advance!\n\nVin"
] | [
"javascript",
"jquery",
"html",
"design-patterns",
"checkbox"
] |
[
"bigQuery c#/Java - How to work with large result",
"I am new to bigQuery, and I am trying to understand better the Large result concept.\n\nI am trying to query over my Table with several select queries.\nI am using C# with the Google API, using the Asynchronous method as described here:\n\nhttps://developers.google.com/bigquery/querying-data#asyncqueries\n\nwhen I reach the LareResult limit - I get this error: \"Table not found\" - with the temporary table I created. (I think this might be a Bug?).\n\nAny way - If I want to get this Large result I must set the \"AllowLargeResult\" flag with a destination table name, and the data will be created in a new table\n\nAnd then What? - How can I get these result? If I query the new created table I still get large result. \nIs there a Way for me to understand if I got this limit without getting this exception?\n\nA working java/C# example will be appreciated."
] | [
"java",
"c#-4.0",
"google-bigquery",
"google-api-java-client",
"google-api-dotnet-client"
] |
[
"Difference between OpenCV and OpenCL",
"Can anyone explain me what is the difference between OpenCV and OpenCL? What is suitable for Android image processing in Java?"
] | [
"java",
"android",
"opencv",
"opencl"
] |
[
"Drools object graph rule definition",
"I have an object graph that I am trying to generate Fulfillment object from in Drools. Specifically, Fulfillment objects represent a rule that is either satisfied, or unsatisfied. My object graph looks like the following:\n\nUsers ---> many Requirements --> Event\n `--> many Records ----^\n\n\nRecords can fulfill Requirements if they both point at the same Event. This produces a Fulfillment object in Drools.\n\nA reduce down rule to produce Fulfillments is the following:\n\nrule \"fulfils\"\nwhen\n $u : User()\n $rec : Record() from $u.records\n $r : Requirement(event contains $rec.event) from $u.requirements\nthen\n insertLogical( new Fulfillment($u, $rec, $r, true));\n System.out.println(\"Inserting logical\");\nend\n\nrule \"unfulfils\"\nwhen\n $u : User()\n $rec : Record() from $u.records\n $r : Requirement(event not contains $rec.event) from $u.requirements\nthen\n insertLogical( new Fulfillment($u, $rec, $r, false));\n System.out.println(\"Inserting logical\");\nend\n\nquery \"fulfillment\"\n $fulfillment : Fulfillment()\nend\n\n\nThe problem I run into here is if the user has no records, there is no Fulfillment inserted for the requirement. I believe this is because there is no Record() to search on to satisfy my graph.\n\nIs there a way to use the records without requiring more than zero to exist?\n\nAlso, do I need two rules here to insert both true and false Fulfillments or is there a better way to do this?\n\nEdit\n\nAnother problem I am facing with these rules is the Requirement(event contains $rec.event) does not accomplish the task of finding if any records satisfy the given collection of events. Is there a better way to find if there exists an overlap between the many record's single events, and the single requirements multiple events?\n\nAnother Edit\n\nHere's another approach I thought up. Instead of inserting Fulfillments if a requirement/record pair is not found, why not just insertLogical Fullfillments for all Requirements that have no matching positive Fullfillment:\n\nrule \"unfulfils\"\nwhen\n $u : User()\n $r : Requirement() from $u.requirements\n not(Fulfillment(user == $u, requirement == $r, fulfilled == true))\nthen\n insertLogical( new Fulfillment($u, null, $r, false));\n System.out.println(\"Inserting logical\");\nend\n\nquery \"fulfillment\"\n $fulfillment : Fulfillment()\nend\n\n\nThis takes care of the issue of comparing the overlap of two collections, and the case where a user has no records. (Would appreciate some validation on this)."
] | [
"drools",
"object-graph"
] |
[
"reading data from a randomaccessfile",
"Here is the function I have :\n\n// Read a record from the specified RandomAccessFile\n public void read( RandomAccessFile file ) throws IOException {\n account = file.readInt();\n byte b1[] = new byte[ 15 ];\n file.readFully( b1 );\n firstName = new String( b1, 0 );\n firstName = firstName.trim();\n byte b2[] = new byte[ 15 ];\n file.readFully( b2 );\n lastName = new String( b2, 0 );\n lastName = lastName.trim();\n balance = file.readDouble();\n }\n\n\nI have to be able to read from a randomaccessfile for one of my exams and the code above is a bit confusing. \n\nhere is what I am guessing is happening, would appreciate it if you could correct me if I am wrong.\n\nwe take file in and readInt from the file and assign it to account. next I guess we create a new byte of size 15 and read the first name from the file into the byte and then assigned to firstname. now here is what I dont understand, what does readFully do? and how does the code above knows to move on to the next value for lastName.\nSo simply put, \n\nbyte b1[] = new byte[ 15 ];\n file.readFully( b1 );\n firstName = new String( b1, 0 );\n firstName = firstName.trim();\n\n\nVS\n\n byte b2[] = new byte[ 15 ];\n file.readFully( b2 );\n lastName = new String( b2, 0 );\n lastName = lastName.trim();\n balance = file.readDouble();\n\n\nWhy doesnt it give the same value? are we guessing how long each value (firstname, lastname etc) is ?"
] | [
"java",
"io",
"randomaccessfile"
] |
[
"How can I tell matplotlib.pyplot to make a scatter graph using values from Column A when Column D is True?",
"M_D min max min15 max15 min_record_2015 max_record_2015\n\n0 693596.0 -4.762312 3.232487 -13.3 1.1 True False\n1 693597.0 -7.787081 1.154286 -12.2 3.9 True True\n2 693598.0 -9.556938 -0.870142 -6.7 3.9 False True\n3 693599.0 -7.292574 0.183099 -8.8 4.4 True True\n4 693600.0 -5.668780 1.768571 -15.5 2.8 True True\n5 693601.0 -5.867633 1.738278 -18.2 3.3 True True\n\n\nI've got this dataframe and how can I tell matplotlib.pyplot to make a scatter graph using values from min15 when min_record_2015 is true and max15 when max_record is true (and M_D should be on the X axis )? \n\nI tried making an index list with the needed value to use later in plt.scatter but I get the full index list.\n\nbroken_min=(foo[\"min_record_2015\"]==True).index.tolist()\n\n\nThanks in advance!\n\nedit:\n\nfoo=pd.merge(temp,temp15,how=\"outer\", left_on=\"M_D\",right_on=\"M_D\")\nfoo['min_record_2015'] = foo['min15'] < foo['min']\nfoo['max_record_2015'] = foo['max15'] > foo['max']\nfoo=foo[(foo.min_record_2015 == True) | (foo.max_record_2015 == True)] #remove false|false rows\n#broken_min=(foo[\"min_record_2015\"]==True).index.tolist()\n#broken_max=(foo[\"max_record_2015\"]==True).tolist()\n\n#ys=foo.apply(lambda x: x[\"min15\"] if x[\"min_record_2015\"] else x[\"max15\"] , axis=1)\n\n\n%matplotlib notebook\n #plt.close()\n plt.figure()\n plt.plot(temp_min[\"M_D\"], temp_min[\"min\"]/10, c=\"b\", lw=0.5, label=\"record low 2005-2014\")\n plt.plot(temp_max[\"M_D\"], temp_max[\"max\"]/10 ,c=\"r\", lw=0.5, label=\"record high 2005-2014\")\n\n #plt.scatter(foo[\"M_D\"], ys, c=\"m\", marker=\"o\", s=5, label=\"record low broken in 2015\")\n #plt.scatter(temp15[\"M_D\"], temp15[\"max15\"], c=\"k\", marker=\"o\", s=5, label=\"record high broken in 2015\")\n (foo.assign(y=np.where(foo['min_record_2015'], foo['min15'], foo['max15'])).plot.scatter('M_D', 'y'))\n\n ax = plt.gca()\n ax.xaxis.set_major_formatter(dates.DateFormatter('%b-%d'))\n ax.xaxis.set_major_locator(dates.MonthLocator())\n loc, labels = plt.xticks()\n plt.setp(labels, rotation=45)\n\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n\n\n plt.subplots_adjust(bottom=0.15)\n plt.legend(loc='best')\n plt.ylabel('Temperature (Deg C)')\n plt.title('Record Temperatures for each Day of the Year')\n\n plt.gca().fill_between(temp['M_D'], \n temp['min'], temp['max'], \n facecolor='blue', \n alpha=0.20)\n #plt.show()"
] | [
"python",
"python-3.x",
"pandas",
"numpy",
"matplotlib"
] |
[
"How do I ignore a URL rewrite when there are no arguments?",
"I want my users to specify friendly URLS for some of the content they will be adding through my CMS. However, .htaccess is not really my strong suit (I generally avoid it like the plague).\n\nHere is what I have so far that is almost working perfectly:\n\nRewriteEngine on\nRewriteRule ^arg/([0-9a-z\\-]+)/?$ index.php?arg=$1 [NC,L]\n\n\nObviously - I probably won't be using \"/arg\" to specify this in production, but for all intents and purposes, it works for right now.\n\nThis probably goes without saying - but all requests that would normally look like:\nindex.php?arg=some-argument not look like /arg/some-argument which is exactly what I want.\n\nHere's the problem\n\nNow - If a user ends up at index.php without passing an argument - it 404s. I would like to present the end user with a list of page-specific options - rather than sending them to a generic 404. How do I go about this?\n\nEdit:\nI answered the question because I found something that works - however, I don't fully understand everything going on in my answer, if someone can break down exactly what is happening - or even just validate that I am doing this the right way - I would appreciate it."
] | [
".htaccess",
"mod-rewrite"
] |
[
"The \"Hide div before scrolling\" codes does not work no matter what",
"I'm building a local website on the Bitnami Wordpress Stack with the Arras theme, if that's important.\n\nI'm making a fixed menu that I want to show after I have scrolled 190 pixels down on the page. The problem is that anything works, no matter which JQuery or JavaScript code I try. I have searched and searched here on StackOverflow, and I know that this question have been asked numerous times here before - but I have tried every code I could find, and none works. This is my JavaScript/JQuery/HTML/PHP code for my menu, placed in the header.php file:\n\n<div class=\"medfolg\" id=\"medfolg\">\n<script type=\"text/javascript\">\n $(document).ready(function(){\n $(window).bind('scroll', function(){\n if($(window).scrollTop() > 190){\n $('#medfolg').show();\n } else {\n $('#medfolg').hide();\n };\n });\n });\n</script>\n<?php \nif ( function_exists('wp_nav_menu') ) {\n wp_nav_menu( array( \n 'menu' => 'medfolg',\n 'menu_class' => 'sf-menu'\n ) );\n} \n?>\n</div>\n\n\nAnd this is the CSS code I have placed in my default.css file:\n\n#medfolg.medfolg {position:fixed;}\n#medfolg { text-transform: lowercase; position: absolute; top: 0; width: 100%; background: #f5f5f5; z-index:5000; display: none;}\n#medfolg .menu-medfolg-container { width: 980px; margin: 0 auto; }\n#medfolg .sf-menu { position: relative; top:3px !important; }\n#medfolg .sf-menu a { font-size: 22px; color: #444; margin-right: 15px;}\n\n\nI desperately need some help - please!\n\nEDIT: I've made a jsFiddle here with only small modifications (Wordpress .php menu cannot be read on other places than Wordpress): http://jsfiddle.net/wHMjr/"
] | [
"javascript",
"jquery",
"wordpress"
] |
[
"Determine in ash if subdirectory exists but not under a certain directory",
"I'm writing a script for BusyBox ash, and need to determine if a subdirectory exists so my script can display an error message.\nNormally if test -d sub/directory would be my go-to, but the problem here is there's one folder I don't want to trip this logic.\nI currently use ls /folder/*/bar | grep -v foo and parse the exit code but I know that's bad practice.\nHere's what I'm looking at (bar should trip the logic, foo should not)\n/folder/foo/bar <- this should not trip because it contains foo\n/folder/dev/bar <- should trip because it contains bar but not foo\n/folder/randome/name <- should not trip doesn't contain bar\n\nIs there a proper/better way to do this?"
] | [
"shell",
"if-statement",
"ash"
] |
[
"Log4j2 does not create the logfile in Spring boot",
"I have a Spring boot app and I want to use LOG4J2 to manage my logs in different files, but the logfile isn't created.\n\nI have a log4j2.properties configuration under \"resources\" \n\nMy log file configuration:\n\nname=PropertiesConfig\n#output folder\nproperty.filename=G:\\\\PRUEBAS\nproperty.packagename=com.package.main\nappenders=console, infoLoggerAppender, commonLoggerAppender, errorLoggerAppender\nappender.console.type=Console\nappender.console.name=STDOUT\nappender.console.layout.type=PatternLayout\nappender.console.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n\n#common appender\nappender.commonLoggerAppender.type=File\nappender.commonLoggerAppender.name=RollingFile\nappender.commonLoggerAppender.fileName=${filename}\\\\log.log\nappender.commonLoggerAppender.layout.type=PatternLayout\nappender.commonLoggerAppender.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n\n#error appender\nappender.errorLoggerAppender.type=RandomAccessFile\nappender.errorLoggerAppender.name=RandomAccessFile\nappender.errorLoggerAppender.fileName=${filename}\\\\error.log\nappender.errorLoggerAppender.layout.type=PatternLayout\nappender.errorLoggerAppender.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n\n#using LevelRangeFilter to only log error levels.\nappender.errorLoggerAppender.filter.threshold.type=LevelRangeFilter\nappender.errorLoggerAppender.filter.threshold.minLevel=error\nappender.errorLoggerAppender.filter.threshold.maxLevel=error\n#info appender\nappender.infoLoggerAppender.type=File\nappender.infoLoggerAppender.name=LOGFILE\nappender.infoLoggerAppender.fileName=${filename}\\\\info.log\nappender.infoLoggerAppender.layout.type=PatternLayout\nappender.infoLoggerAppender.layout.info=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n\n#using LevelRangeFilter to only log info levels.\nappender.infoLoggerAppender.filter.threshold.type=LevelRangeFilter\nappender.infoLoggerAppender.filter.threshold.minLevel=info\nappender.infoLoggerAppender.filter.threshold.maxLevel=info\n# creating only one logger, we can use this with multiple appenders.\nloggers=fileLogger\n# this is package name. This package and all of it's child packages will use this logger\nlogger.fileLogger.name=${packagename}\n# logger base level\nlogger.fileLogger.level=debug\nlogger.fileLogger.appenderRefs=infoLoggerAppender, commonLoggerAppender, errorLoggerAppender\nlogger.fileLogger.appenderRef.infoLoggerAppender.ref=LOGFILE\nlogger.fileLogger.appenderRef.commonLoggerAppender.ref=RollingFile\nlogger.fileLogger.appenderRef.errorLoggerAppender.ref=RandomAccessFile\nrootLogger.level=debug\nrootLogger.appenderRefs=stdout\nrootLogger.appenderRef.stdout.ref=STDOUT\n\n\nWhat can I do? Someone can help me?\nI waste my last two days with this..."
] | [
"java",
"spring-boot",
"log4j",
"log4j2"
] |
[
".NET Page Method vs UpdatePanel, Which is Better for Updating and Refreshing",
"I haven't started writing any code for this program, but here's what I need to do in C#/ASP.NET, both of which I'm just starting to learn.\n\nI have a DIV on a page that I want to update with information from an MS SQL Server every five seconds.\n\n\nWould it be better to create my countdown timer on the JavaScript or C# side?\nWould UpdatePanel or creating a Page Method be more efficient for updating the DIV with the database information?\n\n\nLoad times are a serious issue for this application, so the lighter and faster the solution, the better."
] | [
"c#",
"asp.net",
"updatepanel",
"pagemethods"
] |
[
"DirectX 11 Win7 versus Win8 difference in brightness/shader ambient lighting",
"The problem shows on all Win8 systems, all brands, all types of desktop, laptop, all-in-one, and tablets (tested on nearly every system at BestBuy which there's a ton of them so I can't be the first person to see this.) \n\nWhat is happening is shown in below image (note captions below each surface), where the rendering on Win8 is brighter than Win7 for native code and WinForm which is based off a windowed ID3D11Device/Context; and to make things worse; the rendering is darker via WPF and WPFs shared surface/texture features though using similar device/context. The actual rendering loop and shaders are identical. Win7/Vista render the same/ideal brightness via native type render target or WPF shared surface.\n\nThe DirectX 11 code was developed on Win7. It's very basic DX stuff and the shader is as simple a shader as possible; very similar to the most basic DirectX SDK examples.\n\n\nWhy is DX11 Win8 brightness not consistent with Win7? Gradients seem different too.\nWhy would Win8 WPF shared surface/texture create even more difference?\nWhat is the best strategy to solve such rendering brightness differences? \n\n\n\n\nI did end up answering, but welcome improvements or expand with related answers to brightness/lighting problems between win7 and win8 as searching the net for such topic shows little results."
] | [
"wpf",
"winforms",
"directx",
"directx-11"
] |
[
"What are the BusinessBase and BusinessListBase classes in the CSLA framework?",
"I'm learning a large legacy application written in VB.net with the CSLA framework. Many of the objects seem to inherit from BusinessBase and BusinessListBase. When I \"go to definition\" in Visual Studio, I see that these classes are a part of the CSLA namespace. What are these classes? What role do they play in the CSLA framework? How do they relate to other CSLA concepts like Root Object and Child Object?"
] | [
".net",
"csla"
] |
[
"Unable to instantiate class nltk.classify.textcat.TextCat",
"I'm trying to run the following:\nimport nltk \ntc = nltk.classify.textcat.TextCat()\n\nI get the following error:\nOSError: classify.textcat requires the regex module that supports unicode. Try '$ pip install regex' and see https://pypi.python.org/pypi/regex for further details.\n\nI've tried adding import regex before import nltk but unfortunately I still get the same error.\nWhat have I missed?"
] | [
"python",
"regex",
"nltk"
] |
[
"How to programmatically insert a parent element in all existing CSS selectors",
"I have a large CSS file with over 1000 selectors. I want to add the ID MyId as parent element to ALL of the selectors.\n\nFor example:\n\np{\n...\n}\n.myclass li{\n...\n}\n\n\nwill become:\n\n#MyId p{\n...\n}\n#MyId .myclass li{\n...\n}\n\n\nIs there any way to do this automatically, for example in PhpStorm or a tool?"
] | [
"css",
"css-selectors",
"phpstorm"
] |
[
"Write 0b11001001 in decimal",
"Problem:\n\n\n Write 0b11001001 in decimal.\n\n\nI tried the following:\n\n\n 110010012 = 1 + 8 + 64 + 128 = 201\n\n\nbut the answer is –55. Where am I going wrong?"
] | [
"decimal",
"bit"
] |
[
"React JS/Webpack/Sass/Bootstrap 4 anchor link cannot be centered?",
"I am new to React JS and Webpack and have run into a really weird error. I just want to center a anchor link on the screen. Thats all! However even if I inspect the element and remove all inherited styles and use the tried and true, set a width, margin auto method it will not move. Not sure if this is a react/webpack thing I am just straight up missing. \n\n\n\nBelow is the anchor link component. And its classes SASS. (Yes its parent has width: 100%)\n\nrender() {\n return (\n <a href={this.strava.oauth.getRequestAccessURL()}\n className=\"connect-strava-btn\">\n Connect With Strava\n </a>\n );\n }\n\n\nsass:\n\n.connect-strava-btn{\n\n width: 250px;\n margin: auto;\n\n color: black;\n font-size: 11px;\n padding: 20px 30px;\n border: 1px solid black;\n text-align: center;\n text-transform: uppercase;\n}\n\n\nInterestingly if you change the a to <a> to a <p> it then centers correctly. What is it about that anchor link that react/webpack dosen't like? Below is my webpack.config.js. Help! \n\nmodule.exports = {\n entry: [\n './src/scripts/index.js'\n ],\n output: {\n path: __dirname,\n publicPath: '/',\n filename: 'bundle.js'\n },\n module: {\n loaders: [\n {\n exclude: /node_modules/,\n loader: 'babel'\n },\n {\n test: /\\.scss$/,\n loaders: [\"style\", \"css\", \"sass\"]\n },\n {\n test: /\\.json$/,\n loader: 'json'\n }\n ]\n },\n resolve: {\n extensions: ['', '.js', '.jsx']\n },\n devServer: {\n historyApiFallback: true,\n contentBase: './'\n }\n};"
] | [
"javascript",
"css",
"twitter-bootstrap",
"reactjs",
"webpack"
] |
[
"Reuse usercontrol in mail in asp.net mvc",
"After a user purchases a product, a receipt is displayed.\n\nI need to also email this receipt to the customer (as html), and would like to reuse the view I already created.\n\nWhat is the best way to do that - and how?"
] | [
"asp.net-mvc",
"user-controls"
] |
[
"Filter rows based on a threshold by grouping ID column",
"I have a data frame that I got from\n\nID <- c(\"A\",\"A\",\"A\",\"B\",\"B\",\"B\",\"C\",\"C\",\"C\") \nType <- c(45,46,47,45,46,47,45,46,47)\nPoint_A <- c(10,15,20,8,9,10,35,33,39) \ndf <- data.frame(ID,Type,Point_A)\n\n ID Type Point_A \n1 A 45 10 \n2 A 46 15 \n3 A 47 20 \n4 B 45 8 \n5 B 46 9 \n6 B 47 10 \n7 C 45 35 \n8 C 46 33 \n9 C 47 39 \n\n\nI want to calculate the median of the Point_A column grouping by ID and then remove the rows based on a threshold. \n\nFor example, lets say my threshold is 11. I want to remove the rows grouped by ID having median less than the threshold and so the desired output would be \n\n ID Type Point_A \n1 A 45 10 \n2 A 46 15 \n3 A 47 20 \n4 C 45 35 \n5 C 46 33 \n6 C 47 39 \n\n\nWhile I am able to calculate the medians but I am not knowing how to remove the rows. \n\nfunc <- function(x) (median(x,na.rm=TRUE))\ndf1 <- df %>% \n group_by(ID) %>% \n mutate_each(funs(.=func(.)),Point_A) \n summarise(Point_A = f(Point_A))\n\n\nKindly let me know how to go about doing this."
] | [
"r",
"data.table",
"plyr",
"dplyr"
] |
[
"Change font color based on variable wont work",
"I want the font color of the tekst in my table changed based on a value stored in my sql database. I have a variable that gets the color hex from an other sql table. It works for the background but it wont work for the font color. \n\nThis is what works.\n\n<td bgcolor=\"#<?= $cat_color ?> \"><?= $rij->cat_color ?></td>\n\nThis is what i tried\n\n<td color=\"#<?= $cat_color ?> \"><?= $rij->cat_color ?></td>\n\n\nThe color of the font i not changing. please help, besides this i have tried many things.."
] | [
"css"
] |
[
"Managing images in bower packages using grunt",
"I have an express app in which I'm using bower to manage the front-end dependencies. I'm also using grunt to build the front end by concatenating, uglifying, minifying, and rev'ing all the assets, including the scripts/styles that ship with each bower component using grunt-usemin.\n\nTo accomplish this I'm moving all of the compiled assets (including bower scripts/styles) to a dist/public directory. I end up with a <cache-buster>.vendor.js and a <cache-buster>.vendor.css file, which contain all of the optimized bower components.\n\nThe question is, how should I manage images that ship with various bower packages? I could manually move them into my images folder, but I would prefer to leave them packaged in bower_components (where they belong, in my opinion) and leave it up to grunt during the build process.\n\nAny input would be appreciated.\n\n\n\nGruntfile.js (extract)\n\n rev: {\n dist: {\n files: [{\n src: [\n 'dist/public/css/{,*/}*.css',\n 'dist/public/js/{,*/}*.js',\n 'dist/public/img/{,*/}*.{gif,jpeg,jpg,png}'\n ]\n }]\n }\n },\n\n useminPrepare: {\n options: {\n dest: 'dist/public'\n },\n jade: ['dist/views/{,*/}*.jade']\n },\n\n usemin: {\n jade: ['dist/views/{,*/}*.jade'],\n options: {\n assetsDirs: ['dist/public'],\n patterns: {\n jade: require('usemin-patterns').jade\n }\n }\n },\n\n concurrent: {\n server: [\n 'stylus', 'coffee'\n ],\n dist: [\n 'stylus', 'coffee'\n ]\n },\n\n copy: {\n dist: {\n files: [{\n expand: true,\n cwd: 'views',\n dest: 'dist/views',\n src: '{,*/}*.jade'\n }]\n }\n }\n });\n\n grunt.registerTask('server', [\n 'clean:server',\n 'concurrent:server',\n 'express:server',\n 'watch'\n ]);\n\n grunt.registerTask('build', [\n 'clean:dist',\n 'concurrent:dist',\n 'copy:dist',\n 'useminPrepare',\n 'concat',\n 'uglify',\n 'cssmin',\n 'rev',\n 'usemin'\n ]);\n\n\n\n\nlayout.jade (extract)\n\n//-<!-- build:css(assets) css/vendor.css -->\nlink(href='/bower_components/nivo-slider/nivo-slider.css')\n//-<!-- endbuild -->\n\n//-<!-- build:css(.tmp) css/application.css -->\nlink(href='/css/one.css')\nlink(href='/css/two.css')\n//-<!-- endbuild -->\n\n//-<!-- build:js(assets) js/vendor.js -->\nscript(type='text/javascript', src='/bower_components/jquery/jquery.js')\nscript(type='text/javascript', src='/bower_components/nivo-slider/jquery.nivo.slider.js')\n//-<!-- endbuild -->\n\n//-<!-- build:js(.tmp) js/application.js -->\nscript(type='text/javascript', src='/js/one.js')\nscript(type='text/javascript', src='/js/two.js')\n//-<!-- endbuild -->"
] | [
"express",
"gruntjs",
"bower"
] |
[
"Razor sharp html link differ from the executed link",
"While creating a custom pager I came across the problem when I send an string to my view and I encode it as @raw(strHTML) it will automatically add a controller name in front of all my links. On initial load the pager is loaded correctly and no extra controllername was added. When I hit the next button a get request is done to the action and the next page has to be loaded and this will also create a new pager. The outputted html is exactly the same as the first time this was executed. The html that is created by my customPager while debugging: \n\n<ul>\n <li class='previousPage'><span>Previous</span></li>\n <li class='currentPage'><span>1</span></li>\n <li><a title='Next page' rel='next nofollow' href='Invoices/Index?page=2'>2 </a></li>\n <li><a title='Next page' rel='next nofollow' href='Invoices/Index?page=3'>3 </a></li>\n <li><a title='Next page' rel='next nofollow' href='Invoices/Index?page=4'>4 </a></li>\n <li><a title='Next page' rel='next nofollow' href='Invoices/Index?page=5'>5 </a></li>\n <li class='nextPage'><a title='Volgende pagina' rel='next nofollow' href='Invoices/Index?page=2'>Volgende</a></li>\n</ul>\n\n\nThe html is correct, but when the page is rendered and I hover over the link it reproduces the following link:\n\nlocalhost:xxxx/company/Invoices/Invoices/Index?page=1\n\n\ncompany is the area, Invoices the controller , second Invoices (NOT necessary, this breaks the link), index the action name.\n\nI was wondering how the html and the reproduced link while clicking in the browser can be different.\n\nThanks in advance"
] | [
"c#",
"asp.net",
"asp.net-mvc",
"asp.net-mvc-4",
"razor"
] |
[
"UIScrollView bounds won't change",
"I have a subclass of a UIScrollView called pagingView. I want to animate it so that when the device is rotated (it is only specific for this viewController and hence landscape mode is turned off in the plist).\n\nI have changed all the clipsToBounds properties and the contentResize properties and autoresizing mask but none seem to work. The code I am using is as follows:\n\nUIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];\nif (orientation == UIInterfaceOrientationLandscapeLeft)\n{\n\n[UIView beginAnimations:nil context:nil];\n[UIView setAnimationDuration:1.5];\n[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; \n graph.frame = CGRectMake(pagingView.frame.origin.x, pagingView.frame.origin.y-200, pagingView.frame.size.width*1.5, pagingView.frame.size.height*2);\n[UIView commitAnimations];\n\n}\n\n\nI've changed them to blocks, changed all the properties, however, when i run the code, all it does is move the pagingView by 200 pixels up the screen and the bounds don't change (I've also tried altering the bounds property as well). Any help would be greatly appreciated, I am hoping it is just a simple thing i am missing but I have spent hours searching for solution and the closest potential answer I have got is maybe it has something to do with the layer property?\n\nThanks in advance!"
] | [
"xcode",
"uiscrollview",
"size",
"bounds",
"cgrect"
] |
[
"Android: Setting a button size programatically",
"I'm trying to make a 100x100 px button and add it to a gridlayout on the position 3,3\n\nButton btn = new Button(this);\nbtn.setLayoutParams(new ViewGroup.LayoutParams(100,100));\nGridLayout grid4x4 = (GridLayout)findViewById(R.id.grid4x4);\n\n//I've narrowed it down to the conclusion that this line is the problem:\ngrid4x4.addView(btn,new GridLayout.LayoutParams(GridLayout.spec(3),GridLayout.spec(3)));\n//if i just use:\n//grid4x4.addView(btn); I get the button the size I want it, but I need it to be on \n//the 3,3 position of the grid.\n\n\nThis \"almost\" works, excepting the fact that the button added is bigger than 100x100px as you can see I'm trying to fix the size I want yet for some reason that's not the size I get."
] | [
"android",
"button",
"android-studio",
"size",
"layoutparams"
] |
[
"How to set the size of the layer as a percentage?",
"I use dip now. But on devices with mdpi, hdpi, xhdpi... proportions are different.\nFor example:\n\n\nI know that on mdpi 1px = 1dp. \nhdpi 1.00dp = 1.50px\nxhdpi 1.00dp = 2.00px\n\nResolutin on hdpi 480x800, on xhdi usualy 720x1280 ... DP is useless"
] | [
"android",
"xml",
"android-layout"
] |
[
"DOMException: Failed to execute 'replaceState' on 'History' React NextJS",
"Opening google cache in my site throw this exception:\n\nDOMException: Failed to execute 'replaceState' on 'History': A history\nstate object with URL\n'https://example.com/search?q=cache:rk9HFUZWPrwJ:https://example.com/istanbul-kadikoy+&cd=2&hl=tr&ct=clnk&gl=tr'\ncannot be created in a document with origin\n'https://webcache.googleusercontent.com' and URL\n'https://webcache.googleusercontent.com/search?q=cache:rk9HFUZWPrwJ:https://example.com/istanbul-kadikoy+&cd=2&hl=tr&ct=clnk&gl=tr'.\n\nWhat is problem, is CORS or Routing ?\nMy routing code :\nRouter.pushRoute(props.routeName, { ...Router.query, pn: page })"
] | [
"reactjs",
"routes",
"react-router",
"next.js"
] |
[
"Requesting XLSX file through js to authorized asp.net web api",
"I have ajax calling my web api to get a xlsx file that is generated when it is called. The xlsx file is in a memory stream that I know is correct because I downloaded it straight from the server and had no issue. However when I try to download the file through the browser it says that the file is invalid. I'm using downloadjs to download the data.\n\nHow I return the Stream\n\n public HttpResponseMessage Function_Name() {\n var stream = getStream();\n\n HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);\n\n result.Content = new StreamContent(stream);\n result.Content.Headers.ContentType =\n new MediaTypeHeaderValue(\"application/octet-stream\");\n return result;\n }\n\n\nHow I get the Stream\n\n$.ajax({ url: \"urlToData\", headers: {\n 'Authorization': 'Authorization'\n },\n success: function (data) { download(data, \"test.xlsx\"); } \n});\n\n\nWhen I run this code I get a file however that file does not read in excel. The file is also 15.3 KB where the functioning file downloaded straight from the server is actually 10.0kb"
] | [
"c#",
"jquery",
"ajax",
"asp.net-web-api"
] |
[
"How to make string as an Array Object in JQuery",
"I have got below string values in a variable.\n\nvar mystring = '{\"img_src\":\"/english/images/spa.jpg\",\n \"img_title\":\"Enjoy a refreshing shower at 43,000 feet\",\n \"img_alt\":\"Enjoy a refreshing shower at 43,000 feet\",\n \"img_height\":\"326\",\n \"img_width\":\"980\",\n \"header\":\"Enjoy a refreshing shower at 43,000 feet\",\n \"subheader\":\"One of many groundbreaking amenities\",\n \"bg_color\":\"\",\n \"url_href\":\"1\"}, \n {\"img_src\":\"/english/images/spa1.jpg\",\n \"img_title\":\"Enjoy a refreshing shower at 43,000 feet\",\n \"img_alt\":\"Enjoy a refreshing shower at 43,000 feet\",\n \"img_height\":\"326\",\n \"img_width\":\"980\",\n \"header\":\"Enjoy a refreshing shower at 43,000 feet\",\n \"subheader\":\"One of many groundbreaking amenities\",\n \"bg_color\":\"\",\n \"url_href\":\"1\"}'\n\n\nNow I want to convert this string variable into Array object. So that If I try to access it my function it should behave like an array object. For example.\n\nsome code to Convert(mystring) to an Array Object(myArryObject), then I want to pass it to my function like below\n\n$.fn.liveBanner = function(myArryObject,optional_options) \n { \n //here I want to access my myArryObject as below\n alert(myArryObject[0].img_src) //then it should give \"/english/images/spa.jpg\"\n});\n\n\nPlease suggest using JQuery.\n\nEDIT:\n\nI did the changes as suggested by @Deceze, please see below:\n\n var myString = \"'\"+ $(\"#RotationImages #mainHidden\").attr(\"value\")+\"'\"; \n\n var myArrayobj = jQuery.parseJSON('[' + myString + ']');\n alert(myArrayobj.img_src);\n\n\nthe above code is giving below error\n\nError: uncaught exception: Invalid JSON:'{\"img_src\":\"/english/images/spa.jpg\", \"img_title\":\"Enjoy a refreshing shower at 43,000 feet\",\"img_alt\":\"Enjoy a refreshing shower at 43,000 feet\", \"img_height\":\"326\",\"img_width\":\"980\",\"header\":\"Enjoy a refreshing shower at 43,000 feet\",\"subheader\":\"One of many groundbreaking amenities on the Flight\",\"bg_color\":\"\",\"url_href\":\"1\"}'"
] | [
"jquery"
] |
[
"Jquery Image Gallery with categories",
"I am going to use the Galleriffic jquery plugin to display my images (please look at demo here: http://www.twospy.com/galleriffic/advanced.html\n\nI want to include categories above the gallery, but when each category is clicked I want the image gallery to change dynamically. That meaning, I don't want the page to reload each time a category is clicked, rather I want just the gallery area to change. Is there any suggestions for how to approach this? AJAX perhaps? Any similar code that you have used?"
] | [
"jquery",
"ajax",
"image",
"image-gallery"
] |
[
"How to get image that is within a data attrbute with Webpack 2?",
"I am using .pug templates for my HTML and standard src attributes on my images like so:\n\nimg(src=`../images/${image}`)\n\n\nWhen I run webpack -p, any images defined in the src's of my images are found by Webpack and placed into my dist directory. This is exactly what I would expect to happen.\n\nHowever, I now have a requirement to lazy load my images, so I want to place the reference to the image into a data-src attribute instead of the standard src, like so:\n\nimg(data-src=`../images/${image}` src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')\n\n\nRunning webpack -p again when I do this though, does not grab the images.\n\nIs there any way that I can make Webpack look at non-src attributes to realise that it requires those images as part of the production build?"
] | [
"javascript",
"webpack",
"pug",
"webpack-dev-server",
"webpack-2"
] |
[
"Distinct in Entity framework",
"I have a List of objects that some of them have the same Ids, so I would like to remove those elements that are duplicated. \n\nI tried with something like this:\n\nList<post> posts = postsFromDatabase.Distinct().ToList();\n\n\nBut it doesn't work!\n\nSo I wrote this method in order to avoid the duplicates:\n\npublic List<Post> PostWithOutDuplicates(List<Post> posts)\n {\n List<Post> postWithOutInclude = new List<Post>();\n var noDupes = posts.Select(x => x.Id).Distinct();\n if (noDupes.Count() < posts.Count)\n {\n foreach (int idPost in noDupes)\n {\n postWithOutInclude.Add(posts.Where(x => x.Id == idPost).First());\n }\n return postWithOutInclude;\n }\n else\n {\n return posts;\n }\n }\n\n\nAny ideas of how to improve the performance??\n\nThanx in advance."
] | [
"c#",
".net",
"linq",
"entity-framework",
"distinct"
] |
[
"CListCtrl GetSelectionMark() not return row being selected correctly",
"GetSelectionMark() should return the current selected line, but instead it returns the previous selected item. but using GetNextItem(-1, LVNI_SELECTED)\ncan get the correct answer."
] | [
"c++",
"mfc"
] |
[
"php SQL how to keep data and maybe autoincrement instead of replacing record in a field",
"an sql database 'test' having table 'patients' and within table is a field 'prescription' of datatype varchar (200 max length) currently hosts inputted text and numbers.\n\nI'm able to fetch prescription record from the table and display it, then am able to update it through a textbox which happens to overwrite the record in the field 'prescription.\n\nwhat should I look at doing in order of preserving the record in prescription field, yet write the new one/new prescription? BTW the table row has an 'id' field serving as primary key. \n\nI'm looking at keeping previous prescriptions, whilst writing new ones, and always fetch the most recent one kindof as what it currently does. Later I'll have to look at an option of displaying all available prescriptions for a distinct 'id'. \n\nhere is the code that uses the input 'id' by user to fetch table fields:\nhttp://pastebin.com/gNv881kR\n\nThe below link shows the code that updates the prescription field:\nhttp://pastebin.com/6sq7ZEtp\n\nThanks for replying everyone, but what about other patient's prescriptions within same table. as currently table has column 'id', full_name, 'address, 'email', ... 'prescription'. Also I forgot to tell that id is an aplhanumeric value which eg: 232987M which is governmental ID. should I create another table, include current id to use as primary key to search for records using it in new table, and have prescription column and 'id2' which auto increments and copies patient's actual 'id' to assign the prescription and will later fetch all with that 'id' irrispective of the incremented 'id2' ?"
] | [
"php",
"mysql",
"auto-increment"
] |
[
"regex to match a maximum of 4 spaces",
"I have a regular expression to match a persons name.\n\nSo far I have ^([a-zA-Z\\'\\s]+)$ but id like to add a check to allow for a maximum of 4 spaces. How do I amend it to do this?\n\nEdit: what i meant was 4 spaces anywhere in the string"
] | [
"regex"
] |
[
"How to count nested parenthesis without match?",
"I'm trying to count the total mismatched parenthesis. \n\ninput: text = “(()”\noutput: 1\n\ninput: text = “(())”\noutput: 0\n\ninput: text = “())(”\noutput: 2\n\n\nI have tried the following, but it doesn't work: \n\n\r\n\r\nlet isMatchingBrackets = function(str) {\r\n let stack = [];\r\n let count = 0;\r\n\r\n for (let i in str.length) {\r\n if (str[i] === \"(\") {\r\n stack.push(str[i])\r\n } else if (str[i] === \")\") {\r\n let tem = map.stack(x => x)\r\n if (tem !== \")\") {\r\n count += 1;\r\n } else {\r\n stack.pop();\r\n }\r\n }\r\n }\r\n\r\n return stack.length + count\r\n}\r\n\r\nconsole.log(isMatchingBrackets(\"(()\"))\r\nconsole.log(isMatchingBrackets(\"(())\"))\r\nconsole.log(isMatchingBrackets(\"())(\"))"
] | [
"javascript",
"algorithm"
] |
[
"insertion sort program not working properly",
"public static void insertionSort(int[] arr) {\n\n // each outer loop iteration inserts arr[i] into the correct location of\n // the already-sorted sub-list: arr[0] through arr[i-1]\n\n for (int i = 1; i < arr.length; i++) {\n int valueToInsert = arr[i];\n int loc = 0;\n while (loc < i && arr[loc] < valueToInsert) { \n loc++;\n }\n for (int j = loc; j < i; j++) { \n arr[j+1] = arr[j]; // some issue with this \n // loop as I'm overriding the next element\n }\n arr[loc] = valueToInsert; //// put the value \n //in correct location in sub-list \n } \n }\n\n\nAbove is my insertion sort code, it is not working properly, the sample input is given below \n\ninput [3, 9, 2]\nexpected output is [2, 3, 9]\nBut I'm getting [2, 3, 3]\n\n\nPlease let me more about this problem regarding insertion sort and your quick response is solicited"
] | [
"java",
"arrays",
"insertion-sort"
] |
[
"Remove field reference from content type programmatically (CSOM)",
"the title says it all. how can i programmatically remove a field reference from a content type?\n\nwhat i've tried so far:\n\n public void RemoveField(ClientContext ctx, Web web, ContentType type, Field field) // doesnt do anything\n {\n try\n {\n FieldLinkCollection fields = type.FieldLinks;\n FieldLink remove_field = fields.GetById(field.Id);\n remove_field.DeleteObject();\n ctx.ExecuteQuery();\n }\n catch (Exception ex)\n {\n throw ex;\n }\n }\n\n\nthis doesnt do anything (also no exception). \n\ni've found another way in a forum:\n\ncontentType.FieldLinks.Delete(field.Title);\ncontentType.Update();\n\n\nbut the Delete(field.Title) method doesnt seem to exist in the CSOM.\n\nthx"
] | [
"sharepoint",
"csom"
] |
[
"How to delete multiple users from server in Flutter?",
"I am trying to delete multiple users from server by sending list of user ids but in http delete method doesn't allowed that.so if i want to delete users with ids 1 ,2 and 3 how can i do that in flutter. \nhere is the code:\n\nMap<String, String> requestHeaders = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'application/json',\n 'Authorization': 'Bearer $token'\n }; //bearer is important\n final ids=[];\n ids.add(1);\n ids.add(1);\n var response = await delete(\n Constants.BasicURL + Constants.Users+ids ,\n headers: requestHeaders,\n );"
] | [
"flutter"
] |
[
"How to play a song when mouseover?",
"I'm new on ActionScript so I'm stuck on it. What I need is: play a song when the mouse is over my image. I tried to do this, but I get the erros:\n\nScene 1, Layer 'actions', Frame 1, Line 45 1120: Access of undefined property soundChannel.\nScene 1, Layer 'actions', Frame 1, Line 46 1120: Access of undefined property soundChannel.\nScene 1, Layer 'actions', Frame 1, Line 74 1120: Access of undefined property des_elefante.\n\n\nHere is my code so far:\n\nimport flash.events.MouseEvent;\nimport flash.media.Sound;\nimport flash.net.URLRequest; \nimport flash.media.SoundChannel; \nimport flash.net.URLLoader;\nimport flash.events.*;\nimport flash.display.MovieClip;\n\nvar dragArray:Array = [letraE, letraA,letraI,letraO,letraU];\nvar matchArray:Array = [letraEmatch,letraAmatch,letraImatch,letraOmatch,letraUmatch];\n\nvar currentClip:MovieClip;\nvar startX:Number;\nvar startY:Number;\nmatchArray[0].alpha = 0.2;\nmatchArray[1].alpha = 0;\nmatchArray[2].alpha = 0;\nmatchArray[3].alpha = 0;\nmatchArray[4].alpha = 0;\n\n\n\nfor(var i:int = 0; i < dragArray.length; i++) {\n dragArray[i].buttonMode = true;\n dragArray[i].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDown);\n\n}\n\n\n\n\n\nfunction item_onMouseDown(event:MouseEvent):void {\n currentClip = MovieClip(event.currentTarget);\n startX = currentClip.x;\n startY = currentClip.y;\n addChild(currentClip); //leva o clip pra frente\n currentClip.startDrag();\n stage.addEventListener(MouseEvent.MOUSE_UP, stage_onMouseUp, MouseEvent.MOUSE_OVER);\n}\nfunction fl_play_sound(event:MouseEvent):void{\n\n var sound = new Sound(); \n sound.load(new URLRequest(\"audio_elefante.wav\"));\n soundChannel = new SoundChannel();\n soundChannel = sound.play();\n\n}\nfunction stage_onMouseUp(event:MouseEvent):void {\n stage.removeEventListener(MouseEvent.MOUSE_UP, stage_onMouseUp);\n currentClip.stopDrag();\n var index:int = dragArray.indexOf(currentClip);\n var matchClip:MovieClip = MovieClip(matchArray[index]);\n if(currentClip.hitTestObject(matchClip)) {\n //se a combinação é a certa, ele posiciona a o clip da letra no clip do tracinho\n currentClip.x = matchClip.x;\n currentClip.y = matchClip.y;\n //Desabilita pra arrastar já que é o certo\n currentClip.removeEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDown);\n currentClip.buttonMode = false;\n } else {\n //se a combinação não é a certa, leva o clip da letra de volta pra posição inicial;\n currentClip.x = startX;\n currentClip.y = startY;\n }\n}\n\n\nletraA.addEventListener(MouseEvent.MOUSE_OVER, fl_MouseOverHandler);\nletraI.addEventListener(MouseEvent.MOUSE_OVER, fl_MouseOverHandler);\nletraO.addEventListener(MouseEvent.MOUSE_OVER, fl_MouseOverHandler);\nletraU.addEventListener(MouseEvent.MOUSE_OVER, fl_MouseOverHandler);\nletraE.addEventListener(MouseEvent.MOUSE_OVER, fl_MouseOverHandler);\ndes_elefante.addEventListener(MouseEvent.MOUSE_OVER, fl_play_sound);\n\nfunction fl_MouseOverHandler(event:MouseEvent):void\n{\n // Start your custom code\n // This example code displays the words \"Moused over\" in the Output panel.\n //trace(\"Moused over\");\n // End your custom code\n}\n\n\nI converted my image to button, movieclip and graphic, but nothing changed about the last error. Thank you"
] | [
"actionscript-3",
"flash"
] |
[
"How do I create a \"spacer\" in a C++ class memory structure?",
"The issue\n\nIn a low level bare-metal embedded context, I would like to create a blank space in the memory, within a C++ structure and without any name, to forbid the user to access such memory location.\n\nRight now, I have achieved it by putting an ugly uint32_t :96; bitfield which will conveniently take the place of three words, but it will raise a warning from GCC (Bitfield too large to fit in uint32_t), which is pretty legitimate.\n\nWhile it works fine, it is not very clean when you want to distribute a library with several hundreds of those warnings...\n\nHow do I do that properly?\n\nWhy is there an issue in the first place?\n\nThe project I'm working on consists of defining the memory structure of different peripherals of a whole microcontroller line (STMicroelectronics STM32). To do so, the result is a class which contains a union of several structures which define all registers, depending on the targeted microcontroller.\n\nOne simple example for a pretty simple peripheral is the following: a General Purpose Input/Output (GPIO)\n\nunion\n{\n\n struct\n {\n GPIO_MAP0_MODER;\n GPIO_MAP0_OTYPER;\n GPIO_MAP0_OSPEEDR;\n GPIO_MAP0_PUPDR;\n GPIO_MAP0_IDR;\n GPIO_MAP0_ODR;\n GPIO_MAP0_BSRR;\n GPIO_MAP0_LCKR;\n GPIO_MAP0_AFR;\n GPIO_MAP0_BRR;\n GPIO_MAP0_ASCR;\n };\n struct\n {\n GPIO_MAP1_CRL;\n GPIO_MAP1_CRH;\n GPIO_MAP1_IDR;\n GPIO_MAP1_ODR;\n GPIO_MAP1_BSRR;\n GPIO_MAP1_BRR;\n GPIO_MAP1_LCKR;\n uint32_t :32;\n GPIO_MAP1_AFRL;\n GPIO_MAP1_AFRH;\n uint32_t :64;\n };\n struct\n {\n uint32_t :192;\n GPIO_MAP2_BSRRL;\n GPIO_MAP2_BSRRH;\n uint32_t :160;\n };\n};\n\n\nWhere all GPIO_MAPx_YYY is a macro, defined either as uint32_t :32 or the register type (a dedicated structure).\n\nHere you see the uint32_t :192; which works well, but it triggers a warning.\n\nWhat I've considered so far:\n\nI might have replaced it by several uint32_t :32; (6 here), but I have some extreme cases where I have uint32_t :1344; (42) (among others). So I would rather not add about one hundred lines on top of 8k others, even though the structure generation is scripted.\n\nThe exact warning message is something like:\nwidth of 'sool::ll::GPIO::<anonymous union>::<anonymous struct>::<anonymous>' exceeds its type (I just love how shady it is).\n\nI would rather not solve this by simply removing the warning, but the use of\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-WTheRightFlag\"\n/* My code */\n#pragma GCC diagnostic pop\n\n\nmay be a solution... if I find TheRightFlag. However, as pointed out in this thread, gcc/cp/class.c with this sad code part:\n\nwarning_at (DECL_SOURCE_LOCATION (field), 0,\n \"width of %qD exceeds its type\", field);\n\n\nWhich tells us that there is no -Wxxx flag to remove this warning..."
] | [
"c++",
"c",
"memory-management",
"low-level",
"bare-metal"
] |
[
"How to loop through an array that triggers an click event on each item in the array one at a time",
"I am having trouble with something in my function. I am trying to trigger click events one after another with a short delay between each item of my array...if anybody can explain to me how to fix It and why. I will be very grateful for any help.\n\n\r\n\r\nvar track3 = new Audio();\r\ntrack3.src= 'https://s3.amazonaws.com/freecodecamp/simonSound1.mp3';\r\n\r\nhead= $(\"#head\").click (function (){\r\n $(\"#head\").css (\"background-color\",\"black\");\r\n $(\"#head\").css({ opacity: 0.9});\r\n track3.play ();\r\n setTimeout(function(){\r\n $(\"#head\").css({ opacity: 0.0 });\r\n $(\"#head\").css(\"background-color\",\"\");\r\n }, 300);\r\n});\r\n\r\nshoulders= $(\"#shoulders\").click (function (){\r\n $(\"#shoulders\").css (\"background-color\",\"cyan\");\r\n track3.play();\r\n setTimeout(function() {\r\n $(\"#shoulders\").css(\"background-color\",\"\");\r\n }, 300);\r\n});\r\n\r\nknees= $(\"#knees\").click (function (){\r\n $(\"#knees\").css (\"background-color\",\"mediumPurple\");\r\n track3.play ();\r\n setTimeout(function(){\r\n $(\"#knees\").css(\"background-color\", \"\");\r\n }, 300);\r\n});\r\n\r\ntoes= $(\"#toes\").click (function (){\r\n $(\"#toes\").css (\"background-color\",\"mediumSpringGreen\");\r\n track3.play();\r\n setTimeout(function() {\r\n $(\"#toes\").css(\"background-color\", \"\");\r\n }, 300);\r\n})\r\n\r\nvar round= 0;\r\nvar player= [ ];\r\nvar simon=[ ];\r\nvar pat= [\"head\", \"shoulders\", \"knees\", \"toes\"];\r\n\r\n$(\".start\").click(function (){\r\n simon=[ ];\r\n player=[ ];\r\n round=0;\r\n additionalRound();\r\n})\r\n\r\nfunction additionalRound(){\r\n round ++;\r\n $(\"h2\").html(\"Round:\" +round);\r\n setTimeout(function() {\r\n $(\"h2\").html(\"HEAD, SHOULDERS, KNEES, AND TOES!\");\r\n },2660);\r\n sequence();\r\n}\r\n\r\nfunction sequence (){\r\n simon.push(pat[Math.floor (Math.random ()*4 )]);\r\n blinkerBeats ();\r\n}\r\n\r\nfunction blinkerBeats() {\r\n for (var i = 0; i < simon.length; i++) {\r\n setTimeout(function() {\r\n $(simon[i]).trigger('click');\r\n }, i * 800);\r\n }\r\n}\r\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>"
] | [
"javascript",
"jquery",
"arrays"
] |
[
"When to call WebResponse.Close()",
"WebResponse response;\ntry\n{ \n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n request.Timeout = 20000;\n response = request.GetResponse();\n\n request = (HttpWebRequest)WebRequest.Create(url2);\n response = request.GetResponse();\n}\ncatch(Exception ex)\n{\n //do something\n} \nfinally\n{\n}\n\n\nwhere should response.Close() be called? \n\n\nafter every GetResponse() in try?\nafter last GetResponse() in try - once? \nin finally block?"
] | [
"c#",
".net",
"httpwebresponse"
] |
[
"Reusing django models",
"I have an app with a bunch of models and templates to perform a certain task (it's called a \"user access review\", but that's not important - the app is called \"uar\"). When the users have completed their task, we want to archive the data from the main models into what we're calling \"history\" tables. Those tables are identical in structure to the original \"uar\" tables, but may live in another database or may be in the same database. They will, however, be read-only except by the process that archives them into these history tables, and possibly a task that expires items after a certain number of years. \n\nSince I wanted the exact same model structure but different names, I thought I'd just make an app called \"uar_history\" and symlink the models.py file between the two apps. But when I attempt to syncdb the new models, I get a lot of complaints about the models not validating because of the related_name back link on the foreign keys.\n\nIs there a better approach to this? Should I just make all my archive tables sub-classes of the model classes instead?"
] | [
"python",
"django",
"django-models"
] |
[
"How to split a big Aggregate Root to smaller?",
"I´m developing a domain layer that has a specific Aggregate Root.\nThat aggregate root consists of a Company that has various types of related persons. Something like this:\npublic class Company\n{\n public virtual ICollecion<PersonType01Entity> Person01 {get; private set;}\n public virtual ICollecion<PersonType02Entity> Person02 {get; private set;}\n public virtual ICollecion<PersonType03Entity> Person03 {get; private set;}\n\n public void AddPersonType01(PersonType01Entity p) \n { \n if(Person01.Any(c => c.id == p.id )\n throw new Exception();\n }\n // more code\n}\n\nImagine that I need to do this type of checking for every person type, and other invariants checks. My Aggregatte Root entity became to big and I´m do not know how to split it to be smaller.\nAny suggestions on this?"
] | [
"design-patterns",
"domain-driven-design"
] |
[
"multiple updates in one submit in SPA page",
"I have a web page written in ASP.net where it finds a list of employees, displays them in a listview and allow the user to change different statuses for each employee.\n\nOn each row I have employee information like name, date of birth, address and then 4 status fields that are displayed as checkboxes and a comment field where the user can type a comment explaining why they changed a certain status.\n\nCurrently in Listview, there is an edit, delete button when they click edit, the checkboxes and text field are displayed the user updates them and click save.\n\nasp.net will do a postback to save the changes for this row and then fetches the data again to refresh the list.\n\nThe problem I am having is the list is very large (more than 3000 names), so I am using pagination to show 50 to 100 names on each page. This is still a big performance problem because after every line update a query needs to run to fetch those names again, and with ASP.NET the server is generating the html and passing everything to the browser.\n\nThe customer wants the page to be mobile friendly too, so I am thinking to redo the page using Angular on front end with web-api or mvc.net on back end that returns JSON. \n\nMy question is there an easy way to do this and allow the user to change the status for multiple employees on the same page at once and then click one submit to update all the changes? if I do it this way, there will be less queries to run and it will be faster for the user because they don't have to wait after every line update.\n\nAny examples will be greatly appreciated, unless there is a different way to implement this, in this case please let me know."
] | [
"asp.net",
"angularjs",
"asp.net-mvc"
] |
[
"Elasticsearch 2.3 Delete all documents in a type by query using PHP LIbrary",
"I want to be able to delete documents by query using the elasticsearch php library. I actually ideally want to delete all documents in my type.\nI can achieve this using a normal curl XDELETE request in sense, however I cant get it to work using elastic search's PHP library.\n\nYes I have installed the delete-by-query plugin hence why raw request works.\n\nmy current code:\n\n$params = [\n 'index' => 'sanctions_lists',\n 'type' => $listName,\n 'body' => [\n 'query' => [\n 'match_all' => []\n ]\n ]\n];\nreturn $this->delete($params);\n\n\nresults in \n\n\n InvalidArgumentException in Client.php line 1440:\n id cannot be null.\n\n\nFrom my error message (ID cannot be null) it appears delete by query could be a limitation of the php library Only allowing deletes by id. \n\nWould be a bit annoying if I have to execute raw HTTP request for this function inside my app when the php library has been really good for my other queries in the app.\n\nQuestion Summary\n\nIs there a workaround to delete by query using the elasticsearch php library without touching library code?\n\nGoes without saying but thanks to anyone who takes any time to view and help with my question. Cheers.\n\nEdit\n\nIncase it helps im using:\n\nelasticsearch php library version v2.1.5"
] | [
"php",
"elasticsearch",
"elasticsearch-plugin"
] |
[
"How make http on android emulator on MacBook m1",
"How can make http request on emulator MacBook m1 ?\nlocalhost:3000 doesn't work on this emulator. On iOS emulator works well.\nAny idea ?\nThank you!"
] | [
"http",
"request",
"android-emulator"
] |
[
"Where can I find an ASP.NET Webforms-compatible chat client with hooks to add additional functionality?",
"I have a client looking to add chat functionality to their Webforms-based site. They would like the following additional features (beyond the usual chat stuff):\n\n\nWhen a client conversation is started, the customer service rep is presented with a view of the order the customer is inquiring about. (As determined by the page on which the customer clicked the chat button.)\nAll chat transcripts are logged and retrievable. (The client would like to allow both the customer and customer service rep to view chat transcripts.)\n\n\nTechnical details:\n\n\nThe site's written in ASP.NET 4 \nMust be IE6 compatible\n\n\nBased on these requirements, can anyone recommend a vendor (or that my company should roll its own)?"
] | [
"c#",
"asp.net",
"webforms",
"chat"
] |
[
"Why is SimpleImputer in ColumnTransformer creating additional Columns?",
"I am following the machine learning book from Aurelion Geron.\nI am experimenting with the ColumnTransformer class. When I include SimplerImputer, an additional columns was created. I understand that SimplerImputer is for filling up missing value in column total_bedrooms (column index 4 in result) , hence I am not clear why it is adding new column (column index: 10) in result.\nWhen i do not include\nthe SimplerImputer from ColumnTransformer, but create an instance, and fit_transform the output of the ColumnTransformer, i will not get the additional column. Please advise.\ncategory_att = X.select_dtypes(include='object').columns\nnum_att = X.select_dtypes(include='number').columns\n\ntransformer = ColumnTransformer(\n [\n ('adder', AttributeAdder(), num_att ),\n ('imputer', SimpleImputer(strategy='median'), ['total_bedrooms']),\n ('ohe', OneHotEncoder(), category_att)\n ],\n remainder = 'passthrough'\n)\n\nCustom Class for adding two new feature/columns\nclass AttributeAdder(BaseEstimator, TransformerMixin):\n \n def __init__(self, add_bed_room = False):\n self.add_bed_room = add_bed_room\n \n def fit(self,y=None):\n return self\n \n def transform(self,X,y=None):\n \n room_per_household = X.iloc[: , t_room ] / X.iloc[: , t_household ]\n population_per_household = X.iloc[: , t_population ] / X.iloc[: , t_household ]\n return np.c_[X,room_per_household,population_per_household]\n\nResults"
] | [
"python",
"scikit-learn"
] |
[
"Have ReSharper keep 'using System;' when optimizing usings",
"I was wondering if there is some option to keep ReSharper from removing just the using System; directive? Perhaps this is configurable somewhere?\n\nAlso, is there a way to have ReSharper sort the remaining directives just as Visual Studio 2008 does it (alphabetically, I think)?\n\nThanks."
] | [
"c#",
"visual-studio-2008",
"resharper",
"using-directives"
] |
[
"storing form data using ajax request",
"I'm trying to store my form data using ajax but it gives me error.\nI'm submitting form data in js file which calls another php file to perform insert operation.\nhere is my code:\n\n <button id=\"submit\" class=\"btn btn-primary\" type=\"submit\" onclick=\"myFunction()\" >Create an Account</button>\n\n\nclicking on that button it calls the js file\nserve.js\n\n function myFunction(){\n\n\n var name = document.getElementById(\"firstName\").value;\n var lname = document.getElementById(\"lastName\").value;\n var mail = document.getElementById(\"email\").value;\n var password =document.getElementById(\"password\").value;\n\n var confpass= document.getElementById(\"passwordConfirmation\").value;\n\n // var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;\n if(password != confpass)\n {\n alert ('password doesnot match!');\n }\n\n // var form_data = $('#edit_user').serialize();\n var datastring= 'name1=' + name + 'name2=' + lname +'email='+mail+ 'pass='+password;\n\n $.ajax({\n url: \"learnapi.php\",\n type: \"get\",\n dataType: \"json\",\n data: {type: \"signup\", datastring:datastring },\n //type: should be same in server code, otherwise code will not run\n ContentType: \"application/json\",\n success: function (response) {\n alert(JSON.stringify(response));\n },\n error: function (err) {\n alert(JSON.stringify(err));\n }\n });\n};\n\n\nThrough ajax request it perform insert operation\nlearnapi.php\n\n<?php\n header('Access-Control-Allow-Origin: *');\nmysql_connect(\"localhost\",\"root\",\"\");\nmysql_select_db(\"learnapp\");\nif(isset($_GET['type']))\n{\n $res = [];\n\n\n if($_GET['type'] ==\"signup\"){\n $name = $_GET ['name1'];\n $lname = $_GET['name2'];\n\n $passW = $_GET['pass'];\n // $passW1 = $_GET['Pass1'];\n $mail = $_GET ['email'];\n\n\n\n $query1 = \"insert into signup(firstname,lastname,password,email) values('$name','$lname','$passW','$mail')\";\n $result1 = mysql_query($query1);\n\n if($result1)\n {\n $res[\"flag\"] = true;\n $rest[\"message\"] = \"Data Inserted Successfully\";\n }\n else\n {\n $res[\"flag\"] = false;\n $rest[\"message\"] = \"Oppes Errors\";\n }\n } \n\n\nelse{\n$res[\"flag\"] = false;\n$rest[\"message\"] = \"Invalid format\";\n }\n\n echo json_encode($rest);\n} \n?>\n\n\nIt gives me error as:"
] | [
"javascript",
"php",
"jquery",
"ajax"
] |
[
"MathJax and MathML displayed 'Unknown node type: declare' on IE",
"I'm studying on MathML using MathJax since for displaying mathematic expressions on IE and Chrome. Any way... when I try to using 'declare' tag like follwing,\n\n<head>\n<meta charset=\"UTF-8\">\n<title>Mixed Markup</title>\n\n<script type=\"text/x-mathjax-config\">\n MathJax.Hub.Config({\n MathML: {\n extensions: [\"content-mathml.js\"]\n }\n });\n</script>\n\n<script type=\"text/javascript\" async\n src=\"https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\">\n</script>\n\n\n\n\n<body>\n <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n <declare>\n <ci> A </ci>\n <vector>\n <ci> a </ci>\n <ci> b </ci>\n <ci> c </ci>\n </vector>\n </declare>\n </math>\n</body>\n\n\nIE shows it as\n\nUnknown node type: declare\n\nSo... what can I do to use declare tag??"
] | [
"html",
"mathjax",
"mathml"
] |
[
"How can I make a custom 503 page on OpenShift?",
"I would like to change the default openshift 503 page that occurs when I am deploying my app. I did find this solution, but I am not sure where to put the python script.\n\nI only have the PHP 5.4 application running (no cartridges), if that matters."
] | [
"openshift"
] |
[
"Running jar with -Dloader.path= works, but not application.properties loader.path",
"I have an external properties file under /config/application.properties which I retrieve properties from. When I run my jar, it is able to pick up certain properties from it, (e.g. server.port=8083)\n\nThis is the structure of my files/folders:\n\nProjectFolder\n |\n +-- mytool.jar\n | \n +-- config\n | | \n | +-- application.properties\n | \n +-- lib\n | | \n | +-- externalJar.jar\n\n\nNow, the problem is that I need the property \"loader.path\" from the external properties file, all other properties are being loaded correctly except for loader.path when I run the jar with:\n\njava -jar mytool.jar\n\n\nInside the external application.properties contains:\n\nspring.servlet.multipart.enabled=false\nserver.port = 8083\nlogging.file = /someplace/\nloader.path=lib\n\n\nSince it is not loading the externalJar.jar, I encounter classNotFoundExceptions.\n\nHowever, what's strange is that when I start the app with:\n\njava -Dloader.path=lib -jar mytool.jar\n\n\nEverything works as expected.\n\nAm I missing something with the application.properties file?\nI have tried using the full path: \n\nloader.path=/home/me/ProjectFolder/lib\n\n\nbut that didn't work either. \nI am confident that the application.properties is being read because the server.port number showing up on boot is the one I specifically specified.\n\nI've changed the project to use the PropertiesLauncher in Maven.\nMANIFEST.MF\n\nManifest-Version: 1.0\nImplementation-Title: mytool\nImplementation-Version: 0.0.1-SNAPSHOT\nBuilt-By: giraffepoo\nImplementation-Vendor-Id: com.sap\nSpring-Boot-Version: 2.1.3.RELEASE\nMain-Class: org.springframework.boot.loader.PropertiesLauncher\nStart-Class: com.sap.mytool\nSpring-Boot-Classes: BOOT-INF/classes/\nSpring-Boot-Lib: BOOT-INF/lib/\nCreated-By: Apache Maven 3.3.9\nBuild-Jdk: 1.8.0_201\nImplementation-URL: https://projects.spring.io/spring-boot/#/spring-bo\n ot-starter-parent/mytool\n\n\nIf someone could point me in the right direction, your help is greatly appreciated. Thanks!\n\nNote:\nNot sure if related, but the externalJar.jar is utilized immediately when the application starts up in the overridden method: contextInitialized"
] | [
"java",
"spring",
"spring-boot",
"jar"
] |
[
"Why is my Android app camera preview running out of memory on my AVD?",
"I have yet to try this on an actual device, but expect similar results.\nAnyway, long story short, whenever I run my app on the emulator, it crashes due to an out of memory exception.\n\nMy code really is essentially the same as the camera preview API demo from google, which runs perfectly fine.\n\nThe only file in the app (that I created/use) is as below-\n\npackage berbst.musicReader;\n\nimport java.io.IOException;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.hardware.Camera;\nimport android.os.Bundle;\nimport android.view.SurfaceHolder;\nimport android.view.SurfaceView;\n\n/*********************************\n* Music Reader v.0001\n* Still VERY under construction.\n* @author Bryan\n*\n*********************************/\n\npublic class MusicReader extends Activity {\nprivate MainScreen main;\n @Override\n //Begin activity\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n main = new MainScreen(this);\n setContentView(main);\n\n }\n\nclass MainScreen extends SurfaceView implements SurfaceHolder.Callback {\n SurfaceHolder sHolder;\n Camera cam;\n\n MainScreen(Context context) {\n super(context);\n\n //Set up SurfaceHolder\n sHolder = getHolder();\n sHolder.addCallback(this);\n sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);\n }\n\n public void surfaceCreated(SurfaceHolder holder) {\n // Open the camera and start viewing\n cam = Camera.open();\n try {\n cam.setPreviewDisplay(holder);\n } catch (IOException exception) {\n cam.release();\n cam = null;\n }\n }\n\n public void surfaceDestroyed(SurfaceHolder holder) {\n // Kill all our crap with the surface\n cam.stopPreview();\n cam.release();\n cam = null;\n }\n\n public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {\n // Modify parameters to match size.\n Camera.Parameters params = cam.getParameters();\n params.setPreviewSize(w, h);\n cam.setParameters(params);\n cam.startPreview();\n }\n\n}\n\n\n}"
] | [
"android",
"android-emulator"
] |
[
"MySQL find_in_set() function skips an item in the set",
"I'm having a very strange issue with the MySQL find_in_set() function. Three tables, as follows. The query at the bottom is looking for all users whose positions are listed in activity_assoc for the particular activity. In other words: \"Which people have this activity?\".\n\nIt should find all three users; but for some reason it skips the position in the middle, and only returns user 1 and 3. (Actual data has more people. It is clearly skipping a particular position -- as though \"DOP\" were not on the list in activity_assoc.positions.)\n\nusers_master\n\nid first_name last_name position_id\n----------------------------------------------------------- \n1 Eblis O'Shaugnessy 13\n2 JimmyJojo Shamadou 20\n3 Bob Justbob 25\n\n\npositions\n\nid position abbreviation\n---------------------------------------------\n13 Director of Stuff DOS\n20 Director of Peoples DOP\n25 Director of Ideas DOI\n\n\nactivity_assoc\n\nid activity positions\n----------------------------------------------\n47 Make Things Happen DOS,DOP,DOI\n\n\nSELECT DISTINCT `users`.`id`, `users`.`first_name`, `last_name`, `position`, `activity_assoc`.`positions`\nFROM `activity_assoc`, \n ( \n SELECT `users_master`.*, `positions`.`abbreviation` AS `position`\n FROM `users_master` LEFT JOIN `positions` ON `users_master`.`position_id` = `positions`.`id` \n ) AS `users`\nWHERE \n `activity_assoc`.`activity` = 'Make Things Happen' AND\n find_in_set( `users`.`position`, `activity_assoc`.`positions` )\n\n\nIf I change the find_in_set line to the following, it works fine.\n\n`users`.`position` IN ( 'DOS','DOP','DOI' )\n\n\nUPDATE: The below part is now fixed:\n\nYou may have noticed the cast() function. If I leave that off I get an \"illegal mix of collations\" error. Most tables in the DB are utf8_general_ci, but the activity_assoc table was utf8_unicode_ci. I ran the following in it yesterday to try and fix this:\n\nALTER TABLE `activity_assoc` COLLATE `utf8_general_ci`;\n\n\nThe Table Inspector in MySQL Workbench now shows it as utf8_general_ci collation, but actually running the query seems to act as though it's still utf8_unicode_ci. (To be clear: Table Inspector currently shows all three tables to be utf8_general_ci collation.) I can't tell if these are two separate problems or the same problem."
] | [
"mysql",
"sql"
] |
[
"how to get results into array from unix commands",
"I'm trying to get the dump of each file into an array from a unix command in a Perl script. below is the error I'm getting. Could anyone please help me fix this issue?\n\nCan't locate object method \"cat\" via package \"C:/prac/cmm_ping.txt\" (perhaps you forgot to load \"C:/test/cmm_ping.txt\"?) at fandd.pl line 25.\n\nbelow is my program\n\n#!/usr/bin/perl\n\nuse warnings;\n\n@files=glob(\"C:/prac/*\");\n\nforeach $file (@files){\n @data=system(cat $file);\n foreach $line (@data){`\n print $line;\n }\n}"
] | [
"arrays",
"perl",
"unix",
"cat"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.