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
10,795,973
Python dictionary search values for keys using regular expression
<p>I am trying to implement to search for a value in Python dictionary for specific key values (using regular expression as a key). </p> <p>Example:</p> <p>I have a Python dictionary which has values like:</p> <pre><code>{'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343} </code></pre> <p>I need to search for values whose key has 'seller_account'? I wrote a sample program but would like to know if something can be done better. Main reason is I am not sure of regular expression and miss out something (like how do I set re for key starting with 'seller_account'):</p> <pre><code>#!usr/bin/python import re my_dict={'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343} reObj = re.compile('seller_account') for key in my_dict.keys(): if(reObj.match(key)): print key, my_dict[key] ~ home&gt; python regular.py seller_account_number 3433343 seller_account_0 454676 seller_account 454545 </code></pre>
10,796,073
5
2
null
2012-05-29 08:56:22.267 UTC
12
2021-12-29 10:48:52.153 UTC
null
null
null
null
304,974
null
1
48
python
94,780
<p>If you only need to check keys that are starting with <code>"seller_account"</code>, you don't need regex, just use <a href="http://docs.python.org/library/stdtypes.html#str.startswith" rel="noreferrer">startswith()</a></p> <pre><code>my_dict={'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343} for key, value in my_dict.iteritems(): # iter on both keys and values if key.startswith('seller_account'): print key, value </code></pre> <p>or in a one_liner way : </p> <pre><code>result = [(key, value) for key, value in my_dict.iteritems() if key.startswith("seller_account")] </code></pre> <p>NB: for a python 3.X use, replace <code>iteritems()</code> by <code>items()</code> and don't forget to add <code>()</code> for <code>print</code>.</p>
28,592,395
How to get the year in 2 digits in php?
<p>I want to get the year in 2 digits like <strong>15</strong>.</p> <p>using the php date() function</p> <pre><code>echo date("Y"); </code></pre> <p>but this returns the full year.</p> <p>any help is much appriciated. Thanks!</p>
28,592,457
3
3
null
2015-02-18 19:38:45.443 UTC
4
2016-11-21 09:06:42.497 UTC
null
null
null
null
2,945,457
null
1
36
php
60,744
<p>Change the upper case 'Y' to lower case 'y'</p> <pre><code>echo date("y"); </code></pre> <p>PHP documentation</p> <pre><code>y A two digit representation of a year </code></pre>
59,317,789
Trouble with CORS Policy and .NET Core 3.1
<p>I'm not sure what I'm missing, but can't seem to get my CORS Policy working with .NET Core 3.1 and Angular 8 client-side.</p> <p><code>Startup.cs</code>:</p> <pre class="lang-cs prettyprint-override"><code> public void ConfigureServices(IServiceCollection services) { // ... // Add CORS policy services.AddCors(options =&gt; { options.AddPolicy("foo", builder =&gt; { // Not a permanent solution, but just trying to isolate the problem builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); // Use the CORS policy app.UseCors("foo"); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =&gt; { endpoints.MapControllers(); }); } </code></pre> <p>Error Message Client-side:</p> <pre><code>Access to XMLHttpRequest at 'https://localhost:8082/api/auth/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. </code></pre> <h1>UPDATE:</h1> <p>Although I <em>was</em> configuring CORS incorrectly (and the accepted answer below did in fact help with that) the root of issue was unrelated. For additional context, the app was working completely fine when running the API and Angular app using the CLI - I was only having this issue after deploying them both to a web server.</p> <p>The <em>"actual"</em> issue ended up being related to the SQL connection, which I only discovered after adding flat-file error logging to the API and running a SQL Server trace to find that the app wasn't able to connect to SQL at all. </p> <p>I would normally expect this to just return a 500 and I would have realized the issue in a matter of 10 seconds - however the CORS mis-configuration meant a 500 was never actually being returned because the CORS middleware failed first. <strong>This was immensely frustrating to say the absolute least!</strong> . However I want to add that here in case others find themselves in this situation, as I was "chasing the wrong rabbit," if you will. <strong>After fixing the CORS configuration, I realized the actual issue was entirely unrelated to CORS.</strong></p> <h1>TL;DR; - Sometimes "Non-CORS" .NET Server-side Errors Can Be Returned as CORS Errors If CORS policies Aren't Set Correctly</h1> <p>References:</p> <p><a href="https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware</a></p> <p><a href="https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785" rel="noreferrer">https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785</a></p>
59,319,161
12
10
null
2019-12-13 07:15:08.78 UTC
7
2021-10-27 19:29:12.953 UTC
2020-02-04 19:58:17.663 UTC
null
3,443,552
null
3,443,552
null
1
47
angular|.net-core|cors
41,704
<p>first <code>app.UseRouting();</code> then <code>app.UseCors("foo");</code></p> <p>Change your <code>Configure</code> method like the following :</p> <pre><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); // first // Use the CORS policy app.UseCors("foo"); // second app.UseAuthorization(); app.UseEndpoints(endpoints =&gt; { endpoints.MapControllers(); }); } </code></pre> <p>It worked for me !</p>
7,162,272
How to change icon in jstree?
<p>I have the following code:</p> <pre><code>$('.wpFolders.co_files').bind('select_node.jstree', function (event, data) { getFileById(data.args[0].hash.replace('#', '')); }).jstree({ 'plugins' : ['html_data','themes','ui','types'], 'ui' : { 'select_limit' : 1 }, 'core' : { 'animation' : 0 }, 'types': { 'default' : { 'icon' : { 'image' : '/admin/views/images/file.png' } } } }); </code></pre> <p>I have a basic unordered list I would like to have displayed as a list of files. I'm trying to use the "types" to change the icon but I can't for the life of me figure out how to do it. I checked their docs <a href="http://www.jstree.com/documentation/types">link</a> and even when using almost identical code nothing seems to happen.</p> <p>From my understanding of the code above the default type of my tree should have the icon I specified but nothing happens, all I get is the default folder icon.</p> <p>Any ideas? Sorry if the question seems basic but I find the documentation hard to follow when trying to do basic things. :)</p>
7,163,778
10
0
null
2011-08-23 14:04:22.757 UTC
9
2017-07-21 19:51:16.797 UTC
2013-02-21 09:16:12.843 UTC
null
1,884,589
null
218,067
null
1
31
javascript|jstree
90,928
<p>Two problems:</p> <ol> <li>I needed to add the "type" in my rel attribute of my list objects (I created a default and file type).</li> <li><p>I forgot one level in my array declaring the types, the code had to be like the following:</p> <pre><code>$('.wpFolders.co_files').bind('select_node.jstree', function (event, data) { getFileById(data.args[0].hash.replace('#', '')); }).jstree({ 'plugins' : ['html_data','themes','ui','types'], 'ui' : { 'select_limit' : 1 }, 'core' : { 'animation' : 0 }, 'types': { 'types' : { 'file' : { 'icon' : { 'image' : '/admin/views/images/file.png' } }, 'default' : { 'icon' : { 'image' : '/admin/views/images/file.png' }, 'valid_children' : 'default' } } } }); </code></pre></li> </ol> <p>I don't really understand why my code is breaking in the WYSIWYG, sorry if it's ugly. Anyway, I hope this can help someone.</p>
7,145,606
How do you save/store objects in SharedPreferences on Android?
<p>I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?</p> <p>I can't store it like this:</p> <pre><code>SharedPreferences.Editor prefsEditor = myPrefs.edit(); prefsEditor.putString(&quot;BusinessUnit&quot;, strBusinessUnit); </code></pre>
18,463,758
22
4
null
2011-08-22 09:45:19.867 UTC
99
2021-10-14 10:17:06.937 UTC
2020-07-25 10:08:48.437 UTC
null
7,487,335
null
831,498
null
1
283
android|sharedpreferences
264,864
<p>You can use gson.jar to store class objects into <strong>SharedPreferences</strong>. You can download this jar from <a href="https://github.com/google/gson/releases" rel="noreferrer">google-gson</a></p> <p>Or add the GSON dependency in your Gradle file:</p> <pre><code>implementation 'com.google.code.gson:gson:2.8.8' </code></pre> <p>you can find latest version <a href="https://github.com/google/gson/releases" rel="noreferrer">here</a></p> <p>Creating a shared preference:</p> <pre><code>SharedPreferences mPrefs = getPreferences(MODE_PRIVATE); </code></pre> <p>To save:</p> <pre><code>MyObject myObject = new MyObject; //set variables of 'myObject', etc. Editor prefsEditor = mPrefs.edit(); Gson gson = new Gson(); String json = gson.toJson(myObject); prefsEditor.putString(&quot;MyObject&quot;, json); prefsEditor.commit(); </code></pre> <p>To retrieve:</p> <pre><code>Gson gson = new Gson(); String json = mPrefs.getString(&quot;MyObject&quot;, &quot;&quot;); MyObject obj = gson.fromJson(json, MyObject.class); </code></pre>
14,125,166
Best way of storing user settings in MySQL?
<p>I was just wondering what would be the best way of storing user-specific settings for my web applications? Just preferences users may have. I've thought of two options:</p> <ol> <li><p><strong>Users table</strong> - I'll have a table for my users. Creating a column called "preferences" and storing serialized data there in key => value pairs</p></li> <li><p><strong>Settings table</strong> - Have a separate table called settings with a user_id column. Save the settings in the same way</p></li> </ol> <p>Any input would be appreciated. Thanks :)!</p> <p>--</p> <p>EDIT: Just to add, if I didn't serialize/json or whatever the data to put in the data, I'd have to have a column for each setting. </p>
14,125,449
6
3
null
2013-01-02 16:03:35.493 UTC
11
2016-11-23 04:36:26.913 UTC
null
null
null
null
1,073,419
null
1
16
php|mysql
15,249
<p>For anything that is <em>always</em> set for <em>every</em> user you should tend to keep that in the <code>Users</code> table, per usual normalization. As for optional config I tend to like the following table structure:</p> <pre><code>TABLE Users: id INT AI name VARCHAR ... TABLE User_Settings user_id INT PK,FK name VARCHAR PK type BOOL value_int INT NULL value_str VARCHAR NULL </code></pre> <p>Where <code>User_Settings.type</code> specifies whether the integer or string field should be referenced.</p> <p>ie:</p> <pre><code>INSERT INTO Users (id, name) VALUES (1, 'Sammitch'); INSERT INTO User_Settings (user_id, name, type, value_int) VALUES (1, 'level', 1, 75); INSERT INTO User_Settings (user_id, name, type, value_str) VALUES (1, 'lang', 0, 'en'); </code></pre> <p>And for the INSERT/UPDATE issue:</p> <pre><code>INSERT INTO User_Settings (user_id, name, type, value_str) VALUES (1, 'lang', 0, 'fr') ON DUPLICATE KEY UPDATE value_str='fr'; </code></pre> <p>Also, as most other people are saying, serializing and storing the preferences is not a particularly good idea because:</p> <ol> <li>You can't retrieve a single value with a query, you must retrieve the entire serialized string, de-serialize it, and discard the unnecessary data.</li> <li>It's easily corruptable, and difficult to recover from.</li> <li>It's a pain in the booty to write a raw query for, ie: to globally fix a certain setting.</li> <li>You're storing what is essentially tabular data within a single table field.</li> </ol> <h2>Sept 2016 Retrospective Edit:</h2> <p>In the intervening time I've had a few arguments with people about how best to store optional settings, as well as the general table structure defined above.</p> <p>While that table structure isn't outright <em>bad</em>, it's not exactly <em>good</em> either. It's trying to make the best of a bad situation. Serialization of optional settings can work so long as you can accommodate for these settings:</p> <ol> <li>All being loaded at once, no picking or choosing.</li> <li>Not being indexable, searchable, or easily modified <em>en masse</em>.</li> </ol> <p>Then you might consider adding a field like <code>optional_settings</code> in the <code>Users</code> table containing a serialized [eg: JSON] form of the settings. You do trade off the above, but it's a more straightforward approach and you can store more complex settings.</p> <p>Also, if you use a LOB type like <code>TEXT</code> for storage the data is not necessarily stored "in the row" at least in MySQL.</p> <p>Anyhow, it's up to <em>you</em> to determine what your application's requirements and constraints are, and make the best choice based on that information.</p>
43,763,858
Change images slider step in TensorBoard
<p>TensorBoard 1.1.0's images history. I would like to set the slider's position (on top of the black image with 7) more precisely, to be able to select any step. Now I can only select e.g. between steps 2050 or 2810. Is that possible? </p> <p>Maybe a place in sources where the 10 constant is hardcoded?</p> <ul> <li><a href="https://i.stack.imgur.com/NQNnt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NQNnt.png" alt="enter image description here"></a></li> </ul>
44,008,016
3
1
null
2017-05-03 15:08:38.053 UTC
7
2018-10-19 07:07:52.717 UTC
null
null
null
null
2,494,561
null
1
31
tensorflow|tensorboard
12,675
<p>I managed to do this by changing <a href="https://github.com/tensorflow/tensorboard/blob/0e1af87fee863542796bddffd398f3cceba482dc/tensorboard/backend/application.py#L58" rel="noreferrer">this</a> line in TensorBoard backend</p>
9,603,696
Use new operator to initialise an array
<p>I want to initialise an array in the format that uses commas to separate the elements surrounded in curly braces e.g:</p> <pre><code>int array[10]={1,2,3,4,5,6,7,8,9,10}; </code></pre> <p>However, I need to use the new operator to allocate the memory e.g:</p> <pre><code>int *array = new int[10]; </code></pre> <p>Is there a way to combine theses methods so that I can allocate the memory using the new operator and initialise the array with the curly braces ?</p>
9,603,834
2
1
null
2012-03-07 14:52:30.347 UTC
9
2017-03-01 09:44:20.34 UTC
null
null
null
null
1,199,397
null
1
37
c++|arrays|new-operator
84,736
<p>In the new Standard for C++ (C++11), you can do this:</p> <pre><code>int* a = new int[10] { 1,2,3,4,5,6,7,8,9,10 }; </code></pre> <p>It's called an <em>initializer list</em>. But in previous versions of the standard that was not possible.</p> <p>The relevant online reference with further details (and very hard to read) is <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2672.htm" rel="noreferrer">here</a>. I also tried it using GCC and the <code>--std=c++0x</code> option and confirmed that it works indeed.</p>
9,301,405
Easy to follow beginners tutorial for Titanium mobile/studio
<p>I'm new to Titanium mobile as well as titanium studio, but have heard good things about it.</p> <p>Can anybody recommend some easy to follow tutorials for beginners? I am also new to Mac - and javascript,- so go easy on me :) </p>
9,307,054
1
1
null
2012-02-15 21:07:16.783 UTC
12
2014-03-12 09:59:17.433 UTC
null
null
null
null
984,153
null
1
43
titanium-mobile
33,548
<p>Here are few links you can follow:</p> <p><a href="http://docs.appcelerator.com/titanium/latest/#!/guide/Quick_Start" rel="noreferrer">1- Titanium Wiki</a></p> <p><a href="http://cssgallery.info/seven-days-with-titanium-day-1-windows-views-navigation-and-tabs/" rel="noreferrer">2- Seven days with Titanium</a></p> <p><a href="http://www.titaniumtips.com/titanium/warehouse.php" rel="noreferrer">3- Titanium WareHouse</a></p>
24,650,218
Image in full screen with img tag
<p>I am using the <code>img</code> tag for my slider images. I need the <strong>image to be full width and height and centered</strong> inside its container.</p> <p>My problem is, when I resize the window width, my image becomes small and its height doesn't follow the window height. I need the <strong>same behaviour as <code>background-size: cover</code> but with the image tag</strong>.</p> <pre><code>background: url(../images/slider/002.jpg) center center; background-size: cover; </code></pre> <p>If I make the image a background, everything works fine, but the slider will not. I need to use the <code>&lt;img&gt;</code> tag. Here is my <a href="https://jsfiddle.net/XW2un/1/" rel="nofollow noreferrer">example</a>.</p>
24,650,874
1
3
null
2014-07-09 09:39:46.817 UTC
10
2021-12-16 09:07:38.51 UTC
2021-08-21 17:56:39.363 UTC
null
775,954
null
3,636,263
null
1
24
html|css|image|responsive-design|background-image
119,749
<p>There are several ways to make an <strong>image cover a div</strong> with the image tag, the simplest is to use the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit?v=control" rel="nofollow noreferrer">object-fit property</a> like this :</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html,body{ margin:0; height:100%; } img{ display:block; width:100%; height:100%; object-fit: cover; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;img src="http://i.imgur.com/5NK0H1e.jpg" alt=""&gt;</code></pre> </div> </div> </p> <p>The browser support is good for object-fit (see <a href="https://caniuse.com/#feat=object-fit" rel="nofollow noreferrer">canIuse</a>) but if you need to support more browsers (like IE), you can use this technique to <strong>center an image fullscreen image with the <code>&lt;img&gt;</code> tag</strong> :</p> <ul> <li>vertical and horizontal centering with absolute positioning, negative top, bottom, left and right values combined with <code>margin:auto;</code></li> <li><strong>image always covers viewport</strong> with 100% <code>min-height</code> and <code>min-width</code></li> </ul> <p><strong><a href="http://jsfiddle.net/webtiki/Yq5KR/135/" rel="nofollow noreferrer">DEMO :</a></strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html,body{ margin:0; height:100%; overflow:hidden; } img{ min-height:100%; min-width:100%; height:auto; width:auto; position:absolute; top:-100%; bottom:-100%; left:-100%; right:-100%; margin:auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;img src="http://i.imgur.com/5NK0H1e.jpg" alt=""&gt;</code></pre> </div> </div> </p>
35,047,557
Unable to upload app to iTunes Connect - iTunes Store operation failed. Authentication timeout
<p>I'm trying to upload my app to iTunes Connect with Xcode. I chose product > archive, choose my account, it compiles and when I try to upload it hand for a long time on:</p> <pre><code>Uploading Archive Sending API usage to iTunes Connect... </code></pre> <p>Then it shows an error message:</p> <p><img src="https://i.stack.imgur.com/C1OK3.png" alt="Archive upload failed with errors: iTunes Store operation failed. Authentication timeout. Please restart Xcode"></p> <p>I've restarted Xcode and the entire machine but still it keeps repeating itself.</p> <p>What's wrong here?</p>
35,048,790
13
3
null
2016-01-27 20:39:44.597 UTC
7
2020-10-25 08:19:58.837 UTC
2016-03-11 14:59:50.86 UTC
null
293,280
null
2,652,208
null
1
28
ios|xcode|app-store-connect
37,485
<p>My solution was to install Application Loader. At first it seemed like it's stuck as well, but after about 10 minutes it started uploading.</p>
845,710
Is there a function that returns the ASCII value of a character? (C++)
<p>I need a function that returns the ASCII value of a character, including spaces, tabs, newlines, etc...</p> <p>On a similar note, what is the function that converts between hexadecimal, decimal, and binary numbers?</p>
845,713
5
0
null
2009-05-10 17:26:03.87 UTC
4
2014-02-06 06:59:32.48 UTC
null
null
null
user98188
null
null
1
18
c++|binary|ascii|character|hex
98,175
<pre><code>char c; int ascii = (int) c; s2.data[j]=(char)count; </code></pre> <p>A char <strong>is</strong> an integer, no need for conversion functions.</p> <p>Maybe you are looking for functions that display integers as a string - using hex, binary or decimal representations?</p>
89,118
Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives
<p>I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file: </p> <p><pre><code> NameVirtualHost 127.0.0.1</p> <p>&lt;VirtualHost 127.0.0.1> ServerName foo.localhost DocumentRoot "C:/xampp/htdocs/foo/public" &lt;/VirtualHost></p> <p>&lt;VirtualHost 127.0.0.1> ServerName bar.localhost DocumentRoot "F:/bar/public" &lt;/VirtualHost> </pre></code></p> <p>When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped.</p> <p>Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.</p>
12,545,200
5
0
null
2008-09-18 01:12:08.037 UTC
15
2020-01-24 16:16:23.447 UTC
2008-09-18 13:32:02.563 UTC
RobbieGee
6,752
RobbieGee
6,752
null
1
57
windows|apache|virtualhost|http-status-code-403
115,752
<p>You did not need</p> <pre><code>Options Indexes FollowSymLinks MultiViews Includes ExecCGI AllowOverride All Order Allow,Deny Allow from all Require all granted </code></pre> <p>the only thing what you need is...</p> <pre><code>Require all granted </code></pre> <p>...inside the directory section.</p> <p>See Apache 2.4 upgrading side:</p> <p><a href="http://httpd.apache.org/docs/2.4/upgrading.html" rel="noreferrer">http://httpd.apache.org/docs/2.4/upgrading.html</a></p>
541,613
How to get started with Symbian (S60 plattorm)
<p>So at my new job one of the platforms we use is S60 (Nokia phones, Symbian OS) and I am getting curious about it, as well feeling the need to help the team a bit from time to time (I actually work on the server side of things for this software).</p> <p>So any good pointers/recommendations/tutorials and shared experiece that might put me in the right direction ?</p> <p>Thanks</p>
546,240
6
0
null
2009-02-12 14:56:41.803 UTC
11
2015-11-06 10:36:10.03 UTC
2009-02-17 12:59:48.303 UTC
sgm
39,892
null
23,238
null
1
15
symbian|mobile-phones|nokia|s60|handheld
1,579
<p>These days, I think it is nearly impossible to <em>begin</em> native (meaning C++) Symbian software development. Nokia, Sony and Motorola don't support their old Symbian phones any more. Most official URLs are broken. Simply obtaining a certificate needed to sign and deploy applications would be a challenge.</p> <p>However, you should still be able to use JavaME to develop software that will run on the remaining Symbian installed base, whatever its current size may be.</p> <p>Shameless plug: <a href="http://www.quickrecipesonsymbianos.com" rel="nofollow noreferrer">http://www.quickrecipesonsymbianos.com</a> was the last best book to be written specifically for developers entering the Symbian OS C++ ecosystem.</p>
1,011,760
What are the technical reasons behind the "Itanium fiasco", if any?
<p>In <a href="http://www.pcmag.com/article2/0,2817,2339629,00.asp" rel="noreferrer">this article</a> Jonh Dvorak calls Itanium "<em>one of the great fiascos of the last 50 years</em>". While he describes the over-optimistic market expectations and the dramatic financial outcome of the idea, he doesn't go into the technical details of this epic fail. I had my chance to work with Itanium for some period of time and I personally loved its architecture, it was so clear and simple and straightforward in comparison to the modern x86 processors architecture...</p> <p>So then what are/were the technical reasons of its failure? Under-performance? Incompatibility with x86 code? Complexity of compilers? Why did this "Itanic" sink?</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/e/e3/Itanium.png" alt="Itanium processor block"></p>
13,825,154
6
10
null
2009-06-18 09:36:38.757 UTC
3
2019-05-21 18:47:25.41 UTC
2017-02-08 14:12:56.94 UTC
null
-1
null
2,351,099
null
1
28
hardware|itanium
7,845
<p>Itanium failed because VLIW for today's workloads is simply an awful idea.</p> <p>Donald Knuth, a widely respected computer scientist, <a href="http://www.informit.com/articles/article.aspx?p=1193856" rel="noreferrer">said in a 2008 interview</a> that "<em>the "Itanium" approach [was] supposed to be so terrific—until it turned out that the wished-for compilers were basically impossible to write.</em>"<sup>1</sup></p> <p>That pretty much nails the problem.</p> <p>For scientific computation, where you get at least a few dozens of instructions per basic block, VLIW probably works fine. There's enough instructions there to create good bundles. For more modern workloads, where oftentimes you get about 6-7 instructions per basic block, it simply doesn't (that's the average, IIRC, for SPEC2000). The compiler simply can't find independent instructions to put in the bundles.</p> <p>Modern x86 processors, with the exception of Intel Atom (pre Silvermont) and I believe AMD E-3**/4**, are all out-of-order processors. They maintain a dynamic instruction window of roughly 100 instructions, and within that window they execute instructions whenever their inputs become ready. If multiple instructions are ready to go and they don't compete for resources, they go together in the same cycle. </p> <p>So how is this different from VLIW? The first key difference between VLIW and out-of-order is that the the out-of-order processor can choose instructions from different basic blocks to execute at the same time. Those instructions are executed speculatively anyway (based on branch prediction, primarily). The second key difference is that out-of-order processors determine these schedules dynamically (i.e., each dynamic instruction is scheduled independently; the VLIW compiler operates on static instructions).</p> <p>The third key difference is that implementations of out-of-order processors can be as wide as wanted, without changing the instruction set (Intel Core has 5 execution ports, other processors have 4, etc). VLIW machines <em>can</em> and do execute multiple bundles at once (if they don't conflict). For example, <a href="https://www.realworldtech.com/ev8-mckinley/5/" rel="noreferrer">early Itanium CPUs execute up to 2 VLIW bundles per clock cycle, 6 instructions</a>, with later designs (<a href="https://www.realworldtech.com/poulson-preview/" rel="noreferrer">2011's Poulson and later</a>) running up to 4 bundles = 12 instructions per clock, with SMT to take those instructions from multiple threads. In that respect, real Itanium hardware is like a traditional in-order superscalar design (like P5 Pentium or Atom), but with more / better ways for the compiler to expose instruction-level parallelism to the hardware (in theory, if it can find enough, which is the problem).</p> <p>Performance-wise with similar specs (caches, cores, etc) they just beat the crap out of Itanium.</p> <p>So why would one buy an Itanium now? Well, the only reason really is HP-UX. If you want to run HP-UX, that's the way to do it...</p> <p>Many compiler writers don't see it this way - they always liked the fact that Itanium gives them more to do, puts them back in control, etc. But they won't admit how miserably it failed. </p> <hr> <p>Footnote 1:</p> <p>This was part of a response about the value of multi-core processors. Knuth was saying parallel processing is hard to take advantage of; finding and exposing fine-grained instruction-level parallelism (and explicit speculation: EPIC) at compile time for a VLIW is also a hard problem, and somewhat related to finding coarse-grained parallelism to split a sequential program or function into multiple threads to automatically take advantage of multiple cores.</p> <p>11 years later he's still basically right: per-thread performance is still very important for most non-server software, and something that CPU vendors focus on because many cores is no substitute.</p>
642,954
IIS7 Cache-Control
<p>I'm trying to do something which I thought would be fairly simple. Get IIS 7 to tell clients they can cache all images on my site for a certain amount of time, let's say 24 hours. </p> <p>I have tried the step on <a href="http://www.galcho.com/Blog/post/2008/02/27/IIS7-How-to-set-cache-control-for-static-content.aspx" rel="noreferrer">http://www.galcho.com/Blog/post/2008/02/27/IIS7-How-to-set-cache-control-for-static-content.aspx</a> but to no avail. I still get requests going to the server with 304s being returned. </p> <p>Does anyone have a way of doing this? I have a graphically intensive site and my users are being hammered (so is my server) every time they request a page. Wierdly the images seem to have "Cache-Control private,max-age=3600" showing up in Firebug but the browser is still requesting them when I press F5.</p>
1,304,839
6
0
null
2009-03-13 14:27:03.623 UTC
39
2016-02-25 01:35:00.013 UTC
2011-12-18 15:20:00.977 UTC
null
938,089
Chris Meek
64,573
null
1
100
asp.net|iis|caching|iis-7
115,000
<p>If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.</p> <p>You can however drop this web.config in the root of the folder or site where you want to set it:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;staticContent&gt; &lt;clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" /&gt; &lt;/staticContent&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>That will inform the client to cache content for 7 days in that folder and all subfolders. </p> <p>You can also do this by editing the IIS7 metabase via <code>appcmd.exe</code>, like so:</p> <pre> \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00" </pre>
683,825
In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?
<p>I'm now using NetBeans as my IDE-of-choice, and it has a plugin for UML modeling. In the class diagram, there are model elements known as <code>Boundary Class</code>, <code>Control Class</code>, and <code>Entity Class</code>. However, I can't find a good definition of them, but I did find <a href="http://www.developer.com/design/article.php/10925_2206791_2" rel="noreferrer">this site</a> on UML Class Diagrams.</p>
17,028,825
6
1
null
2009-03-25 22:46:03.817 UTC
65
2022-02-27 17:21:01.7 UTC
2022-02-27 17:21:01.7 UTC
null
3,723,423
Thomas Owens
572
null
1
104
uml|class-diagram|ecb-pattern
213,469
<p>Robustness diagrams are written after use cases and before class diagrams. They help to identify the roles of use case steps. You can use them to <strong>ensure your use cases are sufficiently robust</strong> to represent usage requirements for the system you're building.</p> <p>They involve:</p> <ol> <li>Actors</li> <li>Use Cases</li> <li><strong><em>Entities</em></strong></li> <li><strong><em>Boundaries</em></strong></li> <li><strong><em>Controls</em></strong></li> </ol> <p>Whereas the <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">Model-View-Controller</a> pattern is used for user interfaces, the Entity-Control-Boundary Pattern (ECB) is used for systems. The following aspects of ECB can be likened to an abstract version of MVC, if that's helpful:</p> <p><img src="https://i.stack.imgur.com/rQPvd.gif" alt="UML notation"></p> <p><strong>Entities</strong> <em>(model)</em><br> Objects representing system data, often from the domain model.</p> <p><strong>Boundaries</strong> <em>(view/service collaborator)</em><br> Objects that interface with system actors (e.g. a <strong>user</strong> or <strong>external service</strong>). Windows, screens and menus are examples of boundaries that interface with users.</p> <p><strong>Controls</strong> <em>(controller)</em><br> Objects that mediate between boundaries and entities. These serve as the glue between boundary elements and entity elements, implementing the logic required to manage the various elements and their interactions. It is important to understand that you may decide to implement controllers within your design as something other than objects – many controllers are simple enough to be implemented as a method of an entity or boundary class for example.</p> <p><strong>Four rules apply to their communication:</strong></p> <ol> <li>Actors can only talk to boundary objects.</li> <li>Boundary objects can only talk to controllers and actors.</li> <li>Entity objects can only talk to controllers.</li> <li>Controllers can talk to boundary objects and entity objects, and to other controllers, but not to actors</li> </ol> <p><strong>Communication allowed:</strong> </p> <pre><code> Entity Boundary Control Entity X X Boundary X Control X X X </code></pre>
448,910
What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?
<p>Can anybody give a clear explanation of how variable assignment really works in Makefiles. </p> <p>What is the difference between :</p> <pre><code> VARIABLE = value VARIABLE ?= value VARIABLE := value VARIABLE += value </code></pre> <p>I have read the <a href="http://www.gnu.org/software/make/manual/make.html#Reading-Makefiles" rel="noreferrer">section</a> in GNU Make's manual, but it still doesn't make sense to me. </p>
448,939
6
0
null
2009-01-15 23:19:02.147 UTC
420
2021-07-07 12:20:11.38 UTC
2017-07-12 08:06:08.183 UTC
null
895,245
mmoris
48,427
null
1
918
makefile|gnu-make
255,143
<h3>Lazy Set</h3> <pre><code>VARIABLE = value </code></pre> <p>Normal setting of a variable, but any other variables mentioned with the <code>value</code> field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared</p> <h3>Immediate Set</h3> <pre><code>VARIABLE := value </code></pre> <p>Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.</p> <h3>Lazy Set If Absent</h3> <pre><code>VARIABLE ?= value </code></pre> <p>Setting of a variable only if it doesn't have a value. <code>value</code> is always evaluated when <code>VARIABLE</code> is accessed. It is equivalent to</p> <pre><code>ifeq ($(origin VARIABLE), undefined) VARIABLE = value endif </code></pre> <p>See the <a href="https://www.gnu.org/software/make/manual/html_node/Flavors.html#Flavors" rel="noreferrer">documentation</a> for more details.</p> <h3>Append</h3> <pre><code>VARIABLE += value </code></pre> <p>Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)</p>
21,224,411
CSS Calc Viewport Units Workaround?
<p>From what I've seen in <a href="https://stackoverflow.com/a/14184433/1191087">other</a> <a href="https://stackoverflow.com/a/14419680/1191087">answers</a>, CSS viewport units can't be used in <code>calc()</code> statements yet. What I would like to achieve is the following statement:</p> <pre><code>height: calc(100vh - 75vw) </code></pre> <p>Is there some workaround way I can achieve this <em>using purely CSS</em> even though the viewport units can't be used in the <code>calc()</code> statement? Or just CSS and HTML? I know I can do it dynamically using javascript, but I'd prefer CSS.</p>
21,279,146
4
9
null
2014-01-20 00:16:15.54 UTC
13
2018-11-21 15:42:03.147 UTC
2017-05-23 11:54:58.043 UTC
null
-1
null
1,191,087
null
1
67
html|css|viewport-units|css-calc
135,248
<p>Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.</p> <h2><strong><a href="http://jsfiddle.net/danield770/tWcwa/">FIDDLE</a></strong> (In IE10+)</h2> <h2>Solution (for other browsers): box-sizing</h2> <p>1) Start of by setting your height as 100vh.</p> <p>2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height. </p> <p>3) Just offset the extra padding-top with a negative margin-top </p> <h2><strong><a href="http://jsfiddle.net/danield770/tWcwa/1/">FIDDLE</a></strong></h2> <pre><code>div { /*height: calc(100vh - 75vw);*/ height: 100vh; margin-top: -75vw; padding-top: 75vw; -moz-box-sizing: border-box; box-sizing: border-box; background: pink; } </code></pre>
21,312,081
How to represent integer infinity?
<p>I need a way to represent an integer number that can be infinite. I'd prefer not to use a floating point type (double.PositiveInfinity) since the number can never be fractional and this might make the API confusing. What is the best way to do this?</p> <p>Edit: One idea I haven't seen yet is using int? with null representing infinity. Are there any good reasons not to do this?</p>
21,312,246
5
13
null
2014-01-23 15:12:54.27 UTC
1
2018-02-08 08:07:56.76 UTC
2018-02-08 08:07:56.76 UTC
null
28,324
null
819,436
null
1
32
c#|infinity
64,447
<p>If you don't need the full range of integer values, you can use the <code>int.MaxValue</code> and <code>int.MinValue</code> constants to represent infinities.</p> <p>However, if the full range of values is required, I'd suggest either creating a wrapper class or simply going for doubles.</p>
21,364,178
Add browser action button in internet explorer BHO
<p>So. I'm working on a BHO in IE and I want to add a <a href="http://developer.chrome.com/extensions/browserAction.html" rel="noreferrer">browser action</a> like this:</p> <p><img src="https://i.stack.imgur.com/LoZV7.png" alt="enter image description here"></p> <p>In internet explorer it would look something like </p> <p><img src="https://i.stack.imgur.com/wOtBo.png" alt="enter image description here"></p> <p>The only tutorials and docs I've found were on creating toolbar items. None mentioned this option. I know this is possible because crossrider let you do this exact thing. I just don't know how.</p> <p>I can't find any documentation on how I would implement this in a BHO. Any pointers are very welcome. </p> <p>I tagged this with C# as a C# solution would probably be simpler but a C++ solution, or any other solution that works is also very welcome.</p>
21,540,353
4
19
null
2014-01-26 13:49:10.29 UTC
13
2014-03-13 10:23:53.92 UTC
2014-01-30 13:23:10.757 UTC
null
1,348,195
null
1,348,195
null
1
39
c#|internet-explorer|winapi|bho|browser-action
4,392
<p>EDIT: <a href="https://github.com/somanuell/SoBrowserAction" rel="noreferrer">https://github.com/somanuell/SoBrowserAction</a></p> <hr> <p>Here is a screen shot of my work in progress.</p> <p><img src="https://i.stack.imgur.com/y9QR3.png" alt="New button in IE9"> </p> <p>The things I did:</p> <p><strong>1. Escaping from the protected mode</strong></p> <p>The BHO Registration must update the <code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Low Rights\ElevationPolicy</code> key. <a href="http://msdn.microsoft.com/en-us/library/bb250462.aspx" rel="noreferrer">See Understanding and Working in Protected Mode Internet Explorer.</a></p> <p>I choose the process way because it's noted as "best practice" and is easier to debug, but the <code>RunDll32Policy</code> may do the trick, too. </p> <p>Locate the <code>rgs</code> file containing your BHO registry settings. It's the one containing the upadte to the Registry Key <code>'Browser Helper Object'</code>. Add to that file the following:</p> <pre><code>HKLM { NoRemove SOFTWARE { NoRemove Microsoft { NoRemove 'Internet Explorer' { NoRemove 'Low Rights' { NoRemove ElevationPolicy { ForceRemove '{AE6E5BFE-B965-41B5-AC70-D7069E555C76}' { val AppName = s 'SoBrowserActionInjector.exe' val AppPath = s '%MODULEPATH%' val Policy = d '3' } } } } } } } </code></pre> <p>The GUID must be a new one, don't use mine, use a GUID Generator. The <code>3</code> value for policy ensures that the broker process will be launched as a medium integrity process. The <code>%MODULEPATH%</code>macro is NOT a predefined one.</p> <p><strong>Why use a macro?</strong> You may avoid that new code in your RGS file, provided that your MSI contains that update to the registry. As dealing with MSI may be painful, it's often easier to provide a "full self registering" package. But if you don't use a macro, you then can't allow the user to choose the installation directory. Using a macro permits to dynamically update the registry with the correct installation directory.</p> <p><strong>How to make the macro works?</strong> Locate the <code>DECLARE_REGISTRY_RESOURCEID</code> macro in the header of your BHO class and comment it out. Add the following function definition in that header:</p> <pre><code>static HRESULT WINAPI UpdateRegistry( BOOL bRegister ) throw() { ATL::_ATL_REGMAP_ENTRY regMapEntries[2]; memset( &amp;regMapEntries[1], 0, sizeof(ATL::_ATL_REGMAP_ENTRY)); regMapEntries[0].szKey = L"MODULEPATH"; regMapEntries[0].szData = sm_szModulePath; return ATL::_pAtlModule-&gt;UpdateRegistryFromResource(IDR_CSOBABHO, bRegister, regMapEntries); } </code></pre> <p>That code is borrowed from the ATL implementation for <code>DECLARE_REGISTRY_RESOURCEID</code> (in my case it's the one shipped with VS2010, check your version of ATL and update code if necessary). The <code>IDR_CSOBABHO</code> macro is the resource ID of the <code>REGISTRY</code> resource adding the RGS in your RC file.</p> <p>The <code>sm_szModulePath</code> variable must contains the installation path of the broker process EXE. I choose to make it a public static member variable of my BHO class. One simple way to set it up is in the <code>DllMain</code> function. When <code>regsvr32</code> load your Dll, <code>DllMain</code> is called, and the registry is updated with the good path.</p> <pre><code>extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { if ( dwReason == DLL_PROCESS_ATTACH ) { DWORD dwCopied = GetModuleFileName( hInstance, CCSoBABHO::sm_szModulePath, sizeof( CCSoBABHO::sm_szModulePath ) / sizeof( wchar_t ) ); if ( dwCopied ) { wchar_t * pLastAntiSlash = wcsrchr( CCSoBABHO::sm_szModulePath, L'\\' ); if ( pLastAntiSlash ) *( pLastAntiSlash ) = 0; } } return _AtlModule.DllMain(dwReason, lpReserved); } </code></pre> <p>Many thanks to Mladen Janković.</p> <p><strong>How to lauch the Broker process?</strong></p> <p>One possible place is in the <code>SetSite</code> implementation. It will be lauched many times, but we will deal with that in the process itself. We will see later that the broker process may benefit from receiving as argument the HWND for the hosting IEFrame. This can be done with the <code>IWebBrowser2::get_HWND</code> method. I suppose here that your already have an <code>IWebBrowser2*</code> member. </p> <pre><code>STDMETHODIMP CCSoBABHO::SetSite( IUnknown* pUnkSite ) { if ( pUnkSite ) { HRESULT hr = pUnkSite-&gt;QueryInterface( IID_IWebBrowser2, (void**)&amp;m_spIWebBrowser2 ); if ( SUCCEEDED( hr ) &amp;&amp; m_spIWebBrowser2 ) { SHANDLE_PTR hWndIEFrame; hr = m_spIWebBrowser2-&gt;get_HWND( &amp;hWndIEFrame ); if ( SUCCEEDED( hr ) ) { wchar_t szExeName[] = L"SoBrowserActionInjector.exe"; wchar_t szFullPath[ MAX_PATH ]; wcscpy_s( szFullPath, sm_szModulePath ); wcscat_s( szFullPath, L"\\" ); wcscat_s( szFullPath, szExeName ); STARTUPINFO si; memset( &amp;si, 0, sizeof( si ) ); si.cb = sizeof( si ); PROCESS_INFORMATION pi; wchar_t szCommandLine[ 64 ]; swprintf_s( szCommandLine, L"%.48s %d", szExeName, (int)hWndIEFrame ); BOOL bWin32Success = CreateProcess( szFullPath, szCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &amp;si, &amp;pi ); if ( bWin32Success ) { CloseHandle( pi.hThread ); CloseHandle( pi.hProcess ); } } } [...] </code></pre> <p><strong>2. Injecting the IEFrame threads</strong></p> <p>It appears that this may be the most complex part, because there are many ways to do it, each one with pros and cons.</p> <p>The broker process, the "injector", may be a short lived one, with one simple argument (a HWND or a TID), which will have to deal with a unique IEFrame, if not already processed by a previous instance.</p> <p>Rather, the "injector" may be a long lived, eventually never ending, process which will have to continually watch the Desktop, processing new IEFrames as they appear. Unicity of the process may be guaranteed by a Named Mutex.</p> <p>For the time being, I will try to go with a KISS principle (Keep It Simple, Stupid). That is: a short lived injector. I know for sure that this will lead to special handling, in the BHO, for the case of a Tab Drag And Drop'ed to the Desktop, but I will see that later.</p> <p>Going that route involves a Dll injection that survives the end of the injector, but I will delegate this to the Dll itself.</p> <p>Here is the code for the injector process. It installs a <code>WH_CALLWNDPROCRET</code> hook for the thread hosting the IEFrame, use <code>SendMessage</code> (with a specific registered message) to immediatly trigger the Dll injection, and then removes the hook and terminates. The BHO Dll must export a <code>CallWndRetProc</code> callback named <code>HookCallWndProcRet</code>. Error paths are omitted.</p> <pre><code>#include &lt;Windows.h&gt; #include &lt;stdlib.h&gt; typedef LRESULT (CALLBACK *PHOOKCALLWNDPROCRET)( int nCode, WPARAM wParam, LPARAM lParam ); PHOOKCALLWNDPROCRET g_pHookCallWndProcRet; HMODULE g_hDll; UINT g_uiRegisteredMsg; int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE, char * pszCommandLine, int ) { HWND hWndIEFrame = (HWND)atoi( pszCommandLine ); wchar_t szFullPath[ MAX_PATH ]; DWORD dwCopied = GetModuleFileName( NULL, szFullPath, sizeof( szFullPath ) / sizeof( wchar_t ) ); if ( dwCopied ) { wchar_t * pLastAntiSlash = wcsrchr( szFullPath, L'\\' ); if ( pLastAntiSlash ) *( pLastAntiSlash + 1 ) = 0; wcscat_s( szFullPath, L"SoBrowserActionBHO.dll" ); g_hDll = LoadLibrary( szFullPath ); if ( g_hDll ) { g_pHookCallWndProcRet = (PHOOKCALLWNDPROCRET)GetProcAddress( g_hDll, "HookCallWndProcRet" ); if ( g_pHookCallWndProcRet ) { g_uiRegisteredMsg = RegisterWindowMessage( L"SOBA_MSG" ); if ( g_uiRegisteredMsg ) { DWORD dwTID = GetWindowThreadProcessId( hWndIEFrame, NULL ); if ( dwTID ) { HHOOK hHook = SetWindowsHookEx( WH_CALLWNDPROCRET, g_pHookCallWndProcRet, g_hDll, dwTID ); if ( hHook ) { SendMessage( hWndIEFrame, g_uiRegisteredMsg, 0, 0 ); UnhookWindowsHookEx( hHook ); } } } } } } if ( g_hDll ) FreeLibrary( g_hDll ); return 0; } </code></pre> <p><strong>3. Surviving Injection: "hook me harder"</strong></p> <p>The temporary loading of the Dll in the main IE process is sufficient to add a new button to the Toolbar. But being able to monitor the <code>WM_COMMAND</code> for that new button requires more: a permanently loaded Dll and a hook still in place despite the end of the hooking process. A simple solution is to hook the thread again, passing the Dll instance handle.</p> <p>As each tab opening will lead to a new BHO instantiation, thus a new injector process, the hook function must have a way to know if the current thread is already hooked (I don't want to just add a hook for each tab opening, that's not clean)</p> <p>Thread Local Storage is the way to go:</p> <ol> <li>Allocate a TLS index in <code>DllMain</code>, for <code>DLL_PROCESS_ATTACH</code>.</li> <li>Store the new <code>HHOOK</code> as TLS data, and use that to know if the thread is already hooked</li> <li>Unhook if necessary, when <code>DLL_THREAD_DETACH</code></li> <li>Free the TLS index in <code>DLL_PROCESS_DETACH</code></li> </ol> <p>That leads to the following code:</p> <pre><code>// DllMain // ------- if ( dwReason == DLL_PROCESS_ATTACH ) { CCSoBABHO::sm_dwTlsIndex = TlsAlloc(); [...] } else if ( dwReason == DLL_THREAD_DETACH ) { CCSoBABHO::UnhookIfHooked(); } else if ( dwReason == DLL_PROCESS_DETACH ) { CCSoBABHO::UnhookIfHooked(); if ( CCSoBABHO::sm_dwTlsIndex != TLS_OUT_OF_INDEXES ) TlsFree( CCSoBABHO::sm_dwTlsIndex ); } // BHO Class Static functions // -------------------------- void CCSoBABHO::HookIfNotHooked( void ) { if ( sm_dwTlsIndex == TLS_OUT_OF_INDEXES ) return; HHOOK hHook = reinterpret_cast&lt;HHOOK&gt;( TlsGetValue( sm_dwTlsIndex ) ); if ( hHook ) return; hHook = SetWindowsHookEx( WH_CALLWNDPROCRET, HookCallWndProcRet, sm_hModule, GetCurrentThreadId() ); TlsSetValue( sm_dwTlsIndex, hHook ); return; } void CCSoBABHO::UnhookIfHooked( void ) { if ( sm_dwTlsIndex == TLS_OUT_OF_INDEXES ) return; HHOOK hHook = reinterpret_cast&lt;HHOOK&gt;( TlsGetValue( sm_dwTlsIndex ) ); if ( UnhookWindowsHookEx( hHook ) ) TlsSetValue( sm_dwTlsIndex, 0 ); } </code></pre> <p>We now have a nearly complete hook function:</p> <pre><code>LRESULT CALLBACK CCSoBABHO::HookCallWndProcRet( int nCode, WPARAM wParam, LPARAM lParam ) { if ( nCode == HC_ACTION ) { if ( sm_uiRegisteredMsg == 0 ) sm_uiRegisteredMsg = RegisterWindowMessage( L"SOBA_MSG" ); if ( sm_uiRegisteredMsg ) { PCWPRETSTRUCT pcwprets = reinterpret_cast&lt;PCWPRETSTRUCT&gt;( lParam ); if ( pcwprets &amp;&amp; ( pcwprets-&gt;message == sm_uiRegisteredMsg ) ) { HookIfNotHooked(); HWND hWndTB = FindThreadToolBarForIE9( pcwprets-&gt;hwnd ); if ( hWndTB ) { AddBrowserActionForIE9( pcwprets-&gt;hwnd, hWndTB ); } } } } return CallNextHookEx( 0, nCode, wParam, lParam); } </code></pre> <p>The code for <code>AddBrowserActionForIE9</code> will be edited later.</p> <p>For IE9, getting the TB is pretty simple:</p> <pre><code>HWND FindThreadToolBarForIE9( HWND hWndIEFrame ) { HWND hWndWorker = FindWindowEx( hWndIEFrame, NULL, L"WorkerW", NULL ); if ( hWndWorker ) { HWND hWndRebar= FindWindowEx( hWndWorker, NULL, L"ReBarWindow32", NULL ); if ( hWndRebar ) { HWND hWndBand = FindWindowEx( hWndRebar, NULL, L"ControlBandClass", NULL ); if ( hWndBand ) { return FindWindowEx( hWndBand, NULL, L"ToolbarWindow32", NULL ); } } } return 0; } </code></pre> <p><strong>4. Processing the Tool Bar</strong></p> <p>That part may be largely improved:</p> <ol> <li>I just created a black and white bitmap, and all was fine, that is: the black pixels where transparent. Each time I tried to add some colors and/or grey levels, the results were awful. I am not fluent, at all, with those "bitmap in toolbar magics"</li> <li>The size of the bitmap should depends on the current size of the other bitmaps already in the toolbar. I just used two bitmaps (one "normal", and one "big")</li> <li>It may be possible to optimize the part which force IE to "redraw" the new state of the toolbar, with a lesser width for the address bar. It works, there is a quick "redraw" phase involving the whole IE Main Window.</li> </ol> <p>See my other answer to the question, as I am currently unable to edit the answer with code format working.</p>
69,406,966
How does alloca() work on a memory level?
<p>I'm trying to figure out how <code>alloca()</code> actually works on a memory level. From the <a href="https://man7.org/linux/man-pages/man3/alloca.3.html" rel="noreferrer">linux man page</a>:</p> <blockquote> <p>The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.</p> </blockquote> <p>Does this mean <code>alloca()</code> will forward the stack pointer by <code>n</code> bytes? Or where exactly is the newly created memory allocated?</p> <p>And isn't this exactly the same as <a href="https://de.wikipedia.org/wiki/Variable_Length_Array" rel="noreferrer">variable length arrays</a>?</p> <p>I know the implementation details are probably left to the OS and stuff. But I want to know how <em>in general</em> this is accomplished.</p>
69,407,054
5
8
null
2021-10-01 13:46:43.5 UTC
null
2021-10-03 07:41:05.743 UTC
2021-10-01 17:19:31.023 UTC
null
1,687,119
null
11,770,390
null
1
44
c|variable-length-array|stack-frame|alloca
2,329
<p>Yes, <code>alloca</code> is functionally equivalent to a local variable length array, i.e. this:</p> <pre><code>int arr[n]; </code></pre> <p>and this:</p> <pre><code>int *arr = alloca(n * sizeof(int)); </code></pre> <p>both allocate space for <code>n</code> elements of type <code>int</code> on the stack. The only differences between <code>arr</code> in each case is that 1) one is an actual array and the other is a pointer to the first element of an array, and 2) the array's lifetime ends with its enclosing scope, while the <code>alloca</code> memory's lifetime ends when the function returns. In both cases the array resides on the stack.</p> <p>As an example, given the following code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;alloca.h&gt; void foo(int n) { int a[n]; int *b=alloca(n*sizeof(int)); int c[n]; printf(&quot;&amp;a=%p, b=%p, &amp;c=%p\n&quot;, (void *)a, (void *)b, (void *)c); } int main() { foo(5); return 0; } </code></pre> <p>When I run this I get:</p> <pre class="lang-none prettyprint-override"><code>&amp;a=0x7ffc03af4370, b=0x7ffc03af4340, &amp;c=0x7ffc03af4320 </code></pre> <p>Which shows that the the memory returned from <code>alloca</code> sits between the memory for the two VLAs.</p> <p>VLAs first appeared in the C standard in C99, but <code>alloca</code> was around well before that. The Linux man page states:</p> <blockquote> <p>CONFORMING TO</p> <p>This function is not in POSIX.1-2001.</p> <p>There is evidence that the alloca() function appeared in 32V, PWB, PWB.2, 3BSD, and 4BSD. There is a man page for it in 4.3BSD. Linux uses the GNU version.</p> </blockquote> <p>BSD 3 dates back to the late 70's, so <code>alloca</code> was an early nonstandardized attempt at VLAs before they were added to the standard.</p> <p>Today, unless you're using a compiler that doesn't support VLAs (such as MSVC), there's really no reason to use this function since VLAs are now a standardized way to get the same functionality.</p>
23,292,159
How to retrieve the SQL used to create a view in Oracle?
<p>In Oracle, to retrieve the SQL used to create a Function, Package, etc, the user_source view can be queried. However, views are not included in this view - nor do they exist in the underlying <code>sys.source$</code>. To access the text of views, the <code>user_views.text</code> column can be used, but this is not exact because Oracle will re-write some parts of the query, for example it will do glob expansion.</p> <p>How can I retrieve the SQL used to create a view, exactly as it was entered, without glob expansion?</p>
23,294,643
5
3
null
2014-04-25 11:45:21.883 UTC
2
2018-12-17 19:45:56.263 UTC
2018-12-17 19:45:56.263 UTC
null
59,087
null
261,017
null
1
24
sql|oracle
99,570
<p>I think the original text is lost:</p> <pre><code>create table t1(id number) / create view t1_vw as select * from t1 / alter table t1 add val varchar2(20) / alter view t1_vw compile / select * from t1_vw / </code></pre> <p>will return only id column. Interesting, but for materialized views original text is preserved.</p>
1,482,395
What happens if both catch and finally blocks throw exception?
<p>What happens if both catch and finally blocks throw exception?</p>
1,482,411
5
4
null
2009-09-26 23:24:13.587 UTC
9
2012-10-22 09:57:57.59 UTC
2012-10-01 06:21:42.437 UTC
null
256,431
null
53,294
null
1
35
c#|java|.net|exception|try-finally
12,361
<p>When the <code>finally</code> block throws an exception, it will effectively hide the exception thrown from the <code>catch</code> block and will be the one ultimately thrown. It is therefore important to either log exceptions when caught, or make sure that the finally block does not itself throw an exception, otherwise you can get exceptions being thrown that are stifled and never seen.</p>
1,788,655
When to use malloc for char pointers
<p>I'm specifically focused on when to use malloc on char pointers</p> <pre><code>char *ptr; ptr = "something"; ...code... ...code... ptr = "something else"; </code></pre> <p>Would a malloc be in order for something as trivial as this? If yes, why? If not, then when is it necessary for char pointers?</p>
1,788,749
5
0
null
2009-11-24 08:28:41.66 UTC
29
2016-01-15 15:44:24.53 UTC
2009-11-24 08:31:25.367 UTC
null
88,851
null
217,639
null
1
39
c|pointers|malloc|char
174,152
<p>As was indicated by others, you don't need to use malloc just to do:</p> <pre><code>const char *foo = "bar"; </code></pre> <p>The reason for that is exactly that <code>*foo</code> <em>is</em> a pointer &mdash; when you initialize <code>foo</code> you're not creating a copy of the string, just a pointer to where <code>"bar"</code> lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.</p> <p>So when should you use malloc? Normally you use <code>strdup()</code> to copy a string, which handles the malloc in the background. e.g.</p> <pre><code>const char *foo = "bar"; char *bar = strdup(foo); /* now contains a new copy of "bar" */ printf("%s\n", bar); /* prints "bar" */ free(bar); /* frees memory created by strdup */ </code></pre> <p>Now, we finally get around to a case where you may want to malloc if you're using <code>sprintf()</code> or, more safely <code>snprintf()</code> which creates / formats a new string.</p> <pre><code>char *foo = malloc(sizeof(char) * 1024); /* buffer for 1024 chars */ snprintf(foo, 1024, "%s - %s\n", "foo", "bar"); /* puts "foo - bar\n" in foo */ printf(foo); /* prints "foo - bar" */ free(foo); /* frees mem from malloc */ </code></pre>
1,683,779
simple text color in rich text box
<p>I can find a million examples of doing reg ex to apply syntax highlighting to a rich text box. but what i need it just a simple way to add in a word of a diffrent color. </p> <p>What would the code be to just put the words "Hello World" into a textbox and have Hello be red and World be green?</p> <p>This code doesnt work.</p> <pre><code>this.richTextBox1.SelectionColor = Color.Red this.richTextBox1.text += "Test" </code></pre>
1,683,833
6
4
null
2009-11-05 21:31:05.917 UTC
null
2021-08-19 23:25:04.267 UTC
null
null
null
null
39,143
null
1
4
vb.net|richtextbox|colors
39,788
<p>Select the text after you put it in and then change the color.</p> <p>For example:</p> <pre><code>richTextBox1.Text += "Test" richTextBox1.Select(richTextBox1.TextLength - 4, 4) richTextBox1.SelectionColor = Color.Red </code></pre>
1,734,806
Is there a way to show alt="text" as a mouseover tooltip in firefox like IE does automatically?
<p>I don't want to repeat alt text in title again? is this possible with any javascript , jquery, css solution? or any solution which can disable to show alt=text and enable title=texr and as a tooltip?</p>
1,734,825
6
1
null
2009-11-14 16:53:47.463 UTC
4
2019-01-10 12:57:40.76 UTC
2009-11-14 17:09:17.383 UTC
null
84,201
null
84,201
null
1
17
jquery|css|firefox|seo|accessibility
59,369
<p><code>alt</code> text is for an <strong>alternative</strong> representation of an image. <code>title</code> text is for tooltips.</p> <p>IE's behavior is <strong>incorrect</strong> in this regard, and Firefox will never implement it. (The bug in the Bugzilla database is <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=25537" rel="noreferrer">#25537</a>, which is VERIFIED WONTFIX.)</p> <p>Not only that, but even <a href="https://web.archive.org/web/20090624020206/http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=334225" rel="noreferrer">Microsoft has admitted that their behavior is incorrect</a>, and <strong>IE 8 doesn't show <code>alt</code> text as tooltips anymore</strong>!.</p> <p>So don't rely on <code>alt</code> text being displayed as a tooltip. Use <code>title</code> instead.</p>
2,309,046
Making ListView scrollable in vertical direction
<p>I am using a <code>System.Windows.Forms.ListView</code> with <code>checkboxes = true</code>. I can see that when the list items are more than what can fit, I get a horizontal scroll bar. I tried to find any properties to change scroll bar orientation. Is there any way to make it scrollable in vertical direction?</p>
2,309,205
6
0
null
2010-02-22 05:41:36.513 UTC
4
2019-11-01 13:54:22.82 UTC
2019-11-01 13:54:22.82 UTC
null
6,113,711
null
232,899
null
1
37
c#|winforms|listview|scrollable
83,822
<p>You need to Set </p> <pre><code>Listview1.Scrollable = true; Listview1.View = View.Details </code></pre> <p>This will only work correctly if you have added some columns in your Listview1, So add a dummy column. like, </p> <pre><code>ColumnHeader header = new ColumnHeader(); header.Text = ""; header.Name = "col1"; listView1.Columns.Add(header); </code></pre>
1,575,111
Can an XSLT insert the current date?
<p>A program we use in my office exports reports by translating a XML file it exports with an XSLT file into XHTML. I'm rewriting the XSLT to change the formatting and to add more information from the source XML File.</p> <p>I'd like to include the date the file was created in the final report. But the current date/time is not included in the original XML file, nor do I have any control on how the XML file is created. There doesn't seem to be any date functions building into XSLT that will return the current date. </p> <p>Does anyone have any idea how I might be able to include the current date during my XSLT transformation?</p>
1,575,134
6
1
null
2009-10-15 21:14:49.157 UTC
19
2022-03-31 12:49:20.323 UTC
null
null
null
null
88,427
null
1
100
xslt|xhtml
200,726
<h2>XSLT 2</h2> <p>Date functions are available natively, such as:</p> <pre><code>&lt;xsl:value-of select="current-dateTime()"/&gt; </code></pre> <p>There is also <code>current-date()</code> and <code>current-time()</code>.</p> <h2>XSLT 1</h2> <p>Use the EXSLT date and times extension package.</p> <ol> <li>Download the <a href="http://www.exslt.org/date/index.html" rel="noreferrer">date and times</a> package from <a href="https://github.com/exslt/exslt.github.io/tree/master/date" rel="noreferrer">GitHub</a>.</li> <li>Extract <code>date.xsl</code> to the location of your XSL files.</li> <li>Set the stylesheet header.</li> <li>Import <code>date.xsl</code>.</li> </ol> <p>For example:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:date="http://exslt.org/dates-and-times" extension-element-prefixes="date" ...&gt; &lt;xsl:import href="date.xsl" /&gt; &lt;xsl:template match="//root"&gt; &lt;xsl:value-of select="date:date-time()"/&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p></p>
2,101,149
How to I serialize a large graph of .NET object into a SQL Server BLOB without creating a large buffer?
<p>We have code like:</p> <pre><code>ms = New IO.MemoryStream bin = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bin.Serialize(ms, largeGraphOfObjects) dataToSaveToDatabase = ms.ToArray() // put dataToSaveToDatabase in a Sql server BLOB </code></pre> <p>But the memory steam allocates a <strong>large buffer</strong> from the large memory heap that is giving us problems. So how can we stream the data without needing enough free memory to hold the serialized objects.</p> <p>I am looking for a way to get a Stream from SQL server that can then be passed to bin.Serialize() so avoiding keeping all the data in my processes memory.</p> <p><em>Likewise for reading the data back...</em></p> <hr /> <p><strong>Some more background.</strong></p> <p>This is part of a complex numerical processing system that processes data in near real time looking for equipment problems etc, the serialization is done to allow a restart when there is a problem with data quality from a data feed etc. (We store the data feeds and can rerun them after the operator has edited out bad values.)</p> <p>Therefore we serialize the object a lot more often then we de-serialize them.</p> <p>The objects we are serializing include <strong>very large arrays</strong> mostly of doubles as well as a lot of small “more normal” objects. We are pushing the memory limit on 32 bit systems and make the garbage collector work very hard. (Effects are being made elsewhere in the system to improve this, e.g. reusing large arrays rather then create new arrays.)</p> <p>Often the serialization of the state is the <a href="http://www.usingenglish.com/reference/idioms/last+straw.html" rel="nofollow noreferrer">last straw</a> that causes an out of memory exception; the peak of our memory usage is always during this serialization step.</p> <p>I <em>think</em> we get large memory pool fragmentation when we de-serialize the object, I expect there are also other problems with large memory pool fragmentation given the size of the arrays. (This has not yet been investigated, as the person that first looked at this is a numerical processing expert, not a memory management expert.)</p> <p>Our customers use a mix of SQL Server 2000, 2005 and 2008 and we would rather not have different code paths for each version of SQL Server if possible.</p> <p>We can have many active models at a time (in different processes, across many machines), each model can have many saved states. Hence the saved state is stored in a database blob rather then a file.</p> <p>As the spread of saving the state is important, I would rather not serialize the object to a file, and then put the file in a BLOB one block at a time.</p> <p><strong>Other related questions I have asked</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/2101346/how-to-stream-data-from-to-sql-server-blob-fields">How to Stream data from/to SQL Server BLOB fields?</a></li> <li><a href="https://stackoverflow.com/questions/2116291/is-there-a-sqlfilestream-like-class-that-works-with-sql-server-2005">Is there a SqlFileStream like class that works with Sql Server 2005?</a></li> </ul>
2,151,491
7
2
null
2010-01-20 12:06:03.313 UTC
25
2021-07-08 14:23:25.867 UTC
2021-07-08 14:23:25.867 UTC
null
431,111
null
57,159
null
1
28
.net|sql-server|serialization|ado.net|memory-management
10,298
<p>There is no built-in ADO.Net functionality to handle this really gracefully for large data. The problem is two fold:</p> <ul> <li>there is no API to 'write' into a SQL command(s) or parameters as into a stream. The parameter types that accept a stream (like <code>FileStream</code>) accept the stream to <strong>READ</strong> from it, which does not agree with the serialization semantics of <em>write</em> into a stream. No matter which way you turn this, you end up with a in memory copy of the entire serialized object, bad.</li> <li>even if the point above would be solved (and it cannot be), the TDS protocol and the way SQL Server accepts parameters do not work well with large parameters as the entire request has to be first received before it is launched into execution and this would create additional copies of the object inside SQL Server.</li> </ul> <p>So you really have to approach this from a different angle. Fortunately, there is a fairly easy solution. The trick is to use the highly efficient <code>UPDATE .WRITE</code> syntax and pass in the chunks of data one by one, in a series of T-SQL statements. This is the MSDN recommended way, see <a href="http://msdn.microsoft.com/en-us/library/bb399384(VS.100).aspx" rel="nofollow noreferrer">Modifying Large-Value (max) Data in ADO.NET</a>. This looks complicated, but is actually trivial to do and plug into a Stream class.</p> <hr> <p><strong>The BlobStream class</strong></p> <p>This is the bread and butter of the solution. A Stream derived class that implements the Write method as a call to the T-SQL BLOB WRITE syntax. Straight forward, the only thing interesting about it is that it has to keep track of the first update because the <code>UPDATE ... SET blob.WRITE(...)</code> syntax would fail on a NULL field:</p> <pre><code>class BlobStream: Stream { private SqlCommand cmdAppendChunk; private SqlCommand cmdFirstChunk; private SqlConnection connection; private SqlTransaction transaction; private SqlParameter paramChunk; private SqlParameter paramLength; private long offset; public BlobStream( SqlConnection connection, SqlTransaction transaction, string schemaName, string tableName, string blobColumn, string keyColumn, object keyValue) { this.transaction = transaction; this.connection = connection; cmdFirstChunk = new SqlCommand(String.Format(@" UPDATE [{0}].[{1}] SET [{2}] = @firstChunk WHERE [{3}] = @key" ,schemaName, tableName, blobColumn, keyColumn) , connection, transaction); cmdFirstChunk.Parameters.AddWithValue("@key", keyValue); cmdAppendChunk = new SqlCommand(String.Format(@" UPDATE [{0}].[{1}] SET [{2}].WRITE(@chunk, NULL, NULL) WHERE [{3}] = @key" , schemaName, tableName, blobColumn, keyColumn) , connection, transaction); cmdAppendChunk.Parameters.AddWithValue("@key", keyValue); paramChunk = new SqlParameter("@chunk", SqlDbType.VarBinary, -1); cmdAppendChunk.Parameters.Add(paramChunk); } public override void Write(byte[] buffer, int index, int count) { byte[] bytesToWrite = buffer; if (index != 0 || count != buffer.Length) { bytesToWrite = new MemoryStream(buffer, index, count).ToArray(); } if (offset == 0) { cmdFirstChunk.Parameters.AddWithValue("@firstChunk", bytesToWrite); cmdFirstChunk.ExecuteNonQuery(); offset = count; } else { paramChunk.Value = bytesToWrite; cmdAppendChunk.ExecuteNonQuery(); offset += count; } } // Rest of the abstract Stream implementation } </code></pre> <hr> <p><strong>Using the BlobStream</strong></p> <p>To use this newly created blob stream class you plug into a <code>BufferedStream</code>. The class has a trivial design that handles only writing the stream into a column of a table. I'll reuse a table from another example:</p> <pre><code>CREATE TABLE [dbo].[Uploads]( [Id] [int] IDENTITY(1,1) NOT NULL, [FileName] [varchar](256) NULL, [ContentType] [varchar](256) NULL, [FileData] [varbinary](max) NULL) </code></pre> <p>I'll add a dummy object to be serialized:</p> <pre><code>[Serializable] class HugeSerialized { public byte[] theBigArray { get; set; } } </code></pre> <p>Finally, the actual serialization. We'll first insert a new record into the <code>Uploads</code> table, then create a <code>BlobStream</code> on the newly inserted Id and call the serialization straight into this stream:</p> <pre><code>using (SqlConnection conn = new SqlConnection(Settings.Default.connString)) { conn.Open(); using (SqlTransaction trn = conn.BeginTransaction()) { SqlCommand cmdInsert = new SqlCommand( @"INSERT INTO dbo.Uploads (FileName, ContentType) VALUES (@fileName, @contentType); SET @id = SCOPE_IDENTITY();", conn, trn); cmdInsert.Parameters.AddWithValue("@fileName", "Demo"); cmdInsert.Parameters.AddWithValue("@contentType", "application/octet-stream"); SqlParameter paramId = new SqlParameter("@id", SqlDbType.Int); paramId.Direction = ParameterDirection.Output; cmdInsert.Parameters.Add(paramId); cmdInsert.ExecuteNonQuery(); BlobStream blob = new BlobStream( conn, trn, "dbo", "Uploads", "FileData", "Id", paramId.Value); BufferedStream bufferedBlob = new BufferedStream(blob, 8040); HugeSerialized big = new HugeSerialized { theBigArray = new byte[1024 * 1024] }; BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(bufferedBlob, big); trn.Commit(); } } </code></pre> <hr> <p>If you monitor the execution of this simple sample you'll see that nowhere is a large serialization stream created. The sample will allocate the array of [1024*1024] but that is for demo purposes to have something to serialize. This code serializes in a buffered manner, chunk by chunk, using the SQL Server BLOB recommended update size of 8040 bytes at a time. </p>
1,694,544
Cross-browser development
<p>I'm developing a web application for a new service, starting from Firefox 3.5.</p> <p>The interface design is tableless, only using divs + CSS &amp; performance-blessed practices.</p> <p>Now, while being compatible with Safari has taken just a small amount of time, IE is a pain.</p> <p>My question is: is there anything out there that could be used to speedup cross-browser checking? I already know many points of difference between FF and IE for instance, but a specific tool would maybe help some more.</p> <p>Could you suggest one, if any?</p> <p>Thanks,</p> <p>Scarlet</p>
1,694,566
8
0
null
2009-11-07 21:49:56.36 UTC
24
2019-07-23 14:39:19.093 UTC
2013-01-14 11:32:14.497 UTC
null
617,450
null
15,908
null
1
19
javascript|css|internet-explorer|firefox|cross-browser
4,178
<h3>Cross Browser Development</h3> <p>No tool can ever make up for bad behaviour, but they can sure make life easier on you.</p> <p>That being said, you should really come up with a workflow that lets you optimize for cross-browser compatability in the least amount of work spent. If that means small iterative or large monolithical steps for you, well that is up to you to decide. But generally working against several browsers during development saves you if not time at least a major headache on d-day.</p> <h3>List of tools/resources I find useful</h3> <ul> <li><a href="http://seleniumhq.org/" rel="noreferrer">Selenium</a> is a tool for frontend testing</li> <li><a href="http://my-debugbar.com/wiki/IETester/HomePage" rel="noreferrer">IETester</a> lets you view a page in different IE versions</li> <li><a href="http://browsershots.org/" rel="noreferrer">Browsershots</a> lets you view the page on different platforms as well</li> <li><a href="http://www.google.com" rel="noreferrer">Google</a> lets you search for known and obscure IE perversions</li> <li><a href="http://www.ie6nomore.com/" rel="noreferrer">IE 6 No More</a> saves you a lot of headache not bothering about the preshistorical crap that goes by the name of IE 6</li> <li><a href="http://developer.yahoo.com/yui/articles/gbs/" rel="noreferrer">YUI Graded Browser Support</a> - make sure you know which browsers to focus on</li> <li><a href="http://jquery.com/" rel="noreferrer">jQuery</a> - cross browser javascript library</li> <li><a href="http://developer.yahoo.com/yui/3/cssreset/" rel="noreferrer">YUI 3: Reset CSS</a> - reset your CSS (link contains useful information as well as the CSS)</li> <li><a href="http://net.tutsplus.com/tutorials/html-css-techniques/9-most-common-ie-bugs-and-how-to-fix-them/" rel="noreferrer">9 Most Common IE Bugs and How to Fix Them</a> - very useful tips on how to get the most bang for the buck by fixing the common problems first.</li> <li><a href="http://www.good-tutorials.com/tutorials/css/cross-browser-development" rel="noreferrer">Cross browser development</a> contains lots of useful tutorials regarding cross browser development.</li> </ul> <h3>References</h3> <p><a href="https://stackoverflow.com/questions/426190/selenium-alternatives">Selenium alternatives</a> / <a href="http://crossbrowsertesting.com/" rel="noreferrer">Cross Browser Testing</a> / <a href="http://litmusapp.com/" rel="noreferrer">Litmus</a></p>
1,532,915
"Undo" feature in Visual Studio 2008 stops working
<p>I'll be coding along in Visual Studio 2008, and eventually I make a mistake. I press <kbd>CTRL</kbd> - <kbd>Z</kbd> to undo and NOTHING HAPPENS. I'm not talking about anything complicated, like undoing a search and replace across multiple files that weren't open. I am talking about undoing a cut &amp; paste action, or simply the typing of text.</p> <p>It's frustrating, do you know of any work-arounds?</p> <p>I save often, so usually I can just close the file, re-open it, and the undo feature works again. Then, eventually (maybe in 20 seconds, maybe in an hour, maybe not at all), undo breaks again. This is really annoying, because I lose my place, my train of thought, the window size and position, and the split pane position when I have to close and re-open the file.</p> <p>Details that might help:</p> <ol> <li>I have the MDI interface enabled.</li> <li>I have Resharper installed.</li> <li>I have VisualSVN installed.</li> <li>Using Windows 7 x64 RTM</li> <li>When undo breaks, the "Undo" option in the edit menu is grayed out. As I continue to edit my document, the option stays grayed out until I close and re-open the document. This demonstrates that it's not just some other app stealing the hotkey. The whole feature stops working.</li> <li>I use a Logitech G19 (can't imagine that's it, but it's not a super popular keyboard, and it does things that are unusual for a keyboard)</li> </ol> <p>I haven't yet taken the painful and annoying troubleshooting steps of reverting to a stripped-down Visual Studio 2008 install (default options, no plugins) and slowly building back up until I begin to experience the issue.</p> <p>Before doing that I wanted to see if anyone else has experienced this and fixed it.</p> <p>So, has <kbd>CTRL</kbd> - <kbd>Z</kbd> ever stopped working for you? Did you fix it?</p> <p>Am I doing something stupid because this is actually a feature? Like, maybe some hotkey I am accidentally hitting or some action I am taking disables undo?</p>
1,736,964
8
2
null
2009-10-07 17:03:29.73 UTC
9
2019-02-24 16:14:01 UTC
2019-02-24 16:14:01 UTC
null
4,157,124
null
13,700
null
1
32
visual-studio-2008
23,176
<p>I've come across the same issue - and I too use VisualSVN and ReShaper. What version of ReSharper are you using, 4.5.x?</p> <p>I've found it appearing with 4.5.x but a recent EAP build (I can't recall which) did address it for me after I reset the Keyboard layout in Visual Studio.</p> <p>So first as others have stated, try disabling ReSharper (Addin Manager, until startup too) restart (the IDE) and see if it appears whilst your working (after resetting the keyboard layout).</p>
1,394,550
How to select the first element in the dropdown using jquery?
<p>I want to know how to select the first option in all select tags on my page using jquery.</p> <p>tried this:</p> <pre><code>$('select option:nth(0)').attr("selected", "selected"); </code></pre> <p>But didn't work</p>
1,394,573
9
0
null
2009-09-08 15:09:02.213 UTC
19
2019-04-02 05:11:51.68 UTC
null
null
null
null
20,126
null
1
109
javascript|jquery|html
228,978
<p>Try this out...</p> <pre><code>$('select option:first-child').attr("selected", "selected"); </code></pre> <p>Another option would be this, but it will only work for one drop down list at a time as coded below:</p> <pre><code>var myDDL = $('myID'); myDDL[0].selectedIndex = 0; </code></pre> <p>Take a look at this post on how to set based on value, its interesting but won't help you for this specific issue:</p> <p><a href="https://stackoverflow.com/questions/499405/change-selected-value-of-drop-down-list-with-jquery">Change the selected value of a drop-down list with jQuery</a></p>
2,157,914
Can vim monitor realtime changes to a file
<p>My question is similar to this <a href="https://stackoverflow.com/questions/18632/how-to-monitor-a-text-file-in-realtime">how to monitor a text file in realtime</a> but I want to do it in vim. I know I can read an opened file use <code>tail -f sample.xml</code> file, and when new content is written to the file, it'll also write the new content to my screen. Can I have vim automatically fill the new data when a file is updated?</p>
2,158,128
9
1
null
2010-01-28 21:02:14.89 UTC
23
2021-09-14 09:19:47.8 UTC
2017-05-23 12:26:07.92 UTC
anon
-1
null
235,878
null
1
115
vim
50,397
<p>You can <code>:set autoread</code> so that vim reads the file when it changes. However (depending on your platform), you have to give it focus.</p> <p>From the help:</p> <blockquote> <p>When a file has been detected to have been changed outside of Vim and it has not been changed inside of Vim, automatically read it again. When the file has been deleted this is not done.</p> </blockquote>
1,515,730
Is there a command like "watch" or "inotifywait" on the Mac?
<p>I want to watch a folder on my Mac and then execute a bash script, passing it the name of whatever file/folder was just moved into or created in the watched directory.</p>
13,807,906
16
3
null
2009-10-04 06:09:48.157 UTC
167
2022-05-18 07:44:46.8 UTC
2022-05-18 07:44:46.8 UTC
null
365,102
null
138,541
null
1
341
macos|watch|inotify
152,277
<h1>fswatch</h1> <p><a href="https://github.com/alandipert/fswatch" rel="noreferrer"><code>fswatch</code></a> is a small program using the Mac OS X FSEvents API to monitor a directory. When an event about any change to that directory is received, the specified shell command is executed by <code>/bin/bash</code></p> <p>If you're on GNU/Linux, <a href="http://linux.die.net/man/1/inotifywatch" rel="noreferrer"><code>inotifywatch</code></a> (part of the <code>inotify-tools</code> package on most distributions) provides similar functionality.</p> <p><strong>Update:</strong> <code>fswatch</code> can now be used across many platforms including BSD, Debian, and Windows.</p> <h2>Syntax / A Simple Example</h2> <p>The new way that can watch multiple paths - for <strong>versions 1.x and higher</strong>:</p> <pre><code>fswatch -o ~/path/to/watch | xargs -n1 -I{} ~/script/to/run/when/files/change.sh </code></pre> <blockquote> <p>Note: The number output by <code>-o</code> will get added to the end of the <code>xargs</code> command if not for the <code>-I{}</code>. If you do choose to use that number, place <code>{}</code> anywhere in your command.</p> </blockquote> <p>The older way for <strong>versions 0.x</strong>:</p> <pre><code>fswatch ~/path/to/watch ~/script/to/run/when/files/change.sh </code></pre> <h2>Installation with Homebrew</h2> <p>As of 9/12/13 it was added back in to <a href="http://brew.sh/" rel="noreferrer">homebrew</a> - yay! So, update your formula list (<code>brew update</code>) and then all you need to do is:</p> <pre><code>brew install fswatch </code></pre> <h2>Installation without Homebrew</h2> <p>Type these commands in <code>Terminal.app</code></p> <pre><code>cd /tmp git clone https://github.com/alandipert/fswatch cd fswatch/ make cp fswatch /usr/local/bin/fswatch </code></pre> <p>If you don't have a <code>c</code> compiler on your system you may need to install Xcode or Xcode command line tools - both free. However, if that is the case, you should probably just <a href="http://brew.sh/" rel="noreferrer">check out homebrew</a>.</p> <h2>Additional Options for <code>fswatch</code> version 1.x</h2> <pre><code>Usage: fswatch [OPTION] ... path ... Options: -0, --print0 Use the ASCII NUL character (0) as line separator. -1, --one-event Exit fsw after the first set of events is received. -e, --exclude=REGEX Exclude paths matching REGEX. -E, --extended Use exended regular expressions. -f, --format-time Print the event time using the specified format. -h, --help Show this message. -i, --insensitive Use case insensitive regular expressions. -k, --kqueue Use the kqueue monitor. -l, --latency=DOUBLE Set the latency. -L, --follow-links Follow symbolic links. -n, --numeric Print a numeric event mask. -o, --one-per-batch Print a single message with the number of change events. in the current batch. -p, --poll Use the poll monitor. -r, --recursive Recurse subdirectories. -t, --timestamp Print the event timestamp. -u, --utc-time Print the event time as UTC time. -v, --verbose Print verbose output. -x, --event-flags Print the event flags. See the man page for more information. </code></pre>
1,954,746
Using reflection in C# to get properties of a nested object
<p>Given the following objects:</p> <pre><code>public class Customer { public String Name { get; set; } public String Address { get; set; } } public class Invoice { public String ID { get; set; } public DateTime Date { get; set; } public Customer BillTo { get; set; } } </code></pre> <p>I'd like to use reflection to go through the <code>Invoice</code> to get the <code>Name</code> property of a <code>Customer</code>. Here's what I'm after, assuming this code would work:</p> <pre><code>Invoice inv = GetDesiredInvoice(); // magic method to get an invoice PropertyInfo info = inv.GetType().GetProperty("BillTo.Address"); Object val = info.GetValue(inv, null); </code></pre> <p>Of course, this fails since "BillTo.Address" is not a valid property of the <code>Invoice</code> class.</p> <p>So, I tried writing a method to split the string into pieces on the period, and walk the objects looking for the final value I was interested in. It works okay, but I'm not entirely comfortable with it:</p> <pre><code>public Object GetPropValue(String name, Object obj) { foreach (String part in name.Split('.')) { if (obj == null) { return null; } Type type = obj.GetType(); PropertyInfo info = type.GetProperty(part); if (info == null) { return null; } obj = info.GetValue(obj, null); } return obj; } </code></pre> <p>Any ideas on how to improve this method, or a better way to solve this problem?</p> <p><strong>EDIT</strong> after posting, I saw a few related posts... There doesn't seem to be an answer that specifically addresses this question, however. Also, I'd still like the feedback on my implementation.</p>
29,823,444
16
5
null
2009-12-23 19:10:53.293 UTC
20
2022-07-22 18:32:11.643 UTC
null
null
null
null
197,772
null
1
95
c#|reflection
106,917
<p>I use following method to get the values from (nested classes) properties like</p> <p><strong>"Property"</strong></p> <p><strong>"Address.Street"</strong></p> <p><strong>"Address.Country.Name"</strong></p> <pre><code> public static object GetPropertyValue(object src, string propName) { if (src == null) throw new ArgumentException("Value cannot be null.", "src"); if (propName == null) throw new ArgumentException("Value cannot be null.", "propName"); if(propName.Contains("."))//complex type nested { var temp = propName.Split(new char[] { '.' }, 2); return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]); } else { var prop = src.GetType().GetProperty(propName); return prop != null ? prop.GetValue(src, null) : null; } } </code></pre> <p>Here is the Fiddle: <a href="https://dotnetfiddle.net/PvKRH0" rel="noreferrer">https://dotnetfiddle.net/PvKRH0</a></p>
8,879,614
Facing a file permission error while running CakePHP in Ubuntu 10.4
<p>I have installed CakePHP 2.0 framwork using steps below:</p> <pre><code>1. Start the terminal 2. sudo mkdir /var/www/cakephp 3.sudo cp -r ~/cakephp/* /var/www/cakephp </code></pre> <p>Change tmp folder permisssion </p> <pre><code>4. sudo chmod -R 777 cakephp/app/tmp </code></pre> <p>Enable mod-rewrite </p> <pre><code>5. sudo a2enmod rewrite </code></pre> <p>Open file /etc/apache2/sites-enabled/000-default and change <code>AllowOverride None</code> to <code>AllowOverride All</code> </p> <pre><code>6. sudo vim /etc/apache2/sites-enabled/000-default </code></pre> <p>Restart Apache </p> <pre><code>7. sudo /etc/init.d/apache2 restart </code></pre> <p>I opened my browser and typed address <a href="http://localhost/cakephp/">http://localhost/cakephp/</a> and I seaw this error message:</p> <blockquote> <p>Warning: _cake_core_ cache was unable to write 'cake_dev_en-us' to File cache in /var/www /cakephp/lib/Cake/Cache/Cache.php on line 310<br> Warning: _cake_core_ cache was unable to write 'cake_dev_en-us' to File cache in /var/www/cakephp/lib/Cake/Cache/Cache.php on line 310<br> Warning: /var/www/cakephp/app/tmp/cache/persistent/ is not writable in /var/www/cakephp /lib/Cake/Cache/Engine/FileEngine.php on line 320<br> Warning: /var/www/cakephp/app/tmp/cache /models/ is not writable in /var/www/cakephp/lib/Cake/Cache/Engine/FileEngine.php on line 320<br> Warning: /var/www/cakephp/app/tmp/cache/ is not writable in /var/www/cakephp/lib/Cake /Cache/Engine/FileEngine.php on line 320</p> </blockquote>
8,879,796
6
2
null
2012-01-16 11:52:15.197 UTC
9
2019-09-11 12:58:25.217 UTC
2012-01-16 12:01:03 UTC
null
502,381
null
260,737
null
1
19
cakephp|ubuntu-10.04
58,984
<p>The command <code>sudo chmod -R 777 cakephp/app/tmp</code> only made <code>tmp</code> writable, you should make cache and it's subdirectories writable as well, otherwise Cake can't write the cache files to the cache directory in tmp.</p> <p>So, these directories should be writable:</p> <pre><code>cakephp/app/tmp/cache cakephp/app/tmp/cache/persistent cakephp/app/tmp/cache/models </code></pre> <p>Make sure the log directory is writable as well: <code>cakephp/app/tmp/logs</code>.</p>
17,773,938
Add a list item through JavaScript
<p>So, I am trying to print out an array that gets user input text added to it, but what I want to print out is an ordered list of the array. As you can see, (if you run my code) the list item just keeps getting the user input added to it, and no new list items are added with people's names.</p> <p>Here is the code below:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; First name: &lt;input type=&quot;text&quot; id=&quot;firstname&quot;&gt;&lt;br&gt; &lt;script type=&quot;text/javascript&quot;&gt; var x= []; function changeText2(){ var firstname = document.getElementById('firstname').value; document.getElementById('boldStuff2').innerHTML = firstname; x.push(firstname); document.getElementById('demo').innerHTML = x; } &lt;/script&gt; &lt;p&gt;Your first name is: &lt;b id='boldStuff2'&gt;&lt;/b&gt; &lt;/p&gt; &lt;p&gt; Other people's names: &lt;/p&gt; &lt;ol&gt; &lt;li id = &quot;demo&quot;&gt; &lt;/li&gt; &lt;/ol&gt; &lt;input type='button' onclick='changeText2()' value='Submit'/&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
17,774,064
4
1
null
2013-07-21 15:30:48.47 UTC
6
2021-04-02 09:46:11.823 UTC
2021-04-02 09:46:11.823 UTC
null
9,193,372
null
2,581,598
null
1
36
javascript|dom
175,158
<p>If you want to create a <code>li</code> element for each input/name, then you have to create it, with <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.createElement"><code>document.createElement</code> <em><sup>[MDN]</sup></em></a>.</p> <p>Give the list the ID:</p> <pre><code>&lt;ol id="demo"&gt;&lt;/ol&gt; </code></pre> <p>and get a reference to it:</p> <pre><code>var list = document.getElementById('demo'); </code></pre> <p>In your event handler, create a new list element with the input value as content and append to the list with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild"><code>Node.appendChild</code> <em><sup>[MDN]</sup></em></a>:</p> <pre><code>var firstname = document.getElementById('firstname').value; var entry = document.createElement('li'); entry.appendChild(document.createTextNode(firstname)); list.appendChild(entry); </code></pre> <p><a href="http://jsfiddle.net/Gmyag/"><strong>DEMO</strong></a></p>
42,020,577
Storing Objects in localStorage
<p>I have an array like this:</p> <pre><code>[{name:"test", time:"Date 2017-02-03T08:38:04.449Z"}] </code></pre> <p>I stored it in <code>localstorage</code> and when I retrieving data from <code>localstorage</code> I got the value:</p> <pre><code>[object, object] </code></pre> <p>How can I solve this issue?</p> <p><strong>config.ts</strong></p> <pre><code>import { Injectable } from "@angular/core"; @Injectable() export class TokenManager { public tokenKey: string = 'app_token'; constructor() { } store(content) { var contentData; console.log("inside localstorsge store:", content); contentData = content.map( (data) =&gt; data.name ) console.log("contentData:", contentData) localStorage.setItem(this.tokenKey, content); } retrieve() { console.log("inside localstorage"); let storedToken: any = localStorage.getItem(this.tokenKey); console.log("storedToken:", storedToken);//====&gt; here this console is[object object] if (!storedToken) throw 'no token found'; return storedToken; } } </code></pre>
42,020,639
4
5
null
2017-02-03 09:11:53.443 UTC
18
2020-01-21 06:04:31.97 UTC
2018-09-17 04:58:13.763 UTC
null
4,887,159
null
5,912,433
null
1
67
javascript|angular|typescript
121,727
<p>local storage limited to handle only string key/value pairs you can do like below using <code>JSON.stringify</code> and while getting value <code>JSON.parse</code></p> <pre><code>var testObject ={name:"test", time:"Date 2017-02-03T08:38:04.449Z"}; </code></pre> <p>Put the object into storage:</p> <pre><code>localStorage.setItem('testObject', JSON.stringify(testObject)); </code></pre> <p>Retrieve the object from storage:</p> <pre><code>var retrievedObject = localStorage.getItem('testObject'); console.log('retrievedObject: ', JSON.parse(retrievedObject)); </code></pre>
18,873,297
Self-host remote git repository on Windows server
<p>We have a computer on our local network designated as 'the server', that runs Windows XP, where we keep the shared folders and stuff that should be visible to all.</p> <p>How do I create a remote Git repository on it, and setup it so different people on different computers on the local network can pull/push?</p> <p>I don't care which protocols are used - <code>http://</code>, <code>ssh://</code>, <code>file://</code>, <code>git://</code> are all fine.</p>
18,890,410
1
2
null
2013-09-18 13:15:39.12 UTC
8
2014-11-27 08:12:17.707 UTC
2013-09-18 14:06:14.353 UTC
null
492,336
null
492,336
null
1
18
windows|git
23,780
<p><strong>Edit:</strong> I recently found about <a href="http://bonobogitserver.com/">Bonobo Git Server</a> - it is a free and open-source Git Server for Windows and IIS, licensed with an MIT license. I haven't tested it myself yet, but you can give it a try.</p> <p>There is also this CodeProject article - <a href="http://www.codeproject.com/Articles/296398/Step-by-Step-Setup-Git-Server-on-Windows-with-CopS">Step by Step Setup Git Server on Windows with CopSSH + msysGit and Integrate Git with Visual Studio</a></p> <hr> <p><strong>Old answer:</strong> In the end, I did as @meagar suggested - I created a shared folder on the server, and I followed <a href="http://elegantcode.com/2011/06/18/git-on-windows-creating-a-network-shared-central-repository/">this tutorial</a>, the part about using Git Gui. <strong>Note</strong> that we use pushd/popd because CD does not support UNC paths:</p> <pre><code>pushd \\remote-pc\SharedDocs\MyRemoteGitRepo1 git init --bare popd </code></pre> <p>Now all you need to do is connect your local repo to remote one. <strong>Note</strong> that you need to use forward slashes for <code>git remote add origin</code>, or it won't work:</p> <pre><code>cd C:\Workspace\MyLocalGitRepo1 git remote add origin //remote-pc/SharedDocs/MyRemoteGitRepo1 </code></pre> <p>And finally you can push your work to the remote repo:</p> <pre><code>git push origin master </code></pre>
34,174,524
SQL datetime compare
<p>I want to get some values from my table an there are some conditions about its datetime columns. </p> <p>I want to get all hotel values of a stated city from my table, which is named "LocalHotels". Also I should declare two <code>DateTime</code>values. First value should be less than or equal to hotel's value in <em>"start"</em> column, which is <code>datetime</code> data type. Second value should be greater than or equal to hotel's value in <em>"deadline"</em> column, which is <code>datetime</code> data type, either. </p> <p>All <code>datetime</code> values in these two columns are inserted in German <code>CultureInfo</code> format.</p> <p>When I stated query below, there are no problems;</p> <pre><code>string query = "SELECT * FROM LocalHotels WHERE city='LONDON' AND start &lt;='5.12.2015 00:00:00' AND deadline &gt;='8.12.2015 00:00:00' ORDER BY city"; </code></pre> <p>However when I changed day value of <code>DateTime</code> values from one digit to two digits, as I stated in below;</p> <pre><code>string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start &lt;='15.12.2015 00:00:00' AND deadline &gt;='18.12.2015 00:00:00' ORDER BY city" </code></pre> <p>I got an SQLException which indicates; </p> <blockquote> <p>The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.</p> </blockquote>
34,174,598
4
6
null
2015-12-09 08:59:26.517 UTC
3
2020-02-25 18:38:24.81 UTC
2015-12-09 09:06:03.673 UTC
null
1,945,345
null
1,945,345
null
1
15
sql-server|datetime
153,970
<p>Even though in Europe and everywhere in the world it makes perfect sense to use the month as the second of three items in the date. In the US and in this case, apparently, SQL's date time is MM.DD.YYYY, so you're going for the 15th month and 18th month </p> <p>Therefore you should use </p> <pre><code>string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start &lt;='12.15.2015 00:00:00' AND deadline &gt;='12.18.2015 00:00:00' ORDER BY city" </code></pre> <p>or </p> <pre><code>string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start &lt;='2015-12-15' AND deadline &gt;='2015-12-18' ORDER BY city" </code></pre>
5,372,501
Capturing Video Frame and then Exporting as Bitmap in HTML5
<p>I have a web application where I play back video.</p> <p>I am considering using the HTML5 <code>&lt;video&gt;</code> element and have determined it will allow me to meet all of my requirements except one: <strong>allowing the user to take a snapshot of the current video frame and save it as a raster image format (i.e. JPG).</strong></p> <p>For this requirement I have not found a solution, and any guidance on this matter would be greatly appreciated.</p> <p>To help answer the question here are more details. I will download the video files from a server via HTTP and then play them back in the browser. This will not be a video stream, but instead a download with playback starting after the file has been received. The video will be in the <em>MP4</em> format.</p> <p>The solution only needs to run in IE 9. (Although naturally I would like the solution to be as cross-browser/platform as possible.)</p>
5,373,155
2
0
null
2011-03-20 23:57:26.063 UTC
11
2012-03-08 03:55:37.227 UTC
null
null
null
null
392,176
null
1
12
html|video|html5-video
8,389
<p>Capture the image to a <code>canvas</code> element:</p> <pre><code>var video = document.getElementById(videoId); var canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; var ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0); </code></pre> <p>Then use the <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-canvas-todataurl" rel="noreferrer"><code>toDataURL()</code></a> method to get the image:</p> <pre><code>canvas.toDataURL('image/jpeg'); </code></pre> <p>Be aware that for all this to work <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements" rel="noreferrer">the video has to be from the same origin as the page</a>.</p>
5,170,698
How to use Spring RestTemplate and JAXB marshalling on a URL that returns multiple types of XML
<p>I need to make a Rest POST to a service that returns either a <code>&lt;job/&gt;</code> or an <code>&lt;exception/&gt;</code> and always status code <code>200</code>. (lame 3rd party product!).</p> <p>I have code like:</p> <pre><code>Job job = getRestTemplate().postForObject(url, postData, Job.class); </code></pre> <p>And my applicationContext.xml looks like: </p> <pre><code>&lt;bean id="restTemplate" class="org.springframework.web.client.RestTemplate"&gt; &lt;constructor-arg ref="httpClientFactory"/&gt; &lt;property name="messageConverters"&gt; &lt;list&gt; &lt;bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"&gt; &lt;property name="marshaller" ref="jaxbMarshaller"/&gt; &lt;property name="unmarshaller" ref="jaxbMarshaller"/&gt; &lt;/bean&gt; &lt;bean class="org.springframework.http.converter.FormHttpMessageConverter"/&gt; &lt;bean class="org.springframework.http.converter.StringHttpMessageConverter"/&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"&gt; &lt;property name="classesToBeBound"&gt; &lt;list&gt; &lt;value&gt;domain.fullspec.Job&lt;/value&gt; &lt;value&gt;domain.fullspec.Exception&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>When I try to make this call and the service fails, I get: </p> <pre><code> Failed to convert value of type 'domain.fullspec.Exception' to required type 'domain.fullspec.Job' </code></pre> <p>In the postForObject() call, I am asking for a Job.class and not getting one and it is getting upset.</p> <p>I am thinking I need to be able to do something along the lines of: </p> <pre><code>Object o = getRestTemplate().postForObject(url, postData, Object.class); if (o instanceof Job.class) { ... else if (o instanceof Exception.class) { } </code></pre> <p>But this doesnt work because then JAXB complains that it doesnt know how to marshal to Object.class - not surprisingly.</p> <p>I have attempted to create subclass of MarshallingHttpMessageConverter and override readFromSource()</p> <p>protected Object readFromSource(Class clazz, HttpHeaders headers, Source source) {</p> <pre><code> Object o = null; try { o = super.readFromSource(clazz, headers, source); } catch (Exception e) { try { o = super.readFromSource(MyCustomException.class, headers, source); } catch (IOException e1) { log.info("Failed readFromSource "+e); } } return o; } </code></pre> <p>Unfortunately, this doesnt work because the underlying inputstream inside source has been closed by the time I retry it.</p> <p>Any suggestions gratefully received, </p> <p>Tom</p> <p><strong>UPDATE: I have got this to work by taking a copy of the inputStream</strong></p> <pre><code>protected Object readFromSource(Class&lt;?&gt; clazz, HttpHeaders headers, Source source) { InputStream is = ((StreamSource) source).getInputStream(); // Take a copy of the input stream so we can use it for initial JAXB conversion // and if that fails, we can try to convert to Exception CopyInputStream copyInputStream = new CopyInputStream(is); // input stream in source is empty now, so reset using copy ((StreamSource) source).setInputStream(copyInputStream.getCopy()); Object o = null; try { o = super.readFromSource(clazz, headers, source); // we have failed to unmarshal to 'clazz' - assume it is &lt;exception&gt; and unmarshal to MyCustomException } catch (Exception e) { try { // reset input stream using copy ((StreamSource) source).setInputStream(copyInputStream.getCopy()); o = super.readFromSource(MyCustomException.class, headers, source); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } return o; } </code></pre> <p>CopyInputStream is taken from <a href="http://www.velocityreviews.com/forums/t143479-how-to-make-a-copy-of-inputstream-object.html">http://www.velocityreviews.com/forums/t143479-how-to-make-a-copy-of-inputstream-object.html</a>, i'll paste it here.</p> <pre><code>import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class CopyInputStream { private InputStream _is; private ByteArrayOutputStream _copy = new ByteArrayOutputStream(); /** * */ public CopyInputStream(InputStream is) { _is = is; try { copy(); } catch(IOException ex) { // do nothing } } private int copy() throws IOException { int read = 0; int chunk = 0; byte[] data = new byte[256]; while(-1 != (chunk = _is.read(data))) { read += data.length; _copy.write(data, 0, chunk); } return read; } public InputStream getCopy() { return (InputStream)new ByteArrayInputStream(_copy.toByteArray()); } } </code></pre>
5,172,220
2
2
null
2011-03-02 16:53:27.74 UTC
5
2014-01-25 17:42:12.133 UTC
2011-03-03 17:51:50.54 UTC
null
394,278
null
394,278
null
1
13
java|jaxb|resttemplate
41,776
<p>@Tom: I don't think creating a custom MarshallingHttpMessageConverter will do you any good. The built-in converter is returning you the right class (Exception class) when the service fails, but it is the <code>RestTemplate</code> that doesn't know how to return Exception class to the callee because you have specified the response type as Job class.</p> <p>I read the <a href="http://www.jarvana.com/jarvana/view/org/springframework/spring-web/3.0.2.RELEASE/spring-web-3.0.2.RELEASE-sources.jar!/org/springframework/web/client/RestTemplate.java?format=ok" rel="noreferrer">RestTemplate source code</a>, and you are currently calling this API:-</p> <pre><code>public &lt;T&gt; T postForObject(URI url, Object request, Class&lt;T&gt; responseType) throws RestClientException { HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(request, responseType); HttpMessageConverterExtractor&lt;T&gt; responseExtractor = new HttpMessageConverterExtractor&lt;T&gt;(responseType, getMessageConverters()); return execute(url, HttpMethod.POST, requestCallback, responseExtractor); } </code></pre> <p>As you can see, it returns type T based on your response type. What you probably need to do is to subclass <code>RestTemplate</code> and add a new <code>postForObject()</code> API that returns an Object instead of type T so that you can perform the <code>instanceof</code> check on the returned object.</p> <p><strong>UPDATE</strong></p> <p>I have been thinking about the solution for this problem, instead of using the built-in <code>RestTemplate</code>, why not write it yourself? I think that is better than subclassing <code>RestTemplate</code> to add a new method. </p> <p>Here's my example... granted, I didn't test this code but it should give you an idea:-</p> <pre><code>// reuse the same marshaller wired in RestTemplate @Autowired private Jaxb2Marshaller jaxb2Marshaller; public Object genericPost(String url) { // using Commons HttpClient HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); // add your data here method.addParameter("data", "your-data"); try { int returnCode = client.executeMethod(method); // status code is 200 if (returnCode == HttpStatus.SC_OK) { // using Commons IO to convert inputstream to string String xml = IOUtil.toString(method.getResponseBodyAsStream()); return jaxb2Marshaller.unmarshal(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); } else { // handle error } } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } return null; } </code></pre> <p>If there are circumstances where you want to reuse some of the APIs from <code>RestTemplate</code>, you can build an adapter that wraps your custom implementation and reuse <code>RestTemplate</code> APIs without actually exposing <code>RestTemplate</code> APIs all over your code.</p> <p>For example, you can create an adapter interface, like this:-</p> <pre><code>public interface MyRestTemplateAdapter { Object genericPost(String url); // same signature from RestTemplate that you want to reuse &lt;T&gt; T postForObject(String url, Object request, Class&lt;T&gt; responseType, Object... uriVariables); } </code></pre> <p>The concrete custom rest template looks something like this:-</p> <pre><code>public class MyRestTemplateAdapterImpl implements MyRestTemplateAdapter { @Autowired private RestTemplate restTemplate; @Autowired private Jaxb2Marshaller jaxb2Marshaller; public Object genericPost(String url) { // code from above } public &lt;T&gt; T postForObject(String url, Object request, Class&lt;T&gt; responseType, Object... uriVariables) { return restTemplate.postForObject(url, request, responseType); } } </code></pre> <p>I still think this approach is much cleaner than subclassing <code>RestTemplate</code> and you have more control on how you want to handle the results from the web service calls.</p>
5,481,282
How do I measure the execution time of python unit tests with nosetests?
<p>Is there a way to time the execution time of individual Python tests which are run by nosetests ?</p>
5,481,328
2
0
null
2011-03-30 02:39:13.223 UTC
6
2013-12-02 06:12:24.353 UTC
2012-09-26 13:32:14.34 UTC
null
725,650
null
454,488
null
1
29
python|nosetests
8,650
<p>You might try the nose plug-in posted here: <a href="https://github.com/mahmoudimus/nose-timer" rel="noreferrer">https://github.com/mahmoudimus/nose-timer</a> (or available via pip / PyPi). You can also use the built-in plugin <code>--with-profile</code> to do more serious profiling.</p>
5,199,133
Function to return only alpha-numeric characters from string?
<p>I'm looking for a php function that will take an input string and return a sanitized version of it by stripping away all special characters leaving only alpha-numeric.</p> <p>I need a second function that does the same but only returns alphabetic characters A-Z.</p> <p>Any help much appreciated.</p>
5,199,183
2
10
null
2011-03-04 20:53:09.17 UTC
23
2020-04-19 05:05:54.893 UTC
null
null
null
null
209,102
null
1
116
php|regex
178,159
<p><strong>Warning: Note that English is not restricted to just A-Z.</strong></p> <p>Try <a href="http://ideone.com/hzXKj" rel="noreferrer">this</a> to remove everything except a-z, A-Z and 0-9:</p> <pre><code>$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s); </code></pre> <p>If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.</p> <p>Try <a href="http://ideone.com/OHfek" rel="noreferrer">this</a> to leave only A-Z:</p> <pre><code>$result = preg_replace("/[^A-Z]+/", "", $s); </code></pre> <p>The reason for the warning is that words like résumé contains the letter <code>é</code> that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.</p>
1,016,515
HTML 5 - Early Adoption Where Possible - Good or Bad?
<p>This question was inspired a bit by <a href="https://stackoverflow.com/questions/992115/custom-attributes-yay-or-nay">this question</a>, in which the most upvoted answer recommended using a feature from HTML 5. It certainly seemed to be a good method to me, but it made me curious about using features from a future spec in general.</p> <p>HTML 5 offers a lot of nice improvements, many of which can be used without causing problems in current browsers. </p> <p>Some examples:</p> <pre><code>// new, simple HTML5 doctype (puts browsers in standards mode) &lt;!doctype HTML&gt; // new input types, for easy, generic client side validation &lt;input type="email" name="emailAddress"/&gt; &lt;input type="number" name="userid"/&gt; &lt;input type="date" name="dateOfBirth"/&gt; // new "required" attribute indicates that a field is required &lt;input type="text" name="userName" required="true"/&gt; // new 'data-' prefixed attributes // for easy insertion of js-accessible metadata in dynamic pages &lt;div data-price="33.23"&gt; &lt;!-- --&gt; &lt;/div&gt; &lt;button data-item-id="93024"&gt;Add Item&lt;/button&gt; </code></pre> <p>Many of these new features are designed to make it possible for browsers to automatically validate forms, as well as give them better inputs (for example a date picker). Some are just convenient and seem like a good way to get ready for the future.</p> <p>They currently don't break anything (as far as I can tell) in current browsers and they allow for clean, generic clientside code.</p> <p>However, even though they are all valid in HTML 5, they are NOT valid for HTML 4, and HTML 5 is still a draft at this point.</p> <p><strong>Is it a good idea to go ahead and use these features early?</strong> </p> <p>Are there browser implementation issues with them that I haven't realized? </p> <p>Should we be developing web pages now that make use of HTML 5 draft features?</p>
1,017,329
7
7
null
2009-06-19 05:55:57.093 UTC
11
2014-01-03 01:42:00.817 UTC
2017-05-23 10:27:28.99 UTC
null
-1
null
12,983
null
1
16
html|cross-browser|w3c-validation
1,418
<p>There are several things to consider:</p> <ol> <li>First, validation doesn't mean that much, because an HTML page can very well be valid but badly authored, inaccessible, etc. See <a href="http://www.cs.tut.fi/~jkorpela/html/validation.html#icon" rel="nofollow noreferrer">Say <em>no</em> to "Valid HTML" icons</a> and <a href="http://hixie.ch/advocacy/xhtml" rel="nofollow noreferrer">Sending XHTML as text/html Considered Harmful</a> (in reference to the hobo-web tests mentioned in another response)</li> <li>Given this, I'd highly recommend using the new DOCTYPE: the only reason for having it in HTML5 is that it's the smallest thing that triggers standards mode in browsers, so if you want standards mode, go with it; you have little to no reason to use another, verbose, error-prone DOCTYPE</li> <li>As for the forms enhancements, you can use Weston Ruter's <a href="http://code.google.com/p/webforms2/" rel="nofollow noreferrer">webforms2</a> JS library to bring it to non-aware browsers</li> <li>and finally, about the <code>data-*</code> attributes, it a) works in all browsers (as long as you use <code>getAttribute()</code>), b) is still better than abusing the <code>title</code> or <code>class</code> attributes and c) won't bother you with validation as we said earlier that validation isn't <em>that</em> important (of course it is, but it doesn't matter that your page is invalid if the validity errors are willful; and you can already use HTML5 validation in the W3C validator, so...); so there's no real reason not to use them either.</li> </ol>
797,354
How to copy a row of values from a 2D array into a 1D array?
<p>We have the following object</p> <pre><code>int [,] oGridCells; </code></pre> <p>which is only used with a fixed first index</p> <pre><code>int iIndex = 5; for (int iLoop = 0; iLoop &lt; iUpperBound; iLoop++) { //Get the value from the 2D array iValue = oGridCells[iIndex, iLoop]; //Do something with iValue } </code></pre> <p>Is there a way in .NET to convert the values at a fixed first index into a single dimension array (other than by looping the values)?</p> <p>I doubt it would speed up the code (and it may well make it slower) if the array is only being looped once. But if the array was being heavily manipulated then a single dimension array would be more efficient than a multi dimension array.</p> <p>My main reason for asking the question is to see if it can be done and how, rather than using it for production code.</p>
797,383
7
0
null
2009-04-28 11:11:05.89 UTC
8
2022-08-16 13:24:43.667 UTC
null
null
null
null
89,075
null
1
17
c#|.net|arrays|multidimensional-array
50,532
<p>The following code demonstrates copying 16 bytes (4 ints) from a 2-D array to a 1-D array.</p> <pre><code>int[,] oGridCells = {{1, 2}, {3, 4}}; int[] oResult = new int[4]; System.Buffer.BlockCopy(oGridCells, 0, oResult, 0, 16); </code></pre> <p>You can also selectively copy just 1 row from the array by providing the correct byte offsets. This example copies the middle row of a 3-row 2-D array.</p> <pre><code>int[,] oGridCells = {{1, 2}, {3, 4}, {5, 6}}; int[] oResult = new int[2]; System.Buffer.BlockCopy(oGridCells, 8, oResult, 0, 8); </code></pre>
1,226,726
How do I capture the enter key in a windows forms combobox
<p>How do I capture the enter key in a windows forms combo box when the combobox is active?</p> <p>I've tried to listen to KeyDown and KeyPress and I've created a subclass and overridden ProcessDialogKey, but nothing seems to work.</p> <p>Any ideas?</p> <p>/P</p>
1,226,740
7
1
null
2009-08-04 10:21:39.88 UTC
1
2016-03-18 14:12:57.623 UTC
null
null
null
null
15,763
null
1
21
c#|windows|winforms|combobox
44,119
<p>Hook up the KeyPress event to a method like this:</p> <pre><code>protected void myCombo_OnKeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) { MessageBox.Show("Enter pressed", "Attention"); } } </code></pre> <p>I've tested this in a WinForms application with VS2008 and it works. </p> <p>If it isn't working for you, please post your code.</p>
58,988
What is the reasoning behind the Interface Segregation Principle?
<p>The Interface Segregation Principle (ISP) says that many client specific interfaces are better than one general purpose interface. Why is this important?</p>
59,008
7
0
null
2008-09-12 13:40:17.947 UTC
11
2021-05-21 15:16:57.263 UTC
2017-09-03 13:31:47.443 UTC
Phillip Wells
1,063,716
Phillip Wells
3,012
null
1
27
java|oop|solid-principles|design-principles|interface-segregation-principle
9,155
<p>ISP states that:</p> <blockquote> <p>Clients should not be forced to depend on methods that they do not use.</p> </blockquote> <p>ISP relates to important characteristics - <a href="http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29" rel="noreferrer">cohesion</a> and <a href="http://en.wikipedia.org/wiki/Coupling_%28computer_science%29" rel="noreferrer">coupling</a>.<br> Ideally your components must be highly tailored. It improves code robustness and maintainability. </p> <p>Enforcing ISP gives you following bonuses:</p> <ul> <li>High <a href="http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29" rel="noreferrer">cohesion</a> - better understandability, robustness</li> <li>Low <a href="http://en.wikipedia.org/wiki/Coupling_%28computer_science%29" rel="noreferrer">coupling</a> - better maintainability, high resistance to changes</li> </ul> <p>If you want to learn more about software design principles, get a copy of <a href="https://rads.stackoverflow.com/amzn/click/com/0135974445" rel="noreferrer" rel="nofollow noreferrer">Agile Software Development, Principles, Patterns, and Practices</a> book.</p>
564,039
JVM performance tuning for large applications
<p>The default JVM parameters are not optimal for running large applications. Any insights from people who have tuned it on a real application would be helpful. We are running the application on a 32-bit windows machine, where the client JVM is used <a href="http://java.sun.com/docs/hotspot/gc5.0/ergo5.html#0.0.%20Garbage%20collector,%20heap,%20and%20runtime%20compiler|outline" rel="noreferrer">by default</a>. We have added -server and changed the NewRatio to 1:3 (A larger young generation).</p> <p>Any other parameters/tuning which you have tried and found useful?</p> <p>[Update] The specific type of application I'm talking about is a server application that are rarely shutdown, taking at least -Xmx1024m. Also assume that the application is profiled already. I'm looking for general guidelines in terms of <strong>JVM performance</strong> only.</p>
564,051
7
3
null
2009-02-19 05:24:11.187 UTC
34
2016-10-25 05:58:07.3 UTC
2009-02-19 06:24:50.417 UTC
null
62,237
null
62,237
null
1
33
java|jvm|performance|jvm-arguments
56,429
<p>There are great quantities of that information around.</p> <p>First, profile the code before tuning the JVM.</p> <p>Second, read the <a href="http://www.oracle.com/technetwork/java/javase/tech/index-jsp-137187.html" rel="noreferrer">JVM documentation</a> carefully; there are a lot of sort of "urban legends" around. For example, the -server flag only helps if the JVM is staying resident and running for some time; -server "turns up" the JIT/HotSpot, and that needs to have many passes through the same path to get turned up. -server, on the other hand, <em>slows</em> initial execution of the JVM, as there's more setup time.</p> <p>There are several good books and websites around. See, for example, <a href="http://www.javaperformancetuning.com/" rel="noreferrer">http://www.javaperformancetuning.com/</a></p>
819,346
How to host static HTML files on Google App Engine?
<p>Is it possible to host a static HTML website on App Engine? And how to make my domain name work with it?</p>
15,101,686
7
0
null
2009-05-04 08:56:50.75 UTC
27
2019-10-08 13:48:09.137 UTC
2019-10-08 13:48:09.137 UTC
null
11,784,749
null
58,800
null
1
39
html|google-app-engine|web-applications|hosting
22,256
<p>I wrote a library to do just that, and it works on AppEngine or any other server you want:</p> <p><a href="https://github.com/stochastic-technologies/static-appengine-hoster" rel="nofollow">https://github.com/stochastic-technologies/static-appengine-hoster</a></p> <p>You just throw your files in the directory, and it hosts them. It also supports Jinja2 templates, URL rewriting and multiple domains.</p>
621,549
How to access session variables from any class in ASP.NET?
<p>I have created a class file in the App_Code folder in my application. I have a session variable </p> <pre><code>Session["loginId"] </code></pre> <p>I want to access this session variables in my class, but when I am writing the following line then it gives error</p> <pre><code>Session["loginId"] </code></pre> <p>Can anyone tell me how to access session variables within a class which is created in app_code folder in ASP.NET 2.0 (C#)</p>
621,620
7
0
null
2009-03-07 08:48:42.517 UTC
90
2020-10-04 18:12:41.19 UTC
2009-03-07 16:45:28.83 UTC
Martin
19,635
Prashant
45,261
null
1
166
c#|asp.net|session-variables
345,092
<p>(Updated for completeness)<br> You can access session variables from any page or control using <code>Session["loginId"]</code> and from any class (e.g. from inside a class library), using <code>System.Web.HttpContext.Current.Session["loginId"].</code></p> <p>But please read on for my original answer...</p> <hr> <p>I always use a wrapper class around the ASP.NET session to simplify access to session variables:</p> <pre><code>public class MySession { // private constructor private MySession() { Property1 = "default value"; } // Gets the current session. public static MySession Current { get { MySession session = (MySession)HttpContext.Current.Session["__MySession__"]; if (session == null) { session = new MySession(); HttpContext.Current.Session["__MySession__"] = session; } return session; } } // **** add your session properties here, e.g like this: public string Property1 { get; set; } public DateTime MyDate { get; set; } public int LoginId { get; set; } } </code></pre> <p>This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:</p> <pre><code>int loginId = MySession.Current.LoginId; string property1 = MySession.Current.Property1; MySession.Current.Property1 = newValue; DateTime myDate = MySession.Current.MyDate; MySession.Current.MyDate = DateTime.Now; </code></pre> <p>This approach has several advantages:</p> <ul> <li>it saves you from a lot of type-casting</li> <li>you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]</li> <li>you can document your session items by adding XML doc comments on the properties of MySession</li> <li>you can initialize your session variables with default values (e.g. assuring they are not null)</li> </ul>
1,152,405
Is it better to use multiple databases with one schema each, or one database with multiple schemas?
<p>After <a href="https://stackoverflow.com/questions/1130555/postgresql-pitr-backup-best-practices-to-handle-multiple-databases/1145332#1145332">this comment</a> to one of my questions, I'm thinking if it is better using one database with X schemas or vice versa.</p> <p>I'm developing a web application where, when people register, I create (actually) a database (no, it's not a social network: everyone must have access to his own data and never see the data of the other user). That's the way I used for the previous version of my application (that is still running on MySQL): through the Plesk API, for every registration, I do:</p> <ol> <li>Create a database user with limited privileges;</li> <li>Create a database that can be accessed just by the previous created user and the superuser (for maintenance)</li> <li>Populate the database</li> </ol> <p>Now, I'll need to do the same with PostgreSQL (the project is getting mature and MySQL don't fulfil all the needs). I need to have all the databases/schemas backups independent: <code>pg_dump</code> works perfectly in both ways, and the same for the users that can be configured to access just one schema or one database.</p> <p>So, assuming you are more experienced PostgreSQL users than me, what do you think is the best solution for my situation, and why? Will there be performance differences using $x database instead of $x schemas? And what solution will be better to maintain in the future (reliability)? All of my databases/schemas will <em>always</em> have the same structure!</p> <p>For the backups issue (using pg_dump), is maybe better using one database and many schemas, dumping all the schemas at once: recovering will be quite simple loading the main dump in a development machine and then dump and restore just the schema needed: there is one additional step, but dumping all the schema seem faster than dumping them one by one.</p> <h2>UPDATE 2012</h2> <p>Well, the application structure and design changed so much during those last two years. I'm still using the &quot;one db with many schemas&quot; -approach, but still, I have one database <em>for each version</em> of my application:</p> <pre><code>Db myapp_01 \_ my_customer_foo_schema \_ my_customer_bar_schema Db myapp_02 \_ my_customer_foo_schema \_ my_customer_bar_schema </code></pre> <p>For backups, I'm dumping each database regularly, and then moving the backups on the development server. I'm also using the PITR/WAL backup but, as I said before, it's not likely I'll have to restore <em>all database</em> at once. So it will probably be dismissed this year (in my situation is not the best approach).</p> <p>The one-db-many-schema approach worked very well for me since now, even if the application structure is totally changed. I almost forgot: all of my databases/schemas will <em>always</em> have the same structure! Now, every schema has its own structure that change dynamically reacting to users data flow.</p>
1,157,008
7
8
null
2009-07-20 08:45:46.723 UTC
75
2022-06-30 08:07:50.107 UTC
2021-01-12 02:13:04.473 UTC
null
4,157,124
null
80,363
null
1
203
database|database-design|postgresql|database-permissions
117,130
<p>A PostgreSQL "schema" is roughly the same as a MySQL "database". Having many databases on a PostgreSQL installation can get problematic; having many schemas will work with no trouble. So you definitely want to go with one database and multiple schemas within that database.</p>
295,224
What are major differences between C# and Java?
<p>I just want to clarify one thing. This is not a question on which one is better, that part I leave to someone else to discuss. I don't care about it. I've been asked this question on my job interview and I thought it might be useful to learn a bit more.</p> <p>These are the ones I could come up with:</p> <ul> <li>Java is "platform independent". Well nowadays you could say there is the <a href="http://en.wikipedia.org/wiki/Mono_%28software%29" rel="noreferrer">Mono</a> project so C# could be considered too but I believe it is a bit exaggerating. Why? Well, when a new release of Java is done it is simultaneously available on all platforms it supports, on the other hand how many features of C# 3.0 are still missing in the Mono implementation? Or is it really <a href="http://en.wikipedia.org/wiki/Common_Language_Runtime" rel="noreferrer">CLR</a> vs. <a href="http://en.wikipedia.org/wiki/JRE" rel="noreferrer">JRE</a> that we should compare here?</li> <li>Java doesn't support events and delegates. As far as I know.</li> <li>In Java all methods are virtual</li> <li>Development tools: I believe there isn't such a tool yet as Visual Studio. Especially if you've worked with team editions you'll know what I mean.</li> </ul> <p>Please add others you think are relevant.</p> <p>Update: Just popped up my mind, Java doesn't have something like custom attributes on classes, methods etc. Or does it?</p>
295,248
7
4
null
2008-11-17 10:07:23.7 UTC
280
2014-05-02 08:40:35.07 UTC
2009-12-31 09:13:20.12 UTC
null
63,550
null
2,921,654
null
1
209
c#|.net|clr|java
194,272
<p><strong>Comparing Java 7 and C# 3</strong></p> <p>(Some features of Java 7 aren't mentioned here, but the <code>using</code> statement advantage of all versions of C# over Java 1-6 has been removed.)</p> <p>Not all of your summary is correct:</p> <ul> <li>In Java methods are virtual <em>by default</em> but you can make them final. (In C# they're sealed by default, but you can make them virtual.)</li> <li>There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)</li> </ul> <p>Beyond that (and what's in your summary already):</p> <ul> <li>Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a <code>List&lt;byte&gt;</code> as a <code>byte[]</code> backing it, rather than an array of boxed bytes.)</li> <li>C# doesn't have checked exceptions</li> <li>Java doesn't allow the creation of user-defined value types</li> <li>Java doesn't have operator and conversion overloading</li> <li>Java doesn't have iterator blocks for simple implemetation of iterators</li> <li>Java doesn't have anything like LINQ</li> <li>Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.</li> <li>Java doesn't have expression trees</li> <li>C# doesn't have anonymous inner classes</li> <li>C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes</li> <li>Java doesn't have static classes (which don't have <em>any</em> instance constructors, and can't be used for variables, parameters etc)</li> <li>Java doesn't have any equivalent to the C# 3.0 anonymous types</li> <li>Java doesn't have implicitly typed local variables</li> <li>Java doesn't have extension methods</li> <li>Java doesn't have object and collection initializer expressions</li> <li>The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)</li> <li>The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)</li> <li>Java doesn't have properties as part of the language; they're a convention of get/set/is methods</li> <li>Java doesn't have the equivalent of "unsafe" code</li> <li>Interop is easier in C# (and .NET in general) than Java's JNI</li> <li>Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.</li> <li>Java has no preprocessor directives (#define, #if etc in C#).</li> <li>Java has no equivalent of C#'s <code>ref</code> and <code>out</code> for passing parameters by reference</li> <li>Java has no equivalent of partial types</li> <li>C# interfaces cannot declare fields</li> <li>Java has no unsigned integer types</li> <li>Java has no <em>language</em> support for a decimal type. (java.math.BigDecimal provides something <em>like</em> System.Decimal - with differences - but there's no language support)</li> <li>Java has no equivalent of nullable value types</li> <li>Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.</li> </ul> <p>This is not exhaustive, but it covers everything I can think of off-hand.</p>
894,268
PHP REST Clients
<p>I'm trying to connect to a RESTful web service, but I'm having some troubles, especially when sending data over PUT and DELETE. With cURL, PUT requires a file to send, and DELETE is just weird. I'm perfectly capable of writing a client using PHP's socket support and writing the HTTP headers myself, but I wanted to know whether you guys have ever used or seen a REST client for PHP?</p>
4,750,415
8
0
null
2009-05-21 18:07:53.987 UTC
14
2014-01-10 12:40:03.283 UTC
null
null
null
null
39,979
null
1
35
php|rest|client
63,590
<p>So as it turns out, Zend_Rest_Client isn't a REST client at all — it does not support the PUT and DELETE methods for example. After trying to kludge it into working with an actual RESTful service I got fed up and wrote a proper REST client for PHP:</p> <p><a href="http://github.com/educoder/pest" rel="noreferrer">http://github.com/educoder/pest</a></p> <p>It's still missing a few things but if it gets picked up I'll put some more work into it.</p> <p>Here's a usage example with the OpenStreetMap REST service:</p> <pre><code>&lt;?php /** * This PestXML usage example pulls data from the OpenStreetMap API. * (see http://wiki.openstreetmap.org/wiki/API_v0.6) **/ require_once 'PestXML.php'; $pest = new PestXML('http://api.openstreetmap.org/api/0.6'); // Retrieve map data for the University of Toronto campus $map = $pest-&gt;get('/map?bbox=-79.39997,43.65827,-79.39344,43.66903'); // Print all of the street names in the map $streets = $map-&gt;xpath('//way/tag[@k="name"]'); foreach ($streets as $s) { echo $s['v'] . "\n"; } ?&gt; </code></pre> <p>Currently it uses curl but I may switch it to HTTP_Request or HTTP_Request2 down the line.</p> <p><strong>Update:</strong> Looks like quite a few people have jumped on this. Pest now has support for HTTP authentication and a bunch of other features thanks to contributors on GitHub.</p>
46,276
Test Driven Development in PHP
<p>I am a web-developer working in PHP. I have some limited experience with using Test Driven Development in C# desktop applications. In that case we used nUnit for the unit testing framework.</p> <p>I would like to start using TDD in new projects but I'm really not sure where to begin. </p> <p>What recommendations do you have for a PHP-based unit testing framework and what are some good resources for someone who is pretty new to the TDD concept?</p>
46,294
8
0
null
2008-09-05 16:48:44.26 UTC
26
2018-06-26 20:23:12.833 UTC
null
null
null
GloryFish
3,238
null
1
44
php|unit-testing|tdd
16,809
<p>I've used both PHPUnit &amp; <strong><a href="http://simpletest.org/" rel="noreferrer">SimpleTest</a></strong> and I found <strong>SimpleTest</strong> to be easier to use.</p> <p>As far as TDD goes, I haven't had much luck with it in the purest sense. I think that's mainly a time/discipline issue on my part though.</p> <p>Adding tests after the fact has been somewhat useful but my favorite things to do is use write SimpleTest tests that test for specific bugs that I have to fix. That makes it very easy to verify that things are actually fixed and stay fixed.</p>
733,668
Delete the 'first' record from a table in SQL Server, without a WHERE condition
<p>Is it possible to delete the <em>first</em> record from a table in <code>SQL Server</code>, without using any <code>WHERE</code> condition and without using a cursor?</p>
733,677
8
9
null
2009-04-09 10:39:38.677 UTC
13
2022-01-10 18:34:18.467 UTC
2022-01-10 18:34:18.467 UTC
null
285,795
null
53,262
null
1
80
sql|sql-server
195,214
<pre><code>WITH q AS ( SELECT TOP 1 * FROM mytable /* You may want to add ORDER BY here */ ) DELETE FROM q </code></pre> <p>Note that</p> <pre><code>DELETE TOP (1) FROM mytable </code></pre> <p>will also work, but, as stated in the <a href="http://msdn.microsoft.com/en-us/library/ms189835.aspx" rel="noreferrer"><strong>documentation</strong></a>:</p> <blockquote> <p>The rows referenced in the <code>TOP</code> expression used with <code>INSERT</code>, <code>UPDATE</code>, or <code>DELETE</code> are not arranged in any order.</p> </blockquote> <p>Therefore, it's better to use <code>WITH</code> and an <code>ORDER BY</code> clause, which will let you specify more exactly which row you consider to be the first.</p>
1,205,375
Filter by property
<p>Is it possible to filter a Django queryset by model property?</p> <p>i have a method in my model:</p> <pre><code>@property def myproperty(self): [..] </code></pre> <p>and now i want to filter by this property like:</p> <pre><code>MyModel.objects.filter(myproperty=[..]) </code></pre> <p>is this somehow possible?</p>
1,205,389
8
1
null
2009-07-30 09:06:23.1 UTC
24
2022-02-04 10:06:05.307 UTC
2018-12-07 21:10:32.717 UTC
null
4,720,018
null
146,283
null
1
139
python|django|orm
82,893
<p>Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.</p>
575,772
The best way to calculate the height in a binary search tree? (balancing an AVL-tree)
<p>I'm looking for the best way to calculate a nodes balance in an <a href="http://en.wikipedia.org/wiki/AVL_tree" rel="noreferrer">AVL-tree</a>. I thought I had it working, but after some heavy inserting/updating I can see that it's not working correct (at all). </p> <p>This is kind of a two-part question, the first part would be how to calculate the height of a sub-tree, I know the definition <em>"The height of a node is the length of the longest downward path to a leaf from that node."</em> and I understand it, but I fail at implementing it. And to confuse me further this quote can be found on wikipedia on tree-heights <em>"Conventionally, the value -1 corresponds to a subtree with no nodes, whereas zero corresponds to a subtree with one node."</em></p> <p>And the second part is getting the balance factor of a sub-tree in an AVL tree, I've got no problem understanding the concept, <em>"get the height of your <code>L</code> and <code>R</code> sub-trees and subtract <code>R</code> from <code>L</code>"</em>. And this is defined as something like this: <code>BALANCE = NODE[L][HEIGHT] - NODE[R][HEIGT]</code></p> <p>Reading on wikipedia says this on the first few lines describing insertions into an AVL tree: <em>"If the balance factor becomes -1, 0, or 1 then the tree is still in AVL form, and no rotations are necessary."</em></p> <p>It then goes on, saying this <em>"If the balance factor becomes 2 or -2 then the tree rooted at this node is unbalanced, and a tree rotation is needed. At most a single or double rotation will be needed to balance the tree."</em> - which I have no trouble grasping. </p> <p>But (yes, there's always a but).</p> <p>Here's where it gets confusing, the text states <em>"If the balance factor of R is 1, it means the insertion occurred on the (external) right side of that node and a left rotation is needed"</em>. But from m understanding the text said (as I quoted) that if the balance factor was within <code>[-1, 1]</code> then there was no need for balancing? </p> <p>I feel I'm so close to grasping the concept, I've gotten the tree rotations down, implemented a normal binary search tree, and on the brink of grasping AVL-trees but just seem to be missing that essential epiphany.</p> <p><strong>Edit:</strong> Code examples are preferred over academic formulas as I've always had an easier time grasping something in code, but any help is greatly appreciated.</p> <p><strong>Edit:</strong> I wish I could mark all answers as "accepted", but for me NIck's answer was the first that made me go "aha".</p>
575,859
9
0
null
2009-02-22 20:59:44.63 UTC
43
2020-02-05 12:00:34.403 UTC
2014-04-30 17:50:20.84 UTC
fredrikholmstrom
881,229
fredrikholmstrom
452,521
null
1
66
algorithm|data-structures|binary-tree|avl-tree|tree-balancing
160,225
<h2> Part 1 - height </h2> <p>As starblue says, height is just recursive. In pseudo-code:</p> <pre><code>height(node) = max(height(node.L), height(node.R)) + 1 </code></pre> <p>Now height could be defined in two ways. It could be the number of nodes in the path from the root to that node, or it could be the number of links. According to the <a href="http://en.wikipedia.org/wiki/Tree_height#Height" rel="noreferrer">page you referenced</a>, the most common definition is for the number of links. In which case the complete pseudo code would be:</p> <pre><code>height(node): if node == null: return -1 else: return max(height(node.L), height(node.R)) + 1 </code></pre> <p>If you wanted the number of nodes the code would be:</p> <pre><code>height(node): if node == null: return 0 else: return max(height(node.L), height(node.R)) + 1 </code></pre> <p>Either way, the rebalancing algorithm I think should work the same.</p> <p>However, your tree will be much more efficient (<em>O(ln(n))</em>) if you store and update height information in the tree, rather than calculating it each time. (<em>O(n)</em>)</p> <h2> Part 2 - balancing </h2> <p>When it says "If the balance factor of R is 1", it is talking about the balance factor of the right branch, when the balance factor at the top is 2. It is telling you how to choose whether to do a single rotation or a double rotation. In (python like) Pseudo-code:</p> <pre><code>if balance factor(top) = 2: // right is imbalanced if balance factor(R) = 1: // do a left rotation else if balance factor(R) = -1: do a double rotation else: // must be -2, left is imbalanced if balance factor(L) = 1: // do a left rotation else if balance factor(L) = -1: do a double rotation </code></pre> <p>I hope this makes sense</p>
335,244
Why does Chrome ignore local jQuery cookies?
<p>I am using the jQuery Cookie plugin (<a href="http://plugins.jquery.com/project/cookie" rel="noreferrer">download</a> and <a href="http://stilbuero.de/jquery/cookie/" rel="noreferrer">demo</a> and <a href="http://plugins.jquery.com/files/jquery.cookie.js.txt" rel="noreferrer">source code with comments</a>) to set and read a cookie. I'm developing the page on my <strong>local machine</strong>.</p> <p>The following code will successfully set a cookie in FireFox 3, IE 7, and Safari (PC). But <strong>if the browser is Google Chrome AND the page is a local file</strong>, it does not work.</p> <pre><code>$.cookie("nameofcookie", cookievalue, {path: "/", expires: 30}); </code></pre> <p><strong>What I know</strong>:</p> <ul> <li>The plugin's <a href="http://stilbuero.de/jquery/cookie/" rel="noreferrer">demo</a> works with Chrome.</li> <li>If I put my code on a web server (address starting with http://), it works with Chrome.</li> </ul> <p>So the cookie fails only <strong>for Google Chrome on local files</strong>.</p> <p><strong>Possible causes</strong>:</p> <ul> <li>Google Chrome doesn't accept cookies from web pages on the hard drive (paths like file:///C:/websites/foo.html)</li> <li>Something in the plugin implentation causes Chrome to reject such cookies</li> </ul> <p>Can anyone confirm this and identify the root cause?</p>
347,997
9
2
null
2008-12-02 20:06:11.023 UTC
13
2020-03-30 14:45:16.66 UTC
null
null
null
Nathan Long
4,376
null
1
85
jquery|cookies|google-chrome
69,839
<p>Chrome doesn't support cookies for local files (or, like Peter Lyons mentioned, localhost*) unless you start it with the --enable-file-cookies flag. You can read a discussion about it at <a href="http://code.google.com/p/chromium/issues/detail?id=535" rel="noreferrer">http://code.google.com/p/chromium/issues/detail?id=535</a>.</p> <p>*Chrome <em>does</em> support cookies if you use the local IP address (127.0.0.1) directly. so in the localhost case, that could be an easier workaround.</p>
168,724
Generate table relationship diagram from existing schema (SQL Server)
<p>Is there a way to produce a diagram showing existing tables and their relationships given a connection to a database?</p> <p>This is for SQL Server 2008 Express Edition.</p>
168,807
9
2
null
2008-10-03 20:23:06.33 UTC
46
2019-01-21 21:22:05.433 UTC
2017-01-05 16:47:02.513 UTC
null
4,016,119
Nick
1,959
null
1
202
sql-server|database|diagram
418,488
<p>Yes you can use SQL Server 2008 itself but you need to install SQL Server Management Studio Express (if not installed ) . Just right Click on Database Diagrams and create new diagram. Select the exisiting tables and if you have specified the references in your tables properly. You will be able to see the complete diagram of selected tables. For further reference see <a href="http://www.mssqltips.com/sqlservertip/1816/getting-started-with-sql-server-database-diagrams/" rel="nofollow noreferrer">Getting started with SQL Server database diagrams</a></p>
22,401
Does PHP have built-in data structures?
<p>I'm looking at the <a href="http://www.php.net/manual/en/" rel="noreferrer">PHP Manual</a>, and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?</p>
22,407
10
2
null
2008-08-22 13:47:43.297 UTC
33
2022-01-09 14:35:35.733 UTC
2008-08-25 12:56:41.913 UTC
Chris Fournier
2,134
Thomas Owens
572
null
1
72
php|data-structures
60,319
<p>The only native data structure in PHP is array. Fortunately, arrays are quite flexible and can be used as hash tables as well.</p> <p><a href="http://www.php.net/array" rel="noreferrer">http://www.php.net/array</a></p> <p>However, there is SPL which is sort of a clone of C++ STL.</p> <p><a href="http://www.php.net/manual/en/book.spl.php" rel="noreferrer">http://www.php.net/manual/en/book.spl.php</a></p>
846,020
How to access the form's 'name' variable from PHP
<p>I'm trying to create a BMI calculator. This should allow people to use either metric or imperial measurements.</p> <p>I realise that I could use hidden tags to solve my problem, but this has bugged me before so I thought I'd ask: I can use <code>$_POST['variableName']</code> to find the submitted variableName field-value; but...I don't know, or see, how to verify which form was <em>used</em> to submit the variables.</p> <p>My code's below (though I'm not sure it's strictly relevant to the question):</p> <pre><code>&lt;?php $bmiSubmitted = $_POST['bmiSubmitted']; if (isset($bmiSubmitted)) { $height = $_POST['height']; $weight = $_POST['weight']; $bmi = floor($weight/($height*$height)); ?&gt; &lt;ul id="bmi"&gt; &lt;li&gt;Weight (in kilograms) is: &lt;span&gt;&lt;?php echo "$weight"; ?&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;Height (in metres) is: &lt;span&gt;&lt;?php echo "$height"; ?&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;Body mass index (BMI) is: &lt;span&gt;&lt;?php echo "$bmi"; ?&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;?php } else { ?&gt; &lt;div id="formSelector"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#metric"&gt;Metric&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#imperial"&gt;Imperial&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;form name="met" id="metric" action="&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;" method="post" enctype="form/multipart"&gt; &lt;fieldset&gt; &lt;label for="weight"&gt;Weight (&lt;abbr title="Kilograms"&gt;kg&lt;/abbr&gt;):&lt;/label&gt; &lt;input type="text" name="weight" id="weight" /&gt; &lt;label for="height"&gt;Height (&lt;abbr title="metres"&gt;m&lt;/abbr&gt;):&lt;/label&gt; &lt;input type="text" name="height" id="height" /&gt; &lt;input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" /&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;input type="reset" id="reset" value="Clear" /&gt; &lt;input type="submit" id="submit" value="Submit" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;form name="imp" id="imperial" action="&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;" method="post" enctype="form/multipart"&gt; &lt;fieldset&gt; &lt;label for="weight"&gt;Weight (&lt;abbr title="Pounds"&gt;lbs&lt;/abbr&gt;):&lt;/label&gt; &lt;input type="text" name="weight" id="weight" /&gt; &lt;label for="height"&gt;Height (Inches):&lt;/label&gt; &lt;input type="text" name="height" id="height" / &lt;input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" /&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;input type="reset" id="reset" value="Clear" /&gt; &lt;input type="submit" id="submit" value="Submit" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;?php } ?&gt; </code></pre> <p>I verified that it worked (though without validation at the moment -I didn't want to crowd my question too much) with metric; I've added the form but not the processing for the imperial yet.</p>
846,025
11
1
null
2009-05-10 20:10:43.413 UTC
4
2021-09-26 21:50:06.273 UTC
2016-11-22 22:41:32.417 UTC
null
63,550
null
82,548
null
1
28
php|forms
108,029
<p>To identify the submitted form, you can use:</p> <ul> <li>A hidden input field.</li> <li>The name or value of the submit button.</li> </ul> <p>The name of the form is not sent to the server as part of the <a href="https://en.wikipedia.org/wiki/POST_%28HTTP%29" rel="nofollow noreferrer">POST</a> data.</p> <p>You can use code as follows:</p> <pre class="lang-html prettyprint-override"><code>&lt;form name=&quot;myform&quot; method=&quot;post&quot; action=&quot;&quot; enctype=&quot;multipart/form-data&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;frmname&quot; value=&quot;&quot;/&gt; &lt;/form&gt; </code></pre>
465,433
Creating pdf files at runtime in c#
<p>Is there a pdf library attached/that can be attached to .NET 3.5 that allows creation of pdf files at runtime i.e opening a new pdf file, writing to it line by line, embedding images, etc and closing the pdf file all in C# code?</p> <p>What I want is a set of tools and specifications which allow me to implement a customised pdf writer in C# without using Reporting Services' pdf output option.</p>
465,447
13
0
null
2009-01-21 14:03:22.503 UTC
38
2020-12-09 21:19:36.247 UTC
null
null
null
Lonzo
47,342
null
1
86
c#|pdf
137,407
<p>iTextSharp <a href="http://itextsharp.sourceforge.net/" rel="nofollow noreferrer">http://itextsharp.sourceforge.net/</a></p> <p>Complex but comprehensive.</p> <p><a href="https://github.com/itext/itext7-dotnet" rel="nofollow noreferrer">itext7</a> former iTextSharp</p>
356,950
What are C++ functors and their uses?
<p>I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?</p>
356,993
14
3
null
2008-12-10 17:47:21.077 UTC
601
2020-10-25 11:06:46.03 UTC
2018-06-29 10:41:13.18 UTC
null
895,245
Whyamistilltyping
18,664
null
1
1,028
c++|functor|function-object|function-call-operator
552,651
<p>A functor is pretty much just a class which defines the operator(). That lets you create objects which "look like" a function:</p> <pre><code>// this is a functor struct add_x { add_x(int val) : x(val) {} // Constructor int operator()(int y) const { return x + y; } private: int x; }; // Now you can use it like this: add_x add42(42); // create an instance of the functor class int i = add42(8); // and "call" it assert(i == 50); // and it added 42 to its argument std::vector&lt;int&gt; in; // assume this contains a bunch of values) std::vector&lt;int&gt; out(in.size()); // Pass a functor to std::transform, which calls the functor on every element // in the input sequence, and stores the result to the output sequence std::transform(in.begin(), in.end(), out.begin(), add_x(1)); assert(out[i] == in[i] + 1); // for all i </code></pre> <p>There are a couple of nice things about functors. One is that unlike regular functions, they can contain state. The above example creates a function which adds 42 to whatever you give it. But that value 42 is not hardcoded, it was specified as a constructor argument when we created our functor instance. I could create another adder, which added 27, just by calling the constructor with a different value. This makes them nicely customizable.</p> <p>As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function <code>std::transform</code> should call. It should call <code>add_x::operator()</code>. That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.</p> <p>If I had passed a function pointer instead, the compiler couldn't immediately see which function it points to, so unless it performs some fairly complex global optimizations, it'd have to dereference the pointer at runtime, and then make the call.</p>
268,490
jQuery document.createElement equivalent?
<p>I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.</p> <pre><code>var d = document; var odv = d.createElement("div"); odv.style.display = "none"; this.OuterDiv = odv; var t = d.createElement("table"); t.cellSpacing = 0; t.className = "text"; odv.appendChild(t); </code></pre> <p>I would like to know if there is a better way to do this using jQuery. I've been experimenting with:</p> <pre><code>var odv = $.create("div"); $.append(odv); // And many more </code></pre> <p>But I'm not sure if this is any better.</p>
268,520
14
3
null
2008-11-06 12:26:31.993 UTC
235
2020-09-25 15:46:43.753 UTC
2016-01-22 20:18:54.59 UTC
null
1,946,501
Rob Stevenson-Leggett
4,950
null
1
1,335
javascript|jquery|html|dom|dhtml
1,004,114
<p>Here's your example in the "one" line.</p> <pre><code>this.$OuterDiv = $('&lt;div&gt;&lt;/div&gt;') .hide() .append($('&lt;table&gt;&lt;/table&gt;') .attr({ cellSpacing : 0 }) .addClass("text") ) ; </code></pre> <hr> <p><em>Update</em>: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about <code>$("&lt;div&gt;")</code> vs <code>$("&lt;div&gt;&lt;/div&gt;")</code> vs <code>$(document.createElement('div'))</code> as a way of creating new elements, and which is "best".</p> <p>I put together <a href="http://jsbin.com/elula3" rel="noreferrer">a small benchmark</a>, and here are roughly the results of repeating the above options 100,000 times:</p> <p><strong>jQuery 1.4, 1.5, 1.6</strong></p> <pre><code> Chrome 11 Firefox 4 IE9 &lt;div&gt; 440ms 640ms 460ms &lt;div&gt;&lt;/div&gt; 420ms 650ms 480ms createElement 100ms 180ms 300ms </code></pre> <p><strong>jQuery 1.3</strong></p> <pre><code> Chrome 11 &lt;div&gt; 770ms &lt;div&gt;&lt;/div&gt; 3800ms createElement 100ms </code></pre> <p><strong>jQuery 1.2</strong></p> <pre><code> Chrome 11 &lt;div&gt; 3500ms &lt;div&gt;&lt;/div&gt; 3500ms createElement 100ms </code></pre> <p>I think it's no big surprise, but <code>document.createElement</code> is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds <em>per thousand elements</em>. </p> <hr> <p><strong>Update 2</strong></p> <p>Updated for <strong>jQuery 1.7.2</strong> and put the benchmark on <code>JSBen.ch</code> which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!</p> <p><a href="http://jsben.ch/#/ARUtz" rel="noreferrer">http://jsben.ch/#/ARUtz</a></p>
651,619
What is the advantage of using try {} catch {} versus if {} else {}
<p>I am switching from plain mysql in php to PDO and I have noticed that the common way to test for errors is using a try / catch combination instead of if / else combinations.</p> <p>What is the advantage of that method, can I use one try / catch block instead of several nested if / else blocks to handle all errors for the different steps (connect, prepare, execute, etc.)?</p>
651,651
14
0
null
2009-03-16 18:31:39.947 UTC
35
2020-05-12 22:17:33.653 UTC
null
null
null
jeroen
42,139
null
1
76
php|mysql|pdo
64,818
<p>I'd use the try/catch block when the normal path through the code should proceed without error unless there are truly some exceptional conditions -- like the server being down, your credentials being expired or incorrect. I wouldn't necessarily use it to handle non-exceptional errors -- say like the current user not being in the correct role. That is, when you can reasonably expect and handle an error that is not an exceptional condition, I think you should do your checks.</p> <p>In the case that you've described -- setting up and performing a query, a try/catch block is an excellent way to handle it as you normally expect the query to succeed. On the other hand, you'll probably want to check that the contents of result are what you expect with control flow logic rather than just attempting to use data that may not be valid for your purpose.</p> <p>One thing that you want to look out for is sloppy use of try/catch. Try/catch shouldn't be used to protect yourself from bad programming -- the "I don't know what will happen if I do this so I'm going to wrap it in a try/catch and hope for the best" kind of programming. Typically you'll want to restrict the kinds of exceptions you catch to those that are not related to the code itself (server down, bad credentials, etc.) so that you can find and fix errors that are code related (null pointers, etc.). </p>
793,812
Javascript AES encryption
<p>Is there a library available for AES 256-bits encryption in Javascript?</p>
793,890
14
4
null
2009-04-27 14:40:00.623 UTC
57
2021-11-30 15:14:11.267 UTC
2009-09-01 02:17:22.537 UTC
null
48,082
null
21,011
null
1
120
javascript|encryption|aes
221,032
<p>JSAES is a powerful implementation of AES in JavaScript. <a href="http://point-at-infinity.org/jsaes/" rel="noreferrer">http://point-at-infinity.org/jsaes/</a></p>
371,328
Why is it important to override GetHashCode when Equals method is overridden?
<p>Given the following class</p> <pre><code>public class Foo { public int FooId { get; set; } public string FooName { get; set; } public override bool Equals(object obj) { Foo fooItem = obj as Foo; if (fooItem == null) { return false; } return fooItem.FooId == this.FooId; } public override int GetHashCode() { // Which is preferred? return base.GetHashCode(); //return this.FooId.GetHashCode(); } } </code></pre> <p>I have overridden the <code>Equals</code> method because <code>Foo</code> represent a row for the <code>Foo</code>s table. Which is the preferred method for overriding the <code>GetHashCode</code>?</p> <p>Why is it important to override <code>GetHashCode</code>?</p>
371,348
15
3
null
2008-12-16 13:41:18.283 UTC
460
2022-05-25 20:24:26.627 UTC
2019-07-04 15:37:02 UTC
null
4,158,479
Longhorn213
2,469
null
1
1,612
c#|overriding|hashcode
438,241
<p>Yes, it is important if your item will be used as a key in a dictionary, or <code>HashSet&lt;T&gt;</code>, etc - since this is used (in the absence of a custom <code>IEqualityComparer&lt;T&gt;</code>) to group items into buckets. If the hash-code for two items does not match, they may <em>never</em> be considered equal (<a href="https://docs.microsoft.com/en-us/dotnet/api/system.object.equals?view=netframework-4.8" rel="noreferrer">Equals</a> will simply never be called).</p> <p>The <a href="https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.8" rel="noreferrer">GetHashCode()</a> method should reflect the <code>Equals</code> logic; the rules are:</p> <ul> <li>if two things are equal (<code>Equals(...) == true</code>) then they <em>must</em> return the same value for <code>GetHashCode()</code></li> <li>if the <code>GetHashCode()</code> is equal, it is <em>not</em> necessary for them to be the same; this is a collision, and <code>Equals</code> will be called to see if it is a real equality or not.</li> </ul> <p>In this case, it looks like &quot;<code>return FooId;</code>&quot; is a suitable <code>GetHashCode()</code> implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that <code>new Foo(3,5)</code> has a different hash-code to <code>new Foo(5,3)</code>):</p> <p>In modern frameworks, the <code>HashCode</code> type has methods to help you create a hashcode from multiple values; on older frameworks, you'd need to go without, so something like:</p> <pre><code>unchecked // only needed if you're compiling with arithmetic checks enabled { // (the default compiler behaviour is *disabled*, so most folks won't need this) int hash = 13; hash = (hash * 7) + field1.GetHashCode(); hash = (hash * 7) + field2.GetHashCode(); ... return hash; } </code></pre> <p>Oh - for convenience, you might also consider providing <code>==</code> and <code>!=</code> operators when overriding <code>Equals</code> and <code>GetHashCode</code>.</p> <hr /> <p>A demonstration of what happens when you get this wrong is <a href="https://stackoverflow.com/questions/638761/c-gethashcode-override-of-object-containing-generic-array/639098#639098">here</a>.</p>
1,248,081
How to get the browser viewport dimensions?
<p>I want to provide my visitors the ability to see images in high quality, is there any way I can detect the window size?</p> <p>Or better yet, the viewport size of the browser with JavaScript? See green area here:</p> <p><a href="https://i.stack.imgur.com/zYrB7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/zYrB7.jpg" alt=""></a></p>
8,876,069
17
4
null
2009-08-08 05:54:41.81 UTC
351
2022-06-30 05:43:23.483 UTC
2019-12-19 11:50:22.073 UTC
null
3,257,186
null
89,771
null
1
965
javascript|cross-browser|viewport
821,643
<h2><b>Cross-browser</b> <a href="http://dev.w3.org/csswg/mediaqueries/#width" rel="noreferrer"><code>@media (width)</code></a> and <a href="http://dev.w3.org/csswg/mediaqueries/#height" rel="noreferrer"><code>@media (height)</code></a> values </h2> <pre class="lang-js prettyprint-override"><code>const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0) </code></pre> <h2><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth" rel="noreferrer"><code>window.innerWidth</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight" rel="noreferrer"><code>window.innerHeight</code></a></h2> <ul> <li>gets <a href="http://www.w3.org/TR/CSS2/visuren.html#viewport" rel="noreferrer">CSS viewport</a> <code>@media (width)</code> and <code>@media (height)</code> which include scrollbars</li> <li><code>initial-scale</code> and zoom <a href="https://github.com/ryanve/verge/issues/13" rel="noreferrer">variations</a> may cause mobile values to <b>wrongly</b> scale down to what PPK calls the <a href="http://www.quirksmode.org/mobile/viewports2.html" rel="noreferrer">visual viewport</a> and be smaller than the <code>@media</code> values</li> <li>zoom may cause values to be 1px off due to native rounding</li> <li><code>undefined</code> in IE8-</li> </ul> <h2><a href="https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements#What.27s_the_size_of_the_displayed_content.3F" rel="noreferrer"><code>document.documentElement.clientWidth</code></a> and <code>.clientHeight</code></h2> <ul> <li>equals CSS viewport width <strong>minus</strong> scrollbar width</li> <li>matches <code>@media (width)</code> and <code>@media (height)</code> when there is <strong>no</strong> scrollbar</li> <li><a href="https://github.com/jquery/jquery/blob/1.9.1/src/dimensions.js#L12-L17" rel="noreferrer">same as</a> <code>jQuery(window).width()</code> which <a href="https://api.jquery.com/width/" rel="noreferrer">jQuery</a> <em>calls</em> the browser viewport</li> <li><a href="http://www.quirksmode.org/mobile/tableViewport.html" rel="noreferrer">available cross-browser</a></li> <li><a href="https://github.com/ryanve/verge/issues/22#issuecomment-341944009" rel="noreferrer">inaccurate if doctype is missing</a></li> </ul> <hr /> <h2>Resources</h2> <ul> <li><a href="http://ryanve.com/lab/dimensions/" rel="noreferrer">Live outputs for various dimensions</a></li> <li><a href="http://github.com/ryanve/verge" rel="noreferrer"><b>verge</b></a> uses cross-browser viewport techniques</li> <li><a href="http://github.com/ryanve/actual" rel="noreferrer"><b>actual</b></a> uses <code>matchMedia</code> to obtain precise dimensions in any unit</li> </ul>
1,318,347
How to use Java property files?
<p>I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.</p> <p>Questions:</p> <ul> <li>Do I need to store the file in the same package as the class which will load them, or is there any specific location where it should be placed?</li> <li>Does the file need to end in any specific extension or is <code>.txt</code> OK?</li> <li>How can I load the file in the code</li> <li>And how can I iterate through the values inside?</li> </ul>
1,318,391
17
0
null
2009-08-23 11:31:48.43 UTC
80
2020-05-31 15:01:48.653 UTC
2016-09-16 12:30:11.547 UTC
null
2,886,891
null
49,153
null
1
224
java|properties
311,222
<p>You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.</p> <pre><code>Properties properties = new Properties(); try { properties.load(new FileInputStream("path/filename")); } catch (IOException e) { ... } </code></pre> <p>Iterate as:</p> <pre><code>for(String key : properties.stringPropertyNames()) { String value = properties.getProperty(key); System.out.println(key + " =&gt; " + value); } </code></pre>
6,462,105
How do I access Android's default beep sound?
<p>I would like to make a button play a beep sound to indicate it has been pressed. I want to know how to use the default android beep sound (like when you adjust the ringer volume), instead of importing my own mp3 music file or using ToneGenerator?</p>
6,690,060
4
0
null
2011-06-24 00:24:24.783 UTC
17
2020-07-02 15:44:01.987 UTC
2011-06-24 00:33:09.307 UTC
null
23,897
null
812,892
null
1
56
java|android|beep
70,345
<pre><code>public void playSound(Context context) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException { Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); MediaPlayer mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(context, soundUri); final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); // Uncomment the following line if you aim to play it repeatedly // mMediaPlayer.setLooping(true); mMediaPlayer.prepare(); mMediaPlayer.start(); } } </code></pre> <p>I found another answer:</p> <pre><code>try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } catch (Exception e) { e.printStackTrace(); } </code></pre> <p>credit goes to <a href="https://stackoverflow.com/a/9622040/737925">https://stackoverflow.com/a/9622040/737925</a></p>
6,789,927
Is there a python module to solve linear equations?
<p>I want to solve a linear equation with three or more variables. Is there a good library in python to do it?</p>
6,789,948
6
1
null
2011-07-22 12:19:39.52 UTC
13
2022-08-01 21:56:15.597 UTC
2016-06-13 01:56:39.547 UTC
null
2,683
null
567,797
null
1
47
python
77,481
<p>See <a href="http://sympy.org/" rel="noreferrer">http://sympy.org/</a> and <a href="http://numpy.scipy.org/" rel="noreferrer">http://numpy.scipy.org/</a>.</p> <p>Specifically, <a href="http://docs.scipy.org/doc/numpy/reference/routines.linalg.html" rel="noreferrer">http://docs.scipy.org/doc/numpy/reference/routines.linalg.html</a></p> <p>And <a href="http://docs.sympy.org/0.7.0/tutorial.html#algebra" rel="noreferrer">http://docs.sympy.org/0.7.0/tutorial.html#algebra</a>, <a href="http://docs.sympy.org/dev/modules/solvers/solvers.html" rel="noreferrer">http://docs.sympy.org/dev/modules/solvers/solvers.html</a></p> <p>Edit: Added solvers link from the comment.</p>
6,474,591
How can you determine how much disk space a particular MySQL table is taking up?
<p>Is there a quick way to determine how much disk space a particular MySQL table is taking up? The table may be MyISAM or Innodb.</p>
6,474,642
9
2
null
2011-06-24 23:03:01.307 UTC
80
2021-07-15 03:33:51.373 UTC
null
null
null
null
232,417
null
1
157
mysql
93,580
<p>For a table <code>mydb.mytable</code> run this for:</p> <h1>BYTES</h1> <pre><code>SELECT (data_length+index_length) tablesize FROM information_schema.tables WHERE table_schema='mydb' and table_name='mytable'; </code></pre> <h1>KILOBYTES</h1> <pre><code>SELECT (data_length+index_length)/power(1024,1) tablesize_kb FROM information_schema.tables WHERE table_schema='mydb' and table_name='mytable'; </code></pre> <h1>MEGABYTES</h1> <pre><code>SELECT (data_length+index_length)/power(1024,2) tablesize_mb FROM information_schema.tables WHERE table_schema='mydb' and table_name='mytable'; </code></pre> <h1>GIGABYTES</h1> <pre><code>SELECT (data_length+index_length)/power(1024,3) tablesize_gb FROM information_schema.tables WHERE table_schema='mydb' and table_name='mytable'; </code></pre> <h1>GENERIC</h1> <p>Here is a generic query where the maximum unit display is TB (TeraBytes)</p> <pre><code>SELECT CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',SUBSTR(units,pw1*2+1,2)) DATSIZE, CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',SUBSTR(units,pw2*2+1,2)) NDXSIZE, CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',SUBSTR(units,pw3*2+1,2)) TBLSIZE FROM ( SELECT DAT,NDX,TBL,IF(px&gt;4,4,px) pw1,IF(py&gt;4,4,py) pw2,IF(pz&gt;4,4,pz) pw3 FROM ( SELECT data_length DAT,index_length NDX,data_length+index_length TBL, FLOOR(LOG(IF(data_length=0,1,data_length))/LOG(1024)) px, FLOOR(LOG(IF(index_length=0,1,index_length))/LOG(1024)) py, FLOOR(LOG(IF(data_length+index_length=0,1,data_length+index_length))/LOG(1024)) pz FROM information_schema.tables WHERE table_schema='mydb' AND table_name='mytable' ) AA ) A,(SELECT 'B KBMBGBTB' units) B; </code></pre> <p>Give it a Try !!!</p>
6,862,250
Change a Django form field to a hidden field
<p>I have a Django form with a <code>RegexField</code>, which is very similar to a normal text input field.</p> <p>In my view, under certain conditions I want to hide it from the user, and trying to keep the form as similar as possible. What's the best way to turn this field into a <code>HiddenInput</code> field?</p> <p>I know I can set attributes on the field with:</p> <pre><code>form['fieldname'].field.widget.attr['readonly'] = 'readonly' </code></pre> <p>And I can set the desired initial value with:</p> <pre><code>form.initial['fieldname'] = 'mydesiredvalue' </code></pre> <p>However, that won't change the form of the widget.</p> <p>What's the best / most "django-y" / least "hacky" way to make this field a <code>&lt;input type="hidden"&gt;</code> field?</p>
6,862,413
11
0
null
2011-07-28 16:19:39.787 UTC
31
2022-06-28 02:12:07.343 UTC
2019-04-25 00:25:28.173 UTC
null
5,250,453
null
161,922
null
1
165
python|html|django|django-forms
234,707
<p>If you have a custom template and view you may exclude the field and use <code>{{ modelform.instance.field }}</code> to get the value.</p> <p>also you may prefer to use in the view:</p> <pre><code>form.fields['field_name'].widget = forms.HiddenInput() </code></pre> <p>but I'm not sure it will protect save method on post.</p> <p>Hope it helps.</p>
6,384,659
A dependent property in a ReferentialConstraint is mapped to a store-generated column
<p>I get this error when writing to the database:</p> <blockquote> <p>A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'PaymentId'.</p> </blockquote> <pre><code>public bool PayForItem(int terminalId, double paymentAmount, eNums.MasterCategoryEnum mastercategoryEnum, int CategoryId, int CategoryItemId) { using (var dbEntities = new DatabaseAccess.Schema.EntityModel()) { int pinnumber = 0; long pinid = 1; //getPinId(terminalId,ref pinnumber) ; var payment = new DatabaseAccess.Schema.Payment(); payment.CategoryId = CategoryId; payment.ItemCategoryId = CategoryItemId; payment.PaymentAmount = (decimal)paymentAmount; payment.TerminalId = terminalId; payment.PinId = pinid; payment.HSBCResponseCode = ""; payment.DateActivated = DateTime.Now; payment.PaymentString = "Payment"; payment.PromotionalOfferId = 1; payment.PaymentStatusId = (int)eNums.PaymentStatus.Paid; //payment.PaymentId = 1; dbEntities.AddToPayments(payment); dbEntities.SaveChanges(); } return true; } </code></pre> <p>The schema is:</p> <p><img src="https://i.stack.imgur.com/ygkYW.png" alt="enter image description here"></p>
6,981,567
15
0
null
2011-06-17 10:50:53.337 UTC
11
2022-07-13 12:24:31.71 UTC
2016-05-12 18:02:29.78 UTC
null
153,797
null
788,101
null
1
107
c#|sql-server-2008|linq-to-sql|entity-framework-4
86,296
<p>Is it possible that you defined a bad column relation between your tables?</p> <p>In my case, I had different columns and one was set as autonumeric.</p>
15,698,251
multiprocessing GUI schemas to combat the "Not Responding" blocking
<p>What are the best ways to create a multiprocessing/ GUI coding system?</p> <p>I would like to create a place for the internet community to come and find examples on how to use the <code>multiprocessing</code> module in python. </p> <p>I have seen several small examples of <code>multiprocessing</code> processes on the internet of simple global functions which are called in a main module, but I have found that this rarely translates easily into anything that anyone actually does with regard to GUIs. I would think that many programs would have the functions which they want to use in a separate process as methods of objects (which may be aggregates of other objects etc.) and perhaps a single GUI element would have an associated object that needs to call this process, etc. </p> <p>For example, I have a relatively complex program and I am having problems in getting a responsive GUI for it, which I believed to be due to my lack of understanding in <code>multiprocessing</code> and threading with <code>QThread</code>. However, I do know that the example given below will at least pass information between processes in the manner I desire (due to being able to execute <code>print</code> statements) but my GUI is still locking. Does anyone know what may be causing this, and if it is still a probelm with my lack of understanding in mutlithreaded/multiprocessing architectures?</p> <p>Here is a small pseudo code example of what I am doing:</p> <pre><code>class Worker: ... def processing(self, queue): # put stuff into queue in a loop # This thread gets data from Worker class Worker_thread(QThread): def __init__(self): ... # make process with Worker inside def start_processing(self): # continuously get data from Worker # send data to Tab object with signals/slots class Tab(QTabWidget): # spawn a thread separate from main GUI thread # update GUI using slot def update_GUI() </code></pre> <p>And this code is fully compilable example which embodies the overlying sturcture of my program:</p> <pre><code>from PyQt4 import QtCore, QtGui import multiprocessing as mp import numpy as np import sys import time # This object can hold several properties which will be used for the processing # and will be run in the background, while it updates a thread with all of it's progress class Worker: def __init__(self, some_var): self.some_var = some_var self.iteration = 0 def some_complex_processing(self, queue): for i in range(0,5000): self.iteration += 1 queue.put(self.iteration) queue.put('done with processing') # This Woker_thread is a thread which will spawn a separate process (Worker). # This separate is needed in order to separate the data retrieval # from the main GUI thread, which should only quickly update when needed class Worker_thread(QtCore.QThread): # signals and slots are used to communicate back to the main GUI thread update_signal = QtCore.pyqtSignal(int) done_signal = QtCore.pyqtSignal() def __init__(self, parent, worker): QtCore.QThread.__init__(self, parent) self.queue = mp.Queue() self.worker = worker self.parent = parent self.process = mp.Process(target=self.worker.some_complex_processing, args=(self.queue,)) # When the process button is pressed, this function will start getting data from Worker # this data is then retrieved by the queue and pushed through a signal # to Tab.update_GUI @QtCore.pyqtSlot() def start_computation(self): self.process.start() while(True): try: message = self.queue.get() self.update_signal.emit(message) except EOFError: pass if message == 'done with processing': self.done_signal.emit() break #self.parent.update_GUI(message) self.process.join() return # Each tab will start it's own thread, which will spawn a process class Tab(QtGui.QTabWidget): start_comp = QtCore.pyqtSignal() def __init__(self, parent, this_worker): self.parent = parent self.this_worker = this_worker QtGui.QTabWidget.__init__(self, parent) self.treeWidget = QtGui.QTreeWidget(self) self.properties = QtGui.QTreeWidgetItem(self.treeWidget, ["Properties"]) self.step = QtGui.QTreeWidgetItem(self.properties, ["Iteration #"]) self.thread = Worker_thread(parent=self, worker=self.this_worker) self.thread.update_signal.connect(self.update_GUI) self.thread.done_signal.connect(self.thread.quit) self.start_comp.connect(self.thread.start_computation) self.thread.start() ############################### # Here is what should update the GUI at every iteration of Worker.some_complex_processing() # The message appears to be getting sent, due to seeing the print statement in the console, but the GUI is not updated. @QtCore.pyqtSlot(int) def update_GUI(self, iteration): self.step.setText(0, str(iteration)) #time.sleep(0.1) print iteration def start_signal_emit(self): self.start_comp.emit() # GUI stuff class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self) self.tab_list = [] self.setTabShape(QtGui.QTabWidget.Rounded) self.centralwidget = QtGui.QWidget(self) self.top_level_layout = QtGui.QGridLayout(self.centralwidget) self.tabWidget = QtGui.QTabWidget(self.centralwidget) self.top_level_layout.addWidget(self.tabWidget, 1, 0, 25, 25) process_button = QtGui.QPushButton("Process") self.top_level_layout.addWidget(process_button, 0, 1) QtCore.QObject.connect(process_button, QtCore.SIGNAL("clicked()"), self.process) self.setCentralWidget(self.centralwidget) self.centralwidget.setLayout(self.top_level_layout) # Make Tabs in loop from button for i in range(0,10): name = 'tab' + str(i) self.tab_list.append(Tab(self.tabWidget, Worker(name))) self.tabWidget.addTab(self.tab_list[-1], name) # Do the processing def process(self): for tab in self.tab_list: tab.start_signal_emit() return if __name__ == "__main__": app = QtGui.QApplication([]) win = MainWindow() win.show() sys.exit(app.exec_()) </code></pre> <p><em><strong>More Information:</em></strong> I am writing a program which I would like to spawn several processes from and have them continuously show their progress throughout their processing. I would like the program to be multiprocessed in order to get the best speed out of the program as possible.</p> <p>At the moment, I am trying to use a thread to spawn a process and use signals and slots to update the GUI while the data is continuously retrieved by a queue. It appears that the <code>queues</code>, <code>signals</code>, and <code>slots</code> work when using <code>print</code> statements, but can not update the GUI. If anyone has any other suggestions as to how I should structure this in order to keep the program more managable, I would like to learn.</p> <p><em><strong>EDIT</em></strong>: I have made the adjustments put forth by Min Lin, with the addition of making <code>Worker</code> a <code>QObject</code> so that <code>moveToThread()</code> would work.<br> Here is the new code I have at the moment:</p> <pre><code>from PyQt4 import QtCore, QtGui import multiprocessing as mp import numpy as np import sys import time class Worker(QtCore.QObject): update_signal = QtCore.pyqtSignal(int) done_signal = QtCore.pyqtSignal() def __init__(self, some_var): QtCore.QObject.__init__(self, parent=None) self.some_var = some_var self.iteration = 0 self.queue = mp.Queue() self.process = mp.Process(target=self.some_complex_processing, args=(self.queue,)) def some_complex_processing(self, queue): for i in range(0,5000): self.iteration += 1 queue.put(self.iteration) queue.put('done with processing') @QtCore.pyqtSlot() def start_computation(self): self.process.start() while(True): try: message = self.queue.get() self.update_signal.emit(message) except EOFError: pass if message == 'done with processing': self.done_signal.emit() break self.process.join() return class Tab(QtGui.QTabWidget): start_comp = QtCore.pyqtSignal() def __init__(self, parent, this_worker): self.parent = parent self.this_worker = this_worker QtGui.QTabWidget.__init__(self, parent) self.treeWidget = QtGui.QTreeWidget(self) self.properties = QtGui.QTreeWidgetItem(self.treeWidget, ["Properties"]) self.step = QtGui.QTreeWidgetItem(self.properties, ["Iteration #"]) # Use QThread is enough self.thread = QtCore.QThread(); # Change the thread affinity of worker to self.thread. self.this_worker.moveToThread(self.thread); self.this_worker.update_signal.connect(self.update_GUI) self.this_worker.done_signal.connect(self.thread.quit) self.start_comp.connect(self.this_worker.start_computation) self.thread.start() ############################### # Here is what should update the GUI at every iteration of Worker.some_complex_processing() # The message appears to be getting sent, due to seeing the print statement in the console, but the GUI is not updated. @QtCore.pyqtSlot(int) def update_GUI(self, iteration): self.step.setText(0, str(iteration)) #time.sleep(0.1) print iteration def start_signal_emit(self): self.start_comp.emit() # GUI stuff class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self) self.tab_list = [] self.setTabShape(QtGui.QTabWidget.Rounded) self.centralwidget = QtGui.QWidget(self) self.top_level_layout = QtGui.QGridLayout(self.centralwidget) self.tabWidget = QtGui.QTabWidget(self.centralwidget) self.top_level_layout.addWidget(self.tabWidget, 1, 0, 25, 25) process_button = QtGui.QPushButton("Process") self.top_level_layout.addWidget(process_button, 0, 1) QtCore.QObject.connect(process_button, QtCore.SIGNAL("clicked()"), self.process) self.setCentralWidget(self.centralwidget) self.centralwidget.setLayout(self.top_level_layout) # Make Tabs in loop from button for i in range(0,10): name = 'tab' + str(i) self.tab_list.append(Tab(self.tabWidget, Worker(name))) self.tabWidget.addTab(self.tab_list[-1], name) # Do the processing def process(self): for tab in self.tab_list: tab.start_signal_emit() return if __name__ == "__main__": app = QtGui.QApplication([]) win = MainWindow() win.show() sys.exit(app.exec_()) </code></pre> <p>Thank you for all of the answers, I appreciate the level of detail that everyone has gone into in describing the idea they believe to be solution, but unfortunately I have not yet been able to perform these types of processes which operate on the object they belong to while displaying the object's attribute on a GUI.<br> However, I have learned a decent amount from this post, which allowed me to realize that the threaded version I have at the moment is hanging the GUI since the GUI update function is too large and takes too much processing.</p> <p>So, I have taken the <code>QTimer()</code> approach to my multi-threaded version and it is performing much better! I would advise anyone facing similar problems to at least attempt something similar to this. </p> <p>I was unaware of this approach to solving GUI update problems, and it is now a pseudo or temporary fix to the problem I am facing.</p>
15,875,187
4
1
null
2013-03-29 06:06:38.39 UTC
8
2013-10-10 12:44:50.2 UTC
2013-04-12 03:42:49.3 UTC
null
1,486,196
null
1,486,196
null
1
15
python|multithreading|qt|user-interface|multiprocessing
6,311
<p>A GUI application is perfect for testing stuff, as it is easy to spawn new tasks and visualize what is going on, so I wrote a little example app (<a href="https://i.stack.imgur.com/TraFQ.png" rel="noreferrer">Screenshot</a>, code is below) as I did want to learn it for my self.</p> <p>At first, i took a similar approach as yours, trying to implement the Consumer/Producer pattern and I struggeled with Background Processes doing endless loops to wait for new jobs and took care of communication back and forth for myself. Then I found out about the <a href="http://docs.python.org/3.2/library/multiprocessing.html#module-multiprocessing.pool" rel="noreferrer">Pool</a> Interface and then I could replace all that hidious code with just a few lines. All you need is a single pool and a few callbacks:</p> <pre><code>#!/usr/bin/env python3 import multiprocessing, time, random, sys from PySide.QtCore import * # equivalent: from PyQt4.QtCore import * from PySide.QtGui import * # equivalent: from PyQt4.QtGui import * def compute(num): print("worker() started at %d" % num) random_number = random.randint(1, 6) if random_number in (2, 4, 6): raise Exception('Random Exception in _%d' % num) time.sleep(random_number) return num class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.toolBar = self.addToolBar("Toolbar") self.toolBar.addAction(QAction('Add Task', self, triggered=self.addTask)) self.list = QListWidget() self.setCentralWidget(self.list) # Pool of Background Processes self.pool = multiprocessing.Pool(processes=4) def addTask(self): num_row = self.list.count() self.pool.apply_async(func=compute, args=(num_row,), callback=self.receiveResult, error_callback=self.receiveException) item = QListWidgetItem("item %d" % num_row) item.setForeground(Qt.gray) self.list.addItem(item) def receiveResult(self, result): assert isinstance(result, int) print("end_work(), where result is %s" % result) self.list.item(result).setForeground(Qt.darkGreen) def receiveException(self, exception): error = str(exception) _pos = error.find('_') + 1 num_row = int(error[_pos:]) item = self.list.item(num_row) item.setForeground(Qt.darkRed) item.setText(item.text() + ' Retry...') self.pool.apply_async(func=compute, args=(num_row,), callback=self.receiveResult, error_callback=self.receiveException) if __name__ == '__main__': app = QApplication(sys.argv) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) </code></pre> <p>Edit: I did another example using a QTimer instead of Callbacks, checking periodically for Entries in a Queue, updating a QProgressBar:</p> <pre><code>#!/usr/bin/env python3 import multiprocessing, multiprocessing.pool, time, random, sys from PySide.QtCore import * from PySide.QtGui import * def compute(num_row): print("worker started at %d" % num_row) random_number = random.randint(1, 10) for second in range(random_number): progress = float(second) / float(random_number) * 100 compute.queue.put((num_row, progress,)) time.sleep(1) compute.queue.put((num_row, 100)) def pool_init(queue): # see http://stackoverflow.com/a/3843313/852994 compute.queue = queue class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.toolBar = self.addToolBar("Toolbar") self.toolBar.addAction(QAction('Add Task', self, triggered=self.addTask)) self.table = QTableWidget() self.table.verticalHeader().hide() self.table.setColumnCount(2) self.setCentralWidget(self.table) # Pool of Background Processes self.queue = multiprocessing.Queue() self.pool = multiprocessing.Pool(processes=4, initializer=pool_init, initargs=(self.queue,)) # Check for progress periodically self.timer = QTimer() self.timer.timeout.connect(self.updateProgress) self.timer.start(2000) def addTask(self): num_row = self.table.rowCount() self.pool.apply_async(func=compute, args=(num_row,)) label = QLabel("Queued") bar = QProgressBar() bar.setValue(0) self.table.setRowCount(num_row + 1) self.table.setCellWidget(num_row, 0, label) self.table.setCellWidget(num_row, 1, bar) def updateProgress(self): if self.queue.empty(): return num_row, progress = self.queue.get() # unpack print("received progress of %s at %s" % (progress, num_row)) label = self.table.cellWidget(num_row, 0) bar = self.table.cellWidget(num_row, 1) bar.setValue(progress) if progress == 100: label.setText('Finished') elif label.text() == 'Queued': label.setText('Downloading') self.updateProgress() # recursion if __name__ == '__main__': app = QApplication(sys.argv) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) </code></pre>
15,844,710
Padding bars remain when scrolling GridView
<p>I have this <code>GridView</code> (see screenshot) that contains items that all need about 12 dip spacing. However, when I set padding on the <code>GridView</code>, it seems that I can't scroll across this paddingm which I do want to do. How do I achieve this?</p> <p>Note the slice of space above the top two pictures that I want to scroll away from:</p> <p><img src="https://i.stack.imgur.com/ry2ZN.png" alt="screenshot while scrolling"></p> <p>Code:</p> <pre><code>&lt;GridView android:id="@+id/feed_grid" android:layout_width="fill_parent" android:layout_height="wrap_content" android:columnWidth="96dp" android:gravity="center" android:horizontalSpacing="@dimen/grid_view_margins" android:numColumns="auto_fit" android:padding="@dimen/grid_view_margins" android:stretchMode="columnWidth" android:scrollbarStyle="outsideInset" android:verticalSpacing="@dimen/grid_view_margins" /&gt; </code></pre>
16,123,746
1
4
null
2013-04-05 22:33:57.477 UTC
9
2013-04-21 10:10:28.577 UTC
2013-04-21 10:10:28.577 UTC
null
673,206
null
673,206
null
1
25
android
3,534
<p><code>android:clipToPadding="false"</code> will solve your purpose</p>
15,619,216
Groovy scope - how to access script variable in a method
<p>I have a question about scoping rules in Groovy. In the following snippet, I have three variables, <code>a</code> has local scope, <code>b</code> has script scope, and <code>c</code> should get script scope as well using the <code>@Field</code> annotation.</p> <pre><code>#!/usr/bin/groovy import groovy.transform.Field; //println org.codehaus.groovy.runtime.InvokerHelper.getVersion() def a = 42; b = "Tea" @Field def c = "Cheese" void func() { // println a // MissingPropertyException println b // prints "Tea" println c // prints "Cheese" with groovy 2.1.2, MissingPropertyException with groovy 1.8.6 } class Main { def method() { // println a // MissingPropertyException // println b // MissingPropertyException // println c // MissingPropertyException with both 1.8.6. and 2.1.2 } } func(); new Main().method(); </code></pre> <p>I get <code>MissingPropertyException</code>s on the lines indicated with comments. The exceptions on <code>a</code> are expected, as that variable has local scope. But I would expect <code>b</code> to be accessible inside <code>method()</code> - it isn't. <code>@Field</code> doesn't do anything in groovy 1.8.6, although after upgrading it works, so I guess that is an old bug. Nevertheless, <code>c</code> is inaccessible inside <code>method()</code> with either version.</p> <p>So my questions are:</p> <ol> <li>Why can't I access a variable annotated with <code>@Field</code> inside <code>method()</code>? </li> <li>How can I refer to a script variable inside <code>method()</code>?</li> </ol>
15,619,867
2
0
null
2013-03-25 15:54:53.42 UTC
9
2015-01-19 09:33:38.143 UTC
2015-01-19 09:33:38.143 UTC
null
33,311
null
3,306
null
1
38
groovy|scope
47,277
<p>When you have methods or statements outside of a <code>class</code> declaration in a groovy script, an implicit class is created. To answer your questions:</p> <ol> <li><p>In your example, <code>func()</code> can access the field <code>c</code> because they are both members of the implicit class. The <code>Main</code> class is not, so it can't.</p></li> <li><p>You need to pass a reference to the script variable to <code>method()</code>. One way is to pass the implicitly defined <code>binding</code> object, through which you can access all the script scope variables.</p></li> </ol> <p>Example:</p> <pre><code>#!/usr/bin/groovy import groovy.transform.Field; //println org.codehaus.groovy.runtime.InvokerHelper.getVersion() def a = 42; b = "Tea" @Field def c = "Cheese" void func() { // println a // MissingPropertyException println b // prints "Tea" println c // prints "Cheese" with groovy 2.1.2, MissingPropertyException with groovy 1.8.6 } class Main { def scriptObject def binding def method() { // println a // MissingPropertyException println binding.b println scriptObject.c } } func(); new Main(scriptObject: this, binding: binding).method(); </code></pre>
15,900,338
Python Request Post with param data
<p>This is the raw request for an API call:</p> <pre><code>POST http://192.168.3.45:8080/api/v2/event/log?sessionKey=b299d17b896417a7b18f46544d40adb734240cc2&amp;format=json HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/json Content-Length: 86 Host: 192.168.3.45:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) {"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}""" </code></pre> <p>This request returns a success (2xx) response.</p> <p>Now I am trying to post this request using <code>requests</code>:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; headers = {'content-type' : 'application/json'} &gt;&gt;&gt; data ={"eventType":"AAS_PORTAL_START","data{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}} &gt;&gt;&gt; url = "http://192.168.3.45:8080/api/v2/event/log?sessionKey=9ebbd0b25760557393a43064a92bae539d962103&amp;format=xml&amp;platformId=1" &gt;&gt;&gt; requests.post(url,params=data,headers=headers) &lt;Response [400]&gt; </code></pre> <p>Everything looks fine to me and I am not quite sure what I posting wrong to get a 400 response.</p>
15,900,453
3
0
null
2013-04-09 11:12:56.547 UTC
64
2020-12-15 05:36:25.293 UTC
2016-11-15 13:55:07.727 UTC
null
202,229
null
1,949,081
null
1
225
python|httprequest|python-requests|http-status-codes
540,203
<p><code>params</code> is for GET-style URL parameters, <code>data</code> is for POST-style body information. It is perfectly legal to provide <em>both</em> types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.</p> <p>Your raw post contains <em>JSON</em> data though. <code>requests</code> can handle JSON encoding for you, and it'll set the correct <code>Content-Type</code> header too; all you need to do is pass in the Python object to be encoded as JSON into the <code>json</code> keyword argument.</p> <p>You could split out the URL parameters as well:</p> <pre><code>params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1} </code></pre> <p>then post your data with:</p> <pre><code>import requests url = 'http://192.168.3.45:8080/api/v2/event/log' data = {&quot;eventType&quot;: &quot;AAS_PORTAL_START&quot;, &quot;data&quot;: {&quot;uid&quot;: &quot;hfe3hf45huf33545&quot;, &quot;aid&quot;: &quot;1&quot;, &quot;vid&quot;: &quot;1&quot;}} params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1} requests.post(url, params=params, json=data) </code></pre> <p>The <code>json</code> keyword is new in <code>requests</code> version 2.4.2; if you still have to use an older version, encode the JSON manually using the <code>json</code> module and post the encoded result as the <code>data</code> key; you will have to explicitly set the Content-Type header in that case:</p> <pre><code>import requests import json headers = {'content-type': 'application/json'} url = 'http://192.168.3.45:8080/api/v2/event/log' data = {&quot;eventType&quot;: &quot;AAS_PORTAL_START&quot;, &quot;data&quot;: {&quot;uid&quot;: &quot;hfe3hf45huf33545&quot;, &quot;aid&quot;: &quot;1&quot;, &quot;vid&quot;: &quot;1&quot;}} params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1} requests.post(url, params=params, data=json.dumps(data), headers=headers) </code></pre>
22,470,150
How to get a java.time object from a java.sql.Timestamp without a JDBC 4.2 driver?
<p>When retrieving a <a href="http://download.java.net/jdk8/docs/api/java/sql/Timestamp.html" rel="noreferrer">java.sql.Timestamp</a> from a database via JDBC 4.1 or earlier, how does one obtain/convert to a <a href="http://download.java.net/jdk8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> object?</p> <p>Neither of the open-source JDBC drivers for Postgres is JDBC 4.2 compliant yet, so I'm looking for a way to use use java.time with JDBC 4.1.</p>
22,470,650
2
3
null
2014-03-18 04:03:57.257 UTC
8
2018-06-03 17:34:50.313 UTC
2014-03-18 04:44:32.683 UTC
null
642,706
null
642,706
null
1
32
java|datetime|jdbc|java-time
12,014
<h1>New Methods On Old Classes</h1> <p>By using the driver with Java 8 and later, you should automatically pick up some methods on your <a href="http://download.java.net/javase/8/docs/api/java/sql/Timestamp.html"><code>java.sql.Timestamp</code></a> object for free. Both <a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Time.html"><code>java.sql.Time</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html"><code>java.sql.Date</code></a> have similar conversion methods.</p> <p>Namely, to convert from <em>java.sql</em> to <em>java.time</em> you are looking for:</p> <ul> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html#toInstant--"><code>Timestamp::toInstant()</code></a> </li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html#toLocalDateTime--"><code>Timestamp::toLocalDateTime()</code></a> </li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#toLocalDate--"><code>Date::toLocalDate()</code></a> </li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Time.html#toLocalTime--"><code>Time::toLocalTime()</code></a> </li> </ul> <p>To go the other direction, from <em>java.time</em> to <em>java.sql</em>, use the new static methods:</p> <ul> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html#from-java.time.Instant-"><code>Timestamp.from(instant)</code></a></li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html#valueOf-java.time.LocalDateTime-"><code>Timestamp.valueOf(localDateTime)</code></a></li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#valueOf-java.time.LocalDate-"><code>Date.valueOf(localDate)</code></a></li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Time.html#valueOf-java.time.LocalTime-"><code>Time.valueOf(localTime)</code></a></li> </ul> <p>Example:</p> <pre class="lang-java prettyprint-override"><code>preparedStatement.setTimestamp( 2, Timestamp.from(instant) ); </code></pre>
13,354,301
Maven: Add local dependencies to jar
<p>I have a dependency </p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;de.matthiasmann&lt;/groupId&gt; &lt;artifactId&gt;twl&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;scope&gt;system&lt;/scope&gt; &lt;systemPath&gt;${project.basedir}/lib/TWL.jar&lt;/systemPath&gt; &lt;/dependency&gt; </code></pre> <p>Then I execute <code>mvn assembly:assembly</code>. All natives files and remote maven libs are added, but there is no this jar.</p> <p><strong>UPDATE</strong></p> <p>When I am trying to run app by <code>java -jar myjar.jar</code>. It returns an error that there is no class from the above dependency (NoClassDefFoundError : de.matthiasmann.twl.ForExample). I want to add classes from this jar to myjar.jar (the same what maven does with remote dependencies). How I can configure maven to do that?</p>
13,354,413
4
2
null
2012-11-13 01:19:46.99 UTC
4
2014-07-11 12:11:46.603 UTC
2012-11-13 01:28:03.307 UTC
null
1,594,394
null
1,594,394
null
1
7
java|maven
42,292
<p>See <a href="https://stackoverflow.com/questions/2065928/maven-2-assembly-with-dependencies-jar-under-scope-system-not-included">Maven 2 assembly with dependencies: jar under scope &quot;system&quot; not included</a> for why system dependencies are not included and how you can work around it, specifically the <code>mvn install:install-file</code> code is what you want.</p>
28,486,138
What is the best way to determine if a string contains a character from a set in Swift
<p>I need to determine if a string contains any of the characters from a custom set that I have defined.</p> <p>I see from <a href="https://stackoverflow.com/questions/24034043/how-do-i-check-if-a-string-contains-another-string-in-swift">this</a> post that you can use rangeOfString to determine if a string contains another string. This, of course, also works for characters if you test each character one at a time.</p> <p>I'm wondering what the best way to do this is.</p>
28,486,492
11
4
null
2015-02-12 19:29:05.02 UTC
15
2020-01-20 12:58:40.51 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,753,703
null
1
51
swift
67,313
<p>You can create a <code>CharacterSet</code> containing the set of your custom characters and then test the membership against this character set:</p> <p><strong>Swift 3:</strong></p> <pre><code>let charset = CharacterSet(charactersIn: "aw") if str.rangeOfCharacter(from: charset) != nil { print("yes") } </code></pre> <p>For case-insensitive comparison, use</p> <pre><code>if str.lowercased().rangeOfCharacter(from: charset) != nil { print("yes") } </code></pre> <p>(assuming that the character set contains only lowercase letters).</p> <p><strong>Swift 2:</strong></p> <pre><code>let charset = NSCharacterSet(charactersInString: "aw") if str.rangeOfCharacterFromSet(charset) != nil { print("yes") } </code></pre> <p><strong>Swift 1.2</strong></p> <pre><code>let charset = NSCharacterSet(charactersInString: "aw") if str.rangeOfCharacterFromSet(charset, options: nil, range: nil) != nil { println("yes") } </code></pre>
16,225,815
Object, world, camera and projection spaces in OpenGL
<p>I'm trying to understand creating spaces in OpenGL:</p> <ol> <li><p>Object space</p></li> <li><p>World space</p></li> <li><p>Camera space</p></li> <li><p>Projection space</p></li> </ol> <hr> <p>Is my understanding of these stages correct?</p> <ol> <li><p>The "cube" is being created in the center of the cartesian coordinate system, directly inside the program by typing the vertices coordinates.</p></li> <li><p>The coordinates are transformed into coordinates inside of the "world", which means moving it to any place on the screen.</p></li> </ol> <p>Well, actually I'd like you to check my understanding of those two terms.</p> <hr> <p>Now, I'm creating a triangle on the black screen. How does openGL code fits to these spaces?</p> <p>It works on <code>GL_MODELVIEW</code> flag by default, but that's the second stage - world space. Does that mean that calling <code>glVertex3f()</code> creates a triangle in the object space?</p> <p>Where is the world space part?</p> <hr> <p>Also, I've read that the last two spaces are not part of the openGL pipeline (or whatever it's called). However, OpenGL contains flags such as the <code>GL_PROJECTION</code>, for example:</p> <pre><code>glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, w, h); // w - width, h - height gluPerspective(45, ratio, 1, 100); // radio = w/h glMatrixMode(GL_MODELVIEW); </code></pre> <p>What does this code do? It sets the perspective. Does it create the z axis? But isn't it already the object space part?</p>
16,226,282
1
1
null
2013-04-25 22:30:53.98 UTC
15
2017-01-18 09:56:31.577 UTC
2017-01-18 09:50:01.96 UTC
null
3,924,118
null
2,252,786
null
1
22
opengl|graphics
16,733
<p>1) Object space is the object's vertices relative to the object's origin. In the case of a 1x1x1 cube, your vertices would be:</p> <pre><code>( 0.5, 0.5, 0.5) (-0.5, 0.5, 0.5) ( 0.5, -0.5, 0.5) (-0.5, -0.5, 0.5) </code></pre> <p>etc.</p> <p>2) World space is where the object is in your world. If you want this cube to be at <code>(15, 10)</code>, you'd create a translation matrix that, when multiplied with each vertex, would center your vertices around <code>(15, 10)</code>. For example, the first vertex would become <code>(15.5, 10.5, 0.5)</code>. The matrix to go from object to world space is called the "model" matrix.</p> <p>3) Eye Space (sometimes called Camera space) is the world relative to the location of the viewer. Since this has to be a matrix that each vertex is multiplied by, it's technically the inverse of the camera's orientation. That is, if you want a camera at <code>(0, 0, -10)</code>, your "view" matrix has to be a translation of <code>(0, 0, 10)</code>. That way all the objects in the world are forward 10 units, making it look like you are backwards 10 units.</p> <p>4) Projection space is how we apply a correct perspective to a scene (assuming you're not using an orthographic projection). This is almost always represented by a frustum, and <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html" rel="noreferrer">this article</a> can explain that better than I can. Essentially you are mapping 3d space onto another skewed space.</p> <p>OpenGL then handles clip space and screen space.</p> <hr> <blockquote> <p>It works on <code>GL_MODELVIEW</code> flag by default, but that's the second stage - world space. Does that mean that calling <code>glVertex3f()</code> creates a triangle in the object space?</p> </blockquote> <p><em>You set vertices with <code>glVertex3f()</code> in object space always</em>. (this is actually a very old and slow way to do it, but that's not really the point of this question)</p> <p>When you set <code>GL_MODELVIEW</code>, it's only changing the model matrix (which can be manipulated with <code>glLoadMatrix</code>, <code>glTranslate</code>, <code>glRotate</code>, <code>glScale</code>, etc.).</p> <hr> <p>Line by line, your piece of code is doing the following:</p> <ol> <li>All transformations will now be affecting the projection matrix.</li> <li>Clear out the old projection matrix and replace it with the identity matrix.</li> <li>Use the entire screen as the viewport.</li> <li>Set the projection matrix to a perspective with a 45 degree vertical field of view with an aspect ratio of w/h, the near-clip plane 1 unit away, and the far-clip plane 100 units away.</li> <li>All transformations are now affecting the modelview matrix again.</li> </ol> <p>The Z axis already exists, this just sets the projection matrix that gives you perspective, tells OpenGL to use the entire window to render. This isn't the object space, it's the way you transform object space to projection space.</p> <hr> <p>Also a side note, you're using really, really old OpenGL (1992 old). glTranslate, etc. were deprecated a long time ago and are now just removed from the API. The only reason you can still use them is because drivers keep them there for compatibility's sake. I'd recommend you look into using modern (3.0+) OpenGL. Modern graphics pipelines are several orders of magnitude faster than immediate mode (glBegin, glVertex, glEnd).</p>
16,526,209
Jasmine in a separate test project
<p>Is it practical/possible to separate jasmine tests into a separate visual studio project? </p> <p>I am just getting started with angular, and am trying to write my tests before I start on the actual angular implementation. I will be writing my project in <strong>Visual Studio 2012</strong> with the <strong>Chutzpah test runner</strong>, see this <a href="http://www.youtube.com/watch?v=meJ94rAN7P8" rel="noreferrer">video</a>. Currently, I am trying to figure out how to organize my folder structure. I know about angular-seed and yeoman, but those are ill suited to starting a .net project. </p> <p>I am assuming that since unit tests in Visual Studio are usually separated into a separate test project, by convention, the jasmine tests should, too.</p> <p>However, for java script, there are no project dlls to reference, so separating the tests out into a different project would require a lot of copy and pasting, I think.</p>
16,614,416
3
0
null
2013-05-13 15:52:21.02 UTC
9
2019-06-19 04:43:50.473 UTC
2013-05-13 17:04:51.453 UTC
null
13,302
null
860,947
null
1
23
asp.net-mvc|asp.net-mvc-4|visual-studio-2012|jasmine|chutzpah
7,761
<p>You can do this with no copy/pasting. In your Jasmine tests you can add a <code>/// &lt;reference</code> comment which posts to your source files (or the directory containing them). For example given this sturcture</p> <blockquote> <p>/ProjectA /scripts</p> <pre><code>code1.js code2.js </code></pre> <p>/TestProjectB test1.js</p> </blockquote> <p>You can add this line at the top of your test1.js file to reference all your code files:</p> <pre><code>/// &lt;reference path="../scripts" /&gt; </code></pre>
16,506,095
Do I have to use #include <string> beside <iostream>?
<p>I started learning C++ and I read a book which writes that I must use the <code>&lt;string&gt;</code> header file because the string type is not built directly into the compiler. If I use the <code>&lt;iostream&gt;</code> I can use the string type.</p> <p>Do I have to include the <code>&lt;string&gt;</code> header when I want to use the string type if I included the <code>&lt;iostream&gt;</code> header? Why? Is there some difference?</p>
16,506,108
2
0
null
2013-05-12 09:49:14.61 UTC
9
2013-05-12 11:04:13.15 UTC
2013-05-12 11:04:13.15 UTC
null
1,796,645
null
2,374,540
null
1
27
c++|string|types|include|iostream
20,737
<p>Yes, you have to include what you use. It's not mandated that standard headers include one another (with a few exceptions IIRC). It might work now, but might fail on a different compiler.</p> <p>In your case, apparently <code>&lt;iostream&gt;</code> includes <code>&lt;string&gt;</code>, directly or indirectly, but don't rely on it.</p>
29,003,215
Newtonsoft.Json serialization returns empty json object
<p>I have list of objects of following class:</p> <pre><code>public class Catagory { int catagoryId; string catagoryNameHindi; string catagoryNameEnglish; List&lt;Object&gt; subCatagories; public Catagory(int Id, string NameHindi, string NameEng,List&lt;Object&gt; l) { this.catagoryId = Id; this.catagoryNameHindi = NameHindi; this.catagoryNameEnglish = NameEng; this.subCatagories = l; } } public class SubCatagory { int subCatagoryId { get; set; } string subCatNameHindi { get; set; } string subCatNameEng { get; set; } public SubCatagory(int Id, string NameHindi, string NameEng) { this.subCatagoryId = Id; this.subCatNameEng = NameEng; this.subCatNameHindi = NameHindi; } } </code></pre> <p>when I am converting this list to json string by using Newtonsoft.Json it returns array of empty objects.</p> <pre><code> string json=JsonConvert.SerializeObject(list); </code></pre> <p>I am getting following result.</p> <blockquote> <p>[{},{},{},{},{}]</p> </blockquote> <p>Please help me regarding this problem.</p>
29,003,893
4
5
null
2015-03-12 06:29:35.707 UTC
8
2022-03-12 05:16:51.413 UTC
2015-03-12 07:57:43.527 UTC
null
14,938,772
null
14,938,772
null
1
60
asp.net|json|json.net
47,167
<p>By default, NewtonSoft.Json will only serialize public members, so make your fields public:</p> <pre><code>public class Catagory { public int catagoryId; public string catagoryNameHindi; public string catagoryNameEnglish; public List&lt;Object&gt; subCatagories; public Catagory(int Id, string NameHindi, string NameEng, List&lt;Object&gt; l) { this.catagoryId = Id; this.catagoryNameHindi = NameHindi; this.catagoryNameEnglish = NameEng; this.subCatagories = l; } } </code></pre> <p>If for some reason you really don't want to make your fields public, you can instead decorate them with the <a href="http://www.newtonsoft.com/json/help/html/SerializationAttributes.htm" rel="noreferrer">JsonPropertyAttribute</a> to allow them to be serialized and deserialized:</p> <pre><code>[JsonProperty] int catagoryId; </code></pre> <p>This attribute also allows specifying other options, such as specifying the property name to use when serializing/deserializing:</p> <pre><code>[JsonProperty(&quot;categoryId&quot;)] int Category; </code></pre>
28,997,326
Postman addon's like in firefox
<p>Is there a recommended add-ons in the firefox, which is has the most features that postman have? </p>
28,998,656
3
6
null
2015-03-11 21:03:37.683 UTC
15
2018-12-24 21:05:38.377 UTC
2015-03-12 01:36:31.173 UTC
null
1,828,637
null
3,419,661
null
1
101
firefox|firefox-addon|postman
145,114
<p>There's a few: </p> <ul> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/rested/?src=stackoverflow" rel="noreferrer">Rested</a></li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/restclient/" rel="noreferrer">RESTClient</a> </li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/rest-easy/?src=userprofile" rel="noreferrer">REST Easy</a></li> </ul>
29,289,177
BinaryFileResponse in Laravel undefined
<p>I have got the following problem: I want to return an Image on the route /getImage/{id} The function looks like this:</p> <pre><code>public function getImage($id){ $image = Image::find($id); return response()-&gt;download('/srv/www/example.com/api/public/images/'.$image-&gt;filename); } </code></pre> <p>When I do this it returns me this:</p> <pre><code>FatalErrorException in HandleCors.php line 18: Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header() </code></pre> <p>I have got <code>use Response;</code> at the beginning of the controller. I dont think that the HandleCors.php is the problem but anyway:</p> <pre><code>&lt;?php namespace App\Http\Middleware; use Closure; use Illuminate\Contracts\Routing\Middleware; use Illuminate\Http\Response; class CORS implements Middleware { public function handle($request, Closure $next) { return $next($request)-&gt;header('Access-Control-Allow-Origin' , '*') -&gt;header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE') -&gt;header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application'); } } </code></pre> <p>I actually dont know why this happens since it is exactly like it is described in the Laravel Docs. I have updated Laravel when I got the error but this did not fix it.</p>
29,289,684
5
12
null
2015-03-26 21:25:58.43 UTC
8
2022-09-05 12:09:18.293 UTC
2022-03-24 06:06:27.81 UTC
null
1,235,698
null
2,540,081
null
1
33
php|laravel
31,519
<p>The problem is that you're calling <code>-&gt;header()</code> on a <code>Response</code> object that doesn't have that function (the <code>Symfony\Component\HttpFoundation\BinaryFileResponse</code> class). The <code>-&gt;header()</code> function is <a href="https://github.com/laravel/framework/blob/b073237d341549ada2f13e8e5b1d6d98f93428ec/src/Illuminate/Http/ResponseTrait.php#L15-L19" rel="noreferrer">part of a trait</a> that is used by Laravel's <a href="https://github.com/laravel/framework/blob/5.0/src/Illuminate/Http/Response.php" rel="noreferrer">Response class</a>, not the base Symfony Response.</p> <p>Fortunately, you have access to the <code>headers</code> property, so you can do this:</p> <pre><code>$response = $next($request); $response-&gt;headers-&gt;set('Access-Control-Allow-Origin' , '*'); $response-&gt;headers-&gt;set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE'); $response-&gt;headers-&gt;set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application'); return $response; </code></pre>
17,540,692
What happens when a variable is assigned to zero in an `if` condition?
<p>It would be helpful if anybody can explain this.</p> <pre><code>int main() { int a=0; if(a=0) printf("a is zero\t"); else printf("a is not zero\t"); printf("Value of a is %d\n",a); return 0; } </code></pre> <p>output of this is</p> <pre><code>a is not zero Value of a is 0 </code></pre>
17,540,721
4
13
null
2013-07-09 05:35:12.12 UTC
3
2019-04-21 08:55:06.697 UTC
2018-11-15 20:35:30.563 UTC
null
1,941,755
null
2,511,451
null
1
6
c
77,048
<p><strong>The result of the assignment is the value of the expression</strong>.</p> <p>Therefore:</p> <pre><code>if (a = 0) </code></pre> <p>is the same as:</p> <pre><code>if (0) </code></pre> <p>which is the same as:</p> <pre><code>if (false) </code></pre> <p>which will force the <code>else</code> path.</p>
24,462,543
What does Unrestricted Web Access mean in iTunes Connect
<p>When you are submitting your app to Apple app store, there is a section named &quot;Rating&quot; where you should rate your content based on the chart and identify how frequently the content appears.</p> <p>There is one option called &quot;Unrestricted web access&quot; which there are no further details available about this on the Internet nor <a href="https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/FirstSteps.html#//apple_ref/doc/uid/TP40011225-CH19-SW26" rel="noreferrer">iTunes Connect Developer Guide</a>. All you can find everywhere is:</p> <blockquote> <p>Select Yes if your app allows users to navigate and view web pages, such as with an embedded browser.</p> </blockquote> <p>What does this mean? Does this mean your app can open links in embedded or Safari browser? Or does this mean your app features a browser where users can enter URLs and navigate through the web unrestricted? Because saying yes to this question will make your app 17+!</p> <p><img src="https://i.stack.imgur.com/d3IEU.png" alt="enter image description here" /> <img src="https://i.stack.imgur.com/7JWYQ.png" alt="enter image description here" /></p> <p>If this means opening links from your app (Safari or embedded), how come other apps that have embedded browser capability have 4+ rating (like Twitter and Facebook)? As it can be seen in screenshots, there is no way to select this one and not be rated 17+</p> <p><img src="https://i.stack.imgur.com/RrnTn.png" alt="enter image description here" /> <img src="https://i.stack.imgur.com/tZYNo.png" alt="enter image description here" /></p> <p><strong>Update</strong>: My app was approved with embedded WebView (TOWebViewController) with the answer &quot;No&quot; (4+). As the answer mentions, any way you let users navigate through the internet such as dynamic address bar that means it should be &quot;Yes&quot; (17+) because it is not possible to do Parental Control on your WebView.</p> <p><strong>Update 2</strong>: Since the release of iOS 9, Apple has introduced <a href="https://developer.apple.com/library/ios/documentation/SafariServices/Reference/SFSafariViewController_Ref/" rel="noreferrer">SFSafariViewController</a> which is a way of opening any URLs on the internet. This feature also has an address bar but read-only. So users can't surf the Web without parental control. It also inherits content blocking from Safari (ads, explicit content, etc.). I am highly positive by using SFSafariViewController in iOS 9 or above you still can choose 4+ as the device with parental control can't open any URLs anyway. (Let me know if I am wrong)</p> <p><strong>Update 3</strong>: Twitter now is 17+ based on the followings:</p> <p>You must be at least 17 years old to download this application.</p> <blockquote> <p>Infrequent/Mild Profanity or Crude Humor</p> <p>Frequent/Intense Mature/Suggestive Themes</p> <p>Infrequent/Mild Sexual Content and Nudity</p> </blockquote> <p><strong>Update 4</strong>: It is possible to use Twitter content inside your app without inheriting its rating (17+). My app is displaying Tweets, but since the users are verified and trusted public figures I could go down to 12+:</p> <blockquote> <p>Infrequent/Mild Sexual Content and Nudity</p> <p>Infrequent/Mild Profanity or Crude Humour</p> <p>Infrequent/Mild Mature/Suggestive Themes</p> </blockquote>
24,462,676
6
8
null
2014-06-28 00:47:11.783 UTC
22
2021-03-29 19:20:30.957 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,449,151
null
1
84
ios|uiwebview|app-store-connect|appstore-approval|sfsafariviewcontroller
37,259
<p>It means that a user of the app can access any URL. The issue is parental controls. If the parent has restricted web access an app that allows unlimited access, that is access to any site the user chooses then the parental controls are subverted.</p> <p>Once Apple provided parental controls that caused a ripple effect on the capabilities of apps and also required Apple to review all apps for parental control violations. It also means that alternate app stores could not be allowed, they could contain apps that did not properly honor parental controls. Hence:"The Walled Garden."</p>
11,850,874
Copy and Insert rows from one sheet to another by pushing a macro button
<p>I have this workbook: I need to have a macro button that my users can click that say "Click Here to Copy", then i need a code that copies rows number 5-25 of sheet titled "TC-Star Here", and i need the copied rows to be inserted (i need the pasted rows to not auto delete the ones that were there previously, so the inserted rows would have to shift the previous ones down) into another sheet named "Time Cards". The inserted rows, i need to have to code insert them starting at cell A1. So everytime the macro button is clicked, rows are copied, and inserted with the previous data unmodified/deleted.</p> <p>I have this code so far: </p> <pre><code>Sub CopyInfo() On Error GoTo Err_Execute Sheet2.Range("A1:F11").Value = Sheet1.Range("A1:F11").Value Sheet1.Range("A1:F11").Copy Sheet2.Range("A1").InsertCopiedCells Err_Execute: MsgBox "All have been copied!" End Sub </code></pre> <p>But everytime the button is clicked, it pastes the rows over the existing rows. </p> <p>Please Help.</p>
11,856,160
5
1
null
2012-08-07 17:13:21.517 UTC
1
2017-05-31 08:06:26.63 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
1,571,625
null
1
2
excel|vba
83,380
<p>Is this what you are trying?</p> <pre><code>Sub CopyInfo() On Error GoTo Err_Execute Sheet1.Range("A1:F11").Copy Sheet2.Range("A1").Rows("1:1").Insert Shift:=xlDown Err_Execute: If Err.Number = 0 Then MsgBox "All have been copied!" Else _ MsgBox Err.Description End Sub </code></pre>
22,358,071
Differences between Oracle JDK and OpenJDK
<blockquote> <p>NOTE: This question is from 2014. As of Java 11 OpenJDK and Oracle JDK are converging.</p> </blockquote> <p>Are there any crucial differences between Oracle and OpenJDK?</p> <p>For example, are the garbage collection and other JVM parameters the same?</p> <p>Does GC work differently between the two?</p>
38,685,948
13
2
null
2014-03-12 16:36:32.633 UTC
211
2021-06-26 09:21:13.763 UTC
2019-01-31 23:33:27.613 UTC
null
53,897
null
1,340,582
null
1
793
java|difference
624,564
<p>Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.</p> <p>OpenJDK and Oracle JDK are implementations of the same Java specification passed the TCK (Java Technology Certification Kit).</p> <p>Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace licensed proprietary parts / replace with more high-performance items that only work on specific OS] components without breaking the TCK compatibility.</p> <p>Many vendors implemented the Java specification and got TCK passed. For example, IBM J9, Azul Zulu, Azul Zing, and Oracle JDK.</p> <p>Almost every existing JDK is derived from OpenJDK.</p> <p>As suggested by many, licensing is a change between JDKs. </p> <p>Starting with JDK 11 accessing the long time support Oracle JDK/Java SE will now require a commercial license. You should now pay attention to which JDK you're installing as Oracle JDK without subscription could stop working. <a href="https://www.infoworld.com/article/3284164/java/oracle-now-requires-a-subscription-to-use-java-se.html" rel="noreferrer">source</a></p> <p>Ref: <em><a href="https://en.wikipedia.org/wiki/List_of_Java_virtual_machines#Proprietary_implementations" rel="noreferrer">List of Java virtual machines</a></em></p>
22,049,824
Conditionally adding data-attribute in Angular directive template
<p>I'm working on the template for a directive. If a property in the scope is set to true, <code>data-toggle="dropdown"</code> should be appended to the element. If the variable is false, this data attribute should not render as an attribute of the element.</p> <p>For example, if scope variable is true, the template should render:</p> <pre><code>&lt;span data-toggle="dropdown"&gt;&lt;/span&gt; </code></pre> <p>If false, the template should render:</p> <pre><code>&lt;span&gt;&lt;/span&gt; </code></pre> <p>What would the template look like to accomplish this? </p> <hr> <p>For example, I know that I can use <code>ng-class</code> to conditionally include a class. If I want the template to render this:</p> <pre><code>&lt;span class="dropdown"&gt;&lt;/span&gt; </code></pre> <p>Then my template would look like this:</p> <pre><code>"&lt;span ng-class="{ 'dropdown': isDropDown }"&gt;&lt;/span&gt; </code></pre> <p>If scope variable <code>isDropDown</code> is <code>false</code>, then the template will simply render:</p> <pre><code>&lt;span&gt;&lt;/span&gt; </code></pre> <p>So there's a way in a template to conditionally add a <code>class="dropdown"</code>. Is there a syntax for templates that allows me to conditionally add <code>data-toggle="dropdown"</code>?</p> <hr> <p>One of the things I've tried for the template is:</p> <pre><code>"&lt;span data-toggle="{ 'dropdown': isDropDown }"&gt;&lt;/span&gt; </code></pre> <p>My thinking with the above template is that if the scope variable <code>isDropDown</code> is true, the value of <code>data-toggle</code> will be set to "dropdown". If <code>isDropDown</code> is false, then the value of <code>data-toggle</code> would simply be an empty string <code>""</code>. That doesn't seem to work though.</p>
24,717,861
3
3
null
2014-02-26 18:17:21.483 UTC
16
2015-08-18 10:06:47.603 UTC
2014-02-26 18:54:54.207 UTC
null
11,574
null
11,574
null
1
65
angularjs|angularjs-directive
93,915
<p>I think a good way could be to use <code>ng-attr-</code> followed by the expression you want to evaluate. In your case it would be something like:</p> <pre><code>&lt;span ng-attr-data-toggle="{{ isValueTrue ? 'toggle' : 'notToggle' }}"&gt;&lt;/span&gt; </code></pre> <p>Here's a <kbd><a href="http://jsfiddle.net/gleezer/sCC72/2/">fiddle</a></kbd> with an example.</p>
62,340,791
Why does javac insert Objects.requireNonNull(this) for final fields?
<p>Consider the following class:</p> <pre><code>class Temp { private final int field = 5; int sum() { return 1 + this.field; } } </code></pre> <p>Then I compile and decompile the class:</p> <pre><code>&gt; javac --version javac 11.0.5 &gt; javac Temp.java &gt; javap -v Temp.class ... int sum(); descriptor: ()I flags: (0x0000) Code: stack=2, locals=1, args_size=1 0: iconst_1 1: aload_0 2: invokestatic #3 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object; 5: pop 6: iconst_5 7: iadd 8: ireturn </code></pre> <p>In simple words, <code>javac</code> compiles <code>sum()</code> to this:</p> <pre><code>int sum() { final int n = 1; Objects.requireNonNull(this); // &lt;--- return n + 5; } </code></pre> <p>What is <code>Objects.requireNonNull(this)</code> doing here? What's the point? Is this somehow connected to reachability?</p> <p>The Java 8 compiler is similar. It inserts <code>this.getClass()</code> instead of <code>Objects.requireNonNull(this)</code>:</p> <pre><code>int sum() { final int n = 1; this.getClass(); // &lt;--- return n + 5; } </code></pre> <p>I also tried to compile it with Eclipse. It doesn't insert <code>requireNonNull</code>:</p> <pre><code>int sum() { return 1 + 5; } </code></pre> <p>So this is javac-specific behavior.</p>
62,341,113
1
3
null
2020-06-12 08:49:49.72 UTC
6
2020-09-12 19:20:21.39 UTC
2020-06-12 12:26:24.777 UTC
null
964,243
null
706,317
null
1
38
java|java-8|javac|java-11|ecj
1,080
<p>Since the field is not only <code>final</code>, but a <em>compile-time constant</em>, it will not get accessed when being read, but the read gets replaced by the constant value itself, the <code>iconst_5</code> instruction in your case.</p> <p>But the behavior of throwing a <code>NullPointerException</code> when dereferencing <code>null</code>, which would be implied when using a <code>getfield</code> instruction, must be retained¹. So when you change the method to</p> <pre><code>int sumA() { Temp t = this; return 1 + t.field; } </code></pre> <p>Eclipse will insert an explicit null check too.</p> <p>So what we see here, is <code>javac</code> failing to recognize that in this specific case, when the reference is <code>this</code>, the non-null property is guaranteed by the JVM and hence, the explicit null check is not necessary.</p> <p>¹ see <a href="https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.11.1-200-B" rel="noreferrer">JLS §15.11.1. Field Access Using a Primary</a>:</p> <blockquote> <ul> <li><p>If the field is not <code>static</code>:</p> <ul> <li>The <em>Primary</em> expression is evaluated. If evaluation of the <em>Primary</em> expression completes abruptly, the field access expression completes abruptly for the same reason.</li> <li>If the value of the <em>Primary</em> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</li> <li>If the field is a non-blank <code>final</code>, then the result is the value of the named member field in type <code>T</code> found in the object referenced by the value of the <em>Primary</em>.</li> </ul> <p>…</p></li> </ul> </blockquote>
26,888,642
How to align query in sqldeveloper 4.0?
<p>I have query written in sqldeveloper but I don't know how to align or format the query in neat order.</p> <p>P.S: I don't know whether this question can be asked here. Kindly answer if any knows the answer here.</p>
26,889,180
5
2
null
2014-11-12 13:53:50.04 UTC
9
2018-03-29 20:54:25.73 UTC
2018-03-29 20:54:25.73 UTC
null
446,792
null
2,231,163
null
1
28
oracle-sqldeveloper
68,985
<p>I have used <kbd>Ctrl</kbd> + <kbd>f7</kbd> to format or align my query in sqldeveloper 4.7 with reference to the above comment from leo.</p>
19,469,136
Python: Function returning highest value in list without max()?
<p>I need to write a function that takes a list of numbers as the parameter and returns the largest number in the list without using <code>max()</code>.</p> <p>I've tried:</p> <pre><code>def highestNumber(l): myMax = 0 if myMax &lt; l: return myMax return l print highestNumber ([77,48,19,17,93,90]) </code></pre> <p>...and a few other things that I can't remember. I just need to understand how to loop over elements in a list.</p>
19,469,162
3
4
null
2013-10-19 17:50:48.077 UTC
1
2016-12-01 07:15:55.57 UTC
2013-10-19 17:55:35.033 UTC
null
100,297
null
2,896,986
null
1
-1
python|python-2.7
68,460
<pre><code>def highestNumber(l): myMax = l[0] for num in l: if myMax &lt; num: myMax = num return myMax print highestNumber ([77,48,19,17,93,90]) </code></pre> <p><strong>Output</strong></p> <pre><code>93 </code></pre> <p>Or You can do something like this</p> <pre><code>def highestNumber(l): return sorted(l)[-1] </code></pre> <p>Or</p> <pre><code>def highestNumber(l): l.sort() return l[-1] </code></pre>
19,722,950
Do sse instructions consume more power/energy?
<p>Very simple question, probably difficult answer:</p> <p>Does using SSE instructions for example for parallel sum/min/max/average operations consume more power than doing any other instructions (e.g. a single sum)?</p> <p>For example, on <a href="http://en.wikipedia.org/wiki/Streaming_SIMD_Extensions" rel="noreferrer">Wikipedia</a> I couldn't find any information in this respect.</p> <p>The only hint of an answer I could find is <a href="https://serverfault.com/a/196590">here</a>, but it's a little bit generic and there is no reference to any published material in this respect.</p>
19,723,106
3
4
null
2013-11-01 08:05:30.52 UTC
8
2015-05-29 14:30:40.367 UTC
2017-04-13 12:13:35.517 UTC
null
-1
null
2,436,175
null
1
16
performance|x86|sse|cpu-architecture|energy
2,678
<p>I actually did a study on this a few years ago. The answer depends on what exactly your question is:</p> <p>In today's processors, power consumption is not much determined by the type of instruction (scalar vs. SIMD), but rather everything else such as:</p> <ol> <li>Memory/cache</li> <li>Instruction decoding</li> <li>OOE, register file</li> <li>And lots others.</li> </ol> <hr> <p>So if the question is:</p> <blockquote> <p>All other things being equal: Does a SIMD instruction consume more power than a scalar instruction.</p> </blockquote> <p>For this, I dare to say yes.</p> <p>One of my graduate school projects eventually became <a href="https://stackoverflow.com/a/8391601/922184">this answer</a>: A side-by-side comparison of SSE2 (2-way SIMD) and AVX (4-way SIMD) did in fact show that AVX had a noticably higher power consumption and higher processor temperatures. (I don't remember the exact numbers though.)</p> <p>This is because the code is identical between the SSE and the AVX. Only the width of the instruction was different. And the AVX version did double the work.</p> <p>But if the question is:</p> <blockquote> <p>Will vectorizing my code to use SIMD consume more power than a scalar implementation.</p> </blockquote> <p>There's numerous factors involved here so I'll avoid a direct answer:</p> <p><strong>Factors that reduce power consumption:</strong></p> <ul> <li><p>We need to remember that the point of SIMD is to improve performance. And if you can improve performance, your app will take less time to run thus saving you power.</p></li> <li><p>Depending on the application and the implementation, SIMD will reduce the number instructions that are needed to do a certain task. That's because you're doing several operations per instruction.</p></li> </ul> <p><strong>Factors that increase power consumption:</strong></p> <ul> <li>As mentioned earlier, SIMD instructions do more work and can use more power than scalar equivalents.</li> <li>Use of SIMD introduces overhead not present in scalar code (such as shuffle and permute instructions). These also need to go through the instruction execution pipeline.</li> </ul> <hr> <p>Breaking it down:</p> <ul> <li>Fewer instructions -> less overhead for issuing and executing them -> less power</li> <li>Faster code -> run less time -> less power</li> <li>SIMD takes more power to execute -> more power</li> </ul> <p>So SIMD saves you power by making your app take less time. But while its running, it consumes more power per unit time. Who wins depends on the situation.</p> <p>From my experience, for applications that get a worthwhile speedup from SIMD (or anything other method), the former usually wins and the power consumption goes down.</p> <p>That's because run-time tends to be the dominant factor in power consumption for modern PCs (laptops, desktops, servers). The reason being that most of the power consumption is not in the CPU, but rather in everything else: motherboard, ram, hard drives, monitors, idle video cards, etc... most of which have a relatively fixed power draw.</p> <p>For my computer, just keeping it on (idle) already draws more than half of what it can draw under an all-core SIMD load such as prime95 or Linpack. So if I can make an app 2x faster by means of SIMD/parallelization, I've almost certainly saved power.</p>
19,302,273
How do you know if Tomcat Server is installed on your PC
<p>I am using Windows 7 OS. I just installed jaspersoft server which installed Apache Tomcat and mysql as a bundle along with it.</p> <p>I go to <code>http://localhost:8080</code> and theres a message that says webpage is not available.</p> <p>I am a beginner, and I would like to know if Tomcat is first installed on my computer. Can you tell me how I can do that ? ( I would also like to know if it has to be started and on what port it was installed.)</p> <p><strong>UPDATE</strong></p> <p>Heres something I did . i am really confused now . I found the location of the tomcat server. I found the server.xml file. The port in the server.xml file was listed as 8005. I also found start.bat which I ran. I now see that <code>http://localhost:8080</code> works but <code>http://localhost:8005</code> doesnt . Would you know why ?? The port 8005 should work because thats what was listed in the server.xml </p>
19,303,253
6
7
null
2013-10-10 17:23:00.443 UTC
4
2018-10-08 09:42:30.073 UTC
2013-10-10 18:12:22.833 UTC
null
1,408,809
null
1,408,809
null
1
12
java|windows|tomcat|jasperserver
129,219
<p>The port 8005 is used as service port. <a href="http://wiki.apache.org/tomcat/FAQ/Security#Q2" rel="noreferrer">You can send a shutdown command (a configurable password)</a> to that port. It will not "speak" HTTP, so you cannot use your browser to connect.</p> <p>The default port for delivering web-content is 8080.</p> <p>But there may be other applications listen to that port. So your tomcat may not start, if the port is not available. </p> <p>You asked "<em>How do you know, if tomcat server is installed on your PC?</em>". The answer to that question is: <strong>You can't</strong></p> <p>You can't determine, if it is installed, because it may be only extracted from a ZIP archive or packaged within another application (Like JBoss AS (I think)).</p>
17,317,862
Is there a left()-function for Java strings?
<p>I have an string str of unknown length (but not null) and a given maximum length len, this has to fit in. All I want to do, is to cut the string at len.</p> <p>I know that I can use </p> <pre><code>str.substring(0, Math.min(len, str.length())); </code></pre> <p>but this does not come handy, if I try to write stacked code like this</p> <pre><code>code = str.replace(" ", "").left(len) </code></pre> <p>I know that I can write my own function but I would prefer an existing solution. Is there an existing left()-function in Java?</p>
17,317,927
7
2
null
2013-06-26 10:41:09.117 UTC
2
2022-03-17 14:49:03.757 UTC
null
null
null
null
2,523,663
null
1
20
java|string
67,709
<p>There's nothing built in, but Apache commons has the StringUtils class which has a suitable <a href="http://commons.apache.org/proper/commons-lang//apidocs/org/apache/commons/lang3/StringUtils.html#left%28java.lang.String,%20int%29" rel="noreferrer">left</a> function for you. </p>