title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Angular ng-repeat without html element
<p>I'm in trouble with a foreach that I need to do with Angular. </p> <p>Thats's what I want to do :</p> <pre><code>&lt;ul&gt; &lt;div ng-repeat="g in groups"&gt; &lt;li ng-repeat="c in g.commands"&gt;{{c.text}}&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;/div&gt; &lt;/ul&gt; </code></pre> <p>How can I do something like that, but in valid HTML structure ? (without a <code>&lt;div&gt;</code> between <code>&lt;ul&gt;</code> and <code>&lt;li&gt;</code>)</p> <p>I see only one solution :</p> <ul> <li>Replace the <code>&lt;div&gt;</code> with a <code>&lt;ul&gt;</code> and make a lot of css rules to make it like it doesn't exists</li> </ul> <p>In addition, I use Angular 1.4.8.</p> <p>Thanks !</p>
1
Angular not getting data from FS.readFile with promises
<p>I am trying to use an Angular service to make a call to either use <code>fs.readFile</code> or <code>fs.writeFile</code> depending on type of button pressed in order to understand how node and angular promises interact. What I have is reading writing files, but does not send back read data, nor does it throw any errors for me to understand what has gone wrong. </p> <pre><code>//HTML &lt;button ng-click="rw('write')"&gt;WRITE FILE&lt;/button&gt; &lt;button ng-click="rw('read')"&gt;READ FILE&lt;/button&gt; //angular angular.module('test', []) .controller('ctrl', function($scope, RWService){ $scope.rw = function(type){ RWService.rw(type) .then( function(res){ console.log('success'); }, function(err){ console.log('error'); }) }; }) .service('RWService',['$http', '$q', function($http, $q){ this.rw = function(type){ var promise = $http.get('./rw/' + type); var dfd = $q.defer(); promise.then( function(successResponse){ dfd.resolve(successResponse); }, function(errorResponse){ dfd.reject(errorResponse); } ); return dfd.promise; }; }]); //node var fs = require('fs') , async = require('async') , Q = require('Q'); var dest = './file.txt'; var rw = { write: function(data){ data = data.repeat(5); return Q.nfcall(fs.writeFile, dest, data); } , read: function(data){ data = data.repeat(5); var deferred = Q.defer(); console.log('inside read'); fs.readFile(dest, 'utf8', function(err, data){ if (err){ deferred.reject('some error'); }else{ deferred.resolve(data); } }); return deferred.promise; } }; module.exports = exports = rw; //node server app.get('/rw/:type', function(req, res, next){ var type = req.params.type; var data = 'some text string\n'; if (type == 'write'){ //omitted fro brevity }else{ rw.read(data) .then(function(response){ return {'response': response}; }) .catch(function(err){ return {'index.js error': err}; }); } }); </code></pre> <p>I structured the angular <code>$q</code> portion off of <a href="http://www.metaltoad.com/blog/angularjs-promises-from-service-to-template" rel="nofollow">this blog post</a>. </p>
1
Complex sorting for search in realm, union of multiple RealmResults
<p>I replaced sqlite with realm in my open source Linux Command Library project. Everything went fine so far, but now I'm facing a problem.</p> <p>I'm using a RealmBaseAdapter to display all the commands in a ListView with an search interface. For a search the realm sniped below orders the results like this:</p> <p>Query: <strong>test</strong></p> <p>result:</p> <ul> <li>l2<strong>test</strong> </li> <li>rc<strong>test</strong></li> <li><strong>test</strong></li> <li><p><strong>test</strong>parm</p> <pre><code>RealmResults&lt;Command&gt; commands = mRealm.where(Command.class).contains("name", query).findAll(); mAdapter.updateRealmResults(commands); </code></pre></li> </ul> <p>With the old sqlite logic the order was like this:</p> <p>result:</p> <ul> <li><strong>test</strong></li> <li><strong>test</strong>parm</li> <li>l2<strong>test</strong> </li> <li>rc<strong>test</strong></li> </ul> <p><code>return getReadableDatabase().rawQuery("Select * from " + CommandsDBTableModel.TABLE_COMMANDS + " WHERE " + CommandsDBTableModel.COL_NAME + " LIKE '%" + query + "%' " + "ORDER BY " + CommandsDBTableModel.COL_NAME + " = '" + query + "' DESC," + CommandsDBTableModel.COL_NAME + " LIKE '" + query + "%' DESC", null);</code></p> <p>Is it possible to realize it with realm too? Here is the link to the project <a href="https://github.com/SimonSchubert/LinuxCommandBibliotheca" rel="nofollow">https://github.com/SimonSchubert/LinuxCommandBibliotheca</a></p>
1
Optimization in Python: 'Var' object is not iterable
<p>I hope this is not a duplicate but i can't seem to find an specific answer to this problem. I'm pretty new to Python so it might be obvious but I can't seem to find my error.</p> <p>So the problem is: I'm using gurobi to optimize a network-flow-model. But I have some trouble formulating the constraints because i have to iterate over 2 variables (I guess that is the problem).</p> <p>Here is the code first: </p> <pre><code>from gurobipy import * import optimization def beer(P, S, W, SP, g, d, b, c, m, n): # Create new model m = Model("Beer-Flow") # Create variables x = { (i,j,p) : m.addVar(name = "x[%s,%s,%s]" % (i,j,p)) for i,j in W for p in P } y = { (i,j) : m.addVar(name = "y[%s,%s]" % (i,j)) for i,j in W } # Integrate variables m.update() # Set objective m.setObjective(quicksum(y[i,j] * d[i,j] * c for (i,j) in W ), GRB.MINIMIZE) # Add constraints for i in S: m.addConstr((quicksum(x[i2,j,p])for p in P for (i2,j) in W if i2 == i ) - (quicksum(x[i2,j,p]for p in P for (i2,j) in W if j == i)) == b[i,p]) for i,j in W: m.addConstr(m * y[i,j] &gt;= (quicksum(x[i,j,p] * w[p] for p in P))) m.addConstr(n * y[i,j] &gt;= (quicksum(x[i,j,p] for p in P))) return m # Fill sets and parameters P, g = multidict({"full" : 12, "empty" : 4 }) S = {"Brauerei","München","Stuttgart","Göttingen","Bielefeld","Magdeburg" } W, d = multidict({("Brauerei", "München") : 558, ("Brauerei", "Stuttgart") : 437, ("Brauerei","Göttingen") : 142, ("Brauerei", "Bielefeld") : 45, ("Brauerei", "Magdeburg") : 290, ("München", "Brauerei") : 558, ("München", "Stuttgart") : 232, ("München", "Göttingen") : 500, ("München", "Bielefeld") : 600, ("München", "Magdeburg") : 523, ("Stuttgart", "Brauerei") : 437, ("Stuttgart", "München") : 232, ("Stuttgart", "Göttingen") : 408, ("Stuttgart", "Bielefeld") : 492, ("Stuttgart", "Magdeburg") : 572, ("Göttingen", "Brauerei") : 142, ("Göttingen", "München") : 500, ("Göttingen", "Stuttgart") : 408, ("Göttingen", "Bielefeld") : 180, ("Göttingen", "Magdeburg") : 197, ("Bielefeld", "Brauerei") : 45, ("Bielefeld", "München") : 600, ("Bielefeld", "Stuttgart") : 492, ("Bielefeld", "Göttingen") : 180, ("Bielefeld", "Magdeburg") : 254, ("Magdeburg", "Brauerei") : 290, ("Magedeburg", "München") : 523, ("Magdeburg", "Stuttgart") : 572, ("Magdeburg", "Göttingen") : 197, ("Magdeburg", "Bielefeld") : 254}) SP, b = multidict({("München", "full") : 1840, ("Brauerei", "empty") : -1700, ("Stuttgart", "full") : 1400, ("Stuttgart", "empty") : -1550, ("Göttingen","full") : 380, ("Göttingen", "empty") : - 400, ("Bielefeld", "full") : 840, ("Bielefeld", "empty") : -800, ("Magdeburg", "full") : 600, ("Magdeburg", "empty") : -500, ("Brauerei", "full") : -5600, ("Brauerei", "empty") : 4950}) c = 1 m = 24000 n = 2000 # Create model for given sets and parameters m = beer(P, S, W, SP, g, d, b, c, m, n) # Run optimization and print results m.optimize() optimization.print_result(m) </code></pre> <p>The part that is not working is: </p> <pre><code>for i in S: m.addConstr((quicksum(x[i2,j,p])for p in P for (i2,j) in W if i2 == i ) - (quicksum(x[i2,j,p]for p in P for (i2,j) in W if j == i)) == b[i,p]) </code></pre> <p>The Error is: 'Var' type is not iterable In Java for example I could get it done by two loops for p and i (tried it in Python, didn't work), but I have no clue how I can solve this problem with Python.</p> <p>Thank you in Advance</p>
1
Suitability/Performance of SQLite for large time-series data
<p>I've got time-series data that I'd like to store in a database of the format:</p> <ul> <li>group : string</li> <li>date : date</li> <li>val1 : number</li> <li>val2 : number</li> <li>... valN</li> </ul> <p>This database will be almost all reads. The searches will be for rows that belong to a group that is within a date range (e.g. group = XXX and date >= START and date &lt;= END).</p> <p>The data-set is big. Hundreds of millions of rows. Will SQLite be able to easily handle this kind of data? The appealing thing about SQLite is that it is serverless and I'd like to use it if I can.</p>
1
Swift Wrap and Unwrap
<p>I'm a little confused about Swift Wrap and Unwrap! So lets say this is my code:</p> <pre><code>var name:String? = "FirstName" print(name) </code></pre> <p>Does the print function automatically unwrap the name which is optional? so I do not need to say <code>print(name!)</code> in order to unwrap the name? I guess what I am trying to understand is these two are equivalent for unwraping an optional variable?</p> <p><code>print("name")</code> is just like saying <code>print ("name"!)</code></p> <p>The other question I have is about nil. is saying <code>var name:String? = "FirstName"</code> equivalent to saying <code>var name:String? = nil</code> . So does assigning a nil value wraps a variable?</p>
1
What version of AXIS2 shipped with Websphere 8.5.5.2?
<p>I just want to know the inputs for below questions.</p> <p>what version of AXIS2 will come with Websphere 8.5.5.2? </p> <p>Where can i see the version details of AXIS2 jars shipped with WAS 8.5.5.2? </p> <p>My code actually compiled with AXIS2 1.6.1 and deployed the same in WAS 8.5.5.2. I am getting below classcast exceptions. What could your suggestions to resolve this issue. I thought there is problem with different versions of axis2 while compiling and deploying. I am not able to know what version of axis2 shipped with websphere 8.5.5.2.</p> <p><strong>Approaches I have used.</strong></p> <p>1) Part of code which uses Axis was compiled against AXIS2 1.6.1 version and generated war was deployed in WAS 8.5.5.2 with no libraires in WAR. Got classNotFoundException for <strong>org.apache.axiom.util.stax.XMLStreamWriterUtils</strong>. Added org.apache.axis2.jar located in plugins in shared libraries and attached to my server war module level. Then class cast exception came.</p> <p>2) Part of code which uses Axis was compiled against AXIS2 1.6.1 and generated war was deployed in WAS 8.5.5.2 with <strong>org.apache.axis2.jar</strong> under WEB-INF/libraires in WAR. Then class cast exception came.</p> <pre><code>Calling getRendererRef(): renderer Type=[OutInRenderer] WSRenderer I Start: WSRenderer E Unable to perform rendering due to exception (java.lang.ClassCastException: org.apache.axiom.util.stax.xop.XOPEncodingStreamWriter incompatible with org.apache.axiom.ext.stax.datahandler.DataHandlerWriter) WSRenderer E stacktrace=org.apache.axiom.util.stax.XMLStreamWriterUtils.internalGetDataHandlerWriter(XMLStreamWriterUtils.java:71) </code></pre> <p>org.apache.axiom.util.stax.XMLStreamWriterUtils.writeDataHandler(XMLStreamWriterUtils.java:134)</p> <p>3) Kept Parent_LAST option in WAS 8.5.5.2 for server war which results plenty of errors related to parsers and other. Application stopped working because of many classcast and incompatible issues. Any inputs are appreciable... </p>
1
Run 'docker volume create' with Ansible?
<p>I have a Rails app I am deploying in Docker containers via Ansible. My app includes three containers so far:</p> <ul> <li>A Docker volume container (created with <code>docker volume create --name dbdata</code>)</li> <li>A Postgres container (with <code>volumes_from</code> dbdata)</li> <li>The Rails app container (which links to the postgres container)</li> </ul> <p>My deploy playbook is working, but I had to run the <code>docker volume create</code> command on the server via SSH. I'd love to do that via Ansible, so I could deploy a fresh instance of the app onto an empty container. </p> <p>Is there a way to run <code>docker volume create</code> via Ansible, or is there some other way to do it? I checked the docs for the Ansible Docker module but it doesn't look like they support <code>volume create</code> yet. Unless I'm missing something?</p>
1
Why object to json conversion using spring MVC doesn't work in this case?
<p>I need to execute this URL: <a href="http://localhost:8080/FitiProject/student" rel="nofollow">http://localhost:8080/FitiProject/student</a> and the response needs to be a json string containing the data of a <code>Student</code> object.</p> <p>Here is my code:</p> <pre><code>package spring.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import model.Student; @Controller public class PruebaController { @RequestMapping("/student") public @ResponseBody Student getStudent(){ return new Student(2, "h"); } } </code></pre> <p>This is Student.java</p> <pre><code>package model; public class Student { private int edad; private String nombre; public Student(int edad, String nombre) { super(); this.edad = edad; this.nombre = nombre; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } } </code></pre> <p>When I do a GET request on the URL, I don't get a JSON response instead I get a 406 error code. How can I solve this?</p> <p>I'm using Jackson 1.9 and Spring 4.1.</p>
1
asp.net core Oracle.DataAccess System.BadImageFormatException: Could not load file or assembly Oracle.DataAccess
<p>I've added Oracle.DataAccess as reference to asp.net core project. I've only installed Oracle Data Provider for .Net when installed ODAC. I would like to make a simple example with Dapper on the project.</p> <pre><code>public class Program { const string connectionString = "xxxxx"; public static void Main(string[] args) { IDbConnection connection = new OracleConnection(connectionString); string sql = "SELECT * FROM People WHERE Name='JOHN'"; var r = connection.Query&lt;People&gt;(sql); } } </code></pre> <p>The application wasn't running. I was getting this error below when I tried "dnx run" on the project folder.</p> <blockquote> <p>System.BadImageFormatException: Could not load file or assembly 'Oracle.DataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. An attempt was made to load a program with an incorrect format.</p> </blockquote> <p>If you get this message, probably, it means Oracle.DataAccess dll doesn't exist in the GAC.</p> <ol> <li><p>Open Command Line and go to bin folder under the odp.net e.g. <pre><code>cd C:\oracle\product\12.1.0\client_x86\odp.net\bin\4</pre></code></p></li> <li><p>Run this command below <pre><code> OraProvCfg.exe /action:gac /providerpath:C:\oracle\product\12.1.0\client_x86\odp.net\bin\4\Oracle.DataAccess.dll</pre></code></p></li> </ol> <p>After doing these steps I was able to run the project successfully.</p>
1
Handling fatal error: unexpectedly found nil while unwrapping an Optional value when creating a date object from a date string
<p>I got a strange error when creating a date object.</p> <p>The error is "fatal error: unexpectedly found nil while unwrapping an Optional value"</p> <p>Simplified code that shows the issue is</p> <pre><code>let dateFormatter = NSDateFormatter() ; dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" ; let startDateText:String = (data["startDate"] as AnyObject? as? String) ?? ""; print( startDateText ) ; let startDate:NSDate! = dateFormatter.dateFromString(startDateText) ; print( startDate ) ; </code></pre> <p>The data object when printed is</p> <pre><code>{ calendar = archived; endDate = "2016-01-25 15:15:00"; notes = "notes and something"; startDate = "2016-01-25 14:00:00"; title = "First event from the command line"; } </code></pre> <p>Archived is a calendar object from EKEventStore</p> <p>The strange part is the code works on another device.</p> <p>Any ideas on how to handle and solve "fatal error: unexpectedly found nil while unwrapping an Optional value"?</p>
1
Print barcode using thermal printer Android
<p>I was able to print text but when it comes to barcode it not showing or just showing irregular text. </p> <p><strong>Here is my source code</strong></p> <pre><code>//barcode 128 byte[] formats = {(byte) 0x1d, (byte) 0x6b, (byte) 0x73,(byte) 0x0d}; byte[] contents = content.getBytes(); byte[] bytes = new byte[formats.length + contents.length]; System.arraycopy(formats, 0, bytes, 0, formats.length ); System.arraycopy(contents, 0, bytes, formats.length, contents.length); usbCtrl.sendByte(bytes, dev); usbCtrl.sendByte(LineFeed(), dev); </code></pre> <p>but the result barcode is not showing, am i missing something</p> <p>Please help me</p> <p><strong>EDIT</strong></p> <p>I found the ESC/POS code : </p> <blockquote> <p>GS k m d1...dk NUL or GS k m n d1...d k</p> </blockquote> <p>But when I try this, still got same result</p>
1
Symfony and Docker - Cache and Log dirs permissions
<p>I am trying to setup a Symfony project using docker but it always return errors related to permissions in "cache" directory.</p> <p>I have tried everything and I can't seem to find a solution. The problem is somehow the cache folder is always created with "root" owner even with my server and php-fpm user set as www-data. Maybe because of the php-cli user?</p> <p>I have tried: - setfacl : Don't work with docker - chown / chmod to www-data: also didn't work. it might changes the owner correctly in the begining but them gives an error in other place.</p> <p><strong>docker-compose.yml</strong></p> <pre><code>app: build: . command: "tail -f /dev/null" # keep the application container running links: - mysql volumes: - .:/var/www nginx: build: docker/nginx/ ports: - 8090:80 links: - php-fpm volumes_from: - app php-fpm: build: docker/fpm ports: - 9000:9000 volumes_from: - app mysql: image: mysql:5.7 volumes: - ./docker/data/mysql:/var/lib/mysql </code></pre> <p><strong>My app Dockerfile:</strong></p> <pre><code>FROM php:5.6-cli ENV DEBIAN_FRONTEND noninteractive RUN apt-get update &amp;&amp; apt-get install -y \ git \ vim \ curl \ php5-json \ php5-intl \ php5-mcrypt \ php5-mysql \ php5-apcu \ php5-gd ADD /docker/fpm/php.ini /usr/local/etc/php/ # install composer. RUN curl -sS https://getcomposer.org/installer | php RUN mv composer.phar /usr/local/bin/composer RUN usermod -u 1000 www-data ADD . /var/www WORKDIR /var/www </code></pre> <p><strong>PHP-fpm Dockerfile</strong></p> <pre><code>FROM php:5.6-fpm ENV DEBIAN_FRONTEND noninteractive RUN apt-get update &amp;&amp; apt-get install -y \ php5-json \ php5-intl \ php5-mcrypt \ php5-mysql \ php5-apcu \ php5-gd RUN apt-get install -y php5-xdebug ADD xdebug.ini /usr/local/etc/php/conf.d/ ADD php.ini /usr/local/etc/php/ EXPOSE 9000 WORKDIR /var/www CMD ["php-fpm"] </code></pre> <p><strong>Nginx Dockerfile</strong></p> <pre><code>FROM nginx:latest ENV DEBIAN_FRONTEND noninteractive RUN apt-get update &amp;&amp; apt-get install -y git vim ADD nginx.conf /etc/nginx/ ADD symfony.conf /etc/nginx/sites-available/ RUN mkdir -p /etc/nginx/sites-enabled RUN ln -s /etc/nginx/sites-available/symfony.conf /etc/nginx/sites-enabled/ RUN usermod -u 1000 www-data EXPOSE 80 EXPOSE 443 ENTRYPOINT ["nginx"] </code></pre> <p>I am out of ideas. Any suggestions? Thank you.</p>
1
Change column header in a JTable
<p>This is my table right now :</p> <p><a href="https://i.stack.imgur.com/k5uu4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k5uu4.png" alt="enter image description here"></a></p> <p>This is the code that I can change the column title:</p> <pre><code>table.getColumnModel().getColumn(0).setHeaderValue("Lecturersssss"); </code></pre> <p>But the column title would not change until I hover the mouse on the <code>Lecturer</code> column header. </p> <p>Even when i use <code>table.repaint()</code> after this code, it won't change. Do you guys have any idea how can I solve this issue ?</p> <p>Thanks.</p>
1
pandas resampling without performing statistics
<p>I have a five minute dataframe:</p> <pre><code>rng = pd.date_range('1/1/2011', periods=60, freq='5Min') df = pd.DataFrame(np.random.randn(60, 4), index=rng, columns=['A', 'B', 'C', 'D']) A B C D 2011-01-01 00:00:00 1.287045 -0.621473 0.482130 1.886648 2011-01-01 00:05:00 0.402645 -1.335942 -0.609894 -0.589782 2011-01-01 00:10:00 -0.311789 0.342995 -0.875089 -0.781499 2011-01-01 00:15:00 1.970683 0.471876 1.042425 -0.128274 2011-01-01 00:20:00 -1.900357 -0.718225 -3.168920 -0.355735 2011-01-01 00:25:00 1.128843 -0.097980 1.130860 -1.045019 2011-01-01 00:30:00 -0.261523 0.379652 -0.385604 -0.910902 </code></pre> <p>I would like to resample only the data on the 15 minute interval, but without aggregating into a statistic (I dont want the mean,median,stdev).I want to subsample and get the actual data on the 15 minute interval.Is there a builtin method to do this?</p> <p>My output would be:</p> <pre><code> A B C D 2011-01-01 00:00:00 1.287045 -0.621473 0.482130 1.886648 2011-01-01 00:15:00 1.970683 0.471876 1.042425 -0.128274 2011-01-01 00:30:00 -0.261523 0.379652 -0.385604 -0.910902 </code></pre>
1
The xgboost package and the random forests regression
<p>The xgboost package allows to build a random forest (in fact, it chooses a random subset of columns to choose a variable for a split for the whole tree, not for a nod, as it is in a classical version of the algorithm, but it can be tolerated). But it seems that for regression only one tree from the forest (maybe, the last one built) is used. </p> <p>To ensure that, consider just a standard toy example. </p> <pre><code>library(xgboost) library(randomForest) data(agaricus.train, package = 'xgboost') dtrain = xgb.DMatrix(agaricus.train$data, label = agaricus.train$label) bst = xgb.train(data = dtrain, nround = 1, subsample = 0.8, colsample_bytree = 0.5, num_parallel_tree = 100, verbose = 2, max_depth = 12) answer1 = predict(bst, dtrain); (answer1 - agaricus.train$label) %*% (answer1 - agaricus.train$label) forest = randomForest(x = as.matrix(agaricus.train$data), y = agaricus.train$label, ntree = 50) answer2 = predict(forest, as.matrix(agaricus.train$data)) (answer2 - agaricus.train$label) %*% (answer2 - agaricus.train$label) </code></pre> <p>Yes, of course, the default version of the xgboost random forest uses not a Gini score function but just the MSE; it can be changed easily. Also it is not correct to do such a validation and so on, so on. It does not affect a main problem. Regardless of which sets of parameters are being tried results are suprisingly bad compared with the randomForest implementation. This holds for another data sets as well.</p> <p>Could anybody provide a hint on such strange behaviour? When it comes to the classification task the algorithm does work as expected.</p> # <p>Well, all trees are grown and all are used to make a prediction. You may check that using the parameter 'ntreelimit' for the 'predict' function. </p> <p>The main problem remains: is the specific form of the Random Forest algorithm that is produced by the xgbbost package valid? </p> <p>Cross-validation, parameter tunning and other crap have nothing to do with that -- every one may add necessary corrections to the code and see what happens.</p> <p>You may specify the 'objective' option like this:</p> <pre><code>mse = function(predict, dtrain) { real = getinfo(dtrain, 'label') return(list(grad = 2 * (predict - real), hess = rep(2, length(real)))) } </code></pre> <p>This provides that you use the MSE when choosing a variable for the split. Even after that, results are suprisingly bad compared to those of randomForest. </p> <p>Maybe, the problem is of academical nature and concerns the way how a random subset of features to make a split is chosen. The classical implementation chooses a subset of features (the size is specified with 'mtry' for the randomForest package) for EVERY split separately and the xgboost implementation chooses one subset for a tree (specified with 'colsample_bytree'). </p> <p>So this fine difference appears to be of great importance, at least for some types of datasets. It is interesting, indeed. </p>
1
Calculate totals by reading from a text file in Python
<p>I am trying to write a program in python in which we have to add the numbers from different categories and sub-categories. The program is about a farmer's annual sale of produce from his farm. The text file from where we have to read from has 4 categories. The first category is the type of product for example Vegetables, Fruits, condiments. The second category tells us about the type of product we have, for example Potatoes, Apples, Hot Sauce. The third category tells us about the sales in 2014 and the fourth category tells us about the sales in 2015. In this program, we only have to calculate the totals from the 2015 numbers. The 2014 numbers are present in the text file but are irrelevant. </p> <p>Here is how the text file looks like</p> <pre><code>PRODUCT,CATEGORY,2014 Sales,2015 Sales Vegetables,Potatoes,4455,5644 Vegetables,Tomatoes,5544,6547 Vegetables,Peas,987,1236 Vegetables,Carrots,7877,8766 Vegetables,Broccoli,5564,3498 Fruits,Apples,398,4233 Fruits,Grapes,1099,1234 Fruits,Pear,2342,3219 Fruits,Bananas,998,1235 Fruits,Peaches,1678,1875 Condiments,Peanut Butter,3500,3902 Condiments,Hot Sauce,1234,1560 Condiments,Jelly,346,544 Condiments,Spread,2334,5644 Condiments,Ketchup,3321,3655 Condiments,Olive Oil,3211,2344 </code></pre> <p>What we are looking to do is to add the sales for 2015 by products and then the total sales for everything in 2015.</p> <p>The output should look something like this in the written text file:</p> <blockquote> <p>Total sales for Vegetables in 2015 : {Insert total number here}</p> <p>Total sales for Fruits in 2015 : {Insert total number here}</p> <p>Total sales for Condiments in 2015 : {Insert total number here}</p> <hr> <p>Total sales for the farmer in 2015: {Insert total for all the products sold in 2015}</p> </blockquote> <p>Along with that, it should also print the grand total on the Python run screen in the IDE along with the text file:</p> <blockquote> <p>Total sales for the farmer in 2015: {Insert total for all the products sold in 2015}</p> </blockquote> <p>Here is my code. I am new to Python and reading and writing files so I can't really say if I am on the right track.</p> <pre><code>PRODUCT_FILE = "products.txt" REPORT_FILE = "report.txt" def main(): #open the file productFile = open(PRODUCT_FILE, "r") reportFile = open(REPORT_FILE, "w") # reading the file proData = extractDataRecord(productFile) product = proData[0] category = proData[1] salesLastYear = prodata[2] salesThisYear = proData[3] #computing product = 0.0 product = salesThisYear productFile.close() reportFile.close() def extractDataRecord(infile) : line = infile.readline() if line == "" : return [] else : parts = line.rsplit(",", 1) parts[1] = int(parts[1]) return parts # Start the program. main() </code></pre>
1
event.waitUntil throws an error when called in a push event listener
<p>I'm getting error in my service-worker.js, when it receive notification from GCM</p> <pre><code>self.addEventListener('push', function(event) { console.log('Received a push message', event); registration.pushManager.getSubscription().then(function(subscription) { console.log("got subscription id: ", subscription.endpoint) var endpointSplit = subscription.endpoint.split('/'); var endpoint = endpointSplit[endpointSplit.length-1]; return fetch('/api/notifications/'+endpoint).then(function(res){ return res.json().then(function(payload){ return event.waitUntil( self.registration.showNotification(payload.title, { body: payload.body, icon: payload.icon, tag: payload.tag, data: payload }) ); }).catch(function(err){ console.log("Error in notifications ",err) }) }) }); }); </code></pre> <p>With the above code, I'm able to finish gcm chrome web notification implementation, but I'm getting a error in console.</p> <pre><code>Uncaught (in promise) DOMException: Failed to execute 'waitUntil' on 'ExtendableEvent': The event handler is already finished. at Error (native) at http://localhost:9000/service-worker.js:9:18 </code></pre>
1
Can we set fact type and fact field dynamically in Drools
<p>How do I set fact type and fact field dynamically in drl file?I am reading a json file which having the records.that records I am mapping to pojo class which is generating dynamically from json schema I used <a href="http://www.jsonschema2pojo.org/" rel="nofollow">json2pojo maven plugin</a>! .now I want to fire some rules on that class. but I am not able to fech that class in drl file as a fact.same for fields. below is drl rule.</p> <pre><code>rule "not null" when obj:Class(fieldName==null) then //take action end </code></pre> <p>this Class and fieldName is generating dynamically. please suggest me solution regarding this. Thanks.</p>
1
Page cannot be served HTTP Error 404.3 - Not Found
<p>I'm new in IIS, I have asp web applications, and I must add them to the default web site, and when I run default web site, it's fine, but when I run the applications I receive the error: "HTTP Error 404.3 - Not Found" "The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map."</p> <p>In server roles I have:</p> <p><a href="https://i.stack.imgur.com/EaeTa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EaeTa.jpg" alt="enter image description here"></a></p> <p>In server Features I have: <a href="https://i.stack.imgur.com/EgzVl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EgzVl.jpg" alt="enter image description here"></a></p> <p>I have tried to register aspnet components: C:\Windows\Microsoft.NET\Framework64\v4.0.30319> .\aspnet_regiis.exe -ir</p> <p>but I recieve this message: "This option is not supported on this version of the operating system. Administrators should instead install/uninstall A SP.NET 4.5 with IIS8 using the Turn Windows Features On/Off dialog"</p> <p>I tried this too: C:\Windows\Microsoft.NET\Framework64\v4.0.30319> .\ServiceModelReg.exe -ia and C:\Windows\Microsoft.NET\Framework64\v4.0.30319> .\ServiceModelReg.exe -ir but I recieve this message:</p> <p>[Error]This tool is not supported on this version of Windows. Administrators should instead install/uninstall Windows Communication Foundation features using the 'Turn Windows Features On/Off' dialog....</p> <p>I have windows server 2012 and this IIS version: <a href="https://i.stack.imgur.com/KQ6j3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KQ6j3.jpg" alt="enter image description here"></a></p> <p>I can't remove or uninstall IIS, because this is our customer server and they uses the default web site for their Application and myapplications must run in that web site.</p> <p>What can I do?? I hope somebody please help me.</p> <p>Best Regards</p>
1
Div Button wrapper width?
<p>First post here. I have shopping cart software called <strong>sellerdeck</strong> previously actinic. There is a lot of different code involved.</p> <p>I have a button wrapper which has pre defined text inserted. I am trying to change the width of the button to a fixed width but pretty much everything I tried, from info I've found here and elsewhere, breaks the code and the button either disappears, does not function, or shrinks to about 10px.</p> <p>Is it possible to set the width in the following code or is it likely that I will have to do it elsewhere within my software?</p> <p>This code creates a small rectangle green button with white text that reads "Add to Cart" the text is pulled from code elsewhere in my software.</p> <pre><code>&lt;div class="button-wrapper cart-button-wrapper"&gt; &lt;input value="&lt;Actinic:Variable Name="CartButtonText"/&gt;" name="_&lt;Actinic:Variable Name="ProductID"/&gt;" type="submit" class="button cart-button" onclick="return ValidateChoices('&lt;actinic:variable name="ProductID" /&gt;');"/&gt; &lt;/div&gt; </code></pre> <p>Any help would be great, I've tried padding and manage to get top padding to work but that's it.</p> <p>Michael</p>
1
What is the android api for getting the list of connected audio devices?
<p>I used the below added code to get the connected audio devices for android device. Used AudioManager api method <code>getDevices()</code> and got the result with connected devices like earphones, speaker, headphones. But this <code>getDevices()</code> method is available since android api level 23 (Marshmallow) only.</p> <p>But my application should support from api level 21 (Lollipop). Please can anybody let me know the alternative api to get the available audio device for the android device.</p> <p>Code used with api level 23.</p> <pre><code>AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.M) { AudioDeviceInfo[] adi = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS); } </code></pre> <p>Please help me by providing a way to get the connected audio devices for the devices running with Android OS version below Marshmallow(api level 23).</p>
1
Insert new Documents or modify an array field of existing document
<p>Apologies if this is a re-post, but I wasn't able to quite get the query I want from the mongodb documentation examples. </p> <p>Here's my issue. I am unable execute in a single query to either update an array_field of an existing document or add a new document and initialize the array_field with an initial value.</p> <p>I can use findOne() with some conditional logic, and probably solve this, but I would think mongodb has an implementation of this use case</p> <p>Here's the code so far:</p> <pre><code>#data_json = JSON document to be added to collection collection.update_one({"json_id":data_json["json_id"], "_dashbd_id_":dashboard_id},{{"$addToSet": {"array_field":keyword}},{"$setOnInsert":data_json}}, upsert=True) </code></pre> <p>I'm querying by the json_id, and _dashbd_id_ from my collection. If it exists, then I intend to add the "keyword" to the array_field. If it doesn't exist, create a new document as data_json which include array_field = [keyword]</p> <p>Any hints and suggestions are appreciated!</p>
1
Entity Framework 7 SaveChanges
<p>Is there any way to register a callback that will be called before a model in EF7 is saved to the database? What I want to do is to set a ModifiedBy and ModifiedDate property that I have on all models. I'm not that keen to do this manually before each save so I'm looking for some more generic and automatic way.</p>
1
stargazer: Omitting multiple variables with multiple models
<p>I'm trying to omit variables that appear in some models but not in others. However, I'm not getting the output I expect. I'm using stargazer 5.2. Here's a MWE:</p> <pre><code>y &lt;- rbinom(100, 1, 0.5) x &lt;- rnorm(100) z &lt;- rnorm(100) fit1.lm &lt;- lm(y~x) fit2.lm &lt;- lm(y~x+z) stargazer(fit.lm, fit2.lm, omit=c("x", "z"), omit.labels=c("x", "z")) </code></pre> <p>This gives the following output in the omitted section.</p> <pre><code>x &amp; Yes &amp; Yes \\ z &amp; No &amp; No \\ </code></pre> <p>The entry in the second row and second column should be a Yes. </p>
1
Is there any advantage of having a method as static?
<p>I am using <code>Webstorm</code> and I wrote a React component, my code looks like:</p> <pre><code>async onDrop( banner, e ) { banner.classList.remove( 'dragover' ); e.preventDefault(); const file = e.dataTransfer.files[ 0 ], reader = new FileReader(); const { dispatch } = this.props; const result = await this.readFile( file, reader ); banner.style.background = `url( ${ result } ) no-repeat center`; dispatch( addLayer( file ) ); return false; } @isImage( 0 ) readFile( file, reader ) { reader.readAsDataURL( file ); return new Promise( function ( resolve, reject ) { reader.onload = ( event ) =&gt; resolve( event.target.result ); reader.onerror = reject; } ); } onDragOver( banner ) { banner.classList.add( 'dragover' ); return false; } </code></pre> <p>Webstorm's code inspection suggest me that <code>Method can be static</code> for the <code>onDragOver</code> method. My question is:</p> <p><strong>Are there any real benefit from having the method as static or this suggestion is somehow useless?</strong></p>
1
Consuming a RESTapi stream with angular2
<p>How is it possible to consume a "never-ending" data stream with angular2? I'm writing a little chat app with a server written in go and a client writting in angular2. For a push service I implemented an endpoint which will keep the connection up. A authorized user can connect to the message broker on <code>server.com:123/broker</code> with a GET request. Every time a new message for the user arrives its send to the broker in form of a json-object. How ever, when using the normale syntax I won't get any results (since the code waits for the connection to be closed as I suppose):</p> <pre><code>return this._http.request(req).map( (res: Response) =&gt; { return res.json(); }).subscrube( results =&gt; { console.log("results arrived", results); }); </code></pre> <p>Consuming streams has a lot of advantages (like video streaming with a rest api, awesome). Is there a way to do this?</p> <p>/edit: A little bit more information here: I checked the http transaction and they look okay:</p> <pre><code>GET /broker HTTP/1.1 User-Agent: curl/7.35.0 Host: mydomain.com:12345 Accept: */* Authorization: Bearer [JWT] </code></pre> <p>The server ansers with the response header:</p> <pre><code>HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Date: Mon, 01 Feb 2016 11:16:45 GMT Transfer-Encoding: chunked </code></pre> <p>[then the client is listening on this connection until the server pushes something into the stream</p> <pre><code>ba {"target":"56addcef7bec6d5785ee6945","payload": ...} </code></pre> <p>Seems correct so far. I can see the size of the chunk in hex (ba), the CRLF, the payload (json) and the final CRLF. So, when talking about HTTP Standard everything seems okay. However, my Angular2 won't fetch the chunks.</p>
1
how to import a txt file in android studio and use it as string?
<p>I want to work with a text in android studio that is very long(70 pages approximately). first is a way to put in my main activity in android studio code? OR how can I import it and use it as string?</p> <p>for example:</p> <pre><code>String deey = "my long text"; </code></pre> <p>so I cant use it. I want to add it to my program and use it as string. I put it into asset folder. but I can't use it.</p>
1
scrapy "Missing scheme in request url"
<p>Here's my code below-</p> <pre><code>import scrapy from scrapy.http import Request class lyricsFetch(scrapy.Spider): name = "lyricsFetch" allowed_domains = ["metrolyrics.com"] print "\nEnter the name of the ARTIST of the song for which you want the lyrics for. Minimise the spelling mistakes, if possible." artist_name = raw_input('&gt;') print "\nNow comes the main part. Enter the NAME of the song itself now. Again, try not to have any spelling mistakes." song_name = raw_input('&gt;') artist_name = artist_name.replace(" ", "_") song_name = song_name.replace(" ","_") first_letter = artist_name[0] print artist_name print song_name start_urls = ["www.lyricsmode.com/lyrics/"+first_letter+"/"+artist_name+"/"+song_name+".html" ] print "\nParsing this link\t "+ str(start_urls) def start_requests(self): yield Request("www.lyricsmode.com/feed.xml") def parse(self, response): lyrics = response.xpath('//p[@id="lyrics_text"]/text()').extract() with open ("lyrics.txt",'wb') as lyr: lyr.write(str(lyrics)) #yield lyrics print lyrics </code></pre> <p>I get the correct output when I use the scrapy shell, however, whenever I try to run the script using scrapy crawl I get the ValueError. What am I doing wrong? I went through this site, and others, and came up with nothing. I got the idea of yielding a request through another question over here, but it still didn't work. Any help?</p> <p>My traceback-</p> <pre><code>Enter the name of the ARTIST of the song for which you want the lyrics for. Minimise the spelling mistakes, if possible. &gt;bullet for my valentine Now comes the main part. Enter the NAME of the song itself now. Again, try not to have any spelling mistakes. &gt;your betrayal bullet_for_my_valentine your_betrayal Parsing this link ['www.lyricsmode.com/lyrics/b/bullet_for_my_valentine/your_betrayal.html'] 2016-01-24 19:58:25 [scrapy] INFO: Scrapy 1.0.3 started (bot: lyricsFetch) 2016-01-24 19:58:25 [scrapy] INFO: Optional features available: ssl, http11 2016-01-24 19:58:25 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'lyricsFetch.spiders', 'SPIDER_MODULES': ['lyricsFetch.spiders'], 'BOT_NAME': 'lyricsFetch'} 2016-01-24 19:58:27 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, LogStats, CoreStats, SpiderState 2016-01-24 19:58:28 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats 2016-01-24 19:58:28 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware 2016-01-24 19:58:28 [scrapy] INFO: Enabled item pipelines: 2016-01-24 19:58:28 [scrapy] INFO: Spider opened 2016-01-24 19:58:28 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2016-01-24 19:58:28 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023 2016-01-24 19:58:28 [scrapy] ERROR: Error while obtaining start requests Traceback (most recent call last): File "C:\Users\Nishank\Miniconda2\lib\site-packages\scrapy\core\engine.py", line 110, in _next_request request = next(slot.start_requests) File "C:\Users\Nishank\Desktop\SNU\Python\lyricsFetch\lyricsFetch\spiders\lyricsFetch.py", line 26, in start_requests yield Request("www.lyricsmode.com/feed.xml") File "C:\Users\Nishank\Miniconda2\lib\site-packages\scrapy\http\request\__init__.py", line 24, in __init__ self._set_url(url) File "C:\Users\Nishank\Miniconda2\lib\site-packages\scrapy\http\request\__init__.py", line 59, in _set_url raise ValueError('Missing scheme in request url: %s' % self._url) ValueError: Missing scheme in request url: www.lyricsmode.com/feed.xml 2016-01-24 19:58:28 [scrapy] INFO: Closing spider (finished) 2016-01-24 19:58:28 [scrapy] INFO: Dumping Scrapy stats: {'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 1, 24, 14, 28, 28, 231000), 'log_count/DEBUG': 1, 'log_count/ERROR': 1, 'log_count/INFO': 7, 'start_time': datetime.datetime(2016, 1, 24, 14, 28, 28, 215000)} 2016-01-24 19:58:28 [scrapy] INFO: Spider closed (finished) </code></pre>
1
How to convert a positive signed int32 value to its negative one?
<p>I have try to write one logic is to convert an <code>int32</code> positive value to a corresponding negative one, i.e., <code>abs(negativeInt32) == positiveInt32</code>.</p> <p>I have tried with both: </p> <ul> <li><p>First:</p> <pre><code>fmt.Printf("%v\n", int32(^uint32(int32(2) -1))) </code></pre> <p>This results in an error : <code>prog.go:8: constant 4294967294 overflows int32</code></p></li> <li><p>Second:</p> <pre><code>var b int32 = 2 fmt.Printf("%v\n", int32(^uint32(int32(b)-1))) </code></pre> <p>This results in <code>-2</code>.</p></li> </ul> <p>How can both result in different results. I think they are equal.<br> <a href="http://play.golang.org/p/zipqfzVkk6" rel="nofollow noreferrer">play.golang.org</a></p> <h3>EDIT</h3> <p>Edit for replacing <code>uint32</code> with <code>int32</code> for the first situation.</p> <h3>ANSWERED</h3> <p>For those who come to this problem, I have answered the question myself. :)</p>
1
Simulate real click programmatically
<p>I am using this code to identify if click is programmatically triggered. </p> <p>How should I edit <code>$('#x').trigger('click')</code> to simulate real click? (hasOwnProperty should return true 'Real')</p> <pre><code>$('#x').click(function(e) { if(e.hasOwnProperty('originalEvent')) { $('#out').append('&lt;li&gt;Real&lt;/li&gt;'); } else { $('#out').append('&lt;li&gt;Unreal&lt;/li&gt;'); } }); $('#y').click(function() { $('#x').trigger('click'); //how to edit this }); </code></pre>
1
python: How to create virtualenv without internet connection
<p>I have trouble creating a virtualenv on a server that blocks all internet access. Has anybody successfully done that before? I searched but doesn't show up anything helpful. I have no problem transferring data back and forth, but I don't know what packages need to be downloaded and what options I need to have for the installation.</p> <p>If you are curious what I got by trying to create one, here's the backtrace:</p> <pre><code>netops@netops1 /spare/local/latency $virtualenv -p /usr/bin/python2.6 latency Running virtualenv with interpreter /usr/bin/python2.6 New python executable in latency/bin/python2.6 Also creating executable in latency/bin/python Installing setuptools..................... Complete output from command /spare/local/latency/latency/bin/python2.6 -c "#!python \"\"\"Bootstra...sys.argv[1:]) " --always-copy -U setuptools: Downloading http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11-py2.6.egg Traceback (most recent call last): File "&lt;string&gt;", line 279, in &lt;module&gt; File "&lt;string&gt;", line 211, in main File "&lt;string&gt;", line 159, in download_setuptools File "/usr/lib64/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib64/python2.6/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib64/python2.6/urllib2.py", line 409, in _open '_open', req) File "/usr/lib64/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib64/python2.6/urllib2.py", line 1181, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib64/python2.6/urllib2.py", line 1156, in do_open raise URLError(err) urllib2.URLError: &lt;urlopen error [Errno 110] Connection timed out&gt; </code></pre> <p>Thanks for any help.</p>
1
error: can't find crate
<p>I'm trying to use <a href="https://github.com/kenpratt/jvm-assembler" rel="noreferrer">this library</a>.<br> But, <code>cargo build</code> says this:</p> <pre><code> Compiling test v0.1.0 (file:///C:/path/to/project/test) src\main.rs:1:1: 1:28 error: can't find crate for `jvm_assembler` [E0463] src\main.rs:1 extern crate jvm_assembler; ^~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to previous error Could not compile `test`. To learn more, run the command again with --verbose. </code></pre> <p>My <code>Cargo.toml</code> is this:</p> <pre><code>[package] name = "test" version = "0.1.0" authors = ["yomizu_rai"] [dependencies] jvm-assembler = "*" </code></pre> <p><code>src/main.rs</code> is this, and there are no other sourcefiles.</p> <pre><code>extern crate jvm_assembler; use jvm_assembler::*; fn main() {} </code></pre> <p>I think my <code>Cargo.toml</code> is not wrong, and <code>src/main.rs</code> has no room for mistake.<br> Why can not rustc find jvm-assembler?<br> How do I resolve?</p>
1
Deferred function doesn't work as expected in IE with jQuery 1.12
<p>I have 2 functions where I am trying to run one function and then the other. I have implemented this line in my code:</p> <pre><code>function1().done(function2); </code></pre> <p>In function1 at the end I have placed this code:</p> <pre><code>return $.Deferred().resolve(); </code></pre> <p>This functionality works in both Firefox and Chrome, but does not seem to be working in Internet Explorer 11. I get no errors, but the functions are not running one after the other like it should be. Does anyone know why this is happening or know of a workaround/other way to do this that would work in all browsers?</p> <p>I have been playing around with this example using Internet Explorer and experiencing the issue I mention above with it (the alert shows up before the text gets hidden, should happen the other way around):</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; function1 = function() { $("p").hide("slow"); return $.Deferred().resolve(); } function2 = function() { alert("Text hidden now."); } $(document).ready(function() { $("button").click(function() { function1().done(function2); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button&gt;Hide&lt;/button&gt; &lt;p&gt;This is a paragraph with little content.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
Defining an int array in a class C++
<p>Is there any way to dynamically (I think that's the right term) define an int array in a class, the size of which is a private member variable in that same class? For example:</p> <pre><code>class Scene() { //public member functions private: int max; int xcoords[max]; } </code></pre> <p>I've searched through other answered questions on here, but I haven't learned how to use vectors in class yet, which is what most responses suggest. Ideally, in my constructor for the class, I'd be passed an int max, with which I then initialize the xcoord array to have a size of max with entries all -1. </p>
1
Missing Visual Studio Web Application publish targets
<p>I am missing the usual publish targets when publishing my c# web application. The usual "Import" and "Custom" options are missing when I go to publish, as well as the "Manage Profiles" drop down that has the option to create a new profile.</p> <p>Here is the screen I am presented with.</p> <p><img src="https://i.imgur.com/NFtii2i.png" alt="Missing Publish Targets"></p> <p>The buttons on the left hand side are "greyed out"</p> <p>Here is another screen from a colleague that has the missing options</p> <p><img src="https://i.imgur.com/FjsXAZR.png" alt="Correct Publish Targets"></p> <p>I have tried a full reinstall of Visual Studio 2015 update 1 with no success. I have also tried creating a fresh ASP.NET Web application project in a new solution resulting with the same problem.</p>
1
from sklearn import DecisionTreeRegressor >> ImportError
<p>(1) Running Windows 8 (2) Downloaded and installed, Anaconda for Windows, PYTHON 2.7</p> <p>(3) From Anaconda Prompt:</p> <pre><code>conda install scikit-learn Fetching package metadata: .... Solving package specifications: ..................... All requested packages already installed. packages in environment at C:\Users\Joey\Anaconda2: scikit-learn 0.17 np110py27_1 </code></pre> <p>(4) Launched Spyder</p> <p>(5) This is ok, and package is found.</p> <pre><code>import sklearn </code></pre> <p>(6) Tab completion (in Spyder) for sklearn, shows:</p> <pre><code>sklearn.base sklearn.clone sklearn.externals sklearn.re sklearn.setup_module sklearn.sys sklearn.utils sklearn.warnings </code></pre> <p>(6) Therefore, when running a snippet as found in <a href="http://scikit-learn.org/stable/" rel="nofollow">http://scikit-learn.org/stable/</a> example.</p> <pre><code>from sklearn import DecisionTreeRegressor Traceback (most recent call last): File "&lt;ipython-input-2-5aa62260685f&gt;", line 1, in &lt;module&gt; from sklearn import DecisionTreeRegressor ImportError: cannot import name DecisionTreeRegressor </code></pre> <p>(7) Earlier, I noticed the same behavior using Enthought Canopy and also couldn't get scikit to work there either. As a result, I uninstalled every Python program and IDE I could find to try and clean my system before attempting Anaconda, as described above. I looked at many other posts and still could not get my system to work properly and suspect there's path, library, or version issue. </p>
1
Good way to secure multiple Angular 2 components
<p>A common recommended way to secure Angular 2 component/routes seems to be to use <code>@CanActivate()</code>, like here:</p> <p><a href="http://youknowriad.github.io/angular2-cookbooks/stateless-authentication.html" rel="nofollow">http://youknowriad.github.io/angular2-cookbooks/stateless-authentication.html</a></p> <p>If you have only a few components this works fine, but is there a better way that would centralize all this? </p> <p>Would having a common base class for each component work? (any examples on how to do this?). Could we have a custom <code>@CanActivate()</code>, something like <code>@ProtectMyApp()</code>? (examples?)</p> <p>I'm basically trying to prevent having to copy+paste the same <code>@CanActivate()</code> code for each component.</p> <p>(apologies if these questions do not make sense, still learning Angular)</p> <p>Thanks</p>
1
How to enable/disable :hover using jquery?
<p>I have a <code>div</code> like this:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("div").on("click", function(){ $("div").css({"background-color":"#f1f1f1"}); $("div").text('Sending ... (I want diactivate :hover)'); setTimeout(function(){ $("div").text('Click (I want activate :hover again)'); $("div").hover(function(e) { $(this).css("background-color","#ddd8") }); }, 5000); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>div{ padding: 20px; border: 1px solid #999; text-align: center; background-color: #f1f1f1; cursor: pointer; } div:hover{ background-color: #ddd; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div&gt;Click (I want activate :hover)&lt;/div&gt;</code></pre> </div> </div> </p> <p>I want when user clicks on that <code>div</code>, <code>:hover</code> get disable and after 5sec it get enable again. But in my code it just deactivate. How can I make it activate again?</p>
1
How to include d3 on JavaScript non html file?
<p>I am new to JS. Here is my question, in webstorm:</p> <p>I created an empty JS file called <code>fn</code> under an empty project .</p> <p>Then I copy the <code>d3.js</code> into the same project.</p> <p>Then in the <code>fn</code>, I input:</p> <pre><code>var fn = "C:/temp/test.csv"; d3.csv(fn, function(e) { console.log(e); }); </code></pre> <p>When I run it, I get:</p> <blockquote> <p>"Error: Cannot find module 'd3.js'"</p> </blockquote> <p>What should I do for the correct running? Thanks.</p>
1
Validate textarea in html with java script
<p>I'm trying to prevent users from inputting and submitting single quotes ( ' ) into the textarea. below is what I have, but it isn't work.</p> <pre><code> &lt;script&gt; function valtxtarea() { var val = document.getElementById('textarea').value; if ('\''.test(val)) { alert('do not add single qoutes to your inputs!'); } } &lt;/script&gt; &lt;form&gt; enter text below &lt;textarea&gt;input contents here&lt;/textarea&gt; &lt;input type="button" onclick="valtxtarea();" value="send"&gt; &lt;/form&gt; </code></pre>
1
Exception of type 'Tamir.SharpSsh.jsch.SftpException' was thrown
<p>Im able to connect to the sftp server am able to get the list of files in "pickup" directory. But I can't download any of those files. Here is my code:</p> <pre><code>try { sftp.Get(txtRemotePath.Text + txtFixedFileName.Text, txtLocalPath.Text + txtFixedFileName.Text); //example: //txtRemotePath.Text + txtFixedFileName.Text = "/pickup/temp.txt"; //txtLocalPath.Text + txtFixedFileName.Text = @"C:\Users\...\temp.txt" } catch (Exception ex) { lblError.Text += "\n" + ex.Message; } </code></pre> <p>I tried modifiying the local and remote paths switching betwen slashes "/" and back-slashes "\", removing/addding starting slashes in remote path.. unfortunatly same error is generated:</p> <p>Exception of type 'Tamir.SharpSsh.jsch.SftpException' was thrown</p>
1
Python Pyinstaller 3.1 Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll
<p>Hello fellow programmers, so I am having a spot of trouble getting this python .exe to function properly. I am using Anaconda 3 and the latest version of pyinstaller, and my code has nothing odd going on when I run it as a .py, but for the sake of distribution I need to have it as a ".exe". Whenever I try to run my .exe all I get is the error:</p> <p>Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll.</p> <p>and then it closes. Again, I am not having this problem if I run my python code in .py format from the same command window.</p> <p>Any help would be greatly appreciated, thank you! </p>
1
PhoneGap/Cordova for android file plugin error code 1
<p>I am using phonegap and i want to access a file located at www/res from an android device but it's throwing NOT_FOUND_ERR... I'm sure the file it's located there and here it's the code I wrote:</p> <pre><code>onDeviceReady: function(){ window.resolveLocalFileSystemURL(cordova.file.applicationDirectory + "www/res/myfile.txt", app.gotFile, app.fail); }, gotFile: function(fileEntry){ fileEntry.file(function(file){ var reader = new FileReader(); reader.onloadend = function(e) { alert(this.result); } reader.readAsText(file); }); }, fail: function(e){ console.log("Error reading"); console.log(e.code); } </code></pre> <p>The code it's super simple yet I can't see what's wrong with it!</p>
1
Adding a property to a queryset in Django
<p>I'm creating a messaging system and part of what I want to do is based on whether the user is a sender or a receiver of a message, different CSS loads. I'm trying to achieve this by attaching a property to each message object that identifies this.</p> <p>I have my message</p> <pre><code>#models.py class Message(models.Model): def __unicode__(self): return unicode(self.time_date) message_from = models.ForeignKey(User, related_name="%(class)s_message_from") message_to = models.ForeignKey(User, related_name="%(class)s_message_to") message = models.TextField() file = models.FileField(blank=True, null=True) read = models.BooleanField(default=False) time_date = models.DateTimeField(default=django.utils.timezone.now) job = models.ForeignKey(Job, blank=True, null=True) </code></pre> <p>and my view to get the messages:</p> <pre><code>def view_messages(request): messages = Message.objects.filter(message_to=request.user, job_id=None).distinct('message_from') messages_from_user_ids = messages.values_list('message_from', flat=True).distinct() messages_from_user = User.objects.filter(id__in=messages_from_user_ids) messages = Message.objects.filter( Q(message_to=request.user) &amp; Q(message_from_id=messages_from_user_ids[0]) &amp; Q(job_id=None) | Q( message_from_id=messages_from_user_ids[0]) &amp; Q( message_from_id=request.user) &amp; Q(job_id=None)).order_by('time_date') messages = Message.objects.annotate(foo='true') # error return render(request, 'freelancestudent/general/messages.html', {'messages': messages, 'messages_from': messages_from_user}) </code></pre> <p>What I was trying to achieve in the line commented error was to simply test <a href="https://docs.djangoproject.com/en/dev/topics/db/aggregation/" rel="noreferrer">annotations</a> by annotating the string <code>'true'</code> to every message object, accessible under <code>foo</code>. This gives me the error <code>'str' object has no attribute 'resolve_expression'</code>.</p> <p>What I'm ultimately trying to achieve, in case I'm going about this the wrong way, is to check if the user is the sender. The idea i had of achieving it was to do something like this:</p> <pre><code>for message in messages: if message_from == request.user.id: messages.annotate(sender=True) </code></pre> <p>Though, this isn't the right syntax. I'm not sure <code>annotate</code> is the right function, either. Any ideas?</p>
1
Twitter API with react JS
<p>I managed to get the following twitter account button working with react with this code:</p> <pre><code>class TwitterShareButton extends React.Component { render() { return &lt;a href="https://twitter.com/share" className="twitter-share-button"&gt;Tweet&lt;/a&gt; } componentDidMount() { var scriptNode = document.getElementById('twitter-wjs') if (scriptNode) { scriptNode.parentNode.removeChild(scriptNode) } !function(d,s,id){ var js, fjs=d.getElementsByTagName(s)[0], p=/^http:/.test(d.location)?'http':'https'; if(!d.getElementById(id)){ js=d.createElement(s); js.id=id; js.src=p+'://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js,fjs); } }(document, 'script', 'twitter-wjs'); } } </code></pre> <p>from <a href="http://qiita.com/h_demon/items/95e638666f6bd479b47b" rel="nofollow">http://qiita.com/h_demon/items/95e638666f6bd479b47b</a></p> <p>How can I bind the events? <a href="https://dev.twitter.com/web/javascript/events" rel="nofollow">https://dev.twitter.com/web/javascript/events</a></p> <p>I added </p> <pre><code>var twttr = document.getElementById('twitter-wjs') twttr.ready(function (twttr) { // Now bind our custom intent events twttr.events.bind('click', clickEventToAnalytics); twttr.events.bind('tweet', tweetIntentToAnalytics); twttr.events.bind('retweet', retweetIntentToAnalytics); twttr.events.bind('like', likeIntentToAnalytics); twttr.events.bind('follow', followIntentToAnalytics); }); </code></pre> <p>to <code>componentDidMount</code>. It didn't work.</p>
1
How To Solve .gradle/wrapper not found
<p>How to set path Gradle Wrapper? I want to build apk from web. but i got stack for 2 days to solve this tings.</p> <p>here my structure folder</p> <pre><code> /var/www/html/engine/api/application/android_app/WebGenerator/ : /.gradle /.idea /source (path i want to build /build /gradle .gitignore webGenerator.iml build.gradle gradle.properties gradlew local.properties settings.gradle </code></pre> <p>in my PHP code i put this one to exec gradlew</p> <pre><code>$app_path = '/var/www/html/engine/api/application/android_app/WebGenerator/'; exec($app_path.'gradlew assembleDebug --parallel --offline 2&gt;&amp;1', $outputs)); </code></pre> <p>ERROR :</p> <pre><code>"Exception in thread "main" java.lang.RuntimeException: java.io.FileNotFoundException: /var/www/.gradle/wrapper/dists/gradle-2.4-all/3i2gobhdl0fm2tosnn15g540i0/gradle-2.4-all.zip.lck (No such file or directory) </code></pre>
1
how to send data using bundle inside RecyclerView onclick method
<p>i want to send my name and image in recycler view oclick but i m bit confused should i use paraceble or simple bundle mechanism how to i send and recived it </p> <pre><code>public class FamousPeople { private static final String FAMOUS_NAME = "famous name"; private static final String FAMOUS_PHOTO="photo"; private String name; private int photo; private String details; FamousPeople(String name, int photo) { this.name = name; this.photo = photo; } public FamousPeople(){ } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public int getPhoto() { return photo; } public void setPhoto(int photo) { this.photo = photo; } public String getName() { return name; } public void setName(String name) { this.name = name; } } </code></pre> <p>BiographyViewHolder class in which i have to pass my images and text data</p> <pre><code> class BiographyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView textView; public ImageView imageView; List&lt;FamousPeople&gt; famousPeoples=GetData.getListdata(); public BiographyViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); textView= (TextView) itemView.findViewById(R.id.country_name); imageView= (ImageView) itemView.findViewById(R.id.country_photo); } @Override public void onClick(View view) { Intent intent=new Intent(); Bundle bundle=new Bundle(); intent.putExtras(bundle); view.getContext().startActivity(intent); } } </code></pre> <p>GetData class getting data from this class</p> <pre><code> public class GetData { public static List&lt;FamousPeople&gt; getListdata() { List&lt;FamousPeople&gt; famousPeoples = new ArrayList&lt;&gt;(); famousPeoples.add(new FamousPeople("rahul", R.drawable.amitabh)); famousPeoples.add(new FamousPeople("sumit", R.drawable.cvraman)); famousPeoples.add(new FamousPeople("neha", R.drawable.indira)); famousPeoples.add(new FamousPeople("surbhi", R.drawable.kishorkumar)); famousPeoples.add(new FamousPeople("rahul", R.drawable.modi)); famousPeoples.add(new FamousPeople("sumit", R.drawable.mother)); famousPeoples.add(new FamousPeople("neha", R.drawable.nehru)) return famousPeoples; } </code></pre>
1
At what point should I worry about underflow in numpy values?
<p>I am doing calculations with Python numpy. Here is a resulting numpy array:</p> <pre><code>[ 5.15054786e-11 5.15251385e-11 5.15262922e-11 ..., 5.21100674e-11 5.21097550e-11 5.21088179e-11] </code></pre> <p>Those are pretty tiny. At what point should I worry about underflow in my calculations? These need to be ultra-precise. Is there a definite value range to worry about, or perhaps a reference which states this value? </p>
1
The result type of the query is neither an EntityType nor a CollectionType with an entity element type
<pre><code>var myQuery = from product in _repository.Query() join prodLocalization in _repoProductLocalization.Query() on product.Id equals prodLocalization.ProductId select new { Product = product, Localization = prodLocalization }; myQuery = myQuery.Include(x =&gt; x.Product.Customer); var prods = myQuery.ToList(); </code></pre> <p>Last line throws:</p> <blockquote> <p>An exception of type 'System.InvalidOperationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code</p> <p>Additional information: The result type of the query is neither an EntityType nor a CollectionType with an entity element type. An Include path can only be specified for a query with one of these result types.</p> </blockquote> <p>I've managed to find little to no explanation on why this happens. Any help?</p>
1
HTML Table page break print in Chrome
<p>This problem is keeping me awake, is there a way to dynamically break a table, and show the header in the next page?</p> <p>The fact is, it is a report and I can't know the number of rows it will show on the screen, I am using AngularJS to fetch the info and show on the screen.</p> <p>Thats my page:</p> <p><a href="http://i.stack.imgur.com/Lbeh8.png" rel="nofollow">Page</a></p> <p>While printing: </p> <p><a href="http://i.stack.imgur.com/UDGd3.png" rel="nofollow">Print</a></p> <p>This is my HTML Page</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;!-- #INCLUDE VIRTUAL="/wvdf_bib/BIB/Includes/bHtmlHead.inc"--&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-8"&gt; &lt;div class="col-xs-4"&gt; &lt;br /&gt; &lt;img class="col-xs-12" src="http://www.cargoweber.com/logos/profile/mepl-international-llc-logo-dubai-dub-916.png" /&gt; &lt;/div&gt; &lt;div class="col-xs-8"&gt; &lt;h3&gt;Demo Company&lt;/h3&gt; &lt;p&gt; John Smith&lt;br /&gt; [email protected]&lt;br /&gt; http://www.demo1.com&lt;br /&gt; Phone: Tel: +1-908-301-6025 &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;h1&gt;Rate quote&lt;/h1&gt; &lt;h5&gt;Created on 17 Jun 2015&lt;/h5&gt; &lt;p&gt;Document Number #LCL FCLJS150617003-1&lt;/p&gt; &lt;small&gt;As of date &lt;strong&gt;17 Jun 2015&lt;/strong&gt;&lt;/small&gt;&lt;br /&gt; &lt;small&gt;Valid until &lt;strong&gt;17 Jul 2015&lt;/strong&gt;&lt;/small&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;table class="table table-bordered"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="col-xs-6"&gt;To&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="col-xs-5"&gt; &lt;br /&gt; &lt;img class="col-xs-12" src="http://www.cocacola.pt/19201201/jopt/post_images/standard/detail_lbITzYnZakM0pchLQsx9frA8wmHFdO.png" /&gt; &lt;/div&gt; &lt;div class="col-xs-7"&gt; &lt;h3&gt;Coca Cola&lt;/h3&gt; &lt;p&gt; http://www.cocacola.com &lt;/p&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row&gt; &lt;div class="col-xs-12"&gt; &lt;table class="table table-bordered"&gt; &lt;thead&gt; &lt;tr&gt; &lt;td colspan="7"&gt;&lt;/td&gt; &lt;td colspan="3"&gt;Total Ocean Freight Sum Up&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;POL&lt;/th&gt; &lt;th&gt;Carrier&lt;/th&gt; &lt;th&gt;POD&lt;/th&gt; &lt;th&gt;VIA Port&lt;/th&gt; &lt;th&gt;Effective date&lt;/th&gt; &lt;th&gt;Expiry date&lt;/th&gt; &lt;th&gt;Transit time&lt;/th&gt; &lt;th&gt;Container20&lt;/th&gt; &lt;th&gt;Container40&lt;/th&gt; &lt;th&gt;Container40HC&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;CNYTN Port of Yantian&lt;/td&gt; &lt;td&gt;NYK Line&lt;/td&gt; &lt;td&gt;USLAX Los Angeles&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;5/17/15&lt;/td&gt; &lt;td&gt;5/17/16&lt;/td&gt; &lt;td&gt;20 days&lt;/td&gt; &lt;td&gt;USD 1,235.00&lt;/td&gt; &lt;td&gt;USD 1,627.00&lt;/td&gt; &lt;td&gt;USD 1,627.00&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; Another x rows &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p></p> <p>The problem is: I need the thead to be printed again on the new page, and I just can't get it to work =(</p> <p>Does anyone know how I can solve this problem?</p>
1
mockito spy object with annotated method
<p>If I add an annotation over a method of mocked objet, the mock is disabled: </p> <pre><code>@Service public class PurchaseService extends AbstractService { @Autowired private CheckoutService checkoutService; @EventAnnotation(EventTypeEnum.PRC_PRODUCT) public CheckoutResponse buy(String productId) { return checkoutService.buy(productId); } } @Service public class CheckoutService extends AbstractService { public CheckoutResponse buy(ExecutionContext context, String productId) { ..... } </code></pre> <p>And the test:</p> <pre><code>@Autowired @Spy private UserService userService; ... @Test public void should_buy() { // Given String productId = "productId"; Loyalty loyalty = new Loyalty(15, new Grade("1", "label", 10)); when(catalogClient.findPromoProductForMember(DEFAULT_TENANT, productId, userId)).thenReturn(promoProduct); when(userService.getUserLoyalty(userId)).thenReturn(loyalty); // When CheckoutResponse result = purchaseService.buy(productId); // &lt;--- // Then assertThat(response).isNotNull(); assertThat(result).isSameAs(response); } </code></pre> <p>If I change <code>purchaseService.buy</code> by <code>CheckoutResponse result = checkoutService.buy</code>, it works</p> <p>Have a solution or get around?</p>
1
Zuul Ribbon exception always returns 500 response
<p>I am using Zuul with Eureka as a reverse proxy. When a downstream service returns a 4xx Client Exception, Ribbon will convert the exception into a 500 server error.</p> <p>An example output on the whitelabel page is:</p> <pre><code>There was an unexpected error (type=Internal Server Error, status=500). 403 FORBIDDEN </code></pre> <p>RibbonRoutingFilter appears to always convert any exception to 500. <a href="https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java#L81" rel="nofollow">https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/zuul/filters/route/RibbonRoutingFilter.java#L81</a></p> <p>Is there any way to override this behavior and have the original status code sent to the client. </p>
1
Makefile Error 3
<p><a href="https://stackoverflow.com/questions/28706489/opencv3-0-with-qt-creator-3-2-qt-5-4-build-error-mingw32-make-makefile">Related Problem</a></p> <p>I have compiled OpenV 3.1 with Qt Creator 3.6.0 32bits in Win10 machine.</p> <p>While building a sample OpenCV program it gives me <code>[Makefile]Error 3</code> with these details:</p> <pre><code>10:02:32: Running steps for project Sanj... 10:02:32: Configuration unchanged, skipping qmake step. 10:02:32: Starting: "C:\Qt\Tools\mingw492_32\bin\mingw32-make.exe" C:\Qt\5.5\mingw492_32\bin\qmake.exe -spec win32-g++ "CONFIG+=debug" "CONFIG+=qml_debug" -o Makefile ..\Sanj\Sanj.pro makefile:195: recipe for target 'Makefile' failed C:/Users/Samir Chohg/Desktop/Sanj/Sanj.pro:27: Extra characters after test expression. Error processing project file: ..\Sanj\Sanj.pro mingw32-make: *** [Makefile] Error 3 10:02:32: The process "C:\Qt\Tools\mingw492_32\bin\mingw32-make.exe" exited with code 2. Error while building/deploying project Sanj (kit: Desktop Qt 5.5.1 MinGW 32bit) When executing step "Make" </code></pre> <p>The code is:</p> <pre><code>QT += core QT -= gui TARGET = Un CONFIG += console CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp INCLUDEPATH += C:/opencv/qttest/install/include LIBS += -LC:/opencv/qttest/install/x86/mingw/bin -lopencv_core310 \ -lopencv_highgui310 \ -lopencv_imgproc310 \ -lopencv_features2d310 \ -lopencv_calib3d310 </code></pre> <p>Can someone show me where the problem is? Thanks in advance.</p>
1
Linker error: unresolved external symbol _WinMain@16 when building console application
<p>I'm trying to compile this code is Visual Studio 2015:</p> <pre><code>int main() { double* pvalue = NULL; pvalue = new double; *pvalue = 29494.99; cout &lt;&lt; "Value of pvalue : " &lt;&lt; *pvalue &lt;&lt; endl; delete pvalue; return 0; } </code></pre> <p>And i'm getting this compile error:</p> <p>1>MSVCRTD.lib(exe_winmain.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)</p> <p>Is this a Visual Studio problem? Should I reinstall it?</p>
1
Android Notification Large Icon Spec?
<p>Where can I find the right dimensions for the Large Icon for Android Notifications?</p> <p>What do I want? I want a nice looking circle (some color) as a Large icon with a little envelop in it. And add a small icon with its own specs. </p> <p>The small icon works all fine. But I have a question about the large icon. I searched for some hours now and couldn't find it! </p> <p>What space can I use for Large Icon? How big is the space? And are there any specs about how big the little envelop in the Large icon should be?</p> <p>Android Kitkat and above:</p> <p>Large Icon (space I can fill): ? Large Icon (how big must the little envelop be? any specs?): ?</p> <p>Below Android KitKat:</p> <p>I know that below Android KitKat the notifications are a bit different. But what are the specs here?</p> <p>Large Icon (space I can fill): ? Large Icon (how big must the little envelop be? any specs?): ?</p> <p><a href="https://stackoverflow.com/questions/26973820/large-notification-icon-background">Large notification icon background</a> The question is kinda the same as in this question. But this question didn't received a final answer. The accepted answer didn't convinced me because there was a discussion in the comments without a conclusion. </p>
1
How to copy file from a network using Python
<p>I want to use Python to copy a zip file (test.zip) from shared network (\svr\shared) to my local computer C:\ drive. Also, my windows account already has access to the network. </p> <p>One more thing, how can I get the content of a network shared folder? Let's say, I need all the file names located at \svr\shared.</p>
1
How to open chrome in incognito tab
<p>I have a scenario open a web link in incognito tab in chrome browser. I am using adb command to open chrome and navigate to specific URL i.e <code>adb shell am start -n com.android.chrome/com.google.android.apps.chrome.Main -d weburl</code> . </p> <p>Is there any way to open link directly in incognito mode through adb?</p>
1
Maven offline: Plugin not found error
<p>I got below compile error in my pom.xml. I want to work with my pom.xml in offline mode. I have dependencies in my repositry. Do I need to install a jar or pom.xml in the org.apache.maven.plugins:maven-javadoc-plugin?. I tried to insert a jar of maven-javadoc-plugin, but it failed. Please help me with this error Or give me some information, I don't know how to solve it. Below is my pom.xml. I know that I have to do something in my .m2 directory. </p> <p>Please find below error:</p> <pre><code>Error resolving version for plugin 'org.apache.maven.plugins:maven-javadoc-plugin' from the repositories [local (C:\Users \myname\.m2\repository), nexus-chrono (http://192.168.241.125:8081/nexus/content/groups/public/)]: Plugin not found in any plugin repository &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;parent&gt; &lt;groupId&gt;es.chx&lt;/groupId&gt; &lt;artifactId&gt;parent-pom&lt;/artifactId&gt; &lt;version&gt;2.0-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;es.chx.gestionEnvios&lt;/groupId&gt; &lt;artifactId&gt;gestionEnvios&lt;/artifactId&gt; &lt;name&gt;gestionEnvios&lt;/name&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;properties&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;org.springframework-version&gt;2.5&lt;/org.springframework-version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;es.chx&lt;/groupId&gt; &lt;artifactId&gt;arq-chx&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;/dependency&gt; &lt;!-- &lt;dependency&gt; --&gt; &lt;!-- &lt;groupId&gt;es.chx.web&lt;/groupId&gt; --&gt; &lt;!-- &lt;artifactId&gt;loginLiferayFromApp&lt;/artifactId&gt; --&gt; &lt;!-- &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; --&gt; &lt;!-- &lt;/dependency&gt; --&gt; &lt;!-- &lt;dependency&gt; --&gt; &lt;!-- &lt;groupId&gt;es.chx.web&lt;/groupId&gt; --&gt; &lt;!-- &lt;artifactId&gt;commonWeb&lt;/artifactId&gt; --&gt; &lt;!-- &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; --&gt; &lt;!-- &lt;/dependency&gt; --&gt; &lt;!-- --&gt; &lt;dependency&gt; &lt;!-- --&gt; &lt;groupId&gt;es.chx.intranet&lt;/groupId&gt; &lt;!-- --&gt; &lt;artifactId&gt;commonIntranet&lt;/artifactId&gt; &lt;!-- --&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;!-- --&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;displaytag&lt;/groupId&gt; &lt;artifactId&gt;displaytag-doc&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;displaytag&lt;/groupId&gt; &lt;artifactId&gt;displaytag&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;displaytag&lt;/groupId&gt; &lt;artifactId&gt;displaytag-export-poi&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;${org.springframework-version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${org.springframework-version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-aop&lt;/artifactId&gt; &lt;version&gt;${org.springframework-version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.ajaxtags&lt;/groupId&gt; &lt;artifactId&gt;ajaxtags&lt;/artifactId&gt; &lt;version&gt;1.3-beta-rc7&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;net.sf.json-lib&lt;/groupId&gt; &lt;artifactId&gt;json-lib&lt;/artifactId&gt; &lt;version&gt;2.2.3&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;net.sf.json-lib&lt;/groupId&gt; &lt;artifactId&gt;json-lib-ext-spring&lt;/artifactId&gt; &lt;version&gt;1.0.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;es.chx.web&lt;/groupId&gt; &lt;artifactId&gt;dwr&lt;/artifactId&gt; &lt;version&gt;3.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;cglib&lt;/groupId&gt; &lt;artifactId&gt;cglib&lt;/artifactId&gt; &lt;version&gt;2.2.2&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.inject&lt;/groupId&gt; &lt;artifactId&gt;javax.inject&lt;/artifactId&gt; &lt;version&gt;1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.validation&lt;/groupId&gt; &lt;artifactId&gt;validation-api&lt;/artifactId&gt; &lt;version&gt;1.0.0.GA&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-validator&lt;/artifactId&gt; &lt;version&gt;4.2.0.Final&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;jstl&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.14&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-validator&lt;/groupId&gt; &lt;artifactId&gt;commons-validator&lt;/artifactId&gt; &lt;version&gt;1.4.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-lang&lt;/groupId&gt; &lt;artifactId&gt;commons-lang&lt;/artifactId&gt; &lt;version&gt;2.6&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;version&gt;2.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-dbcp&lt;/groupId&gt; &lt;artifactId&gt;commons-dbcp&lt;/artifactId&gt; &lt;version&gt;1.2.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.oracle&lt;/groupId&gt; &lt;artifactId&gt;ojdbc14&lt;/artifactId&gt; &lt;version&gt;10.2.0.2.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.4&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-test&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.lowagie&lt;/groupId&gt; &lt;artifactId&gt;itext&lt;/artifactId&gt; &lt;version&gt;1.3&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;repositories&gt; &lt;repository&gt; &lt;releases&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/releases&gt; &lt;snapshots&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/snapshots&gt; &lt;id&gt;nexus-chrono&lt;/id&gt; &lt;url&gt;http://192.168.241.125:8081/nexus/content/groups/public/&lt;/url&gt; &lt;/repository&gt; &lt;repository&gt; &lt;id&gt;apache.snapshots&lt;/id&gt; &lt;name&gt;Maven Plugin Snapshots&lt;/name&gt; &lt;url&gt;http://repository.apache.org/snapshots/&lt;/url&gt; &lt;releases&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/releases&gt; &lt;snapshots&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.1.1&lt;/version&gt; &lt;configuration&gt;&lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-eclipse-plugin&lt;/artifactId&gt; &lt;version&gt;2.9&lt;/version&gt; &lt;configuration&gt; &lt;additionalProjectnatures&gt; &lt;projectnature&gt;org.springframework.ide.eclipse.core.springnature&lt;/projectnature&gt; &lt;/additionalProjectnatures&gt; &lt;additionalBuildcommands&gt; &lt;buildcommand&gt;org.springframework.ide.eclipse.core.springbuilder&lt;/buildcommand&gt; &lt;/additionalBuildcommands&gt; &lt;downloadSources&gt;true&lt;/downloadSources&gt; &lt;downloadJavadocs&gt;true&lt;/downloadJavadocs&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre>
1
JQuery to find LI by text and UL by Class
<p>I am working with a list in SharePoint 2013 that creates an unordered list dynamically on mouseover (the List item ECB for those familiar with SharePoint). </p> <p>The class name that is given has spaces added after at, 1 additional space for each menu item. I'm not sure if this affects the class property value in jquery so that is why I'm using the begins with notation. </p> <p>I am needing to hide several menu items and I'm not getting alerts in my debug so I'm thinking my syntax is off.</p> <p>I'm using this:</p> <pre><code>if($('ul[class^="ms-core-menu-list"] li[text="View Item"]') ! == null) { alert('F'); } else { alert('no F'); } </code></pre> <p>I do not get alerts so either my syntax is wrong and I need assistance with that or the menu item isn't created when this code executes, in which case I'm wondering how it is possible to get at these menu items using jquery as I'm unable to deploy code in my environment. I've looked at a number of blogs over the past few days but nothing recommended comes close to working for me.</p> <p>Thank you</p>
1
How to split react js components into multiple files
<p>I'm trying to separate every component to a separate file for better modularity. Although I've included component jsx file on index page i'm still getting <code>Uncaught ReferenceError: TopicsList is not defined</code></p> <p>Here's the code:</p> <p><strong>index.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;React.js Demo&lt;/title&gt; &lt;link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="css/style.css"&gt; &lt;script src="//code.jquery.com/jquery-2.2.0.min.js"&gt;&lt;/script&gt; &lt;script src="//fb.me/react-0.14.5.js"&gt;&lt;/script&gt; &lt;script src="//fb.me/react-dom-0.14.5.js"&gt;&lt;/script&gt; &lt;script src="//fb.me/JSXTransformer-0.12.2.js"&gt;&lt;/script&gt; &lt;script src="../components/layout.jsx" type="text/jsx"&gt;&lt;/script&gt; &lt;script src="../components/topic-list.jsx" type="text/jsx"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="main-container"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>layout.jsx</strong></p> <pre><code>"use strict"; var Layout = React.createClass({ render: function() { return ( &lt;div className="container"&gt; &lt;TopicsList /&gt; &lt;/div&gt; ); } }); ReactDOM.render(&lt;Layout /&gt;, document.getElementById('main-container')); </code></pre> <p><strong>topic-list.jsx</strong></p> <pre><code>"use strict"; var TopicsList = React.createClass({ getInitialState: function () { return { isTopicClicked : false, topicPages }; }, onClick: function (topicID) { this.setState({isTopicClicked : true}); this.setState({topicsID : topicID}); }, render: function () { return ( &lt;div&gt; &lt;div className="row topic-list"&gt; &lt;SingleTopicBox topicID="1" onClick={this.onClick} label="Topic" /&gt; &lt;SingleTopicBox topicID="2" onClick={this.onClick} label="Topic" /&gt; &lt;SingleTopicBox topicID="3" onClick={this.onClick} label="Topic" /&gt; &lt;SingleTopicBox topicID="4" onClick={this.onClick} label="Topic" /&gt; &lt;/div&gt; &lt;div className="row"&gt; { this.state.isTopicClicked ? &lt;SelectedTopicPage topicsID={this.state.topicsID} key={this.state.topicsID} topicPages={topicPages} /&gt; : null } &lt;/div&gt; &lt;/div&gt; ); } }); var SingleTopicBox = React.createClass({ render: function () { return ( &lt;div&gt; &lt;div className="col-sm-2"&gt; &lt;div onClick={this.props.onClick.bind(null, this.props.topicID)} className="single-topic" data-topic-id={this.props.topicID}&gt; {this.props.label} {this.props.topicID} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } }); var topicPages = [ { topic_no: '1', topic_pages: [ { headline: 'Topic 1 headline', description: 'Topic 1 description comes here...page 1' }, { headline: 'Topic 1 headline', description: 'Topic 1 description comes here...page 2' }, { headline: 'Topic 1 headline', description: 'Topic 1 description comes here...page 3' } ] }, { topic_no: '2', topic_pages: [ { headline: 'Topic 2 headline', description: 'Topic 2 description comes here...page 1' }, { headline: 'Topic 2 headline', description: 'Topic 2 description comes here...page 2' }, { headline: 'Topic 2 headline', description: 'Topic 2 description comes here...page 3' } ] }, { topic_no: '3', topic_pages: [ { headline: 'Topic 3 headline', description: 'Topic 3 description comes here...page 1' }, { headline: 'Topic 3 headline', description: 'Topic 3 description comes here...page 2' }, { headline: 'Topic 3 headline', description: 'Topic 3 description comes here...page 3' } ] }, { topic_no: '4', topic_pages: [ { headline: 'Topic 4 headline', description: 'Topic 4 description comes here...page 1' }, { headline: 'Topic 4 headline', description: 'Topic 4 description comes here...page 2' }, { headline: 'Topic 4 headline', description: 'Topic 4 description comes here...page 3' } ] }, ]; var SelectedTopicPage = React.createClass({ getInitialState: function() { return{ topicPageNo: 0, total_selected_topic_pages: 1 } }, navigateBack: function() { let topicPageNo; if (this.state.topicPageNo &gt; 0){ topicPageNo = this.state.topicPageNo - 1; } else { topicPageNo = 0; } this.setState({topicPageNo : topicPageNo}); }, navigateNext: function(totalPagesInSelectedTopic) { let topicPageNo; if (totalPagesInSelectedTopic &gt; this.state.topicPageNo + 1){ topicPageNo = this.state.topicPageNo + 1; } else { topicPageNo = this.state.topicPageNo; } this.setState({topicPageNo : topicPageNo}); }, render: function() { let topicsID = this.props.topicsID; let topicPageNo = this.state.topicPageNo; return ( &lt;div&gt; {this.props.topicPages.filter(function(topicPage) { // if condition is true, item is not filtered out return topicPage.topic_no === topicsID; }).map(function (topicPage) { let totalPagesInSelectedTopic = topicPage.topic_pages.length; return ( &lt;div&gt; &lt;div&gt; &lt;SelectedTopicPageMarkup headline={topicPage.topic_pages[0].headline} key={topicPage.topic_no}&gt; {topicPage.topic_pages[topicPageNo].description} &lt;/SelectedTopicPageMarkup&gt; &lt;/div&gt; &lt;div&gt; &lt;NextPrevBtn moveNext={this.navigateNext.bind(this, totalPagesInSelectedTopic)} key={topicPage.topic_no} moveBack={this.navigateBack}/&gt; &lt;/div&gt; &lt;/div&gt; ); }.bind(this))} &lt;/div&gt; ); } }); var SelectedTopicPageMarkup = React.createClass({ render: function() { return ( &lt;div className="topics-page"&gt; &lt;h1&gt;{this.props.headline}&lt;/h1&gt; &lt;p&gt;{this.props.children}&lt;/p&gt; &lt;/div&gt; ); } }); var NextPrevBtn = React.createClass({ render: function() { return ( &lt;div className="next-prev-btn"&gt; &lt;a onClick={this.props.moveBack} className="btn prev-btn"&gt;Back&lt;/a&gt; &lt;a onClick={this.props.moveNext} className="btn next-btn"&gt;Next&lt;/a&gt; &lt;/div&gt; ); } }); </code></pre>
1
Comparing Python accelerators (Cython,Numba,f2py) to Numpy einsum
<p>I'm comparing Python accelerators (Numba, Cython, f2py) to simple For loops and Numpy's einsum for a particular problem (see below). So far Numpy is the fastest for this problem (factor 6x faster), but I wanted some feedback if there are additional optimizations I should try, or if I'm doing something wrong. This simple code is based on a larger code that has a number of these einsum calls, but no explicit for loops. I'm checking if any of these accelerators can do better. </p> <p>Timings done with Python 2.7.9 on Mac OS X Yosemite, with gcc-5.3.0 installed (--with-fortran --without-multilib) from Homebrew. Also did %timeit calls; these single call timings are fairly accurate.</p> <pre><code>In [1]: %run -i test_numba.py test_numpy: 0.0805640220642 Matches Numpy output: True test_dumb: 1.43043899536 Matches Numpy output: True test_numba: 0.464295864105 Matches Numpy output: True test_cython: 0.627640008926 Matches Numpy output: True test_f2py: 5.01890516281 Matches Numpy output: True test_f2py_order: 2.31424307823 Matches Numpy output: True test_f2py_reorder: 0.507861852646 Matches Numpy output: True </code></pre> <p>The main code: </p> <pre><code>import numpy as np import numba import time import test_f2py as tf2py import pyximport pyximport.install(setup_args={'include_dirs':np.get_include()}) import test_cython as tcyth def test_dumb(f,b): fnew = np.empty((f.shape[1],f.shape[2])) for i in range(f.shape[0]): for l in range(f.shape[3]): fnew += f[i,:,:,l] * b[i,l] return fnew def test_dumber(f,b): fnew = np.empty((f.shape[1],f.shape[2])) for i in range(f.shape[0]): for j in range(f.shape[1]): for k in range(f.shape[2]): for l in range(f.shape[3]): fnew[j,k] += f[i,j,k,l] * b[i,l] return fnew @numba.jit(nopython=True) def test_numba(f,b): fnew = np.zeros((f.shape[1],f.shape[2])) #NOTE: can't be empty, gives errors for i in range(f.shape[0]): for j in range(f.shape[1]): for k in range(f.shape[2]): for l in range(f.shape[3]): fnew[j,k] += f[i,j,k,l] * b[i,l] return fnew def test_numpy(f,b): return np.einsum('i...k,ik-&gt;...',f,b) def test_f2py(f,b): return tf2py.test_f2py(f,b) def test_f2py_order(f,b): return tf2py.test_f2py(f,b) def test_f2py_reorder(f,b): return tf2py.test_f2py_reorder(f,b) def test_cython(f,b): return tcyth.test_cython(f,b) if __name__ == '__main__': #goal is to create: fnew = sum f*b over dim 0 and 3. f = np.random.rand(32,33,2000,64) b = np.random.rand(32,64) f1 = np.asfortranarray(f) b1 = np.asfortranarray(b) f2 = np.asfortranarray(np.transpose(f,[1,2,0,3])) funcs = [test_dumb,test_numba, test_cython, \ test_f2py,test_f2py_order,test_f2py_reorder] tstart = time.time() fnew_numpy= test_numpy(f,b) tstop = time.time() print test_numpy.__name__+': '+str(tstop-tstart) print 'Matches Numpy output: '+str(np.allclose(fnew_numpy,fnew_numpy)) print '' for func in funcs: tstart = time.time() if func.__name__ == 'test_f2py_order': fnew = func(f1,b1) elif func.__name__ == 'test_f2py_reorder': fnew = func(f2,b1) else: fnew = func(f,b) tstop = time.time() print func.__name__+': '+str(tstop-tstart) print 'Matches Numpy output: '+str(np.allclose(fnew,fnew_numpy)) print '' </code></pre> <p>The f2py file (compiled with f2py -c -m test_f2py test_f2py.F90): </p> <pre><code>!file: test_f2py subroutine test_f2py(f,b,fnew,n1,n2,n3,n4) integer :: n1,n2,n3,n4 real(8), dimension(n1,n2,n3,n4) :: f real(8), dimension(n1,n4) :: b real(8), dimension(n2,n3) :: fnew !f2py intent(in) f !f2py intent(in) b !f2py intent(out) fnew !f2py intent(in) n1 !f2py intent(in) n2 !f2py intent(in) n3 !f2py intent(in) n4 integer :: i1,i2,i3,i4 do i1=1,n1 do i2=1,n2 do i3=1,n3 do i4=1,n4 fnew(i2,i3) = fnew(i2,i3) + f(i1,i2,i3,i4)*b(i1,i4) enddo enddo enddo enddo end subroutine test_f2py subroutine test_f2py_reorder(f,b,fnew,n1,n2,n3,n4) integer :: n1,n2,n3,n4 real(8), dimension(n1,n2,n3,n4) :: f real(8), dimension(n3,n4) :: b real(8), dimension(n1,n2) :: fnew !f2py intent(in) f !f2py intent(in) b !f2py intent(out) fnew !f2py intent(in) n1 !f2py intent(in) n2 !f2py intent(in) n3 !f2py intent(in) n4 integer :: i1,i2,i3,i4 do i3=1,n3 do i4=1,n4 do i1=1,n1 do i2=1,n2 fnew(i1,i2) = fnew(i1,i2) + f(i1,i2,i3,i4)*b(i3,i4) enddo enddo enddo enddo end subroutine test_f2py_reorder </code></pre> <p>And the Cython .pyx file (compiled with pyximport in the main routine):</p> <pre><code>#/usr/bin python import numpy as np cimport numpy as np def test_cython(np.ndarray[np.float64_t,ndim=4] f, np.ndarray[np.float64_t,ndim=2] b): # cdef np.ndarray[np.float64_t,ndim=4] f # cdef np.ndarray[np.float64_t,ndim=2] b cdef np.ndarray[np.float64_t,ndim=2] fnew = np.empty((f.shape[1],f.shape[2]),dtype=np.float64) cdef int i,j,k,l cdef int Ni = f.shape[0] cdef int Nj = f.shape[1] cdef int Nk = f.shape[2] cdef int Nl = f.shape[3] for i in range(Ni): for j in range(Nj): for k in range(Nk): for l in range(Nl): fnew[j,k] += f[i,j,k,l] * b[i,l] return fnew </code></pre>
1
Transaction returns E00027 but response code is 1
<p>Using the Java API version 1.8.6 to commit a simple credit card payment transaction in live mode against a real gateway account. TransactionResponse getResponseCode() returns 1 which is supposed to mean that the transaction succeeded. But getErrors() includes an error E00027 that suggests that the transaction failed. Did the transaction succeed or not?</p>
1
Generate and Send .ics file via Symfony2 (Swift Mailer)
<p>I am trying to generate a calendar event MS Outlook/Google Calendar in Symfony2, while the email is sent with .ics file but I am not able to get the event added to calendar. When I try to open the file it says </p> <pre><code>Failed to import events: Unable to process your iCal/CSV file.. </code></pre> <p>This is how I am trying to generate the iCal file</p> <pre><code>$message=" BEGIN:VCALENDAR VERSION:2.0 CALSCALE:GREGORIAN METHOD:REQUEST BEGIN:VEVENT DTSTART:".date('Ymd\THis', strtotime($meetingStartTime))." DTEND:".date('Ymd\THis', strtotime($meetingEndTime))." DTSTAMP:".date('Ymd\THis', strtotime($meetingStartTime))." ORGANIZER;CN=XYZ:mailto:[email protected] UID:".rand(5, 1500)." ATTENDEE;PARTSTAT=NEEDS-ACTION;RSVP= TRUE;CN=Sample:[email protected] DESCRIPTION:".$this-&gt;getUser()-&gt;getName()." requested Phone/Video Meeting Request LOCATION: Phone/Video SEQUENCE:0 STATUS:CONFIRMED SUMMARY:Meeting has been scheduled by ".$this-&gt;getUser()-&gt;getName()." TRANSP:OPAQUE END:VEVENT END:VCALENDAR"; $messageObject = \Swift_Message::newInstance(); $messageObject-&gt;setContentType("text/calendar"); $messageObject-&gt;setSubject("Your meeting has been booked") -&gt;setFrom($this-&gt;container-&gt;getParameter('mailer_user'), "From Name") -&gt;setTo($this-&gt;getUser()-&gt;getEmail()) -&gt;setBody(trim($message)); $this-&gt;get('mailer')-&gt;send($messageObject); </code></pre> <p>I will really appreciate if I can get some help on what I am doing wrong which leads to the error of <strong>Failed to import events: Unable to process your iCal/CSV file</strong></p>
1
How to insert pause in speech synthesis with grammatical hints
<p>I am writing a simple spelling test app using the HTML5 SpeechSynthesis API. The text I would like my app to say is something like the following: "The spelling word is Cat. The cat chased the dog.". </p> <p>The API tends to race without much of a pause from the first sentence to the second. I wonder if there is a way to insert a bit of a pause between the 2 sentences. I realize I could create 2 separate utterances and use the pause() call. However the code would be simpler and less brittle if I could simply insert grammatical hints.</p> <p>Normally in spoken English, one tends to pause a little longer between paragraphs. So I inserted a newline character in my text, but there was no noticeable impact.</p> <p>I also tried using an ellipsis.</p> <p>Is there any way to do this or am I stuck breaking everything into separate utterances?</p>
1
Empty PDF report is generated when we have multiple graphs using html2canvas and jsPDF library
<p>I have two flot charts in One page , and with the code below, I want to use jsPDF to create report of them in two different pages (but one PD file) here id my code: Lets use this sample graphs :</p> <pre><code>function flot1() { var oilPrices = [[1167692400000, 61.05], [1167778800000, 58.32], [1167865200000, 57.35], [1167951600000, 56.31], [1168210800000, 55.55], [1168297200000, 55.64] , [1168383600000, 54.02], [1168470000000, 51.88], [1168556400000, 52.99], [1168815600000, 52.99], [1168902000000, 51.21], [1168988400000, 52.24], [1169074800000, 50.48]]; var exchangeRates = [[1167606000000, 0.7580], [1167692400000, 0.7580], [1167778800000, 0.75470], [1167865200000, 0.75490], [1167951600000, 0.76130], [1168038000000, 0.76550], [1168124400000, 0.76930], [1168210800000, 0.76940], [1168297200000, 0.76880], [1168383600000, 0.76780], [1168470000000, 0.77080], [1168556400000, 0.77270], [1168642800000, 0.77490], [1168729200000, 0.77410], [1168815600000, 0.77410], [1168902000000, 0.77320], [1168988400000, 0.77270], [1169074800000, 0.77370], [1169161200000, 0.77240], [1169247600000, 0.77120]]; var data = [ { data: oilPrices, label: "Oil price ($)" }, { data: exchangeRates, label: "USD/EUR exchange rate", yaxis: 2 } ]; var options = { canvas: true, xaxes: [{ mode: "time" }], yaxes: [{ min: 0 }, { position: "right", alignTicksWithAxis: 1, tickFormatter: function (value, axis) { return value.toFixed(axis.tickDecimals) + "€"; } }], legend: { position: "sw" } } plot = $.plot("#placeholder_2", data, options); } function flot2() { plot = $.plot($("#placeholder"), [{ label: 'Test', data: [[0, 0], [1, 1]] }], { yaxis: { max: 1 } }); } var doc = new jsPDF(); html2canvas($("#placeholder").get(0), { onrendered: function (canvas) { var imgData = canvas.toDataURL('image/png'); doc.addImage(imgData, 'PNG', 10, 10, 180, 115); } }); var element = $("#placeholder_2").get(0); html2canvas(element, { onrendered: function (canvas2) { var imgData2 = canvas2.toDataURL('image/png'); doc.addPage() doc.addImage(imgData2, 'PNG', 10, 10, 180, 60); } }); doc.save('sample-file.pdf'); </code></pre> <p>the problem is : </p> <p>when I save pdf with <strong>ONE</strong> graph, it works fine, but after puting doc.save() at the end of canvas renders , the created PDF file is empty.</p> <blockquote> <p>NOTE: I use <a href="http://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js" rel="nofollow">html2canvas</a> and <a href="http://mrrio.github.io/jsPDF/dist/jspdf.min.js" rel="nofollow">jsPDF</a> libraries.</p> </blockquote>
1
Adding siblings to nodes in a family tree
<p>This <a href="http://bl.ocks.org/mbostock/2966094" rel="nofollow noreferrer">example</a> shows d3 being used to draw an ancestry chart.</p> <p>I have been looking at chart having the ancestors, descendants and siblings as shown below. In the example John Doe, Mary Joe and Jacob Joes are siblings.</p> <p>This is tree for John Doe. The tree for B1 Doe is collapsed. It will be complex if her tree is also shown in this chart. If that is done, her ancestor edges/links will cross with John Doe's. </p> <p>Can a tree like this can be drawn with d3?</p> <p><a href="https://i.stack.imgur.com/2QyIr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2QyIr.png" alt="enter image description here"></a></p>
1
Google API: refresh_token missing (access type = offline)
<p>I'm trying to connect my webapp to google drive. So I'm using PHP with official Github PHP client code [ <a href="https://github.com/google/google-api-php-client/tree/v1-master" rel="nofollow">https://github.com/google/google-api-php-client/tree/v1-master</a> ].</p> <p>I followed the quickstart [ <a href="https://developers.google.com/drive/v2/web/quickstart/php" rel="nofollow">https://developers.google.com/drive/v2/web/quickstart/php</a> ] for v2, because PHP client is for v2 only.</p> <p>Then I added a line to request offline access. [See <a href="https://developers.google.com/identity/protocols/OAuth2WebServer#offline]" rel="nofollow">https://developers.google.com/identity/protocols/OAuth2WebServer#offline]</a> </p> <p>My app code, developed using Yii 1, but it's not important, is:</p> <pre><code> $client = new Google_Client(); $client-&gt;setApplicationName("Google Drive Client"); $client-&gt;addScope(Google_Service_Drive::DRIVE_METADATA_READONLY); $client-&gt;setRedirectUri( Yii::app()-&gt;createAbsoluteUrl("site/googleApiLoginCallback") ); $client-&gt;setAuthConfigFile(CLIENT_SECRET_PATH); $client-&gt;setAccessType('offline'); if (file_exists(CREDENTIALS_PATH)) { $accessToken = file_get_contents(CREDENTIALS_PATH); } else { // Request authorization from the user. $auth_url = $client-&gt;createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); Yii::app()-&gt;end(); } $client-&gt;setAccessToken($accessToken); // Refresh the token if it's expired. if ($client-&gt;isAccessTokenExpired()) { $refresh_token = $client-&gt;getRefreshToken(); // CVarDumper::dump($refresh_token,2,true); $client-&gt;refreshToken($refresh_token); file_put_contents(CREDENTIALS_PATH, $client-&gt;getAccessToken()); } return $client; </code></pre> <p>This is the code for handling the OAuth callback. I simply set the access token received, then redirect to the page.</p> <pre><code>public function actionGoogleApiLoginCallback($code) { $client = new Google_Client(); $client-&gt;setApplicationName("Google Drive Client"); $client-&gt;addScope(Google_Service_Drive::DRIVE_METADATA_READONLY); $client-&gt;setRedirectUri( Yii::app()-&gt;createAbsoluteUrl("site/googleApiLoginCallback") ); $client-&gt;setAuthConfigFile(CLIENT_SECRET_PATH); $client-&gt;setAccessType('offline'); $accessToken = $client-&gt;authenticate($code); if(!file_exists(dirname(CREDENTIALS_PATH))) { mkdir(dirname(CREDENTIALS_PATH), 0700, true); } file_put_contents(CREDENTIALS_PATH, $accessToken); $preGoogleApiLoginRoute = Yii::app()-&gt;user-&gt;getState("preGoogleApiLoginRoute", null); if ($preGoogleApiLoginRoute) { $this-&gt;redirect(array( $preGoogleApiLoginRoute )); } else { $this-&gt;redirect(array("site/index")); } } </code></pre> <p>When user the first time access the page, my webapp sucessfully redirect to Google Login; user do login, and Google redirect user to my website at <code>site/googleApiLoginCallback</code>. I set the received code as accessToken and redirect user to the page of webapp he come from. </p> <p>It works.</p> <p>BUT: After a while, when user came back to the page, tyhe token is expired. When it's executed the <code>$client-&gt;getRefreshToken()</code>, it returns a <code>null</code>, so <code>$client-&gt;refreshToken()</code> throw the following error because of missing refresh token</p> <blockquote> <p>Error refreshing the OAuth2 token, message: '{ "error" : "invalid_request", "error_description" : "Missing required parameter: refresh_token" }'</p> </blockquote> <p><strong>What am I missing or doing wrong?</strong></p> <p>For reference: this is my json access token. As you can see I've not a field named 'refreshToken' as I expect</p> <pre><code>{"access_token":"...hiddden...","token_type":"Bearer","expires_in":3600,"created":1453759023} </code></pre>
1
D3.JS: Multi-series line chart, show tooltip for all lines at date?
<p>I've created a multi-series line chart with tooltips. Please check it out at <a href="https://jsfiddle.net/rd1eoLq8/" rel="nofollow noreferrer">this JSFiddle</a>.</p> <p>Currently, the tooltip works as expected: when you hover over a circle, it shows a tooltip with the data's value at that point.</p> <pre><code>var tooltip = d3.tip() .attr('class', 'tooltip') .offset([-10, 0]) .html(function (d) { return '&lt;strong&gt;Population ' + (d.date).getFullYear() + ':&lt;/strong&gt; ' + format(d.population) + ' people'; }); svg.call(tooltip); ... city.selectAll('.circle') .data( function(d) { return(d. values); } ) .enter() .append('svg:circle') .attr('class', 'circle') .attr('cx', function (d, i) { return x(d.date); }) .attr('cy', function (d, i) { return y(d.population); }) .attr('r', 5) .on('mouseover', tooltip.show) .on('mouseout', tooltip.hide) </code></pre> <p>However, I would like to open tooltips at all data points with that x-value. So it would look like this:</p> <p><a href="https://i.stack.imgur.com/pX9id.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pX9id.png" alt="Tooltip idea"></a></p> <p>Of course with the correct values for those points.</p> <p>How could I modify my code to achieve this? Any help is greatly appreciated!</p>
1
Why Remove support for ParNew+SerialOld and DefNew+CMS in the future?
<p>Java HotSpot(TM) 64-Bit Server VM warning: Using the ParNew young collector with the Serial old collector is deprecated and will likely be removed in a future release </p>
1
How to display validation errors on WooCommerce user registration before default errors
<p>I'm using the following filter &amp; action to produce some custom validation errors on woocommerce registration process. </p> <p>filter</p> <pre><code>woocommerce_registration_errors </code></pre> <p>action</p> <pre><code>woocommerce_register_post </code></pre> <p>The problem is that both of the hooks above, are fired after some basic validations of woocommerce such as checking email, and password.</p> <p>I want to limit some IP's to not register, and the error should be at the top of validation errors. So first we check if the ip is valid, now we can go further and do other validations.</p> <p>I couldn't find any other action or filter.</p>
1
Cannot connect to datastax agent
<p>I am unable to connect to any nodes through opscenter. In opscenter it says that agents need to be connected inorder for opscenter to work. I checked in datastax-agent/agent.log file and found below errors. </p> <pre><code>ERROR [clojure-agent-send-off-pool-0] 2016-01-27 09:30:54,545 Can't connect to Cassandra (All host(s) tried for query failed (tried: /127.0.0.1:9042 (com.datastax.driver.core.TransportException: [/127.0.0.1:9042] Cannot connect))), retrying soon. </code></pre> <p>I checked port 9042 and 7199 both are listening.. </p> <pre><code>x.x.x.10:9042 :::* LISTEN 497 499005 28550/java </code></pre> <p>pls advise.. what needs to be checked for this. Thanks</p>
1
Firebase and select distinct
<p>My data in firebase looks like</p> <p><a href="https://i.stack.imgur.com/VHoWk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VHoWk.png" alt="enter image description here"></a></p> <p>Can I do a select distinct on the Genre node using the REST API of firebase?</p>
1
Issue using try within R to catch errors with importing files
<p>I have a process in R in which I am importing a number of files in R. </p> <p>Occasionally there are issues with some of the files, for example there isn't an EOF character present in the file that I'm reading in, so the read.table statement errors.</p> <p>As there are a lot of files to process this is difficult to manage manually, so I would like to use some error trapping to alter the user of the issue and carry on with the other files. </p> <p>I have tried using <code>try</code> and referenced the SOF post <a href="https://stackoverflow.com/questions/31214361/what-is-the-r-equivalent-for-excel-iferror" title="What is the R equivalent for Excel IFERROR?">What is the R equivalent for Excel IFERROR?</a></p> <p>Below I would like to test the import then depending on the result either give some message to the user or actually import the file. </p> <pre><code> mtry &lt;- try(read.table("~/file_location/test_file.csv", fill = TRUE, stringsAsFactors = FALSE)) if (!inherits(mtry, "try-error")) { read.table("~/file_location/test_file..csv", fill = TRUE, stringsAsFactors = FALSE) } else { message("File doesn't exist, please check") } </code></pre> <p>The issue is that the <code>try()</code> statement is producing an error in the log which is what I'm trying to avoid.</p> <p>Thanks</p>
1
using HTML how to open a file save dialog for download?
<p>When I click a button I generate a file, the file name will be different each time, and the generated file should be downloaded to the user, with automatic save dialog.</p> <p>Now I have created a hyperlink of it, on clicking it the dialog box opens, but the requirement is to have direct open of dialog without the hyperlink. Not sure what is missing. </p> <p>I currently use <code>&lt;a href="filname" /a&gt;</code></p> <p>P.S.: Web server is hosted on an embedded device with limited resources, and it supports basic HTML only. ( without <code>.htaccess</code> files )</p>
1
Check String null or empty and replace with another string
<p>In here i want to, If AvailCode comes as a <code>null</code> or <code>empty</code> string then i need to show it "Temporary Unavailable".But my coding doen't show that one. (Consider only Avail Code).</p> <pre><code>var _staff = trv.GetBookDetails("4500").Select(b =&gt; new { value = b.bookno, text = b.bookname + " " + "/"+" " + b.AvailCode ?? "TemporaryUnavailable", }); </code></pre>
1
getDrawable(int) from the type Resources is deprecated in Eclipse Android
<p>I am following some tutorials in android about how to create an app that can toggle the silent mode. Everything is fine until I got this errors:</p> <p><a href="https://i.stack.imgur.com/yuMVB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yuMVB.png" alt="enter image description here"></a></p> <pre><code>The method getDrawable(int) from the type Resources is deprecated </code></pre> <p>Can you help me with this? I am new in Android. By the way I am using API 23 for this.</p>
1
Imported constant is undefined
<p>I have a <code>server.js</code> file and a <code>main.js</code> file that are compiled with <code>watchify app/src/main.js --node -t babelify -o app/build/main.js &amp; watchify app/src/server.js --node -t babelify -o app/build/server.js</code></p> <p>main.js:</p> <pre><code>const rnd = 3 export { rnd } </code></pre> <p>server.js:</p> <pre><code>import { rnd } from '../build/main' console.log(rnd) import express from 'express' let app = express() app.listen(8080) </code></pre> <p>But it logs <code>undefined</code>. What am I doing wrong?</p> <p>main.js build:</p> <pre><code>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&amp;&amp;require;if(!u&amp;&amp;a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&amp;&amp;require;for(var o=0;o&lt;r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var rnd = 3; exports.rnd = rnd; },{}]},{},[1]); </code></pre> <p>server.js build:</p> <pre><code>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&amp;&amp;require;if(!u&amp;&amp;a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&amp;&amp;require;for(var o=0;o&lt;r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ "use strict"; (function e(t, n, r) { function s(o, u) { if (!n[o]) { if (!t[o]) { var a = typeof require == "function" &amp;&amp; require;if (!u &amp;&amp; a) return a(o, !0);if (i) return i(o, !0);var f = new Error("Cannot find module '" + o + "'");throw f.code = "MODULE_NOT_FOUND", f; }var l = n[o] = { exports: {} };t[o][0].call(l.exports, function (e) { var n = t[o][1][e];return s(n ? n : e); }, l, l.exports, e, t, n, r); }return n[o].exports; }var i = typeof require == "function" &amp;&amp; require;for (var o = 0; o &lt; r.length; o++) { s(r[o]); }return s; })({ 1: [function (require, module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var rnd = 3; exports.rnd = rnd; }, {}] }, {}, [1]); },{}],2:[function(require,module,exports){ 'use strict'; var _main = require('../build/main'); var _express = require('express'); var _express2 = _interopRequireDefault(_express); function _interopRequireDefault(obj) { return obj &amp;&amp; obj.__esModule ? obj : { default: obj }; } console.log(_main.rnd); var app = (0, _express2.default)(); app.listen(8080); },{"../build/main":1,"express":20}],3:[function(require,module,exports){ // ... </code></pre>
1
Spring JPA - deleting child element doesn't reflect in database table
<p>I'm having problems deleting the child element of a one-to-many relationship entity. Here's a code snippet:</p> <pre><code>@Override @Transactional public void deleteTask(UUID listId, UUID taskId) { TaskList list = repo.findOne(listId); System.out.println("Old List: " + list); for(Task t : list.getTasks()) { if(t.getId().toString().equals(taskId.toString())) { System.out.println(list.getTasks().remove(t)); System.out.println("Task with id " + taskId + " deleted."); } } System.out.println("New List: " + repo.save(list)); } </code></pre> <p>The Task class is this:</p> <pre><code>@Entity(name = "task") public class Task implements Serializable { // Id and 3 fields @ManyToOne @JoinColumn(name="tasklist_id") private TaskList parentList; // 3 more fields // Constructor public Task() {} //Getters and Setters } </code></pre> <p>and the TaskList class is this:</p> <pre><code>@Entity(name = "task_list") public class TaskList implements Serializable { // Id and two fields @OneToMany(mappedBy="parentList", cascade={CascadeType.ALL}) private List&lt;Task&gt; tasks; // Constructor public TaskList() {} } </code></pre> <p>The <code>Task</code> entity is the child, and even though the save() function returns the truncated <code>TaskList</code>, I can't get the changes to show in a separate query to the database. The number of tasks remains the same. However, deleting a list through <code>repo.delete(listId)</code> works fine with both the list and its tasks gone.</p> <p>Here, <code>repo</code> is a repository corresponding to the parent <code>TaskList</code> class. All operations to the child <code>Task</code> class happen through a <code>@OneToMany({cascade=CascadeType.ALL})</code> relation.</p> <p>For some reason, searching for all <code>TaskList</code>s using <code>repo.findAll()</code> also returns faulty results.</p> <p>I'm obviously doing something fundamentally wrong. Please tell me what to do.</p>
1
How to correctly pass an image as an argument to a class in opencv python
<p>I am a newbie to python and opencv and when I try to run this code I get an error in the colors method while converting <code>BGR</code> to <code>HSV</code> as </p> <pre><code>hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) cv2.error: C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\imgproc\src\color.cpp:7646: error: (-215) (scn == 3 || scn == 4) &amp;&amp; (depth == CV_8U || depth == CV_32F) in function cv::ipp_cvtColor </code></pre> <p>Even if I comment that part out and only run the part where it is simply returning the image as it is, it gives an error while displaying the image in cv2.imshow() as</p> <pre><code>cv2.imshow('image',res) cv2.error: C:\builds\master_PackSlaveAddon-win32-vc12-static\opencv\modules\highgui\src\window.cpp:281: error: (-215) size.width&gt;0 &amp;&amp; size.height&gt;0 in function cv::imshow </code></pre> <p>Please help me figure out if I'm missing out on something.</p> <pre><code>class basicop: @staticmethod def colors(color, frame): if(color=='red'): lower = np.array([0, 100, 100]) upper= np.array([10, 255, 255]) elif(color=='green'): lower = np.array([86, 36, 99]) upper= np.array([86, 255, 255]) #CONVERT BGR TO HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(frame, lower, upper) res = cv2.bitwise_and(frame, frame, mask= mask) return frame frame= cv2.imread('gree.jpg') res=basicop.colors('green', frame) cv2.imshow('image', res) k = cv2.waitKey(0) if k == 27: cv2.destroyAllWindows() elif k == ord('s'): cv2.imwrite('sanj.jpg', res) cv2.destroyAllWindows() </code></pre>
1
Can I let Shiny wait for a longer time for numericInput before updating?
<p>In my Shiny App, there are a few <code>numericInput</code> and <code>selectInput</code>. </p> <p>Shiny updates outputs during typing, especially when users type is slower in the numericInput.</p> <p><code>sumbitButton</code> could you be used to stop automatically updading. But I prefer to not to use it. </p> <p>How could I let Shiny waits for a longer time for <code>numericInput</code>?</p> <p>Thanks for any suggestion. Let me know if my question is not clear.</p>
1
'NameError: global name is not defined' under pdb, for dictionary that does exist
<p>I've encountered an issue re scopes in a <code>lambda</code> function. I can successfully output foo to stdout but I get an error when using <code>max()</code> including a <code>lambda</code> - see simplified code below...</p> <p>All in all, I am trying find the largest value for a nested key <code>budget</code> within an unknown number of first order keys.</p> <pre><code>(Pdb) foo = self.some_method() # some_method() returns a dict, printed in the next step (Pdb) pp foo {'1': {'count': 1, 'extra_data': {'activity-count': 1, 'budget': 0, [...MORE KEY-VALUE PAIRS HERE...] 'version': 1}, [...LOTS MORE KEY-VALUE PAIRS HERE...] 'elements_total': defaultdict(&lt;type 'int'&gt;, {'result': 1, 'another_key': 2}), 'extra_year_data': defaultdict(&lt;function &lt;lambda&gt; at 0x10e05bd70&gt;, {})}, '2': {'count': 1, 'extra_data': {'activity-count': 1, 'budget': 3, [...MORE KEY-VALUE PAIRS HERE...] 'version': 1}, [...LOTS MORE KEY-VALUE PAIRS HERE...] 'elements_total': defaultdict(&lt;type 'int'&gt;, {'result': 1, 'another_key': 2}), 'extra_year_data': defaultdict(&lt;function &lt;lambda&gt; at 0x10e05bd70&gt;, {})}} (Pdb) max(foo, key=lambda x: foo[x]['extra_data']['budget']) *** NameError: global name 'foo' is not defined </code></pre> <p>All in all, I am trying to use <code>max(foo, key=lambda x: foo[x]['extra_data']['budget'])</code> to find the largest value for a nested key <code>budget</code> within an unknown number of first order keys. </p> <p>The expected result in this case could be <code>2</code> as the value for <code>foo['2']['extra_data']['budget'] = 3</code> vs. <code>foo['1']['extra_data']['budget'] = 0</code>.</p> <p>Could the error be related to the fact that some of the (unrelated) keys have <code>defaultdict</code>s within them?</p>
1
Unable to increase MySql open-files-limit
<p>I have modified <code>/etc/mysql/my.cnf</code> as follows</p> <pre><code>[mysqld] open-files-limit = 100000 [mysqld_safe] open-files-limit = 100000 </code></pre> <p>Still when login to mysql I am not seeing any change in this variable</p> <pre><code>mysql&gt; SHOW VARIABLES LIKE 'open%'; +------------------+-------+ | Variable_name | Value | +------------------+-------+ | open_files_limit | 1024 | +------------------+-------+ 1 row in set (0.00 sec) </code></pre> <p>I have first tried using open_files_limit but read somewhere that we need to replace underscore(_) with dash(-) in this variable</p> <p>I am using <strong><code>ubuntu 15.10</code></strong> Any help?</p> <hr> <p>I have tried following things too</p> <pre><code>http://duntuk.com/how-raise-ulimit-open-files-and-mysql-openfileslimit http://serverfault.com/questions/440878/changing-open-files-limit-in-mysql-5-5 </code></pre> <p>-------Also made change to following file</p> <pre><code>/etc/mysql/mysql.conf.d/mysqld.cnf # query_cache_limit = 1M query_cache_size = 16M open-files-limit = 15000 # </code></pre>
1
Most efficient way to compare two lists and delete the same
<p>I want to compare two lists and get the valid words into a new list.</p> <pre><code>var words = new List&lt;string&gt;(); var badWords = new List&lt;string&gt;(); //this is just an example list. actual list does contain 700 records words.Add("Apple"); words.Add("Moron"); words.Add("Seafood"); words.Add("Cars"); words.Add("Chicken"); words.Add("Twat"); words.Add("Watch"); words.Add("Android"); words.Add("c-sharp"); words.Add("Fool"); badWords.Add("Idiot"); badWords.Add("Retarded"); badWords.Add("Twat"); badWords.Add("Fool"); badWords.Add("Moron"); </code></pre> <p>I am looking for most efficient way to compare the lists and put all the 'good' words into a new list. The finalList shouldn't contain "Moron", "Twat" and "Fool".</p> <pre><code>var finalList = new List&lt;string&gt;(); </code></pre> <p>Or is it unnecessary to create a new List? I am happy to hear your ideas! </p> <p>Thank you in advance</p>
1
Get Output of a PowerShell Script in a HTA
<p>I am trying to call a powershell script from HTML Application [HTA] as :</p> <pre><code>Set WshShell = CreateObject("WScript.Shell") Set retVal = WshShell.Exec("powershell.exe C:\PS_Scripts\test.ps1") </code></pre> <p>Where the test.ps1 just has the process count returning</p> <pre><code>return (Get-Process).Count </code></pre> <p>I want to get the output of this powershell script and then store it in a local variable or display on HTA. How can this be done ?</p> <p>I tried using :</p> <pre><code>retVal.StdIn.Close() result = retVal.StdOut.ReadAll() alert(result) </code></pre> <p>But the printed result value is null.</p> <p>Please help me how to achieve this.</p>
1
sending row id when RecyclerView item clicked
<p>I have prepared a Database in my asset folder . I have one <code>recyclerView</code> for showing the title in the database . Now i want show <code>DetailActivity</code> with specific<code>id</code> . my means is show description of post . I think it can be done with intent , but i don't know how .</p> <pre><code> public class FehrestRecyclerAdapter extends RecyclerView.Adapter&lt;FehrestRecyclerAdapter.ViewHolder&gt; { private Context ctx; private List&lt;Post&gt; posts; //constructor public FehrestRecyclerAdapter(Context ctx, List&lt;Post&gt; posts) { this.ctx = ctx; this.posts= posts; } //ViewHodler Pattern public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ private TextView txtTitle; public ViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); txtTitle= (TextView)itemView.findViewById(R.id.txtTitle); } @Override public void onClick(View v) { //Toast.makeText(v.getContext() , txtTitle.getText() , Toast.LENGTH_SHORT).show(); Intent intent = new Intent(itemView.getContext() , DetailActivity.class); intent.putExtra("postId" , "id"); itemView.getContext().startActivity(intent); } } //OncreateViewHolder @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_row , parent , false); ViewHolder viewHolder = new ViewHolder(v); return viewHolder; } //OnBindViewHolder @Override public void onBindViewHolder(ViewHolder holder, int position) { Post current = Post.get(position); holder.txtTitle.setText(current.getTitle()); } //getItemCount method @Override public int getItemCount() { return posts.size(); } } </code></pre> <p>i have a 3 columns in my database </p> <blockquote> <p>1.id 2.title 3.desc</p> </blockquote> <p>and 3 methods in my Post model Class :</p> <blockquote> <ol> <li>getId() 2.getTitle() 3.getDesc()</li> </ol> </blockquote> <p>as you can see i can send intent to <code>DetailActivity</code> . But i don't know how can i achieve to sending specific id to <code>DetailActivity</code>. thanks</p>
1
CommandBinding WPF
<p>In my simple application I'm using <code>Command</code> and <code>CommandBinding</code>. My probem is that when I declare <code>Command</code> in my mainWindow like this :</p> <pre><code>&lt;RibbonWindow x:Class="BooksDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:BooksDemo" mc:Ignorable="d" Title="MainWindow" Height="400" Width="600"&gt; &lt;Window.CommandBindings&gt; &lt;CommandBinding Command="Close" Executed="OnClose" /&gt; &lt;CommandBinding Command="local:BooksCommands.ShowBooksList" /&gt; &lt;/Window.CommandBindings&gt; &lt;Ribbon DockPanel.Dock="Top"&gt; &lt;Ribbon.QuickAccessToolBar&gt; &lt;RibbonQuickAccessToolBar&gt; &lt;RibbonButton SmallImageSource="Images/one.png" Command="local:BooksCommands.ShowBook"/&gt; &lt;RibbonButton SmallImageSource="Images/list.png" Command="local:BooksCommands.ShowBooksList"/&gt; &lt;/RibbonQuickAccessToolBar&gt; &lt;/Ribbon.QuickAccessToolBar&gt; &lt;Ribbon.ApplicationMenu&gt; &lt;RibbonApplicationMenu SmallImageSource="Images/books.png" &gt; &lt;RibbonApplicationMenuItem Header="Show _Book" /&gt; &lt;RibbonSeparator /&gt; &lt;RibbonApplicationMenuItem Header="Exit" Command="Close" /&gt; &lt;/RibbonApplicationMenu&gt; &lt;/Ribbon.ApplicationMenu&gt; &lt;RibbonTab Header="Home"&gt; &lt;RibbonGroup Header="Clipboard"&gt; &lt;RibbonButton Command="Paste" Label="Paste" LargeImageSource="Images/paste.png" /&gt; &lt;RibbonButton Command="Cut" SmallImageSource="Images/cut.png" /&gt; &lt;RibbonButton Command="Copy" SmallImageSource="Images/copy.png" /&gt; &lt;RibbonButton Command="Undo" LargeImageSource="Images/undo.png" /&gt; &lt;/RibbonGroup&gt; &lt;RibbonGroup Header="Show"&gt; &lt;RibbonButton LargeImageSource="Images/one.png" Label="Book" /&gt; &lt;RibbonButton LargeImageSource="Images/list.png" Label="Book List" /&gt; &lt;RibbonButton LargeImageSource="Images/grid.png" Label="Book Grid" /&gt; &lt;/RibbonGroup&gt; &lt;/RibbonTab&gt; &lt;RibbonTab Header="Ribbon Controls"&gt; &lt;RibbonGroup Header="Sample"&gt; &lt;RibbonButton Label="Button" /&gt; &lt;RibbonCheckBox Label="Checkbox" /&gt; &lt;RibbonComboBox Label="Combo1"&gt; &lt;Label&gt;One&lt;/Label&gt; &lt;Label&gt;Two&lt;/Label&gt; &lt;/RibbonComboBox&gt; &lt;RibbonTextBox&gt;Text Box&lt;/RibbonTextBox&gt; &lt;RibbonSplitButton Label="Split Button"&gt; &lt;RibbonMenuItem Header="One" /&gt; &lt;RibbonMenuItem Header="Two" /&gt; &lt;/RibbonSplitButton&gt; &lt;RibbonComboBox Label="Combo2" IsEditable="False"&gt; &lt;RibbonGallery SelectedValuePath="Content" MaxColumnCount="1" SelectedValue="Green"&gt; &lt;RibbonGalleryCategory&gt; &lt;RibbonGalleryItem Content="Red" Foreground="Red" /&gt; &lt;RibbonGalleryItem Content="Green" Foreground="Green" /&gt; &lt;RibbonGalleryItem Content="Blue" Foreground="Blue" /&gt; &lt;/RibbonGalleryCategory&gt; &lt;/RibbonGallery&gt; &lt;/RibbonComboBox&gt; &lt;/RibbonGroup&gt; &lt;/RibbonTab&gt; &lt;ListBox DockPanel.Dock="Left" Margin="5" MinWidth="120"&gt; &lt;Hyperlink Click="OnShowBook"&gt;Show Book&lt;/Hyperlink&gt; &lt;/ListBox&gt; &lt;TabControl Margin="5" x:Name="tabControl1"&gt; &lt;/TabControl&gt; &lt;/Ribbon&gt; </code></pre> <p></p> <p>It's telling me that <code>BooksCommands</code> does not exist in the namespace.</p> <p>and in the class BooksCommands I declared the namespace:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace BooksDemo { class BooksCommands { private static RoutedUICommand showBook; public static ICommand ShowBook { get { return showBook ?? (showBook = new RoutedUICommand("Show Book", "ShowBook", typeof(BooksCommands))); } } private static RoutedUICommand showBooksList; public static ICommand ShowBooksList { get { if (showBooksList == null) { showBooksList = new RoutedUICommand("Show Books","ShowBooks", typeof(BooksCommands)); showBook.InputGestures.Add(new KeyGesture(Key.B,Modifierkeys. Alt)); } return showBooksList; } } } </code></pre> <p>And this is the MainWindow.xaml.cs:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Controls.Ribbon; namespace BooksDemo{ public partial class MainWindow : RibbonWindow { public MainWindow() { InitializeComponent(); } private void OnClose(object sender, ExecutedRoutedEventArgs e) { Application.Current.Shutdown(); } } } </code></pre> <p>Could someone help me please.</p>
1
Spring JPA Multiple Relations with same entity
<p>I have the following relation:</p> <p><a href="https://i.stack.imgur.com/DWsN8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DWsN8.png" alt="Relation database"></a></p> <p>I'm trying to map those relations using JPA in Spring Boot, but I'm having some trouble. These are the classes:</p> <p><strong>Person:</strong></p> <pre><code>public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // Relations @OneToOne @JoinColumn(name = "child_id") private PersonBirth birth; @OneToMany @JoinColumn(name = "mother_id") private List&lt;PersonBirth&gt; motherOf; @OneToMany @JoinColumn(name = "father_id") private List&lt;PersonBirth&gt; fatherOf; } </code></pre> <p><strong>PersonBirth:</strong></p> <pre><code>public class Birth { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "birth_date") @JsonProperty(value = "birth_date") private Long birthDate; // Relations @OneToOne @JoinColumn(name = "child_id") private Person child; @ManyToOne @JoinColumn(name = "mother_id") private Person mother; @ManyToOne @JoinColumn(name = "father_id") private Person father; } </code></pre> <p>I'm trying to be able to get a <code>Pearson</code> and his <code>Birth</code> data including his <code>mother</code> and <code>father</code>. And also be able so get a <code>Person</code> with its children mapped by <code>fatherOf</code> or <code>motherOf</code>. But the way it is right now, it throws stackoverflow when I fetch a <code>Person</code> who is a mother, because it gets the <code>Birth</code> data, that contains the <code>child</code> data (so far what I want), that contains his <code>Birth</code> data, that contains his mother, that contains her children (and so on). I don't know if what I'm trying to do is possible using this structure or if I'll have to change it... Any suggestions are appreciated.</p>
1
How to round QWidget corners
<p><a href="https://i.stack.imgur.com/2Nxpi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2Nxpi.png" alt="enter image description here"></a></p> <p>I wonder if there is there a way to round Qt widget corners?</p> <pre><code>from PyQt4 import QtCore, QtGui class Custom(QtGui.QWidget): def __init__(self, *args, **kwargs): QtGui.QWidget.__init__(self, *args, **kwargs) self.setWindowOpacity(0.9) self.setWindowFlags(QtCore.Qt.Popup|QtCore.Qt.FramelessWindowHint) self.setWindowTitle('Custom') self.resize(440,220) self.move(QtGui.QCursor.pos()) def closeEvent(self, event): event.accept() sys.exit(app.exec_()) def mousePressEvent(self, event): self.close() if __name__ == "__main__": app = QtGui.QApplication(sys.argv) w = Custom() w.show() sys.exit(app.exec_()) </code></pre>
1
How to get Class Metadata into JSON string
<p>How to generate JSON of Class meta data. </p> <p>for eg.</p> <p><strong>C# Classes</strong> </p> <pre><code>public class Product { public int Id { get; set; } public string Name { get; set; } public bool IsActive { get; set; } public Description Description { get; set; } } public class Description { public string Content { get; set; } public string ShortContent { get; set; } } </code></pre> <p><strong>JSON</strong></p> <pre><code>[ { "PropertyName" : "Id", "Type" : "Int", "IsPrimitive" : true }, { "PropertyName" : "Name", "Type" : "string", "IsPrimitive" : true }, { "PropertyName" : "IsActive", "Type" : "bool", "IsPrimitive" : true }, { "PropertyName" : "Description", "Type" : "Description", "IsPrimitive" : false "Properties" : { { "PropertyName" : "Content", "Type" : "string", "IsPrimitive" : true }, { "PropertyName" : "ShortContent", "Type" : "string", "IsPrimitive" : true } } }, ] </code></pre>
1
Commenting system with Ajax and Codeigniter
<p>I am implementing a commenting box with ajax and CodeIgniter.</p> <p>I want a script where a signed in user comments, and Ajax sends the <code>user_id</code> and the <code>post</code> to the controller, the comment is added to the MySQL database and the comment list is then refreshed. this code below is doing the functionality only i want it done using ajax. Here is part of my view scenery.php</p> <pre><code> &lt;?php $scenery_id=$scenery1['scenery_id']; echo form_open(('display_scenery/add_comment/'.$scenery_id)); ?&gt; &lt;div class="input-group" &gt;&lt;!-- input group starts--&gt; &lt;input type="text" class="form-control" id ="Comment" name ="Comment" placeholder="Comment on Scenery..." maxlength="300" size= "70" required&gt; &lt;input type ="hidden" name= "Scenery_id" value= " &lt;?php echo $scenery_id?&gt;" /&gt; &lt;button type="submit" id = "submit"class="btn btn-info regibutton" &gt;Post&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;hr/&gt; &lt;div id = "comment-box"&gt; &lt;?php if ($comment==NULL){ //if no scenery comment echo disclaimer echo " &lt;ul style = ' margin-left: 0px;padding-left: 0px;'&gt; &lt;li style = 'list-style: none; background-color: #fff; padding : 5px 5px 5px 10px; margin: 5px 5px 5px 5px'&gt;"; echo " No scenery Comments"; echo "&lt;/li&gt; &lt;/ul&gt;"; } else{ foreach ($comment as $row){ // if the comments are availabe echo them echo " &lt;ul style = ' margin-left: 0px;padding-left: 0px;'&gt; &lt;li style = 'list-style: none; background-color: #fff; padding : 10px 5px 5px 10px; margin: 5px 5px 5px 5px'&gt;"; echo $row-&gt;Comment; echo "&lt;br/&gt;"; echo "&lt;p style='font-size: 11px; color:#333; padding-top: 5px;'&gt;".date(" D d M Y - H:i:s ",strtotime($row-&gt;Date_posted))."By - ". $row-&gt;Username. " &lt;/p&gt;"; echo $row-&gt;Date_added; echo "&lt;/li&gt; &lt;/ul&gt;"; } } } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt; &lt;br&gt; </code></pre> <p>Here is my Controller display_scenery.php</p> <pre><code> public function add_comment(){ $this-&gt;load-&gt;library('form_validation'); $session_data = $this-&gt;session-&gt;userdata('logged_in'); $User_id= $session_data['User_id']; $scenery_id = $_POST['Scenery_id']; $Comment=$_POST['Comment']; $this-&gt;form_validation-&gt;set_rules('Comment', 'Comment', 'trim|required'); if($this-&gt;form_validation-&gt;run() == FALSE) { ///$error= form_error('Comment'); $this-&gt; session-&gt;set_flashdata('error', form_error('Comment')); redirect ('scenery', 'refresh'); } else { //loads the model image_display then redirects to scenery page $this-&gt; image_display-&gt;add_comment( $scenery_id, $Comment,$User); redirect ('scenery', 'refresh'); } } </code></pre>
1
C# Encoding from utf-16 to ascii
<p>I get question marks in output of my program: ?????? ??????</p> <pre><code> string str = "Привет медвед"; Encoding srcEncodingFormat = Encoding.GetEncoding("utf-16"); Encoding dstEncodingFormat = Encoding.ASCII; byte [] originalByteString = srcEncodingFormat.GetBytes(str); byte [] convertedByteString = Encoding.Convert(srcEncodingFormat, dstEncodingFormat, originalByteString); string finalString = dstEncodingFormat.GetString(convertedByteString); Console.WriteLine (finalString); </code></pre>
1
Python Tkinter Clickable Text?
<p>I'm wondering if there's a way to make clickable text in Tkinter. Maybe like you would see on a title screen of a game, and where you hover your mouse over the text and it changes color/hightlights itself. All I need the click to do is execute another function. </p> <p>Are either of these things possible? Thanks! </p>
1
linking succeeds with arm-none-eabi-g++ but not arm-none-eabi-gcc
<p>I am using the Launchpad Arm compiler tools. Specifically, </p> <p>arm-none-eabi-g++ and arm-none-eabi-gcc from:</p> <p>(GNU Tools for ARM Embedded Processors) 5.2.1 20151202 (release) [ARM/embedded-5-branch revision 231848]</p> <p>I have a simple program targeted at an STM32F103 processor that has no purpose except to prove that I can write the hardware and call a function from the math library. This is all it is:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include "stm32f10x.h" void hardwareTest(void){ // Turn on the clock for PortB RCC-&gt;APB2ENR = RCC_APB2ENR_IOPBEN; // Turn on IO Port B // Put PB0 into push pull 50 MHz mode GPIOB-&gt;CRL = 0x03; // Turn PB0 on GPIOB-&gt;ODR = 1; } volatile int x; // force call to sqrt() later int main(void) { x = sqrt(100.0f); x = sqrt(x); hardwareTest(); return (x); } </code></pre> <p>When I tried to build this, I got a linker error telling me that there is an undefined reference to sqrt. The build was done with arm-none-eabi-gcc. By chance I discovered that, if the build is done with arm-none-eabi-g++, using the same command line arguments, the linking is performed successfully.</p> <p>I wrote a Makefile to demonstrate the difference:</p> <pre><code>PROJECT = minimal SOURCES = src/startup_stm32f10x_hd.s \ src/system_stm32f10x.c \ src/main.c OUTPUT = ./out print-%: @echo '$*=$($*)' TOOLCHAIN = arm-none-eabi- CXX = $(TOOLCHAIN)g++ CC = $(TOOLCHAIN)gcc AR = $(TOOLCHAIN)ar AS = $(TOOLCHAIN)gcc -c -x assembler-with-cpp LD = $(TOOLCHAIN)gcc OBJCOPY = $(TOOLCHAIN)objcopy OBJDUMP = $(TOOLCHAIN)objdump SIZE = $(TOOLCHAIN)size RM = rm -f CFLAGS = -O CFLAGS += -nostartfiles CXXFLAGS = -O CXXFLAGS += -nostartfiles ARCH = -mcpu=cortex-m3 -mthumb -DSTM32F10X_HD LDFLAGS = all: clean $(PROJECT).elf $(PROJECT).gcc $(PROJECT).bin $(PROJECT).bin: $(PROJECT).elf @echo ' ======== ' @echo ' Generating binaries' $(OBJCOPY) -O binary $(OUTPUT)/$&lt; $(OUTPUT)/$(PROJECT).bin $(OBJCOPY) -O ihex $(OUTPUT)/$&lt; $(OUTPUT)/$(PROJECT).hex @echo ' ======== ' $(PROJECT).elf: $(SOURCES) @echo ' ======== ' @echo ' Successful build uses g++' @echo ' CXXFLAGS = $(CXXFLAGS)' @echo ' LDFLAGS = $(LDFLAGS)' @echo ' ARCH = $(ARCH)' $(CXX) -o $(OUTPUT)/$@ $(ARCH) $(CXXFLAGS) $(LDFLAGS) -Wl,-Tld_script/stm32.ld,-lm $^ @echo ' ======== ' $(PROJECT).gcc: $(SOURCES) @echo ' ======== ' @echo ' Broken build uses gcc' @echo ' CFLAGS = $(CFLAGS)' @echo ' LDFLAGS = $(LDFLAGS)' @echo ' ARCH = $(ARCH)' $(CC) -o $(OUTPUT)/$@ $(ARCH) $(CFLAGS) $(LDFLAGS) -Wl,-Tld_script/stm32.ld,-lm $^ @echo ' ======== ' $(PROJECT).gxx: $(SOURCES) @echo ' ======== ' @echo ' build with g++' $(CXX) -o $(OUTPUT)/$@ $(ARCH) $(CXXFLAGS) $(LDFLAGS) -Wl,-Tld_script/stm32.ld $^ @echo ' ======== ' # Program the binary to the board using the builtin serial bootloader program: stm32loader.py -p /dev/ttyUSB0 -ewv $(OUTPUT)/$(PROJECT).bin # Remove the temporary files clean: @echo ' ' @echo ' Cleaning up: ' $(RM) $(OUTPUT)/* *.o *.elf *.bin *.hex *.gcc *.gxx *.g++ @echo ' ======== ' </code></pre> <p>It give the following results:</p> <pre><code>Cleaning up: rm -f ./out/* *.o *.elf *.bin *.hex *.gcc *.gxx *.g++ ======== ======== Successful build uses g++ CXXFLAGS = -O -nostartfiles LDFLAGS = ARCH = -mcpu=cortex-m3 -mthumb -DSTM32F10X_HD arm-none-eabi-g++ -o ./out/minimal.elf -mcpu=cortex-m3 -mthumb -DSTM32F10X_HD -O -nostartfiles -Wl,-Tld_script/stm32.ld,-lm src/startup_stm32f10x_hd.s src/system_stm32f10x.c src/main.c ======== ======== Broken build uses gcc CFLAGS = -O -nostartfiles LDFLAGS = ARCH = -mcpu=cortex-m3 -mthumb -DSTM32F10X_HD arm-none-eabi-gcc -o ./out/minimal.gcc -mcpu=cortex-m3 -mthumb -DSTM32F10X_HD -O -nostartfiles -Wl,-Tld_script/stm32.ld,-lm src/startup_stm32f10x_hd.s src/system_stm32f10x.c src/main.c /var/folders/t4/dv7b46055cjgknp4nndn1_zr0000gn/T//ccbl4swG.o: In function `main': main.c:(.text+0x28): undefined reference to `sqrt' collect2: error: ld returned 1 exit status make: *** [minimal.gcc] Error 1 ======== Generating binaries arm-none-eabi-objcopy -O binary ./out/minimal.elf ./out/minimal.bin arm-none-eabi-objcopy -O ihex ./out/minimal.elf ./out/minimal.hex make: Target `all' not remade because of errors. </code></pre> <p>So can anyone tell me why the two compilers behave differently? What simple thing have I overlooked? How should I ensure proper linking with libm and others if I want to use arm-none-eabi-gcc?</p> <p>I have looked at Freddie Chopin's makefiles but they are too complicated for me to unravel.</p>
1
Batch file replace line in text file with new line
<p>I want to be able to replace a line in a properties file but i only know part of the line string at any one time</p> <p>Heres the line i want to replace: <code>mb.datasource.password=ENC(8dF45fdD)</code></p> <p>with this: <code>mb.datasource.password=apassword</code></p> <p>What i have just now is this</p> <pre><code>@echo off &amp;setlocal set "search=mb.datasource.password=" set "replace=mb.datasource.password=apassword" set "textfile=mb.properties" set "newfile=mb-new.properties" (for /f "delims=" %%i in (%textfile%) do ( set "line=%%i" setlocal enabledelayedexpansion set "line=!line:%search%=%replace%!" echo(!line! endlocal ))&gt;"%newfile%" </code></pre> <p>This ends up giving me mb.datasource.password=apassword=ENC(8fFdeUdK)</p> <p>I can't just find the full string it needs to only be mb.datasource.password= because the part after the equals changes</p> <p>Any help would be greatly appreciated?</p>
1
Get value of radio Button codeigniter
<p>I am trying to get the value from a radio button. I have two radio buttons 1 and 2 each having different values. When i print_r on the controller, the value is always of the second radio button even if i select the first radio button <strong>View</strong></p> <pre><code>&lt;input class="payment_method_icon" type="radio" value= "1" name="mode" checked="checked"&gt; &lt;input class="payment_method_icon" type="radio" value="2" name="mode"&gt; </code></pre> <p><strong>Controller</strong></p> <pre><code>print_r($this-&gt;input-&gt;post()); </code></pre> <p>How do i get the correct value of the radio button</p>
1
ASP.Net Identity Force Logout From SQL
<p>I'm using the ASPNET Identity tables for my MVC 5 application. Each night we perform "maintenance" on our database. If we modify something under that user, I want to inactivate their current session so that the next action they perform in the web application will kick them back to the login screen. The authentication/authorization already is built into my application using AspNet.Identity. I just need a way to wake it up by setting a flag if it exists.</p> <p>For example the ASPNETUsers table has an "Inactive" column, but that's too permanent. I'm looking for the "ThisGuyIsLoggedIn" column.</p> <p>This was close to the same problem, but the answer was to manage it from within MVC, which is not an option.</p> <p><a href="https://stackoverflow.com/questions/10369225/forcefully-log-out-a-specific-user-among-all-online-users">forcefully log out a specific user among all online users</a></p>
1
Writing a regex to validate username in Ruby
<p>I'm stuck trying to figure out how to make this method work. </p> <p>I want to return true if the username is made up of lowercase characters, numbers, and underscores, and is between 4 and 16 characters in length, otherwise return false.</p> <pre><code>def validate_usr(username) if username == /A[a-z0-9_]{4,16}Z/ return true else return false end end </code></pre> <p>I don't know what I'm doing wrong.</p>
1
Autocomplete Textbox in C# and MVC
<p>Hi to all and thanks for your help,</p> <p>I need to autocomplete a textbox with suggestions in C# and MVC.</p> <p>The textbox in the view is:</p> <pre><code>&lt;div class="col-lg-3 col-md-3 hidden-sm hidden-xs" style="margin-top:2%;"&gt; &lt;input type="text" class="formLocator" value="Milano" data-date-end-date="0d" id="textLocator" name="searchstring"&gt; &lt;h4 class="FormTextLocator"&gt;Where&lt;/h4&gt; &lt;/div&gt; &lt;div class="hidden-lg hidden-md col-sm-3 col-xs-12" style="margin-top:2%;"&gt; &lt;input type="text" class="formLocator" value="Milano" data-date-end-date="0d" id="textLocator" name="searchstring"&gt; &lt;h4 class="FormTextLocator"&gt;Where&lt;/h4&gt; &lt;/div&gt; </code></pre> <p>I have created a javascript code for this textbox:</p> <pre><code>$(function () { $("#textLocator").autocomplete( { source: "/Home/AutocompleteSuggestions", minLength: 1, select: function (event, ui) { if (ui.item) { $("#textLocator").val(ui.item.value); $("form").submit(); } } }); }); </code></pre> <p>And the controller associated is: </p> <pre><code> public JsonResult AutocompleteSuggestions(string searchstring) { var db = new TocFruit(); var suggestions = from s in db.city select s.name; var namelist = suggestions.Where(n =&gt; n.ToString().StartsWith(searchstring.ToLower())); return Json(namelist, JsonRequestBehavior.AllowGet); } </code></pre> <p>But all of this doesn't work but i don't understand what I'm doing wrong.</p> <p>Thanks to all,</p> <p>Roberto</p>
1
Add and remove target actions for UIButton in UITableViewCell
<p>What is the best way Add and remove target actions for UIButton in UITableViewCell.</p> <p>For each row of the I will have different button action based on the row index. Show please tell me where do I add the add target for button and remove target for the button.</p> <p>I am asking about the delegate and data source to be used.</p>
1