id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
16,465,454
How do I scroll to the right on a page that overflows horizontally?
<p>I want to scroll to the far right edge of a page that is really wide (it's wide on purpose) when the user closes a modal (specifically, the Reveal modal in Foundation 4).</p> <p>I've tried setting an id on a div that's aligned all the way right, but that obviously doesn't work.</p>
16,465,556
3
1
null
2013-05-09 15:28:43.23 UTC
2
2013-08-12 22:45:35.59 UTC
null
null
null
null
1,475,082
null
1
17
javascript|jquery
44,806
<p>To scroll horizontally, you use <a href="http://api.jquery.com/scrollLeft/" rel="noreferrer">scrollLeft()</a>.</p> <pre><code>$('body, html').scrollLeft(400); </code></pre> <p>jQuery also supports animating the <code>scrollLeft</code> property.</p> <p>To scroll all the way to the right, you get the full width of the page, and subtract the window width to get the left edge :</p> <pre><code>var left = $(document).outerWidth() - $(window).width(); $('body, html').scrollLeft(left); </code></pre>
16,110,528
Tomcat multiple instances simultaneously
<p>I am trying to run multiple instances of Tomcat, but even after configuring different ports for listening and shutting down the second instance, it keeps trying to listen on 8080 (configured for 8081). I read that I have to set a different value for <code>CATALINA_BASE</code>. From all the articles there are online, none of them actually show in which file this variable can be set.</p> <p>Where and how can I set CATALINA_BASE for my Tomcat instance in <code>C:\apache-tomcat-7.0.39</code></p>
16,110,675
5
4
null
2013-04-19 17:43:06.74 UTC
24
2018-04-10 12:25:47.91 UTC
2013-12-12 16:16:21.013 UTC
null
1,098,211
null
2,014,549
null
1
29
windows|tomcat|multiple-instances|catalina
52,262
<p>The easiest way I have run two copies of Tomcat involved the following steps (I was trying to run two distinct versions of tomcat, 6 and 7):</p> <ul> <li><p>Establish 2 copies of tomcat in different folders (if they are different versions then this is easy, if they are the same version then you will need be distinguished in some other way. There are a lot of files that Tomcat creates to manage it so running two instances with the same work directory likely isn't possible)</p></li> <li><p>Change the following ports that tomcat is listening to in <code>server.xml</code></p> <ul> <li><code>&lt;Connector port="8080"&gt;</code> &lt;- This is the port that tomcat uses to respond to HTTP requests</li> <li><code>&lt;Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /&gt;</code> &lt;- this defines two ports, one for the AJP connector (used if you are using tomcat behind an Apache or IIS server) and the port used for HTTPS traffic</li> <li><code>&lt;Server port="8005" shutdown="SHUTDOWN"&gt;</code> &lt;- this is the port that Tomcat uses to respond to SHUTDOWN events</li> </ul></li> </ul> <p>Finally, if you are running this as a Windows service you will need to establish different service names for each instance (you can do this during setup, the default for Tomcat 7 is tomcat7). Once Tomcat is running all of it's configuration fields use relative paths so you don't need to touch <code>CATALINA_BASE</code></p>
16,267,903
Changing minDate and maxDate on the fly using jQuery DatePicker
<p>I'm having a particular issue with the jQuery Datepicker. I can easily add a date range, but I want the selectable range to change depending on the event the user has picked.</p> <p>So if they pick event #1, they can only pick dates from event #1's date range.</p> <p>I've written a simple little function that gets called whenever the user selects a new event, but it only ever shows the initially set minDate/maxDate values.</p> <pre><code>function datepicker(startDate, endDate) { $( "#date" ).datepicker({ inline: true, minDate: new Date(startDate), maxDate: new Date(endDate), dateFormat: 'dd/mm/yy' }); } </code></pre> <p>I've tried calling <code>$('#date').datepicker('remove');</code> before calling the above function again, to see if it creates a new instance with the correct dates, but it doesn't seem to work.</p> <p>I've checked all the data through developer tools and everything is being called and passed correctly. Is there anything I can do to make this work how I want it to?</p>
16,267,968
5
2
null
2013-04-28 21:08:11.76 UTC
7
2019-02-20 06:27:27.673 UTC
2018-11-05 10:21:29.653 UTC
null
608,639
null
199,700
null
1
31
jquery|jquery-ui|datepicker
114,378
<p>You have a couple of options...</p> <p>1) You need to call the <code>destroy()</code> method not <code>remove()</code> so...</p> <pre><code>$('#date').datepicker('destroy'); </code></pre> <p>Then call your method to recreate the <code>datepicker</code> object.</p> <p>2) You can update the property of the existing <code>object</code> via</p> <pre><code>$('#date').datepicker('option', 'minDate', new Date(startDate)); $('#date').datepicker('option', 'maxDate', new Date(endDate)); </code></pre> <p>or...</p> <pre><code>$('#date').datepicker('option', { minDate: new Date(startDate), maxDate: new Date(endDate) }); </code></pre>
16,059,771
Reverse Apply a commit to working copy
<p>In order to investigate the effect introduced by a previous commit, I want to reverse- apply it to my working copy and fiddle around with the code. </p> <p>I managed with a workflow around creating and applying a patch, but wonder if this can be done easier.</p> <pre><code>git checkout -b "tmp-fiddle" git diff -R -p d9fd2bb^ d9fd2bb &gt; patch_to_examine.patch # Manually edit the patch a little git apply patch_to_examine.patch </code></pre> <p>Note that I am not looking at <code>git revert</code> or <code>git rebase -i</code> since these would either introduce a new commit or change the history: I merely want the changes introduced in <code>d9fd2bb</code> to be un-applied to my current working copy.</p>
16,059,902
3
2
null
2013-04-17 12:16:52.557 UTC
8
2021-10-30 19:26:07.99 UTC
null
null
null
null
73,673
null
1
46
git|revert
12,914
<p>How about <a href="https://www.kernel.org/pub/software/scm/git/docs/git-revert.html" rel="noreferrer"><code>git revert -n</code></a>?</p> <blockquote> <pre><code>-n --no-commit </code></pre> <p>Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.</p> <p>This is useful when reverting more than one commits' effect to your index in a row.</p> </blockquote>
15,169,418
how can I get sessions to work using redis, express & socket.io?
<p>So I am trying to get Sessions to work inside my socket.on('connection', ...) I am trying to get this working using recent versions: Socket.io - 0.9.13, Express - 3.1.0 and latest versions of other modules.</p> <p>Anyway I have tried using both modules '<a href="https://npmjs.org/package/connect-redis" rel="noreferrer">connect-redis</a>' and '<a href="https://npmjs.org/package/session.socket.io" rel="noreferrer">session.socket.io</a>' and they both have similar problems.</p> <p>In my code I have 2 redis stores (socketio.RedisStore and require('connect-redis')(express)), now this program all runs fine, but because express and socket.io need to share session data, I was wondering if this setup will use sessions correctly? do the session stores need to be the same object for express/socketio? A bit of a gray area to me, because the 2 RedisStore's will use the same db in the background?</p> <p>I have tried using either the socket.io redisStore or the connect-redis redisStore in both places, but socket.io doesnt like the connect-redis redisStore and express doesnt like the socketio.redisStore.</p> <p>If I use the connect-redis RedisStore then socket.io/lib/manager.js complains: this.store.subscribe(... TypeError Object # has no method 'subscribe'</p> <p>If I use socketio.RedisStore then express/node_modules/connect/lib/middleware/session.js complains: TypeError: Object # has no method 'get'</p> <p>*Note I would rather get the session.socket.io plugin working, but when I do the same setup with that plugin, express (also) complains: TypeError: Object # has no method 'get'</p> <p>So is it ok that I use 2 different RedisStores for sessions, or do I need to somehow get one or the other working for both, and if so any ideas on how to fix?</p> <p>My current code looks like this:</p> <pre><code>var CONST = { port: 80, sessionKey: 'your secret sauce' }; var redis = require('redis'); var express = require('express'), socketio = require('socket.io'), RedisStore = require('connect-redis')(express); var redisStore = new RedisStore(), socketStore = new socketio.RedisStore(); var app = express(), server = require('http').createServer(app), io = socketio.listen(server); app.configure(function(){ app.use(express.cookieParser( CONST.sessionKey )); app.use(express.session({ secret: CONST.sessionKey, store: redisStore })); app.use(express.static(__dirname + '/test')); app.get('/', function (req, res) {res.sendfile(__dirname + '/test/' + 'index.htm');}); }); io.configure(function(){ io.set('log level', 1); io.enable('browser client minification'); io.enable('browser client etag'); io.enable('browser client gzip'); io.set('store', socketStore); }); io.sockets.on('connection', function(socket){ socket.emit('message', 'Test 1 from server') }); server.listen( CONST.port ); console.log('running...'); </code></pre>
15,169,642
2
0
null
2013-03-02 00:58:32.333 UTC
9
2013-11-16 03:46:20.28 UTC
2013-03-02 01:29:45.223 UTC
null
685,404
null
685,404
null
1
9
session|express|redis|socket.io|node-redis
4,965
<p>inside the <code>io.configure</code>, you have to link the socket with the http session.</p> <p>Here's a piece of code that extracts the cookie (This is using socket.io with <code>xhr-polling</code>, I don't know if this would work for websocket, although I suspect it would work).</p> <pre><code>var cookie = require('cookie'); var connect = require('connect'); var sessionStore = new RedisStore({ client: redis // the redis client }); socketio.set('authorization', function(data, cb) { if (data.headers.cookie) { var sessionCookie = cookie.parse(data.headers.cookie); var sessionID = connect.utils.parseSignedCookie(sessionCookie['connect.sid'], secret); sessionStore.get(sessionID, function(err, session) { if (err || !session) { cb('Error', false); } else { data.session = session; data.sessionID = sessionID; cb(null, true); } }); } else { cb('No cookie', false); } }); </code></pre> <p>Then you can access the session using:</p> <pre><code>socket.on("selector", function(data, reply) { var session = this.handshake.session; ... } </code></pre> <p>This also has the added benefit that it checks there is a valid session, so only your logged in users can use sockets. You can use a different logic, though.</p>
24,475,917
Swift - Create data model from JSON response
<p>I'm learning Swift lang and one of the things that would be great to hear others input about is "How you handle models from JSON responses"? For example -</p> <p>I have <code>User.swift</code> model:</p> <pre><code>class User: NSObject { var user_token:String? var email:String? } </code></pre> <p>and also I would like to use <a href="https://github.com/dchohfi/KeyValueObjectMapping" rel="noreferrer">KeyValueObjectMapping</a> as I do in Obj-C projects. Unfortunately this doesn't work here:</p> <pre><code>let parser = DCKeyValueObjectMapping.mapperForClass(User) let user = parser.parseDictionary(data.objectForKey("user") as NSDictionary) as User println(user.user_token) // returns nil </code></pre> <p>How do you create your models in Swift?</p>
31,843,191
6
5
null
2014-06-29 12:05:54.757 UTC
8
2019-09-13 20:08:09.057 UTC
2014-06-29 12:28:17.687 UTC
null
727,208
null
2,117,550
null
1
12
json|swift|key-value
19,876
<p>I recommend using code generation to generate models in Swift based on JSON. To that end, I've created a tool at <a href="http://www.guideluxe.com/JsonToSwift">http://www.guideluxe.com/JsonToSwift</a> to make modeling and parsing JSON as easy as possible.</p> <p>After you've submited a sample JSON object with a class name to the tool, it will generate a corresponding Swift class, as well as any needed subsidiary Swift classes, to represent the structure implied by the sample JSON. Also included are class methods used to populate Swift objects, including one that utilizes the NSJSONSerialization.JSONObjectWithData method. The necessary mappings from the NSArray and NSDictionary objects are provided.</p> <p>After copying the generated code into your project as a Swift class(es), you only need to supply an NSData object containing JSON that matches the sample provided to the tool.</p> <p>Other than Foundation, there are no dependencies.</p> <p>Here's how to create an NSData object from a JSON file to test with.</p> <pre><code>let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")! let jsonData: NSData = NSData(contentsOfURL: fileUrl)! </code></pre>
37,276,637
RDP session is slow
<p>So I am connecting to my work computer from home and the Remote Desktop Connection app is annoyingly slow.</p> <p>I pinged my work pc from my computer and it returned at a reasonable time of 50ms~ with 0 loss. I then attempted to ping my home IP from the RDP session and it timed out every time. Not sure if this might help anyone come to a conclusion but hopefully it does. Note I am also using it in conjunction with <strong>Cisco AnyConnect Secure Mobility Client</strong> if that helps at all. <em>Work is Windows 7</em> and <em>Home is Windows 8</em></p> <p>I attempted switching off my home pc's firewall but that did nothing.</p> <p>Any assistance would be great, surely a setting in the RDP file might make it run a little smoother.</p> <p>I'll edit this post with further attempts at fixes below</p>
45,227,464
4
3
null
2016-05-17 12:45:33.973 UTC
12
2021-03-09 22:01:50.873 UTC
null
null
null
null
2,495,847
null
1
26
rdp|remote-connection|remote-client
113,765
<p>Did three things and now RDP is running screaming fast:</p> <ol> <li>Change RDP settings:</li> </ol> <p><a href="https://i.stack.imgur.com/P0WJ1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/P0WJ1.png" alt="enter image description here"></a></p> <ol start="2"> <li><p>Run the RDP session and connect to the remote machine</p></li> <li><p>Find <strong>mstcsc.exe</strong> in the Task Manager and and set priority to <strong>Realtime</strong></p></li> </ol> <p><a href="https://i.stack.imgur.com/bw3Yx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bw3Yx.png" alt="enter image description here"></a></p>
26,988,071
Allow multiple CORS domain in express js
<p>How do I allow multiple domains for CORS in express in a simplified way.</p> <p>I have</p> <pre><code> cors: { origin: "www.one.com"; } app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", cors.origin); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); </code></pre> <p>This works when there is only one domain mentioned in <code>origin</code></p> <p>But if I want to have <code>origin</code> as an array of domains and I want to allow CORS for all the domains in the origin array, I would have something like this - </p> <pre><code>cors: { origin: ["www.one.com","www.two.com","www.three.com"]; } </code></pre> <p>But then the problem is this below code would not work - </p> <pre><code>app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", cors.origin); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); </code></pre> <p>How do I make <code>res.header</code> take an array of domains via <code>cors.origin</code> ?</p>
26,988,252
6
7
null
2014-11-18 06:34:31.79 UTC
6
2022-04-17 07:52:31.613 UTC
null
null
null
null
2,098,614
null
1
33
javascript|node.js|express|cors
61,813
<p>I would recommend the cors-module: <a href="https://www.npmjs.org/package/cors" rel="noreferrer">https://www.npmjs.org/package/cors</a> It does this kind of stuff for you - check the "<a href="https://www.npmjs.com/package/cors#configuring-cors-w-dynamic-origin" rel="noreferrer">Configuring CORS w/ Dynamic Origin</a>"-Section</p>
17,208,254
How to Change Pixel Color of an Image in C#.NET
<p>I am working with Images in Java, I have designed more over 100+ images(.png) format, They were all Trasparent and Black Color Drawing.</p> <p>The problem is, Now I have been asked to change the color of the Drawing (Black -to ).</p> <p>I have searched many code snipped at google,that changes the Bitmap (pixels) of the Image, but i am not guessing what i have to do to match the exact pixel and replace specially when the images if in Transparent mode. Below is the code in .Net (C#) </p> <pre><code> Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height); for (int i = 0; i &lt; scrBitmap.Width; i++) { for (int j = 0; j &lt; scrBitmap.Height; j++) { originalColor = scrBitmap.GetPixel(i, j); if(originalColor = Color.Black) newBitmap.SetPixel(i, j, Color.Red); } } return newBitmap; </code></pre> <p>but it was not matching at all, I debugged it, throughout the file, there was no value of Red,Green,Blue parameters of Color (originalColor) variable.</p> <p>Anybody can help?</p>
17,209,284
4
0
null
2013-06-20 07:58:44.403 UTC
8
2015-12-30 08:34:06.183 UTC
2013-06-20 09:34:54.063 UTC
null
1,079,945
null
1,079,945
null
1
21
c#|.net|drawing|pixels|bitmapimage
64,264
<p>Here is the Solution I have done with Pixels.</p> <p>Attaching the source code so one can try the exact and get the result.</p> <p>I have sample images of 128x128 (Width x Height).</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.IO; //using System.Globalization; namespace colorchange { class Program { static void Main(string[] args) { try { Bitmap bmp = null; //The Source Directory in debug\bin\Big\ string[] files = Directory.GetFiles("Big\\"); foreach (string filename in files) { bmp = (Bitmap)Image.FromFile(filename); bmp = ChangeColor(bmp); string[] spliter = filename.Split('\\'); //Destination Directory debug\bin\BigGreen\ bmp.Save("BigGreen\\" + spliter[1]); } } catch (System.Exception ex) { Console.WriteLine(ex.ToString()); } } public static Bitmap ChangeColor(Bitmap scrBitmap) { //You can change your new color here. Red,Green,LawnGreen any.. Color newColor = Color.Red; Color actualColor; //make an empty bitmap the same size as scrBitmap Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height); for (int i = 0; i &lt; scrBitmap.Width; i++) { for (int j = 0; j &lt; scrBitmap.Height; j++) { //get the pixel from the scrBitmap image actualColor = scrBitmap.GetPixel(i, j); // &gt; 150 because.. Images edges can be of low pixel colr. if we set all pixel color to new then there will be no smoothness left. if (actualColor.A &gt; 150) newBitmap.SetPixel(i, j, newColor); else newBitmap.SetPixel(i, j, actualColor); } } return newBitmap; } } } </code></pre> <p>//Below is the sample image and different results by applying different color <img src="https://i.stack.imgur.com/s3hWj.png" alt="enter image description here"></p> <p>Code modifications will be highly appreciated.</p>
17,507,525
Putting three.js animation inside of div
<p>This is three.js animation code example:</p> <pre><code>&lt;script defer="defer"&gt; var angularSpeed = 0.2; var lastTime = 0; function animate(){ var time = (new Date()).getTime(); var timeDiff = time - lastTime; var angleChange = angularSpeed * timeDiff * 2 * Math.PI / 1000; plane.rotation.z += angleChange; lastTime = time; renderer.render(scene, camera); requestAnimationFrame(function(){ animate(); }); } var renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000); camera.position.y = -450; camera.position.z = 400; camera.rotation.x = 45 * (Math.PI / 180); var scene = new THREE.Scene(); var plane = new THREE.Mesh(new THREE.PlaneGeometry(300, 300), new THREE.MeshNormalMaterial()); plane.overdraw = true; scene.add(plane); animate(); &lt;/script&gt; </code></pre> <p>I would like to bind this animation code to some specific div via div id. So, animation would be displayed inside of div. That would allow me to easily manipulate animation location with css. I was having in mind something like this:</p> <p>html:</p> <pre><code>&lt;canvas id="myCanvas" width="578" height="200"&gt;&lt;/canvas&gt; </code></pre> <p>javascript: </p> <pre><code>var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // do stuff here </code></pre> <p>But I haven't found a way to do something like this with three.js. As you can see in code example, there is no canvas element that I can refer to. Any ideas?</p>
17,507,839
3
0
null
2013-07-06 22:01:54.18 UTC
8
2022-08-28 17:54:18.257 UTC
2013-07-06 22:08:25.763 UTC
null
1,226,513
null
1,226,513
null
1
24
html5-canvas|three.js
39,121
<p>You can use a pattern like the following:</p> <pre><code>&lt;div id=&quot;canvas&quot;&gt; #canvas { background-color: #000; width: 200px; height: 200px; border: 1px solid black; margin: 100px; padding: 0px; position: static; /* fixed or static */ top: 100px; left: 100px; } container = document.getElementById( 'canvas' ); document.body.appendChild( container ); renderer = new THREE.WebGLRenderer(); renderer.setSize( 200, 200 ); container.appendChild( renderer.domElement ); </code></pre> <p>Fiddle: <a href="https://jsfiddle.net/v63Lnsd9/" rel="nofollow noreferrer">https://jsfiddle.net/v63Lnsd9/</a></p> <p>Also see <a href="https://stackoverflow.com/questions/13542175/three-js-ray-intersect-fails-by-adding-div/13544277#13544277">THREE.js Ray Intersect fails by adding div</a></p> <p>three.js r.143</p>
17,435,861
Kendo UI Datepicker disable typing
<p>I want users to be able to change a Kendo UI Datepicker value only through its button and selecting the date from the pop-up. How can I prevent users from typing in the Datepicker textbox? Can I disable the textbox without disabling the whole control?</p>
18,835,696
11
0
null
2013-07-02 21:05:42.16 UTC
6
2021-10-08 06:08:15.437 UTC
2013-07-03 07:07:40.187 UTC
null
2,759,625
null
966,572
null
1
37
javascript|html|kendo-ui
42,725
<p>On your input element add this attribute and value... </p> <pre><code>onkeydown="return false;" </code></pre> <p>This will disable typed input and still allow using the calendar control input. </p>
18,626,544
Devise "Confirmation token is invalid" when user signs up
<p>Using Rails 4 and Devise 3.1.0 on my web app. I wrote a Cucumber test to test user sign up; it fails when the "confirm my account" link is clicked from the e-mail.</p> <pre><code>Scenario: User signs up with valid data # features/users/sign_up.feature:9 When I sign up with valid user data # features/step_definitions/user_steps.rb:87 Then I should receive an email # features/step_definitions/email_steps.rb:51 When I open the email # features/step_definitions/email_steps.rb:76 Then I should see the email delivered from "[email protected]" # features/step_definitions/email_steps.rb:116 And I should see "You can confirm your account email through the link below:" in the email body # features/step_definitions/email_steps.rb:108 When I follow "Confirm my account" in the email # features/step_definitions/email_steps.rb:178 Then I should be signed in # features/step_definitions/user_steps.rb:142 expected to find text "Logout" in "...Confirmation token is invalid..." (RSpec::Expectations::ExpectationNotMetError) ./features/step_definitions/user_steps.rb:143:in `/^I should be signed in$ </code></pre> <p>This error is reproducible when I sign up manually through the web server as well, so it doesn't appear to be a Cucumber issue.</p> <p>I would like:</p> <ul> <li>The user to be able to one-click confirm their account through this e-mail's link</li> <li>Have the user stay signed in after confirming their account</li> </ul> <p>I have setup:</p> <ul> <li>The latest Devise code, from GitHub (3.1.0, ref 041fcf90807df5efded5fdcd53ced80544e7430f)</li> <li>A <code>User</code> class that implements <code>confirmable</code></li> <li>Using the 'default' confirmation controller (I have not defined my own custom one.)</li> </ul> <p>I have read these posts:</p> <ul> <li><a href="https://stackoverflow.com/questions/18390080/devise-confirmation-token-is-invalid">Devise confirmation_token is invalid</a></li> <li><a href="http://blog.plataformatec.com.br/2013/08/devise-3-1-now-with-more-secure-defaults/" rel="nofollow noreferrer">Devise 3.1: Now with more secure defaults</a></li> <li><a href="https://github.com/plataformatec/devise/issues/2587" rel="nofollow noreferrer">GitHub Issue - Devise confirmation_token invalid</a></li> </ul> <p>And have tried:</p> <ul> <li>Setting <code>config.allow_insecure_tokens_lookup = true</code> in my Devise initializer, which throws an 'unknown method' error on startup. Plus it sounds like this is only supposed to be a temporary fix, so I'd like to avoid using it.</li> <li>Purged my DB and started from scratch (so no old tokens are present)</li> </ul> <p><strong>Update:</strong></p> <p>Checking the confirmation token stored on the <code>User</code> after registering. The emails token matches the DBs token. According to the posts above, the new Devise behavior says not supposed to, and that instead it is should generate a second token based on the e-mail's token. <em>This is suspicious.</em> Running <code>User.confirm_by_token('[EMAIL_CONFIRMATION_TOKEN]')</code> returns a User who has errors set "@messages={:confirmation_token=>["is invalid"]}", which appears to be the source of the issue.</p> <p>Mismatching tokens seems to be the heart of the issue; running the following code in console to manually change the User's confirmation_token causes confirmation to succeed:</p> <pre><code>new_token = Devise.token_generator.digest(User, :confirmation_token, '[EMAIL_TOKEN]') u = User.first u.confirmation_token = new_token u.save User.confirm_by_token('[EMAIL_TOKEN]') # Succeeds </code></pre> <p>So why is it saving the wrong confirmation token to the DB in the first place? I am using a custom registration controller... maybe there's something in it that causes it to be set incorrectly?</p> <p><strong>routes.rb</strong></p> <pre><code> devise_for :users, :path =&gt; '', :path_names =&gt; { :sign_in =&gt; 'login', :sign_out =&gt; 'logout', :sign_up =&gt; 'register' }, :controllers =&gt; { :registrations =&gt; "users/registrations", :sessions =&gt; "users/sessions" } </code></pre> <p><strong>users/registrations_controller.rb</strong>:</p> <pre><code>class Users::RegistrationsController &lt; Devise::RegistrationsController def create # Custom code to fix DateTime issue Utils::convert_params_date_select params[:user][:profile_attributes], :birthday, nil, true super end def sign_up_params # TODO: Still need to fix this. Strong parameters with nested attributes not working. # Permitting all is a security hazard. params.require(:user).permit! #params.require(:user).permit(:email, :password, :password_confirmation, :profile_attributes) end private :sign_up_params end </code></pre>
18,675,155
3
5
null
2013-09-05 01:55:07.607 UTC
6
2018-03-01 18:21:57.633 UTC
2017-05-23 11:44:11.96 UTC
null
-1
null
2,217,557
null
1
44
ruby-on-rails|devise|devise-confirmable
16,727
<p>So upgrading to Devise 3.1.0 left some 'cruft' in a view that I hadn't touched in a while.</p> <p>According to <a href="http://blog.plataformatec.com.br/2013/08/devise-3-1-now-with-more-secure-defaults/" rel="noreferrer">this blog post</a>, you need to change your Devise mailer to use <code>@token</code> instead of the old <code>@resource.confirmation_token</code>.</p> <p>Find this in <code>app/views/&lt;user&gt;/mailer/confirmation_instructions.html.erb</code> and change it to something like:</p> <pre><code>&lt;p&gt;Welcome &lt;%= @resource.email %&gt;!&lt;/p&gt; &lt;p&gt;You can confirm your account email through the link below:&lt;/p&gt; &lt;p&gt;&lt;%= link_to 'Confirm my account', confirmation_url(@resource, :confirmation_token =&gt; @token) %&gt;&lt;/p&gt; </code></pre> <p>This should fix any token-based confirmation problems you're having. This is likely to fix any unlock or reset password token problems as well.</p>
18,486,660
What are the differences between Model, ModelMap, and ModelAndView?
<p>What are the main differences between the following <a href="http://projects.spring.io/spring-framework/" rel="noreferrer">Spring Framework</a> classes?</p> <ul> <li><code>Model</code></li> <li><code>ModelMap</code></li> <li><code>ModelAndView</code></li> </ul> <p>Using <code>Model.put(String,Object)</code> we can access the values in <code>.jsp</code> files, but <code>ModelMap.addAttribute(String,Object)</code> also did same thing. I do not understand the difference between these classes.</p>
18,487,335
3
0
null
2013-08-28 11:31:17.313 UTC
25
2018-01-06 01:50:05.603 UTC
2015-01-21 21:22:05.963 UTC
null
606,910
null
2,046,194
null
1
80
spring|spring-mvc
66,980
<p><code>Model</code> is an interface while <code>ModelMap</code> is a class.</p> <p><code>ModelAndView</code> is just a container for both a <code>ModelMap</code> and a view object. It allows a controller to return both as a single value.</p>
5,331,293
What's the benefit of seeding a random number generator with only prime numbers?
<p>While conducting some experiments in Java, my project supervisor reminded me to seed each iteration of the experiment with a different number. He also mentioned that I should use prime numbers for the seed values. This got me thinking &#8212; why primes? Why not any other number as the seed? Also, why must the prime number be sufficiently big? Any ideas? I would've asked him this myself, but its 4am here right now, everyone's asleep, I just remembered this question and I'm burning to know the answer (I'm sure you know the feeling).</p> <p>It would be nice if you could provide some references, I'm very interested in the math/concept behind all this!</p> <p><strong>EDIT:</strong></p> <p>I'm using java.util.Random.</p> <p><strong>FURTHER EDIT:</strong></p> <p>My professor comes from a C background, but I'm using Java. Don't know if that helps. It appears that using primes is his idiosyncrasy, but I think we've unearthed some interesting answers about generating random numbers. Thanks to everyone for the effort!</p>
5,331,910
3
8
null
2011-03-16 20:23:02.853 UTC
2
2011-03-17 10:19:55.007 UTC
2011-03-17 10:19:55.007 UTC
null
495,545
null
495,545
null
1
31
java|algorithm|random|seed
5,088
<p>Well one blink at the implementation would show you that he CAN'T have any reason for that claim at all. Why? Because that's how the set seed function looks like:</p> <pre><code>synchronized public void setSeed(long seed) { seed = (seed ^ multiplier) &amp; mask; this.seed.set(seed); haveNextNextGaussian = false; } </code></pre> <p>And that's exactly what's called from the constructor. So even if you give it a prime, it won't use it anyhow, so if at all you'd have to use a seed s where (s^ multiplier) &amp; mask results in a prime ;)</p> <p>Java uses a usual linear congruency method, i.e.: </p> <p>x_n+1 = (a * x_n + c) mod m with 2 &lt;= a &lt; m; 0 &lt;= c &lt; m.</p> <p>Since you want to get a maximal periode, c and m have to be relatively prime and a few other quite obscure limitations, plus a few tips how to get a practically useful version. Knuth obviously covers that in detail in part2 ;)</p> <p>But anyhow, the seed doesn't influence the qualities of the generator at all. Even if the implementation would be using a Lehmer generator, it would obviously make sure that N is prime (otherwise the algorithm is practically useless; and not uniformly distributed if all random values would have to be coprime to a non prime N I wager) which makes the point moot</p>
18,387,814
Drawing on Canvas - PorterDuff.Mode.CLEAR draws black! Why?
<p>I'm trying to create a custom View which works simple: there is a Bitmap which is revealed by arc path - from 0deg to 360deg. Degrees are changing with some FPS.</p> <p>So I made a custom View with overridden <code>onDraw()</code> method:</p> <pre><code>@Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); arcPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); canvas.drawArc(arcRectF, -90, currentAngleSweep, true, arcPaint); arcPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, circleSourceRect, circleDestRect, arcPaint); } </code></pre> <p><code>arcPaint</code> is initialized as follows:</p> <pre><code>arcPaint = new Paint(); arcPaint.setAntiAlias(true); arcPaint.setColor(Color.RED); // Color doesn't matter </code></pre> <p>Now, everything draws great, but... the background is BLACK in whole View.</p> <p>If I set <code>canvas.drawColor(..., PorterDuff.Mode.DST)</code> and omit <code>canvas.drawBitmap()</code> - the arc is drawn properly on transparent background.</p> <p>My question is - how to set <code>PorterDuff</code> modes to make it work with transparency?</p> <p>Of course <code>bitmap</code> is 32-bit PNG with alpha channel.</p>
44,607,874
7
2
null
2013-08-22 18:08:52.56 UTC
6
2021-09-10 22:39:24.277 UTC
2013-08-23 16:48:16.757 UTC
null
997,381
null
997,381
null
1
34
android|canvas|drawing|porter-duff
24,612
<p><code>PorterDuff.Mode.CLEAR</code> doesn't work with hardware acceleration. Just set </p> <pre><code>view.setLayerType(View.LAYER_TYPE_SOFTWARE, null); </code></pre> <p>Works perfectly for me.</p>
18,410,035
Ways to iterate over a list in Java
<p>Being somewhat new to the Java language I'm trying to familiarize myself with all the ways (or at least the non-pathological ones) that one might iterate through a list (or perhaps other collections) and the advantages or disadvantages of each. </p> <p>Given a <code>List&lt;E&gt; list</code> object, I know of the following ways to loop through all elements:</p> <h3>Basic <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.1" rel="noreferrer">for</a> <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html" rel="noreferrer">loop</a> (of course, there're equivalent <code>while</code> / <code>do while</code> loops as well)</h3> <pre><code>// Not recommended (see below)! for (int i = 0; i &lt; list.size(); i++) { E element = list.get(i); // 1 - can call methods of element // 2 - can use 'i' to make index-based calls to methods of list // ... } </code></pre> <p>Note: As @amarseillan pointed out, this form is a poor choice for iterating over <code>List</code>s, because the actual implementation of the <code>get</code> method may not be as efficient as when using an <code>Iterator</code>. For example, <code>LinkedList</code> implementations must traverse all of the elements preceding i to get the i-th element.</p> <p>In the above example there's no way for the <code>List</code> implementation to "save its place" to make future iterations more efficient. For an <code>ArrayList</code> it doesn't really matter, because the complexity/cost of <code>get</code> is constant time (O(1)) whereas for a <code>LinkedList</code> is it proportional to the size of the list (O(n)). </p> <p>For more information about the computational complexity of the built-in <code>Collections</code> implementations, check out <a href="https://stackoverflow.com/questions/559839/big-o-summary-for-java-collections-framework-implementations">this question</a>.</p> <h3>Enhanced <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2" rel="noreferrer">for loop</a> (nicely explained <a href="https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work">in this question</a>)</h3> <pre><code>for (E element : list) { // 1 - can call methods of element // ... } </code></pre> <h3><a href="http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html" rel="noreferrer">Iterator</a></h3> <pre><code>for (Iterator&lt;E&gt; iter = list.iterator(); iter.hasNext(); ) { E element = iter.next(); // 1 - can call methods of element // 2 - can use iter.remove() to remove the current element from the list // ... } </code></pre> <h3><a href="http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html" rel="noreferrer">ListIterator</a></h3> <pre><code>for (ListIterator&lt;E&gt; iter = list.listIterator(); iter.hasNext(); ) { E element = iter.next(); // 1 - can call methods of element // 2 - can use iter.remove() to remove the current element from the list // 3 - can use iter.add(...) to insert a new element into the list // between element and iter-&gt;next() // 4 - can use iter.set(...) to replace the current element // ... } </code></pre> <h3><a href="http://functionaljava.org/" rel="noreferrer">Functional Java</a></h3> <pre><code>list.stream().map(e -&gt; e + 1); // Can apply a transformation function for e </code></pre> <h3><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-" rel="noreferrer">Iterable.forEach</a>, <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-" rel="noreferrer">Stream.forEach</a>, ...</h3> <p>(A map method from Java 8's Stream API (see @i_am_zero's answer).)</p> <p>In Java 8 collection classes that implement <code>Iterable</code> (for example, all <code>List</code>s) now have a <code>forEach</code> method, which can be used instead of the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.1" rel="noreferrer">for loop statement</a> demonstrated above. (Here is <a href="https://stackoverflow.com/questions/16635398/java-8-iterable-foreach-vs-foreach-loop">another question</a> that provides a good comparison.)</p> <pre><code>Arrays.asList(1,2,3,4).forEach(System.out::println); // 1 - can call methods of an element // 2 - would need reference to containing object to remove an item // (TODO: someone please confirm / deny this) // 3 - functionally separates iteration from the action // being performed with each item. Arrays.asList(1,2,3,4).stream().forEach(System.out::println); // Same capabilities as above plus potentially greater // utilization of parallelism // (caution: consequently, order of execution is not guaranteed, // see [Stream.forEachOrdered][stream-foreach-ordered] for more // information about this). </code></pre> <p>What other ways are there, if any?</p> <p>(BTW, my interest does not stem at all from a desire to <a href="https://stackoverflow.com/questions/2113216/which-is-more-efficient-a-for-each-loop-or-an-iterator">optimize performance</a>; I just want to know what forms are available to me as a developer.)</p>
18,410,489
13
11
null
2013-08-23 19:00:14.92 UTC
230
2022-01-13 17:20:49.253 UTC
2018-02-23 17:22:48.827 UTC
null
63,550
null
1,171,509
null
1
674
java|loops|collections|iteration
1,144,876
<p>The three forms of looping are nearly identical. The enhanced <code>for</code> loop:</p> <pre><code>for (E element : list) { . . . } </code></pre> <p>is, according to the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2" rel="noreferrer">Java Language Specification</a>, <em>identical</em> in effect to the explicit use of an iterator with a traditional <code>for</code> loop. In the third case, you can only modify the list contents by removing the current element and, then, only if you do it through the <code>remove</code> method of the iterator itself. With index-based iteration, you are free to modify the list in any way. However, adding or removing elements that come before the current index risks having your loop skipping elements or processing the same element multiple times; you need to adjust the loop index properly when you make such changes.</p> <p>In all cases, <code>element</code> is a reference to the actual list element. None of the iteration methods makes a copy of anything in the list. Changes to the internal state of <code>element</code> will always be seen in the internal state of the corresponding element on the list.</p> <p>Essentially, there are only two ways to iterate over a list: by using an index or by using an iterator. The enhanced for loop is just a syntactic shortcut introduced in Java 5 to avoid the tedium of explicitly defining an iterator. For both styles, you can come up with essentially trivial variations using <code>for</code>, <code>while</code> or <code>do while</code> blocks, but they all boil down to the same thing (or, rather, two things).</p> <p>EDIT: As @iX3 points out in a comment, you can use a <code>ListIterator</code> to set the current element of a list as you are iterating. You would need to use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/List.html#listIterator%28%29" rel="noreferrer"><code>List#listIterator()</code></a> instead of <a href="http://docs.oracle.com/javase/7/docs/api/java/util/List.html#iterator%28%29" rel="noreferrer"><code>List#iterator()</code></a> to initialize the loop variable (which, obviously, would have to be declared a <code>ListIterator</code> rather than an <code>Iterator</code>).</p>
20,036,984
How do I restore a missing IIS Express SSL Certificate?
<p>After setting up HTTPS in IIS Express, according to such articles as <a href="http://robrich.org/archive/2012/06/04/moving-to-iis-express-and-https.aspx" rel="noreferrer">this</a> and <a href="http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx" rel="noreferrer">this</a>, I am unable to actually load an IIS Express site using HTTPS. In <strong>Chrome</strong>, I am only getting:</p> <blockquote> <p>This webpage is not available (with error code "ERR_CONNECTION_RESET")</p> </blockquote> <p>...and in <strong>IE</strong> I am only getting:</p> <blockquote> <p>Internet Explorer cannot display the webpage</p> </blockquote> <p>...when I follow the directions in those articles.</p> <p>It appears this has to do with the fact that the "IIS Express Development Certificate" that IIS Express installs automatically has been removed. How do I get this certificate reinstalled?</p>
20,048,613
8
3
null
2013-11-17 22:24:39.503 UTC
64
2021-04-24 12:12:24.267 UTC
2018-01-15 18:53:40.3 UTC
null
208,990
null
208,990
null
1
164
ssl|https|ssl-certificate|iis-express
114,465
<p>Windows 10 users: Repair is only in the Control Panel, not in the Add Remove programs app. I typically run appwiz.cpl to launch the old control panel applet and run repair from there.</p> <p>Windows 7 and 8.1: After going to Add/Remove Programs and choosing the &quot;Repair&quot; option on IIS Express, the certificate has been reinstalled and I can now launch IIS Express sites using HTTPS.</p> <p><img src="https://i.stack.imgur.com/7i395.png" alt="Repair IIS Express" /></p> <p>The certificate is back:</p> <p><img src="https://i.stack.imgur.com/0C1ke.png" alt="IIS Express Development Certificate" /></p> <p>And I can now launch the IIS Express site using HTTPS:</p> <p><img src="https://i.stack.imgur.com/CbZpG.png" alt="Success!" /></p>
20,158,793
Creating c++ vector of pointers
<p>In my C++ code I have a class Object equipped with an id field of type int. Now I want to create a vector of pointers of type Object*. First I tried</p> <pre><code>vector&lt;Object*&gt; v; for(int id=0; id&lt;n; id++) { Object ob = Object(id); v.push_back(&amp;ob); } </code></pre> <p>but this failed because here the same address just repeats itself n times. If I used the new operator I would get what I want but I'd like to avoid dynamic memory allocation. Then I thought that what I need is somehow to declare n different pointers before the for loop. Straightforward way to this is to declare an array so I did this :</p> <pre><code>vector&lt;Object*&gt; v; Object ar[n]; for(int i=0; i&lt;n; i++) { ar[i] = Object(i); } for(int i=0; i&lt;n; i++) { v.push_back(ar+i); } </code></pre> <p>Is there still possibility to get a memory leak if I do it this way? Also going through an array declaration is a bit clumsy in my opinion. Are there any other ways to create vector of pointers but avoid manual memory management?</p> <p>EDIT: Why do I want pointers instead of just plain objects?</p> <p>Well I modified the original actual situation a bit because I thought in this way I can represent the question in the simplest possible form. Anyway I still think the question can be answered without knowing why I want a vector of pointers.</p> <p>Actually I have</p> <pre><code>Class A { protected: vector&lt;Superobject*&gt; vec; ... }; Class B: public A {...}; Class Superobject { protected: int id; ... } Class Object: public Superobject {...} </code></pre> <p>In derived class <code>B</code> I want to fill the member field <code>vec</code> with objects of type <code>Object</code>. If the superclass didn't use pointers I would have problems with object slicing. So in class <code>B</code> constructor I want to initialize <code>vec</code> as vector of pointers of type <code>Object*</code>.</p> <p>EDIT2</p> <p>Yes, it seems to me that dynamic allocation is the reasonable option and the idea to use an array is a bad idea. When the array goes out of scope, things will go wrong because the pointers in vector point to memory locations that don't necessarily contain the objects anymore. </p> <p>In constructor for class B I had</p> <pre><code>B(int n) { vector&lt;Object*&gt; vec; Object ar[n]; for(int id=0; id&lt;n; id++) { ar[id] = Object(id); } for(int id=0; id&lt;n; id++) { v.push_back(ar+id); } } </code></pre> <p>This caused very strange behavior in objects of class B. </p>
20,159,876
3
3
null
2013-11-23 05:07:11.88 UTC
6
2015-04-06 02:39:45.797 UTC
2013-11-23 15:32:36.117 UTC
null
1,363,208
null
1,363,208
null
1
9
c++|pointers|vector
52,302
<p>In this loop:</p> <pre><code>for(int id=0; id&lt;n; id++) { Object ob = Object(id); v.push_back(&amp;ob); } </code></pre> <p>You are creating n times Object instance on stack. At every iteration there is created and removed element. You can simply avoid this using that:</p> <pre><code>for(int id=0; id&lt;n; id++) { Object* ob = new Object(id); v.push_back(ob); } </code></pre> <p>thanks that every new element exist on heap not on the stack. Try to add to in class Object constructor something like that:</p> <pre><code>std::cout&lt;&lt;"Object ctor()\n"; </code></pre> <p>and the same in the destructor:</p> <pre><code>std::cout&lt;&lt;"Object dtor()\n"; </code></pre> <p>If you dont want to create these objects with "new" try reason written by @woolstar</p>
15,436,702
Estimate Cohen's d for effect size
<p>given two vectors:</p> <pre><code>x &lt;- rnorm(10, 10, 1) y &lt;- rnorm(10, 5, 5) </code></pre> <p>How to calculate Cohen's d for effect size?</p> <p>For example, I want to use the <a href="http://www.statmethods.net/stats/power.html">pwr package</a> to estimate the power of a t-test with unequal variances and it requires Cohen's d.</p>
15,437,034
4
0
null
2013-03-15 15:52:19.907 UTC
9
2021-06-29 09:53:43.687 UTC
2013-03-15 16:08:57.11 UTC
null
429,846
null
1,144,724
null
1
14
r|statistics
42,793
<p>Following <a href="http://www.statmethods.net/stats/power.html" rel="noreferrer"><strong>this link</strong></a> and <a href="http://en.wikipedia.org/wiki/Cohen%27s_d#Cohen.27s_d" rel="noreferrer"><strong>wikipedia</strong></a>, Cohen's d for a t-test seems to be:</p> <p><img src="https://i.stack.imgur.com/PP2Cf.jpg" alt="enter image description here"></p> <p>Where <code>sigma</code> (denominator) is:</p> <p><img src="https://i.stack.imgur.com/wZxZE.jpg" alt="enter image description here"></p> <p>So, with your data:</p> <pre><code>set.seed(45) ## be reproducible x &lt;- rnorm(10, 10, 1) y &lt;- rnorm(10, 5, 5) cohens_d &lt;- function(x, y) { lx &lt;- length(x)- 1 ly &lt;- length(y)- 1 md &lt;- abs(mean(x) - mean(y)) ## mean difference (numerator) csd &lt;- lx * var(x) + ly * var(y) csd &lt;- csd/(lx + ly) csd &lt;- sqrt(csd) ## common sd computation cd &lt;- md/csd ## cohen's d } &gt; res &lt;- cohens_d(x, y) &gt; res # [1] 0.5199662 </code></pre>
15,484,622
How to convert sparse matrix to dense matrix in Eigen
<p>Is there some easy and fast way to convert a sparse matrix to a dense matrix of doubles?</p> <p>Because my <code>SparseMatrix</code> is not sparse any more, but became dense after some matrix products.</p> <p>Another question I have: The Eigen library has excellent performance, how is this possible? I don't understand why, because there are only header files, no compiled source.</p>
15,592,295
1
2
null
2013-03-18 18:53:25.187 UTC
9
2015-08-10 23:38:21.443 UTC
2013-03-23 14:48:45.25 UTC
null
1,737,727
null
2,165,656
null
1
20
c++|matrix|sparse-matrix|eigen
14,950
<p>Let's declare two matrices:</p> <pre><code>SparseMatrix&lt;double&gt; spMat; MatrixXd dMat; </code></pre> <p>Sparse to dense:</p> <pre><code>dMat = MatrixXd(spMat); </code></pre> <p>Dense to sparse:</p> <pre><code>spMat = dMat.sparseView(); </code></pre>
15,428,777
whats the difference between: %%a and %variable% variables?
<pre><code>for /f "tokens=*" %%a in ('find /v ":" "%appdata%\gamelauncher\options.txt" ^| find "menu=a"') do ( set usemenu=a ) for /f "tokens=*" %%a in ('find /v ":" "%appdata%\gamelauncher\options.txt" ^| find "menu=b"') do ( set usemenu=b ) for /f "tokens=*" %%a in ('find /v ":" "%appdata%\gamelauncher\options.txt" ^| find "menu=c"') do ( set usemenu=c ) </code></pre> <p>Right, in this code (which may not work, that what i'm trying to find out) we have this "%%a" in that 'for' command.</p> <p>First, whats the difference between %variable% and %%a?</p> <p>Second, can someone explain the 'for' command to me? I have Google'd it way too much and all the explanations seem way to complicated...</p> <p>What I am trying to do is pull a variable from options.txt, so i can change the menu style of my game launcher. there are 3 styles (a, b and c), so if the options.txt reads "menu=a" how can i get it to set a variable like %usemenu% to the value of a?</p> <p>Thanks for any help in advance!</p>
15,428,976
1
0
null
2013-03-15 09:29:14.63 UTC
5
2019-07-03 02:30:00.133 UTC
null
null
null
null
2,010,401
null
1
20
variables|batch-file|cmd
99,446
<p><code>%variable%</code> are <em>environment</em> variables. They are set with <code>set</code> and can be accessed with <code>%foo%</code> or <code>!foo!</code> (with delayed expansion if enabled). <code>%%a</code> are special variables created by the <code>for</code> command to represent the current loop item or a token of a current line.</p> <p><code>for</code> is probably about the most complicated and powerful part of batch files. If you need loop, then in most cases <code>for</code> has you covered. <code>help for</code> has a summary.</p> <p>You can</p> <ul> <li>iterate over files: <code>for %x in (*.txt) do ...</code></li> <li>repeat something <em>n</em> times: <code>for /l %x in (1, 1, 15) do...</code> (the arguments are <em>start</em>, <em>step</em> and <em>end</em>)</li> <li>iterate over a set of values: <code>for %x in (a, b, c) do ...</code></li> <li>iterate over the lines of a file: <code>for /f %x in (foo.txt) do ...</code></li> <li>tokenize lines of a file: <code>for /f "tokens=2,3* delims=," %x in (foo.txt) do ...</code></li> <li>iterate over the output of a command: <code>for /f %x in ('somecommand.exe') do ...</code></li> </ul> <p>That's just a short overview. It gets more complex but please read the help for that.</p> <p>Variables of the form <code>%%a</code> (or <code>%a</code> if <code>for</code> is used outside of batch files) are very similar to arguments to batch files and subroutines (<code>%1</code>, <code>%2</code>, ...). Some kinds of expansions can be applied to them, for example to get just the file name and extension if the variable represents a file name with path you can use <code>%%~nxa</code>. A complete overview of those is given in <code>help for</code>.</p> <p>On the other hand, environment variables have other kinds of special things. You can perform replacements in them via <code>%foo:a=b%</code> would result in <code>%foo%</code> except that every <code>a</code> is replaced by a <code>b</code>. Also you can take substrings: <code>%foo:~4,2%</code>. Descriptions of those things can be found in <code>help set</code>.</p> <p>As to why <code>%variables%</code> and <code>%%a</code> are different things that's a bit hard to answer and probably just a historical oddity. As outlined above there is a third kind of variable, <code>%1</code>, etc. which are very similar to those used in <code>for</code> and have existed for longer, I guess. Since environment variables are a bit unwieldy to use in <code>for</code> due to blocks and thus heavy reliance on delayed expansion the decision probably was made to use the same mechanisms as for arguments instead of environment variables.</p> <p>Also environment variables could be more expensive, given that the process has a special “environment” block of memory where they are stored in <code>variable=value␀</code> pairs, so updating environment variables involves potentially copying around a bit of memory while the other kind of variables could be more lightweight. This is speculation, though.</p> <hr> <p>As for your problem, you don't really need <code>for</code> here:</p> <pre><code>find /v ":" "%appdata%\gamelauncher\options.txt" | find "menu=a" &amp;&amp; set usemenu=a </code></pre> <p>This will only run the <code>set</code> if the preceding command was successful, i.e. <code>menu=a</code> was found. This should be considerably easier than <code>for</code>. From what I read you're trying to look whether <code>menu=a</code> exists in a line that does not contain a colon and in that case <code>usemenu</code> should be set to <code>a</code>, right? (And likewise for <code>b</code> and <code>c</code>. You could try coaxing <code>for</code> into doing that by looping over the lines of the file or output and tokenizing appropriately to figure out the value of <code>menu</code> but depending on the format of the lines this can be tricky. If what you have there works in theory then you should simply stick to that. You can however use a loop around it to avoid having to repeat the same line three times for <code>a</code>, <code>b</code> and <code>c</code>:</p> <pre><code>for %%X in (a b c) do ( find /v ":" "%appdata%\gamelauncher\options.txt" | find "menu=%%X" &amp;&amp; set usemenu=%%X ) </code></pre> <p>If the file you are parsing is simple, however, with just <code>name=value</code> pairs in each line where <code>: foo</code> would be a comment, then you <em>could</em> use <code>for</code> as well:</p> <pre><code>for /f "tokens=1,* eol=: delims==" %%A in (%appdata%\gamelauncher\options.txt) do ( if "%%A"=="menu" set usemenu=%%B ) </code></pre> <p>But that depends a little on the exact format of the file. Above snippet would now read the file line by line and for each line would discard everything after a colon (the <code>eol=:</code> option), use the equals sign as a token delimiter and capture two tokens: The part before the first <code>=</code> and everything after it. The tokens are named starting with <code>%%A</code> so the second one is implicitly <code>%%B</code> (again, this is explained in <code>help for</code>). Now, for each line we examine the first token and look whether it's <code>menu</code> and if so, assign its value to the <code>usemenu</code> variable. If you have a lot of possible options to support this is certainly easier to maintain :-).</p>
15,133,595
Use case generalization versus extension
<p>UML Use Case Diagrams allow for two seemingly equivalent ways to show that a given use case might be realised in several different ways namely <a href="https://i.stack.imgur.com/VThNF.png">use case generalizations</a> as opposed to <a href="https://i.stack.imgur.com/Xc0hU.png">use case extensions</a>. I have seen the following basically example modelled using either approach with equal frequency, sometimes within a single source.</p> <p><img src="https://i.stack.imgur.com/VThNF.png" alt="Use case generalisation image"></p> <p><img src="https://i.stack.imgur.com/Xc0hU.png" alt="Use case extension image"></p> <p>To my mind an extension is a weaker relationship than generalization as a direct substitution of the specialised use case for the base case must be possible in generalization but not necessarily in extensions.</p> <p>It seems to me that generalisation implies a polymorphic implementation is desired while extension implies some branching structure is to be used. </p> <pre><code>void makePayment(const PaymentDetails* pd) { pd-&gt;pay(); } </code></pre> <p>as opposed to</p> <pre><code>void makePayment(const PaymentDetails* pd) { switch(pd-&gt;type) { case EFT: payViaEFT(pd); break; case PAYPAL: payViaPayPal(pd); break; case CREDITCARD: payViaCreditCard(pd); break; } } </code></pre> <p>Isn't the Use Case stage far too early for such implementation specific concerns to be modelled? There are much more appropriate UML diagrams for that. Is there a hard and fast rule regarding which of the two to use and if so what is it?</p>
15,135,858
3
1
null
2013-02-28 10:51:30.013 UTC
8
2022-06-12 13:17:00.59 UTC
null
null
null
null
141,997
null
1
27
uml|use-case
21,706
<blockquote> <p>To my mind an extension is a weaker relationship than generalization as a direct substitution of the specialised use case for the base case must be possible in generalization but not necessarily in extensions.</p> </blockquote> <p>That is true.</p> <blockquote> <p>It seems to me that generalisation implies a polymorphic implementation is desired while extension implies some branching structure is to be used.</p> </blockquote> <p>The diagram does not dictate any implementation. You can interpret a hint from the diagram for yourself, though. UML remains independent of language and solution there.</p> <blockquote> <p>Isn't the Use Case stage far too early for such implementation specific concerns to be modelled?</p> </blockquote> <p>Well, as indicated above, UML does not enforce any specific kind of implementation. However, you are gathering some important functional requirements here that might greatly influence your time schedule and workload. (&quot;Pay with credit card&quot; is way more complex to handle than &quot;pay in advance by bank transfer&quot;). So you'd strive to capture that but remain open to different solution approaches.</p> <blockquote> <p>There are much more appropriate UML diagrams for that.</p> </blockquote> <p>You can really use them in parallel :) as they are different views on the same subject.</p> <blockquote> <p>Is there a hard and fast rule regarding which of the two to use and if so what is it?</p> </blockquote> <p>I prefer the generalization in this case because the extensions falsely suggest there could be a way of paying without using any of the three named options. As you indicated yourself.</p> <p>Addendum (as per comments): The high-level purpose of the example diagram is to outline the foreseen payment <em>means</em>. A <em>payment</em> needs at least one <em>means</em> (unless payment is cancelled), just like &quot;print&quot; is too vague without clarifications such as &quot;what&quot; and &quot;where&quot;. Hence my preference for using the generalization, despite &quot;make payment&quot; being a valid use case in itself.</p>
15,195,750
Minify/compress CSS with regex?
<p>In PHP can you compress/minify CSS with regex (PCRE)?</p> <p>(As a theoretical in regex. I'm sure there are libraries out there that do this well.)</p> <p><sub>Background note: After spending hours writing an answer to a <a href="https://stackoverflow.com/questions/15186425/string-replacement-fails-with-important">deleted (half crap) question</a>, I thought I'd post a part of the underlying question and answer it my self. Hope it's ok.</sub></p>
15,195,752
4
6
null
2013-03-04 06:24:22.66 UTC
10
2018-06-08 00:52:57.677 UTC
2017-05-23 12:25:20.837 UTC
null
-1
null
107,152
null
1
28
php|css|regex|pcre|minify
7,875
<h1>Simple regex CSS minifier/compressor</h1> <p>(Ok, it may not be overly simple, but pretty straight forward.)</p> <h2>Requirements</h2> <p>This answer assumes that the requirements are:</p> <ul> <li>Remove comments</li> <li>Replace whitespace combinations longer than 1 space with a single space</li> <li>Remove all whitespace around the meta characters: <code>{</code>, <code>}</code>, <code>;</code>, <code>,</code>, <code>&gt;</code>, <code>~</code>, <code>+</code>, <code>-</code></li> <li>Remove spaces around <code>!important</code></li> <li>Remove spaces around <code>:</code>, except in selectors (where you have to keep a space before it)</li> <li>Remove spaces around operators like <code>$=</code></li> <li>Remove all spaces right of <code>(</code>/<code>[</code> and left of <code>)</code>/<code>]</code></li> <li>Remove all spaces at the beginning and end of string</li> <li>Remove the last <code>;</code> in a block</li> <li>Don't change anything in strings</li> <li>Doesn't have to work on invalid CSS</li> </ul> <p>Note that the requirements here do not include converting CSS properties to shorter versions (like using shorthand properties instead of several full length properties, removing quotes where not required). This is something that regex would not be able to solve in general.</p> <h2>Solution</h2> <p>It's easier to solve this in two passes: first remove the comments, then everything else.</p> <p>It should be possible to do in a single pass, but then you have to replace all <code>\s</code> with an expression that matches both spaces and comments (among some other modifications).</p> <p>The first pass expression to remove comments:</p> <pre><code>(?xs) # quotes ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' ) | # comments /\* (?&gt; .*? \*/ ) </code></pre> <p>Replace with <code>$1</code>.</p> <p>And to remove everything else you can use:</p> <pre><code>(?six) # quotes ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' ) | # ; before } (and the spaces after it while we're here) \s*+ ; \s*+ ( } ) \s*+ | # all spaces around meta chars/operators \s*+ ( [*$~^|]?+= | [{};,&gt;~+-] | !important\b ) \s*+ | # spaces right of ( [ : ( [[(:] ) \s++ | # spaces left of ) ] \s++ ( [])] ) | # spaces left (and right) of : \s++ ( : ) \s*+ # but not in selectors: not followed by a { (?! (?&gt; [^{}"']++ | "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )*+ { ) | # spaces at beginning/end of string ^ \s++ | \s++ \z | # double spaces to single (\s)\s+ </code></pre> <p>Replaced with <code>$1$2$3$4$5$6$7</code>.</p> <p>The selector check for removing spaces before <code>:</code> (the negative lookahead) can slow this down compared to proper parsers. Parsers already know if they are in a selector or not, and don't have to do extra searches to check that.</p> <h2>Example implementation in PHP</h2> <pre><code>function minify_css($str){ # remove comments first (simplifies the other regex) $re1 = &lt;&lt;&lt;'EOS' (?sx) # quotes ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' ) | # comments /\* (?&gt; .*? \*/ ) EOS; $re2 = &lt;&lt;&lt;'EOS' (?six) # quotes ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' ) | # ; before } (and the spaces after it while we're here) \s*+ ; \s*+ ( } ) \s*+ | # all spaces around meta chars/operators \s*+ ( [*$~^|]?+= | [{};,&gt;~+-] | !important\b ) \s*+ | # spaces right of ( [ : ( [[(:] ) \s++ | # spaces left of ) ] \s++ ( [])] ) | # spaces left (and right) of : \s++ ( : ) \s*+ # but not in selectors: not followed by a { (?! (?&gt; [^{}"']++ | "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )*+ { ) | # spaces at beginning/end of string ^ \s++ | \s++ \z | # double spaces to single (\s)\s+ EOS; $str = preg_replace("%$re1%", '$1', $str); return preg_replace("%$re2%", '$1$2$3$4$5$6$7', $str); } </code></pre> <h2>Quick test</h2> <p>Can be found <a href="http://ideone.com/Q5USEF">at ideone.com</a>:</p> <pre><code>$in = &lt;&lt;&lt;'EOS' p * i , html /* remove spaces */ /* " comments have no escapes \*/ body/* keep */ /* space */p, p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) &gt; b span i , div::after { /* comment */ background : url( " /* string */ " ) blue !important ; content : " escapes \" allowed \\" ; width: calc( 100% - 3em + 5px ) ; margin-top : 0; margin-bottom : 0; margin-left : 10px; margin-right : 10px; } EOS; $out = minify_css($in); echo "input:\n"; var_dump($in); echo "\n\n"; echo "output:\n"; var_dump($out); </code></pre> <p>Output:</p> <pre><code>input: string(435) " p * i , html /* remove spaces */ /* " comments have no escapes \*/ body/* keep */ /* space */p, p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) &gt; b span i , div::after { /* comment */ background : url( " /* string */ " ) blue !important ; content : " escapes \" allowed \\" ; width: calc( 100% - 3em + 5px ) ; margin-top : 0; margin-bottom : 0; margin-left : 10px; margin-right : 10px; } " output: string(251) "p * i,html body p,p [remove~=" spaces "] :nth-child(3+2n)&gt;b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px}" </code></pre> <h2>Compared</h2> <h3>cssminifier.com</h3> <p>Results of <a href="http://www.cssminifier.com/">cssminifier.com</a> for the same input as the test above:</p> <pre><code>p * i,html /*\*/body/**/p,p [remove ~= " spaces "] :nth-child(3+2n)&gt;b span i,div::after{background:url(" /* string */ ") blue;content:" escapes \" allowed \\";width:calc(100% - 3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px} </code></pre> <p>Length 263 byte. 12 byte longer than the output of the regex minifier above.</p> <p><a href="http://www.cssminifier.com/">cssminifier.com</a> has some disadvantages compared to this regex minifier:</p> <ul> <li>It leaves parts of comments. (There may be a reason for this. Maybe some CSS hacks.)</li> <li>It doesn't remove spaces around operators in some expressions</li> </ul> <h3>CSSTidy</h3> <p>Output of <a href="http://csstidy.sourceforge.net/">CSSTidy 1.3</a> (via <a href="http://www.codebeautifier.com">codebeautifier.com</a>) at highest compression level preset:</p> <pre><code>p * i,html /* remove spaces */ /* " comments have no escapes \*/ body/* keep */ /* space */p,p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) &gt; b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin:0 10px;} </code></pre> <p>Length 286 byte. 35 byte longer than the output of the regex minifier.</p> <p>CSSTidy doesn't remove comments or spaces in some selectors. But it does minify to shorthand properties. The latter should probably help compress normal CSS a lot more.</p> <h3>Side by side comparison</h3> <p>Minified output from the different minifiers for the same input as in the above example. (Leftover line breaks replaced with spaces.)</p> <pre><code>this answern (251): p * i,html body p,p [remove~=" spaces "] :nth-child(3+2n)&gt;b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px} cssminifier.com (263): p * i,html /*\*/body/**/p,p [remove ~= " spaces "] :nth-child(3+2n)&gt;b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100% - 3em+5px);margin-top:0;margin-bottom:0;margin-left:10px;margin-right:10px} CSSTidy 1.3 (286): p * i,html /* remove spaces */ /* " comments have no escapes \*/ body/* keep */ /* space */p,p [ remove ~= " spaces " ] :nth-child( 3 + 2n ) &gt; b span i,div::after{background:url(" /* string */ ") blue!important;content:" escapes \" allowed \\";width:calc(100%-3em+5px);margin:0 10px;} </code></pre> <p>For normal CSS CSSTidy is probably best as it converts to shorthand properties.</p> <p>I assume there are other minifiers (like the YUI compressor) that should be better at this, and give shorter result than this regex minifier.</p>
15,363,923
Disable the underlying window when a popup is created in Python TKinter
<p>I have a master Frame (call it <code>a</code>), and a popup Toplevel (call it <code>b</code>). How do I make sure the user cannot click on anything in <code>a</code> while <code>b</code> is "alive"?</p>
15,363,998
1
0
null
2013-03-12 14:25:27.287 UTC
12
2018-02-22 18:47:34.183 UTC
null
null
null
null
755,934
null
1
32
python|tkinter
32,869
<p>If you don't want to hide the root but just make sure the user can only interact with the popup, you can use <a href="http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.grab_set-method" rel="noreferrer"><code>grab_set()</code></a> and <a href="http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.grab_release-method" rel="noreferrer"><code>grab_release()</code></a>.</p> <pre><code>b.grab_set() # when you show the popup # do stuff ... b.grab_release() # to return to normal </code></pre> <p><strong>Alternatively</strong>, you could <code>withdraw()</code> the root to make it invisible:</p> <pre><code>a.withdraw() </code></pre> <p>will leave the root alive, but only <code>b</code> visible. </p> <p>If you need it back, you can do</p> <pre><code>a.deiconify() </code></pre>
15,390,303
How to group by DESC order
<p>I have the following table called questions:</p> <pre><code>ID | asker 1 | Bob 2 | Bob 3 | Marley </code></pre> <p>I want to select each asker only once and if there are multiple askers with the same name, select the one of the highest id. So, the expected results:</p> <pre><code>ID | asker 3 | Marley 2 | Bob </code></pre> <p>I use the following query:</p> <pre><code>SELECT * FROM questions GROUP by questions.asker ORDER by questions.id DESC </code></pre> <p>I get the following result:</p> <pre><code>ID | asker 3 | Marley 1 | Bob </code></pre> <p>It selects the first 'Bob' it encounters instead of the last one.</p>
15,390,352
7
3
null
2013-03-13 15:59:44.897 UTC
5
2020-10-25 22:10:19.017 UTC
2020-10-25 22:10:19.017 UTC
null
1,839,439
null
1,848,708
null
1
40
mysql|sql|group-by
108,106
<p>If you want the last <code>id</code> for each <code>asker</code>, then you should use an aggregate function:</p> <pre><code>SELECT max(id) as id, asker FROM questions GROUP by asker ORDER by id DESC </code></pre> <p>The reason why you were getting the unusual result is because MySQL uses an extension to <code>GROUP BY</code> which allows items in a select list to be nonaggregated and not included in the GROUP BY clause. This however can lead to unexpected results because MySQL can choose the values that are returned. (See <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html" rel="noreferrer">MySQL Extensions to GROUP BY</a>) </p> <p>From the MySQL Docs:</p> <blockquote> <p>MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. ... You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values the server chooses.</p> </blockquote> <p>Now if you had other columns that you need to return from the table, but don't want to add them to the <code>GROUP BY</code> due to the inconsistent results that you could get, then you could use a subquery to do so. (<a href="http://sqlfiddle.com/#!9/a82d769/5/0" rel="noreferrer">Demo</a>)</p> <pre><code>select q.Id, q.asker, q.other -- add other columns here from questions q inner join ( -- get your values from the group by SELECT max(id) as id, asker FROM questions GROUP by asker ) m on q.id = m.id order by q.id desc </code></pre>
45,183,875
Spring Boot Controller not mapping
<p>I have used STS and now I am using IntelliJ Ultimate Edition but I am still getting the same output. My controller is not getting mapped thus showing 404 error. I am completely new to Spring Framework.</p> <p>DemoApplication.java</p> <pre><code>package com.webservice.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } </code></pre> <p>HelloController.java</p> <pre><code>package com.webservice.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String sayHello(){ return "Hey"; } } </code></pre> <p>Console Output</p> <pre><code>com.webservice.demo.DemoApplication : Starting DemoApplication on XFT000159365001 with PID 11708 (started by Mayank Khursija in C:\Users\Mayank Khursija\IdeaProjects\demo) 2017-07-19 12:59:46.150 INFO 11708 --- [ main] com.webservice.demo.DemoApplication : No active profile set, falling back to default profiles: default 2017-07-19 12:59:46.218 INFO 11708 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@238e3f: startup date [Wed Jul 19 12:59:46 IST 2017]; root of context hierarchy 2017-07-19 12:59:47.821 INFO 11708 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8211 (http) 2017-07-19 12:59:47.832 INFO 11708 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2017-07-19 12:59:47.832 INFO 11708 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15 2017-07-19 12:59:47.944 INFO 11708 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2017-07-19 12:59:47.944 INFO 11708 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1728 ms 2017-07-19 12:59:47.987 INFO 11708 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2017-07-19 12:59:48.510 INFO 11708 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-07-19 12:59:48.519 INFO 11708 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 2017-07-19 12:59:48.634 INFO 11708 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8211 (http) 2017-07-19 12:59:48.638 INFO 11708 --- [ main] com.webservice.demo.DemoApplication : Started DemoApplication in 2.869 seconds (JVM running for 3.44) </code></pre>
47,283,396
13
14
null
2017-07-19 07:35:56.767 UTC
6
2022-08-11 17:21:17.99 UTC
2017-07-19 11:42:54.93 UTC
null
472,495
null
6,154,775
null
1
45
java|spring
79,351
<p>I too had the similar issue and was able to finally resolve it by correcting the source package structure following <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html" rel="noreferrer">this</a></p> <p>Your Controller classes are not scanned by the Component scanning. Your Controller classes must be nested below in package hierarchy to the main SpringApplication class having the main() method, then only it will be scanned and you should also see the RequestMappings listed in the console output while Spring Boot is getting started.</p> <p>Tested on Spring Boot 1.5.8.RELEASE</p> <p>But in case you prefer to use your own packaging structure, you can always use the <code>@ComponentScan</code> annotation to define your <code>basePackages</code> to scan.</p>
23,583,497
How to pass javascript/jQuery variable to PHP using POST method
<p>This is really basic. All I want to do is measure the html width of a browser window, and pass that data to a PHP script so that I can adjust what information is passed to the site.</p> <p>I've got the HTML width part down. I'm just having trouble passing the Javascript/jQuery variable to the PHP script using AJAX.</p> <p>Here's the Javascript/jQuery. It is written in PHP so that I can use the <code>include()</code> function later.</p> <pre><code>echo '&lt;script&gt; htmlWidth = $("html").width(); $.ajax({ type: "POST", url: "mobileView.php", data:{ width: htmlWidth } }) &lt;/script&gt;'; </code></pre> <p>And here's the PHP:</p> <pre><code>$width = $_POST['width']; function mobileView(){ if ($width &lt; 950){ return true; } else{ return false; } } mobileView(); </code></pre>
23,583,747
2
8
null
2014-05-10 16:22:22.557 UTC
0
2014-05-10 16:52:40.477 UTC
2014-05-10 16:46:46.787 UTC
null
1,021,725
null
3,623,716
null
1
2
javascript|php|jquery|ajax|post
47,274
<p>Here is the code that can be function within a file:</p> <p>For PHP part, you should pass value to the function and call the function.</p> <p>I guess you need return data to the client from the php function return. Then, for ajax part, you have to catch the return data.</p> <pre><code>&lt;? if(isset($_POST['width'])){ $width = $_POST['width']; function mobileView($width){ if ($width &lt; 950){ echo 'true'; } else{ echo 'false'; } } mobileView($width); }else{ ?&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; htmlWidth = $("html").width(); $.ajax({ type: "POST", url: "mobileView.php", data:{ width: htmlWidth }, success: function(data){ console.log(data); } }) &lt;/script&gt; &lt;? }; ?&gt; </code></pre>
8,548,030
Why does "pip install" inside Python raise a SyntaxError?
<p>I'm trying to use pip to install a package. I try to run <code>pip install</code> from the Python shell, but I get a <code>SyntaxError</code>. Why do I get this error? How do I use pip to install the package?</p> <pre><code>&gt;&gt;&gt; pip install selenium ^ SyntaxError: invalid syntax </code></pre>
8,548,165
8
3
null
2011-12-17 21:23:32.337 UTC
91
2021-11-19 15:07:17.573 UTC
2017-01-10 00:44:18.36 UTC
null
202,229
null
958,083
null
1
292
python|pip|installation
955,024
<p>pip is run from the command line, not the Python interpreter. It is a program that <strong>installs</strong> modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and do <code>import selenium</code>.</p> <p>The Python shell is not a command line, it is an interactive interpreter. You type Python code into it, not commands.</p>
4,986,683
Difference between Implicit and Explicit Transaction
<p>What is the difference between Implicit and Explicit transaction in Sql Server 2008?</p> <p>What happens in TransactionScope background? I'm using TransactionScope but in Sql server profiler I don't see "Begin transaction..." statement.</p> <p>How does it work?</p>
4,988,483
4
0
null
2011-02-13 20:30:59.217 UTC
6
2015-05-06 14:31:26.883 UTC
2011-02-14 02:49:04.467 UTC
null
573,261
null
648,723
null
1
20
sql-server-2005|sql-server-2008|c#-4.0|transactions|transactionscope
51,641
<ul> <li>Implicit Transactions: <a href="http://msdn.microsoft.com/en-us/library/ms188317.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms188317.aspx</a></li> <li>SET IMPLICIT_TRANSACTIONS { ON | OFF} <a href="http://msdn.microsoft.com/en-us/library/ms187807.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms187807.aspx</a></li> </ul> <p>Basically, in c# when you set the TransactionScope to Implicit, it calls the SQL Server SET command to put the connection in IMPLICIT_TRANSACTIONS mode. Anything that you do (using one of the commands listed in the 2nd link) starts a transaction that is kept open <em>until</em> a commit is issued. If no commit is issued at the end of a connection, an implicit ROLLBACK is performed.</p> <p>This differs from the OFF setting, which also puts every statement into a transaction - the difference is that in the OFF mode (therefore transactions are explicit), each transaction (singular statement) is <strong>immediately</strong> committed.</p>
5,013,917
Can I serve JSPs from inside a JAR in lib, or is there a workaround?
<p>I have a web application deployed as a WAR file in Tomcat 7. The application is build as a multi-module project:</p> <ul> <li>core - packaged as JAR, contains most of the backend code</li> <li>core-api - packaged as JAR, contains interfaces toward core</li> <li>webapp - packaged as WAR, contains frontend code and depends on core</li> <li>customer-extensions - optional module, packaged as JAR</li> </ul> <p>Normally, we can put our JSP files in the webapp project, and reference them relative to the context:</p> <pre><code>/WEB-INF/jsp/someMagicalPage.jsp </code></pre> <p>The question is what we do about JSP files that are specific to the customer-extensions project, that should not always be included in the WAR. Unfortunately, I cannot refer to JSPs inside JAR files, it appears. Attempting <code>classpath:jsp/customerMagicalPage.jsp</code> results in a file not found in the JspServlet, since it uses <code>ServletContext.getResource()</code>.</p> <p>Traditionally, we "solved" this having maven unpack the customer-extensions JAR, locate the JSPs, and put them in the WAR when building it. But an ideal situation is where you just drop a JAR in the exploded WAR in Tomcat and the extension is discovered - which works for everything but the JSPs.</p> <p>Is there anyway to solve this? A standard way, a Tomcat-specific way, a hack, or a workaround? For example, I've been thinking of unpacking the JSPs on application startup...</p>
11,063,065
5
2
null
2011-02-16 08:03:12.63 UTC
26
2019-06-13 07:45:08.25 UTC
null
null
null
null
90,566
null
1
64
java|jsp|tomcat|servlets|tiles
32,152
<p>Servlet 3.0 which Tomcat 7 supports includes the ability to package jsps into a jar.</p> <p>You need to:</p> <ul> <li>place your jsps in <code>META-INF/resources</code> directory of your jar</li> <li>optionally include a <code>web-fragment.xml</code> in the <code>META-INF</code> directory of your jar</li> <li>place the jar in <code>WEB-INF/lib</code> directory of your war</li> </ul> <p>You should then be able to reference your jsps in your context. For example if you have a jsp <code>META-INF/resources/test.jsp</code> you should be able reference this at the root of your context as <code>test.jsp</code></p>
4,967,530
How can I maintain the space between these two buttons in IE7 mode?
<p>I have 2 buttons horizontally aligned. In most browsers there's a space between them, but if you view this:</p> <p><a href="http://jsfiddle.net/2HP43/1/" rel="nofollow">http://jsfiddle.net/2HP43/1/</a></p> <p>in "Browser Mode: IE7" &amp; "Document Mode: IE7 Standards" you can see that the 2 buttons are stuck together. </p> <p>Can somebody suggest how I can correct this so that there is always a consistent space between these buttons?</p>
4,967,564
6
1
null
2011-02-11 09:42:47.5 UTC
1
2016-05-12 13:15:21.663 UTC
null
null
null
null
181,771
null
1
0
html|css|internet-explorer|internet-explorer-7
41,081
<p>Have you tried putting <code>&amp;nbsp;</code> in between them?</p> <p>IE does not render "padding" to W3C standards. (See <a href="http://www.quirksmode.org/css/box.html" rel="nofollow">here</a> for explanation.) That's almost assuredly where this problem is coming from, so you'll need to insert something in between them to make it work properly.</p>
5,229,586
What is the C# standard for capitialising method names?
<p>What is the C# standard for capitialising method names? Is it:</p> <pre><code>MyClass.MyMethod() </code></pre> <p>or</p> <pre><code>MyClass.myMethod() </code></pre> <p>?</p>
5,229,612
8
3
null
2011-03-08 07:27:16.633 UTC
7
2021-01-24 13:39:51.81 UTC
2021-01-24 13:39:51.81 UTC
null
939,213
null
626,023
null
1
54
c#|naming-conventions
40,941
<p>The first one is right following the <a href="https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions" rel="nofollow noreferrer">.NET Capitalization Conventions</a></p>
5,448,545
How to retrieve GET parameters from JavaScript
<p>Consider:</p> <pre><code>http://example.com/page.html?returnurl=%2Fadmin </code></pre> <p>For <code>js</code> within <code>page.html</code>, how can it retrieve <code>GET</code> parameters?</p> <p>For the above simple example, <code>func('returnurl')</code> should be <code>/admin</code>.</p> <p>But it should also work for complex query strings...</p>
5,448,595
17
1
null
2011-03-27 10:09:49.803 UTC
86
2022-06-11 06:59:58.467 UTC
2020-10-08 21:02:27.487 UTC
null
63,550
null
641,151
null
1
413
javascript|get
664,589
<p>With the <a href="https://developer.mozilla.org/en/DOM/window.location" rel="noreferrer">window.location</a> object. This code gives you GET without the question mark.</p> <pre><code>window.location.search.substr(1) </code></pre> <p>From your example it will return <code>returnurl=%2Fadmin</code></p> <p><strong>EDIT</strong>: I took the liberty of changing <a href="https://stackoverflow.com/a/21210643/179669">Qwerty's answer</a>, which is <strong>really good</strong>, and as he pointed I followed exactly what the OP asked:</p> <pre><code>function findGetParameter(parameterName) { var result = null, tmp = []; location.search .substr(1) .split("&amp;") .forEach(function (item) { tmp = item.split("="); if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]); }); return result; } </code></pre> <p>I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent" rel="noreferrer"><code>decodeURIComponent</code></a>, exactly as OP asked. I'm not sure if this may or may not be a security issue.</p> <p>Or otherwise with plain for loop, which will work even in IE8:</p> <pre><code>function findGetParameter(parameterName) { var result = null, tmp = []; var items = location.search.substr(1).split("&amp;"); for (var index = 0; index &lt; items.length; index++) { tmp = items[index].split("="); if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]); } return result; } </code></pre>
17,042,431
How to focus div?
<p>Please don't throw stones at me because i'm total newbie at js and jquery. is it possible to focus a div? i just wanted to process events when div is clicked OR is focused and when we click outside the div. Something like that:</p> <p>HTML:</p> <pre><code>&lt;div id="focusedDiv"&gt;&lt;/div&gt; </code></pre> <p>JS:</p> <pre><code> $("#focusedDiv").focus(function () { .... }); $("#focusedDiv").focusout(function () { .... }); </code></pre> <p>Thanks in advance!</p>
17,042,452
1
2
null
2013-06-11 10:56:17.253 UTC
1
2013-06-11 10:57:39.83 UTC
null
null
null
null
1,178,399
null
1
6
jquery|html
55,086
<p>You have to set tabindex attribute:</p> <p><a href="http://jsfiddle.net/QAkGV/">http://jsfiddle.net/QAkGV/</a></p> <pre><code>&lt;div id="focusedDiv" tabindex="-1"&gt;&lt;/div&gt; </code></pre> <p>Or:</p> <pre><code>$("#focusedDiv").attr('tabindex',-1).focus(function () { .... }); </code></pre> <p>For style, you could set outline CSS property too:</p> <pre><code>$("#focusedDiv").css('outline',0).attr('tabindex',-1).focus(function () { .... }); </code></pre>
61,966,810
Flutter - save file to download folder - downloads_path_provider
<p>I'm developing a mobile app using flutter. For that I used <a href="https://pub.dev/packages/downloads_path_provider" rel="noreferrer">downloads-path-provider</a> to get the download directory of the mobile phone. The emulator returns <code>/storage/emulated/0/Download</code>. Also when I save a file in this directory the file can be visible in the Download folder.</p> <p>But on a real devices it also returns the same directory path. <code>/storage/emulated/0/Download</code> Is this correct for the actual devices? Because on actual devices I cannot see the saved file in the Download folder. </p> <p>Is there any solution to find the downloads directory on a real device?</p>
62,087,942
2
8
null
2020-05-23 02:47:15.773 UTC
4
2022-05-05 19:12:37.947 UTC
2020-05-29 14:15:34.463 UTC
null
436,341
null
9,532,360
null
1
10
android|flutter
38,086
<p>path_provider will probably undergo some changes soon, there are some open issues:</p> <p><a href="https://github.com/flutter/flutter/issues/35783" rel="noreferrer">https://github.com/flutter/flutter/issues/35783</a></p> <p>As of right now, the best way to get the download path on an Android device is to use:</p> <pre><code>/storage/emulated/0/Download/ </code></pre> <p>No (s) needed.</p> <p>And to get the external dir path in Android:</p> <pre><code>/storage/emulated/0/ </code></pre> <p>The &quot;emulated&quot; word does not mean it's the emulator path, it's just a naming convention.</p> <p>Make sure you have permission to write to the file, add this to manifest.xml file, right under &lt;manifest tag:</p> <pre><code>&lt;manifest package=&quot;...&quot; ... &gt; &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt; </code></pre> <p>and also request permission at run time.</p> <p>See <a href="https://pub.dev/packages/permission_handler" rel="noreferrer">https://pub.dev/packages/permission_handler</a></p>
12,064,439
Detect whether cell value was actually changed by editing
<p><code>Worksheet_Change</code> triggers when a cell value is changed (which is what I want), but it also triggers when you enter a cell as if to edit it but don't actually change the cell's value (and this is what I don't want to happen). </p> <p>Say I want to add shading to cells whose value was changed. So I code this:</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) Target.Interior.ColorIndex = 36 End Sub </code></pre> <p>Now to test my work: Change cell A1 and the cell gets highlighted. That's the desired behaviour. So far so good. Then, double click B1 but don't change the value there and then click C1. You'll notice B1 gets highlighted! And this is not the desired behaviour. </p> <p>Do I have to go through the methods discussed here of capturing the old value, then compare old to new before highlighting the cell? I certainly hope there's something I'm missing.</p>
12,068,586
5
4
null
2012-08-21 23:21:53.973 UTC
4
2021-03-31 15:02:59.883 UTC
2018-06-27 16:09:49.793 UTC
user2140173
8,112,776
null
1,615,488
null
1
11
vba|excel
40,619
<p>I suggest automatically maintaining a "mirror copy" of your sheet, in another sheet, for comparison with the changed cell's value. </p> <p>@brettdj and @JohnLBevan essentially propose doing the same thing, but they store cell values in comments or a dictionary, respectively (and +1 for those ideas indeed). My feeling, though, is that it is conceptually much simpler to back up cells in cells, rather than in other objects (especially comments, which you or the user may want to use for other purposes). </p> <p>So, say I have <code>Sheet1</code> whose cells the user may change. I created this other sheet called <code>Sheet1_Mirror</code> (which you could create at <code>Workbook_Open</code> and could set to be hidden if you so desire -- up to you). To start with, the contents of <code>Sheet1_Mirror</code> would be identical to that of <code>Sheet1</code> (again, you could enforce this at <code>Workbook_Open</code>). </p> <p>Every time <code>Sheet1</code>'s <code>Worksheet_Change</code> is triggered, the code checks whether the "changed" cell's value in <code>Sheet1</code> is actually different from that in <code>Sheet1_Mirror</code>. If so, it does the action you want and updates the mirror sheet. If not, then nothing. </p> <p>This should put you on the right track:</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) Dim r As Range For Each r In Target.Cells 'Has the value actually changed? If r.Value &lt;&gt; Sheet1_Mirror.Range(r.Address).Value Then 'Yes it has. Do whatever needs to be done. MsgBox "Value of cell " &amp; r.Address &amp; " was changed. " &amp; vbCrLf _ &amp; "Was: " &amp; vbTab &amp; Sheet1_Mirror.Range(r.Address).Value &amp; vbCrLf _ &amp; "Is now: " &amp; vbTab &amp; r.Value 'Mirror this new value. Sheet1_Mirror.Range(r.Address).Value = r.Value Else 'It hasn't really changed. Do nothing. End If Next End Sub </code></pre>
12,608,356
How to build simple jQuery image slider with sliding or opacity effect?
<p>Some of us might not want to use ready plugins because of their high sizes and possibilty of creating conflicts with current javascript. </p> <p>I was using light slider plugins before but when customer gives modular revise, it became really hard to manipulate. Then I aim to build mine for customising it easily. I believe sliders shouldn't be that complex to build from beginning. </p> <p>What is a simple and clean way to build jQuery image slider?</p>
12,608,357
5
1
null
2012-09-26 18:43:32.93 UTC
34
2019-01-15 13:41:31.637 UTC
2014-10-14 13:41:22.62 UTC
null
1,428,241
null
1,428,241
null
1
28
javascript|jquery|css|animation|slideshow
77,386
<p>Before inspecting examples, you should know two jQuery functions which i used most. </p> <p><a href="http://api.jquery.com/index/" rel="nofollow noreferrer">index()</a> returns value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.</p> <p><a href="http://api.jquery.com/eq/" rel="nofollow noreferrer">eq()</a> selects of an element based on its position (index value).</p> <p>Basicly i take selected trigger element's <code>index value</code> and match this value on images with <code>eq</code> method.</p> <p><a href="http://jsfiddle.net/mjaA3/1662/" rel="nofollow noreferrer"> - <strong>FadeIn / FadeOut</strong> effect.</a></p> <p><a href="http://jsfiddle.net/mjaA3/1672/" rel="nofollow noreferrer"> - <strong>Sliding</strong> effect.</a></p> <p><a href="http://jsfiddle.net/mjaA3/332/" rel="nofollow noreferrer"> - alternate <strong>Mousewheel</strong> response.</a></p> <hr> <p>​<strong>html sample:</strong></p> <pre><code>&lt;ul class="images"&gt; &lt;li&gt; &lt;img src="images/1.jpg" alt="1" /&gt; &lt;/li&gt; &lt;li&gt; &lt;img src="images/2.jpg" alt="2" /&gt; &lt;/li&gt; ... &lt;/ul&gt; &lt;ul class="triggers"&gt; &lt;li&gt;1&lt;/li&gt; &lt;li&gt;2&lt;/li&gt; ... &lt;/ul&gt; &lt;span class="control prev"&gt;Prev&lt;/span&gt; &lt;span class="control next"&gt;Next&lt;/span&gt; </code></pre> <hr> <h2>OPACITY EFFECT: <a href="http://jsfiddle.net/mjaA3/1662/" rel="nofollow noreferrer"><strong>jsFiddle.</strong></a></h2> <p><strong><em>css trick:</strong> overlapping images with position:absolute</em></p> <pre><code>ul.images { position:relative; } ul.images li { position:absolute; } </code></pre> <p><strong>jQuery:</strong></p> <pre><code>var target; var triggers = $('ul.triggers li'); var images = $('ul.images li'); var lastElem = triggers.length-1; triggers.first().addClass('active'); images.hide().first().show(); function sliderResponse(target) { images.fadeOut(300).eq(target).fadeIn(300); triggers.removeClass('active').eq(target).addClass('active'); } </code></pre> <hr> <h2>SLIDING EFFECT: <a href="http://jsfiddle.net/etfgy1kx/" rel="nofollow noreferrer"><strong>jsFiddle.</strong></a></h2> <p><strong><em>css trick:</strong> with double wrapper and use child as mask</em></p> <pre><code>.mask { float:left; margin:40px; width:270px; height:266px; overflow:hidden; } ul.images { position:relative; top:0px;left:0px; } /* this width must be total of the images, it comes from jquery */ ul.images li { float:left; } </code></pre> <p><strong>jQuery:</strong></p> <pre><code>var target; var triggers = $('ul.triggers li'); var images = $('ul.images li'); var lastElem = triggers.length-1; var mask = $('.mask ul.images'); var imgWidth = images.width(); triggers.first().addClass('active'); mask.css('width', imgWidth*(lastElem+1) +'px'); function sliderResponse(target) { mask.stop(true,false).animate({'left':'-'+ imgWidth*target +'px'},300); triggers.removeClass('active').eq(target).addClass('active'); } </code></pre> <hr> <h2>Common jQuery response for both slider:</h2> <p><em>( <strong>triggers + next/prev click and timing</strong> )</em></p> <pre><code>triggers.click(function() { if ( !$(this).hasClass('active') ) { target = $(this).index(); sliderResponse(target); resetTiming(); } }); $('.next').click(function() { target = $('ul.triggers li.active').index(); target === lastElem ? target = 0 : target = target+1; sliderResponse(target); resetTiming(); }); $('.prev').click(function() { target = $('ul.triggers li.active').index(); lastElem = triggers.length-1; target === 0 ? target = lastElem : target = target-1; sliderResponse(target); resetTiming(); }); function sliderTiming() { target = $('ul.triggers li.active').index(); target === lastElem ? target = 0 : target = target+1; sliderResponse(target); } var timingRun = setInterval(function() { sliderTiming(); },5000); function resetTiming() { clearInterval(timingRun); timingRun = setInterval(function() { sliderTiming(); },5000); } </code></pre> <hr>
12,338,244
Making resources theme dependent
<p>Now that we have two Icons (Dark and Light) as described in <a href="http://developer.android.com/guide/practices/ui_guidelines/icon_design_action_bar.html" rel="noreferrer">ActionBar Icon Guide</a>.</p> <pre><code>@drawable/ic_search_light @drawable/ic_search_dark </code></pre> <p>How to reference these Icons in XML menu resource:</p> <p><code>&lt;item android:title="Search" android:icon="</code>Which drawable here ? <code>"/&gt;</code></p> <p>Every time switch Application theme between Light and Dark, Do I have to update all these drawable references ?</p>
12,339,924
1
4
null
2012-09-09 10:17:19.9 UTC
21
2015-05-01 08:39:40.727 UTC
2012-09-09 14:31:23.03 UTC
null
1,531,054
null
1,531,054
null
1
28
android|android-theme
10,119
<p>There's a way to define android <em>drawables</em> (and many other elements found in <em>res/values</em>) to be Theme dependent.</p> <p>Lets suppose we have two <em>drawables</em>, menu icons in this case:</p> <pre><code>res/drawable/ic_search_light.png res/drawable/ic_search_dark.png </code></pre> <p>And we want to use <code>ic_search_dark.png</code> for Application theme which is default <code>Theme</code> or extends it, Similarly, we want <code>ic_search_light.png</code> if our Application theme changes to default <code>Theme.Light</code> or some theme extending it.</p> <p>Define a general attribute with a unique name in <em>/res/attrs.xml</em> like:</p> <pre><code>&lt;resources&gt; &lt;attr name="theme_dependent_icon" format="reference"/&gt; &lt;/resources&gt; </code></pre> <p>This is a global attribute and format type is reference, In case of a Custom View it can be defined along with style-able attributes:</p> <pre><code>&lt;resources&gt; &lt;declare-styleable name="custom_menu"&gt; &lt;attr name="theme_dependent_icon" format="reference"/&gt; &lt;/declare-styleable&gt; &lt;/resources&gt; </code></pre> <p>Next, define two Themes, extending default <code>Theme</code> and <code>Theme.Light</code> (or themes that inherit from these) in <em>res/styles.xml</em> or <em>res/themes.xml</em>:</p> <pre><code>&lt;resources&gt; &lt;style name="CustomTheme" parent="android:Theme"&gt; &lt;item name="theme_dependent_icon" &gt;@drawable/ic_search_dark&lt;/item&gt; &lt;/style&gt; &lt;style name="CustomTheme.Light" parent="android:Theme.Light"&gt; &lt;item name="theme_dependent_icon" &gt;@drawable/ic_search_light&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>Finally, use the reference attribute we define to refer to these icons. In this case, we use while defining a menu layout</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:title="Menu Item" android:icon="?attr/theme_dependent_icon"/&gt; &lt;/menu&gt; </code></pre> <p><code>?attr</code> refers to an attribute of current theme in use.</p> <p>Now, we can use above two themes for application:</p> <pre><code>&lt;application android:theme="@style/CustomTheme"&gt; </code></pre> <p>or</p> <pre><code>&lt;application android:theme="@style/CustomTheme.Light"&gt; </code></pre> <p>and corresponding resources will be used accordingly.</p> <p>Theme can also be applied in Code, by setting it at the very beginning of Activity's <code>onCreate()</code>.</p> <p><strong>UPDATE</strong></p> <p>Method to access these theme dependent resources from code is explained in <a href="https://stackoverflow.com/a/3679026/1531054">this answer</a>.</p>
12,595,631
Debugging with gdb on a program with no optimization but still there is no symbol in the current context for local variables
<p>I've been having this problem for while now, but always seem to put off asking this question because it seems like I am doing something wrong... but right now I feel otherwise... taken this code:</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; int main(int argc, char** argv) { if(argc &lt; 2) { std::cout &lt;&lt; "usage: " &lt;&lt; argv[0] &lt;&lt; " &lt;string&gt;" &lt;&lt; std::endl; return 1; } std::string str = argv[1]; std::reverse(str.begin(), str.end()); std::cout &lt;&lt; str &lt;&lt; std::endl; return 0; } </code></pre> <p>Compiled with the command:</p> <pre><code>g++ -std=c++11 -Wall main.cpp -o main -O0 -ggdb3 </code></pre> <p>I am using a very recent trunk version of gcc, I the trunk was taken around September 23rd ish... Also note that I am not compiling with optimization!</p> <p>Now anyway, I start debugging, like this:</p> <pre><code>gdb --quiet --args ./main string </code></pre> <p>I set a break point at line 12 (the reverse algorithm)</p> <pre><code>b 12 </code></pre> <p>then I run the program</p> <pre><code>run </code></pre> <p>then I try to print out the string, to see what it is</p> <pre><code>print str </code></pre> <p>And this, my dear friends, is what seems strange to me: The output of that previous command is:</p> <pre><code>No symbol "str" in current context. </code></pre> <p>a quick check to the local variables doesn't show the string either</p> <pre><code>info locals </code></pre> <p>all I get is</p> <pre><code>std::__ioinit = {static _S_refcount = 2, static _S_synced_with_stdio = true} </code></pre> <p>so I'm wondering, am I at fault, or is the compiler or debugger at fault... this has been a pretty pain in the ass problem for a long time for me... so thanks for even reading this question... :)</p> <p>EDIT: now that it has become clear that there is something wrong with my gcc build, I'm wondering if anyone has come across a bug report or any other case where there seems to a be a problem similar to this... I will also try checking with a recent build of gdb to make sure that there is definitely not a problem with my current debugger (that comes with ubuntu)... does that make sense?</p> <p>EDIT2: So after compiling gdb v7.5, I got relatively the same result except there were no locals present at all... I guess that means it's a gcc issue, thanks everyone...</p>
12,595,773
2
3
null
2012-09-26 06:17:46.55 UTC
21
2013-02-24 11:02:49.66 UTC
2012-09-26 07:00:33.663 UTC
user451498
null
user451498
null
null
1
33
c++|debugging|gcc|gdb
16,250
<p>No, even with --quiet it works for me. Maybe there's something wrong with your setup.</p> <pre><code>~/tmp $ g++ -Wall tmp.cpp -o tmp -O0 -ggdb3 ~/tmp $ gdb --quiet --args ./tmp string Reading symbols from /xxxxxxxx/tmp...done. (gdb) b 12 Breakpoint 1 at 0x400c95: file tmp.cpp, line 12. (gdb) run Starting program: /xxxxxxxx/tmp string Breakpoint 1, main (argc=2, argv=0x7fffffffdc58) at tmp.cpp:12 12 std::reverse(str.begin(), str.end()); (gdb) print str $1 = "string" (gdb) info locals str = "string" (gdb) </code></pre>
12,399,505
Understanding difference between redirect and rewrite .htaccess
<p>I'd like to understand the difference between redirecting and rewriting a URL using .htaccess. So here's an example: Say I have a link like <code>www.abc.com/ index.php?page=product_types&amp;cat=88</code> (call this the "original" url)</p> <p>But when the user types in <code>abc.com/shoes</code> (let's call this the "desired" url), they need to see the contents of the above link. To accomplish this, I would do this:</p> <pre><code>Options +FollowSymLinks RewriteEngine on RewriteBase / RewriteRule ^(.*)shoes(.*)$ index.php?page=product_types&amp;cat=88 </code></pre> <p>Nothing wrong with this code and it does the trick. However, if I type in the original url in the address bar, the content comes up, but the url does not change. So it remains as <code>www.abc.com/index.php?page=product_types&amp;cat=88</code></p> <p>But what if I wanted the desired url (<code>/shoes</code>) to show up in the address bar if I typed in <code>www.abc.com/ index.php?page=product_types&amp;cat=88</code>? How would this be accomplished using .htaccess? Am I running into a potential loop?</p>
12,399,668
1
2
null
2012-09-13 04:39:19.273 UTC
10
2017-09-03 12:04:20.967 UTC
2017-09-03 12:04:20.967 UTC
null
1,033,581
null
700,343
null
1
36
apache|.htaccess|mod-rewrite
30,649
<p>Some of the explanation can be found here: <a href="https://stackoverflow.com/a/11711948/851273">https://stackoverflow.com/a/11711948/851273</a></p> <p>The gist is that a rewrite happens solely on the server, the client (browser) is blind to it. The browser sends a request and gets content, it is none the wiser to what happened on the server in order to serve the request.</p> <p>A redirect is a server <strong>response</strong> to a request, that tells the client (browser) to submit a new request. The browser asks for a url, this url is what's in the location bar, the server gets that request and <strong>responds with a redirect</strong>, the browser gets the response and loads the URL in the server's response. The URL in the location bar is now the new URL and the browser sends a request for the new URL.</p> <p>Simply rewriting internally on the server does absolutely nothing to URLs in the wild. If google or reddit or whatever site has a link to <code>www.abc.com/index.php?page=product_types&amp;cat=88</code>, your internal server rewrite rule does absolutely nothing to that, nor to anyone who clicks on that link, or any client that happens to request that URL for any reason whatsoever. All the rewrite rule does is internally change something that contains <code>shoes</code> to <code>/index.php?page=product_types&amp;cat=88</code> within the server. </p> <p>If you want make it so a request is made for the index.php page with all of the query strings, you can tell the client (browser) to <strong>redirect</strong> to the nicer looking URL. You need to be careful because rewrite rules loop and your redirect will be internally rewritten which will cause a redirect which will be internally rewritten, etc.. causing a loop and will throw a 500 Server Error. So you can match specifically to the request itself:</p> <pre><code>RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?page=product_types&amp;cat=88 RewriteRule ^/?index.php$ /shoes [L,R=301] </code></pre> <p>This should only be used to make it so links in the wild get pointed to the right place. <strong>You must ensure that your content is generating the correct links</strong>. That means everything on your site is using the <code>/shoes</code> link instead of the <code>/index.php?page=product_types&amp;cat=88</code> link.</p>
12,432,154
Int vs Word in common use?
<p>It seems like the common pattern of taking/returning <code>Int</code> (ie <code>ByteString.hGet</code> and <code>Data.List.length</code>) is contrary to the Haskell pattern of using strongly-descrbing types, since many of these cases can only handle positive numbers. Would it not be better to use <code>Word</code>, or is there a reason these functions are partial on <code>Int</code>?</p>
12,432,899
3
6
null
2012-09-14 21:21:09.377 UTC
6
2012-09-16 10:08:50.287 UTC
null
null
null
null
8,611
null
1
43
haskell|type-safety
4,883
<p>It is true that the expressiveness of the Haskell type system encourages users to assign precise types to entities they define. However, seasoned Haskellers will readily acknowledge that one must strike a balance between ultimate type precision (which besides isn't always attainable given the current limits of Haskell type system) and convenience. In short, precise types are only useful to a point. Beyond that point, they often just cause extra bureaucracy for little to no gain.</p> <p>Let's illustrate the problem with an example. Consider the factorial function. For all <code>n</code> bigger than 1, the factorial of <code>n</code> is an even number, and the factorial of 1 isn't terribly interesting so let's ignore that one. Therefore, in order to make sure that our implementation of the factorial function in Haskell is correct, we might be tempted to introduce a new numeric type, that can only represent unsigned even integers:</p> <pre><code>module (Even) where newtype Even = Even Integer instance Num Even where ... fromInteger x | x `mod` 2 == 0 = Even x | otherwise = error "Not an even number." instance Integral Even where ... toInteger (Even x) = x </code></pre> <p>We seal this datatype inside a module that doesn't export the constructor, to make it abstract, and make it an instance of the all the relevant type classes that <code>Int</code> is an instance of. Now we can give the following signature to factorial:</p> <pre><code>factorial :: Int -&gt; Even </code></pre> <p>The type of <code>factorial</code> sure is more precise than if we just said that it returns <code>Int</code>. But you'll find that definining <code>factorial</code> with such a type is really quite annoying, because you need a version of multiplication that multiplies an (even or odd) <code>Int</code> with an <code>Even</code> and produces and <code>Even</code>. What's more, you might have to introduce extraneous calls to <code>toInteger</code> on the result of a call to <code>factorial</code> in client code, which can be a significant source of clutter and noise for little gain. Besides, all these conversion functions could potentially have a negative impact on performance.</p> <p>Another problem is that when introducing a new, more precise type, you often end up having to duplicate all manner of library functions. For instance, if you introduce the type <code>List1 a</code> of non-empty lists, then you will have to reimplement many of the functions that <code>Data.List</code> already provides, but for <code>[a]</code> only. Sure, one can then make these functions methods of <code>ListLike</code> type class. But you quickly end up with all manner of adhoc type classes and other boilerplate, with again not much gain.</p> <p>One final point is that one shouldn't consider <code>Word</code> to be an unsigned variant of <code>Int</code>. The <a href="http://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x13-1350006.4" rel="noreferrer">Haskell report</a> leaves the actual size of <code>Int</code> unspecified, and only guarantees that this type should be capable of representing integers in the range [− 2<sup>29</sup>, 2<sup>29</sup> − 1]. The type <code>Word</code> is said to provide unsigned integers of unspecified width. It isn't guaranteed that in any conforming implementation the width of a <code>Word</code> corresponds to the width of an <code>Int</code>.</p> <p>Though I make a point guarding against excessive type proliferation, I do acknowledge that introducing a type of <code>Natural</code> of naturals could be nice. Ultimately, though, whether Haskell should have a dedicated type for natural numbers, in addition to <code>Int</code>, <code>Integer</code>, and the various <code>Word*</code> types, is largely a matter of taste. And the current state of affairs is probably in very large part just an accident of history.</p>
12,131,273
Twitter Bootstrap - Tabs - URL doesn't change
<p>I'm using Twitter Bootstrap and its "tabs".</p> <p>I have the following code:</p> <pre><code>&lt;ul class="nav nav-tabs"&gt; &lt;li class="active"&gt;&lt;a data-toggle="tab" href="#add"&gt;add&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-toggle="tab" href="#edit" &gt;edit&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-toggle="tab" href="#delete" &gt;delete&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>The tabs work properly, but the in the URL is not added the #add, #edit, #delete.</p> <p>When I remove <code>data-toggle</code> the URL changes, but the tabs don't work. </p> <p>Any solutions for this?</p>
12,138,756
15
2
null
2012-08-26 15:19:06.007 UTC
44
2020-05-16 07:54:28.1 UTC
2012-12-04 20:12:01.297 UTC
null
448,144
null
867,418
null
1
113
jquery|twitter-bootstrap
93,227
<p>Try this code. It adds tab href to url + opens tab based on hash on page load:</p> <pre><code>$(function(){ var hash = window.location.hash; hash &amp;&amp; $('ul.nav a[href="' + hash + '"]').tab('show'); $('.nav-tabs a').click(function (e) { $(this).tab('show'); var scrollmem = $('body').scrollTop() || $('html').scrollTop(); window.location.hash = this.hash; $('html,body').scrollTop(scrollmem); }); }); </code></pre>
3,238,517
How do I redirect a domain to a specific "landing page"?
<p>My client has several parked domains. She wants those domains to point to specific pages in her main site. For example:</p> <p>Let's pretend she has a page on her main site about bedroom redecorating. That page is located at www.mainsite.com/bedrooms/</p> <p>And let's say she has a parked domain called www.999bedrooms.com/</p> <p>She wants to redirect that domain to www.mainsite.com/bedrooms/ </p> <p>What's the best way to do this without being penalized by the search engines? </p> <p>Also, keep in mind that www.mainsite.com/bedrooms is actually a WordPress page, so it's not an actual file on the server, per se. </p> <p>Thanks!</p>
3,238,667
3
0
null
2010-07-13 15:05:27.063 UTC
6
2013-11-08 01:23:09.677 UTC
null
null
null
null
320,942
null
1
11
redirect
40,731
<p>There are (at least) two ways to do this. One way requires access to some sort of configuration on the server, and the other doesn't. I don't know if you're using the Apache web server, but if you are, you would add <code>mod_alias</code> to your configuration and restart Apache:</p> <pre><code>a2enmod alias apache2ctl graceful </code></pre> <p>Then add this to the VirtualHost section for 999bedrooms.com:</p> <pre><code>Redirect permanent / http://www.mainsite.com/bedrooms </code></pre> <p>Then you should be done.</p> <p>The other way is in an HTML file that you put at <a href="http://999bedrooms.com/index.html" rel="noreferrer">http://999bedrooms.com/index.html</a>, put a line like this within the HEAD section:</p> <pre><code>&lt;meta http-equiv="refresh" content="1; url=http://www.mainsite.com/bedrooms"&gt; </code></pre> <p>This is one of those "Please wait while we redirect you to our main page" sorts of redirections that you see sometimes. Not as nice as the server-based ones, but easier to do.</p> <p>Hope this helps!</p>
3,976,272
JavaScript confirm box with custom buttons
<p>Can I write a custom confirm box in JavaScript that, instead of the default <code>OK</code> and <code>CANCEL</code> button, shows a <code>SAVE</code> and <code>DELETE</code> button?</p>
3,976,283
3
2
null
2010-10-20 09:11:09.333 UTC
1
2019-09-20 22:47:19.13 UTC
2015-07-11 13:15:19.74 UTC
null
4,370,109
null
461,807
null
1
14
javascript|confirmbutton
81,206
<p>Use the <a href="http://jqueryui.com/demos/dialog/#modal-confirmation" rel="noreferrer">jQuery UI Dialog Box</a> for this.</p> <p>You can do something like this:</p> <p>JS: </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { $("#dialog-confirm").dialog({ resizable: false, height: "auto", width: 400, modal: true, buttons: { "Do it": function() { $(this).dialog("close"); }, Cancel: function() { $(this).dialog("close"); } } }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://jqueryui.com/jquery-wp-content/themes/jquery/css/base.css" rel="stylesheet"/&gt; &lt;link href="http://jqueryui.com/jquery-wp-content/themes/jqueryui.com/style.css" rel="stylesheet" /&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"&gt;&lt;/script&gt; &lt;div id="dialog-confirm" title="Is it treason, then?"&gt; &lt;p&gt;&lt;span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"&gt;&lt;/span&gt;Am I the Senate?&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3,583,061
Automatically mirror a git repository
<p>One of the side-effects of using an external Subversion repository was getting automatic offsite backups on every commit.</p> <p>I'd like to achieve the same using Git. </p> <p>i.e. every commit to my local repository automatically commits to an external one so the two repositories are always in sync.</p> <p>I imagine that a post-commit hook would be the way to go. Does anyone have any specific examples of this?</p>
3,583,114
3
0
null
2010-08-27 09:56:10.967 UTC
14
2022-08-02 13:27:21.89 UTC
null
null
null
null
45,955
null
1
30
git|version-control|dvcs
16,377
<p>I wrote a post-commit hook for just this purpose. The hook itself is simple; just add a file named <code>post-commit</code> to your <code>.git/hooks/</code> directory with the following contents:</p> <pre><code>git push my_remote </code></pre> <p>The <code>post-commit</code> file should be executable. Also make sure that you add a suitable <a href="http://www.kernel.org/pub/software/scm/git/docs/git-remote.html" rel="noreferrer">remote</a> repository with the name <code>my_remote</code> for this this hook to work.</p> <p>I also made a symlink named <code>post-merge</code> that points to <code>post-commit</code>. This is optional. If you do this you'll auto-sync after merges as well. </p> <p><strong>UPDATE:</strong> If you want to ensure that your server, and your mirror do not get out of sync, and ensure that all branches are also backed up, your <code>post-commit</code> hook can use:</p> <pre><code>git push my_remote -f --mirror </code></pre>
3,320,355
How should I approach building a Universal iOS app that will include iOS 4 features, even though the iPad doesn't yet run iOS 4?
<p>I'd like build a game for both the iPhone and iPad. As such, it would make sense to start this project from scratch as a universal app. However, iPhone and iPad currently run two different versions of the iOS since iOS 4 isn't available for the iPad yet. There are two iOS 4 features (GameCenter and iAd) that I would like to support in my game. </p> <ol> <li>In this case, is it a bad idea to create this project as a universal app?</li> <li>If not, what are some thoughts I should take into consideration as I'm building a universal app that supports two different versions of the iOS?</li> <li>Is it somewhat safe to bet on Apple releasing the iOS 4 for the iPad in the fall as speculated? </li> <li>If so, is there anyway I can begin building these iOS 4 features (GameCenter and iAd) into my iPad version of my game?</li> </ol> <p>Thanks so much in advance for all your wisdom! </p> <p><em>EDIT:</em> I understand this issue involves managing risks. I'm aware of the risks, but I'm more interested in any tech design considerations related to building a universal app when the iOS is fragmented among the various iOS devices.</p>
3,320,709
4
1
null
2010-07-23 16:41:38.79 UTC
12
2011-08-14 01:21:58.01 UTC
2010-07-23 17:07:15.08 UTC
null
191,808
null
191,808
null
1
11
iphone|ipad|ios4|universal-binary
10,284
<p>If you're about to build a Universal App, just remember the following two source code snippets:</p> <ul> <li><p>Using classes only if they are available on the current device</p> <p>Consider this piece of code:</p> <pre><code>UILocalNotification* n = [[UILocalNotification alloc] init]; </code></pre> <p>When building a Universal App, this code will lead to a runtime error on any device running an iOS version that does not know about the UILocalNotification class.</p> <p>You can still support UILocalNotification in your code while maintaining backwards compatibility by using the following code snippet:</p> <pre><code>Class notificationClass = NSClassFromString(@"UILocalNotification"); if (notificationClass) { UILocalNotification* n = [[notificationClass alloc] init]; } </code></pre> <p>This technique allows you to use classes which are unavailable in certain OS versions on devices that do support the classes.</p></li> <li><p>Using methods only if they are available on the current device</p> <p>Suppose you'd like to do the following:</p> <pre><code>[[UIApplication sharedApplication] scheduleLocalNotification:n]; </code></pre> <p>Use the following piece of code to conditionally call the method in case it's available on the current device:</p> <pre><code>if ([UIApplication instancesRespondToSelector:@selector(scheduleLocalNotification:)]) { [[UIApplication sharedApplication] scheduleLocalNotification:n]; } </code></pre></li> </ul> <p>These two techniques are probably the only things you need to know to create your Universal App. Conditionally execute your code depending on device capabilities and you should be fine.</p> <p>Having said that, you still need to consider that the iPad will probably be using a different UI than your iPhone counterpart. And, unfortunately, you won't be able to test your iPad UI with the iOS 4 features until they become available on the iPad. But this shouldn't be too much of a problem: if you use <code>[[UIDevice currentDevice] userInterfaceIdiom]</code> to check whether you're running on an iPad, you can prevent your Universal App from executing code that has no iPad UI yet. Once Apple releases iOS 4 for iPads, you can implement the UI, remove that check and release an update to the store.</p>
24,024,702
How can I decrypt a password hash in PHP?
<p>I need to decrypt a password. The password is encrypted with <code>password_hash</code> function.</p> <pre><code>$password = 'examplepassword'; $crypted = password_hash($password, PASSWORD_DEFAULT); </code></pre> <p>Now, let's assume that <code>$crypted</code> is stored in a database (there's a "users" table, with usernames, passwords, etc) and I need to do a login: I have to see if the password entered by the user matches the encrypted password stored in the database.</p> <p>This is the sql code...</p> <pre><code>$sql_script = 'select * from USERS where username="'.$username.'" and password="'.$inputpassword.'"'; </code></pre> <p>...but <code>$inputpassword</code> is not encrypted, so it's not equal to what is stored in the password field of the table users...</p> <p>So, there's a function to decrypt after the use of <code>password_hash</code>? Or should I change my encrypt method? Or what else?</p>
24,024,772
6
11
null
2014-06-03 20:51:40.343 UTC
12
2021-08-30 21:24:17.797 UTC
2020-04-30 02:19:16.76 UTC
null
9,811,969
null
3,569,234
null
1
24
php|mysql|encryption
180,927
<p>Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use <a href="http://docs.php.net/manual/en/function.password-verify.php" rel="noreferrer">password_verify</a> to check whether a password matches the stored hash:</p> <pre><code>&lt;?php // See the password_hash() example to see where this came from. $hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq'; if (password_verify('rasmuslerdorf', $hash)) { echo 'Password is valid!'; } else { echo 'Invalid password.'; } </code></pre> <p>In your case, run the SQL query using only the username:</p> <pre><code>$sql_script = 'SELECT * FROM USERS WHERE username=?'; </code></pre> <p>And do the password validation in PHP using a code that is similar to the example above.</p> <p>The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See <a href="https://stackoverflow.com/a/60496">this Stack Overflow answer</a> on how to prevent SQL injection.</p>
22,739,701
Django, save ModelForm
<p>I have created a model <strong>Student</strong> which extends from the <strong>Django User</strong> and is a foreign key to another model while it has an integer field called year. What i'm trying to do is to save a form, which has 2 fields. The one is the <strong>course id</strong> and the another one is the the integer field <strong>year</strong>. When I'm clicking submit, i'm getting an error <em>Cannot assign "u'2'": "Student.course" must be a "Course" instance.</em></p> <p>models.py</p> <pre><code>class Student(models.Model): user = models.OneToOneField(User) course = models.ForeignKey(Course) year = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(7)]) </code></pre> <p>view.py</p> <pre><code>def step3(request): user = request.user if request.method == 'POST': form = SelectCourseYear(request.POST) if form.is_valid(): form.save() return render_to_response("registration/complete.html", RequestContext(request)) else: form = SelectCourseYear() return render(request, 'registration/step3.html',) </code></pre> <p>forms.py</p> <pre><code>class SelectCourseYear(forms.ModelForm): course = forms.CharField() year = forms.IntegerField(required=True) class Meta: model = Student fields = ['user', 'course', 'year'] </code></pre>
22,749,879
2
4
null
2014-03-30 02:51:33.313 UTC
16
2014-03-30 21:06:50.72 UTC
2014-03-30 03:20:37.02 UTC
null
1,867,980
null
1,460,144
null
1
32
python|django|django-forms
65,671
<p>You dont need to redefine fields in the <code>ModelForm</code> if you've already mentioned them in the <code>fields</code> attribute. So your form should look like this -</p> <pre><code>class SelectCourseYear(forms.ModelForm): class Meta: model = Student fields = ['course', 'year'] # removing user. we'll handle that in view </code></pre> <p>And we can handle the form with ease in the view - </p> <pre><code>def step3(request): user = request.user if request.method == 'POST': form = SelectCourseYear(request.POST) if form.is_valid(): student = form.save(commit=False) # commit=False tells Django that "Don't send this to database yet. # I have more things I want to do with it." student.user = request.user # Set the user object here student.save() # Now you can send it to DB return render_to_response("registration/complete.html", RequestContext(request)) else: form = SelectCourseYear() return render(request, 'registration/step3.html',) </code></pre>
8,464,262
Access is denied error on XDomainRequest
<p>I'm trying to use microsoft XDomainRequest to send cross domain request. Here is the code </p> <blockquote> <pre><code>... if ($.browser.msie &amp;&amp; window.XDomainRequest) { // Use Microsoft XDR var xdr = new XDomainRequest(); xdr.open("POST", "http://graph.facebook.com/1524623057/"); xdr.send(); } .... </code></pre> </blockquote> <p>It gives <code>SCRIPT5: Access is denied.</code> error on <code>xdr.open(...)</code> line.</p>
8,509,981
2
6
null
2011-12-11 13:20:49.597 UTC
5
2013-01-16 12:18:14.403 UTC
2012-02-13 20:57:42.19 UTC
null
213,269
null
1,051,927
null
1
32
javascript|internet-explorer|cross-domain|xdomainrequest
19,329
<p>I found the reason of this problem. As stated in <a href="http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx" rel="noreferrer">Point 7</a>:</p> <blockquote> <p><strong>Requests must be targeted to the same scheme as the hosting page</strong></p> <p>This restriction means that if your AJAX page is at <code>http://example.com</code>, then your target URL must also begin with <em><strong>HTTP</strong></em>. Similarly, if your AJAX page is at <code>https://example.com</code>, then your target URL must also begin with <em><strong>HTTPS</strong></em>.</p> </blockquote>
20,868,103
ref and out arguments in async method
<p>Does anyone know why <code>async</code> methods are not allowed to have <code>ref</code> and <code>out</code> arguments? I've done a bit of research on it but the only thing I could find was that it has to do with the stack unrolling.</p>
20,868,150
2
4
null
2014-01-01 11:22:16.94 UTC
16
2021-04-22 02:38:33.467 UTC
2021-04-22 02:38:33.467 UTC
null
1,402,846
null
1,239,433
null
1
95
c#|asynchronous
63,102
<blockquote> <p>Does anyone know why async methods are not allowed to have ref and out arguments? </p> </blockquote> <p>Sure. Think about it - an async method usually <em>returns</em> almost immediately, long before most of the actual logic is executed... that's done asynchronously. So any <code>out</code> parameters would have to be assigned before the first <code>await</code> expression, and there'd quite possibly have to be some restriction on <code>ref</code> parameters to stop them from being used after the first <code>await</code> expression anyway, as after that they may not even be valid.</p> <p>Consider calling an async method with <code>out</code> and <code>ref</code> parameters, using local variables for the arguments:</p> <pre><code>int x; int y = 10; FooAsync(out x, ref y); </code></pre> <p>After <code>FooAsync</code> returns, the method itself could return - so those local variables would no longer logically exist... but the async method would still effectively be able to use them in its continuations. Big problems. The compiler could create a new class to capture the variable in the same way that it does for lambda expressions, but that would cause other issues... aside from anything else, you could have a <em>local</em> variable changing at arbitrary points through a method, when continuations run on a different thread. Odd to say the least.</p> <p>Basically, it doesn't make sense to use <code>out</code> and <code>ref</code> parameters for <code>async</code> methods, due to the timing involved. Use a return type which includes all of the data you're interested in instead.</p> <p>If you're only interested in the <code>out</code> and <code>ref</code> parameters changing before the first <code>await</code> expression, you can always split the method in two:</p> <pre><code>public Task&lt;string&gt; FooAsync(out int x, ref int y) { // Assign a value to x here, maybe change y return FooAsyncImpl(x, y); } private async Task&lt;string&gt; FooAsyncImpl(int x, int y) // Not ref or out! { } </code></pre> <p>EDIT: It would be feasible to have <code>out</code> parameters using <code>Task&lt;T&gt;</code> and assign the value directly within the method just like return values. It would be a bit odd though, and it wouldn't work for <code>ref</code> parameters.</p>
26,399,783
How to properly execute a function inside ng-repeat
<p><strong>SITUATION:</strong></p> <p>I am making an app in AngularJs that assign permissions. In order to do this i have three nested ng-repeat.</p> <p><em>First loop</em>: display PERMISSION GROUP</p> <p><em>Second loop</em>: For each permission group display CATEGORIES. Inside this loop execute a function that will get all the SUB CATEGORIES for each category</p> <p><em>Third loop</em>: display SUB CATEGORIES</p> <p><strong>ISSUE:</strong></p> <p>The problem is in the execution of the function inside the second loop.</p> <p><strong>ATTEMPT 1 - ng-init:</strong></p> <pre><code>&lt;div class="row" ng-repeat="permission_group in list_permission_groups"&gt; &lt;div class="col-sm-3"&gt; &lt;h3&gt; {{permission_group.permission_group_name}} &lt;/h3&gt; &lt;/div&gt; &lt;div class="col-sm-9"&gt; &lt;ul&gt; &lt;li ng-repeat="category in list_categories"&gt; &lt;span&gt; {{ category.name }} &lt;/span&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;div ng-init="temp_result = get_Sub_Categories(category.category_id)"&gt; &lt;p ng-repeat="sub_category in temp_result"&gt; {{ sub_category.name }} &lt;/p&gt; &lt;/div&gt; &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>In the controller:</p> <pre><code>$scope.get_Sub_Categories = function(category_id) { $http({ url: base_url + 'main/json_get_list_sub_categories', data: { category_id: category_id }, method: "POST" }).success(function(data) { return data; }); } </code></pre> <p>Te behavior is quite strange. Porbably due to dirty checking the page is loaded 682 times. No result is displayed. </p> <p><strong>ATTEMPT 2 - ng-click: (only for debug)</strong> </p> <pre><code>&lt;div class="row" ng-repeat="permission_group in list_permission_groups"&gt; &lt;div class="col-sm-3"&gt; &lt;h3&gt; {{permission_group.permission_group_name}} &lt;/h3&gt; &lt;/div&gt; &lt;div class="col-sm-9"&gt; &lt;ul&gt; &lt;li ng-repeat="category in list_categories"&gt; &lt;span&gt; {{ category.name }} &lt;/span&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;button ng-click="get_Sub_Categories(category.category_id)"&gt; GET SUB-CATEGORIES &lt;/button&gt; {{ list_sub_categories }} &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>In the controller:</p> <pre><code>$scope.get_Sub_Categories = function(category_id) { $http({ url: base_url + 'main/json_get_list_sub_categories', data: { category_id: category_id }, method: "POST" }).success(function(data) { $scope.list_sub_categories = data; }); } </code></pre> <p>This time the page is loaded only once. If I press the button the proper sub-categories are displayed BUT of course not only for the corresponding category but FOR ALL, because i am modifying the var in the global scope.</p> <p><strong>THE AIM:</strong></p> <p>What I want to obtain is simply displaying all the proper sub-categories for each category. Without using a button, but simply see all the proper content as soon as the page load. But i don't understand how can this be done properly in AngularJs.</p> <p><strong>THE QUESTION:</strong></p> <p>How can i properly execute a function inside a ng-repeat that return and display different data for each loop?</p> <p><strong>EDIT</strong> - DUMP OF EXAMPLE OF SUB-CATEGORIES FOR ONE CATEGORY:</p> <pre><code>[{ "sub_category_id": "1", "name": "SUB_CATEGORY_1", "category_id_parent": "1", "status": "VISIBLE" }, { "sub_category_id": "2", "name": "SUB_CATEGORY_2", "category_id_parent": "1", "status": "VISIBLE" }, { "sub_category_id": "3", "name": "SUB_CATEGORY_3", "category_id_parent": "1", "status": "VISIBLE" }, { "sub_category_id": "4", "name": "SUB_CATEGORY_4", "category_id_parent": "1", "status": "VISIBLE" }] </code></pre>
26,400,951
4
5
null
2014-10-16 08:37:46.37 UTC
3
2016-02-15 03:01:25.107 UTC
2014-10-16 10:05:33.217 UTC
null
731,314
null
2,433,664
null
1
17
javascript|php|angularjs|angularjs-ng-repeat
65,177
<p>Calling a function inside ng-repeat is same as normal one. Since you need to display the sub categories at the time of page loading its better to get these data beforehand. Asynchronously loading sub categories will not fit into this scenario.</p> <p>Here is a minimal snippet achieving this (<a href="http://jsfiddle.net/Amitesh_Bharat/5m8pxtru/" rel="noreferrer">JS Fiddle</a>)</p> <pre><code>&lt;div ng-app="app" ng-controller="ctrl"&gt; &lt;div ng-repeat="category in model.categories"&gt; &lt;span&gt; Category: {{ category.name }} &lt;/span&gt; &lt;p ng-repeat="subCategory in getSubCategories(category.Id)"&gt;{{ subCategory.name }}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Controller</p> <pre><code>angular.module("app", []) .controller('ctrl', ['$scope', function ($scope) { $scope.model = { categories: [{ "Id": 1, name: '1' }, { "Id": 2, name: '2' }], subCategories: [{ "parentId": 1, name: 'a1' }, { "parentId": 1, name: 'a2' }, { "parentId": 2, name: 'a3' }] } $scope.getSubCategories = function(parentId){ var result = []; for(var i = 0 ; i &lt; $scope.model.subCategories.length ; i++){ if(parentId === $scope.model.subCategories[i].parentId){ result.push($scope.model.subCategories[i]); } } console.log(parentId) return result; }}]) </code></pre>
26,093,545
How to validate domain name using regex?
<p>This is my code for validating domain name.</p> <pre><code>function frmValidate() { var val = document.frmDomin; if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/.test(val.name.value)) { } else { alert("Enter Valid Domain Name"); val.name.focus(); return false; } } </code></pre> <p>and</p> <pre><code>&lt;form name="frmDomin" action="" method="post" onsubmit="return frmValidate();"&gt; Domain Name : &lt;input type="text" value="" id="name" name="name" /&gt; &lt;/form&gt; </code></pre> <p>Now I entered <code>http://devp1.tech.in</code> and it alert the message. I want to enter sub domain also. How to change this? I should not get alert.</p>
26,093,611
5
6
null
2014-09-29 06:14:01.893 UTC
2
2020-07-15 14:18:37.187 UTC
2017-06-01 09:33:46.8 UTC
null
2,724,961
null
1,416,847
null
1
15
javascript|regex
54,539
<p>Try this:</p> <pre><code>^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$ </code></pre> <p><a href="http://rubular.com/r/KByADagF3Z">Demo</a></p>
10,889,391
regex - get numbers after certain character string
<p>I have a text string that can be any number of characters that I would like to attach an order number to the end. Then I can pluck off the order number when I need to use it again. Since there's a possibility that the number is variable length, I would like to do a regular expression that catch's everything after the <code>=</code> sign in the string <code>?order_num=</code></p> <p>So the whole string would be</p> <pre><code>"aijfoi aodsifj adofija afdoiajd?order_num=3216545" </code></pre> <p>I've tried to use the online regular expression generator but with no luck. Can someone please help me with extracting the number on the end and putting them into a variable and something to put what comes before the <code>?order_num=203823</code> into its own variable.</p> <p>I'll post some attempts of my own, but I foresee failure and confusion. </p>
10,889,423
3
0
null
2012-06-04 22:40:46.33 UTC
5
2013-12-01 06:32:06.48 UTC
2012-06-04 22:59:37.343 UTC
null
20,938
null
1,252,748
null
1
12
javascript|regex
47,756
<pre><code>var s = "aijfoi aodsifj adofija afdoiajd?order_num=3216545"; var m = s.match(/([^\?]*)\?order_num=(\d*)/); var num = m[2], rest = m[1]; </code></pre> <p>But remember that regular expressions are <em>slow</em>. Use <code>indexOf</code> and <code>substring</code>/<code>slice</code> when you can. For example:</p> <pre><code>var p = s.indexOf("?"); var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p); </code></pre>
11,011,724
Java Object Assignment
<p>I am new to Java and I have some questions in mind regarding object assignment. For instance,</p> <pre><code>Test t1 = new Test(); Test t2 = t1; t1.i=1; </code></pre> <p>Assuming variable <code>i</code> is defined inside Test class, am I right to assume both t1 and t2 point to the same object where the modification <code>t1.i=1</code> affects both <code>t1</code> and <code>t2</code>? Actually I tested it out and seems like I was right. However when I try the same thing on <code>String</code>, the modification happens only on one side where the other side is unaffected. What is the reason behind this?</p> <p>Edit: The case I tried with String.</p> <pre><code>String s1 = "0"; String s2 = s1; s1 = "1"; System.out.println(s1); System.out.println(s2); </code></pre> <p>I realise my mistake by testing the cases on String since it is immutable. The situation where I thought <code>s1="1"</code> modify the string is in fact returning the reference of "1" to the s1. Nevertheless, my question remains. Does <code>Test t2 = t1;</code> cause both t2 and t1 point to the same object or each now have their own objects? Does this situation applies on all objects on Java?</p>
11,011,764
8
2
null
2012-06-13 09:15:45.44 UTC
12
2020-10-20 06:33:19.563 UTC
2012-06-13 09:37:04.073 UTC
user1238193
null
user1238193
null
null
1
24
java|object|pass-by-reference|variable-assignment
46,760
<p>You are right, but Strings are a special case; they are immutable and act like primitives in this case.</p> <p>@newacct</p> <p>I quote <a href="http://docs.oracle.com/javase/tutorial/java/data/strings.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/java/data/strings.html</a> :</p> <blockquote> <p>Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.</p> </blockquote> <p>This is what makes strings a special case. If you don't know this, you might expect the methods discussed in the quote not to return new strings, wich would lead to unexpected results.</p> <p>@user1238193</p> <p>Considering your following question: "Does Test t2 = t1; cause both t2 and t1 point to the same object or each now have their own objects? Does this situation applies on all objects on Java?"</p> <p>t1 and t2 will point to the same object. This is true for any java object (immutable objects included)</p>
11,268,930
How to git revert a commit using a SHA
<p>How can I revert a commit with a GIVEN SHA? I just want to remove the changes with a given SHA? I want to keep all the commits made BEFORE &amp; AFTER the give SHA. I just want to remove changes of that specified SHA.</p> <p>I have read <a href="https://stackoverflow.com/questions/1895059/git-revert-to-a-commit-by-sha-hash">Revert to a commit by a SHA hash in Git?</a>, my understanding is that reset all the commits made AFTER the SHA i want to revert. That is not way i want.</p>
11,268,992
3
0
null
2012-06-29 21:04:46.92 UTC
5
2020-06-27 20:29:29.883 UTC
2017-05-23 12:17:28.077 UTC
null
-1
null
286,802
null
1
28
git
28,744
<p>You can use <code>git revert &lt;commit hash&gt;</code> to try to revert the changes made by the commit. This will not remove the commit from history, just make changes to undo it as a new commit. In other words you will have the first commit still in history, and an additional commit on the head of your branch which is the effective inverse of the original commit.</p> <p>If you have not yet shared your changes with anyone else, then it is possible to remove the original offending commit from history altogether by using <code>git rebase</code>. There are details in <a href="https://stackoverflow.com/questions/37219/how-do-you-remove-a-specific-revision-in-the-git-history">this SO post</a>.</p>
11,138,927
Best way to limit the number of active Tasks running via the Parallel Task Library
<p>Consider a queue holding a <strong>lot</strong> of jobs that need processing. Limitation of queue is can only get 1 job at a time and no way of knowing how many jobs there are. The jobs take 10s to complete and involve a lot of waiting for responses from web services so is not CPU bound.</p> <p>If I use something like this</p> <pre><code>while (true) { var job = Queue.PopJob(); if (job == null) break; Task.Factory.StartNew(job.Execute); } </code></pre> <p>Then it will furiously pop jobs from the queue much faster than it can complete them, run out of memory and fall on its ass. >.&lt;</p> <p>I can't use (I don't think) <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.aspx" rel="noreferrer">ParallelOptions.MaxDegreeOfParallelism</a> because I can't use Parallel.Invoke or Parallel.ForEach </p> <p>3 alternatives I've found</p> <ol> <li><p>Replace Task.Factory.StartNew with</p> <pre><code>Task task = new Task(job.Execute,TaskCreationOptions.LongRunning) task.Start(); </code></pre> <p>Which seems to somewhat solve the problem but I am not <a href="https://stackoverflow.com/questions/3488381/does-the-task-parallel-library-or-plinq-take-other-processes-into-account">clear exactly what this is doing</a> and if this is the best method.</p></li> <li><p>Create a <a href="http://msdn.microsoft.com/en-us/library/ee789351.aspx" rel="noreferrer">custom task scheduler that limits the degree of concurrency</a></p></li> <li><p>Use something like <a href="http://msdn.microsoft.com/en-us/library/dd997371.aspx" rel="noreferrer">BlockingCollection</a> to add jobs to collection when started and remove when finished to limit number that can be running.</p></li> </ol> <p>With #1 I've got to trust that the right decision is automatically made, #2/#3 I've got to work out the max number of tasks that can be running myself.</p> <p>Have I understood this correctly - which is the better way, or is there another way?</p> <p><strong>EDIT</strong> - This is what I've come up with from the answers below, producer-consumer pattern.</p> <p>As well as overall throughput aim was not to dequeue jobs faster than could be processed and not have multiple threads polling queue (not shown here but thats a non-blocking op and will lead to huge transaction costs if polled at high frequency from multiple places).</p> <pre><code>// BlockingCollection&lt;&gt;(1) will block if try to add more than 1 job to queue (no // point in being greedy!), or is empty on take. var BlockingCollection&lt;Job&gt; jobs = new BlockingCollection&lt;Job&gt;(1); // Setup a number of consumer threads. // Determine MAX_CONSUMER_THREADS empirically, if 4 core CPU and 50% of time // in job is blocked waiting IO then likely be 8. for(int numConsumers = 0; numConsumers &lt; MAX_CONSUMER_THREADS; numConsumers++) { Thread consumer = new Thread(() =&gt; { while (!jobs.IsCompleted) { var job = jobs.Take(); job.Execute(); } } consumer.Start(); } // Producer to take items of queue and put in blocking collection ready for processing while (true) { var job = Queue.PopJob(); if (job != null) jobs.Add(job); else { jobs.CompletedAdding() // May need to wait for running jobs to finish break; } } </code></pre>
11,139,555
6
4
null
2012-06-21 13:10:51.557 UTC
12
2016-09-08 20:23:55.277 UTC
2017-05-23 12:02:22.183 UTC
null
-1
null
20,198
null
1
37
c#|.net|task-parallel-library
42,182
<p>I just gave an <a href="https://stackoverflow.com/questions/11099810/managing-the-tpl-queue/11100423#11100423">answer</a> which is very applicable to this question.</p> <p>Basically, the TPL Task class is made to schedule CPU-bound work. It is not made for blocking work.</p> <p>You are working with a resource that is not CPU: waiting for service replies. This means the TPL will mismange your resource because it assumes CPU boundedness to a certain degree.</p> <p>Manage the resources yourself: Start a fixed number of threads or LongRunning tasks (which is basically the same). Decide on the number of threads empirically.</p> <p><strong>You can't put unreliable systems into production.</strong> For that reason, I recommend #1 but <em>throttled</em>. Don't create as many threads as there are work items. Create as many threads which are needed to saturate the remote service. Write yourself a helper function which spawns N threads and uses them to process M work items. You get totally predictable and reliable results that way.</p>
13,037,126
javascript void functions
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1291942/what-does-javascriptvoid0-mean">What does “javascript:void(0)” mean?</a> </p> </blockquote> <p>I want to ask a few questions regarding <code>javascript:void(0)</code></p> <pre><code>&lt;input type='submit' name='btn' value='submit' onClick='javascript:void(0)' /&gt; </code></pre> <p>Can you please explain <code>void(0)</code> - is it a built-in function? Does the keyword <code>javascript</code> represent that the code is written in javascript? If there is anything weird that you know about it, please share it with me. Thank you.</p>
13,037,181
4
5
null
2012-10-23 18:47:00.463 UTC
2
2019-07-05 15:16:31.527 UTC
2019-07-05 15:16:31.527 UTC
null
10,445,697
null
1,370,507
null
1
7
javascript
39,470
<p><strong><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/void" rel="nofollow noreferrer">void()</a>:</strong></p> <blockquote> <p>This operator <strong>allows inserting expressions</strong> that produce side effects into places where an expression that evaluates to undefined is desired.</p> <p>The void operator is often <strong>used merely to obtain the undefined primitive value</strong>, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value). <strong>Note, however, that the javascript: pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers.</strong></p> </blockquote> <p>You can read more on this similar thread: <a href="https://stackoverflow.com/questions/1291942/what-does-javascriptvoid0-mean?lq=1">What does &quot;javascript:void(0)&quot; mean?</a></p>
13,051,204
Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction
<p>I have a method that has the <code>propagation = Propagation.REQUIRES_NEW</code> transactional property:</p> <pre><code>@Transactional(propagation = Propagation.REQUIRES_NEW) public void createUser(final UserBean userBean) { //Some logic here that requires modification in DB } </code></pre> <hr> <p>This method can be called multiple times simultaneously, and for every transaction if an error occurs than it's rolled back (independently from the other transactions).</p> <p>The problem is that this might force Spring to create multiple transactions, even if another one is available, and may cause some performance problems.</p> <hr> <p>Java doc of <code>propagation = Propagation.REQUIRED</code> says: <code>Support a current transaction, create a new one if none exists.</code></p> <p>This seems to solve the performance problem, doesn't it?</p> <p>What about the rollback issue ? What if a new method call rolls back while using an existing transaction ? won't that rollback the whole transaction even the previous calls ?</p> <p><strong>[EDIT]</strong> I guess my question wasn't clear enough:</p> <p>We have hundreds of clients connected to our server. </p> <p>For each client we naturally need to send a feedback about the transaction (OK or exception -> rollback). </p> <p>My question is: if I use <code>REQUIRED</code>, does it mean only one transaction is used, and if the 100th client encounters a problem the 1st client's transaction will rollback as well ?</p>
13,052,757
2
3
null
2012-10-24 14:22:12.853 UTC
29
2022-02-19 19:12:33.08 UTC
2014-07-12 00:30:19.977 UTC
null
1,438,628
null
1,438,628
null
1
65
java|spring|hibernate|transactions|spring-transactions
174,693
<p>Using <code>REQUIRES_NEW</code> is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as <code>REQUIRED</code> - it will create a new transaction.</p> <p>That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a <code>@Transactional</code>, it will create a new transaction.</p> <p>So, with that in mind, if using <code>REQUIRES_NEW</code> makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.</p> <p>On rollback - using <code>REQUIRES_NEW</code> will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: <a href="https://web.archive.org/web/20170213005145/http://www.ibm.com/developerworks/library/j-ts1/index.html" rel="noreferrer">«Transaction strategies: Understanding transaction pitfalls», Mark Richards</a>.</p>
12,647,891
How can you pass a bound variable to an ng-click function?
<p>I have a simple delete button that will accept a string or number but won't accept an ng-model variable ( not sure if that's the correct terminology ).</p> <pre><code>&lt;button class="btn btn-danger" ng-click="delete('{{submission.id}}')"&gt;delete&lt;/button&gt; </code></pre> <p>Which generates:</p> <pre><code>&lt;button class="btn btn-danger" ng-click="delete('503a9742d6df30dd77000001')"&gt;delete&lt;/button&gt; </code></pre> <p>However, nothing happens when I click. If I hard code a variable then it works just fine. I assume I'm just not doing things the "Angular" way, but I'm not sure what that way is :)</p> <p>Here's my controller code:</p> <pre><code>$scope.delete = function ( id ) { alert( 'delete ' + id ); } </code></pre>
12,648,221
2
0
null
2012-09-28 21:55:36.95 UTC
11
2018-06-23 23:20:23.38 UTC
null
null
null
null
1,607,717
null
1
73
javascript|angularjs
53,844
<p>You don't need to use curly brackets (<code>{{}}</code>) in the <code>ng-click</code>, try this:</p> <pre><code>&lt;button class="btn btn-danger" ng-click="delete(submission.id)"&gt;delete&lt;/button&gt; </code></pre>
12,955,222
How to trigger HTML button when you press Enter in textbox?
<p>So the code that I have so far is:</p> <pre><code>&lt;fieldset id="LinkList"&gt; &lt;input type="text" id="addLinks" name="addLinks" value="http://"&gt; &lt;input type="button" id="linkadd" name="linkadd" value="add"&gt; &lt;/fieldset&gt; </code></pre> <p>It is not in a <code>&lt;form&gt;</code> and is just as it is within a <code>&lt;div&gt;</code>. However when I type something into the <code>textbox</code> called "addLinks" I want the user to be able to press Enter and trigger the "linkadd" <code>button</code> which will then run a JavaScript function.<br /> How can I do this?<br /> Thanks</p> <p><strong>Edit:</strong> I did find this code, but it doesnt seem to work.</p> <pre><code>$("#addLinks").keyup(function(event){ if(event.keyCode == 13){ $("#linkadd").click(); } }); </code></pre>
12,955,267
14
4
null
2012-10-18 12:54:52.303 UTC
29
2022-06-14 00:14:58.48 UTC
2021-01-15 09:31:17.09 UTC
null
542,251
null
1,753,537
null
1
127
html|jquery|button|input|textbox
262,493
<pre><code>$(document).ready(function(){ $('#TextBoxId').keypress(function(e){ if(e.keyCode==13) $('#linkadd').click(); }); }); </code></pre>
16,961,838
Working with arrays in V8 (performance issue)
<p>I tried next code (it shows similar results in Google Chrome and nodejs):</p> <pre><code>var t = new Array(200000); console.time('wtf'); for (var i = 0; i &lt; 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf'); wtf: 27839.499ms undefined </code></pre> <p>I also runned next tests:</p> <pre><code>var t = []; console.time('wtf'); for (var i = 0; i &lt; 400000; ++i) {t.push(Math.random());} console.timeEnd('wtf'); wtf: 449.948ms undefined var t = []; console.time('wtf'); for (var i = 0; i &lt; 400000; ++i) {t.push(undefined);} console.timeEnd('wtf'); wtf: 406.710ms undefined </code></pre> <p>But in Firefox all looks fine with the first variant:</p> <pre><code>&gt;&gt;&gt; var t = new Array(200000); console.time('wtf'); ...{t.push(Math.random());} console.timeEnd('wtf'); wtf: 602ms </code></pre> <p>What happens in V8?</p> <p><strong>UPD</strong> <em>*</em> magically decreasing performance <em>*</em></p> <pre><code>var t = new Array(99999); console.time('wtf'); for (var i = 0; i &lt; 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf'); wtf: 220.936ms undefined var t = new Array(100000); t[99999] = 1; console.time('wtf'); for (var i = 0; i &lt; 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf'); wtf: 1731.641ms undefined var t = new Array(100001); console.time('wtf'); for (var i = 0; i &lt; 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf'); wtf: 1703.336ms undefined var t = new Array(180000); console.time('wtf'); for (var i = 0; i &lt; 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf'); wtf: 1725.107ms undefined var t = new Array(181000); console.time('wtf'); for (var i = 0; i &lt; 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf'); wtf: 27587.669ms undefined </code></pre>
16,962,031
2
9
null
2013-06-06 12:15:13.323 UTC
13
2022-09-03 05:59:08.737 UTC
2013-06-06 12:39:29.24 UTC
null
2,027,961
null
2,027,961
null
1
28
javascript|arrays|google-chrome|firefox|v8
6,756
<p>If you preallocate, do not use <code>.push</code> because you will create a sparse array backed by a hashtable. <a href="https://github.com/v8/v8/blob/abfa9f17410a2a84c2ac3364e0288f4a8311b9b1/src/objects.h#L2411" rel="noreferrer">You can preallocate sparse arrays up to 99999 elements</a> which will be backed by a C array, after that it's a hashtable.</p> <p>With the second array you are adding elements in a contiguous way starting from 0, so it will be backed by a real C array, not a hash table.</p> <p>So roughly:</p> <p>If your array indices go nicely from 0 to Length-1, with no holes, then it can be represented by a fast C array. If you have holes in your array, then it will be represented by a much slower hash table. The exception is that if you preallocate an array of size &lt; 100000, then you can have holes in the array and still get backed by a C array:</p> <pre><code>var a = new Array(N); //If N &lt; 100000, this will not make the array a hashtable: a[50000] = "sparse"; var b = [] //Or new Array(N), with N &gt;= 100000 //B will be backed by hash table b[50000] = "Sparse"; //b.push("Sparse"), roughly same as above if you used new Array with N &gt; 0 </code></pre>
16,751,772
How do I use Travis-CI with C# or F#
<p>Travis CI continuous integration service officially supports many <a href="http://about.travis-ci.org/docs/#Specific-Language-Help" rel="noreferrer">languages</a>, but not C# or F#. </p> <p>Can I use it with my .net projects?</p>
27,413,136
5
0
null
2013-05-25 16:48:39.12 UTC
58
2017-06-22 13:37:13.443 UTC
2014-03-22 13:57:50.177 UTC
null
637,783
null
637,783
null
1
92
c#|f#|mono|travis-ci
14,626
<p>Travis CI now <a href="http://docs.travis-ci.com/user/languages/csharp/" rel="noreferrer">supports C#</a>. Quoting liberally from that page:</p> <blockquote> <h1>Overview</h1> <p>The setup for C#, F#, and Visual Basic projects looks like this:</p> </blockquote> <pre><code>language: csharp solution: solution-name.sln mono: - latest - 3.12.0 - 3.10.0 </code></pre> <blockquote> <h1>Script</h1> <p>By default Travis will run xbuild solution-name.sln. Xbuild is a build tool designed to be an implementation for Microsoft's MSBuild tool. To override this, you can set the script attribute like this:</p> </blockquote> <pre><code>language: csharp solution: solution-name.sln script: ./build.sh </code></pre> <blockquote> <h1>NuGet</h1> <p>By default, Travis will run nuget restore solution-name.sln, which restores all NuGet packages from your solution file. To override this, you can set the install attribute like this:</p> </blockquote> <pre><code>language: csharp solution: solution-name.sln install: - sudo dosomething - nuget restore solution-name.sln </code></pre>
25,700,971
Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root
<p>I am not sure how to fix this:</p> <pre><code>dyn-72-33-214-45:python mona$ sudo /usr/local/mysql/bin/mysqld stop 2014-09-06 09:49:04 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). 2014-09-06 09:49:04 22992 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/mysql-5.6.15-osx10.7-x86_64/data/ is case insensitive 2014-09-06 09:49:04 22992 [ERROR] Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root! 2014-09-06 09:49:04 22992 [ERROR] Aborting 2014-09-06 09:49:04 22992 [Note] Binlog end 2014-09-06 09:49:04 22992 [Note] /usr/local/mysql/bin/mysqld: Shutdown complete </code></pre>
26,450,522
14
9
null
2014-09-06 13:50:58.353 UTC
15
2022-01-04 08:49:13.66 UTC
null
null
null
null
2,414,957
null
1
60
mysql|sql|my.cnf
161,084
<p>I'm using OS X (Yosemite) and this error happened to me when I upgraded from Mavericks to Yosemite. It was solved by using this command</p> <pre><code>sudo /usr/local/mysql/support-files/mysql.server start </code></pre>
58,010,655
Is adb remount broken on android api 29?
<p><code>adb remount</code> does not work correctly on api 29 when running from the emulator. The command works fine on all other emulators that have been tried (18, 23, 25, 26, 27 and 28).</p> <p>Any ideas why this might be?</p> <pre><code>Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services W Disabling verity for /system E Skipping /system Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services Skip mounting partition: /product Skip mounting partition: /product_services /system/bin/remount exited with status 7 remount failed </code></pre>
61,375,430
2
3
null
2019-09-19 12:05:51.963 UTC
18
2021-01-23 21:03:56.28 UTC
null
null
null
null
12,090,237
null
1
58
android|android-emulator|adb|android-10.0
9,900
<h2>Update:</h2> <p>See @KiddTang answer which seems to be an actual solution</p> <hr /> <ul> <li><p>This issue is still occurring now even with API 30 (API R)! And even when starting emulator with writable-system option: (<code>emulator -writable-system -avd NAME_OF_DEVICE</code>)!</p> <ul> <li>I found there is an <a href="https://issuetracker.google.com/issues/144891973" rel="nofollow noreferrer">existing issue</a> for it in Google's issue tracker.</li> </ul> </li> <li><p>I tried following these <a href="https://android.googlesource.com/platform/system/core/+/master/fs_mgr/README.overlayfs.md" rel="nofollow noreferrer">instructions</a> to disable-verity and reboot before remounting</p> <ul> <li>However this solution caused my emulator to freeze/hang, and never booting.</li> </ul> </li> </ul> <p><strong>Note:</strong> I am experiencing the current issue when using the emulator with the &quot;AVD&quot; provided &quot;Android Sdk Images&quot;. Its possible however that this kind of images are limited somewhat. So it might not occur for other types of Android Images</p> <hr /> <h2>Summary of Code from Link:</h2> <ul> <li>This code <strong>did not work for my situation</strong>, as it causes the emulator to freeze and wont start after rebooting, however, they may work others. <ul> <li>See the <a href="https://android.googlesource.com/platform/system/core/+/master/fs_mgr/README.overlayfs.md" rel="nofollow noreferrer">link</a> for additional details and caveats.</li> </ul> </li> <li>Use the following sequence to perform the remount.</li> </ul> <pre><code>$ adb root $ adb disable-verity $ adb reboot $ adb wait-for-device $ adb root $ adb remount </code></pre> <ul> <li>Then enter one of the following sequences:</li> </ul> <pre><code>$ adb shell stop $ adb sync $ adb shell start $ adb reboot </code></pre> <ul> <li>or</li> </ul> <pre><code>$ adb push &lt;source&gt; &lt;destination&gt; $ adb reboot </code></pre> <ul> <li>Note that you can replace these two lines in the above sequence:</li> </ul> <pre><code>$ adb disable-verity $ adb reboot </code></pre> <ul> <li>with this line:</li> </ul> <pre><code>$ adb remount -R </code></pre> <p><strong>Note</strong>: adb remount -R won’t reboot if the device is already in the adb remount state.</p>
4,095,504
Programmatically skip an NUnit test
<p>Is there a way for an NUnit test to end and tell the test runner that it should be considered skipped/ignored, rather than succeeded or failed?</p> <p>My motivation for this is that I have a few tests that don't apply in certain circumstances, but this can't be determined until the test (or maybe the fixture) starts running.</p> <p>Obviously in these circumstances I could just return from the test and allow it to succeed, but (a) this seems wrong and (b) I'd like to know that tests have been skipped.</p> <p>I am aware of the [Ignore] attribute, but this is compiled-in. I'm looking for a run-time, programmatic equivalent. Something like:</p> <pre><code>if (testNotApplicable) throw new NUnit.Framework.IgnoreTest(&quot;Not applicable&quot;); </code></pre> <p>Or is programmatically skipping a test just wrong? If so, what should I be doing?</p>
4,095,528
2
0
null
2010-11-04 10:00:24.503 UTC
4
2021-03-22 07:37:24.867 UTC
2021-03-22 07:37:24.867 UTC
null
1,402,846
null
67,316
null
1
47
.net|unit-testing|nunit
17,195
<pre><code>Assert.Ignore(); </code></pre> <p>is specifically what you're asking for, though there is also:</p> <pre><code>Assert.Inconclusive(); </code></pre>
10,191,506
Internet Explorer Automation with VBA input events
<p>am trying to use automation in from Microsoft Access 2003 to control Internet Explorer 9 to complete a form using database data. </p> <p>The input fires an event in the browser which validates the data and makes the save button visible. If I use sendkeys the event is triggered; however, I have found sendkeys to be very unreliable. If I change the value of the element and then use .fireevent ("onchange"), nothing happens – not even an error.</p> <p>My question is, how do I fire the event. Or, how can I find out what javascript is running. Is there a debug type of addin for IE which will tell me what event is fired? If so, can I just run the script myself? </p> <p>My code is below. </p> <pre><code> Set IE = CreateObject("internetexplorer.application") IE.Visible = True IE.Navigate "https://extranet.website.com/Planning/Edition/Periodic?language=en" Do While IE.ReadyState &lt;&gt; 4 Or IE.Busy = True DoEvents Loop 'log in If IE.Document.Title = "website- access" Then IE.Document.getElementById("login_uid").Value = "username" IE.Document.getElementById("login_pwd").Value = "password" IE.Document.all("ButSubmit").Click Do While IE.ReadyState &lt;&gt; 4 Or IE.Busy = True DoEvents Loop End If Do While Not RstAvailability.EOF StartDate = RstAvailability!AvailDate IE.Document.getElementById("periodStart").Value = Format(StartDate, "dd mmm yy") IE.Document.getElementById("periodEnd").Value = Format(StartDate, "dd mmm yy") Set LinkCollection = IE.Document.GetElementsByTagName("A") For Each link In LinkCollection If link.innertext = "Add" Then link.Click Exit For End If Next Do While IE.ReadyState &lt;&gt; 4 Or IE.Busy = True DoEvents Loop Set objRows = IE.Document.GetElementsByTagName("tr") If RstAvailability!RoomType = "DTW" Then n = 0 While n &lt; objRows.Length If Trim(objRows(n).Cells(0).innertext) = "Single Room" Then For i = 1 To 7 'objRows(n).FireEvent ("onchange") 'objRows(n).Cells(i).GetElementsByTagName("input")(0).Focus 'SendKeys Format(RstAvailability!roomcount - RstAvailability!RoomsSold, "0") &amp; "{TAB}" objRows(n).Cells(i).GetElementsByTagName("input")(0).Value = Format(RstAvailability!roomcount - RstAvailability!RoomsSold, "0") objRows(n).Cells(i).GetElementsByTagName("input")(0).fireevent ("onchange") Do While IE.ReadyState &lt;&gt; 4 Or IE.Busy = True DoEvents Loop Next i End If n = n + 1 Wend End If Set objButtons = IE.Document.getelementsbyname("savePlanning") objButtons(0).Click Do While IE.ReadyState &lt;&gt; 4 Or IE.Busy = True DoEvents Loop newtime = Now + TimeValue("0:00:10") Do While True If Now &gt; newtime Then Exit Do Loop RstAvailability.MoveNext Loop </code></pre> <p>The html of the input fields are:</p> <pre><code>&lt;tr class="first" roomId="30494" articleId="0" type="Availability" readonly="False"&gt; </code></pre> <p></p> <pre><code>&lt;div&gt; &lt;span class="roomName"&gt; Single Room &lt;/span&gt; &lt;/div&gt; </code></pre> <p></p> <p></p> <pre><code>&lt;span class="data"&gt; </code></pre> <p></p> <pre><code>&lt;input id="Availabilities" name="Availabilities" type="text" value="" /&gt; </code></pre> <p></p> <p></p> <pre><code>&lt;/span&gt; </code></pre> <p></p> <p></p> <pre><code>&lt;span class="data"&gt; </code></pre> <p></p> <pre><code>&lt;input id="Availabilities" name="Availabilities" type="text" value="" /&gt; </code></pre> <p></p> <p></p> <pre><code>&lt;/span&gt; </code></pre> <p></p> <p>Thanks!</p>
10,258,397
2
0
null
2012-04-17 12:44:28.933 UTC
4
2016-03-23 18:42:05.307 UTC
2012-04-20 18:09:27.923 UTC
null
290,504
null
290,504
null
1
6
internet-explorer|vba|automation
50,979
<p>After sweating over this for a few days, the answer was actually very simple but nearly impossible to find in any documentation on MSDN or anywhere else on the web. </p> <p>Before you change the value of the input field, you net to set the focus on that field. After you change the value, you need to set the focus to another field. Apparently, the events fire on the loss of focus. Therefore, the code should look like this:</p> <pre><code> n = 0 While n &lt; objRows.Length If Trim(objRows(n).Cells(0).innertext) = "Family Room" Then For i = 1 To 7 objRows(n).Cells(i).GetElementsByTagName("input")(0).Focus objRows(n).Cells(i).GetElementsByTagName("input")(0).Value = Format(RstAvailability!roomcount - RstAvailability!RoomsSold, "0") Next i objRows(n).Cells(1).GetElementsByTagName("input")(0).Focus End If n = n + 1 Wend </code></pre> <p>The way I found this was by looking at some MSDN documentation about accessibility for IE9. It was advising on setting the focus for disabled users. I just thought I would give this a try and it worked. I hope this helps someone else.</p> <p>Dave</p>
9,784,683
Android external camera options - overlay on top of video stream, no middleman server/router
<p>I'm looking for a way to interface with an external camera from an Android device. The reason it needs to be an external camera is because I need to be able to modify the camera (remove IR filter) and I have no desire to break an on-board phone camera. </p> <p>It doesn't matter how the camera connects whether it is through USB, bluetooth, WiFi, or some other communication protocol, the two devices just need to be able to talk without having a middleman server/router. </p> <p>I'm looking for a solution that:</p> <ul> <li>Doesn't require rooting or rebuilding Android/the Linux Kernel (absolute must)</li> <li>Allows me to overlay items over the image/video (good)</li> <li>Access the video stream to do image analysis (best)</li> </ul> <p>The last requirement isn't required but would be nice.</p> <p>Options I have explored:</p> <ul> <li>USB camera: rebuilt Linux Kernel as per <a href="http://brain.cc.kogakuin.ac.jp/research/usb-e.html" rel="nofollow noreferrer">http://brain.cc.kogakuin.ac.jp/research/usb-e.html</a> and tried using provided code using camera: <a href="https://rads.stackoverflow.com/amzn/click/com/B002X3VEIE" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/gp/product/B002X3VEIE/ref=oh_o02_s00_i00_details</a>. Did not work in the slightest bit. I later learned that the author used the CM9 mod however this really isn't an option given that it isn't practical for an app in the market.</li> <li>Bluetooth camera: <a href="http://looxcie.com/" rel="nofollow noreferrer">Looxcie</a> and <a href="http://contour.com/products/contour-gps" rel="nofollow noreferrer">CountourGPS</a> look like the best options however the feed is streamed to their app and they have no API or SDK so how can one overlay on their video feed?</li> <li>IP camera: to me this looks like the most promising option but how can one access an IP cameras video feed without a middleman server/router? <a href="http://gopro.com/cameras/hd-hero2-outdoor-edition/" rel="nofollow noreferrer">GoPro HD Hero2 with WiFi BacPac</a> looks potentially promising but it isn't out yet and from what I can tell requires you to use their app similar to the bluetooth camera options. What cameras exist that allow me to connect to them and receive a direct video feed and how do I go about this programmatically?</li> </ul> <p>If connection to an IP camera without the middleman is possible the code at <a href="https://stackoverflow.com/questions/3205191/android-and-mjpeg">Android and MJPEG</a> and <a href="https://stackoverflow.com/questions/4490707/getting-ip-cam-video-stream-on-android-mjepg">Getting IP Cam video stream on Android (MJEPG)</a> looks promising.</p> <p>Can I overlay on top of another apps video feed? Is it possible to connect directly to an IP camera? Any suggested options greatly appreciated. </p>
10,570,501
2
0
null
2012-03-20 10:05:56.243 UTC
9
2012-05-13 08:59:08.52 UTC
2017-05-23 12:25:39.467 UTC
null
-1
null
1,233,435
null
1
15
android|bluetooth|camera|usb|ip-camera
38,103
<p>I ended up opting for the IP camera option as it seemed to be the only viable option.</p> <p>I was able to purchase <a href="https://rads.stackoverflow.com/amzn/click/com/B00452V66G" rel="nofollow noreferrer" rel="nofollow noreferrer" title="this">this</a> camera and remove the IR filter by removing the glue at the base of the lens and then breaking the IR filter out.</p> <p>I was able to connect the camera to ICS using the AndroidAP hotspot and to older Android devices using an ad-hoc network setup on the camera (you have to manually set IP addresses, etc for ad-hoc and it's a pain).</p> <p>As for getting MJPEG working in an app on ICS I made <a href="https://stackoverflow.com/questions/10550139/android-ics-and-mjpeg-using-asynctask%20these">these</a> modifications to the code I found on SO.</p> <p>Lastly the app needs to be able to turn the AP on and off which I have not finished yet but <a href="http://www.diyphonegadgets.com/2011/11/programmatically-enable-and-configure.html%20here" rel="nofollow noreferrer">here</a> is some code to start with.</p>
9,896,216
Deploy Sinatra app on Heroku
<p>I have simple Sinatra app.</p> <p><strong>web.rb:</strong></p> <pre><code>require 'sinatra' get '/' do "Hello" end </code></pre> <p><strong>Gemfile:*</strong></p> <pre><code>source :rubygems gem 'sinatra', '1.1.0' gem 'thin', '1.2.7' </code></pre> <p><strong>config.ru:</strong></p> <pre><code>require './web' run Sinatra::Application </code></pre> <p>But when I deploy my app on Heroku I'll get the error on logs:</p> <pre><code>2012-03-27T19:17:48+00:00 heroku[router]: Error H14 (No web processes running) -&gt; GET furious-waterfall-6586.herokuapp.com/ dyno= queue= wait= service= status=503 bytes= </code></pre> <p>How can I fix it?</p>
9,896,773
5
4
null
2012-03-27 19:22:11.413 UTC
14
2018-04-08 21:58:07.567 UTC
2012-03-27 20:07:22.673 UTC
null
25,066
null
205,270
null
1
16
ruby|heroku|sinatra
11,956
<p>You need a <code>Procfile</code> file alongside your <code>config.ru</code> to tell Heroku how to run your app. Here is the content of an example <code>Procfile</code>:</p> <pre><code>web: bundle exec ruby web.rb -p $PORT </code></pre> <p><a href="https://devcenter.heroku.com/articles/procfile" rel="nofollow noreferrer">Heroku Ruby docs on Procfiles</a></p> <p>EDIT: Here's a sample <code>config.ru</code> from one of my sinatra/Heroku apps:</p> <pre><code>$:.unshift File.expand_path("../", __FILE__) require 'rubygems' require 'sinatra' require './web' run Sinatra::Application </code></pre> <p>You may need to require sinatra and rubygems for it to work. </p>
9,734,384
Default timeout for HttpComponent Client
<p>I can't find any documentation on the default httpParams for httpclient 4.1 ?</p> <p>What's the default socket timeout when I do a GET ? </p>
9,734,836
5
0
null
2012-03-16 09:04:20.727 UTC
3
2021-01-29 14:15:33.67 UTC
null
null
null
null
356,899
null
1
23
java|apache-httpcomponents
52,334
<p>According to the <a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html" rel="noreferrer">documentation</a>, the <code>http.socket.timeout</code> parameter controls the SO_TIMEOUT value, and:</p> <blockquote> <p>If this parameter is not set, read operations will not time out (infinite timeout).</p> </blockquote>
10,137,214
How get next (previous) element in std::list without incrementing (decrementing) iterator?
<p>Say I have an <code>std::list&lt;int&gt; lst</code> and some <code>std::list&lt;int&gt;::iterator it</code> for iterating through the list. And depended to value of the <code>it</code> I want to use <code>it + 1</code> or <code>it - 1</code> in my code. Is there some good way to do that like <code>next()</code>, <code>prev()</code> (I couldn't find such things in stl documentation)? Or should I copy the <code>it</code> each time and increment(decrement) the copy?</p>
10,137,694
3
6
null
2012-04-13 08:00:34.11 UTC
3
2012-04-13 08:37:58.617 UTC
2012-04-13 08:02:13.133 UTC
null
427,328
null
509,233
null
1
51
c++|list|iterator
46,781
<p>Copying and incrementing/decrementing the copy is the only way it can be done.</p> <p>You can write wrapper functions to hide it (and as mentioned in answers, C++11 has std::prev/std::next which do just that (and Boost defines similar functions). But they are wrappers around this "copy and increment" operation, so you don't have to worry that you're doing it "wrong".</p>
9,802,788
Call a REST API in PHP
<p>Our client had given me a REST API to which I need to make a PHP call. But as a matter of fact, the documentation given with the API is very limited, so I don't really know how to call the service.</p> <p>I've tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in-depth information.</p> <p>Is there any decent information around how to call a REST API or some documentation about it? Because even in W3schools, they only describe the SOAP method. What are different options for making the rest of API in PHP?</p>
9,802,854
12
0
null
2012-03-21 10:33:38.28 UTC
204
2022-02-25 00:14:44.67 UTC
2022-02-25 00:14:44.67 UTC
null
17,079,652
null
452,421
null
1
387
php|rest|web-services
941,770
<p>You can access any REST API with PHPs <code>cURL</code> Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!</p> <p>Example:</p> <pre><code>// Method: POST, PUT, GET etc // Data: array("param" =&gt; "value") ==&gt; index.php?param=value function CallAPI($method, $url, $data = false) { $curl = curl_init(); switch ($method) { case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_PUT, 1); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); } // Optional Authentication: curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_USERPWD, "username:password"); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return $result; } </code></pre>
8,141,795
How to add an assembly manifest to a .NET executable?
<p>How can i add an assembly manifest to my .NET executable?</p> <hr> <p>An assembly manifest is is an XML file that is added to a .NET portable executable (PE) with resource type <code>RT_MANIFEST</code> (24). </p> <p>Assembly manifests are used to declare a number of things about the executable, e.g.:</p> <ul> <li><p>If i want to disable DPI-scaling because i am a good developer:</p> <pre><code>&lt;!-- We are high-dpi aware on Windows Vista --&gt; &lt;asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3"&gt; &lt;asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings"&gt; &lt;dpiAware&gt;true&lt;/dpiAware&gt; &lt;/asmv3:windowsSettings&gt; &lt;/asmv3:application&gt; </code></pre></li> <li><p>i can declare that i was designed and tested on Windows 7, and i should continue to depend on any bugs in Windows 7</p> <pre><code>&lt;!-- We were designed and tested on Windows 7 --&gt; &lt;compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"&gt; &lt;application&gt; &lt;!--The ID below indicates application support for Windows 7 --&gt; &lt;supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/&gt; &lt;/application&gt; &lt;/compatibility&gt; </code></pre></li> <li><p>i can declare that i am a good developer, and don't need file and registry virtualization</p> <pre><code>&lt;!-- Disable file and registry virtualization --&gt; &lt;trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"&gt; &lt;security&gt; &lt;requestedPrivileges&gt; &lt;requestedExecutionLevel level="asInvoker" uiAccess="false"/&gt; &lt;/requestedPrivileges&gt; &lt;/security&gt; &lt;/trustInfo&gt; </code></pre></li> <li><p>i can declare that i depend on a particular version 6 of the <strong>Microsoft Common Controls</strong> library:</p> <pre><code>&lt;!-- Dependency on Common Controls version 6 --&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*"/&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; </code></pre></li> <li><p>i can declare that i depend on a particular version of GDI+:</p> <pre><code>&lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.GdiPlus" version="1.0.0.0" processorArchitecture="x86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; </code></pre></li> </ul> <hr> <p><a href="https://stackoverflow.com/questions/8057080/vs2010-net-how-to-embed-a-resource-in-a-net-pe-executable">In the olden days</a>, we would create a <strong>resource script</strong> file (<code>*.rc</code>), e.g.:</p> <p><strong>wumpa.rc</strong></p> <pre><code> 1 24 AssemblyManifest.xml </code></pre> <p>add that file to the project, and the compiler would compile the <code>.rc</code> file; including resources in the final executable image.</p> <p>Except <a href="https://stackoverflow.com/questions/8057080/vs2010-net-how-to-embed-a-resource-in-a-net-pe-executable">Visual Studio 2010 doesn't seem to have a way to add a resource script file to a project</a>.</p> <p>How do i add a resource script to a project in Visual Studio 2010?</p> <p>How do i add an assembly manifest to a project in Visual Studio 2010?</p> <p><strong>Note</strong>: Any solution must work in an environment with source control and multiple developers (e.g. hard-coded paths to probably not installed binaries will break the build and not work).</p> <h2>Bonus Chatter</h2> <ul> <li><a href="https://stackoverflow.com/questions/8057080/vs2010-net-how-to-embed-a-resource-in-a-net-pe-executable">VS2010/.NET: How to embed a resource in a .NET PE executable?</a></li> <li>VS2005: <a href="http://blogs.msdn.com/b/cheller/archive/2006/08/24/how-to-embed-a-manifest-in-an-assembly-let-me-count-the-ways.aspx" rel="noreferrer">How to embed a manifest in an assembly: let me count the ways...</a> (can't be done)</li> </ul> <hr> <p><strong>Update</strong>: Michael Fox suggests that the project properties dialog can be used to include an assembly manifest, but he doesn't indicate <em>where</em>:</p> <p><img src="https://i.stack.imgur.com/35ZMM.png" alt="enter image description here"></p> <hr> <p><strong>Update</strong>: Things I've tried:</p> <ul> <li>From the project properties screen, select <strong>Application</strong>. Select radio option <strong>Icon and Manifest</strong>. Under <strong>Manifest</strong> leave the default option of <code>Embed manifest with default settings</code>:</li> </ul> <p><a href="https://i.stack.imgur.com/5iEt5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5iEt5.png" alt="enter image description here"></a></p> <p><em>Doesn't work because it embeds a manifest with <strong>default</strong> settings, rather than my settings.</em></p> <ul> <li><p>Under <strong>Manifest</strong>, change the combo option to <code>Create application without a manifest</code>:</p> <p><img src="https://i.stack.imgur.com/i2acY.png" alt="enter image description here"></p> <p><em>Doesn't work because it embeds no manifest</em></p></li> <li><p>Under <strong>Resources</strong> select the <strong>Resource File</strong> radio option:</p> <p><img src="https://i.stack.imgur.com/0cW3X.png" alt="enter image description here"></p> <p><em>Doesn't work because you cannot select an assembly manifest (or a resource script that includes an assembly manifest)</em></p></li> <li><p>Under <strong>Resources</strong>, select the <strong>Resource File</strong> radio option, then enter the path to an assembly manifest XML file:</p></li> </ul> <p><a href="https://i.stack.imgur.com/cZ2Sf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cZ2Sf.png" alt="enter image description here"></a></p> <p><em>Doesn't work because Visual Studio chokes when presented with an assembly manifest</em>:</p> <p><a href="https://i.stack.imgur.com/uRzHs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uRzHs.png" alt="enter image description here"></a></p> <ul> <li>Under <strong>Resources</strong>, select the <strong>Resource File</strong> radio option, then enter the path to a resource script file:</li> </ul> <p><a href="https://i.stack.imgur.com/kpcGM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kpcGM.png" alt="enter image description here"></a></p> <p><em>Doesn't work because Visual Studio chokes when presented with a resource script</em>:</p> <p><a href="https://i.stack.imgur.com/a8E6a.png" rel="noreferrer"><img src="https://i.stack.imgur.com/a8E6a.png" alt="enter image description here"></a></p> <ul> <li><p>Add the <code>AssemblyManifest.xml</code> to my project, then look for it in the <strong>Manifest</strong> combo box:</p> <p><img src="https://i.stack.imgur.com/ITG9a.png" alt="enter image description here"></p> <p><em>Doesn't work because the Assembly Manifest file isn't listed as an option</em></p></li> </ul> <blockquote> <p>i have a dozen other things i can keep screenshotting (add a .rc file to the solution, look for it in the dropdown, select "no manifest" and change the <code>wumpa.rc</code> build action to various things, build the <code>.rc</code> file using a separate resource compiler, either manually, or a pre-build/msbuild step, and select that <code>.res</code> file as my resource). i'll stop adding extra bulk to my question and hope for an answer.</p> </blockquote>
8,844,086
3
2
null
2011-11-15 19:12:39.027 UTC
8
2015-11-27 18:15:33.73 UTC
2017-05-23 10:31:26.04 UTC
null
-1
null
12,597
null
1
33
visual-studio-2010|manifest|fusion
47,542
<p>If you want to add custom information to your application's manifest, you can follow these steps:</p> <ol> <li>Right-click on the project in the Solution Explorer.</li> <li>Click "Add New Item".</li> <li>Select "Application Manifest File".</li> </ol> <p>This adds a file named <code>app.manifest</code> to your project, which you can open and modify as desired.</p> <hr> <p>Similar steps, with screenshots, lifted from <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ee308410%28v=vs.85%29.aspx" rel="noreferrer">Declaring Managed Applications As DPI-Aware</a> on MSDN:</p> <ol> <li><p>In the Solution Explorer, right-click on your project, point to <strong>Add</strong>, and then click <strong>New Item</strong>.</p></li> <li><p>In the <strong>Add New Item</strong> dialog box, select <strong>Application Manifest File</strong>, and then click <strong>Add</strong>. The app.manifest file appears.</p> <p><img src="https://i.stack.imgur.com/U9O57.png" alt="enter image description here"></p></li> <li><p>Copy and paste the following text into the <strong>app.manifest</strong> file and then save.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;assemblyIdentity version="1.0.0.0" name="MyApplication.app"/&gt; &lt;!-- Disable file and registry virtualization. --&gt; &lt;trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"&gt; &lt;security&gt; &lt;requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"&gt; &lt;requestedExecutionLevel level="asInvoker" uiAccess="false" /&gt; &lt;!-- &lt;requestedExecutionLevel level="asInvoker" uiAccess="false" /&gt; &lt;requestedExecutionLevel level="requireAdministrator" uiAccess="false" /&gt; &lt;requestedExecutionLevel level="highestAvailable" uiAccess="false" /&gt; --&gt; &lt;/requestedPrivileges&gt; &lt;/security&gt; &lt;/trustInfo&gt; &lt;!-- We are high-dpi aware on Windows Vista --&gt; &lt;asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3"&gt; &lt;asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings"&gt; &lt;dpiAware&gt;true&lt;/dpiAware&gt; &lt;/asmv3:windowsSettings&gt; &lt;/asmv3:application&gt; &lt;!-- Declare that we were designed to work with Windows Vista and Windows 7--&gt; &lt;compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"&gt; &lt;application&gt; &lt;!--The ID below indicates application support for Windows Vista --&gt; &lt;supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/&gt; &lt;!--The ID below indicates application support for Windows 7 --&gt; &lt;supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/&gt; &lt;/application&gt; &lt;/compatibility&gt; &lt;!-- Enable themes for Windows common controls and dialogs (Windows XP and later) --&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;/asmv1:assembly&gt; </code></pre></li> <li><p>In the Solution Explorer, right-click on the <strong>project</strong>, and then click <strong>Properties</strong> to verify that the <strong>app.manifest</strong> is used.</p> <p><img src="https://i.stack.imgur.com/u81Mg.png" alt="enter image description here"></p></li> <li><p>Your application is now manifested as required to be "designed for Windows", and is</p> <ul> <li>disables file and registry virtualization</li> <li>disables DWM scaling of applications</li> <li>announces that you were designed and tested on Windows 7 and Windows Vista</li> <li>takes a dependency on Common Controls library version 6 (enabling the use of visual styles by the common controls)</li> </ul></li> </ol>
11,619,545
jQuery loop through Child divs
<pre><code>&lt;div id="ChosenCategory" class="chosen"&gt; &lt;div class="cat_ch" name="1"&gt; &lt;div class="cat_ch" name="2"&gt; &lt;div class="cat_ch" name="3"&gt; &lt;div class="cat_ch" name="5"&gt; &lt;div class="clear"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to loop though <code>div.cat_ch</code> How?</p> <p>This one fails:</p> <pre><code> $("div").each(function () { alert("FW"); alert($(this).attr("name").val()); }); </code></pre>
11,619,756
8
3
null
2012-07-23 19:55:59.167 UTC
null
2015-10-22 18:10:30.457 UTC
null
null
null
null
842,767
null
1
10
javascript|jquery|loops|html|each
40,828
<p><a href="http://jsfiddle.net/2TRxh/" rel="nofollow">http://jsfiddle.net/2TRxh/</a></p> <p>I think your issue lies with the attempt to get the val off the div after you get the attribute <code>$(this).attr("name").val()</code>. Using <code>.val()</code> on a div doesn't make sense. If you remove that <code>$(this).attr("name")</code> returns the <code>name</code> property off the divs. You can further specify the div's to loop through by using the class selector in your each rather than just div. <code>$(".cat_ch").each(function () {});</code> This has been shown in various other answers to this question. </p>
11,689,800
extra white space between tables in html email for gmail client
<p>My code is at</p> <p><a href="http://jsfiddle.net/user1212/G86KE/4/" rel="noreferrer">http://jsfiddle.net/user1212/G86KE/4/</a></p> <p>The problem is in gmail it leaves an extra white space between 2 tables inside the same cell. I have tried <code>display:block; margin:0; padding:0; line-height:0;</code></p> <p>However , it does not seem to go away.</p> <p><img src="https://i.stack.imgur.com/omsJK.png" alt="enter image description here"></p> <p>Is there a fix to this?</p>
11,692,240
9
5
null
2012-07-27 14:23:37.83 UTC
4
2018-06-26 23:33:47.337 UTC
2012-07-27 16:45:03.263 UTC
null
544,079
null
544,079
null
1
14
html|css|html-email
69,943
<p>Styling HTML mails is horrible.</p> <p>A few tips:</p> <p><code>border-spacing:0; /*this should fix the spacing problem*/</code></p> <p>You need to apply this to all the tables you are using, so you should include it in a <code>&lt;style&gt;</code> block at the top like so:</p> <pre><code>&lt;head&gt; &lt;style&gt; table {border-spacing: 0;} &lt;/style&gt; &lt;/head&gt; </code></pre> <p>(sorry for the bad formatting, somehow the code refused to show up properly on multiple lines)</p>
11,556,607
Android : difference between invisible and gone?
<p>What is the difference between <code>invisible</code> and <code>gone</code> for the View visibility status?</p>
11,556,629
8
1
null
2012-07-19 08:14:18.817 UTC
66
2021-05-25 18:31:46.457 UTC
2015-12-22 17:12:31.04 UTC
null
1,332,549
null
1,399,620
null
1
539
android|android-xml|xml-attribute
180,747
<p>INVISIBLE:</p> <blockquote> <p>This view is invisible, but it still takes up space for layout purposes.</p> </blockquote> <p>GONE:</p> <blockquote> <p>This view is invisible, and it doesn't take any space for layout purposes.</p> </blockquote>
11,810,858
How to create SVN repository on server?
<p>How to create SVN repository on server? Although i have found various articles on this but still facing issues while creating repository on my website. Right now i am using <a href="http://www.assembla.com" rel="noreferrer">assembla</a> as my SVN repository, but want to create my own on my hosting.</p>
11,810,992
1
1
null
2012-08-04 18:04:01.653 UTC
11
2017-01-26 12:31:19.837 UTC
null
null
null
null
802,744
null
1
29
svn|webserver
70,127
<ol> <li><p><strong>Create a Repository:</strong></p> <p><code>svnadmin create /svnrepos</code> </p></li> <li><p><strong>Create a SVN User</strong></p> <p><code>vi /svnrepos/conf/svnserve.conf</code></p> <blockquote> <p>anon-access = none </p> <p>auth-access = write </p> <p>password-db = passwd</p> </blockquote> <p><strong>And add users in the format:</strong> <code>user = password</code></p> <p>E.g.: <code>tony = mypassword</code></p></li> <li><p><strong>Import Your Project</strong></p> <p>(Assuming you’ve put your project files in <code>/projects/myrailsproject</code>)</p> <p><code>svn import /projects/myrailsproject file:///svnrepos/myrailsproject</code></p></li> <li><p><strong>Start the SVN Server as Daemon</strong></p> <p><code>svnserve -d</code></p> <p><strong>Done!</strong> You should now have an Apache Subversion server running with one project named myrailsproject.</p> <p>Try checking it out of the repository:</p> <p><code>svn co svn://192.168.0.2/svnrepos/myyrailsproject</code></p> <p>Since we set anon-access to none you should be prompted for username and password which you created in the file <code>/svnrepos/conf/passwd</code>.</p></li> </ol>
11,776,767
What exactly is UIFont's point size?
<p>I am struggling to understand exactly what the point size in <code>UIFont</code> means. It's not pixels and it doesn't appear to be the standard definition of point which is that they relate to 1/72th inch.</p> <p>I worked out the pixel size using <code>-[NSString sizeWithFont:]</code> of fonts at various sizes and got the following:</p> <pre><code>| Point Size | Pixel Size | | ---------- | ---------- | | 10.0 | 13.0 | | 20.0 | 24.0 | | 30.0 | 36.0 | | 40.0 | 47.0 | | 50.0 | 59.0 | | 72.0 | 84.0 | | 99.0 | 115.0 | | 100.0 | 116.0 | </code></pre> <p>(I did <code>[@"A" sizeWithFont:[UIFont systemFontOfSize:theSize]]</code>)</p> <p>And looking at the <code>72.0</code> point size, that is not 1-inch since this is on a device with a DPI of 163, so 1-inch would be 163.0 pixels, right?</p> <p>Can anyone explain what a "point" in <code>UIFont</code> terms is then? i.e. is my method above wrong and really if I used something else I'd see something about the font is 163 pixels at 72 point? Or is it purely that a point is defined from something else?</p>
11,784,813
5
5
null
2012-08-02 11:48:06.513 UTC
17
2015-05-14 19:14:33.507 UTC
2012-08-03 09:07:07.653 UTC
null
1,068,248
null
1,068,248
null
1
50
objective-c|ios|fonts|uikit|uifont
23,264
<p>A font has an internal coordinate system, think of it as a unit square, within which a glyph's vector coordinates are specified at whatever arbitrary size accommodates all the glyphs in the font +- any amount of margin the font designer chooses.</p> <p>At 72.0 points the font's unit square is one inch. Glyph <em>x</em> of font <em>y</em> has an arbitrary size in relation to this inch square. Thus a font designer can make a font that appears large or small in relation to other fonts. This is part of the font's 'character'.</p> <p>So, drawing an 'A' at 72 points tells you that it will be twice as high as an 'A' drawn at 36 points in the same font - and absolutely nothing else about what the actual bitmap size will be.</p> <p>ie For a given font the only way to determine the relationship between point size and pixels is to measure it. </p>
11,510,483
Will a browser give an iframe a separate thread for JavaScript?
<p>Do web browsers use separate executional threads for JavaScript in iframes?</p> <p>I believe Chrome uses separate threads for each tab, so I am guessing that JavaScript in an iframe would share the same thread as its parent window, however, that seems like a security risk too.</p>
11,510,596
10
4
null
2012-07-16 18:40:04.717 UTC
6
2022-02-25 23:45:39.58 UTC
null
null
null
null
2,582
null
1
67
javascript|multithreading|browser
22,861
<p>Before chrome came along, all tabs of any browser shared the same single thread of JavaScript. Chrome upped the game here, and some others have since followed suit.</p> <p>This is a browser implementation detail, so there is no solid answer. Older browsers definitely don't. I don't know of any browser that definitely uses another thread for iframes, but to be honest I've never really looked into it.</p> <p>It isn't a security risk, as no objects are brought along with the thread execution.</p>
12,018,992
Print Combining Strings and Numbers
<p>To print strings and numbers in Python, is there any other way than doing something like:</p> <pre><code>first = 10 second = 20 print "First number is %(first)d and second number is %(second)d" % {"first": first, "second":second} </code></pre>
12,019,007
6
5
null
2012-08-18 13:32:47.407 UTC
30
2022-03-14 15:48:16.357 UTC
2018-09-04 16:21:02.57 UTC
null
9,767,286
null
680,441
null
1
79
python|python-2.7
400,418
<blockquote> <p>Using <em>print function without parentheses</em> works with older versions of Python but is <strong>no longer supported on Python3</strong>, so you have to put the arguments inside parentheses. However, there are <a href="https://stackoverflow.com/questions/32122868/python-3-print-without-parenthesis/32124420">workarounds, as mentioned in the answers to this question</a>. Since the support for Python2 has ended in Jan 1st 2020, the <strong>answer has been modified to be compatible with Python3</strong>.</p> </blockquote> <p>You could do any of these (and there may be other ways):</p> <pre><code>(1) print(&quot;First number is {} and second number is {}&quot;.format(first, second)) (1b) print(&quot;First number is {first} and number is {second}&quot;.format(first=first, second=second)) </code></pre> <p>or</p> <pre><code>(2) print('First number is', first, 'second number is', second) </code></pre> <p><em>(Note: A space will be automatically added afterwards when separated from a comma)</em></p> <p>or</p> <pre><code>(3) print('First number %d and second number is %d' % (first, second)) </code></pre> <p>or</p> <pre><code>(4) print('First number is ' + str(first) + ' second number is' + str(second)) </code></pre> <p>Using <em><a href="http://docs.python.org/library/stdtypes.html#str.format" rel="noreferrer">format()</a></em> (1/1b) is preferred where available.</p>
11,555,468
How should I read a file line-by-line in Python?
<p>In pre-historic times (Python 1.4) we did:</p> <pre><code>fp = open('filename.txt') while 1: line = fp.readline() if not line: break print(line) </code></pre> <p>after Python 2.1, we did:</p> <pre><code>for line in open('filename.txt').xreadlines(): print(line) </code></pre> <p>before we got the convenient iterator protocol in Python 2.3, and could do:</p> <pre><code>for line in open('filename.txt'): print(line) </code></pre> <p>I've seen some examples using the more verbose:</p> <pre><code>with open('filename.txt') as fp: for line in fp: print(line) </code></pre> <p>is this the preferred method going forwards?</p> <p>[edit] I get that the with statement ensures closing of the file... but why isn't that included in the iterator protocol for file objects?</p>
11,555,509
3
6
null
2012-07-19 06:58:25.2 UTC
44
2022-08-29 13:23:39.647 UTC
2022-08-29 13:23:39.647 UTC
null
523,612
null
75,103
null
1
143
python
360,177
<p>There is exactly one reason why the following is preferred:</p> <pre><code>with open('filename.txt') as fp: for line in fp: print(line) </code></pre> <p>We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close the file &quot;quickly enough&quot; without the <code>with</code> block if they use some other scheme to reclaim memory.</p> <p>In such an implementation, you might get a &quot;too many files open&quot; error from the OS if your code opens files faster than the garbage collector calls finalizers on orphaned file handles. The usual workaround is to trigger the GC immediately, but this is a nasty hack and it has to be done by <strong>every</strong> function that could encounter the error, including those in libraries. What a nightmare.</p> <p>Or you could just use the <code>with</code> block.</p> <h2>Bonus Question</h2> <p>(Stop reading now if are only interested in the objective aspects of the question.)</p> <blockquote> <p>Why isn't that included in the iterator protocol for file objects?</p> </blockquote> <p>This is a subjective question about API design, so I have a subjective answer in two parts.</p> <p>On a gut level, this feels wrong, because it makes iterator protocol do two separate things—iterate over lines <em>and</em> close the file handle—and it's often a bad idea to make a simple-looking function do two actions. In this case, it feels especially bad because iterators relate in a quasi-functional, value-based way to the contents of a file, but managing file handles is a completely separate task. Squashing both, invisibly, into one action, is surprising to humans who read the code and makes it more difficult to reason about program behavior.</p> <p>Other languages have essentially come to the same conclusion. Haskell briefly flirted with so-called &quot;lazy IO&quot; which allows you to iterate over a file and have it automatically closed when you get to the end of the stream, but it's almost universally discouraged to use lazy IO in Haskell these days, and Haskell users have mostly moved to more explicit resource management like Conduit which behaves more like the <code>with</code> block in Python.</p> <p>On a technical level, there are some things you may want to do with a file handle in Python which would not work as well if iteration closed the file handle. For example, suppose I need to iterate over the file twice:</p> <pre><code>with open('filename.txt') as fp: for line in fp: ... fp.seek(0) for line in fp: ... </code></pre> <p>While this is a less common use case, consider the fact that I might have just added the three lines of code at the bottom to an existing code base which originally had the top three lines. If iteration closed the file, I wouldn't be able to do that. So keeping iteration and resource management separate makes it easier to compose chunks of code into a larger, working Python program.</p> <p>Composability is one of the most important usability features of a language or API.</p>
11,828,485
Get the option value in select in javascript
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1085801/how-to-get-the-selected-value-of-dropdownlist-using-javascript">How to get the selected value of dropdownlist using JavaScript?</a><br> <a href="https://stackoverflow.com/questions/11828125/how-to-get-the-value-of-a-selected-text-in-javascript">How to get the value of a selected text in javascript</a> </p> </blockquote> <pre><code>&lt;select id="short_code"&gt; &lt;option value="12"&gt;First&lt;/option&gt; &lt;option value="11"&gt;Second&lt;/option&gt; &lt;option value="10"&gt;Third&lt;/option&gt; &lt;option value="9"&gt;Fourth&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I need to do this:</p> <pre><code>if(document.getElementById("short_code").options.item(document.getElementById("short_code").selectedIndex).text)== "First") //get the value of the option Fist , how to get the value? </code></pre>
11,828,653
2
1
null
2012-08-06 12:40:56.503 UTC
1
2016-10-21 14:33:05.247 UTC
2017-05-23 12:24:29.913 UTC
null
-1
null
1,115,161
null
1
-3
javascript
45,533
<pre><code>var elem = document.getElementById("short_code"), selectedNode = elem.options[elem.selectedIndex]; if ( selectedNode.value === "First" ) { //... </code></pre>
3,735,531
SQL/C# - Best method for executing a query
<p>I need to execute a sql query from within a c# class. I have thought of 2 options</p> <ol> <li>Starting a process of sqlcmd.</li> <li>Using a SqlCommand object.</li> </ol> <p>My question is which would be the better way? It's important that the solution only holds a connection to the server for a short time.</p> <p>I'm open to other ideas if the above aren't good.</p> <p>Thanks in advance.</p>
3,735,547
5
4
null
2010-09-17 13:06:02.29 UTC
0
2015-07-31 15:30:26.67 UTC
null
null
null
null
393,908
null
1
18
c#|sql|sql-server-express
78,235
<p>Use a SqlCommand. This code will only keep the connection alive for a very short period of time (as long as your query is performant):</p> <pre><code>DataTable results = new DataTable(); using(SqlConnection conn = new SqlConnection(connString)) using(SqlCommand command = new SqlCommand(query, conn)) using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command)) dataAdapter.Fill(results); </code></pre>
3,803,951
htmlspecialchars(): Invalid multibyte sequence in argument
<p>I am getting this error in my local site.</p> <pre><code>Warning (2): htmlspecialchars(): Invalid multibyte sequence in argument in [/var/www/html/cake/basics.php, line 207] </code></pre> <p>Does anyone knows, what is the problem or what should be the solution for this?</p> <p>Thanks.</p>
3,803,972
6
0
null
2010-09-27 12:52:42.34 UTC
4
2014-10-23 13:10:32.977 UTC
null
null
null
null
417,143
null
1
16
php|cakephp|warnings|htmlspecialchars
39,599
<p>Be sure to specify the encoding to UTF-8 if your files are encoded as such:</p> <pre><code>htmlspecialchars($str, ENT_COMPAT, 'UTF-8'); </code></pre> <p>The default charset for <code>htmlspecialchars</code> is ISO-8859-1 (as of PHP v5.4 the default charset was turned to 'UTF-8'), which might explain why things go haywire when it meets multibyte characters.</p>
3,498,730
Is C++ an Object Oriented language?
<p>I have always heard that C++ is not Object Oriented but rather "C with Classes". So, when I mentioned to an interviewer that C++ was not really object oriented, he asked me why I didn't consider it an OO language. I haven't done any C++ since University, and I didn't have much of an answer. Is C++ Object Oriented or not? and why?</p>
3,498,750
18
13
null
2010-08-17 01:45:43.137 UTC
10
2021-11-11 22:04:25.21 UTC
2015-10-05 12:22:53.457 UTC
null
1,916,893
null
295,916
null
1
31
c++|oop
49,209
<p>C++ is usually considered a "multi-paradigm" language. That is, you can use it for object-oriented, procedural, and even functional programming.</p> <p>Those who would deny that C++ is OO generally have beef with the fact that the primitive types are not objects themselves. By this standard, Java would also not be considered OO.</p> <p>It is certainly true that C++ isn't OO to the same extent as Smalltalk, Ruby, Self, etc. are, but it is definitely an effective OO language by most standards.</p>
8,065,571
Change state of toggle button from another button
<p>I'm creating a Java GUI using Swing with Eclipse and Window Builder Pro. I'm using <code>JButtons</code> and <code>JToggleButtons</code>. I want to change toggle button's state from another button.</p> <p><img src="https://i.stack.imgur.com/TbbtK.jpg" alt="enter image description here"></p> <p>For example, when I click the clear grid, all the toggle buttons will be 'not selected'.</p> <p>How can I do this? What are the methods that I have to use for toggle buttons and buttons?</p>
8,065,687
4
0
null
2011-11-09 13:17:14.477 UTC
4
2014-11-15 07:57:16.083 UTC
2011-11-09 13:32:47.757 UTC
null
418,556
null
819,013
null
1
10
java|swing|jbutton|windowbuilder|jtogglebutton
48,070
<p><a href="http://download.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html#setSelected%28boolean%29">toggleButton.setSelected(boolean b)</a></p> <pre><code>import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractButton; import javax.swing.JFrame; import javax.swing.JToggleButton; public class JToggleButtonAction { public static void main(String args[]) { JFrame frame = new JFrame("Selecting Toggle"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JToggleButton toggleButton = new JToggleButton("Toggle Button"); final JToggleButton toggleButton1 = new JToggleButton("Another Toggle Button"); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { AbstractButton abstractButton = (AbstractButton) actionEvent.getSource(); boolean selected = abstractButton.getModel().isSelected(); System.out.println("Action - selected=" + selected + "\n"); toggleButton1.setSelected(selected); } }; toggleButton.addActionListener(actionListener); frame.add(toggleButton, BorderLayout.NORTH); frame.add(toggleButton1, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } } </code></pre>
8,145,509
MPMediaItem and iTunes Match
<p>I have an app that uses the iPod Library API to access the song database in iOS. With the release of iTunes Match, any song which is not on the device will fail to load. Is there a way I an request that the song be downloaded? Perhaps using the new iCloud API? </p> <p><strong>Edit:</strong> To be clear I am not asking how to download songs with iTunes Match using the iPhone. The iOS SDK allows access to the iPod Library via the MPMediaQuery/MPMediaItems. On a iOS device with iTunes Match enabled songs which are in your iTunes Match library but not local on the device are returned via a MPMediaQuery however the MPMediaItems have their 'exportable' flag set to false. When I access these songs in the Music app they are automatically downloaded. I would like to trigger the same automatic download via the MPMediaItem.</p> <p>I have seen items in iTunes Match refereed to as part of iCloud and there is a new iCloud section of the iOS 5 SDK. However as I understand it I can only get data my app as uploaded. I was hoping there was a way via the MPMediaItem or using the URL via iCloud to trigger an iTunes Match download. </p>
8,393,349
4
5
null
2011-11-16 01:23:51.463 UTC
14
2016-11-29 08:43:33.67 UTC
2011-11-16 17:37:32.737 UTC
null
647,315
null
647,315
null
1
30
objective-c|ios|core-audio|ipod|icloud
9,320
<p>I have found something, but it isn't great. If you select the song to be played through the iPod player then that will trigger a download. You can access the iPod player with an MPMusicPlayerController.</p> <pre><code>MPMusicPlayerController *mDRMAudioPlayer; mDRMAudioPlayer = [MPMusicPlayerController iPodMusicPlayer]; MPMediaQuery *assetQuery = [[MPMediaQuery alloc] init]; NSNumber *persistentID = [mediaItem valueForProperty: MPMediaItemPropertyPersistentID]; MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue: persistentID forProperty: MPMediaItemPropertyPersistentID]; [assetQuery addFilterPredicate: predicate]; [mDRMAudioPlayer setQueueWithQuery: assetQuery]; [mDRMAudioPlayer play]; </code></pre> <p>No feedback on if this really started a download or not, or progress on the download but the item will start downloading and if your connection is good it will play the first time (otherwise you can spam play and it will get around to starting).</p>
8,090,229
resize with averaging or rebin a numpy 2d array
<p>I am trying to reimplement in python an IDL function:</p> <p><a href="http://star.pst.qub.ac.uk/idl/REBIN.html" rel="noreferrer">http://star.pst.qub.ac.uk/idl/REBIN.html</a></p> <p>which downsizes by an integer factor a 2d array by averaging.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; a=np.arange(24).reshape((4,6)) &gt;&gt;&gt; a array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]]) </code></pre> <p>I would like to resize it to (2,3) by taking the mean of the relevant samples, the expected output would be:</p> <pre><code>&gt;&gt;&gt; b = rebin(a, (2, 3)) &gt;&gt;&gt; b array([[ 3.5, 5.5, 7.5], [ 15.5, 17.5, 19.5]]) </code></pre> <p>i.e. <code>b[0,0] = np.mean(a[:2,:2]), b[0,1] = np.mean(a[:2,2:4])</code> and so on.</p> <p>I believe I should reshape to a 4 dimensional array and then take the mean on the correct slice, but could not figure out the algorithm. Would you have any hint?</p>
8,090,605
5
1
null
2011-11-11 05:58:38.413 UTC
9
2022-07-03 16:48:44.36 UTC
null
null
null
null
597,609
null
1
38
python|numpy|slice|binning
34,221
<p>Here's an example based on <a href="https://stackoverflow.com/questions/4624112/grouping-2d-numpy-array-in-average/4624923#4624923">the answer you've linked</a> (for clarity):</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.arange(24).reshape((4,6)) &gt;&gt;&gt; a array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]]) &gt;&gt;&gt; a.reshape((2,a.shape[0]//2,3,-1)).mean(axis=3).mean(1) array([[ 3.5, 5.5, 7.5], [ 15.5, 17.5, 19.5]]) </code></pre> <p>As a function:</p> <pre class="lang-py prettyprint-override"><code>def rebin(a, shape): sh = shape[0],a.shape[0]//shape[0],shape[1],a.shape[1]//shape[1] return a.reshape(sh).mean(-1).mean(1) </code></pre>
8,141,440
How are constructors called during serialization and deserialization?
<p>How are the constructors called during serialization and deserialization</p> <ol> <li>When there is one class implementing serializable?</li> <li>When there is parent/child relationship and only child implements serializable?</li> <li>When there is parent/child relationship and both parent and child implements serializable?</li> </ol>
8,141,671
6
1
null
2011-11-15 18:46:00.283 UTC
17
2020-06-24 05:04:32.857 UTC
2015-09-21 11:41:04.427 UTC
null
1,310,566
null
968,161
null
1
60
java|serialization
47,270
<p>Example:</p> <pre><code> public class ParentDeserializationTest { public static void main(String[] args){ try { System.out.println(&quot;Creating...&quot;); Child c = new Child(1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); c.field = 10; System.out.println(&quot;Serializing...&quot;); oos.writeObject(c); oos.flush(); baos.flush(); oos.close(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); System.out.println(&quot;Deserializing...&quot;); Child c1 = (Child)ois.readObject(); System.out.println(&quot;c1.i=&quot;+c1.getI()); System.out.println(&quot;c1.field=&quot;+c1.getField()); } catch (IOException ex){ ex.printStackTrace(); } catch (ClassNotFoundException ex){ ex.printStackTrace(); } } public static class Parent { protected int field; protected Parent(){ field = 5; System.out.println(&quot;Parent::Constructor&quot;); } public int getField() { return field; } } public static class Child extends Parent implements Serializable{ protected int i; public Child(int i){ this.i = i; System.out.println(&quot;Child::Constructor&quot;); } public int getI() { return i; } } } </code></pre> <p>Output:</p> <pre><code>Creating... Parent::Constructor Child::Constructor Serializing... Deserializing... Parent::Constructor c1.i=1 c1.field=5 </code></pre> <p>So if you deserialized your object, its constructors doesn't called, but default constructor of its parent will be called. And don't forget: all your serializable object should have a standard constructor without parameters.</p>
8,080,579
Android TextField : set focus + soft input programmatically
<p>In my view, I have a search EditText and I would like to trigger programmatically the behaviour of a click event on the field, i.e give focus to the text field AND display soft keyboard if necessary (if no hard keyboard available).</p> <p>I tried <code>field.requestFocus()</code>. The field actually gets focus but soft keyboard is not displayed.</p> <p>I tried <code>field.performClick()</code>. But that only calls the OnClickListener of the field.</p> <p>Any idea ?</p>
8,080,621
7
0
null
2011-11-10 13:55:22.653 UTC
18
2021-06-09 04:10:37.807 UTC
null
null
null
null
569,558
null
1
86
android|android-edittext
93,449
<p>Good sir, try this:</p> <pre><code>edittext.setFocusableInTouchMode(true); edittext.requestFocus(); </code></pre> <p>I'm not sure, but this might be required on some phones (some of the older devices):</p> <pre><code>final InputMethodManager inputMethodManager = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.showSoftInput(edittext, InputMethodManager.SHOW_IMPLICIT); </code></pre>
8,345,581
C: printf a float value
<p>I want to print a float value which has 2 integer digits and 6 decimal digits after the comma. If I just use <code>printf("%f", myFloat)</code> I'm getting a truncated value.</p> <p>I don't know if this always happens in C, or it's just because I'm using C for microcontrollers (CCS to be exact), but at the reference it tells that <code>%f</code> get just that: a truncated float.</p> <p>If my float is <code>44.556677</code>, I'm printing out <code>"44.55"</code>, only the first two decimal digits.</p> <p>So the question is... how can I print my 6 digits (and just the six of them, just in case I'm having zeros after that or something)?</p>
8,345,605
7
7
null
2011-12-01 17:25:42.54 UTC
17
2022-03-01 18:10:50.177 UTC
2012-06-19 01:32:38.2 UTC
null
44,390
null
808,091
null
1
104
c|floating-point
691,788
<p>You can do it like this:</p> <pre><code>printf("%.6f", myFloat); </code></pre> <p>6 represents the number of digits after the decimal separator.</p>
8,297,705
How to implement thread-safe lazy initialization?
<p>What are some recommended approaches to achieving <strong><em>thread-safe</em></strong> lazy initialization? For instance,</p> <pre><code>// Not thread-safe public Foo getInstance(){ if(INSTANCE == null){ INSTANCE = new Foo(); } return INSTANCE; } </code></pre>
8,297,830
13
0
null
2011-11-28 14:57:32.71 UTC
28
2022-08-24 02:24:55.127 UTC
null
null
null
null
584,862
null
1
66
java|thread-safety|lazy-initialization
61,484
<p>For singletons there is an elegant solution by delegating the task to the JVM code for static initialization.</p> <pre><code>public class Something { private Something() { } private static class LazyHolder { public static final Something INSTANCE = new Something(); } public static Something getInstance() { return LazyHolder.INSTANCE; } } </code></pre> <p>see </p> <p><a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom" rel="noreferrer">http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom</a></p> <p>and this blog post of Crazy Bob Lee </p> <p><a href="http://blog.crazybob.org/2007/01/lazy-loading-singletons.html" rel="noreferrer">http://blog.crazybob.org/2007/01/lazy-loading-singletons.html</a></p>
8,158,969
H2 database error: Database may be already in use: "Locked by another process"
<p>I am trying to use the H2 database from a Java application. </p> <p>I created the database and its tables through the H2 Console and then I try to connect from Java using </p> <pre><code>Connection con = DriverManager.getConnection("jdbc:h2:~/dbname", "username", "password"); </code></pre> <p>However I receive the following error:</p> <blockquote> <p>Exception in thread "main" org.h2.jdbc.JdbcSQLException: Database may be already in use: "Locked by another process". Possible solutions: close all other connection(s); use the server mode [90020-161]</p> </blockquote> <p>I tried to delete the <code>dbname.lock.db</code> file but it is automatically re-created.</p> <p>How can I unlock the database to use it from my Java program?</p>
8,159,043
16
0
null
2011-11-16 21:27:43.807 UTC
18
2022-04-08 11:33:17.367 UTC
2015-10-24 12:24:29.077 UTC
null
5,240,004
null
260,108
null
1
58
java|database|h2
134,207
<p>H2 is still running (I can guarantee it). You need to use a TCP connection for multiple users such as -></p> <pre><code>&lt;property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/C:\Database\Data\production;"/&gt; </code></pre> <p>OR</p> <pre><code>DriverManager.getConnection("jdbc:h2:tcp://localhost/server~/dbname","username","password"); </code></pre> <p>It also means you need to start the server in TCP mode. Honesetly, it is pretty straight forward in the documentation.</p> <p>Force kill the process (javaw.exe for Windows), and make sure that any application that might have started it is shut down. You have an active lock.</p>
61,411,498
Why does rand() repeat numbers far more often on Linux than Mac?
<p>I was implementing a hashmap in C as part of a project I'm working on and using random inserts to test it. I noticed that <code>rand()</code> on Linux seems to repeat numbers far more often than on Mac. <code>RAND_MAX</code> is <code>2147483647/0x7FFFFFFF</code> on both platforms. I've reduced it to this test program that makes a byte array <code>RAND_MAX+1</code>-long, generates <code>RAND_MAX</code> random numbers, notes if each is a duplicate, and checks it off the list as seen.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; int main() { size_t size = ((size_t)RAND_MAX) + 1; char *randoms = calloc(size, sizeof(char)); int dups = 0; srand(time(0)); for (int i = 0; i &lt; RAND_MAX; i++) { int r = rand(); if (randoms[r]) { // printf("duplicate at %d\n", r); dups++; } randoms[r] = 1; } printf("duplicates: %d\n", dups); } </code></pre> <p>Linux consistently generates around 790 million duplicates. Mac consistently only generates one, so it loops through every random number that it can generate <em>almost</em> without repeating. Can anyone please explain to me how this works? I can't tell anything different from the <code>man</code> pages, can't tell which RNG each is using, and can't find anything online. Thanks!</p>
61,413,211
4
18
null
2020-04-24 15:08:24.23 UTC
8
2020-05-19 23:51:25.127 UTC
2020-05-19 23:51:25.127 UTC
null
13,513,445
null
9,242,143
null
1
124
c|linux|macos|random
8,394
<p>While at first it may sound like the macOS <code>rand()</code> is somehow better for not repeating any numbers, one should note that with this amount of numbers generated it is <a href="https://en.wikipedia.org/wiki/Birthday_problem" rel="noreferrer">expected</a> to see plenty of duplicates (in fact, around 790 million, or (2<sup>31</sup>-1)/<i>e</i>). Likewise iterating through the numbers in sequence would also produce no duplicates, but wouldn't be considered very random. So the Linux <code>rand()</code> implementation is <em>in this test</em> indistinguishable from a true random source, whereas the macOS <code>rand()</code> is not.</p> <p>Another thing that appears surprising at first glance is how the macOS <code>rand()</code> can manage to avoid duplicates so well. Looking at <a href="https://opensource.apple.com/source/Libc/Libc-1353.11.2/stdlib/FreeBSD/rand.c" rel="noreferrer">its source code</a>, we find the implementation to be as follows:</p> <pre><code>/* * Compute x = (7^5 * x) mod (2^31 - 1) * without overflowing 31 bits: * (2^31 - 1) = 127773 * (7^5) + 2836 * From "Random number generators: good ones are hard to find", * Park and Miller, Communications of the ACM, vol. 31, no. 10, * October 1988, p. 1195. */ long hi, lo, x; /* Can't be initialized with 0, so use another value. */ if (*ctx == 0) *ctx = 123459876; hi = *ctx / 127773; lo = *ctx % 127773; x = 16807 * lo - 2836 * hi; if (x &lt; 0) x += 0x7fffffff; return ((*ctx = x) % ((unsigned long) RAND_MAX + 1)); </code></pre> <p>This does indeed result in all numbers between 1 and <code>RAND_MAX</code>, inclusive, exactly once, before the sequence repeats again. Since the next state is based on multiplication, the state can never be zero (or all future states would also be zero). Thus the repeated number you see is the first one, and zero is the one that is never returned.</p> <p>Apple has been promoting the use of better random number generators in their documentation and examples for at least as long as macOS (or OS X) has existed, so the quality of <code>rand()</code> is probably not deemed important, and they've just stuck with one of the simplest pseudorandom generators available. (As you noted, their <code>rand()</code> is even commented with a recommendation to use <code>arc4random()</code> instead.)</p> <p>On a related note, the simplest pseudorandom number generator I could find that produces decent results in this (and many other) tests for randomness is <a href="https://en.wikipedia.org/wiki/Xorshift#xorshift*" rel="noreferrer">xorshift*</a>:</p> <pre><code>uint64_t x = *ctx; x ^= x &gt;&gt; 12; x ^= x &lt;&lt; 25; x ^= x &gt;&gt; 27; *ctx = x; return (x * 0x2545F4914F6CDD1DUL) &gt;&gt; 33; </code></pre> <p>This implementation results in almost exactly 790 million duplicates in your test.</p>
4,382,440
C++ operator+ and operator+= overloading
<p>I'm implementing my own matrix class in c++ to help me develop my understanding of the language. I read somewhere that if you've got a working += operator, to use it in your + operator. So that's what I've got:</p> <pre><code>template &lt;class T&gt; const Matrix&lt;T&gt;&amp; Matrix&lt;T&gt;::operator+(const Matrix&lt;T&gt; &amp;R){ Matrix&lt;T&gt; copy(*this); return copy += R; } </code></pre> <p>And here is the += operator overload:</p> <pre><code>template &lt;class T&gt; const Matrix&lt;T&gt;&amp; Matrix&lt;T&gt;::operator+=(const Matrix&lt;T&gt; &amp; second_matrix){ //Learn how to throw errors.... if (rows != second_matrix.getNumRows() || cols != second_matrix.getNumCols()){throw "Dimension mismatch.";} int i,j; for (i = 0; i &lt; rows; i++){ for (j = 0; j &lt; cols; j++){ data[i][j] += second_matrix.get(i,j); } } return *this; } </code></pre> <p>I can use the += just fine (eg, a += b; returns no errors). But calling the + operator (eg, a = b + c;) returns :</p> <pre><code>test.cpp.out(77055) malloc: *** error for object 0x300000004: pointer being freed was not allocated </code></pre> <p>Just for completeness, here's my destructor:</p> <pre><code>template &lt;class T&gt; Matrix&lt;T&gt;::~Matrix(){ for (int i = 1; i &lt; rows; i++){ delete[] data[i]; } delete[] data; } </code></pre> <p>I've been using C++ for a couple years on and off, and still have trouble sometimes keeping track of pointers. I hope that's normal... Any help would be great. Thanks!</p> <p>EDIT: here's my copy constructor. It was set to free the data arrays but i removed that. now I get segmentation faults.</p> <pre><code>template &lt;class T&gt; Matrix&lt;T&gt;::Matrix(const Matrix&lt;T&gt;&amp; second_matrix){ rows = second_matrix.getNumRows(); cols = second_matrix.getNumCols(); data = new T*[rows]; int i,j; for (i = 0; i &lt; rows; i++){ data[i] = new T[cols]; } for (i = 0; i &lt; rows; i++){ for (j = 0; j &lt; cols; j++){ data[i][j] = second_matrix.get(i,j); } } } </code></pre>
4,382,461
3
9
null
2010-12-07 22:45:46.927 UTC
2
2010-12-08 13:43:27.967 UTC
2010-12-07 22:55:12.25 UTC
null
364,015
null
364,015
null
1
10
c++|operator-overloading
66,027
<p><code>operator+()</code> should not return a reference type as it is a new (locally declared) instance that holds the result of the operation.</p>
4,573,526
What could be causing a "Cannot access a disposed object" error in WCF?
<p>I am using the following code:</p> <pre><code>private WSHttpBinding ws; private EndpointAddress Srv_Login_EndPoint; private ChannelFactory&lt;Srv_Login.Srv_ILogin&gt; Srv_LoginChannelFactory; private Srv_Login.Srv_ILogin LoginService; </code></pre> <p>The Login is my constructor:</p> <pre><code>public Login() { InitializeComponent(); ws = new WSHttpBinding(); Srv_Login_EndPoint = new EndpointAddress("http://localhost:2687/Srv_Login.svc"); Srv_LoginChannelFactory = new ChannelFactory&lt;Srv_Login.Srv_ILogin&gt;(ws, Srv_Login_EndPoint); } </code></pre> <p>And I'm using service this way:</p> <pre><code>private void btnEnter_Click(object sender, EventArgs e) { try { LoginService = Srv_LoginChannelFactory.CreateChannel(); Srv_Login.LoginResult res = new Srv_Login.LoginResult(); res = LoginService.IsAuthenticated(txtUserName.Text.Trim(), txtPassword.Text.Trim()); if (res.Status == true) { int Id = int.Parse(res.Result.ToString()); } else { lblMessage.Text = "Not Enter"; } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { Srv_LoginChannelFactory.Close(); } } </code></pre> <p>When the user enters a valid username and password, everything is fine. When the user enters a wrong username and password, the first try correctly displays a "Not Enter" message, but on the second try, the user sees this message:</p> <pre><code>{System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.ServiceModel.ChannelFactory`1[Test_Poosesh.Srv_Login.Srv_ILogin]'. at System.ServiceModel.Channels.CommunicationObject.ThrowIfDisposed() at System.ServiceModel.ChannelFactory.EnsureOpened() at System.ServiceModel.ChannelFactory`1.CreateChannel(EndpointAddress address, Uri via) at System.ServiceModel.ChannelFactory`1.CreateChannel() </code></pre> <p>How can I fix my code to prevent this error from occurring?</p>
4,573,571
3
0
null
2011-01-01 08:13:22.867 UTC
3
2019-03-21 08:37:13.433 UTC
2011-01-01 08:19:07.6 UTC
null
366,904
null
648,723
null
1
20
c#|wcf|objectdisposedexception
95,899
<p><code>Srv_LoginChannelFactory.Close()</code> is where it's being disposed. When you call close you are giving up whatever unmanaged resource you had. Attempting to do something other then inspecting its state or re-opening it results in the "Cannot access a disposed object" exception. </p> <p>This is true whenever you close a disposable object and try and do something with it afterwards. For example writing to a file that's closed, or executing a sql statement on a closed database connection. </p> <p>To address this you have three options. </p> <ol> <li><p>Don't make the Srv_LoginChannelFactory a field. Instead make it local to the button click. If this is the only place you are using it, this probably makes sense to do because it shortens the amount of time you are using an unmanaged resource.</p></li> <li><p>Implement IDisposable (you are supposed do this whenever you have field that is Disposable) don't close Srv_LoginChannelFactory except in Login.Dispose.</p></li> <li><p>Change the button click to check the State of Srv_LoginChannelFactory before you try and create a channel with it. You still need to implement IDisposable in case the button click doesn't happen. </p></li> </ol> <p><strong><em>Note</em></strong>: <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channelfactory.ensureopened.aspx" rel="noreferrer">EnsureOpened</a> looks like it could be used to check the state, but it only works before its opened. Once its been closed it will throw.</p> <p>Regarding Close() being the same as Dispose. </p> <p>From the section 'Customizing a Dispose Method Name' in <a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx" rel="noreferrer">Implementing Finalize and Dispose to Clean Up Unmanaged Resources</a> in the Design Guidelines for Developing Class Libraries</p> <blockquote> <p>Occasionally a domain-specific name is more appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In this case, implement Dispose privately and create a public Close method that calls Dispose. The following code example illustrates this pattern. You can replace Close with a method name appropriate to your domain. This example requires the System namespace.</p> </blockquote> <p>The idea here is to give parity to the Open method. Personally I think it causes a lot of confusion, but I can't think of anything better (CloseAndDispose?)</p>
4,657,142
How do I encourage emacs to follow the compilation buffer
<p>Occasionally when I'm compiling, I have to scroll up my <em>compilation</em> buffer to see the details of an error. At this point, emacs stops "following" my compilation buffer, i.e., scrolling to automatically display new output. </p> <p>I'm using Aqumacs on OS X. Any idea how I can "reattach" or re encourage the compilation buffer to follow again?</p> <p>Regards, Chris</p>
4,657,387
3
0
null
2011-01-11 11:32:39.343 UTC
4
2016-04-28 15:01:48.553 UTC
null
null
null
null
571,178
null
1
39
emacs
7,667
<p>I am not sure about aquamacs but for me (Emacs 23/Debian) I just go in the compilation window and place my cursor at the end of the window which will attach and follow (you can go to another window and it will still follow).</p>
4,139,532
Insert data into MySQL Database using javascript/AJAX
<p>I have made a very simple page using google maps API with several fields where users are going to put some data. It looks like following -</p> <p><a href="http://aiworker2.usask.ca/marker_field_db.html" rel="nofollow">http://aiworker2.usask.ca/marker_field_db.html</a></p> <p>What I want to do is store the data into MySQL database using javascript/Ajax. I have found several examples that has used Jquery. I'm very new to this javascript/Ajax/Jquery platform. Now my question is-</p> <ol> <li>Is it possible to insert data into MySQL database without using JQuery?</li> <li>Can anyone send any link of simple example or tutorial to deal with the issue?</li> </ol> <p>Thanks in advance.</p>
4,139,625
4
0
null
2010-11-09 22:49:54.547 UTC
null
2012-10-11 06:28:33.66 UTC
null
null
null
null
400,859
null
1
2
javascript|jquery|ajax
42,810
<p>Your JavaScript runs on the client (in the browser). Your MySQL database exists on a server. </p> <p>In short, the client-side JavaScript cannot establish a <strong>direct</strong> connection to MySQL. You need to make an AJAX request to the server which runs a script that interacts with MySQL. The script can be written in any language that has a MySQL library.</p> <p>Here's an example where an AJAX request is made, which calls a PHP script on the server, which, in turn, grabs data from a MySQL database and returns results back to the client:</p> <p><a href="http://www.w3schools.com/PHP/php_ajax_database.asp" rel="nofollow">http://www.w3schools.com/PHP/php_ajax_database.asp</a></p>
14,596,499
iTunes Search Lookup for all a Developers Apps
<p>Is there a way to use the iTunes Lookup to show all of the apps a Developer has? Eg:</p> <pre><code>https://itunes.apple.com/lookup?devid=123 </code></pre> <p>I also tried:</p> <pre><code>http://itunes.apple.com/search?media=software&amp;term=Developer Name </code></pre> <p>But that didn't work either. Ideas?</p>
14,596,622
2
0
null
2013-01-30 04:04:37.11 UTC
8
2015-11-25 18:00:37.983 UTC
2015-11-25 18:00:37.983 UTC
null
1,505,120
null
144,695
null
1
5
ios|iphone|itunes
3,017
<p>To get the details of a developer,</p> <pre><code>https://itunes.apple.com/lookup?id=514675684 </code></pre> <p>To get all apps by that developer,</p> <pre><code>https://itunes.apple.com/lookup?id=514675684&amp;entity=software </code></pre> <p>To get the apps based on localization,</p> <pre><code>https://itunes.apple.com/lookup?id=514675684&amp;entity=software&amp;country=in </code></pre> <p>or, <code>itunes.apple.com/in/lookup?id=514675684&amp;entity=software</code> </p>
4,500,198
Suppress warning on unused exception variable in C#
<p>I have this code:</p> <pre><code>try { someMethod(); } catch (XYZException e) { // do something without using e } </code></pre> <p>Doing this will give me a warning about declaring but never using <code>e</code>, which I hate. However, I also don't want to use a <code>catch</code> clause without that variable, because then it will catch all exceptions, not just <code>XYZException</code>s. This seems like a fairly often occurring pattern. I know I can use <code>#pragma warning disable 0168</code> to suppress the warning, but I don't really find that a very elegant solution. Is there a better way?</p>
4,500,222
4
1
null
2010-12-21 14:17:13.96 UTC
5
2020-01-23 10:21:00.6 UTC
2010-12-21 14:45:31.82 UTC
null
25,727
null
48,648
null
1
50
c#|visual-studio-2008|exception-handling
14,421
<p>Define the catch clause without the exception variable as follows:</p> <pre><code>try { someMethod(); } catch (XYZException) { // do something without using e } </code></pre>
4,263,339
Installing Android Market App on Emulator
<p>I want to install android Market App on Emulator, so that I can browse and install various free apps on emulators.</p> <p>Can you guide me how to do this?</p>
4,755,642
5
2
null
2010-11-24 04:01:17.03 UTC
10
2020-12-28 01:50:07.847 UTC
2020-12-28 01:50:07.847 UTC
null
1,783,163
null
395,661
null
1
10
android
18,626
<p>Android market application cannot be directly downloaded to a computer. But there may be some alternative sites that provide the .apk file of the application. Search in Google. If you got that .apk file downloaded in your system, you can easily install that by the following steps. I usually do like this.</p> <ul> <li><p>First of all copy the .apk file to the android sdk --> 'platform-tools' directory </p></li> <li><p>To start the emulator use type the following command on your terminal</p> <p><code>cd /path_to_android_sdk/platform-tools</code> // press enter</p> <p>then type the following to start the emulator</p> <p><code>emulator -avd &lt;emulator_name&gt;</code> // press enter</p></li> </ul> <p><code>&lt;emulator_name&gt;</code> is the name that you have given when you first created that emulator. If you don't know that name, go to eclipse and click window-->Avd and Sdk manager. On that window you can see the AVD name.</p> <p>After that wait for a couple of minutes so that the emulator starts. After that, unlock the emulator:</p> <ul> <li><p>Open another tab in terminal or open another terminal and type the following commands</p> <p><code>cd /path_to_android_sdk/platform-tools; ls</code> //press enter</p> <p>Now you should see your application name.</p> <p><code>adb install &lt;name_of_the_apk&gt;</code> // press enter <code>./adb install &lt;name_of_the_apk&gt;</code> // for MAC machine</p></li> </ul> <p>After that you can see a success message.</p> <ul> <li>Eventually press on the menu launcher button on the emulator where you can see your application installed. Click on the icon to launch that application.</li> </ul>