texts
sequence | tags
sequence |
---|---|
[
"Merge duplicates into one row and sum up values using php",
"I have a table that hows the following rows...\n\nID | TITLE | ARTIST | ADDED | HITS | HITS THIS WEEK\n--------------------------------------------------------------------------------\n7505 | Track 2 | Artist 1 | 2009-08-24 10:32:41 | 1539 | 2\n7483 | Track 2 | Artist 1 | 2009-08-23 16:58:35 | 1450 | 3\n7324 | Track 1 | Artist 1 | 2009-08-14 11:28:18 | 5291 | 1\n7320 | Track 1 | Artist 1 | 2009-08-14 10:24:17 | 2067 | 1\n\n\nWhat I want to do is is have the the duplicates add up the hits and hits this week and display as one row.\n\nI want to fetch the mysql data as it is (with the duplicates), and then using php i wanna sum up the duplicates as one row for echo'ing.\n\nCan someone tell me how I would go about this?\n\nEDIT:\n\nHeres my current sql query...\n\nSELECT `files`.`file_id` , `files_meta`.`title` , `files_meta`.`artists` , `files`.`added` , `files`.`uniquehits` , `files`.`uniquehits_week` , `files_meta`.`filename`\nFROM promo_artists\nINNER JOIN promo_files ON promo_artists.id = promo_files.artist_id\nINNER JOIN files ON files.file_id = promo_files.file_id\nINNER JOIN files_meta ON files.file_id = files_meta.file_id\nWHERE username = '$username' ORDER BY `files`.`added` DESC"
] | [
"php",
"mysql"
] |
[
"MongoDb cannot get result from $ifNull",
"Am using the following script to update quotes as escaped characters in strings that are held in a 4 String array and am unable to get the $ifnull to work. Have tried various forms and the latest is:\n\nvar myCursor = db.collection.Fence.find( { \"properties.d.v\" : { $regex : '.*\".*'} } );\n\nwhile (myCursor.hasNext())\n{\n printjson( myCursor.next() );\n var fence = myCursor.next();\n var test;\n\n test = { $ifNull: [ fence.properties.d.v[0], \"null\" ] }\n print ( \"0: \", test );\n $cond: [ { $eq: [ test, \"null\" ] }, fence.properties.d.v[0], fence.properties.d.v[0].replace( '\"', '\\\"' ) ];\n test = { $ifNull: [ fence.properties.d.v[1], \"null\" ] }\n print ( \"1: \", test );\n $cond: [ { $eq: [ test, \"null\" ] }, fence.properties.d.v[1], fence.properties.d.v[1].replace( '\"', '\\\"' ) ];\n test = { $ifNull: [ \"fence.properties.d.v[2]\", \"null\" ] }\n print ( \"2: \", test );\n $cond: [ { $eq: [ test, null ] }, fence.properties.d.v[2], fence.properties.d.v[2].replace( '\"', '\\\"' ) ];\n test = { $ifNull: [ \"fence.properties.d.v[3]\", \"null\" ] }\n print ( \"3: \", test );\n $cond: [ { $eq: [ test, null ] }, fence.properties.d.v[3], fence.properties.d.v[3].replace( '\"', '\\\"' ) ];\n\n db.au.com.bluedot.application.model.geo.Fence.update( { _id : fence._id }, fence );\n}\n\n\nEven when the v[1] is null, the test variable still outputs the following from the print statement:\n\n1: [object Object]\n\n\nThe following error is then returned from the replace statement:\n\n2015-12-24T10:54:14.301+1100 TypeError: Cannot call method 'replace' of null\n\n\nIf there is a better or easier way to find and escape the quotes within MongoDb, would be happy to know."
] | [
"arrays",
"mongodb",
"null",
"ifnull"
] |
[
"Image height and width getting swapped when read using opencv imread",
"When I read an image using opencv imread function, I find its height and width being swapped as what it should be. Like my original image is of dimensions (610 by 406) but on being read using opencv::imread function, its dimensions are 406 by 610. Also, if I rotate my original image before passing it to the function then also, no change. The image read still has original dimensions.\n\nPlease see example code and images for clarification:\nSo, below I have provided the input images: one is original and second one is rotated (I rotated it using windows rotate command, by right-clicking and selecting 'rotate right'). Output I get for both the images is same. It seems to me that rotating image did not actually change its shape. I think so because, when I try to put the rotated image here then also, it was showing the un-rotated version of it only (in the preview) so, I had to take a screen-capture of it and then, paste it here.\n\nThis is the code:\n\nimport cv2\nimport numpy as np\nimport sys\nimport os\n\nimage = cv2.imread(\"C:/img_8075.jpg\")\nprint \"image shape: \",image.shape\ncv2.imshow(\"image\",image)\ncv2.waitKey(0)\nimage2 = cv2.imread(\"C:/img_8075_Rotated.jpg\")\nprint \"image shape: \",image2.shape\ncv2.imshow(\"image\",image2)\ncv2.waitKey(0)\n\n\nThe result I get for this is: image shape: (406,610,3)\n image shape: (406,610,3)\nfor both the images.\n\nI am unable to paste input/output pictures here since, it says you should have '10 reputations' and I have just joined.\nAny suggestions would be helpful. thanks!"
] | [
"python",
"opencv",
"imread"
] |
[
"Blur content behind div tag when background centred",
"I know this has been asked before and I have been able to blur content behind a div tag, but when the background is centred, Blur.js doesn't pick up that the background has been centred and continues to blur it as if the background was the full sized image.\n\nThe problem can be seen here: http://home.josephftaylor.com/cadets/"
] | [
"jquery",
"html",
"css",
"blur"
] |
[
"GWT Background Study For Project help!",
"I am currently doing a project on GWT and in the background study, I need to perform research on GWT. I have included many things which I will list below. Can anyone point out something that I may be missing or what other interesting thing concerning GWT I can include? The following is a list of all the topics that are currently included:\n\n\nGWT Java to JavaScript Compiler\nDeferred Binding \nJSNI (JavaScript Native Interface) \nJRE Emulation Library \nGWT-I18N (Internationalization and Configuration tools) \nGWT’s XMLParser \nWidgets and Panels \nCustom Composite Widget \nEvent and Listeners\nStyling through CSS \nGWT History Management \nGWT Hibernate Integration (through GLead) \nMVP (Model-View-Presenter) for GWT through Model View Presenter Application \nController and Event Bus\nServer Calls using RPC and request builder\nComet \nSerialization in GWT\nJSON (JavaScript Object Notation)\nTesting Web Application with GWT\nJUnit Benchmarking Selenium\nFurther work in GWT such as Ext-GWT and smart GWT"
] | [
"gwt"
] |
[
"bookshelf and knex initialization error",
"I am trying to setup a mysql connection in node js using bookshelf and knex. This is my setup:\n\nvar knex = require('knex')({\nclient: 'mysql',\n connection: {\n host : '127.0.0.1',\n user : 'my_user',\n password : 'my_password',\n database : 'my_db',\n charset : 'utf8'\n }\n});\nvar DB = require('bookshelf')(knex);\nmodule.exports.DB = DB;\n\n\nI get the following error:\n\nError: [object KnexClient] is not a valid Knex client, did you misspell it?\n at new Knex (/Users/arenduchintala/Projects/MacaronicWebApp/node_modules/bookshelf/node_modules/knex/knex.js:48:17)\n at new Bookshelf (/Users/arenduchintala/Projects/MacaronicWebApp/node_modules/bookshelf/bookshelf.js:43:14)\n at Bookshelf (/Users/arenduchintala/Projects/MacaronicWebApp/node_modules/bookshelf/bookshelf.js:37:14)\n at Object.<anonymous> (/Users/arenduchintala/Projects/MacaronicWebApp/db.js:11:37)\n at Module._compile (module.js:434:26)\n at Object.Module._extensions..js (module.js:452:10)\n at Module.load (module.js:355:32)\n at Function.Module._load (module.js:310:12)\n at Module.require (module.js:365:17)\n at require (module.js:384:17)\n at Object.<anonymous> (/Users/arenduchintala/Projects/MacaronicWebApp/model.js:1:72)\n at Module._compile (module.js:434:26)\n at Object.Module._extensions..js (module.js:452:10)\n at Module.load (module.js:355:32)\n at Function.Module._load (module.js:310:12)\n at Module.require (module.js:365:17)\n at require (module.js:384:17)\n\n\nLooks like the line : require('bookshelf')(knex) throws an error."
] | [
"bookshelf.js",
"knex.js"
] |
[
"Setting content type \"application/pdf\" in Groovy RESTClient / HTTPBuilder",
"I'm using Groovy's RESTClient/HTTPBuilder library to send GET and POST requests to a webservice. One resource requires a PDF with content type application/pdf. The response will be an XML.\n\nRequest --> POST application/pdf\nResponse <-- application/xml\n\nI have tried the following:\n\ndef client = new RESTClient(url)\nclient.post(\n uri: url,\n body: new File('C:/temp/test.pdf').bytes,\n requestContentType: 'application/pdf'\n)\n\ndef client = new RESTClient(url)\nclient.setContentType('application/pdf')\nclient.post(\n uri: url,\n body: new File('C:/temp/test.pdf').bytes,\n)\n\n\nBoth variants produce: \n\n\n No encoder found for request content type application/pdf\n\n\nAs far as I have understood the library doesn't support application/pdf by default.\n\nHow can I implement the above?\n\nUpdate from 2015-10-15 after answer by @opal \n\nThe following code snippet at least puts the PDF into the request body. However I cannot see the Content-type: application/pdf in the POST request. Also the server rejects the request with \"Invalid mime type\".\n\nclient.encoder.putAt('application/pdf', new MethodClosure(this, 'encodePDF'))\nresponse = client.post(\n uri: url,\n body: new File('C:/temp/test.pdf'),\n requestContentType: 'application/pdf'\n)\n\nHttpEntity encodePDF(File pdf) {\n new FileEntity(pdf)\n}"
] | [
"rest",
"groovy",
"content-type",
"httpbuilder"
] |
[
"VB.Net thread seems to be running twice giving file access problems",
"I have some very basic code that takes a list of strings and a new thread is created per string.\n\nThe thread then writes a file named with the string so should be unique but I get access violations.\n\nI try the debugger option in VS 2010 and it doesn't give me the file access problems when I step through but it writes two lines per loop so I am assuming it still has a problem with running the thread twice\n\nCode to call the thread:\n\nFor Each x In x_list\n Dim trd as new Thread(DirectCast(Sub() tp(x), ThreadStart))\nNext\n\n\nCode for thread:\n\nPrivate Sub tp(ByVal x_in As String)\n Dim res_file As New StreamWriter(\"C:\\result_\" + x_in + \".txt\", True)\n For i = 1 to 5\n res_file.WriteLine(DateTime.Now.ToString)\n Next\n res_file.Close()\nEnd Sub"
] | [
"vb.net",
"multithreading",
"file-io"
] |
[
"How to listen for ICMP packets?",
"I'm working on a two part application where one side sends ICMP packets and the other side listens for the ICMP packets and takes action when it receives them. The problem is, I'm not sure how to keep the listener alive indefinitely (just want it sitting there in a loop only taking action when it receives a packet).\n\nCurrently, I'm able to use the go-fastping library and can send and receive packets if it's a two way communication (I send it, they respond, I process the remote response). The question is how do I make this asymmetrical?\n\nMy attempt at a listener was:\n\nfor {\n conn, err := icmp.ListenPacket(\"ip4:icmp\", \"192.168.1.8\")\n if err != nil {\n fmt.Println(err)\n }\n}\n\n\nbut this doesn't work. My logic here was that I want a while true loop to keep the listener alive (in this case that's the for {), then I listen for new packets with ICMP's ListenPacket but I don't seem to be getting anything using this approach. \n\nAny ideas or help would be greatly appreciated. Thanks in advance for your time and assistance."
] | [
"sockets",
"go",
"network-programming",
"listener",
"icmp"
] |
[
"Outlook.com makes text clickable",
"This is my send mail: \nWhen I manually type exact the same text it does not become clickable\n\nWhen I send a mail from my template to my hotmail account my text become clickable/blue but there is no hyperlink is there anyway to fix this?\n\nNote: This is not happening with any other mail client\n\nEdit: Bug is in all browsers so its not a plug-in / add-on that makes this happen."
] | [
"hotmail",
"outlook.com"
] |
[
"How to avoid shipping libtool .la file into build package?",
"Below is makefile:\n\nlibdir=/usr/lib/test/\n\nlib_LTLIBRARIES = libmain.la\n\nlibmainla_SOURCES = main.c\nlibmain_la_LDFLAGS = -avoid-version\n\n\nWhen i built the package, libmain.la file also shipped along with the libmain.so into the package. \n\nCould you please let me know how to avoid shipping of .la file?"
] | [
"c",
"linux"
] |
[
"Getting blank page after publishing react app on godaddy",
"My app is working fine on localhosthost but when I run npm run build and deploy the build folder to godaddy in a subdirectory, it displays a blank page with no errors in the console. I've read some other people having the same issue and I've tried setting \"homepage\": \".\" in package.json which hasn't changed anything and I've also tried changing the BrowserRouter basename prop but this also hasn't changed anything (here's the URL I want to publish the app to if it helps at all https://www.harryh.tech/projects/Web_Dev_Quiz/index.html and the app uses react-router and firebase, not sure if either of these could be causing an issue). If anyone has any ideas how to fix this issue I would be super grateful thanks. \n\nindex.js\n\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { AuthProvider } from \"./components/Context/Auth\";\nimport { BrowserRouter as Router, Switch, Route } from \"react-router-dom\";\n\n\nconst Root = () => {\n return (\n <Switch>\n <PrivateRoute exact path=\"/\" component={App} />\n <Route exact path=\"/register\" component={Register} />\n <Route exact path=\"/login\" component={Login} />\n </Switch>\n );\n};\n\nReactDOM.render(\n <AuthProvider>\n <Router basename={process.env.PUBLIC_URL}>\n <Root />\n </Router>\n </AuthProvider>,\n document.getElementById(\"root\")\n);\n\n\npackage.json\n\n{\n \"name\": \"WebDevQuiz\",\n \"homepage\": \"https://www.harryh.tech/projects/Web_Dev_Quiz\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"firebase\": \"^7.1.0\",\n \"md5\": \"^2.2.1\",\n \"react\": \"^16.10.2\",\n \"react-color\": \"^2.17.3\",\n \"react-dom\": \"^16.10.2\",\n \"react-router-dom\": \"^5.1.2\",\n \"react-scripts\": \"3.2.0\",\n \"semantic-ui-react\": \"^0.88.1\"\n },\n \"scripts\": {\n \"start\": \"react-scripts start\",\n \"build\": \"react-scripts build\",\n \"test\": \"react-scripts test\",\n \"eject\": \"react-scripts eject\"\n },\n \"eslintConfig\": {\n \"extends\": \"react-app\"\n },\n \"browserslist\": {\n \"production\": [\n \">0.2%\",\n \"not dead\",\n \"not op_mini all\"\n ],\n \"development\": [\n \"last 1 chrome version\",\n \"last 1 firefox version\",\n \"last 1 safari version\"\n ]\n }\n}"
] | [
"reactjs",
"npm",
"deployment",
"build",
"react-router"
] |
[
"Finding a list of un-compilable packages",
"If I make a lot of modifications to tables in Oracle. Is there a way to have a list of packages that don't compile anymore?\n\nI can easely get the list of packages from the list of tables that I changed, but I wonder if it's possible to get everything that isn't compiling."
] | [
"sql",
"oracle"
] |
[
"C++ Wrong answer in code chef",
"Problem: http://www.codechef.com/problems/LEBOMBS\n\nI have tried every single test case that come to my mind. But it still gives a wrong answer. I don't know why.\nPlease point out if there's any error in my code. This is my code.\n\n#include <iostream>\nusing namespace std;\nint main() {\n int t, i, total, n;\n char a[1001];\n cin >> t;\n while (t--) {\n i = 0;\n cin >> n;\n total = n;\n cin >> a;\n while (i < n) {\n if (a[i] == '1') {\n if (i == '0')\n total -= 2;\n\n else if (i == 1) {\n if (a[i - 1] == '1')\n total--;\n else\n total -= 3;\n } else if (i > 1 && i < n - 1) {\n if (a[i - 1] == '1')\n total--;\n else if (a[i - 2] == '1')\n total -= 2;\n else\n total -= 3;\n } else {\n if (a[i - 1] == '1')\n ;\n else if (a[i - 2] == '1')\n total--;\n else\n total -= 2;\n }\n }\n i++;\n }\n if (total < 0)\n total = 0;\n cout << total << \"\\n\";\n }\n\n return 0;\n}\n\n\nP.S. If you see the code, there is a line that says \"if(total<0)total=0;\" that is for the case when the number of buildings is equal to 1 or 2, because that case gave the wrong answer for the code that I wrote, but after that it gives a wrong answer. Please help.\n\nAnd is there any way about how do I think a test case that might be violating my code for future reference?"
] | [
"c++"
] |
[
"Why mangled names found within an exe?",
"I have an MS C/C++ statically linked release exe (no debug info on it), that does not export any symbol, but when browsing it with a hex viewer I see things like \n\n.?AVElxInterface@@\n.?AV?$CBufferRefT@H@@\n.?AV?$CBufferT@H@@\n.?AV?$CBufferRefT@PAVElxInterface@@@@\n\n\nof course they are the mangled names of certain classes/members provided by the internal C++ modules.\n\nwhy are they there? how can avoid exposing them?"
] | [
"c++",
"linker",
"name-mangling"
] |
[
"MapClustering not rendering String.valueof(cluster.getSize)",
"I am using MapCustomClustering to show images on the map. The Cluster Icon also shows the number of items in the cluster but it doesn't show in mine. I am loading data from Parse cloud. The example one renders cluster.getSize() but in mine it doesn't work.\n\n @Override\n protected void onBeforeClusterRendered(final Cluster<MapPosts> cluster, final MarkerOptions markerOptions) {\n // Draw multiple people.\n // Note: this method runs on the UI thread. Don't spend too much time in here (like in this example).\n final List<Drawable> profilePhotos = new ArrayList<>(Math.min(4, cluster.getSize()));\n final int width = mDimension;\n final int height = mDimension;\n int i = 0;\n for (MapPosts p : cluster.getItems()) {\n // Draw 4 at most.\n i++;\n Picasso.with(getApplicationContext())\n .load(String.valueOf(p.profilePhoto))\n .into(new Target() {\n @Override\n public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {\n Drawable drawable = new BitmapDrawable(getResources(), bitmap);\n drawable.setBounds(0, 0, width, height);\n profilePhotos.add(drawable);\n MultiDrawable multiDrawable = new MultiDrawable(profilePhotos);\n multiDrawable.setBounds(0, 0, width, height);\n mClusterImageView.setImageDrawable(multiDrawable);\n Bitmap icon = mClusterIconGenerator.makeIcon(String.valueOf(cluster.getSize()));\n markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));\n }\n\n @Override\n public void onBitmapFailed(Drawable errorDrawable) {\n }\n\n @Override\n public void onPrepareLoad(Drawable placeHolderDrawable) {\n\n }\n });\n if (profilePhotos.size() == 4) break;\n }\n\n }"
] | [
"android",
"android-maps-utils"
] |
[
"Getting my postgresql db version?",
"On SQlite I could do a query for PRAGMA user_version; and I could set the version if need be too. Is there anything in postgres that could do the same thing? \n\nI tried select version() but that gets the literal version of postgres, and not a custom set version.\n\nAs an update: I researched commenting on databases. Perhaps this could be solution... commenting docs"
] | [
"postgresql",
"sqlite",
"postgresql-9.5"
] |
[
"How to set `typeof this` as type of instance function parameter?",
"TL;DR: Is it possible to declare instance method parameter in a way that it automatically takes the same type as this?\n\n\n\nI'm trying to define a Comparable interface. The naive definition would be this:\n\ninterface Comparable<T> {\n equals(operand: T): boolean;\n}\n\nclass Thingy implements Comparable<Thingy> {\n equals(operand: Thingy): boolean {\n // implementation\n }\n}\n\n\nBut, obviously enough, an instance of some class will probably be compared with another instance of the same class. Therefore the type parameter in Comparable<T> will always repeat the class identifier.\n\nI wonder, is there a way to define Comparable interface so that it automatically sets operand to be of the same type as this?\n\nThis is what I've tried so far"
] | [
"typescript",
"generics",
"interface"
] |
[
"How to use an array that is created in one class in a second class?",
"I have created an array in the implementation of my class loginController. Now I want to use this array (with its objects) in another class of my project. What is the right way to import it?"
] | [
"arrays",
"import",
"connection"
] |
[
"Error loading image - MediumBlob",
"I made a system where the user can upload multiple images. These images are stored in the database in a field of type MEDIUMBLOB. Below the code that makes this feature.\n\n//Configurações para a geração de um arquivo binário temporário\n $diretorio = \"temp/\";\n $nomeArquivo = \"sipi_binario.img\";\n\n if ($_FILES[\"arquivo\"][\"name\"][0] != null) {\n for ($i = 0; $i < count($_FILES[\"arquivo\"][\"tmp_name\"]); $i++) {\n\n $pFoto = $_FILES[\"arquivo\"][\"tmp_name\"][$i];\n\n move_uploaded_file($pFoto, $diretorio . $nomeArquivo);\n $pont = fopen($diretorio . $nomeArquivo, \"rb\");\n\n $dados[4][$i] = base64_encode(fread($pont, filesize($diretorio . $nomeArquivo)));\n $dados[5][$i] = $_FILES[\"arquivo\"][\"type\"][$i];\n\n fclose($pont);\n }\n }\n\n\nWhen the user selects a few iamgens, the system behaves correctly, but when the user selects for example 20 images, some of them start to get corrupted. See below:\n\n\nDoes anyone know how this surely?"
] | [
"php",
"file-upload",
"blob"
] |
[
"Change CSS values dynamically with passed in hex color when application loads",
"My application is initialized by a redirect that occurs. The application url has query parameters attached to it and I must retrieve and use them when the application loads. One of the parameters is a hex value that must be applied to control the applications primary color theme. Currently I am grabbing the parameters using ActiveRoute queryParams and using them. \n\nI am applying the colors in a file called theme.scss with my other SASS files and is being imported into my main app component which adds all those styles to the DOM in a style tag.\n\nMy styles are basically applied as follows:\n\n.sidebar-left-item.active {\n background-color: $pirmary-light;\n}\n\n.btn-pirmary-light {\n background-color: $pirmary-light;\n}\n\n\nThe variable $primary-light is the variable that needs the hex value coming in from the redirect applied to it. So it can really be any color. \n\nHow can I achieve this kind of behavior? Thanks for any advice. \n\nUpdate:\n\nHere is what I would like to do. With Angular 1 I made a directive that does the following. I would add it to the body tag of the index.html and it would go take care of the bindings and it the end leave valid CSS rules in a style tag. This allowed me to have properties applied at runtime.\n\nHTLM:\n\n<dynamic-styles id=\"dynamic-styles\" class=\"ng-cloak\">\n\n #ad-container:before {\n background-color: {{ design.bgAlph }};\n }\n\n</dynamic-styles>\n\n\nAngular Directive:\n\ndynamicStyles = function($interpolate, $timeout) {\n return {\n restrict: 'AE',\n link: function(scope, element) {\n $timeout(function() {\n var domElement = element[0];\n // General interpolation digest cycle will take part after the directive\n // is executed. Separate text interpolation allows not to wait for it,\n // and apply dynamic styles as soon as possible.\n var interpolatedFn = $interpolate(goog.dom.getTextContent(\n domElement));\n goog.dom.setTextContent(domElement, '');\n var styleElement = goog.dom.createElement(goog.dom.TagName.STYLE);\n goog.dom.setTextContent(styleElement, interpolatedFn(scope));\n goog.dom.appendChild(document.head, styleElement);\n });\n }\n };\n};"
] | [
"angular"
] |
[
"Android Bitmap OnTouch Questions",
"I've drawn 5 bitmaps from .png files on a canvas - a head, a body and two arms and legs.\n\nHow can I detect which of these has been touched on an OnTouch? And, more specifically, can I detect if the OnTouch was within the actual shape of the body part touched?\n\nWhat I mean is, obviously, the .pngs themselves are rectangular, but does Android know, or can I tell it, to ignore the transparency within the image?"
] | [
"android",
"bitmap",
"touch"
] |
[
"Heroku push is being rejected, after reinstallation of OS?",
"I'm following the tutorials made by Michael Hartl, but I tend to distro hop a lot on Linux. I cloned my repo from github and I'm doing good with that. However I can't push to heroku anymore and I'm not sure why exactly...\n\nHere is the commands I'm trying to run:\n\n$ bundle exec rake test\n$ git add -A\n$ git commit -m \"Use SSL and the Puma webserver in production\"\n$ git push\n$ git push heroku\n$ heroku run rake db:migrate\n\n\nEverything works fine up until the last part:\n\ngit push heroku\nwarning: push.default is unset; its implicit value is changing in\nGit 2.0 from 'matching' to 'simple'. To squelch this message\nand maintain the current behavior after the default changes, use:\n\ngit config --global push.default matching\n\nTo squelch this message and adopt the new behavior now, use:\n\ngit config --global push.default simple\n\nWhen push.default is set to 'matching', git will push local branches\nto the remote branches that already exist with the same name.\n\nIn Git 2.0, Git will default to the more conservative 'simple'\nbehavior, which only pushes the current branch to the corresponding\nremote branch that 'git pull' uses to update the current branch.\n\nSee 'git help config' and search for 'push.default' for further information.\n(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode\n'current' instead of 'simple' if you sometimes use older versions of Git)\n\nTo [email protected]:morning-stream-6357.git\n ! [rejected] master -> master (non-fast-forward)\nerror: failed to push some refs to '[email protected]:morning-stream-6357.git'\nhint: Updates were rejected because the tip of your current branch is behind\nhint: its remote counterpart. Integrate the remote changes (e.g.\nhint: 'git pull ...') before pushing again.\nhint: See the 'Note about fast-forwards' in 'git push --help' for details.\n\n\nI'm not really sure how to fix this at all :/ Can someone help? I have researched this and I've added the remote heroku repo using this:\n\ngit remote add heroku-remote [email protected]:project.git\n\n\nOf course to modify it for my code would be like this:\n\ngit remote add heroku-remote [email protected]:morning-stream-6357.git\n\n\nBut I'm still not able to push from the command line, I've been pushing using the heroku deploy button that lets me deploy the master branch but I think that's not a good idea otherwise I think it would be mentioned in the book. Any help at all would be greatly appreciated. \n\nEDIT: In case anyone is wondering,I did install the heroku tool belt.\n\nEDIT: I should have noted before that I have indeed already tried running this command:\n\ngit push heroku master\n\n\nBut it still gives me an error:\n\njose@jose-desktop:~/Workspace/sample_app$ git push heroku master\nTo [email protected]:morning-stream-6357.git\n ! [rejected] master -> master (non-fast-forward)\nerror: failed to push some refs to '[email protected]:morning-stream-6357.git'\nhint: Updates were rejected because the tip of your current branch is behind\nhint: its remote counterpart. Integrate the remote changes (e.g.\nhint: 'git pull ...') before pushing again.\nhint: See the 'Note about fast-forwards' in 'git push --help' for details.\n\n\nI'm not sure what's causing this, it should be up to date. I cloned the repo and I've manually deployed from heroku's github connection before so it should be current.\n\ngit pull\n\n\nResults in this:\n\njose@jose-desktop:~/Workspace/sample_app$ git pull\nAlready up-to-date."
] | [
"ruby-on-rails",
"git",
"heroku",
"github",
"heroku-toolbelt"
] |
[
"How to read rsav file in R",
"I have a file with extension rsav, what is the type of this file? How could I read it properly in R? I found bearly not so much files regarding this type of file from Google.\n\nThanks in adavnce.\n\nThe following is the description of question:\n\nFind (on Canvas) the file “file.rsav” (which can be loaded into R using load(“file.rsav”)).\nIt contains a time series (“xx”). The series is a “demeaned” monthly revenue stream (in millions of dollars) for a company. There are n = 96 observations.\n\ndf = load('./file.rsav')\nprint(df)\n\n\nOut:\n\n[1] \"xx\"\n\n\nWith load function:\n\nload('./file.rsav'); ls()\n\n\nOut:\n\n [1] \"agg\" \"air_reserve\" \"air_store\" \n...... \n\n[139] \"wdi\" \"world\" \"xx\" \n\n\nWith str(xx), it generates:\n\n Time-Series [1:96] from 1 to 8.92: 2.45 2.18 0.389 -1.44 -1.47 ...\n\n\nWith xx, it generates:\n\n Jan Feb Mar Apr May Jun Jul\n1 2.45017780 2.17955829 0.38874020 -1.43979552 -1.47049807 -2.25233354 -0.82580703\n2 1.92378321 1.87944208 1.07382472 1.01933130 1.88660307 -0.31109156 -0.25732342\n3 0.60732330 1.53185399 1.58614371 0.63922270 0.82728407 0.28910411 -1.18154941\n4 0.41375543 1.96633332 1.97402973 4.16058136 5.15474250 5.71865844 3.93136013\n5 -1.51228022 -3.03396294 -3.65446772 -4.69589618 -3.51276584 -2.97682246 -3.08655352\n6 3.43027017 4.68909032 6.55598795 4.95816124 4.87626503 3.17103291 0.79093946\n7 -0.62481997 -0.94469455 -2.13648402 -3.64364158 -2.07214317 -3.26793808 -3.38573375\n8 0.67823828 1.09908274 0.93832242 0.08791237 1.77322327 2.01201710 3.70197246\n Aug Sep Oct Nov Dec\n1 0.53048061 1.31994246 0.69306401 1.25916404 1.53363966\n2 -0.47154459 0.52849630 0.90548093 0.71783457 0.86908457\n3 -0.52525201 -0.40335058 0.73415310 0.58501633 0.29875228\n4 2.50242432 1.69408297 0.96230124 0.53164036 -0.64480235\n5 -1.60735865 -0.20500888 -0.44508903 -0.01443040 1.71087427\n6 -0.09975821 -0.85972650 -0.41557374 -0.99876068 0.52620555\n7 -2.25968715 -0.91700127 -0.49302872 -1.44275203 -0.66221559\n8 4.62724761 4.17549847 3.43992950 3.15302462 4.17300576"
] | [
"r"
] |
[
"Surface plotting a matrix in WPF or WinForms",
"I have a matrix of data (the columns represent time, and the rows spectrum frequencies) that I want to plot in a WinForms or WPF control. Something like a surface plot in MATLAB.\n\nI have looked at Microsoft Charting Controls, but it doesn't seem to support anything that could help me.\n\nDo you have a good idea of how to display this data? A library preferably."
] | [
"c#",
"wpf",
"winforms"
] |
[
"Optimising iterative loop",
"I'm gradually moving from Matlab to Python and would like to get some advice on optimising an iterative loop.\nThis is how I am currently running the loop, and for info I've included the code that defines the variables.\n\nnh = 2000 \nh = np.array(range(nh))\nnt = 10000 \nwmin = 1 \nwmax = 10\nhw = np.array(wmin + (wmax-wmin)*invlogit(randn(1,nh))); \nsl = np.array(zeros((nh,1))+radians(40))\nfa = np.array(zeros((nh,1))+radians(35))\nc = np.array(zeros((nh,1))+4.4)\ny = np.array(zeros((nh,1))+17.6)\nyw = np.array(zeros((nh,1))+9.81)\nir = 0.028\nm = np.array(zeros((nh,nt)));\nm[:,49] = 0.1\nz = np.array(zeros((nh,nt)))\nz[:,0] = 0+(3.0773-0)*rand(nh,1).T\nreset = np.array(zeros((nh,nt)))\nfs = np.array(zeros((nh,nt)))\n\nfor t in xrange(0, nt-1):\n fs[:,t] = (c.T+(y.T-m[:,t]*yw.T)*z[:,t]*(np.cos(sl.T)**2)*np.tan(fa.T))/(y.T*z[:,t]*np.sin(sl.T)*np.cos(sl.T))\n reset[fs[:,t]<=1,t+1] = 1;\n z[fs[:,t]<=1,t+1] = 0;\n z[fs[:,t]>1,t+1] = z[fs[:,t]>1,t]+(ir/hw[0,fs[:,t]>1]).T\n\n\nThis is how I would optimise the code in Matlab, however it runs fairly slowly in python. I suspect there is a more pythonic way of doing this and would really appreciate a nudge in the right direction.\nMany thanks!"
] | [
"python",
"matlab",
"loops",
"numpy",
"iteration"
] |
[
"jQuery - timeout in for loop",
"I have written a bit of jQuery to loop through items in a array an display a random number and then move on to display another number. The problem is I want to put a delay inside the loop so that it shows the number for 2 seconds and then moves of to the next. so you see a random number it holds for 2 seconds and then moves on to the next. I have tried putting a timeout inside the loop but that didn't work. Any help would be amazing thanks.\n\nfunction RandomNumberGenerator(){\n\n var myArray = new Array(99);\n\n for (var i=0; i< 99; i++) {\n myArray[i] = Math.floor(Math.random()*100)\n myArrayTwo[i] = Math.floor(Math.random()*100)\n }\n\n for (var i=0; i< 9; i++) {\n $('li.num').text(function(index) {\n\n // timeout needs to be here somewhere \n\n return (myArray[i]);\n\n })\n }\n});\n}"
] | [
"jquery",
"loops",
"for-loop",
"timeout"
] |
[
"Sum up a newly inserted blank row",
"I have 13 worksheets with similar data (each worksheet contains data for a different client). \n\nI need to do all these steps for each worksheet:\n\n\nSort Data in Column \"D\" - Working \nInsert an empty row in each worksheet when a value has changed in column \"D\" - Working\nWhen a value has changed in Column \"D\" and I insert the empty row, all rows with same value in column \"D\" should Sum up in Column \"K\".\n\n\nIn the screenshot below you can see the result of my code: a new row inserted after a value has changed in column \"D\". The red cells are what I need to do - Sum up.\n\nScreenshot with SumUp\n\n\nI run the below code after I sort all worksheets:\n\nSub InsertRowsAtValueChangeColumnD()\n\n'--- INSERT CLEAR ROWS\n\n Dim X As Long, LastRow As Long\n Const DataCol As String = \"D\"\n Const StartRow = 2\n LastRow = Cells(Rows.Count, DataCol).End(xlUp).Row\n Application.ScreenUpdating = False\n For X = LastRow To StartRow + 1 Step -1\n If Cells(X, DataCol).Value <> Cells(X - 1, DataCol) Then Rows(X).Insert\n Next\n Application.ScreenUpdating = True\nEnd Sub\n\n\nI need to sum up after inserting the row."
] | [
"excel",
"vba"
] |
[
"Batch File - Error in FOR / IF statement with numbers and text",
"These code was working before. I added some additional letters to the \"FOR\" line and now it's not working.\n\nGoal: Get user input. User input can be a number or letter. Set input as the \"SELECTION\".\n\n:choice1\nA. 1-12\nB. 1-7\n 1. stuff\n 2. more stuff\n etc to 7\nC. 8-10\n 8.\n etc to 10\nD. 11-12\n 11....\n 12...\n\nSET /P c= Make a selection or eXit (X)...\nCLS\nIF /i %c%==X GOTO choice1\nIF %A%==1 FOR %%I IN (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 A B C D) DO (\n IF /i #%c%==#%%I SET SELECTION=%c%\n EXIT /B\n )\n\nIF %A%==2 FOR %%I IN (1 2 3 4 5 6 7 8 9 10 13 A B C D) DO (\n IF /i #%c%==#%%I SET SELECTION=%c%\n EXIT /B\n )\n\n\nIt is not setting SELECTION = %c% on true. I assume that is not returning TRUE when it should. This was working before. I don't understand what changed. The original line of code was:\n\nIF %A%==1 FOR %%I IN (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 E) DO IF /i #%c%==#%%I SET SELECTION=%c% & EXIT /B"
] | [
"batch-file",
"if-statement",
"for-loop",
"user-input"
] |
[
"Dataframe python reshape some values from horizontal to vertical",
"I have 92 columns and 13 rows Dataframe where each row corresponds to one poker hand. Column (not all) names and values look like this:\n\n'Soft','Hand_ID','Table_Size', 'Blinds', 'Day', 'No_of_players', 'Seat_1','Seat_2','Seat_3', 'Seat_4', 'Seat_5', 'Seat_6'\nPokerStars 172109655423 6-max €0.50/€1.00 2017/06/22 4 KO fasolakia14 Johnii141 bogec 0 0\nPokerStars 143736274858 6-max £0.25/£0.50 2015/11/13 6 Racushniak koluha1000 Bantina DMIGNN Johnii141 vor4mohs\n\n\nI need to reshape columns: 'Seat_1','Seat_2','Seat_3', 'Seat_4', 'Seat_5', 'Seat_6' to vertical.\nOutput shoud look like this:"
] | [
"python",
"dataframe"
] |
[
"How to make TODO and FIXMEs show up in a particular order in Eclipse",
"I want to make a skeleton application for some students, and I want to be able to direct the order in which the //TODO Task tags appear in the Task List View.\n\nThis is necessary so that the order in which the students will do the tasks actually teaches them something, rather than confusing them and having them spend too much time on understanding the application, rather its parts.\n\nIs there any way to do this? Thank you"
] | [
"eclipse"
] |
[
"spacing problem in JS/CSS text flipper",
"I am trying to make an ambigram making tool that shows text in capitals and some other font both right side up and up side down. I managed to do this, but the spacing between the words is very big. Is there some way to get it to be near zero? I tried adding some margins to the css, but it seems to ignore it.\n\nIt is made as a wordpress plugin. You can see it running here: https://makeambigrams.com/demo/\n\n<?php\nadd_shortcode( 'worder', 'worder_print_html' );\nfunction worder_print_html( ) {\n wp_enqueue_script('worder-script');\n ob_start();\n ?>\n <div class=\"the_worder_contaienr\">\n <form method=\"post\" id=\"word-er-form\" name=\"word-er-form\">\n <input type=\"text\" name=\"word_er_word\" id=\"word_er_word\" value=\"\" /> <br>\n <input type=\"submit\" value=\"Generate\" />\n </form>\n <div id=\"the_result\">\n </div>\n </div>\n <style>\n .the_worder_contaienr {\n text-align: center;\n margin:0\n margin-top: -20px;\n }\n .the_worder_contaienr input{\n margin:0\n }\n p.origgina_other_font, .upside_down_font p {\n font-family: serif;\n margin:0\n margin-top: -20px;\n }\n .upside_down_uppwe,.upside_down,.upside_down_font {\n transform: scaleY(-1);\n margin:0\n margin-top: -20px;\n }\n </style>\n <?php\n //$output = ob_end_clean();\n return ob_get_clean();\n //return \"foo = {$atts['foo']}\";\n}\nfunction the_worder_jquery() {\n wp_register_script( 'worder-script', plugin_dir_url( __FILE__ ) . '/custom.js', array( 'jquery' ), '1.0.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'the_worder_jquery' );\n\n\njs\n\n(function($) {\n\n $('#word-er-form').on('submit', function() {\n event.preventDefault();\n var the_input = $('#word_er_word').val().toLowerCase();\n var the_characters = the_input.split('');\n console.table(the_characters);\n var the_original = $('#word_er_word').val();\n var the_upper_case = the_input.toUpperCase();\n var the_revese_case = the_characters.reverse().toString().replace(/,/g, \"\");;\n console.log(the_original);\n console.log(the_upper_case);\n console.log(the_revese_case);\n var the_result = '<p class=\"original\">'+the_input+'</p>';\n the_result += '<p class=\"original_capitalize\">'+the_upper_case+'</p>';\n the_result += '<p class=\"origgina_other_font\">'+the_input+'</p>';\n the_result += '<div class=\"upside_down_font\"><p>'+the_revese_case+'</p></div>';\n the_result += '<div class=\"upside_down_uppwe\"><p>'+the_revese_case.toUpperCase()+'</p></div>';\n the_result += '<div class=\"upside_down\"><p>'+the_revese_case+'</p></div>';\n $('#the_result').html(the_result);\n })\n\n})( jQuery );"
] | [
"javascript",
"css",
"wordpress"
] |
[
"Dynamic Call to processor by request type",
"Maybe my problem is easy but I became so confuse because I am so new to dynamic programming.\n\nHere is the issue:\nI have an Interface which is called IGame. and I have two other interfaces IGameRequest and IGameProcessor.\n\npublic interface IGame {}\npublic interface IGameRequest: IGame {}\npublic interface IGameProcessor: IGame\n{ void process();}\n\npublic interface IKidGameRequest : IGameRequest {}\npublic interface IKidGameProcessor : IGameProcessor \n{ void process();}\n\n\nOn the other hand,\n\npublic class KidGameRegistrationRequest : IKidRelatedRequest {//something}\n\n\nSo in total I have something like below\n\n IGame\n | |\n IGameRequest IGameProcessor\n | |\n IKidGameRequest **IKidGameProcessor**\n | \n **KidGameRegistrationRequest **\n\n\nI try to find KidGameProcessor when I receive KidGameRegistrationRequest in runtime.\n\nI have tried to fetch all assemblies and search for any with Kid name and to prevent any static string, I added an enum class, GameTypeand I managed to find the right processor, but I stuck to invoke that method in runtime.\n\nPublic enum GameType {Kid}"
] | [
"c#",
"dynamic-programming"
] |
[
"Accessing Javascript nested object returned by Laravel",
"For some reasons I can not access name from category object it says undefined\n\n datas: [{\n \"id\": 3,\n \"title\": \"public\",\n \"created_at\": \"2019-01-12 02:37:28\",\n \"updated_at\": \"2019-01-12 02:37:28\",\n \"announcements\": [{\n \"id\": 3,\n \"user_id\": 37,\n \"title\": \"Jumapili 13-01-2019\",\n \"category_id\": 13,\n \"body\": \"Saa 1030 asubuhi Consequuntur autem veniam ut voluptatibus. Qui impedit et ipsam est veritatis dolores. Voluptate quos harum eos nisi aut. Officiis nemo occaecati voluptas id modi. Sit omnis est autem aliquam sint quam libero.\",\n \"end_date\": \"2019-01-12 02:56:15\",\n \"live\": 0,\n \"created_at\": \"2019-01-12 02:36:15\",\n \"updated_at\": \"2019-01-12 02:36:15\",\n \"pivot\": {\"viewer_id\": 3, \"viewable_id\": 3, \"viewable_type\": \"App\\\\Announcement\"},\n \"category\": {\n \"id\": 13,\n \"user_id\": 38,\n \"name\": \"et\",\n \"created_at\": \"2019-01-12 02:36:15\",\n \"updated_at\": \"2019-01-12 02:36:15\"\n }\n }]\n }]\n\n\nwhen I try to access it on the Vue component I get undefined\n\n div class=\"public\" v-for=\"dataSet in datas\">\n <div v-for=\"announcements in dataSet\">\n <dl v-for=\"announcement in announcements\">\n <dt class=\"category\" \n v-text=\"announcement.category\"></dt>\n <h3 v-text=\"announcement.title\"></h3>\n <dd v-text=\"announcement.body\"></dd>\n </dl>\n </div>\n\n </div>\n\n\nPlease help, thanks in advance"
] | [
"javascript",
"object"
] |
[
"SqlDataReader C#, SQL Server 2005, VS 2008",
"I am trying to select food_ItemName and food_UnitPrice from t_Food table in SQL Server 2005 using C# and VS 2008.\n\nI have the following code:\n\n\n private SqlConnection connection;\n\n private void GetDatabaseConnection()\n {\n string connectionString = @\"Server = RZS-F839AD139AA\\SQLEXPRESS; Integrated Security = SSPI; Database = HotelCustomerManagementDatabase\";\n connection = new SqlConnection(connectionString);\n connection.Open();\n }\n\n public Food PopulateFoodItemListview()\n {\n GetDatabaseConnection();\n string selectFoodItemQuery = @\"SELECT food_ItemName, food_UnitPrice FROM t_Food\";\n SqlCommand command = new SqlCommand(selectFoodItemQuery, connection);\n SqlDataReader reader = command.ExecuteReader();\n Food food = new Food();\n List foodList = new List();\n\n while (reader.Read())\n {\n food.ItemName.Add(reader.GetString(0));\n MessageBox.Show(\"ItemName: \"+ food.ItemName);\n food.UnitPrice.Add(reader.GetDouble(1));\n MessageBox.Show(\"UnitPrice: \" + food.UnitPrice);\n\n }\n connection.Close();\n return food;\n }\n\n\nAnd in Food class I have the following code:\n\n\n public class Food\n {\n private List itemName = new List();\n private List unitPrice = new List();\n private double itemUnit;\n private Customer foodCustomer = new Customer();\n\n public List ItemName\n {\n get { return itemName; }\n set { itemName = value ; }\n }\n\n public List UnitPrice\n {\n get { return unitPrice; }\n set { unitPrice = value; }\n }\n\n public double ItemUnit\n {\n get { return itemUnit; }\n set { itemUnit = value; }\n }\n public double GetItemPrice(double itemUnit, double unitPrice)\n {\n double itemPrice = itemUnit*unitPrice;\n return itemPrice;\n }\n}\n\n\nIn messageBox it supposed to show Rice, Mutton, Beef and their price 50, 100, 150. But it showhing ItemName: System.Collections.Generic.List`1[System.String] and\nItemName: System.Collections.Generic.List`1[System.Double]\n\nWhats the problem?"
] | [
"c#",
"sql"
] |
[
"Windows Installer not deleting all files on uninstall",
"I've seen some similar questions asked on here, but none of the solutions given were very clear or worked for me.\n\nI have an installer (created with WiX) which installs certain files and folders. However, when running the installed application, this creates some folders and copies some files into it. These files and folders are not removed on uninstall.\n\nEdited to Show Code so Far:\n\nThis INSTALLDIR property:\n\n<Property Id=\"INSTALLDIR\">\n <RegistrySearch Id='Registry' Type='raw' Root='HKLM' Key='Software\\$(var.Manufacturer)\\$(var.ProductName)' Name='Location' />\n </Property>\n\n\nThis Component which should set the install location in the registry:\n\n<Component Id=\"Registry\" Guid=\"*\">\n <RegistryKey Root=\"HKMU\" Key=\"Software\\$(var.Manufacturer)\\$(var.ProductName)\">\n <RegistryValue Name=\"Location\" \n Type=\"string\" \n Value=\"[INSTALLDIR]\" \n Action=\"write\" \n KeyPath=\"yes\" />\n </RegistryKey>\n <util:RemoveFolderEx On=\"uninstall\" Property=\"INSTALLDIR\" />\n </Component>\n\n\nThis does create a record in the registry with the install location, but I'm not sure how to adapt this code to making note of the 'public' directory and removing it - I don't know where the util:RemoveFolderEx should go either (inside which component)"
] | [
"wix",
"windows-installer",
"uninstallation"
] |
[
"Access Repository to fragment presenter, in MVP model and dagger2",
"I am using repository pattern in mvp with dagger .In App scope I binded my RemoteDataSource and LocalDataSource:\n\n@Binds\n @AppScope\n @Remote\n abstract MainDataSource RemoteDataSource(RemoteDataSource remoteDataSource);\n\n @Binds\n @AppScope\n @Local\n abstract MainDataSource LocalDataSource(LocalDataSource localDataSource);\n\n\nAnd i injected main repository in app scope:\n\n @Inject\n public MainRepository(@Remote MainDataSource remoteDataSource,\n @Local MainDataSource localDataSource) {\n this.remoteDataSource = checkNotNull(remoteDataSource);\n this.localDataSource = checkNotNull(localDataSource);\n }\n\n\nNow in fragment scope in mainpresenter i passed MainRepository in it's contractor :\n\n@MainFragScope\n@Component(modules = {MainFragModule.class}, dependencies = AppComponent.class)\npublic interface MainFragComponent {\n\n\nPresenter constructor:\n\nprivate MainDataSource remoteDataSource;\nprivate MainDataSource localDataSource;\n @Inject\n public MainPresenter(MainRepository repository, ArrayAdapter<String> typesAdapter) {\n this.repository = checkNotNull(repository);\n this.typesAdapter = checkNotNull(typesAdapter);\n }\n@Override\npublic void loadChart(String district, String date, String type) {\n remoteDataSource.loadChart(district,date,type);\n}\n\n\nIn RemoteDataSource i have a method called loadChart and it's job is fetch data from remote server by retrofit:\n\n public void loadChart(String district, String date, String type) {\n JsonObject joParam = new JsonObject();\n apiService.getAnalyticalReport(joParam).enqueue(new Callback<ResponseBody>() {\n @Override\n public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {\n try {\n if (response.isSuccessful()) {\n // need presenter reference to pass response to it\n\n\nAfter fetching data i need to return this data from server to fragment presenter(MainPresenter).I need to presenter reference. How could i get presenter without destroy mvp roles!!? Because in AppScope i do not access to MainPresenter."
] | [
"android",
"repository-pattern",
"dagger-2",
"android-mvp"
] |
[
"Android Espresso fails AssertionFailedWithCauseError",
"I am trying to run an Android Espresso test on a layout that contains multiple EditTexts. Each EditText has a unique id. My test successfully clears the text from each EditText, but it fails to replace the text with my String (stringToBeTyped = \"123 Sesame St.\").\n\nThis same test is also being run successfully on other layouts that have just one EditText each. My hunch is that there may be a bug in Espresso related to multiple EditTexts per layout.\n\nMy test method:\n\nvoid performEditTextComparisonAndModificationTest(int resId, String initialText, String stringToBeTyped) {\n onView(withId(resId)).check(matches(withText(initialText)));\n onView(withId(resId)).perform(click(), replaceText(stringToBeTyped));\n onView(withId(resId)).check(matches(withText(stringToBeTyped)));\n}\n\n\nMy logcat output:\n\nandroid.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text: is \"123 Sesame St.\"' doesn't match the selected view.\nExpected: with text: is \"123 Sesame St.\"\nGot: \"EditText{id=3, visibility=VISIBLE, width=432, height=49, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=true, editor-info=[inputType=0x2071 imeOptions=0x8000005 privateImeOptions=null actionLabel=null actionId=0 initialSelStart=0 initialSelEnd=0 initialCapsMode=0x2000 hintText=Street Address label=null packageName=null fieldId=0 fieldName=null extras=null ], x=0.0, y=0.0, text=, hint=Street Address, input-type=8305, ime-target=false, has-links=false}\"\n\n\nAs you can see from the end of the third logcat line, the EditText's text=\"\". Why is this? Could it be a bug in the espresso framework?"
] | [
"android",
"android-espresso",
"ui-testing"
] |
[
"ReactJS, Rerendering, and the Public Directory",
"I have a ReactJS application in development for which it would be extremely useful to be able to write into, and fetch (via flask) from, the projects "public" directory and associated subdirectories, without triggering the immediate re-render.\nIs it possible to configure React in such a way, while in development mode?\nIs there some clever arrangement of symbolic links in Ubuntu which will let me fake the system out?"
] | [
"reactjs"
] |
[
"Android Studio not reflecting my changes",
"Currently my Andriod studio is stuck at point where whatever changes I make in Studio is not getting reflected in apk. I invalidated the cache and restarted Android studio still doest work. I restarted the machine still I am getting this.. Can anyone help me?"
] | [
"android-studio"
] |
[
"Doesn't PIC mean no relocations?",
"I'm building an ELF SO for bada on ARM using GCC. The compiler options include -fpic. Yet in the built file, when I do readelf -r, there's a whole lot of relocation records, of following types:\n\n\nR_ARM_RELATIVE\nR_ARM_REL32\nR_ARM_ABS32\nR_ARM_GLOB_DAT\nR_ARM_JUMP_SLOT\n\n\nWhat am I misunderstanding here?\n\nEDIT: from what I can see, the PIC implementation in the compiler doesn't use GOT. Instead, they use PC-relative addressing with stored constants being offsets from point of use to the symbol address; that's resolved by the linker. Like this, to read a global variable:\n\n ldr r12, OffsetToVar\nPointOfUse:\n ldr r0, [r12, pc] \n# r0 now has the value of MyVar\n\n#...\n\n# At function's end...\nOffsetToVar:\n .long MyVar-PointOfUse-8\n# Compiler can't resolve this, since it doesn't know\n# the address of MyVar, but linker can\n\n\nSimilar idea for cross-module function calls. When a project mixes ARM and Thumb code though, the latter may misfire. But I've worked around that."
] | [
"gcc",
"assembly",
"arm",
"elf"
] |
[
"How to Serialize/Deserialize Swagger Json To/From C#",
"Swagger Json is malformed in the sense that it cannot be serialized or deserialized in many languages because it allows for properties with illegal variable names such as forward slash. Take this common example from the Swagger website:\n\nhttp://petstore.swagger.io/v2/swagger.json\n\nIf you copy and past the json in to this common Json -> C# converter, you get an error. Try it out:\n\nhttp://json2csharp.com/\n\nIt kind of works here:\nhttps://www.freecodeformat.com/json2csharp.php\n\nBut, this is the C# that is generated:\n\npublic class Paths\n{\n /// <summary>\n /// \n /// </summary>\n public /pet /pet { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /pet/findByStatus /pet/findByStatus { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /pet/findByTags /pet/findByTags { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /pet/{petId} /pet/{petId} { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /pet/{petId}/uploadImage /pet/{petId}/uploadImage { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /store/inventory /store/inventory { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /store/order /store/order { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /store/order/{orderId} /store/order/{orderId} { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /user /user { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /user/createWithArray /user/createWithArray { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /user/createWithList /user/createWithList { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /user/login /user/login { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /user/logout /user/logout { get; set; }\n /// <summary>\n /// \n /// </summary>\n public /user/{username} /user/{username} { get; set; }\n}\n\n\nNote: it is totally malformed. \n\nIs there a way to get this stuff in and out of an object model without resorting to trawling through the object model with Newtonsoft's JObjects etc.?"
] | [
"c#",
"json",
"serialization",
"swagger",
"swashbuckle"
] |
[
"Heroku: rake aborted",
"I'm trying to run db:migrate on Heroku (app's working fine locally) and I get this error:\n\nrake aborted!\nuninitialized constant Bootstrap::Rails::Engine::Sass\n/app/vendor/bundle/ruby/2.0.0/bundler/gems/bootstrap-rails-8eb1287f94b3/lib/bootstrap-rails/engine.rb:6:in `block in <class:Engine>'\n/app/vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/initializable.rb:30:in `instance_exec'\n/app/vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/initializable.rb:30:in `run'\n/app/vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/initializable.rb:55:in `block in run_initializers'\n/app/vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/initializable.rb:54:in `run_initializers'\n/app/vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/application.rb:215:in `initialize!'\n/app/vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/railtie/configurable.rb:30:in `method_missing'\n/app/config/environment.rb:5:in `<top (required)>'\n/app/vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/application.rb:189:in `require_environment!'\n/app/vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/application.rb:249:in `block in run_tasks_blocks'\nTasks: TOP => db:migrate => environment\n(See full trace by running task with --trace)\n\n\nGemfile:\n\nsource 'https://rubygems.org'\nruby \"2.0.0\"\n\ngem 'rails', '4.0.0'\n\n# Gems used only for assets and not required\n# in production environments by default.\ngroup :assets do\n gem 'sass-rails'\n gem 'coffee-rails'\n\n # See https://github.com/sstephenson/execjs#readme for more supported runtimes\n # gem 'therubyracer', :platforms => :ruby\n #gem 'therubyracer'\n #gem 'less-rails'\n #gem 'twitter-bootstrap-rails'\n gem 'uglifier', '>= 1.0.3'\nend\n\ngem 'anjlab-bootstrap-rails', :require => 'bootstrap-rails',\n :github => 'anjlab/bootstrap-rails',\n :branch => '3.0.0'\n\ngem 'railties', '>=4.0.0'\ngem 'protected_attributes'\n\ngem 'jquery-rails'\ngem 'foreman'\n# PostgreSQL\ngem 'pg'\n\n# Use Unicorn as the app server\ngem 'unicorn'\n\n# Devise for user accounts management\ngem 'devise'\n\n# Stripe for processing payments\ngem 'stripe'\n\n# New Relic monitoring\ngem 'newrelic_rpm'\n\n# QR Code generation\ngem 'rqrcode-rails3'\n\n# User auth\ngem 'cancan'\n\ngroup :development do\n gem 'debugger'\n gem 'better_errors'\n gem \"binding_of_caller\"\n gem 'meta_request' \nend"
] | [
"ruby-on-rails",
"ruby",
"ruby-on-rails-3",
"heroku"
] |
[
"Saving Dictionary with NSAttributed String into a PList or into NSUserDefaults",
"I've a Dictionary with an NSAttributtedString\n\n{\n 9 = {\n 9x0 = {\n UserID = 123;\n formattedMessage = \"Hi... How are you ?{\\n CTForegroundColor = \\\"<CGColor 0x601e460> [<CGColorSpace 0x6010020> (kCGColorSpaceDeviceGray)] ( 0 1 )\\\";\\n NSFont = \\\"CTFont <name: Cochin-BoldItalic, size: 17.000000, matrix: 0x0>\\\\nCTFontDescriptor <attributes: <CFBasicHash 0x6070640 [0x11f8400]>{type = mutable dict, count = 1,\\\\nentries =>\\\\n\\\\t1 : <CFString 0xf4d5c4 [0x11f8400]>{contents = \\\\\\\"NSFontNameAttribute\\\\\\\"} = <CFString 0x60707f0 [0x11f8400]>{contents = \\\\\\\"Cochin-BoldItalic\\\\\\\"}\\\\n}\\\\n>\\\";\\n}\";\n isDeleted = 0;\n isEdited = 0;\n lastModifiedDate = \"2011-10-19 17:27:38 +0000\";\n message = \"Hi... How are you ?\";\n };\n };\n}\n\n\nI tried Saving this Dictionary as a Plist in the Documents folder \nand also, \nsave the dictionary in NSUserDefaults.\nNeither of it worked. \nBoth methods work if the attributed string in the dictionary is removed.\n\nCode used to save to Plist in Documents folder :\n\nNSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];\nNSString *aFilePath = [NSString stringWithFormat:@\"%@/ChatHistory.plist\",aDocumentsDirectory];\nBOOL aStatus = [aDictionary writeToFile:aFilePath atomically:YES];\n\n\nCode used to save Dictionary in NSUserDefaults :\n\nNSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];\n[defaults setObject:aDictionary forKey:@\"ChatHistory\"];\n\n\nSomeone please help. Am I missing something ?"
] | [
"ios",
"save",
"plist",
"nsuserdefaults",
"nsattributedstring"
] |
[
"Strange execution times on string reversal",
"Last week I read this answer and its accompanying comments about a string\nreversal routine.\nI decided to test it myself and stumbled upon an apparent anomalie.\nFor some reason the second routine performs very differently depending on\nthe length of the string being shorter than 128 bytes or not.\n\n UsingXchg UsingMov UsingBswap\n\n add eax, ebx add eax, ebx mov edx, eax\n jmp B jmp B add eax, ebx\nA: mov dl, [ebx] A: mov dl, [ebx] jmp B\n xchg dl, [eax] mov cl, [eax] A: sub eax, 4\n mov [ebx], dl mov [eax], dl mov esi, [ebx]\n inc ebx mov [ebx], cl mov edi, [eax]\nB: dec eax inc ebx bswap esi\n cmp ebx, eax B: dec eax bswap edi\n jb A cmp ebx, eax mov [eax], esi\n jb A mov [ebx], edi\n add ebx, 4\n B: sub edx, 8\n jnb A\n jmp D\n On entry: EBX is address C: mov dl, [ebx]\n EAX is length mov cl, [eax]\n mov [eax], dl\n mov [ebx], cl\n inc ebx\n D: dec eax\n cmp ebx, eax\n jb C\n\n\nNext come the times (in msec) I measured for a large number of repeats.\n\nStringSize UsingXchg UsingMov UsingBswap\n\n 26 30.7 17.4 6.4\n 52 60.9 33.4 12.2\n 78 90.5 49.4 17.9\n 104 121.9 65.4 22.7\n /------\\\n 127 | 79.0 |\n 128 | 27.3 |\n \\------/\n 130 152.1 27.6 27.9\n 156 181.9 30.7 33.5\n 182 211.8 34.4 39.2\n 208 241.8 37.2 44.0\n\n 260 301.6 43.6 54.9\n 2600 2996.5 337.2 538.4\n26000 29949.2 3226.5 5350.4\n\n\n\nBoth UsingXchg and UsingBswap show regularity, but UsingMov clearly\nshifts gear at the 128 bytes mark.\nI suspect caches are at the heart of this little problem, but then why don't\nall 3 routines show the same effect?\nI'd like to conclude that the best string reversal routine is UsingBswap\nwith a bypass in case the string has more than 127 bytes.\nWould this be a valid conclusion at all?\n\n mov edx, eax ;Remaining string length\n add eax, ebx ;Turn EAX into a pointer\n cmp edx, 127\n ja D ;Don't use Bswap on long strings\n jmp B\nA: sub eax, 4\n ...\nD: dec eax\n cmp ebx, eax\n jb C ;Still 2 bytes left"
] | [
"string",
"assembly",
"x86",
"timing"
] |
[
"Audit trail for established Access database",
"Good Evening all\n\nI have inherited an Access database that is now running on Access 2010, there is currently no Audit trail for this dB and it's quite important that it has one.\n\nI've read various articles that suggest a fairly neat solution based on calling a code module on an update event. However this involves editing every field in the dB to add a tagged property. The database isn't massive compared to some but going through maybe a hundred forms with between 5 and 50 fields on these form. Is there a method by which I could tag all the fields at once or maybe even another methodology \n\nI was thinking of building a form users can fill in then an administrator does whatever is required at table level fills in their part of the same form, the data being appended to an audit trail table, seems a fairly unsatisfactory solution if this could be taken care of automatically ?\n\nAny ideas"
] | [
"ms-access-2010",
"audit",
"audit-trail"
] |
[
"Comparing two arrays in C without case sensitivity",
"I have for example two arrays\nchar 1 is: 77a abcd Abc abc1d @#@# v k\nchar2 is: 789 ABA AABB 123 ab #% abcde\nThe common index should be in places 0,3,4,5,9,10,12,20\nThe result should be 8 but I get 9 The problem is that an Aski code lower than 64 still works and it should not\nIs the code\nint intersection(char arrayNumberOne[size], char arrayNumberTwo[size])\n{\n int counter = 0;\n\n for (int i = 0; i < strlen(arrayNumberOne); i++)\n {\n if ((arrayNumberOne[i] == arrayNumberTwo[i]) || (arrayNumberOne[i] == arrayNumberTwo[i] + 32) || (arrayNumberOne[i] + 32 == arrayNumberTwo[i]))\n {\n if (arrayNumberOne[i] < 64)\n {\n ?????\n }\n \n \n counter++;\n \n }\n }\n return counter;\n}"
] | [
"arrays",
"c"
] |
[
"Delete file in server fedora 11",
"I have an application with server fedora 11. I want to delete 1 object in fedora.This is the code for deleting file:\n\n$path = \"/opt/html/bancas/scb/csv/test.csv\";\n\nif(file_exist($path)){\n$delete = exec( \"yes | rm /opt/html/bancas/scb/csv/test.csv\" );\n$delete;\nif($delete){\necho \"success remove the file\";}\nelse \n{\necho \"failed to remove file\";\n}\n}\nelse\necho \"Problem Deleting\".$path;\n\n\nBut when i check, the file is failed to removed. And there is an meesage \"failed to remove file\" when i check using firebug.\n\nPlease help me\n\nThanks,\nAgung"
] | [
"php",
"fedora"
] |
[
"How to pass values from bat file to DB2 sql file using CLP",
"I need to update Customer table in chunk of 50K, The number of records in customer table is 2 million.\n\nI am using DB2 command prompt to execute my sql from a file using bat file.\n\nThere are two file which I have created.\n\n1. customerupdate.bat\n\nDB2 CONNECT TO DBTEST USER DB2ADMIN USING XXXXXX\nset start=%1\nset end=%2\ndb2 -l D:\\vinu\\CUSTOMERADDRESS.log -mstf D:\\vinu\\CUSTOMERADDRESS.sql \n\n\n2. customer.sql\n\nupdate customer set firstname='XXXX' where customercid between 1 and 50000\n\n\nHere I need to pass 1 and 50000 value from command prompt.\n\nupdate customer set firstname='XXXX' where customercid between 1 and 50000\n\nI am executing above sql using below command successfully, However I need pass the parameter to sql file.\n\nC:\\Program Files\\IBM\\SQLLIB\\BIN>customerupdate.bat 1 50000\n\nPlease note: I cannot use the query directly like\n\ndb2 -l D:\\vinu\\CUSTOMERADDRESS.log -mst \" update customer set firstname='XXXX' where customercid between %1 and %2\"\nThe query should be supplied from a sql file only."
] | [
"sql",
"windows",
"batch-file",
"db2",
"clp"
] |
[
"I've installed EOAUTH extension, i can authenticate with google, but I'm wondering how to get user information after that",
"Wishing You a Happy New year I start with my first problem of the year \n\nhere's what I do in login method of user controller:\n\nYii::import('ext.eoauth.*');\n\n $ui = new EOAuthUserIdentity(\n array(\n //Set the \"scope\" to the service you want to use\n 'scope'=>'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',\n 'provider'=>array(\n 'request'=>'https://www.google.com/accounts/OAuthGetRequestToken',\n 'authorize'=>'https://www.google.com/accounts/OAuthAuthorizeToken',\n 'access'=>'https://www.google.com/accounts/OAuthGetAccessToken',\n )\n )\n );\n\n if ($ui->authenticate()) {\n $user=Yii::app()->user;\n $user->login($ui);\n $this->redirect(array('loggedin'));\n }\n else \n throw new CHttpException(401, $ui->error);\n\n\nits logged and in place of name it display the token key.. i need to get email at least to store it to db... Please help me out.. thanks in advance"
] | [
"yii-extensions",
"yii",
"yii-components"
] |
[
"Select single column by detecting col-name and keep colname",
"I have a data.frame (df1) in which I want to transfer one (or more) certain columns to a new data frame (df2). When I with\nwhich(str_detect (colnames (data), col-key))\n\nsearch for the columns, and match several columns, then the column names are retained. If I only match one column in df1, the column name is not kept. Why is that?\nExamplary:\ndf1 <- data.frame(col1 = c("a", "b"), col2 = c(1, 2))\ndf2 <- data.frame(id = c("123456789", "123456780"))\n\nselect multiple cols by str_detect: ✓\ndf2 <- df2 %>% bind_cols(df1[, str_detect(colnames(df1), "col")])\n\nid col1 col2\n1 123456789 a 1\n2 123456780 b 2\n\nselect single col by str_detect: ❌\ndf2 <- df2 %>% bind_cols(df1[, str_detect(colnames(df1), "col1")])\n\nNew names:\n* NA -> ...2\n> \n> df2\n id ...2\n1 123456789 a\n2 123456780 b\n\nWhat is the reason for this that the column name is not adopted?\nThanks"
] | [
"r"
] |
[
"DirectLine API never returns a conversation",
"So I'm using Microsofts Bot framework and their DirectLine api to talk to it. I do this beacuse I need to send a notification to the bot. The class below is called by my endpoint that I have in my backend. So when I call my notify endpoint, this class is invoked and is supposed to start a conversation with the bot to trigger certain events in it. The problem is that it doesn't seem to work as expected. When I run the code and make a request to my endpoint, it get's stuck at var conversation = await client.Conversations.StartConversationAsync();\nthe await keyword stops the execution until it is finished, problem is that it never finishes. BUT I can see in the debug window that the request is sent with a 201 created statuscode, so it should finish, but it never does. Not sure what to do here. \n\n private static async Task StartBotConversation()\n {\n string directLineSecret = \"SECRECT\";\n string fromUser = \"DirectLineSampleClientUser\";\n\n DirectLineClient client = new DirectLineClient(directLineSecret);\n\n Debug.WriteLine(\"Before starting con \");\n var conversation = await client.Conversations.StartConversationAsync();\n\n Debug.WriteLine(\"After starting con\");\n Activity userMessage = new Activity\n {\n From = new ChannelAccount(fromUser),\n Text = \"ERROR1337\",\n Type = ActivityTypes.Trigger\n };\n Debug.WriteLine(\"Before posting activity\");\n await client.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);\n Debug.WriteLine(\"After posting activity\");\n }"
] | [
"c#",
"direct-line-botframework"
] |
[
"Using C# Regular expression to replace XML element content",
"I'm writing some code that handles logging xml data and I would like to be able to replace the content of certain elements (eg passwords) in the document. I'd rather not serialize and parse the document as my code will be handling a variety of schemas.\n\nSample input documents:\n\ndoc #1:\n\n <user>\n <userid>jsmith</userid>\n <password>myPword</password>\n </user>\n\n\ndoc #2:\n\n<secinfo>\n <ns:username>jsmith</ns:username>\n <ns:password>myPword</ns:password>\n </secinfo>\n\n\nWhat I'd like my output to be:\n\noutput doc #1:\n\n<user>\n <userid>jsmith</userid>\n <password>XXXXX</password>\n </user>\n\n\noutput doc #2: \n\n<secinfo>\n <ns:username>jsmith</ns:username>\n <ns:password>XXXXX</ns:password>\n </secinfo>\n\n\nSince the documents I'll be processing could have a variety of schemas, I was hoping to come up with a nice generic regular expression solution that could find elements with password in them and mask the content accordingly.\n\nCan I solve this using regular expressions and C# or is there a more efficient way?"
] | [
"c#",
".net",
"xml",
"regex",
"parsing"
] |
[
"Need help in understanding Dist and DistArray",
"I don't understand the following piece of code.\n\nval array = new Array[INT](1..1000, ([i]:Point) => 0);\nval dist = Dist.makeBlock(array.region);\nval distArray = DistArray.make(dist, ([i]:Point) => array(i));\n\n\nThis is all. The expressions in () are very confusing, but also the =>, Dist and DistArray."
] | [
"x10-language"
] |
[
"CSS: iframe not displaying 100% height...more like 100px height",
"Having an issue with this page (http://purcraft.com/madeinla/) which I'm trying to use an iframe element to display the contents of this page: (http://purcraft.com/madeinla/home2_height.html).\n\nThe width is good but the height? Seems to be more like 100px rather than the 100% I want. Why is this? Here's my code. It's pretty straightforward.\n\n<iframe style=\"overflow:hidden;height:100%;width:100%\" height=\"100%\" width=\"100%\" src=\"http://purcraft.com/madeinla/home2_height.html\"></iframe>"
] | [
"css",
"iframe",
"height",
"width",
"overflow"
] |
[
"Aws AuthenticationHandler",
"I am working on authenticating user on AWS Cognito android sdk but I am getting SRP error. I uncheck ADMIN_NO_SRP_AUTH, CUSTOM_AUTH_FLOW_ONLY, and USER_PASSWORD_AUTH and still getting the \"SRP Error\". Is there anything I am doing wrong. My code is below\n\n userPool = new CognitoUserPool(getApplicationContext(), \"us-east- \n 2_UMicfarEa\", \"6q46s4k4jgvmliumcf4h4p94rs\", \n \"t2dmr2ghna2l145qu4nst2gdr5actogeft7blr3eruv2yrvaye\", Regions.US_EAST_2);\n\n user = userPool.getUser( userName);\n\n authenticateDetails = new Hashtable();\n authenticateDetails.put(\"username\",userName);\n authenticateDetails.put(\"password\", passWord);\n user = userPool.getUser( userName);\n\n\n\n AuthenticationHandler authenticationHandler = new AuthenticationHandler() {\n @Override\n public void onSuccess(CognitoUserSession userSession, CognitoDevice \n newDevice) {}\n @Override\n public void getAuthenticationDetails(AuthenticationContinuation \n authenticationContinuation, String userId) { AuthenticationDetails \n authenticationDetails = new AuthenticationDetails(userName, passWord, \n authenticateDetails); authenticationContinuation.setAuthenticationDetails(authenticationDetails);\n authenticationContinuation.continueTask();}\n @Override\n public void getMFACode(MultiFactorAuthenticationContinuation \n multiFactorAuthenticationContinuation) {\n multiFactorAuthenticationContinuation.setMfaCode(mfaVerificationCode);\n multiFactorAuthenticationContinuation.continueTask();}\n @Override\n public void authenticationChallenge(ChallengeContinuation continuation) {}\n @Override\n public void onFailure(Exception exception) {}\n };\n user.getSessionInBackground(authenticationHandler);"
] | [
"java",
"android",
"amazon-web-services",
"aws-sdk",
"amazon-cognito"
] |
[
"moment.preciseDiff() not working properly",
"I am using momentjs precise difference to calculate the time difference between two moment objects but each time it returns 6 hours, however the difference should be less then 2 hours. Below is my code.\n\nThe first object contains US date which I converted using moment.tz('Asia/Karachi').\n\nCheck this image:"
] | [
"javascript",
"momentjs"
] |
[
"Find number of lines in label with fixed length and word wrap property true",
"I have a label with fixed length and word wrap property set to true. At run time that label has two lines e.g.:\ntest := 'quick brown fox jumps over the lazy dog';\n\nOn Label this text displayed as two lines\nquick brown fox jumps\nover the lazy dog\n\nI want to know number of lines at run time:\n#13#10 does not work."
] | [
"delphi",
"tlabel"
] |
[
"In the latest version of XCode, why does the simulator not run even with a settings reset?",
"I get this error when I try running my app in the simulator. The error is:\n\n\n An error was encountered while running (Domain = LaunchServicesError, Code = 0)\n\n\nI tried changing the name of the app and this happened.\nFurthermore, I tried cleaning the product and it didn't do anything, still having the same error of:\n\n\n Unable to run app in Simulator. An error was encountered while running (Domain = LaunchServicesError, Code=0) \n\n\nI also tried changing the name back to what it used to be in the Info file which you can see at postimg.org/image/erieubblp/. But it didn't change anything.\nIf you need anything else let me know.\n\nI've also done a Reset content and settings on the simulator.\n\nAlso, I checked all the other forum posts on this error and nothing worked."
] | [
"ios",
"objective-c",
"parse-platform",
"ios-simulator"
] |
[
"Add App Icon on lower left corner in lock screen",
"I have installed app on device and i want to show it in left lower corner in lock screen when it entered a specific region but i do not want to use iBeacon, Is there is a way to make using passbook card that i can add a locations and date/time to the pass.json file and read that location and time from the passbook card and show the app on the lower left corner on lock screen of the iPhone depend on the location or time from passbook card ?"
] | [
"ios",
"objective-c",
"ibeacon",
"passbook"
] |
[
"How to do sum of the two different time",
"i have the following code :\n\nSELECT distinct userinfo.userid,userinfo.name,timeframe,deptname from EarlyOut\nINNER JOIN userinfo ON USERINFO.USERID = earlyout.USERID\nINNDER JOIN DEPARTMENTS ON DEPARTMENTS.DEPTID = EarlyOut.DEFAULTDEPTID\n where date>='2015-02-01' and date<='2015-02-28' and\nDEPARTMENTS.DEPTNAME = 'abc'\n\n\nNow from above code i am getting following answer:\n\nuserid name timeframe deptname\n111 xyz 2015-02-05 08:00:00 abc \n111 xyz 2015-02-10 09:15:00 abc\n\n\nNow i want the following output:\n\nuserid name timeframe deptname\n111 xyz 17:15:00 abc \n\n\nI want the total of time\n\nSo How can i do that?"
] | [
"sql",
"sql-server",
"sql-server-2008"
] |
[
"Run ELF 64-bit LSB executable on Ubuntu 64",
"I am trying to run a package that is precompiled (supposedly for 'linux64') but get the following error message:\n\nt.kuilman@steroid:~/Peeper/bin/netchop-3.1/bin$ ./netChop \n-bash: ./netChop: cannot execute binary file: Exec format error\n\n\nI checked how this file is compiled (see below) and it turns out to be an ELF 64-bit LSB executable.\n\nt.kuilman@steroid:~/Peeper/bin/netchop-3.1/bin$ file ./netChop \n./netChop: ELF 64-bit LSB executable, no machine, version 1 (SYSV), statically linked, for GNU/Linux 2.4.1, for SuSE 9.1, stripped\nt.kuilman@steroid:~/Peeper/bin/netchop-3.1/bin$ ldd ./netChop \n not a dynamic executable\nt.kuilman@steroid:~/Peeper/bin/netchop-3.1/bin$ uname -a\nLinux steroid 3.13.0-76-generic #120-Ubuntu SMP Mon Jan 18 15:59:10 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux\n\n\nHow can I get this file to run on my system (Ubuntu 14.04.1 LTS (GNU/Linux 3.13.0-76-generic x86_64))?"
] | [
"linux",
"ubuntu",
"elf"
] |
[
"jQuery Parse JSON Response",
"I am successfully Posting to a PHP file, and getting a good response. The part I cannot seem to get is parsing it out then displaying it on my page. Here is my javascript in a validate handler:\n\nsubmitHandler: function(form) {\n var formData = $(form).serialize();\n $.post('http://test.php', formData, function(data) {\n if(data.success) {\n $('#load').show();\n var response = i;\n $('#load').hide();\n //var msg = '';\n for(var i = 0; i < x.flights.length; i++) {\n msg += '<span>';\n msg += '<p>Flight Number: ' + x.flights[i].flight_number + '</p>';\n msg += '<p>Cost: ' + x.flights[i].cost + '</p>';\n msg += '</span>';\n }\n //this is were I think it should display. but It's not working\n\n $('#load').html(msg);\n\n\nHere is my json response:\n\n success\ntrue\n\n message\n\"Success\"\n\nflights\n[Object { flight_number=\"334\", cost=\"983.40\", departure_city=\"Kearney Regional Airpor...arney, Nebraska - (EAR)\", more...}]\n\n0\nObject { flight_number=\"334\", cost=\"983.40\", departure_city=\"Kearney Regional Airpor...arney, Nebraska - (EAR)\", more...}\n\nflight_number\n\"334\"\n\ncost\n\"983.40\"\n\ndeparture_city\n\"Kearney Regional Airport, Kearney, Nebraska - (EAR)\"\n\narrival_city\n\"Chadron Muni Airport, Chadron, Nebraska - (CDR)\"\n\ndeparts\n\"2014-03-19 04:33:00\"\n\narrives\n\"2014-03-19 08:12:00\"\n\nduration\n\"219\"\n\nadult_seats_available\n\"2\"\n\nsenior_seats_available\n\"1\"\n\n\nI know you you are not seeing the JSON response, but I can see it in FF firebug. I'm new to jQuery/JSON, and I just want to print the response to my page. Thanks in advance."
] | [
"javascript",
"jquery",
"json"
] |
[
"Each element in list at least equal to the previous one",
"A list of monthly sales until November, I want to know if the sales trend is upward.\n\nDefinition of upward: each monthly sales is greater or at least equal to previous month's.\n\n\n\nThis question is similar to Python: Finding a trend in a set of numbers, but much simpler - only looking the list of numbers.\n\nWhat I have now is, to check them one by one (in a list). If one month satisfies the condition, it adds an \"ok\" to a new list. When total number of \"ok\" equals to 10. The original list of numbers are upward.\n\nimport pandas as pd\n\ndf_a = pd.DataFrame([['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov'],\n[278,342,476,500,559,594,687,739,917,940,982]]).T\ndf_a.columns = [\"Month\", \"Sales\"]\n\nsales_a = df_a['Sales'].tolist()\nok_a = []\n\nfor num, a in enumerate(sales_a):\n if sales_a[num] >= sales_a[num-1]:\n ok_a.append(\"ok\")\n\nif ok_a.count(\"ok\") == 10:\n print (\"df_a is uptrend.\")\n\n\nWhat's the smarter way to do it? Thank you."
] | [
"python",
"pandas",
"list",
"dataframe"
] |
[
"Entity with Inner class for building the entity",
"I am trying out one-to-one mapping in JPA,\nhere i have taken relationship between Student and Contact, each student has an contact.\n\ni have create Student entity as follows,\n\n@Entity\n@Table(name=\"TBL_STUDENT\")\npublic class Student implements Serializable{\n\n public Student(){ }\n @Id\n @GeneratedValue(strategy=GenerationType.IDENTITY)\n @Column(name=\"ID\") \n private Integer studentId;\n\n @OneToOne(targetEntity=StudentContact.class,fetch=FetchType.LAZY)\n @JoinColumn(name=\"CONTACT_ID\")\n private StudentContact contact;\n ....\n ....\n ....\n}\n\n\nNow the StudentContact entity as follows,\n\n@Entity\n@Table(name=\"TBL_STD_CONTACT\")\npublic class StudentContact extends Serializable{\n public StudentContact(){ }\n\n @Id\n @Column(name=\"ID\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Integer contactId;\n ...\n ...\n // all the properties mapped,\n\n public static class Builder{\n private Integer contactId;\n private String phoneNo;\n private String streetAddr;\n ....\n // all the properties as same as StudentContact\n\n public Builder(String val){\n this.city = val;\n }\n\n public Builder setContactId(Integer contactId) {\n this.contactId = contactId;\n return this;\n }\n\n // rest all the setter methods are like the above, having return type Builder\n\n public StudentContact build(){\n return new StudentContact(this);\n }\n }\n\n private StudentContact(Builder builder){\n this.contactId = builder.contactId;\n this.city = builder.city;\n this.phoneNo = builder.phoneNo;\n .......\n ...\n }\n}\n\n\nIn the above StudentContact Entity you can see i have created an inner class Builder, whose responsibility is to build StudentContact object by using its \"build\" method, which you can see in below mentioned StudentTest class\n\nNow i have written a StudentTest class which has the main method as follows,\n\npublic class StudentTest {\n public static void main(String [] args){\n try{\n StudentDAO dao = new StudentDAO();\n Student student = dao.getEntity(110); \n StudentContact contact = new StudentContact.Builder(\"Bhubaneshwar\")\n .setPhoneNo(\"9867342313\")\n .setPinCode(\"400392\")\n .setState(\"Odhisha\").build(); \n\n student.setContact(contact);\n dao.updateEntity(student);\n }catch(Exception e){\n e.printStackTrace();\n }\n}\n\n\nWhen i run StudentTest from netbeans IDE, it gives as error \n\nException in thread \"main\" java.lang.VerifyError: Constructor must call super() or this() before return in method com.entities.StudentContact.<init>()V at offset 0\n\n\nI am not able to understand this error, whether this error is because for the inner class which i have created in StudentContact class,\n\nHow can i solve this,"
] | [
"java",
"hibernate",
"jpa",
"orm"
] |
[
"Canvas drawings, like lines, are blurry",
"I have a <div style=\"border:1px solid border;\" /> and canvas, which is drawn using:\n\ncontext.lineWidth = 1;\ncontext.strokeStyle = \"gray\";\n\n\nThe drawing looks quite blurry (lineWidth less than one creates even worse picture), and nothing near to the div's border. Is it possible to get the same quality of drawing as HTML using canvas? \n\n\r\n\r\nvar ctx = document.getElementById(\"canvas\").getContext(\"2d\");\r\nctx.lineWidth = 1;\r\nctx.moveTo(2, 2);\r\nctx.lineTo(98, 2);\r\nctx.lineTo(98, 98);\r\nctx.lineTo(2, 98);\r\nctx.lineTo(2, 2);\r\nctx.stroke();\r\ndiv {\r\n border: 1px solid black;\r\n width: 100px;\r\n height: 100px;\r\n}\r\ncanvas, div {background-color: #F5F5F5;}\r\ncanvas {border: 1px solid white;display: block;}\r\n<table>\r\n<tr><td>Line on canvas:</td><td>1px border:</td></tr>\r\n<tr><td><canvas id=\"canvas\" width=\"100\" height=\"100\"/></td><td><div>&nbsp;</div></td></tr>\r\n</table>"
] | [
"html",
"canvas"
] |
[
"Randomly round to integer in Excel",
"Is there a way in Excel to randomly round up or down a float to an integer number? Possibly with 50% chance of rounding up.\nSomething like:\nROUND_RANDOM(3.6,0) = 3\n\nROUND_RANDOM(3.6,0) = 4\n\nROUND_RANDOM(3.6,0) = 4\n\nROUND_RANDOM(3.6,0) = 3"
] | [
"excel",
"random",
"excel-formula",
"rounding"
] |
[
"AntiSamy to prevent XSS in java?",
"Basically I have a web-app which it currently is vulnerable to XSS. Based on my research I found one of good and open library that can help would be AntiSamy. So I downloaded the library .jar file which is antisamy-1.5.1.jar and The policy file antisamy-slashdot-1.4.4.xml and exported it to my project WEB-INF directory.\n\nI'm pretty much new to AntiSamy and don't really know how to implement it on a string to encode and secure it from XSS.\n\nSay I've a string of: String XSSPossible = \"<script>alert(\"It's vulnerable.\");</script>\"; Now I want to encode this to a normal text and secure it from XSS.\n\nMuch Regards."
] | [
"java",
"html",
"xss",
"encode",
"antisamy"
] |
[
"Using a callback when interval finishes",
"I am making a tree traversal program which animates the traversal using setInterval. While setInterval is running, I want to disable \"run traversal\" button so they can't keep running new traversals.\n\nWhen the traversal finishes and interval is cleared, I want to re-enable the buttons. A stackoverflow answer suggested using callback to call enableButtons once the interval has finished... \n\nthis.traverseNodes(nodesToDraw, aryList, e.target.id, this.enableButtons); \n\n api.traverseNodes = function (nodesToDraw, dataStructureList, algType, enableButtonsCallback) {\n ...\n var myInterval = setInterval (function() {\n if (i >= nodesToDraw.length-1) {\n matrixTraversalRunning = false;\n enableButtonsCallback(dsTraversalRunning, matrixTraversalRunning);\n clearInterval(myInterval);\n }\n\n\nThis works fine, but then thought... why do I need a callback? I can just call enableButtons directly after the interval finishes, as such:\n\nthis.traverseNodes(nodesToDraw, aryList, e.target.id);\n\napi.traverseNodes = function (nodesToDraw, dataStructureList, algType) {\n ...\n var myInterval = setInterval (function() {\n if (i >= nodesToDraw.length-1) {\n self.enableButtons(dsTraversalRunning); //call function to enable buttons\n clearInterval(myInterval);\n }\n ...\n\n\nFrom this, I am confused on when to use a callback. Is it necessary here?"
] | [
"javascript",
"jquery"
] |
[
"CRLF (\\r\\n) in PHP's header() function",
"Why/when does one has to use CRLF's at the end of header in PHP?\nHere is one example (it's not necessarily correct):\n\nheader(\"method: POST\\r\\n\");\nheader('Host: '.get_option('transact_url').\"\\r\\n\");\nheader('Content-type: application/x-www-form-urlencoded');\nheader('Content-length: '.strlen($transaction).\"\\r\\n\");\nheader($transaction.\"\\r\\n\\r\\n\");\nheader(\"Connection: close\\r\\n\\r\\n\");\nheader(\"Location: \".$key_client_url.\"\\r\\n\");"
] | [
"php",
"http-headers",
"newline"
] |
[
"SSRS Report Manager set default zoom level",
"I have deployed around 40 report parts to my reporting server which are all working correctly.\n\nThe problem is my zoom is default 100 for all of them, I want a number of them to default to 75.\n\nI have tried creating a portal with links to all report parts and using the &rc:Zoom=75\non the end of the URL for the link but it still defaults to 100.\n\nCan anyone suggest how I can achieve what I want?"
] | [
"sql-server",
"sql-server-2008",
"reporting-services",
"ssrs-2008"
] |
[
"Is this possible to use jquery dependant script (lazy load) before jquery.js script tag (footer)?",
"I'm getting html from ajax callback. Inside this content I have script tag for loading a code which uses jQuery, but I have always jQuery is undefined error.\n\nAll scripts are attached before </body>\n\nIs this any option to make this work, besides moving jQuery to the head?"
] | [
"javascript",
"jquery",
"html",
"ajax"
] |
[
"excel searching for key word on multiple lines",
"Is there a way to combine the following Excell formula into one line and to cover all lines? for example look at a1 and a 5? \n\n=IF(A1=\"black\",B1,0)-IF(D1=\"black\",E1,0)+\n IF(A2=\"black\",B2,0)-IF(D2=\"black\",E2,0)+\n IF(A3=\"black\",B3,0)-IF(D3=\"black\",E3,0)+\n IF(A4=\"black\",B4,0)-IF(D4=\"black\",E4,0)+\n IF(A5=\"black\",B5,0)-IF(D5=\"black\",E5,0)+\n IF(A6=\"black\",B6,0)-IF(D6=\"black\",E6,0)+\n IF(A7=\"black\",B7,0)-IF(D7=\"black\",E7,0)+\n IF(A8=\"black\",B8,0)-IF(D8=\"black\",E8,0)+\n IF(A9=\"black\",B9,0)-IF(D9=\"black\",E9,0)+\n IF(A10=\"black\",B10,0)-IF(D10=\"black\",E10,0)+\n IF(A11=\"black\",B11,0)-IF(D11=\"black\",E11,0)+\n IF(A12=\"black\",B12,0)-IF(D12=\"black\",E12,0)+\n IF(A13=\"black\",B13,0)-IF(D13=\"black\",E13,0)+\n IF(A14=\"black\",B14,0)-IF(D14=\"black\",E14,0) \n\n\nSo basically i am trying to scan all of A for the key word of black. If the key word black is in A I want to go over to B and get the numerical value. After that I want to go over the C and search for the key word of black, if that is there i want to go to D and get that numerical value. i want B to be positive values (that represents inventory i have received) and i wand D to represent negative values (that is inventory i have shipped out)."
] | [
"excel"
] |
[
"How to understand if an object belong to a generic collection through introspection",
"Let's say I have a reference to an Object. I'd like to use introspection to find out if it is a reference to a collection but I don't know (and don't care) about the generic type of the elements it holds.\n\nAs an example:\n\nList<int> l;\nObject referenceToList = l;\n\nif (typeof(referenceToList) == ??)\n{\n //condition is true for List<int>, List<float> ....\n}\n\n\nAny suggestion?"
] | [
"c#",
"reflection"
] |
[
"Save a List not serialisable to a file",
"I would like to save and restore the size and order of columns datagrid on a WPF application.\nI store this data on two lists :\n\nList<DataGridColumn>\nList<SortDescription>\n\n\nDataGridColumn and SortDescription are MSDN class not serialiable.\nI would like to save these list in a file ( xml or txt...)\n\nWhat is the simplest way please ?\n\nBest regards,\nNixeus"
] | [
"c#",
"wpf",
"xml",
"serialization",
"datagrid"
] |
[
"Please install package: 'Xamarin.Android.Support.Animated.Vector.Drawable' available in SDK installer",
"I am trying run my working project in another pc gives me this types of errors.\n\n\n Please install package: 'Xamarin.Android.Support.Animated.Vector.Drawable' available in SDK installer. Java library file C:\\Users\\Administrator\\AppData\\Local\\Xamarin\\Xamarin.Android.Support.Animated.Vector.Drawable\\23.3.0.0\\content\n\n\nI tried some of the solutions that I found on the internet, but they didn't help me.\n\n=> deleted zip file and downloaded again.\n\n=> deleted bin and obj folder and restarted VS\n\n=> clean, rebuild, run"
] | [
"ios",
"xamarin",
"packages"
] |
[
"Error when using pander on a data.table created with data.table::dcast",
"this is more a question of interest, as I found a work-around, although I don't find it pretty. \n\nWhen I updated the pander package (to 0.6.1) an error started to occure whenever I try to to use pander() on a data.table in wide format that was constructed from a data.table (package version 1.10.4-3 or older) in long format using data.table::dcast():\n\n\n Error in data.table::setattr(x, \"row.names\", row.names.dt) : \n row names must be 'character' or 'integer', not 'double'\n\n\nI tried to remove any row names, but to no avail. After some research, I found out that with reshape2::dcast there is no error, but reshape2::dcast transforms the data.table in a data.frame, which isn't something I want. Of course I could transform the data.frame back into a data.table.\n\nHere is some sample code that produces the error for me: \n\nlibrary(pander)\nlibrary(data.table)\n\ndt.long <- data.table(time=c(1, 1, 2, 2), T=c(\"c\", \"t\", \"c\", \"t\"), count=c(10, 15, 15, 20))\npander(dt.long) # this works fine\n\ndt.wide <- dcast(dt.long, time~T, value.var = \"count\")\nrow.names(dt.wide) <- NULL # doesn't help\nrow.names(dt.wide) <- c() # doesn't help either\npander(dt.wide) # produces error\n\n# work-around\nlibrary(reshape2)\ndt.wide <- dcast(dt.long, time~T, value.var = \"count\")\npander(dt.wide) # works fine\nclass(dt.wide) # but this is a data.frame\ndt.wide <- data.table(dt.wide) # now it is a data.table again\n\n\nIs there a simple way to keep the data as data.table and use pander as it worked before?\nI use R version 3.3.2, in case this matters.\n\nThank you in advance!"
] | [
"r",
"data.table",
"pander",
"dcast"
] |
[
"Wix Error 1920 - While updating with a lower version the setup removes the installed version on error instead of rolling it back",
"I have two versions of setup say v1 and v2. Both of them are run using the same privilages and both of them install and start a service - which is also the same.\n\nWhen I install v1 first and then v2 everything works fine. The setup prompts to stop the services already running before the update and then proceeds.\n\nThe problem occurs when I install v2 first and then try to run v1. The setup discovers that the product has been installed previously and then prompts to stop the previously running services.\n\nIt manages to stop these services and then tries to install it again. While trying to start the services it fails with the following message in the log:\n\n\"Error 1920. Service 'Service Name' (serviceName) failed to start. Verify that you have sufficient privileges to start system services.\"\n\nThe error dialog also gives options to Retry and Cancel the setup. On retry the same thing happens again.\n\nOn cancel the setup goes into RollBack mode but it does not actually restores the previous version i.e. v2. Instead it just removes v2. It should have either restored the original setup or carried out the downgrade?"
] | [
"wix",
"wix3.5",
"wix3"
] |
[
"NSDateFormatter respect user settings - no minutes",
"I'm trying to turn a given hour to AM/PM or 24-hour display depending on the user's preferences.\n\nI currently have:\n\n+ (NSString *)formatWithTemplate:(NSString *)template {\n return [NSDateFormatter dateFormatFromTemplate:template options:0 locale:[NSLocale currentLocale]];\n}\n\n+ (NSString *)format:(NSDate *)date {\n [formatter setDateFormat:[MyFormatter formatWithTemplate:@\"h a\"]];\n [dateFormatter setDateStyle:NSDateFormatterShortStyle];\n [dateFormatter setTimeStyle:NSDateFormatterNoStyle];\n return [formatter stringFromDate:date];\n}\n\n\nExample usage:\n\n[MyFormatter format:24] would display \"24:00\" if using a 24 hour clock but \"12:00 PM\" if using a 12 hour clock (in the user's device settings).\n\nHowever, for 12 hour clock it keeps displaying: \"12:00 PM\". Is there any way to get rid of the :00 while respecting locale and the user's settings so that it displays: \"12 PM\" instead of \"12:00 PM\"?\n\nWhen I use:\n\n[dateFormatter setDateStyle:NSDateFormatterShortStyle];\n[dateFormatter setTimeStyle:NSDateFormatterNoStyle];\n\n\nit respects the user's settings but completely ignores my format. However, if I use my format, it ignores the user's settings.\n\nAny ideas?"
] | [
"ios",
"objective-c",
"nsdateformatter"
] |
[
"Error 404 on page reload with vue3 routing",
"Problem\nWhen I hit reload on a route, e.g /installer, in vue3.js I get the following error:\n\nCode\nI use the Router with the following setup:\nconst router = createRouter({\n history: createWebHistory(process.env.BASE_URL),\n routes,\n});\n\nAdditional Information\n(I don't use createWebHashHistory to get rid of the hashtags in url)\nI also get this error when I go to the route, e.g. /installer, directly and not via link.\nQuestion\nHow to resolve this error?"
] | [
"javascript",
"html",
"vue.js",
"vue-router",
"vuejs3"
] |
[
"How to send image with multipart request in Flutter?",
"I want to send an image to the server and upload it. I did this with the following code but it did not upload to the server.\nI have to send a parameter containing a photo with the name of "img" to the server. In Postman the upload operation is performed, but it is not uploaded in the flutter.\n Future<String> uploadImage(filename) async {\n var model=widget.parent.selectedJobModel;\n var request = http.MultipartRequest('POST', Uri.parse(baseUrl+"update_job"));\n request.headers.addAll({\n "key":reqKey,\n "token":widget.parent.widget.spParent.userLogin,\n "user_id":widget.parent.widget.spParent.userNo,\n "job_id":model.job_id,\n });\n request.files.add(await http.MultipartFile.fromPath('img', filename));\n var res = await request.send();\n return res.reasonPhrase;\n }"
] | [
"php",
"flutter",
"upload",
"multipart"
] |
[
"Accordion with increasing widths",
"I have a jQuery accordion on my site with all tabs open\n\nWhat I want is for the width of the closed tabs (when it is closed) to increase in the order that it is closed\n\nExample here\n\n\nWhat I want to happen is that if there are 10 tabs and only the first 2 are closed, tab1 width should be 95% & tab2 should be 100%. \nIf tab 3 is closed, tab1 width=90%, tab2=95% & tab3=100%.\n\nHere's what I've tried:\n\nI have added a jQuery which toggles a class closed to the closed tab & have tried using the nth-last-child to that for example\n\n.tab.closed:nth-last-child(1) {\n width: 100%\n}\n\n.tab.closed:nth-last-child(2) {\n width: 95%\n}\n\n\nBut what is happening is that pseudo class is appending itself to the tab's main class & not just to the tabs with the closed class. \n\nIs this method logical?\nOr is there some better way to do this?\n\nEdit: Added a snippet below.\n\n\r\n\r\n$('.panel-title a').click(function() {\r\n if ($('.collapse').hasClass('in')) {\r\n $(this).closest('.panel.panel-white').toggleClass(\"open\");\r\n $(this).closest('.panel.panel-white').toggleClass(\"closed\");\r\n }\r\n});\r\n.panel.panel-white .panel-heading {\r\n background: #0769AD;\r\n}\r\n\r\n.panel.panel-white .panel-heading a {\r\n color: white\r\n}\r\n\r\n.closed:nth-last-child(1) {\r\n width: 80%;\r\n}\r\n\r\n.closed:nth-last-child(1) {\r\n width: 80%;\r\n}\r\n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\r\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\r\n<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\r\n\r\n\r\n<div class=\"panel-group content-group-lg\">\r\n <div class=\"panel panel-white open\">\r\n <div class=\"panel-heading\">\r\n <h6 class=\"panel-title\">\r\n <a data-toggle=\"collapse\" href=\"#collapse-group1\">Collapsible Item #1</a>\r\n </h6>\r\n </div>\r\n <div id=\"collapse-group1\" class=\"panel-collapse collapse in\">\r\n <div class=\"panel-body\">\r\n Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"panel panel-white closed\">\r\n <div class=\"panel-heading\">\r\n <h6 class=\"panel-title\">\r\n <a class=\"collapsed\" data-toggle=\"collapse\" href=\"#collapse-group2\">Collapsible Item #2</a>\r\n </h6>\r\n </div>\r\n <div id=\"collapse-group2\" class=\"panel-collapse collapse\">\r\n <div class=\"panel-body\">\r\n Тon cupidatat skateboard dolor brunch. Тesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda.\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"panel panel-white closed\">\r\n <div class=\"panel-heading\">\r\n <h6 class=\"panel-title\">\r\n <a class=\"collapsed\" data-toggle=\"collapse\" href=\"#collapse-group3\">Collapsible Item #3</a>\r\n </h6>\r\n </div>\r\n <div id=\"collapse-group3\" class=\"panel-collapse collapse\">\r\n <div class=\"panel-body\">\r\n 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it.\r\n </div>\r\n </div>\r\n </div>\r\n</div>\r\n<!-- /basic collapsible -->"
] | [
"jquery",
"html",
"css",
"accordion",
"jquery-ui-accordion"
] |
[
"iOS13 system UITabBar",
"How to remove the black line at the top of tab,\n\n[self.tabBar setShadowImage:[UIImage new]];\nself.tabBar.backgroundImage = [UIImage new];\n\n\niOS13 invalid"
] | [
"ios",
"objective-c",
"uitabbar",
"ios13"
] |
[
"How do I set a js action when the page reach an id?",
"Well the thing is really simple, I'm a newbi on Js and know almost nothing, the thing is that I want to change a navbar's style but I just can do it when it reaches a specific amount of pixels, I would like to make it change when it reaches the next div id of the page, this is the code: \n\n$(window).scroll(function() { \n var scroll = $(window).scrollTop();\n\n if (scroll >= 500) {\n $(\".fondoa\").addClass(\"fondoazul\");\n } else {\n $(\".fondoa\").removeClass(\"fondoazul\");\n }\n});\n\n\nThank you so much for your help"
] | [
"javascript",
"css"
] |
[
"Issue with javascript timer",
"I wrote a timer code via JavaScript. I want to stop this timer when I click on a button, and restart it by double clicking the same button, however, it currently only works once.\n\nHere is the code:\n\n\r\n\r\nlet pElement = document.createElement('p');\r\ndocument.body.appendChild(pElement);\r\n\r\nlet liveTimer = () => {\r\n let date = new Date();\r\n let onlineTime = date.toLocaleTimeString();\r\n\r\n pElement.innerHTML = onlineTime;\r\n};\r\n\r\nlet setI = setInterval(liveTimer, 1000);\r\n\r\nfunction stopTime() {\r\n clearInterval(setI);\r\n}\r\n\r\nfunction startTimer() {\r\n setInterval(liveTimer, 1000);\r\n}\r\n<button onclick=\"stopTime()\" ondblclick=\"startTimer()\">click me</button>"
] | [
"javascript",
"timer"
] |
[
"How to avoid \"Task size too large\"?",
"My issue is that I'm getting task size too large warnings while using Spark SQL to denormalize tables into larger tables.\n\nBefore people point to other answers saying to use broadcast or avoid closing on the entire class; let me say that I've read those and am still confused specifically when using Spark SQL.\n\nI have task sizes going up to 10 times the recommended size when using Spark SQL. \n\nHere's the situation:\n\n\nI have 10+ tables/data-frames to join into an uber-table.\nI created a single scala object and in the body populated those 10 tables from their CSVs.\nI import the members of that object (just the tables) in other objects where the calculation to form he uber-tables is.\nWhen the Spark-SQL joins between those 10 tables run to, say, write the result table to a parquet file, I get the task size warnings.\n\n\nExtra Information:\n\n\nI've tried moving the source tables into different classes and embedding them in functions and the task sizes did not change.\nI'm unsure how broadcast could help with this as the source data is read straight into data frames using Spark-CSV, and thus should already be distributed."
] | [
"apache-spark",
"apache-spark-sql"
] |
[
"Spree - Creating site-wide preferences",
"This is probably a routine job for anyone who customizes Spree to fit their needs, but I'm having quite a hard time with it.\n\nI want to create a preference that will store an array of products, in order to display them as \"featured products\" in the homepage. I went through this guide, and I already created a file under lib/spree/ in my application tree. The file looks like this:\n\nclass Spree::HomepageConfiguration < Spree::Preferences::Configuration\n preference :featured_products, :string\nend\n\n\nAfter that I added the lib/spree folder in the autoload_paths in the application.rb file:\n\nconfig.autoload_paths += %W(#{config.root}/lib/spree/)\n\n\nFinally I created an initializer called homepage_configuration under config/initializers/ to configure the preference:\n\nmodule Spree\n Spree::MyApp::Config = Spree::HomepageConfiguration.new\nend\n\nSpree::MyApp::Config[:featured_products] = [\"a\", \"b\"]\n\n\nBut, when I run the server I get this error:\n\nExpected C:/path/to/my/application/lib/spree/homepage_configuration.rb to define HomepageConfiguration (LoadError)\n\n\nI'm not sure what I'm doing wrong. Any suggestions are welcome.\n\nI'm running Rails 3.2.13 and using Spree from 1-3-stable branch."
] | [
"ruby-on-rails",
"spree"
] |
[
"NodeJS & Javascript: Filter table with pagination",
"I use this code when I have table with little data and was very useful, but when I add pagination into table now it works only in page where I am. This is route with pagination that I need for filtering:\n\nrouter.get('/', (req, res)=>{\n const perPage = 10;\n const page = req.query.page || 1;\n\n ElectoralUnit.find({})\n .skip((perPage * page) - perPage)\n .limit(perPage)\n .populate('town')\n .then(electoralUnits=>{\n\n ElectoralUnit.count().then(electoralUnitCount=>{\n Town.find({}).sort({name: 1}).then(towns=>{\n res.render('admin/electoralUnits/index', {\n electoralUnits: electoralUnits,\n towns: towns,\n current: parseInt(page),\n pages: Math.ceil(electoralUnitCount / perPage)\n });\n });\n });\n });\n});\n\n\nTable:\n\n<div class=\"col-sm-8\">\n <input class=\"form-control\" type=\"text\" id=\"myInput\" onkeyup=\"filterTowns()\" placeholder=\"Filter: Ukucajte ime grada/opštine\">\n <table class=\"table table-hover\" id=\"myTable\">\n <thead>\n <tr>\n <th>City</th>\n <th>IJ</th>\n <th>Datum unosa</th>\n </tr>\n </thead>\n <tbody>\n {{#each electoralUnits}}\n <tr>\n <td>{{town.name}}</td>\n <td>{{name}}</td>\n <td>{{generateDate date 'DD. MMM. YYYY.'}}</td>\n <td><a href=\"/admin/electoralUnits/edit/{{id}}\" class=\"btn btn-outline-info btn-sm\">Edit</a></td>\n <td>\n <form action=\"/admin/electoralUnits/{{id}}?_method=DELETE\" method=\"post\">\n <button class=\"btn btn-outline-danger btn-sm\">Delete</button>\n </form>\n </td>\n </tr>\n {{/each}}\n </tbody>\n </table>\n <!-- Pagination -->\n <ul class=\"pagination justify-content-center mb-4\">\n {{#paginate current=current pages=pages}}{{/paginate}}\n </ul>\n</div>\n\n\nJavascript:\n\nfunction filterTowns() {\n // Declare variables\n var input, filter, table, tr, td, i;\n input = document.getElementById(\"myInput\");\n filter = input.value.toUpperCase();\n table = document.getElementById(\"myTable\");\n tr = table.getElementsByTagName(\"tr\");\n\n // Loop through all table rows, and hide those who don't match the search query\n for (i = 0; i < tr.length; i++) {\n td = tr[i].getElementsByTagName(\"td\")[0];\n if (td) {\n if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {\n tr[i].style.display = \"\";\n } else {\n tr[i].style.display = \"none\";\n }\n }\n }\n}\n\n\nI Google for this solution and I find some solutions like this but no luck for my code.\n\nHow can I modify code from w3schools to filter through whole pages that pagination provides and not just in page that I'm current?"
] | [
"javascript",
"node.js",
"filter"
] |
[
"Unable to monitor Network storage location(NETWORK SHARED PATH) using Python Watch Dog Library in Windows Server 2012R2",
"When I use the below code to monitor any storage location on the same server, it is working perfectly. Whereas, when I try to use the same with the network drive(Mapped to my machine already), it doesn't work.\nPlease have a look at the code and suggest how to proceed. Please let me know if I can use any other library or other technology to achieve the purpose.\nCurrently I am using Python Watchdog Library.\n\nimport time\nfrom watchdog.observers import Observer\nfrom watchdog.events import PatternMatchingEventHandler\nfrom watchdog.observers.polling import PollingObserver\n\nimport os\nimport hashlib\nimport shutil,time\n\nif __name__ == \"__main__\":\n patterns = \"*\"\n ignore_patterns = \"\"\n ignore_directories = False\n case_sensitive = True\n my_event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)\n\ndef on_created(event):\n print(f\"hey, {event.src_path} has been created!\")\n\ndef on_deleted(event):\n print(f\"Someone deleted {event.src_path}!\")\n\ndef on_modified(event):\n print(f\"{event.src_path} has been modified\")\n\ndef on_moved(event):\n print(f\"someone moved {event.src_path} to {event.dest_path}\")\n\nmy_event_handler.on_created = on_created\nmy_event_handler.on_deleted = on_deleted\nmy_event_handler.on_modified = on_modified\nmy_event_handler.on_moved = on_moved \n\npath = \"\\\\\\\\apc.ent.petap.net\\\\dfs\\\\Resource\\\\ABS\\\\ARCHIVE\\\\\" ##This is my shared drive, I also tried #mapping it to the system, but the same thing I am getting. No error, but no response.\ngo_recursively = True\n#my_observer = Observer()\nmy_observer = PollingObserver()\nmy_observer.schedule(my_event_handler, path, recursive=go_recursively)\n\nmy_observer.start()\ntry:\n while True:\n time.sleep(1)\nexcept KeyboardInterrupt:\n my_observer.stop()\n my_observer.join()"
] | [
"python-3.x",
"windows",
"windows-server-2012-r2",
"python-watchdog",
"file-monitoring"
] |
[
"How to configure Spring cloud stream (kafka) to use protobuf as serialization",
"I am using Spring cloud stream (kafka) to exchange messages between producer and consumer microservices. \nIt exchanges data with native java serialization. As per Spring cloud documentation, It supports JSON,AVRO serialization.\n\nIs any one tried protobuf serialization (message converter) in spring cloud stream\n\n---------------- Later Added \n\nI wrote this MessageConverter\n\npublic class ProtobufMessageConverter<T extends AbstractMessage > extends AbstractMessageConverter\n{\n private Parser<T> parser;\n public ProtobufMessageConverter(Parser<T> parser)\n\n {\n super(new MimeType(\"application\", \"protobuf\"));\n this.parser = parser;\n }\n\n @Override\n protected boolean supports(Class<?> clazz)\n {\n if (clazz != null)\n {\n return EquipmentProto.Equipment.class.isAssignableFrom(clazz);\n }\n return true;\n }\n\n @Override\n public Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint)\n {\n if (!(message.getPayload() instanceof byte[]))\n {\n return null;\n }\n try\n {\n// return EquipmentProto.Equipment.parseFrom((byte[]) message.getPayload());\n return parser.parseFrom((byte[]) message.getPayload());\n }\n catch (Exception e)\n {\n this.logger.error(e.getMessage(), e);\n }\n return null;\n }\n\n @Override\n protected Object convertToInternal(Object payload, MessageHeaders headers, Object conversionHint)\n {\n return ((AbstractMessage) payload).toByteArray();\n }\n\n}"
] | [
"protocol-buffers",
"spring-cloud-stream"
] |
[
"How to compare two MutableArrays and display the unmatched value in iphone?",
"I have two MutableArray values like.\n\nNSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@\"Apple\", @\"Orange\", @\"Grapes\", @\"Banana\", nil];\n\nNSMutableArray *array1=[[NSMutableArray alloc]initWithObjects:@\"Apple\", @\"Orange\", @\"Grapes\", nil];\n\n\nNow i have to compare that two Mutable arrays and display that unmatched object \"Banana\" into one string.\n\nI am fresher to iOS so, anybody would send me the code for that problem. \n\nThanks in Advance."
] | [
"iphone",
"ios",
"objective-c",
"nsmutablearray"
] |
[
"Objective-C calling a method from another method",
"Say if i have a method as follows;\n\n - (void)carpentorLoad {\n NSlog(@\"HI... Hello\");\n }\n\n\nNow, i need to call this method from another method, say - (int) CallingMethod\n\n-(int) CallingMethod{\n // Here, i need to call carpentorLoad Method\n return 0;\n}\n\n\nHow should i call carpentorLoad from CallingMethod do this?"
] | [
"objective-c"
] |
[
"SQL Server Index Creation",
"I need to create non clustered index on a table, I will be using 5 columns in the where clause. I will have to use include(Covering) to avoid lookup. Shall I create 5 non clustered index with include columns for each index or Shall I create one index with 5 columns with include columns. I will be having around 50 million records in it. What would be best for above given scenarios. Please suggest me the best way to increase the retrieval performance."
] | [
"sql",
"sql-server",
"indexing"
] |
[
"Remove white space on HTML/CSS banner?",
"I have tried every kind of CSS trick I know to remove this white space including cell-padding, margins, padding ect ect. \n\nAny idea how to remove this white space below the \"sign up\" on this banner?\n\nhttp://oil.wpengine.com/"
] | [
"html",
"css",
"wordpress"
] |
[
"Why initialize a new Random() with unchecked(Environment.TickCount * 31)?",
"I found this initialization of a Random instance:\n\nvar random = new Random(unchecked(Environment.TickCount * 31));\n\n\nWhy not simply use new Random()?"
] | [
"c#",
"random"
] |
[
"Plot line graph from histogram data in matplotlib",
"I have a numpy array of ints representing time periods, which I'm currently plotting in a histogram to get a nice distribution graph, using the following code:\n\nax.hist(data,bins=100,range=(minimum,maximum),facecolor=\"r\")\n\n\nHowever I'm trying to modify this graph to represent the exact same data using a line instead of bars, so I can overlay more samples to the same plot and have them be clear (otherwise the bars overlap each other). What I've tried so far is to collate the data array into an array of tuples containing (time, count), and then plot it using\n\nax.plot(data[:,0],data[:,1],color=\"red\",lw=2)\n\n\nHowever that's not giving me anything close, as I can't accurately simulate the bins option of the histogram in my plot. Is there a better way to do this?"
] | [
"python",
"numpy",
"matplotlib"
] |
[
"jOpenDocumet: How to add date style to cell",
"I need to add a custom date style (dd/MM/yyyy) to a cell using jOpenDocumet. I didn't find examples in the official documentation or in the internet searches\nCan anyone provide me with an example? My code is this:\nFile fileODS = new File(pathDestino, fileName);\n char separator = ';';\n char quotechar = '"';\n BufferedReader fileReaderCSV = new BufferedReader(new FileReader(fileCSV));\n CSVReader csvReader = new CSVReader(fileReaderCSV, separator, quotechar);\n String[] header = csvReader.readNext();\n TableModel model = new DefaultTableModel(null, header); \n SpreadSheet spreadSheet = SpreadSheet.createEmpty(model);\n Sheet sheet = spreadSheet.getSheet(0);\n String[] lineCSV = null;\n int rowIndex = 1;\n \n sheet.setColumnCount(header.length);\n \n \n \n while ((lineCSV = csvReader.readNext()) != null) {\n int columnIndex = 0;\n \n sheet.setRowCount(rowIndex + 1);\n \n for (String valueText : lineCSV) {\n MutableCell<SpreadSheet> cell = sheet.getCellAt(columnIndex, rowIndex);\n ODValueType columnType = columnTypes != null && columnTypes[columnIndex] != null ? ODValueType.get(columnTypes[columnIndex].trim().toUpperCase()) : ODValueType.STRING;\n Object value = convertColumnValue(valueText, columnType);\n \n if (value != null) {\n cell.setValue(value, columnType, false, false);\n } \n \n columnIndex++;\n }\n \n rowIndex++;\n }"
] | [
"java",
"jopendocument"
] |
[
"Getting coordinates of chart on selecting plot in highcharts",
"I am generating one image using High-Charts library but i have 40000 polygon series so it takes lot of time in plotting all those points. \n\n<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n <title> - jsFiddle demo</title>\n\n\n <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>\n\n\n\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/css/result-light.css\">\n\n <style type='text/css'>\n\n </style>\n\n\n\n\n<script type='text/javascript'>\n$(function () {\n\n var options = {\n chart :{\n type: 'polygon',\n renderTo: 'container',\n zoomType:'x'\n\n },\n title: {\n text: ''\n },\n yAxis: {\n title: false,\n gridLineWidth:0,\n lineWidth:0,\n labels:{\n enabled: false\n }\n },\n\n xAxis: {\n title: false,\n gridLineWidth:0,\n lineWidth:0,\n labels:{\n enabled: false\n }\n },\n plotOptions: {\n series: {\n lineWidth: 1,\n lineColor:'black',\n\n }\n }, \n series: []\n };\n\n $.getJSON('data.json', function(data) {\n\n options.series=data;\n var chart = new Highcharts.Chart(options);\n })\n $.getJSON('title.json', function(title) {\n options.title.text=title;\n var chart = new Highcharts.Chart(options);\n })\n\n});\n</script>\n\n</head>\n<body>\n <script src=\"http://code.highcharts.com/highcharts.js\"></script>\n<script src=\"http://highcharts.base.is/highcharts-downsample.js\"></script>\n<script src=\"http://highcharts.base.is/demo_data.js\"></script>\n<script src=\"http://code.highcharts.com/highcharts-more.js\"></script>\n<script src=\"http://code.highcharts.com/modules/exporting.js\"></script>\n\n<div id=\"container\" style=\"min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto\"></div>\n\n\n</body>\n\n\nsample data.json file\n\n[{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61448208.5, 10791], [61453100.5, 20575], [61451242.5, 24291], [61446350.5, 14507]] } \n,{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61453100.5, 20575], [61453544, 21462], [61451686, 25178], [61451242.5, 24291]] } \n,{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61453544, 21462], [61453681.5, 21737], [61451823.5, 25453], [61451686, 25178]] } \n,{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61453681.5, 21737], [61459631.5, 33637], [61457773.5, 37353], [61451823.5, 25453]] } \n,{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61459631.5, 33637], [61462023.5, 38421], [61460165.5, 42137], [61457773.5, 37353]] } \n,{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61462023.5, 38421], [61462226, 38826], [61460368, 42542], [61460165.5, 42137]] } \n,{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61462226, 38826], [61462340, 39054], [61460482, 42770], [61460368, 42542]] } \n,{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61462340, 39054], [61462372.5, 39119], [61460514.5, 42835], [61460482, 42770]] } \n,{\"showInLegend\": false,\"color\": \"#FFFFFF\", \"data\": [[61462372.5, 39119], [61462429.5, 39233], [61460571.5, 42949], [61460514.5, 42835]] } \n\n]\n\n\nIs there any way to down sample multiple series to some 100's or create a mouse event on selection of area so that plot can regenerate plot based on coordinates and read chunk of json data within that range."
] | [
"javascript",
"plot",
"highcharts",
"lazy-loading"
] |
[
"Ending a redigo process",
"I'm working on a chat server and am using redigo in order to publish messages across many web socket connections. I have a go routine that (per user connection) opens a connection to redis, subscribes to some channels and waits for a message. Waiting for this message -\n\nmsg := psc.Receive()\n\n\nis a blocking operation in the fact that any code after the receive function will not run until a message comes in. However I would like to be able to watch for context -\n\nctx.Done()\n\n\nor the like. Is this achievable using a select, or is there a more idiomatic way of writing this? I am attempting to do this as in the current implementation this function is run as a go routine, and if the web session ends I would like to end the redis connection and finish the go routine.\n\nfunc relayRedisMessages (ctx context.Context, ws *websocket.Conn, rc []string) {\n\n c, err := redis.Dial(\"tcp\", \"localhost:6379\")\n if err != nil {\n log.Println(err)\n return\n }\n defer c.Close()\n\n psc := redis.PubSubConn{c}\n\n for _, channel := range rc {\n psc.Subscribe(channel)\n }\n\n for {\n msg := psc.Receive()\n // Write message to websocket\n var msg Message\n json.Unmarshal(v.Data, &msg)\n err = ws.WriteJSON(msg)\n if err != nil {\n log.Println(err)\n break\n }\n }\n}"
] | [
"go",
"redis",
"redigo"
] |
[
"How to set bindings in ngFor in Angular 2?",
"NOTE: I found several similar questions but none really answered my (generic) question\n\nI have this\n\ncomponent.ts\n\nfirst: string;\nsecond: string;\nthird: string;\nfields = [\"first\", \"second\", \"third\"];\n\n\nI want to be able to generate in component.html a complex component (without importing a custom-defined directive) which includes:\n\n\nRequired: ngModel binding based on fields[i]\n\n(e.g. i = 0, fields[i] = \"first\", ngModel = first)\nDesiderable: use fields[i] as strings to assign to any DOM element property (e.g. \n\n\nThe loop looks like this:\n\n <div *ngFor=\"let field of fields\">\n <label for=\"???>\n [(ngModel)]=\"???\"\n </div>\n\n\nAs for the 2nd point, it works with id and as content of the div.\n\nHowever...\n\n\nin the case of ngModel: [(ngModel)] = \"field\" leads to an exception (Cannot assign to a reference or variable!)\nin the case of assigning a string to (for example)\n\n <label for=\"{{field}}\">,\n\n\nI get an exception as well (Can't bind to 'for' since it isn't a known native property (\" i\">)"
] | [
"angular",
"angular2-template"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.