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
25,293,045
count number of rows in a data frame in R based on group
<p>I have a data frame in <code>R</code> like this:</p> <pre><code> ID MONTH-YEAR VALUE 110 JAN. 2012 1000 111 JAN. 2012 2000 . . . . 121 FEB. 2012 3000 131 FEB. 2012 4000 . . . . </code></pre> <p>So, for each month of each year there are <code>n</code> rows and they can be in any order(mean they all are not in continuity and are at breaks). I want to calculate how many rows are there for each <code>MONTH-YEAR</code> i.e. how many rows are there for JAN. 2012, how many for FEB. 2012 and so on. Something like this:</p> <pre><code> MONTH-YEAR NUMBER OF ROWS JAN. 2012 10 FEB. 2012 13 MAR. 2012 6 APR. 2012 9 </code></pre> <p>I tried to do this:</p> <pre><code>n_row &lt;- nrow(dat1_frame %.% group_by(MONTH-YEAR)) </code></pre> <p>but it does not produce the desired output.How can I do that?</p>
25,293,526
8
6
null
2014-08-13 17:59:02.357 UTC
25
2017-10-04 08:00:17.893 UTC
2014-12-15 10:43:12.353 UTC
null
1,270,695
null
3,926,499
null
1
59
r|dataframe|rowcount
356,132
<p>Here's an example that shows how <code>table(.)</code> (or, more closely matching your desired output, <code>data.frame(table(.))</code> does what it sounds like you are asking for.</p> <p>Note also how to share reproducible sample data in a way that others can copy and paste into their session.</p> <p>Here's the (reproducible) sample data:</p> <pre><code>mydf &lt;- structure(list(ID = c(110L, 111L, 121L, 131L, 141L), MONTH.YEAR = c("JAN. 2012", "JAN. 2012", "FEB. 2012", "FEB. 2012", "MAR. 2012"), VALUE = c(1000L, 2000L, 3000L, 4000L, 5000L)), .Names = c("ID", "MONTH.YEAR", "VALUE"), class = "data.frame", row.names = c(NA, -5L)) mydf # ID MONTH.YEAR VALUE # 1 110 JAN. 2012 1000 # 2 111 JAN. 2012 2000 # 3 121 FEB. 2012 3000 # 4 131 FEB. 2012 4000 # 5 141 MAR. 2012 5000 </code></pre> <p>Here's the calculation of the number of rows per group, in two output display formats:</p> <pre><code>table(mydf$MONTH.YEAR) # # FEB. 2012 JAN. 2012 MAR. 2012 # 2 2 1 data.frame(table(mydf$MONTH.YEAR)) # Var1 Freq # 1 FEB. 2012 2 # 2 JAN. 2012 2 # 3 MAR. 2012 1 </code></pre>
46,578,584
how to securely store encryption keys in android?
<p>I want to know how to securely store <strong>encryption key</strong> in Android? What is the best scenario to protect encryption and secrete keys? </p>
50,389,146
5
11
null
2017-10-05 05:41:15.683 UTC
15
2020-06-04 13:20:54.807 UTC
2018-05-23 13:47:08.983 UTC
null
3,328,736
user6693721
null
null
1
38
java|android|security|encryption|keystore
20,774
<p>From your comments, you need to encrypt data using a local key for current Android versions and the old ones</p> <p><a href="https://developer.android.com/training/articles/keystore" rel="noreferrer">Android Keystore</a> is designed to generate and protect your keys. But it is not available for API level below 18 and it has some limitations until API level 23. </p> <p>You will need a random symmetric encryption key, for example AES. The AES key is used to encrypt and decrypt you data. I'm going to summarize your options to generate and store it safely depending on Android API level. </p> <ul> <li><p><strong>API Level &lt; 18: Android Keystore not present</strong>. Request a password to the user, derive an encryption key from the password, The drawback is that you need to prompt for the password when application starts. The encryption key it is not stored in the device. It is calculated each time when the application is started using the password </p></li> <li><p><strong>API Level >=18 &lt;23: Android Keystore available without AES support</strong>. Generate a random AES key using the default cryptographic provider (not using AndroidKeystore). Generate a RSA key pair into Android Keystore, and encrypt the AES key using RSA public key. Store encrypted AES key into Android SharedPreferences. When application starts, decrypt the AES key using RSA private key</p></li> <li><p><strong>API Level >=23: Android Keystore available with AES support</strong>. Generate a random AES key using into Android Keystore. You can use it directly.</p></li> </ul> <p>To encrypt to can use <code>AES/CBC/PKCS7Padding</code> algorithm. It requires also a random initialization vector (IV) to encrypt your data, but it can be public.</p> <p>Alternatives: </p> <ul> <li><p><strong>API level >14: Android Key Chain</strong>: KeyChain is a system-wide credential storage. You can install certificates with private keys that can be used by applications. Use a preinstalled key to encrypt/decrypt your AES key as shown in the second case above.</p></li> <li><p><strong>External token</strong>: The protected keys are not stored in the device. You can use an external token containing a private/public key pair that allows you to encrypt the AES key. The token can be accesed using bluetooth or NFC</p></li> </ul>
56,859,604
Swagger not loading - Failed to load API definition: Fetch error undefined
<p>Trying to setup swagger in conjunction with a web application hosted on IIS express. API is built using ASP Net Core. I have followed the instructions prescribed on the relevant microsoft help page regarding Swashbuckle and ASP.NET Core.</p> <p>Thus far I have got the swagger page to load up and can see that the SwaggerDoc that I have defined is loading, however no API's are present. Currently am getting the following error: </p> <blockquote> <p>"Fetch error undefined ./swagger/v1/swagger.json"</p> </blockquote> <pre><code>public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // services.AddDbContext&lt;TodoContext&gt;(opt =&gt; // opt.UseInMemoryDatabase("TodoList")); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c =&gt; { c.SwaggerDoc("v1", new Info { Title = "API WSVAP (WebSmartView)", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c =&gt; { c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; }); app.UseMvc(); } } </code></pre>
56,959,143
32
7
null
2019-07-02 20:24:58.957 UTC
18
2022-08-10 08:34:41.08 UTC
2021-02-19 15:31:59.873 UTC
null
113,116
null
9,058,993
null
1
87
c#|asp.net-mvc|swagger-ui|swashbuckle
159,603
<p>So after a lot of troubleshooting it came down to basically two things, but I feel that in general this could be helpful to someone else in the future so I'm posting an answer.</p> <p>First- if ever your stuck with the aforementioned error the best way to actually see whats going on is by adding the following line to your Configure() method</p> <pre><code>app.UseDeveloperExceptionPage(); </code></pre> <p>Now if you navigate to the 'swagger/v1/swagger.json' page you should see some more information which will point you in useful direction.</p> <p>Second- now for me the error was something along the lines of</p> <blockquote> <p>'Multiple operations with path 'some_path' and method 'GET' '</p> </blockquote> <p>However these API were located inside of dependency libraries so I was unable to apply a solution at the point of definition. As a workaround I found that adding the following line to your ConfigureServices() method resolved the issue</p> <pre><code>services.AddSwaggerGen(c =&gt; { c.SwaggerDoc(&quot;v1&quot;, new Info { Title = &quot;API WSVAP (WebSmartView)&quot;, Version = &quot;v1&quot; }); c.ResolveConflictingActions(apiDescriptions =&gt; apiDescriptions.First()); //This line }); </code></pre> <p>Finally- After all that I was able to generate a JSON file but still I wasn't able to pull up the UI. In order to get this working I had to alter the end point in Configure()</p> <pre><code>app.UseSwaggerUI(c =&gt; { c.SwaggerEndpoint(&quot;./v1/swagger.json&quot;, &quot;My API V1&quot;); //originally &quot;./swagger/v1/swagger.json&quot; }); </code></pre> <p>I'm not sure why this was necessary, although it may be worth noting the web application's virtual directory is hosted on IIS which might be having an effect.</p> <p>NOTE: Navigating to swagger/v1/swagger.json will give you more details, for me it was causing issue due to undecorated action. This information is mentioned in comment by @MarkD</p> <p>Hope this helps someone in the future.</p>
13,488,957
Interpolate from one color to another
<p>I am trying to get an interpolation of one color to another shade of the same color. (for eg: sky blue to dark blue and then back).</p> <p>I stumbled upon <a href="https://stackoverflow.com/questions/5860100/how-to-interpolate-a-color-sequence">some code</a> that could be used if the range was from 0-255 or 0-1. However, in my case, I have the RGB codes for Color1 and Color2, and want the rotation to occur.</p> <p>Color 1: 151,206,255<br/> Color 2: 114,127,157</p> <p>Any ideas how to go about this?</p>
13,489,050
7
11
null
2012-11-21 08:17:33.133 UTC
13
2020-10-29 16:23:10.077 UTC
2017-05-23 12:25:23.57 UTC
null
-1
null
1,240,679
null
1
24
c++|openframeworks
57,696
<p>I suggest you convert RGB to HSV, then adjust its components, then convert back to RGB.</p> <p>Wikipedia has <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" rel="noreferrer">an article</a> about it, and it's been discussed here before:</p> <p><a href="https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion">HSL to RGB color conversion</a></p> <p><a href="https://stackoverflow.com/questions/3018313/algorithm-to-convert-rgb-to-hsv-and-hsv-to-rgb">Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both</a></p> <p>Also many frameworks have conversion functions, for example Qt has <a href="http://qt-project.org/doc/qt-5.0/qtgui/qcolor.html" rel="noreferrer">QColor class</a>.</p> <hr> <p>But the question was about the actual interpolation... here's a trivial interpolation function:</p> <pre><code>// 0 &lt;= stepNumber &lt;= lastStepNumber int interpolate(int startValue, int endValue, int stepNumber, int lastStepNumber) { return (endValue - startValue) * stepNumber / lastStepNumber + startValue; } </code></pre> <p>So call that for all color components you want to interpolate, in a loop. With RBG interpolation, you need to interpolate every component, in some other color space you may need to interpolate just one.</p>
13,642,171
Elastic Beanstalk Ruby/Rails need to install git so bundle install works.. but is not
<p>I'm having an issue deploying our rails app.. I created a hook like the example on the AWS blog howto <a href="http://ruby.awsblog.com/post/Tx2AK2MFX0QHRIO/Deploying-Ruby-Applications-to-AWS-Elastic-Beanstalk-with-Git" rel="noreferrer">http://ruby.awsblog.com/post/Tx2AK2MFX0QHRIO/Deploying-Ruby-Applications-to-AWS-Elastic-Beanstalk-with-Git</a> like:</p> <pre><code>packages: yum: git: [] </code></pre> <p>even I run a bundle package to create vendor/cache to have all the gems there... and still getting: git://github.com/refinery/refinerycms-search.git (at 2-0-stable) is not checked out. Please run <code>bundle install</code> (Bundler::GitError)</p> <p>any help will be nice, we trying to move all our apps to EB. but seens that git does not install or something is going on.. I need git on the EB ec2 instance it creates.</p> <p>StackTrace:</p> <pre><code>Error message: git://github.com/refinery/refinerycms-search.git (at 2-0-stable) is not checked out. Please run `bundle install` (Bundler::GitError) Exception class: PhusionPassenger::UnknownError Application root: /var/app/current Backtrace: # File Line Location 0 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/source.rb 801 in `rescue in load_spec_files' 1 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/source.rb 799 in `load_spec_files' 2 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/source.rb 381 in `local_specs' 3 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/source.rb 774 in `specs' 4 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/definition.rb 174 in `block in resolve' 5 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/definition.rb 172 in `each' 6 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/definition.rb 172 in `resolve' 7 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/definition.rb 113 in `specs' 8 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/definition.rb 158 in `specs_for' 9 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/definition.rb 147 in `requested_specs' 10 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/environment.rb 23 in `requested_specs' 11 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/runtime.rb 11 in `setup' 12 /usr/share/ruby/1.9/gems/1.9.1/gems/bundler-1.2.1/lib/bundler.rb 116 in `setup' 13 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/utils.rb 326 in `prepare_app_process' 14 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/rack/application_spawner.rb 156 in `block in initialize_server' 15 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/utils.rb 563 in `report_app_init_status' 16 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/rack/application_spawner.rb 154 in `initialize_server' 17 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6- 1002/support/lib/phusion_passenger/abstract_server.rb 204 in `start_synchronously' 18 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/abstract_server.rb 180 in `start' 19 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/rack/application_spawner.rb 129 in `start' 20 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/spawn_manager_orig.rb 253 in `block (2 levels) in spawn_rack_application' 21 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/abstract_server_collection.rb 132 in `lookup_or_add' 22 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/spawn_manager_orig.rb 246 in `block in spawn_rack_application' 23 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/abstract_server_collection.rb 82 in `block in synchronize' 24 prelude&gt; 10:in `synchronize' 25 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/abstract_server_collection.rb 79 in `synchronize' 26 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/spawn_manager_orig.rb 244 in `spawn_rack_application' 27 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/spawn_manager_orig.rb 137 in `spawn_application' 28 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/spawn_manager.rb 16 in `spawn_application_with_env' 29 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/spawn_manager_orig.rb 275 in `handle_spawn_application' 30 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/abstract_server.rb 357 in `server_main_loop' 31 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/lib/phusion_passenger/abstract_server.rb 206 in `start_synchronously' 32 /var/lib/passenger-standalone/3.0.17-x86_64-ruby1.9.3-linux-gcc4.4.6-1002/support/helper-scripts/passenger-spawn-server </code></pre> <p>UPDATE more info: I decided to log into the instance with ec2-user and notice that git is installed the gems I need ARE installed so far I can see.. when I do bundle list they all show up even the one that the error is complaining about.. I do notice that when I do a general gem list then it DOES not show up... but it should be using the bundle one.</p>
13,657,473
5
6
null
2012-11-30 09:20:12.917 UTC
15
2017-09-14 16:33:14.283 UTC
2012-11-30 11:13:46.413 UTC
null
3,314,723
null
3,314,723
null
1
42
ruby-on-rails|ruby|amazon-web-services|amazon-ec2|amazon-elastic-beanstalk
19,283
<p>(<em>Note that the following workaround should only be used if you <strong>must</strong> use Git sources for dependencies. It is recommended not to install dependencies from external Git repositories if it can be avoided. See below for details on why that is.</em>)</p> <p>When using Git backed libraries in a Gemfile with Passenger, you <em>must</em> disable shared gems in an installation (in addition to installing Git in the hook you listed above). You can do this by setting the <code>BUNDLE_DISABLE_SHARED_GEMS</code> Bundler environment variable in your existing <code>.ebextensions/ruby.config</code> file like so:</p> <pre><code>option_settings: - option_name: BUNDLE_DISABLE_SHARED_GEMS value: "1" - option_name: BUNDLE_PATH value: "vendor/bundle" packages: yum: git: [] </code></pre> <p>Disabling shared gems will force all dependencies to be vendored into your application in <code>vendor/bundle</code> as specified by the <code>BUNDLE_PATH</code> variable.</p> <p>Note that, whenever possible, you should avoid installing public libraries from Git sources with your application. Using Git for library locations introduces another point of failure for a deployment install, since the Git repository may be temporarily unavailable or even permanently moved. Also keep in mind that forcing vendored installs in a deployment will cause your Elastic Beanstalk deployments to be much slower on subsequent deploys of an app with the same dependencies. This is because the libraries will be re-installed at each deploy instead of taking advantage of the system-wide installation that Elastic Beanstalk has Bundler perform by default.</p> <p>In short, if there is an official RubyGem release of the library in question, you should use that version instead; and if not, you should suggest to the library author that an official RubyGem release be made available.</p> <p>FYI a similar question about this Git problem with regular Passenger/Rails deployments was previously asked: <a href="https://stackoverflow.com/questions/3605235/rails-3-passenger-cant-find-git-gems-installed-by-bundler">Rails 3: Passenger can&#39;t find git gems installed by bundler</a></p>
13,285,924
How to define constraints on multiple generics parameters
<p>I am wondering why I cant get such simple thing like this on google. This code is not compilable. How can I do this?</p> <pre><code>public class TestStep&lt;StartEvent, CompletedEvent&gt; where StartEvent : MyBase1, MyInterface1, new() &amp;&amp; where CompletedEvent : MyBase2, MyInterface2, new() { } </code></pre> <p>Please help.</p>
13,285,975
1
1
null
2012-11-08 09:16:09.683 UTC
2
2018-03-06 23:02:55.72 UTC
2016-09-09 04:51:18.823 UTC
null
177,018
null
1,134,237
null
1
42
c#|generics
17,103
<p>Try without the "&amp;&amp;"</p> <pre><code>public class TestStep&lt;StartEvent, CompletedEvent&gt; where StartEvent : MyBase1, MyInterface1, new() where CompletedEvent : MyBase2, MyInterface2, new() { } </code></pre>
13,779,338
Use results from one sql query in another where statement (subquery?)
<p>I see many similar questions but they're either so complex I can't understand them, or they don't seem to be asking the same thing.</p> <p>It's simple: I have two columns: users (dmid) and downloads (dfid).</p> <ol> <li><p>Select all users who downloaded a specific file:</p> <pre><code>SELECT DISTINCT dmid FROM downloads_downloads where dfid = "7024" </code></pre></li> <li><p>Using the users above, find all the files they all downloaded:</p> <pre><code>SELECT dfid from downloads_downloads WHERE dmid = {user ids from #1 above} </code></pre></li> <li><p>Count and order the dfid results , so we can see how many downloads each file received:</p> <pre><code>dfid dl_count_field ---- -------------- 18 103 3 77 903 66 </code></pre></li> </ol> <p><strong>My attempt at answering.</strong></p> <p>This seems close, but MySql bogs down and doesn't respond even after 30 seconds--I restart Apache eventually. And I do not now how to structure the count and order by without getting syntax errors because of the complex statement--and it may not even be the right statement.</p> <pre><code>SELECT dfid from downloads_downloads WHERE dmid IN ( SELECT DISTINCT dmid FROM `downloads_downloads` where dfid = "7024") </code></pre>
13,779,394
1
1
null
2012-12-08 16:23:07.913 UTC
14
2014-10-28 09:17:56.673 UTC
2014-10-28 09:17:56.673 UTC
null
3,187,556
null
710,624
null
1
51
mysql|sql|subquery
115,664
<pre><code>SELECT dfid,count(*) from downloads_downloads WHERE dmid IN ( SELECT dmid FROM downloads_downloads where dfid = "7024" ) group by dfid </code></pre> <p>or using a self join</p> <pre><code>select t1.dfid,count(*) from downloads_downloads t1 inner join downloads_downloads t2 on t1.dmid = t2.dmid where t2.dfid = "7024" </code></pre> <p>if this takes too long then you will probably need to post an explain plan (google it!)</p>
13,604,137
Definition of int64_t
<p>I am new to C/C++, so I have a couple of questions about a basic type: </p> <p>a) Can you explain to me the difference between <code>int64_t</code> and <code>long</code> (<code>long int</code>)? In my understanding, both are 64 bit integers. Is there any reason to choose one over the other?</p> <p>b) I tried to look up the definition of <code>int64_t</code> on the web, without much success. Is there an authoritative source I need to consult for such questions?</p> <p>c) For code using <code>int64_t</code> to compile, I am currently including <code>&lt;iostream&gt;</code>, which doesn't make much sense to me. Are there other includes that provide a declaration of <code>int64_t</code>?</p>
13,604,190
5
6
null
2012-11-28 11:35:13.59 UTC
25
2022-08-03 07:45:45.243 UTC
null
null
null
null
626,537
null
1
91
c++|c|integer|long-integer
159,018
<blockquote> <p>a) Can you explain to me the difference between <code>int64_t</code> and <code>long</code> (<code>long int</code>)? In my understanding, both are 64 bit integers. Is there any reason to choose one over the other?</p> </blockquote> <p>The former is a signed integer type with <em>exactly</em> 64 bits. The latter is a signed integer type with <em>at least</em> 32 bits.</p> <blockquote> <p>b) I tried to look up the definition of <code>int64_t</code> on the web, without much success. Is there an authoritative source I need to consult for such questions?</p> </blockquote> <p><a href="http://cppreference.com" rel="noreferrer">http://cppreference.com</a> covers this here: <a href="http://en.cppreference.com/w/cpp/types/integer" rel="noreferrer">http://en.cppreference.com/w/cpp/types/integer</a>. The authoritative source, however, is the <a href="https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents">C++ standard</a> (this particular bit can be found in §18.4 Integer types [cstdint]).</p> <blockquote> <p>c) For code using <code>int64_t</code> to compile, I am including <code>&lt;iostream&gt;</code>, which doesn't make much sense to me. Are there other includes that provide a declaration of <code>int64_t</code>?</p> </blockquote> <p>It is declared in <code>&lt;cstdint&gt;</code> or <code>&lt;cinttypes&gt;</code> (under namespace <code>std</code>), or in <code>&lt;stdint.h&gt;</code> or <code>&lt;inttypes.h&gt;</code> (in the global namespace).</p>
13,409,912
How to create a horizontal loading progress bar?
<p>When uninstalling an android application, or do some configuration, there will show such a horizontal progress bar, like following picture:</p> <p><img src="https://i.stack.imgur.com/o31Op.png" alt="progress bar"></p> <p>It's not the same style like <code>@android:style/Widget.ProgressBar.Horizontal</code>.</p> <p>How to use it in my own application?</p>
13,409,967
6
1
null
2012-11-16 03:24:50.837 UTC
12
2022-04-07 09:10:40.86 UTC
null
null
null
null
342,235
null
1
96
android|android-progressbar
166,826
<p>It is <code>Widget.ProgressBar.Horizontal</code> on my phone, if I set <code>android:indeterminate="true"</code></p>
20,517,723
How to make shark/spark clear the cache?
<p>when i run my shark queries, the memory gets hoarded in the main memory This is my top command result.</p> <hr> <p>Mem: 74237344k total, 70080492k used, 4156852k free, 399544k buffers Swap: 4194288k total, 480k used, 4193808k free, 65965904k cached</p> <hr> <p>this doesn't change even if i kill/stop shark,spark, hadoop processes. Right now, the only way to clear the cache is to reboot the machine.</p> <p>has anyone faced this issue before? is it some configuration problem or a known issue in spark/shark?</p>
44,075,950
5
2
null
2013-12-11 11:19:42.153 UTC
10
2021-11-25 16:25:10.67 UTC
2014-02-15 14:49:21.783 UTC
null
354,577
null
783,670
null
1
27
hadoop|hive|apache-spark|shark-sql
70,091
<p>To remove all cached data:</p> <pre><code>sqlContext.clearCache() </code></pre> <p>Source: <a href="https://spark.apache.org/docs/2.0.1/api/java/org/apache/spark/sql/SQLContext.html" rel="noreferrer">https://spark.apache.org/docs/2.0.1/api/java/org/apache/spark/sql/SQLContext.html</a></p> <p>If you want to remove an specific Dataframe from cache:</p> <pre><code>df.unpersist() </code></pre>
20,857,773
Create dynamic variable name
<p>Can we create dynamic variable in C#?</p> <p>I know my below code is threw error and very poor coding. But this code have small logic like create dynamic variable </p> <pre><code>var name=0; for(i=0;i&lt;10;i++)// 10 means grid length { name+i=i; } var xx1=name1; var xx2=name2; var xx3=name3; </code></pre> <blockquote> <p>Is it possible in c#? Create dynamic variable in c#? and change the variable name in c#? and concatenate the variable name in c#(<em>like we can concatenate any control id or name</em>)...</p> </blockquote> <p><strong>Why I need the dynamic variable name (scenario):</strong></p> <pre><code>var variablename="" var variablename0=No; var variablename1=Yes; var variablename2=No; </code></pre> <p>. . .</p> <p>I have a <code>gridview</code> with multiple rows. And I need assign server side variable to every row. So I need set of variables in server side. the only I can set <code>Text=&lt;%# variablename+rowCount%&gt;</code> for every template field.</p> <p>This <code>rowCount</code> means every grid row index. </p> <p>If the grid has 2 rows, Then <code>rowCount</code> values are 0,1,2</p> <p>Now I need to change the <code>variablename</code> to <code>variablename0,variablename1,variablename2</code> dynamically for separate row. </p>
20,857,916
5
3
null
2013-12-31 12:58:22.56 UTC
14
2020-09-19 08:49:19.687 UTC
2020-09-19 08:49:19.687 UTC
null
2,141,621
null
2,218,635
null
1
52
c#
161,904
<p>C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on <a href="http://msdn.microsoft.com/en-us/library/xfhwa508%28v=vs.110%29.aspx">C# dictionaries here</a>.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuickTest { class Program { static void Main(string[] args) { Dictionary&lt;string, int&gt; names = new Dictionary&lt;string,int&gt;(); for (int i = 0; i &lt; 10; i++) { names.Add(String.Format("name{0}", i.ToString()), i); } var xx1 = names["name1"]; var xx2 = names["name2"]; var xx3 = names["name3"]; } } } </code></pre>
9,126,567
Method not found using DigestUtils in Android
<p>I am trying to use the library <a href="http://commons.apache.org/codec/apidocs/org/apache/commons/codec/digest/DigestUtils.html">DigestUtils</a> in Android 2.3.1 using JDK 1.6, however I get the following error when executing the app:</p> <p><code>Could not find method org.apache.commons.codec.binary.Hex.encodeHexString, referenced from method org.apache.commons.codec.digest.DigestUtils.shaHex</code></p> <p>Here you have the stacktrace:</p> <pre><code>02-03 10:25:45.153: I/dalvikvm(1230): Could not find method org.apache.commons.codec.binary.Hex.encodeHexString, referenced from method org.apache.commons.codec.digest.DigestUtils.shaHex 02-03 10:25:45.153: W/dalvikvm(1230): VFY: unable to resolve static method 329: Lorg/apache/commons/codec/binary/Hex;.encodeHexString ([B)Ljava/lang/String; 02-03 10:25:45.153: D/dalvikvm(1230): VFY: replacing opcode 0x71 at 0x0004 02-03 10:25:45.153: D/dalvikvm(1230): VFY: dead code 0x0007-0008 in Lorg/apache/commons/codec/digest/DigestUtils;.shaHex ([B)Ljava/lang/String; 02-03 10:25:45.163: D/AndroidRuntime(1230): Shutting down VM 02-03 10:25:45.163: W/dalvikvm(1230): threadid=1: thread exiting with uncaught exception (group=0x40015560) 02-03 10:25:45.173: E/AndroidRuntime(1230): FATAL EXCEPTION: main 02-03 10:25:45.173: E/AndroidRuntime(1230): java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Hex.encodeHexString 02-03 10:25:45.173: E/AndroidRuntime(1230): at org.apache.commons.codec.digest.DigestUtils.md5Hex(DigestUtils.java:226) 02-03 10:25:45.173: E/AndroidRuntime(1230): at com.caumons.trainingdininghall.ConnectionProfileActivity.onCreate(ConnectionProfileActivity.java:20) 02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586) 02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638) 02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928) 02-03 10:25:45.173: E/AndroidRuntime(1230): at android.os.Handler.dispatchMessage(Handler.java:99) 02-03 10:25:45.173: E/AndroidRuntime(1230): at android.os.Looper.loop(Looper.java:123) 02-03 10:25:45.173: E/AndroidRuntime(1230): at android.app.ActivityThread.main(ActivityThread.java:3647) 02-03 10:25:45.173: E/AndroidRuntime(1230): at java.lang.reflect.Method.invokeNative(Native Method) 02-03 10:25:45.173: E/AndroidRuntime(1230): at java.lang.reflect.Method.invoke(Method.java:507) 02-03 10:25:45.173: E/AndroidRuntime(1230): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 02-03 10:25:45.173: E/AndroidRuntime(1230): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 02-03 10:25:45.173: E/AndroidRuntime(1230): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>The line of code which causes the exception is:</p> <p><code>String hash = DigestUtils.shaHex("textToHash");</code></p> <p>I have executed the same code in a Java class outside Android and it works! So, I do not know why when working with Android it does not work... I put the libraty inside a new libs/ folder in my app and updated the BuildPath to use it. If I try to use md5 instead of sha1 I get the same exception. Any help would be appreciated! Thank you.</p> <p><strong>UPDATE:</strong></p> <p>As this is a very active question, I've changed the accepted answer in favour of @DA25, as his solution is straightforward and the high number of upvotes prove that it works.</p>
9,284,092
8
2
null
2012-02-03 09:43:11.427 UTC
31
2019-10-02 12:25:24.06 UTC
2013-08-28 02:24:38.883 UTC
null
955,619
null
955,619
null
1
84
android|apache|encryption|sha|digest
43,805
<p>I ran into the same issue trying to use DigestUtils in my Android app. This was the best answer I could find by searching, but I was reluctant to rebuild the .jar file with the namespace changed. After spending some time on this issue, I found an easier way to solve the problem for my case. The problem statement for my code was </p> <pre><code>String s = DigestUtils.md5Hex(data); </code></pre> <p>Replace this statement with the following and it will work:</p> <pre><code>String s = new String(Hex.encodeHex(DigestUtils.md5(data))); </code></pre> <p>Similarly, for shaHex exampl, you can change it to</p> <pre><code>String hash = new String(Hex.encodeHex(DigestUtils.sha("textToHash"))); </code></pre> <p>This works because even though Android does not have encodeHexString(), it does have encodeHex(). Hope this would help others who run into the same issue.</p>
29,688,115
How do I check if an environment variable is set in cmake
<p>I set an environment variable in my bash profile, so I can see it in the terminal just fine . .</p> <blockquote> <p>blah/builds$ echo $THING</p> <p>thingy</p> </blockquote> <p>How do I display it in a cmake message and check if it is set? I have tried the following, but it just displays thing as blank and skips the body of the if statement</p> <pre><code>message(&quot;THING:&quot; $ENV{THING}) if(DEFINED ENV{THING}) message(STATUS &quot;THING environment variable defined&quot;) # some more commands endif() </code></pre>
32,904,761
5
3
null
2015-04-17 00:15:52.07 UTC
4
2019-07-31 11:03:47.383 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
276,193
null
1
41
bash|cmake|environment-variables
43,858
<p>You CMake code is correct. The problem is most likely that you only <em>set</em> the environment variable in your shell but did not <em>export</em> it. Run the following before invoking <code>cmake</code>:</p> <pre><code>export THING </code></pre>
16,097,724
Warning: Your Magento folder does not have sufficient write permissions
<p>I am new to Magento, I am trying to install a theme via magento connect manager, I copy and paste the extension key then click install and then proceed.I get error 'Warning: Your Magento folder does not have sufficient write permissions.'</p> <p>please give some solution .Any help would be highly appreciated. </p>
16,097,821
7
1
null
2013-04-19 05:23:04.253 UTC
8
2018-10-17 21:34:04.253 UTC
null
null
null
null
1,829,010
null
1
16
magento
44,749
<p>go to Magento home directory and just give permissions for your webroot. </p> <pre><code>e.g. (in ubuntu) : sudo chown -R www-data . </code></pre> <p>You could also change the permissions </p> <pre><code>chmod 777 -R downloader/* </code></pre> <p>I hope it helps.</p> <p>[EDIT]</p> <p>How about in your magento directory (use <code>sudo</code> for below commands if required.):</p> <pre><code>find . -type d -exec chmod 775 {} \; find . -type f -exec chmod 664 {} \; </code></pre> <p>For the normal operation or installation of a Magento store, only 2 folders need to be writable:</p> <pre><code>/media - for web accessible files, such as product images /var - for temporary (cache, session) and import/export files </code></pre> <p><a href="http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/magento_filesystem_permissions" rel="noreferrer">Source here</a></p>
16,352,131
Apple Push Notifications in Bulk
<p>I have an app that involves sending Apple Push Notifications to ~1M users periodically. The setup for doing so has been built and tested for small numbers of notifications. Since there is no way I can test sending at that scale, I am interested in knowing whether there are any gotchas in sending bulk push notifications. I have scripts written in Python that open a single connection to the push server and send all notifications over that connection. Apple recommends keeping it open for as long as possible. But I have also seen that the connection terminates and you need to reestablish it. </p> <p>All in all, it is disconcerting that successful sends are not acknowledged, only erroneous ones are flagged. From a programmer's standpoint instead of simply checking one thing "if (success)" you now need to watch for numerous things that could go wrong.</p> <p>My question is: What are the typical set of errors that you need to watch out for to make sure your messages don't silently disappear into oblivion? The connection closing is an easy one. Are there others?</p>
16,363,554
2
3
null
2013-05-03 05:22:44.273 UTC
10
2015-01-09 11:11:40.763 UTC
2013-05-03 15:11:01.183 UTC
null
344,199
null
344,199
null
1
26
iphone|ios|push-notification|apple-push-notifications
12,494
<p>I completely agree with you that this API is very frustrating, and if they would have sent a response for each notification it would have been much easier to implement.</p> <p>That said, here's what Apple say you should do (from <a href="https://developer.apple.com/library/ios/#technotes/tn2265/_index.html" rel="noreferrer">Technical Note</a>) :</p> <blockquote> <p>Push Notification Throughput and Error Checking</p> <p>There are no caps or batch size limits for using APNs. The iOS 6.1 press release stated that APNs has sent over 4 trillion push notifications since it was established. It was announced at WWDC 2012 that APNs is sending 7 billion notifications daily.</p> <p>If you're seeing throughput lower than 9,000 notifications per second, your server might benefit from improved error handling logic.</p> <p>Here's how to check for errors when using the enhanced binary interface. Keep writing until a write fails. If the stream is ready for writing again, resend the notification and keep going. If the stream isn't ready for writing, see if the stream is available for reading.</p> <p>If it is, read everything available from the stream. If you get zero bytes back, the connection was closed because of an error such as an invalid command byte or other parsing error. If you get six bytes back, that's an error response that you can check for the response code and the ID of the notification that caused the error. You'll need to send every notification following that one again.</p> <p>Once everything has been sent, do one last check for an error response.</p> <p>It can take a while for the dropped connection to make its way from APNs back to your server just because of normal latency. It's possible to send over 500 notifications before a write fails because of the connection being dropped. Around 1,700 notifications writes can fail just because the pipe is full, so just retry in that case once the stream is ready for writing again.</p> <p>Now, here's where the tradeoffs get interesting. You can check for an error response after every write, and you'll catch the error right away. But this causes a huge increase in the time it takes to send a batch of notifications.</p> <p>Device tokens should almost all be valid if you've captured them correctly and you're sending them to the correct environment. So it makes sense to optimize assuming failures will be rare. You'll get way better performance if you wait for write to fail or the batch to complete before checking for an error response, even counting the time to send the dropped notifications again.</p> <p>None of this is really specific to APNs, it applies to most socket-level programming.</p> <p>If your development tool of choice supports multiple threads or interprocess communication, you could have a thread or process waiting for an error response all the time and let the main sending thread or process know when it should give up and retry.</p> </blockquote>
16,436,666
Highcharts - issue about full chart width
<p>I'm using Highcharts column chart and I want it to be 100% width responsive chart. The container is a simple <code>&lt;div&gt;</code> with no any formatting. When the document loads, the chart is always fixed width 600x400px size. If I resize window or switch to another browser tab, the chart fills the width and becomes responsive full width chart just like I wanted. If I reload page, it's fixed width again. I tried setting width to both container and chart, however, nothing helps. If I move the container div one level above the parent div, It works. How to make the chart become full width on page load also?</p> <p>Thanks</p>
16,440,351
2
4
null
2013-05-08 09:07:45.103 UTC
10
2016-10-12 13:26:58.823 UTC
null
null
null
null
2,029,035
null
1
40
javascript|html|css|highcharts
26,033
<p>Chart's width is taken from <code>jQuery.width(container)</code>, so if you have chart in some hidden tabs or something similar, width will be undefined. In that case default width and height are set (600x400).</p>
16,344,223
AngularJs - cancel route change event
<p>How do I cancel route change event in AngularJs?</p> <p>My current code is</p> <pre><code>$rootScope.$on("$routeChangeStart", function (event, next, current) { // do some validation checks if(validation checks fails){ console.log("validation failed"); window.history.back(); // Cancel Route Change and stay on current page } }); </code></pre> <p>with this even if the validation fails Angular pulls the next template and associated data and then immediately switches back to previous view/route. I don't want angular to pull next template &amp; data if validation fails, ideally there should be no window.history.back(). I even tried event.preventDefault() but no use.</p>
16,346,403
9
0
null
2013-05-02 17:31:25.033 UTC
31
2020-10-22 10:25:47.15 UTC
null
null
null
null
1,636,062
null
1
88
javascript|angularjs
99,023
<p>Instead of <code>$routeChangeStart</code> use <code>$locationChangeStart</code></p> <p>Here's the discussion about it from the angularjs guys: <a href="https://github.com/angular/angular.js/issues/2109" rel="noreferrer">https://github.com/angular/angular.js/issues/2109</a></p> <p><strong>Edit 3/6/2018</strong> You can find it in the docs: <a href="https://docs.angularjs.org/api/ng/service/$location#event-$locationChangeStart" rel="noreferrer">https://docs.angularjs.org/api/ng/service/$location#event-$locationChangeStart</a></p> <p>Example:</p> <pre><code>$scope.$on('$locationChangeStart', function(event, next, current) { if ($scope.form.$invalid) { event.preventDefault(); } }); </code></pre>
29,154,877
Use HTML5 (datalist) autocomplete with 'contains' approach, not just 'starts with'
<p>(I can't find it, but then again I don't really know how to search for it.)</p> <p>I want to use <code>&lt;input list=xxx&gt;</code> and <code>&lt;datalist id=xxx&gt;</code> to get autocompletion, BUT I want the browser to match all options by 'contains' approach, instead of 'starts with', which seems to be standard. Is there a way?</p> <p>If not simply, is there a way to force-show suggestions that I want to show, not those that the browser matched? Let's say I'm typing "foo" and I want to show options "bar" and "baz". Can I force those upon the user? If I just fill the datalist with those (with JS), the browser will still do its 'starts with' check, and filter them out.</p> <p>I want ultimate control over HOW the datalist options show. NOT over its UI, flexibility, accessibility etc, so I don't want to completely remake it. Don't even suggest a jQuery plugin.</p> <p>If I can ultimate-control form element validation, why not autocompletion, right?</p> <p><strong>edit:</strong> I see now that Firefox does use the 'contains' approach... That's not even a standard?? Any way to force this? Could I change Firefox's way?</p> <p><strong>edit:</strong> I made this to illustrate what I'd like: <a href="http://jsfiddle.net/rudiedirkx/r3jbfpxw/" rel="noreferrer">http://jsfiddle.net/rudiedirkx/r3jbfpxw/</a></p> <ul> <li><a href="https://html.spec.whatwg.org/multipage/forms.html#the-list-attribute" rel="noreferrer">HTMLWG's specs on <code>[list]</code></a></li> <li><a href="http://www.w3.org/TR/html-markup/datalist.html" rel="noreferrer">W3's specs on <code>datalist</code></a></li> <li><a href="http://davidwalsh.name/demo/datalist.php" rel="noreferrer">DavidWalsh example</a></li> <li><a href="http://www.hongkiat.com/blog/html5-datalist/" rel="noreferrer">HONGKIAT's summary on behaviors..?</a></li> </ul>
32,394,157
4
5
null
2015-03-19 20:58:13.59 UTC
9
2020-02-29 04:24:01.197 UTC
2015-09-03 19:43:44.247 UTC
null
247,372
null
247,372
null
1
38
html|autocomplete|html-datalist
21,631
<p><strong>'contains' approach</strong></p> <p>Maybe this is what you are looking for (part 1 of your question).</p> <p>It goes with the limitation of "starts with" and changes when a selection is made.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict'; function updateList(that) { if (!that) { return; } var lastValue = that.lastValue, value = that.value, array = [], pos = value.indexOf('|'), start = that.selectionStart, end = that.selectionEnd, options; if (that.options) { options = that.options; } else { options = Object.keys(that.list.options).map(function (option) { return that.list.options[option].value; }); that.options = options; } if (lastValue !== value) { that.list.innerHTML = options.filter(function (a) { return ~a.toLowerCase().indexOf(value.toLowerCase()); }).map(function (a) { return '&lt;option value="' + value + '|' + a + '"&gt;' + a + '&lt;/option&gt;'; }).join(); updateInput(that); that.lastValue = value; } } function updateInput(that) { if (!that) { return; } var value = that.value, pos = value.indexOf('|'), start = that.selectionStart, end = that.selectionEnd; if (~pos) { value = value.slice(pos + 1); } that.value = value; that.setSelectionRange(start, end); } document.getElementsByTagName('input').browser.addEventListener('keyup', function (e) { updateList(this); }); document.getElementsByTagName('input').browser.addEventListener('input', function (e) { updateInput(this); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input list="browsers" name="browser" id="browser" onkeyup="updateList();" oninput="updateInput();"&gt; &lt;datalist id="browsers"&gt; &lt;option value="Internet Explorer"&gt; &lt;option value="Firefox"&gt; &lt;option value="Chrome"&gt; &lt;option value="Opera"&gt; &lt;option value="Safari"&gt; &lt;/datalist&gt;</code></pre> </div> </div> </p> <p>Edit</p> <p>A different approach of displaying the search content, to make clear, what happens. This works in Chrome as well. Inspired by <a href="https://stackoverflow.com/questions/29882361/show-datalist-labels-but-submit-the-actual-value">Show datalist labels but submit the actual value</a></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-js lang-js prettyprint-override"><code> 'use strict'; var datalist = { r: ['ralph', 'ronny', 'rudie'], ru: ['rudie', 'rutte', 'rudiedirkx'], rud: ['rudie', 'rudiedirkx'], rudi: ['rudie'], rudo: ['rudolf'], foo: [ { value: 42, text: 'The answer' }, { value: 1337, text: 'Elite' }, { value: 69, text: 'Dirty' }, { value: 3.14, text: 'Pi' } ] }, SEPARATOR = ' &gt; '; function updateList(that) { var lastValue = that.lastValue, value = that.value, array, key, pos = value.indexOf('|'), start = that.selectionStart, end = that.selectionEnd; if (lastValue !== value) { if (value !== '') { if (value in datalist) { key = value; } else { Object.keys(datalist).some(function (a) { return ~a.toLowerCase().indexOf(value.toLowerCase()) &amp;&amp; (key = a); }); } } that.list.innerHTML = key ? datalist[key].map(function (a) { return '&lt;option data-value="' + (a.value || a) + '"&gt;' + value + (value === key ? '' : SEPARATOR + key) + SEPARATOR + (a.text || a) + '&lt;/option&gt;'; }).join() : ''; updateInput(that); that.lastValue = value; } } function updateInput(that) { var value = that.value, pos = value.lastIndexOf(SEPARATOR), start = that.selectionStart, end = that.selectionEnd; if (~pos) { value = value.slice(pos + SEPARATOR.length); } Object.keys(that.list.options).some(function (option) { var o = that.list.options[option], p = o.text.lastIndexOf(SEPARATOR); if (o.text.slice(p + SEPARATOR.length) === value) { value = o.getAttribute('data-value'); return true; } }); that.value = value; that.setSelectionRange(start, end); } document.getElementsByTagName('input').xx.addEventListener('keyup', function (e) { updateList(this); }); document.getElementsByTagName('input').xx.addEventListener('input', function (e) { updateInput(this); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input list="xxx" name="xx" id="xx"&gt; &lt;datalist id="xxx" type="text"&gt;&lt;/datalist&gt;</code></pre> </div> </div> </p>
17,258,787
Formatting of persp3d plot
<p>I have the following 3d plot:</p> <p><img src="https://i.stack.imgur.com/04AOC.png" alt="ro"></p> <p>With my <a href="http://uploadeasy.net/upload/15k2d.rar" rel="nofollow noreferrer">data</a> I created it with the following code:</p> <pre><code>library(rugarch) library(rgl) library(fGarch) fd &lt;- as.data.frame(modelfit, which = 'density') color &lt;- rgb(85, 141, 85, maxColorValue=255) x &lt;- seq(-0.2, 0.2, length=100) y &lt;-c(1:2318) f &lt;- function(s, t) { dged(s,mean=fd[t,'Mu'],sd=fd[t,'Sigma'],nu=fd[t,'Shape']) } z &lt;- outer(x, y, f) persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color, ticktype="detailed", xlab="", ylab="time", zlab="",axes=TRUE) </code></pre> <p>How can I get a coloring depending on the z values? I looked at different solutions, e.g. this <a href="https://stackoverflow.com/questions/10357002/create-3d-plot-colored-according-to-the-z-axis">one</a>, but I could not create the coloring depending on the z values in this case. The solution according to <a href="https://stackoverflow.com/questions/10357002/create-3d-plot-colored-according-to-the-z-axis?rq=1">this thread</a> would be the following:</p> <pre><code>nrz &lt;- nrow(z) ncz &lt;- ncol(z) jet.colors &lt;- colorRampPalette( c("#ffcccc", "#cc0000") ) # Generate the desired number of colors from this palette nbcol &lt;- 100 color &lt;- jet.colors(nbcol) # Compute the z-value at the facet centres zfacet &lt;- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz] # Recode facet z-values into color indices facetcol &lt;- cut(zfacet, nbcol) persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color[facetcol], ticktype="detailed", xlab="", ylab="time", zlab="",axes=TRUE) </code></pre> <p>But this does not give a good result, since it does not color the plot appropriate. I want to have the spikes of my surface to be e.g. in red and the low values to be e.g. in blue with a nice smooth transition, but this kind of colors the slices, so depending on the time? So extreme large spikes should be colored at their spikes in red and values at the bottom e.g. in green. How can I get this?</p> <p>Edit: I found a solution to my previous question about the date on the axis, the only problem left, is an appropriate coloring dependent on the z values.</p>
17,386,030
3
1
null
2013-06-23 08:05:01.433 UTC
13
2017-01-01 15:41:15.207 UTC
2017-05-23 12:25:21.27 UTC
null
-1
null
2,165,335
null
1
12
r|colors|plot
19,950
<p>Try this:</p> <pre><code>nbcol = 100 color = rev(rainbow(nbcol, start = 0/6, end = 4/6)) zcol = cut(z, nbcol) persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color[zcol], ticktype="detailed", xlab="", ylab="time", zlab="",axes=TRUE) </code></pre> <p><img src="https://i.stack.imgur.com/hwmwj.png" alt="theplot"></p> <p>If you want the coloring to be by time (so spikes are always red) you can set the coloring for each time slice:</p> <pre><code>mycut = function(x, breaks) as.numeric(cut(x=x, breaks=breaks)) # to combine different factors zcol2 = as.numeric(apply(z,2, mycut, breaks=nbcol)) persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color[zcol2], ticktype="detailed", xlab="", ylab="time", zlab="",axes=TRUE) </code></pre> <p><img src="https://i.stack.imgur.com/fYTf4.png" alt="theplot2"></p> <p>You already know how to edit the axes properly.</p>
11,877,665
'int' object has no attribute 'append'
<p>When I run this code then following error is encountered, I am new to programming and I know I have bunch of useless arrays. I don't know where my error is as I have declared <code>j</code> as an array. I am completely out of ideas.</p> <pre><code>import pyodbc,nltk,array,re,itertools cnxn = pyodbc.connect('Driver={MySQL ODBC 5.1 Driver};Server=127.0.0.1;Port=3306;Database=information_schema;User=root; Password=1234;Option=3;') cursor = cnxn.cursor() cursor.execute("use collegedatabase ;") cursor.execute("select * from sampledata ; ") cnxn.commit() s=[] j=[] x=[] words = [] w = [] sfq = [] POS=[] wnl = nltk.WordNetLemmatizer() p = [] clean= [] l =[] tupletolist= [] results = [] aux = [] regex = re.compile("\w+\.") pp = [] array1=[] f = open("C:\\Users\\vchauhan\\Desktop\\tupletolist.txt","w") for entry in cursor: s.append(entry.injury_type),j.append(entry.injury_desc) def isAcceptableChar(character): return character not in "~!@#$%^&amp;*()_+`1234567890-={}|:&lt;&gt;?[]\;',/." from nltk.tokenize import word_tokenize from nltk.corpus import stopwords english_stops = set(stopwords.words('english')) for i in range(0,200): j.append(filter(isAcceptableChar, j[i])) w.append([word for word in word_tokenize(j[i].lower()) if word not in english_stops]) for j in range (0,len(w[i])): results = regex.search(w[i][j]) if results: str.rstrip(w[i][j],'.') for a in range(0 , 200): sfq.append(" ".join(w[a])) from nltk.stem import LancasterStemmer stemmer = LancasterStemmer() for i in range (0,200): pp.append(len(w[i])) for a in range (0,200): p.append(word_tokenize(sfq[a])) POS.append([wnl.lemmatize(t) for t in p[a]]) x.append(nltk.pos_tag(POS[a])) clean.append((re.sub('()[\]{}'':/\-[(",)]','',str(x[a])))) cursor.execute("update sampledata SET POS = ? where SRNO = ?", (re.sub('()[\]{}'':/\-[(",)]','',str(x[a]))), a) for i in range (0,len(array1)): results.append(regex.search(array1[i][0])) if results[i] is not None: aux.append(i) f.write(str(w)) </code></pre> <p>Exception:</p> <pre><code>Traceback (most recent call last): File "C:\Users\vchauhan\Desktop\regexsolution_try.py", line 37, in &lt;module&gt; j.append(filter(isAcceptableChar, j[i])) AttributeError: 'int' object has no attribute 'append' </code></pre>
11,877,785
4
1
null
2012-08-09 06:11:06.44 UTC
null
2018-02-19 20:01:32.26 UTC
2018-02-19 20:01:32.26 UTC
null
472,495
null
1,234,419
null
1
4
python
89,263
<p><code>j</code> has been used a a list as well as an integer. Use <code>j</code> only for integer name, name the list to something else.</p> <pre><code>j.append(filter(isAcceptableChar, j[i])) # j is not a list here,it is an int. w.append([word for word in word_tokenize(j[i].lower()) if word not in english_stops]) for j in range (0,len(w[i])): # here j is an int </code></pre>
11,941,929
Get all empty groups in Active Directory
<p>I am stuck trying to figure out how to get all Active Directory groups that are empty. I came up with this command, which selects groups that have no Members and aren't a MemberOf anything.</p> <pre><code>Get-QADGroup -GroupType Security -SizeLimit 0 | where-object {$_.Members.Count -eq 0 -and $_.MemberOf.Count -eq 0} | select GroupName, ParentContainer | Export-Csv c:\emptygroups.csv </code></pre> <p>This is mostly correct, but it's saying certain groups like the default group <strong>Domain Computers</strong> is empty, but it isn't empty. This particular group has only members that are computers, but it appears that other groups that only have computers as well aren't selected.</p> <p>Does anyone know why this command is pulling in some that have members?</p>
11,945,228
6
0
null
2012-08-13 20:38:43.447 UTC
null
2019-06-14 09:24:09.297 UTC
null
null
null
null
935,779
null
1
4
powershell|quest
46,273
<p>The <code>Get-QADGroup</code> cmdlet has a parameter <code>-Empty</code>. The description in the help hints at the reason these default groups are being returned:</p> <blockquote> <p>Note: A group is considered empty if it has the "member" attribute not set. So, this parameter can retrieve a group that has only those members for which the group is set as the primary group. An example is the Domain Users group, which normally is the primary group for any user account while having the "member" attribute not set.</p> </blockquote> <p>I'm not really familiar with the Quest stuff, but I was able to find empty groups this way, (probably not the most efficient):</p> <pre><code>Get-ADGroup -Filter {GroupCategory -eq 'Security'} | ?{@(Get-ADGroupMember $_).Length -eq 0} </code></pre>
22,149,329
Remove strange blue box in visual studio
<p><img src="https://i.imgur.com/FKX5hH4.png" alt="Bluebox microsoft devilspawn"></p> <p>This blue rectangle is fixed on the screen. Sometimes growing, shrinking and changing place.</p> <p>tried the answer to this question: <a href="https://stackoverflow.com/questions/270005/in-the-visual-studio-sql-editor-how-do-i-get-rid-of-the-boxes">In the Visual Studio SQL editor, how do I get rid of the boxes?</a> as I thought it might be related but didn't help. How to get rid of it?</p>
22,232,590
3
3
null
2014-03-03 14:29:39.75 UTC
3
2018-07-27 10:37:06.05 UTC
2017-05-23 12:18:13.22 UTC
null
-1
null
1,303,205
null
1
41
visual-studio|visual-studio-2012
12,356
<p>The box is drawn by <a href="http://windows.microsoft.com/en-us/windows/hear-text-read-aloud-narrator" rel="noreferrer">Windows' Narrator feature</a> for people with low vision. I recently accidentally toggled this myself by hitting <kbd>winkey</kbd>+<kbd>enter</kbd>. Hitting it again and moving the mouse cursor seems to toggle it back off again as well.</p> <p>As mentioned below, depending on the narrator shortcuts configured on your system one of the following may work:</p> <ul> <li><kbd>winkey</kbd>+<kbd>enter</kbd>.</li> <li><kbd>caps lock</kbd>+<kbd>esc</kbd></li> </ul> <p>Full overview of narrator hot keys <a href="https://support.microsoft.com/en-us/help/22806/windows-10-narrator-keyboard-commands-touch-gestures" rel="noreferrer">can be found here</a>. </p>
22,011,200
creating Hashmap from a JSON String
<p>creating a hashmap from a json string in java?</p> <p>I have json string like <code>{"phonetype":"N95","cat":"WP"}</code> and want to convert into a standard Hashmap.</p> <p>How can i do it?</p>
22,011,887
16
3
null
2014-02-25 10:22:12.897 UTC
25
2021-07-14 13:42:51.03 UTC
2014-02-25 10:23:52.797 UTC
null
1,594,817
null
3,346,638
null
1
66
java|android|json|hashmap
204,254
<p>Parse the JSONObject and create HashMap</p> <pre><code>public static void jsonToMap(String t) throws JSONException { HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); JSONObject jObject = new JSONObject(t); Iterator&lt;?&gt; keys = jObject.keys(); while( keys.hasNext() ){ String key = (String)keys.next(); String value = jObject.getString(key); map.put(key, value); } System.out.println("json : "+jObject); System.out.println("map : "+map); } </code></pre> <p>Tested output:</p> <pre><code>json : {"phonetype":"N95","cat":"WP"} map : {cat=WP, phonetype=N95} </code></pre>
26,949,569
Do temp variables slow down my program?
<p>Suppose I have the following C code:</p> <pre><code>int i = 5; int j = 10; int result = i + j; </code></pre> <p>If I'm looping over this many times, would it be faster to use <code>int result = 5 + 10</code>? I often create temporary variables to make my code more readable, for example, if the two variables were obtained from some array using some long expression to calculate the indices. Is this bad performance-wise in C? What about other languages?</p>
26,949,631
5
10
null
2014-11-15 19:04:05.59 UTC
10
2017-12-12 04:35:37.487 UTC
2017-12-12 04:35:37.487 UTC
null
3,154,996
null
3,154,996
null
1
76
c|performance|temporary
7,717
<p>A modern optimizing compiler should optimize those variables away, for example if we use the following example in <a href="http://gcc.godbolt.org/" rel="noreferrer">godbolt</a> with <code>gcc</code> using the <code>-std=c99 -O3</code> flags (<em><a href="http://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22AQ4YgSwOwYwGwK4BMCmwA8BnALkiB7AOgAsA%2BAKHNGADd8IlgAzBWACgEoqQBvbkaNmARgAXmABWANz9hUIQCsxwAIwAGGdUHAATikwI4Q8SIDUwBZuCyADjsFM2wAEQBSJAB0ozgDS79hkIcwFbAAL5AAA%3D%22%2C%22compiler%22%3A%22%2Fopt%2Fgcc-4.9.0%2Fbin%2Fg%2B%2B%22%2C%22options%22%3A%22-x%20c%20-std%3Dc99%20-O3%22%7D%5D%7D" rel="noreferrer">see it live</a></em>):</p> <pre><code>#include &lt;stdio.h&gt; void func() { int i = 5; int j = 10; int result = i + j; printf( "%d\n", result ) ; } </code></pre> <p>it will result in the following assembly:</p> <pre><code>movl $15, %esi </code></pre> <p>for the calculation of <code>i + j</code>, this is form of <a href="http://en.wikipedia.org/wiki/Constant_folding" rel="noreferrer">constant propagation</a>.</p> <p>Note, I added the <code>printf</code> so that we have a side effect, otherwise <code>func</code> would have been optimized away to:</p> <pre><code>func: rep ret </code></pre> <p>These optimizations are allowed under the <em>as-if rule</em>, which only requires the compiler to emulate the observable behavior of a program. This is covered in the draft C99 standard section <code>5.1.2.3</code> <em>Program execution</em> which says:</p> <blockquote> <p>In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).</p> </blockquote> <p>Also see: <a href="http://blogs.msdn.com/b/vcblog/archive/2013/07/04/optimizing-c-code-constant-folding.aspx" rel="noreferrer">Optimizing C++ Code : Constant-Folding</a></p>
19,546,920
how to Check NSString is null or not
<p>I want to check weather a <code>NSString</code> is null or not. Im assigning from an JSON array. After assigning that string value is <code>&lt;null&gt;</code>. Now I want to check this string is null or not. So I put like this</p> <p><code>if (myStringAuthID==nil)</code> but this if statement always false. How I can check a string for null. Please help me</p> <p>Thanks</p>
19,546,993
5
6
null
2013-10-23 16:12:44.667 UTC
6
2014-06-24 17:31:33.08 UTC
2013-11-06 16:46:04.23 UTC
null
2,692,029
null
2,889,249
null
1
21
ios|objective-c|xcode|nsstring
47,176
<p>Like that:</p> <pre><code>[myString isEqual: [NSNull null]]; </code></pre>
17,221,725
How to increase the memory heap size on IntelliJ IDEA?
<p>I want to allocate around 1GB of heap size, but I can't seem to figure it out.</p> <p>How to do this?</p>
17,221,838
7
0
null
2013-06-20 19:03:46.017 UTC
7
2020-05-04 11:46:28.547 UTC
2019-03-27 15:27:47.93 UTC
null
10,739,377
null
2,350,850
null
1
32
intellij-idea|heap-memory
75,440
<p>Use <strong>Help</strong> | <strong>Edit Custom VM Options…</strong></p> <p><a href="https://i.stack.imgur.com/2Dp8y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2Dp8y.png" alt="VM Options"></a></p> <p>An editor will open automatically for the right <code>.vmoptions</code> file, adjust the value of <code>-Xmx</code>, save and restart IntelliJ IDEA:</p> <p><a href="https://i.stack.imgur.com/Omkf5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Omkf5.png" alt="editor"></a></p> <p>Check these documents from IntelliJ IDEA knowledge base for more details:</p> <ul> <li><a href="https://intellij-support.jetbrains.com/hc/articles/206544869" rel="noreferrer">Configuring JVM options and platform properties</a></li> <li><a href="https://intellij-support.jetbrains.com/hc/en-us/articles/207241105" rel="noreferrer">The JVM could not be started. The main method may have thrown an exception</a>.</li> </ul> <p>Answers below suggest to edit <code>.vmoptions</code> file directly inside the application installation directory. Please note that it's not recommended since it will cause conflicts during patch updates. The method above creates a copy of the file in the <a href="https://intellij-support.jetbrains.com/hc/articles/206544519" rel="noreferrer">CONFIG</a> directory and your IDE installation remains intact.</p> <p>Also be aware of the 32-bit <a href="https://intellij-support.jetbrains.com/hc/articles/207241105" rel="noreferrer">address space limit on Windows</a> which makes it hard to use heap sizes higher than <code>750m</code>. Should you need to use larger heap, make sure to <a href="https://intellij-support.jetbrains.com/hc/articles/206544879" rel="noreferrer">switch to the 64-bit JVM first</a>, otherwise IDE may crash on start or start to crash randomly during work.</p>
17,132,003
FBSDKLog: Cannot use the Facebook app or Safari to authorize, fb**** is not registered as a URL Scheme
<p>I want to have the <code>Facebook app native dialog login</code> (<a href="https://developers.facebook.com/docs/technical-guides/iossdk/login/#fbnative" rel="nofollow noreferrer">https://developers.facebook.com/docs/technical-guides/iossdk/login/#fbnative</a>).</p> <p>In the console, I get the following message when clicking on the FBLoginView:</p> <pre><code>FBSDKLog: Cannot use the Facebook app or Safari to authorize, fb**** is not registered as a URL Scheme </code></pre> <p>Yet I did exactly as here: <a href="https://stackoverflow.com/questions/16113688/failing-to-open-active-session-after-updating-facebook-sdk-to-3-5">Failing to open active session after updating Facebook SDK to 3.5</a></p>
17,143,903
10
0
null
2013-06-16 09:50:31.387 UTC
11
2015-05-24 07:42:49.827 UTC
2017-05-23 11:53:20.223 UTC
null
-1
null
1,435,156
null
1
34
ios6|facebook-login
27,236
<p>In <code>myapp-Info.plist</code>, I renamed <code>URL Schemes</code> key to <code>CFBundleURLSchemes</code>:</p> <p>Before:</p> <pre><code>&lt;key&gt;CFBundleURLTypes&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;URL Schemes&lt;/key&gt; &lt;array&gt; &lt;string&gt;fb***&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/array&gt; </code></pre> <p>After:</p> <pre><code>&lt;key&gt;CFBundleURLTypes&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;CFBundleURLSchemes&lt;/key&gt; &lt;array&gt; &lt;string&gt;fb***&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/array&gt; </code></pre> <p>The difference is not visible in XCode because <code>CFBundleURLSchemes</code> is aliased with <code>URL Schemes</code>.</p> <p>As a consequence, you have to edit <code>myapp-Info.plist</code> manually.</p>
17,335,984
What is log4j's default log file dumping path
<p>Hi i am new to programming concepts and i am tend to work out something with log4j. So i am reading Log4j tutorials where i found the following code:</p> <pre><code>package test; import org.apache.log4j.Logger; import java.io.*; import java.sql.SQLException; public class Log4jExample { /* Get actual class name to be printed on */ static Logger log = Logger.getLogger(Log4jExample.class.getName()); public static void main(String[] args)throws IOException,SQLException { log.debug("Hello this is an debug message"); log.info("Hello this is an info message"); } } </code></pre> <p>But after running this in eclipse i am not able to locate the generated log file. Can anybody tell where is the file being dumped? Also help me with some best sites wherefrom i can learn Log4j and Java Doc from the scratch. Thanks!!</p>
17,336,188
4
7
null
2013-06-27 06:27:48.483 UTC
11
2015-03-25 03:44:15.357 UTC
2013-07-03 22:40:41.187 UTC
null
545,127
null
2,427,415
null
1
40
java|eclipse|log4j
124,828
<p>To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:</p> <pre><code># Root logger option log4j.rootLogger=INFO, file # Direct log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=C:\\loging.log log4j.appender.file.MaxFileSize=1MB log4j.appender.file.MaxBackupIndex=1 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n </code></pre> <p>Follow this tutorial to learn more about log4j usage:</p> <p><a href="http://www.mkyong.com/logging/log4j-log4j-properties-examples/">http://www.mkyong.com/logging/log4j-log4j-properties-examples/</a></p>
17,553,543
PySerial non-blocking read loop
<p>I am reading serial data like this:</p> <pre><code>connected = False port = 'COM4' baud = 9600 ser = serial.Serial(port, baud, timeout=0) while not connected: #serin = ser.read() connected = True while True: print("test") reading = ser.readline().decode() </code></pre> <p>The problem is that it prevents anything else from executing including bottle py web framework. Adding <code>sleep()</code> won't help.</p> <p>Changing "while True"" to "while ser.readline():" doesn't print "test", which is strange since it worked in Python 2.7. Any ideas what could be wrong?</p> <p>Ideally I should be able to read serial data only when it's available. Data is being sent every 1,000 ms.</p>
17,564,557
4
7
null
2013-07-09 16:31:30.553 UTC
17
2021-10-04 16:28:23.637 UTC
2017-10-16 12:14:51.43 UTC
null
1,136,195
null
998,368
null
1
42
python|python-3.x|nonblocking|pyserial
113,081
<p>Put it in a separate thread, for example:</p> <pre class="lang-py prettyprint-override"><code>import threading import serial connected = False port = 'COM4' baud = 9600 serial_port = serial.Serial(port, baud, timeout=0) def handle_data(data): print(data) def read_from_port(ser): while not connected: #serin = ser.read() connected = True while True: print("test") reading = ser.readline().decode() handle_data(reading) thread = threading.Thread(target=read_from_port, args=(serial_port,)) thread.start() </code></pre> <p><a href="http://docs.python.org/3/library/threading" rel="noreferrer">http://docs.python.org/3/library/threading</a></p>
17,391,364
What is the difference between the selectors ".class.class" and ".class .class"?
<p>What is the different between <code>.class.class</code> and <code>.class .class</code>?</p>
17,391,397
5
2
null
2013-06-30 14:28:27.1 UTC
34
2022-04-05 05:04:52.12 UTC
2018-07-23 12:10:21.347 UTC
null
269,970
null
2,494,384
null
1
88
css|css-selectors
62,615
<p><code>.class .class</code> matches any elements of class <code>.class</code> that are <strong>descendants</strong> of another element with the class <code>.class</code>.</p> <p><code>.class.class</code> matches any element with both classes.</p>
17,321,138
How can I use a conditional expression (expression with if and else) in a list comprehension?
<p>I have a list comprehension that produces list of odd numbers of a given range:</p> <pre><code>[x for x in range(1, 10) if x % 2] </code></pre> <p>That makes a filter that removes the even numbers. Instead, I'd like to use conditional logic, so that even numbers are treated differently, but still contribute to the list. I tried this code, but it fails:</p> <pre><code>&gt;&gt;&gt; [x for x in range(1, 10) if x % 2 else x * 100] File &quot;&lt;stdin&gt;&quot;, line 1 [x for x in range(1, 10) if x % 2 else x * 100] ^ SyntaxError: invalid syntax </code></pre> <p>I know that Python expressions allow a syntax like that:</p> <pre><code>1 if 0 is 0 else 3 </code></pre> <p>How can I use it inside the list comprehension?</p>
17,321,170
6
1
null
2013-06-26 13:17:25.297 UTC
83
2022-06-30 22:42:52.773 UTC
2022-06-30 22:42:52.773 UTC
null
523,612
null
769,384
null
1
239
python|list-comprehension|conditional-operator
421,803
<p><code>x if y else z</code> is the syntax for the expression you're returning for each element. Thus you need:</p> <pre><code>[ x if x%2 else x*100 for x in range(1, 10) ] </code></pre> <p>The confusion arises from the fact you're using a <em>filter</em> in the first example, but not in the second. In the second example you're only <em>mapping</em> each value to another, using a ternary-operator expression.</p> <p>With a filter, you need:</p> <pre><code>[ EXP for x in seq if COND ] </code></pre> <p>Without a filter you need:</p> <pre><code>[ EXP for x in seq ] </code></pre> <p>and in your second example, the expression is a "complex" one, which happens to involve an <code>if-else</code>.</p>
10,147,690
if else statement inside a for loop?
<p>On the final part of a project i'm doing for school, I am supposed to use a <code>if-else</code> statement inside a <code>for</code> loop, but I have no idea how to do this. I could just use a huge lot of <code>if-else</code> statements to do the same thing, but I dont think my teacher would appreciate it.</p> <p>Here are the instructions for the final part of the homework... </p> <blockquote> <p>Compute the Grade (A, B, C, D or F) and store in another Array8 called grades using if-else loop and the following cutoff inside a for-loop to assign grades.</p> <pre><code>1. Average Grade 2. &gt;= 90 A 3. &gt;=80 and &lt;90 B 4. &gt;=70 and &lt;80 C 5. &gt;=60 and &lt;70 D 6. &lt;60 F </code></pre> </blockquote> <p>This is my code so far...</p> <pre><code>public class Proj5 { public static void main (String[] args) { String[] Array1= {new String("Adam"),new String("Smith"),new String("Jones"),new String("Becky"),new String("Taylor")}; Integer[] Array2={new Integer(90),new Integer(89),new Integer(86),new Integer(76),new Integer(95)}; Integer[] Array3={new Integer(92),new Integer(79),new Integer(85),new Integer(90),new Integer(87)}; Integer[] Array4={new Integer(93),new Integer(80),new Integer(90),new Integer(87),new Integer(92)}; Integer[] Array5={new Integer(90),new Integer(77),new Integer(86),new Integer(92),new Integer(89)}; double av1 = (((Array2[0]+Array3[0]+Array4[0])/3)); double av2 = (((Array2[1]+Array3[1]+Array4[1])/3)); double av3 = (((Array2[2]+Array3[2]+Array4[2])/3)); double av4 = (((Array2[3]+Array3[3]+Array4[3])/3)); double av5 = (((Array2[4]+Array3[4]+Array4[4])/3)); double[] Array6 = {(av1),(av2),(av3),(av4),(av5)}; double avf1 = (av1*.30)+(Array5[0]*.7); double avf2 = (av2*.30)+(Array5[1]*.7); double avf3 = (av3*.30)+(Array5[2]*.7); double avf4 = (av4*.30)+(Array5[3]*.7); double avf5 = (av5*.30)+(Array5[4]*.7); double[] Array7 = {(avf1),(avf2),(avf3),(avf4),(avf5)}; System.out.println("Report for Spring Semester 2009"+ "\n-------------------------------------------"); System.out.println("Name Test1 Test2 Test3 Final Average Grade"); for (int column = 0; column&lt;Array1.length; column++){ System.out.printf("%s ", Array1[column]); System.out.printf("%s ", Array2[column]); System.out.printf("%s ", Array3[column]); System.out.printf("%s ", Array4[column]); System.out.printf("%s ", Array5[column]); System.out.printf("%s ", Array7[column]); System.out.println(); //start new line of output } } } </code></pre>
10,156,573
4
6
null
2012-04-13 20:12:28.82 UTC
3
2017-04-07 09:14:09.977 UTC
2016-01-15 13:04:10.473 UTC
null
4,215,088
null
1,325,455
null
1
3
java|if-statement
124,156
<pre><code>char[] Array8 = new char[5]; for (int i = 0; i &lt; Array8.length;i++ ) { if (Array6[i] &gt;= 90) Array8[i] = 'A'; else if (Array6[i] &gt;= 80) Array8[i] = 'B'; else if (Array6[i] &gt;= 70) Array8[i] = 'C'; else if (Array6[i] &gt;= 60) Array8[i] = 'D'; else Array8[i] = 'F'; } </code></pre>
10,018,363
How to design a web crawler in Java?
<p>I'm working on a project which needs to design a web crawler in Java which can take a user query about a particular news subject and then visit different news websites and then extract news content from those pages and store it in some files/databases. I need this to make a summary of overall stored content. I'm new to this field and so expect some help from people who have any experience how to do it.</p> <p>Right now I have the code to extract news content from a single page which takes the page manually, but I have no idea how to integrate it in a web crawler to extract content from different pages.</p> <p>Can anyone give some good links to tutorials or implementations in Java which I can use or modify according to my needs?</p>
10,018,446
5
0
null
2012-04-04 19:58:27.6 UTC
8
2021-02-14 06:47:21.727 UTC
2014-04-14 21:17:04.493 UTC
null
881,229
null
751,223
null
1
4
java|web-scraping|web-crawler
21,022
<p><a href="http://jsoup.org/" rel="noreferrer">http://jsoup.org/</a></p> <pre><code>Document doc = Jsoup.connect("http://en.wikipedia.org/").get(); Elements newsHeadlines = doc.select("#mp-itn b a"); </code></pre>
5,280,906
Difference between Groovy Binary and Source release?
<p>I have been seeing the words <strong>binary</strong> and <strong>source</strong> release in many websites download sections.</p> <p>What do they actually mean?</p> <p>For example, I have seen this in <a href="https://groovy.apache.org/download.html" rel="nofollow noreferrer">Groovy</a> download page.</p> <p>My question is how they differ? Both tend to install Groovy, but what's the main difference?</p>
5,280,925
3
0
null
2011-03-12 06:01:57.62 UTC
66
2021-05-24 00:40:43.887 UTC
2021-05-24 00:40:43.887 UTC
null
10,794,031
null
576,682
null
1
149
groovy|installation|executable
131,020
<p>A source release will be compiled on your own machine while a binary release must match your operating system.</p> <p>source releases are more common on linux systems because linux systems can dramatically vary in cpu, installed library versions, kernelversions and nearly every linux system has a compiler installed.</p> <p>binary releases are common on ms-windows systems. most windows machines do not have a compiler installed.</p>
5,158,400
How to use scriptlet inside javascript
<p>Can someone test this example and share the results? <a href="http://timothypowell.net/blog/?p=23" rel="noreferrer">http://timothypowell.net/blog/?p=23</a><br> When I do:</p> <pre><code>var myVar = '&lt;% request.getContextPath(); %&gt;'; alert(myVar); </code></pre> <p>I get : <code>'&lt;% request.getContextPath(); %&gt;'.</code></p> <p>Removing the enclosing single quotes from '&lt;% request.getContextPath(); %>'; gives syntax error. How can I use the scrptlet or expresion inside a js function?</p> <p>EDIT: this link has an explanation that helped me:<br> <a href="http://www.codingforums.com/showthread.php?t=172082" rel="noreferrer">http://www.codingforums.com/showthread.php?t=172082</a></p>
5,158,548
4
2
null
2011-03-01 17:57:41.63 UTC
0
2017-12-27 11:55:03.977 UTC
2011-03-01 18:24:36.83 UTC
null
454,671
null
454,671
null
1
10
javascript|jsp
83,571
<p>It sounds like you are placing the JSP code within a JavaScript page, or at least in a non-JSP page. Scriptlets can only be included in a JSP page (typically configured to be *.jsp). </p> <p>The statement as presented, if processed by the JSP compiler, would result in myVar being equal to '' as the scriptlet format you are using &lt;% ... %&gt; executes Java code between the tags, but does not return a result. </p> <p>So, to use this tag you would need to manually write a value to the request output stream. To get the desired functionality you need to do the following: </p> <pre><code> make sure your code is in a JSP page use var myVar = '&lt;%= request.getContextPath() %&gt;'; (note the equals sign) </code></pre> <p>With all that said, scriptlets are viewed as bad practice in most cases. For most cases, your should be using JSTL expressions and custom tags.</p>
43,169,002
How to access a return value from a node script in BASH?
<p>Let's say I have a bash script that calls a node script. I've tried to do it like this:</p> <p>b.sh file:</p> <pre><code>#!/bin/bash v=$(node app.js) echo "$v" </code></pre> <p>app.js file:</p> <pre><code>#!/usr/bin/env node function f() { return "test"; } return f(); </code></pre> <p>How do I access the value returned by the node script ("test") from my bash script ?</p>
43,169,153
2
3
null
2017-04-02 13:39:44.16 UTC
4
2021-04-07 14:25:03.557 UTC
2017-04-02 13:45:19.547 UTC
null
91,607
null
91,607
null
1
30
javascript|node.js|bash
14,801
<p>@Daniel Lizik gave an good answer (now deleted) for the part: how to output the value, e.g. using his answer:</p> <pre><code>#!/usr/bin/env node function f() { return "test"; } console.log(f()) </code></pre> <p>And for the part <em>how to capture the value in bash</em>, do exactly as in your question:</p> <pre><code>#!/bin/bash val=$(node app.js) echo "node returned: $val" </code></pre> <p>the above prints:</p> <pre><code>node returned: test </code></pre>
43,233,025
Use Retrofit methods more expressive way
<p>I want to make <code>void enqueue(Callback&lt;T&gt; callback);</code> method invocation code block more expressive, Here is what I have an usually </p> <pre><code>request.enqueue(object : Callback&lt;MyModel&gt; { override fun onFailure(call: Call&lt;MyModel&gt;?, t: Throwable?) { // } override fun onResponse(call: Call&lt;MyModel&gt;?, response: Response&lt;MyModel&gt;?) { // } }) </code></pre> <p>And what I want and mean is that, to change this code blocks more cleaner way and remove those <strong>override, object, Callback</strong> keywords and do something like that: </p> <p><code>request.enqueue({throwable, response -&gt; })</code></p> <p>I think it could be improved somehow using extensions and higher-order functions. Does anyone know how it can be done? </p>
53,073,258
5
4
null
2017-04-05 13:43:50.353 UTC
12
2018-12-22 23:34:08.923 UTC
2018-12-22 23:34:08.923 UTC
null
4,585,387
null
4,585,387
null
1
36
android|retrofit|kotlin|higher-order-functions
19,851
<p>this is how i do it with extension function and a class</p> <pre><code>fun&lt;T&gt; Call&lt;T&gt;.enqueue(callback: CallBackKt&lt;T&gt;.() -&gt; Unit) { val callBackKt = CallBackKt&lt;T&gt;() callback.invoke(callBackKt) this.enqueue(callBackKt) } class CallBackKt&lt;T&gt;: Callback&lt;T&gt; { var onResponse: ((Response&lt;T&gt;) -&gt; Unit)? = null var onFailure: ((t: Throwable?) -&gt; Unit)? = null override fun onFailure(call: Call&lt;T&gt;, t: Throwable) { onFailure?.invoke(t) } override fun onResponse(call: Call&lt;T&gt;, response: Response&lt;T&gt;) { onResponse?.invoke(response) } } </code></pre> <p>then you can use it like this</p> <pre><code>request.enqueue { onResponse = { // do } onFailure = { // do } } </code></pre>
18,281,636
What replaces nav lists in Bootstrap 3?
<p>I am preparing to update my site to Bootstrap 3, but I can’t figure out how to replace <a href="http://getbootstrap.com/2.3.2/components.html#navs">the <code>nav-list</code> class from Bootstrap 2</a>.</p> <p>I looked into <a href="http://getbootstrap.com/components/#list-group">list groups</a>, but I am not sure if this is to be used to replace nav lists. How would I make the below markup work in Bootstrap 3?</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="well"&gt; &lt;ul class="nav nav-list"&gt; &lt;li&gt;&lt;a href="#"&gt;Link 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <h3>EDIT</h3> <p>This is the look I am going for: <a href="http://jsfiddle.net/bplumb/2Nguy/">http://jsfiddle.net/bplumb/2Nguy/</a></p>
18,281,984
5
0
null
2013-08-16 20:27:51.687 UTC
8
2019-05-15 02:05:17.213 UTC
2013-08-16 21:04:46.613 UTC
null
578,288
null
1,161,353
null
1
30
html|css|twitter-bootstrap
28,740
<h3>EDIT</h3> <p>The removal of <code>.nav-list</code> <a href="https://github.com/twbs/bootstrap/pull/10419" rel="nofollow noreferrer">has been documented</a> in <a href="https://getbootstrap.com/docs/3.3/migration/#dropped" rel="nofollow noreferrer">Migrating to v3.x – What’s removed</a>:</p> <blockquote> <p>Nav lists<br> <code>.nav-list</code> <code>.nav-header</code><br> No direct equivalent, but <a href="https://getbootstrap.com/docs/3.3/components/#list-group" rel="nofollow noreferrer">list groups</a> and <a href="https://getbootstrap.com/docs/3.3/javascript/#collapse" rel="nofollow noreferrer"><code>.panel-group</code>s</a> are similar.</p> </blockquote> <hr> <p>I found this change listed in the changelog inside the <a href="https://github.com/twbs/bootstrap/pull/6342" rel="nofollow noreferrer">“WIP: Bootstrap 3” pull request</a>:</p> <blockquote> <ul> <li><strong>Remove <code>.nav-list</code> option</strong>. Replaced by the new <code>.list-group</code> component.</li> </ul> </blockquote> <p>So if I translate your code to use <code>.list-group</code> instead, I get this:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="well"&gt; &lt;ul class="list-group"&gt; &lt;li class="list-group-item"&gt;&lt;a href="#"&gt;Link 1&lt;/a&gt;&lt;/li&gt; &lt;li class="list-group-item"&gt;&lt;a href="#"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc2/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;div class="well"&gt; &lt;ul class="list-group"&gt; &lt;li class="list-group-item"&gt;&lt;a href="#"&gt;Link 1&lt;/a&gt;&lt;/li&gt; &lt;li class="list-group-item"&gt;&lt;a href="#"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>However, this does not look identical to the way it did in Bootstrap 2. As I <a href="https://stackoverflow.com/questions/18281636/what-replaces-nav-lists-in-bootstrap-3/18281984#comment26819666_18281984">noted</a> in this answer’s comments, there seems to be no exact <code>.nav-list</code> equivalent built-in to Bootstrap 3. So if you need features that <code>.list-group</code> doesn’t have, you will have to write the CSS yourself, or try to port it from Bootstrap 2.</p>
18,577,569
Add view over tableview (UITableViewController)
<p><strong>Situation:</strong> I've got a UITableViewController loading some data asynchronously from a service. During this time I would like to place a full screen (except navigation bar) view over the table view showing my custom indicator and text. </p> <p><strong>Problem:</strong> The problem I'm facing is that when my custom view (it has a red background) is placed over the UITableView the lines of the table view are shown trough my custom view (see image below). </p> <p><strong>What I tried:</strong> I tried to use insertBelow and above, didn't work. I also tried to do: tableview.Hidden = true, but this also hides the custom view for some reason as seen on image 2.</p> <p><img src="https://i.stack.imgur.com/Jg7qd.png" alt="See lines"></p> <p>Image1: For some reason I can see the lines threw my view.</p> <p><img src="https://i.stack.imgur.com/KnINr.png" alt="Hidden true"></p> <p>Image 2: Tableview + custom view gone when hidden = true used.</p> <p><strong>My code:</strong></p> <pre><code> public override void ViewDidLoad () { base.ViewDidLoad (); UIView view = new UIView (new RectangleF (0, 0, this.TableView.Frame.Width, this.TableView.Frame.Height)); view.BackgroundColor = UIColor.Red; this.TableView.AddSubview (view); TableView.Source = new SessionTableViewSource (); } </code></pre>
18,596,655
7
2
null
2013-09-02 16:37:14.753 UTC
5
2020-07-02 12:50:51.967 UTC
2013-09-02 16:55:03.623 UTC
null
1,659,876
null
1,007,240
null
1
18
iphone|ios|uitableview|xamarin.ios|xamarin
38,039
<p>The issue is that the View of a <code>UITableViewController</code> is a <code>UITableView</code>, so you cannot add subviews to the controller on top of the table.</p> <p>I'd recommend switching from a <code>UITableViewController</code> to a simple <code>UIViewController</code> that contains a <code>UITableView</code>. This way the controller main view is a plain <code>UIView</code> that contains a table, and you can add subviews to the main <code>UIView</code> and they will be placed on top of the table view.</p>
20,036,547
MySql : Grant read only options?
<p>I have a user, whom I want to grant all the READ permission on a db schema.</p> <p>One way is this :</p> <pre><code>GRANT SELECT, SHOW_VIEW ON test.* TO 'readuser'@'%'; </code></pre> <p>Is there a way to group all read operations in grant ? </p>
20,061,002
7
2
null
2013-11-17 21:42:24.623 UTC
36
2019-05-09 10:11:45.423 UTC
null
null
null
null
462,923
null
1
130
mysql|sql
216,006
<blockquote> <p>If there is any single privilege that stands for ALL READ operations on database.</p> </blockquote> <p>It depends on how you define "all read."</p> <p>"Reading" from tables and views is the <code>SELECT</code> privilege. If that's what you mean by "all read" then yes:</p> <pre><code>GRANT SELECT ON *.* TO 'username'@'host_or_wildcard' IDENTIFIED BY 'password'; </code></pre> <p>However, it sounds like you mean an ability to "see" everything, to "look but not touch." So, here are the other kinds of reading that come to mind:</p> <p>"Reading" the definition of views is the <code>SHOW VIEW</code> privilege.</p> <p>"Reading" the list of currently-executing queries by other users is the <code>PROCESS</code> privilege.</p> <p>"Reading" the current replication state is the <code>REPLICATION CLIENT</code> privilege.</p> <p>Note that any or all of these might expose more information than you intend to expose, depending on the nature of the user in question.</p> <p>If that's the reading you want to do, you can combine any of those (or any other of <a href="http://dev.mysql.com/doc/refman/5.6/en/privileges-provided.html" rel="noreferrer">the available privileges</a>) in a single <code>GRANT</code> statement.</p> <pre><code>GRANT SELECT, SHOW VIEW, PROCESS, REPLICATION CLIENT ON *.* TO ... </code></pre> <p>However, there is no single privilege that grants some subset of other privileges, which is what it sounds like you are asking.</p> <p>If you are doing things manually and looking for an easier way to go about this without needing to remember the exact grant you typically make for a certain class of user, you can look up the statement to regenerate a comparable user's grants, and change it around to create a new user with similar privileges:</p> <pre><code>mysql&gt; SHOW GRANTS FOR 'not_leet'@'localhost'; +------------------------------------------------------------------------------------------------------------------------------------+ | Grants for not_leet@localhost | +------------------------------------------------------------------------------------------------------------------------------------+ | GRANT SELECT, REPLICATION CLIENT ON *.* TO 'not_leet'@'localhost' IDENTIFIED BY PASSWORD '*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' | +------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) </code></pre> <p>Changing 'not_leet' and 'localhost' to match the new user you want to add, along with the password, will result in a reusable <code>GRANT</code> statement to create a new user.</p> <p>Of, if you want a single operation to set up and grant the limited set of privileges to users, and perhaps remove any unmerited privileges, that can be done by creating a stored procedure that encapsulates everything that you want to do. Within the body of the procedure, you'd build the <code>GRANT</code> statement with dynamic SQL and/or directly manipulate the grant tables themselves.</p> <p>In <a href="https://dba.stackexchange.com/questions/51500">this recent question on Database Administrators</a>, the poster wanted the ability for an unprivileged user to modify other users, which of course is not something that can normally be done -- a user that can modify other users is, pretty much by definition, not an unprivileged user -- however -- stored procedures provided a good solution in that case, because they run with the security context of their <code>DEFINER</code> user, allowing anybody with <code>EXECUTE</code> privilege on the procedure to temporarily assume escalated privileges to allow them to do the specific things the procedure accomplishes.</p>
14,962,289
Bad Django / uwsgi performance
<p>I am running a django app with nginx &amp; uwsgi. Here's how i run uwsgi:</p> <pre><code>sudo uwsgi -b 25000 --chdir=/www/python/apps/pyapp --module=wsgi:application --env DJANGO_SETTINGS_MODULE=settings --socket=/tmp/pyapp.socket --cheaper=8 --processes=16 --harakiri=10 --max-requests=5000 --vacuum --master --pidfile=/tmp/pyapp-master.pid --uid=220 --gid=499 </code></pre> <p>&amp; nginx configurations:</p> <pre><code>server { listen 80; server_name test.com root /www/python/apps/pyapp/; access_log /var/log/nginx/test.com.access.log; error_log /var/log/nginx/test.com.error.log; # https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-production location /static/ { alias /www/python/apps/pyapp/static/; expires 30d; } location /media/ { alias /www/python/apps/pyapp/media/; expires 30d; } location / { uwsgi_pass unix:///tmp/pyapp.socket; include uwsgi_params; proxy_read_timeout 120; } # what to serve if upstream is not available or crashes #error_page 500 502 503 504 /media/50x.html; } </code></pre> <p>Here comes the problem. When doing "ab" (ApacheBenchmark) on the server i get the following results: </p> <p>nginx version: nginx version: nginx/1.2.6</p> <p>uwsgi version:1.4.5</p> <pre><code>Server Software: nginx/1.0.15 Server Hostname: pycms.com Server Port: 80 Document Path: /api/nodes/mostviewed/8/?format=json Document Length: 8696 bytes Concurrency Level: 100 Time taken for tests: 41.232 seconds Complete requests: 1000 Failed requests: 0 Write errors: 0 Total transferred: 8866000 bytes HTML transferred: 8696000 bytes Requests per second: 24.25 [#/sec] (mean) Time per request: 4123.216 [ms] (mean) Time per request: 41.232 [ms] (mean, across all concurrent requests) Transfer rate: 209.99 [Kbytes/sec] received </code></pre> <p>While running on 500 concurrency level</p> <pre><code>oncurrency Level: 500 Time taken for tests: 2.175 seconds Complete requests: 1000 Failed requests: 50 (Connect: 0, Receive: 0, Length: 50, Exceptions: 0) Write errors: 0 Non-2xx responses: 950 Total transferred: 629200 bytes HTML transferred: 476300 bytes Requests per second: 459.81 [#/sec] (mean) Time per request: 1087.416 [ms] (mean) Time per request: 2.175 [ms] (mean, across all concurrent requests) Transfer rate: 282.53 [Kbytes/sec] received </code></pre> <p>As you can see... all requests on the server fail with either timeout errors or "Client prematurely disconnected" or:</p> <pre><code>writev(): Broken pipe [proto/uwsgi.c line 124] during GET /api/nodes/mostviewed/9/?format=json </code></pre> <p>Here's a little bit more about my application: Basically, it's a collection of models that reflect MySQL tables which contain all the content. At the frontend, i have django-rest-framework which serves json content to the clients.</p> <p>I've installed django-profiling &amp; django debug toolbar to see whats going on. On django-profiling here's what i get when running a single request:</p> <pre><code>Instance wide RAM usage Partition of a set of 147315 objects. Total size = 20779408 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 63960 43 5726288 28 5726288 28 str 1 36887 25 3131112 15 8857400 43 tuple 2 2495 2 1500392 7 10357792 50 dict (no owner) 3 615 0 1397160 7 11754952 57 dict of module 4 1371 1 1236432 6 12991384 63 type 5 9974 7 1196880 6 14188264 68 function 6 8974 6 1076880 5 15265144 73 types.CodeType 7 1371 1 1014408 5 16279552 78 dict of type 8 2684 2 340640 2 16620192 80 list 9 382 0 328912 2 16949104 82 dict of class &lt;607 more rows. Type e.g. '_.more' to view.&gt; CPU Time for this request 11068 function calls (10158 primitive calls) in 0.064 CPU seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.064 0.064 /usr/lib/python2.6/site-packages/django/views/generic/base.py:44(view) 1 0.000 0.000 0.064 0.064 /usr/lib/python2.6/site-packages/django/views/decorators/csrf.py:76(wrapped_view) 1 0.000 0.000 0.064 0.064 /usr/lib/python2.6/site-packages/rest_framework/views.py:359(dispatch) 1 0.000 0.000 0.064 0.064 /usr/lib/python2.6/site-packages/rest_framework/generics.py:144(get) 1 0.000 0.000 0.064 0.064 /usr/lib/python2.6/site-packages/rest_framework/mixins.py:46(list) 1 0.000 0.000 0.038 0.038 /usr/lib/python2.6/site-packages/rest_framework/serializers.py:348(data) 21/1 0.000 0.000 0.038 0.038 /usr/lib/python2.6/site-packages/rest_framework/serializers.py:273(to_native) 21/1 0.000 0.000 0.038 0.038 /usr/lib/python2.6/site-packages/rest_framework/serializers.py:190(convert_object) 11/1 0.000 0.000 0.036 0.036 /usr/lib/python2.6/site-packages/rest_framework/serializers.py:303(field_to_native) 13/11 0.000 0.000 0.033 0.003 /usr/lib/python2.6/site-packages/django/db/models/query.py:92(__iter__) 3/1 0.000 0.000 0.033 0.033 /usr/lib/python2.6/site-packages/django/db/models/query.py:77(__len__) 4 0.000 0.000 0.030 0.008 /usr/lib/python2.6/site-packages/django/db/models/sql/compiler.py:794(execute_sql) 1 0.000 0.000 0.021 0.021 /usr/lib/python2.6/site-packages/django/views/generic/list.py:33(paginate_queryset) 1 0.000 0.000 0.021 0.021 /usr/lib/python2.6/site-packages/django/core/paginator.py:35(page) 1 0.000 0.000 0.020 0.020 /usr/lib/python2.6/site-packages/django/core/paginator.py:20(validate_number) 3 0.000 0.000 0.020 0.007 /usr/lib/python2.6/site-packages/django/core/paginator.py:57(_get_num_pages) 4 0.000 0.000 0.020 0.005 /usr/lib/python2.6/site-packages/django/core/paginator.py:44(_get_count) 1 0.000 0.000 0.020 0.020 /usr/lib/python2.6/site-packages/django/db/models/query.py:340(count) 1 0.000 0.000 0.020 0.020 /usr/lib/python2.6/site-packages/django/db/models/sql/query.py:394(get_count) 1 0.000 0.000 0.020 0.020 /usr/lib/python2.6/site-packages/django/db/models/query.py:568(_prefetch_related_objects) 1 0.000 0.000 0.020 0.020 /usr/lib/python2.6/site-packages/django/db/models/query.py:1596(prefetch_related_objects) 4 0.000 0.000 0.020 0.005 /usr/lib/python2.6/site-packages/django/db/backends/util.py:36(execute) 1 0.000 0.000 0.020 0.020 /usr/lib/python2.6/site-packages/django/db/models/sql/query.py:340(get_aggregation) 5 0.000 0.000 0.020 0.004 /usr/lib64/python2.6/site-packages/MySQLdb/cursors.py:136(execute) 2 0.000 0.000 0.020 0.010 /usr/lib/python2.6/site-packages/django/db/models/query.py:1748(prefetch_one_level) 4 0.000 0.000 0.020 0.005 /usr/lib/python2.6/site-packages/django/db/backends/mysql/base.py:112(execute) 5 0.000 0.000 0.019 0.004 /usr/lib64/python2.6/site-packages/MySQLdb/cursors.py:316(_query) 60 0.000 0.000 0.018 0.000 /usr/lib/python2.6/site-packages/django/db/models/query.py:231(iterator) 5 0.012 0.002 0.015 0.003 /usr/lib64/python2.6/site-packages/MySQLdb/cursors.py:278(_do_query) 60 0.000 0.000 0.013 0.000 /usr/lib/python2.6/site-packages/django/db/models/sql/compiler.py:751(results_iter) 30 0.000 0.000 0.010 0.000 /usr/lib/python2.6/site-packages/django/db/models/manager.py:115(all) 50 0.000 0.000 0.009 0.000 /usr/lib/python2.6/site-packages/django/db/models/query.py:870(_clone) 51 0.001 0.000 0.009 0.000 /usr/lib/python2.6/site-packages/django/db/models/sql/query.py:235(clone) 4 0.000 0.000 0.009 0.002 /usr/lib/python2.6/site-packages/django/db/backends/__init__.py:302(cursor) 4 0.000 0.000 0.008 0.002 /usr/lib/python2.6/site-packages/django/db/backends/mysql/base.py:361(_cursor) 1 0.000 0.000 0.008 0.008 /usr/lib64/python2.6/site-packages/MySQLdb/__init__.py:78(Connect) 910/208 0.003 0.000 0.008 0.000 /usr/lib64/python2.6/copy.py:144(deepcopy) 22 0.000 0.000 0.007 0.000 /usr/lib/python2.6/site-packages/django/db/models/query.py:619(filter) 22 0.000 0.000 0.007 0.000 /usr/lib/python2.6/site-packages/django/db/models/query.py:633(_filter_or_exclude) 20 0.000 0.000 0.005 0.000 /usr/lib/python2.6/site-packages/django/db/models/fields/related.py:560(get_query_set) 1 0.000 0.000 0.005 0.005 /usr/lib64/python2.6/site-packages/MySQLdb/connections.py:8() </code></pre> <p>..etc</p> <p>However, django-debug-toolbar shows the following:</p> <pre><code>Resource Usage Resource Value User CPU time 149.977 msec System CPU time 119.982 msec Total CPU time 269.959 msec Elapsed time 326.291 msec Context switches 11 voluntary, 40 involuntary and 5 queries in 27.1 ms </code></pre> <p>The problem is that "top" shows the load average rising quickly and apache benchmark which i ran both on the local server and from a remote machine within the network shows that i am not serving many requests / second. What is the problem? this is as far as i could reach when profiling the code so it would be appreciated if someone can point of what i am doing here.</p> <p><strong>Edit (23/02/2013): Adding more details based on Andrew Alcock's answer:</strong> The points that require my attention / answer are (3)(3) I've executed "show global variables" on MySQL and found out that MySQL configurations had 151 for max_connections setting which is more than enough to serve the workers i am starting for uwsgi.</p> <p>(3)(4)(2) The single request i am profiling is the heaviest one. It executes 4 queries according to django-debug-toolbar. What happens is that all queries run in: 3.71, 2.83, 0.88, 4.84 ms respectively.</p> <p>(4) Here you're referring to memory paging? if so, how could i tell? </p> <p>(5) On 16 workers, 100 concurrency rate, 1000 requests the load average goes up to ~ 12 I ran the tests on different number of workers (concurrency level is 100):</p> <ol> <li>1 worker, load average ~ 1.85, 19 reqs / second, Time per request: 5229.520, 0 non-2xx</li> <li>2 worker, load average ~ 1.5, 19 reqs / second, Time per request: 516.520, 0 non-2xx</li> <li>4 worker, load average ~ 3, 16 reqs / second, Time per request: 5929.921, 0 non-2xx</li> <li>8 worker, load average ~ 5, 18 reqs / second, Time per request: 5301.458, 0 non-2xx</li> <li>16 worker, load average ~ 19, 15 reqs / second, Time per request: 6384.720, 0 non-2xx</li> </ol> <p>AS you can see, the more workers we have, the more load we have on the system. I can see in uwsgi's daemon log that the response time in milliseconds increases when i increase the number of workers.</p> <p>On 16 workers, running 500 concurrency level requests uwsgi starts loggin the errors:</p> <pre><code> writev(): Broken pipe [proto/uwsgi.c line 124] </code></pre> <p>Load goes up to ~ 10 as well. and the tests don't take much time because non-2xx responses are 923 out of 1000 which is why the response here is quite fast as it's almost empty. Which is also a reply to your point #4 in the summary.</p> <p>Assuming that what i am facing here is an OS latency based on I/O and networking, what is the recommended action to scale this up? new hardware? bigger server?</p> <p>Thanks</p>
15,037,998
3
9
null
2013-02-19 16:21:40.69 UTC
84
2013-02-25 00:04:50.913 UTC
2013-02-23 20:39:57.91 UTC
null
202,690
null
202,690
null
1
53
python|django|uwsgi|django-rest-framework
35,273
<p><strong>EDIT 1</strong> Seen the comment that you have 1 virtual core, adding commentary through on all relavant points</p> <p><strong>EDIT 2</strong> More information from Maverick, so I'm eliminating ideas ruled out and developing the confirmed issues.</p> <p><strong>EDIT 3</strong> Filled out more details about uwsgi request queue and scaling options. Improved grammar.</p> <p><strong>EDIT 4</strong> Updates from Maverick and minor improvements</p> <p>Comments are too small, so here are some thoughts:</p> <ol> <li>Load average is basically how many processes are running on or waiting for CPU attention. For a perfectly loaded system with 1 CPU core, the load average should be 1.0; for a 4 core system, it should be 4.0. The moment you run the web test, the threading rockets and you have a <em>lot</em> of processes waiting for CPU. Unless the load average exceeds the number of CPU cores by a significant margin, it is not a concern</li> <li>The first 'Time per request' value of 4s correlates to the length of the request queue - 1000 requests dumped on Django nearly instantaneously and took on average 4s to service, about 3.4s of which were waiting in a queue. This is due to the very heavy mismatch between the number of requests (100) vs. the number of processors (16) causing 84 of the requests to be waiting for a processor at any one moment.</li> <li><p>Running at a concurrency of 100, the tests take 41 seconds at 24 requests/sec. You have 16 processes (threads), so each request is processed about 700ms. Given your type of transaction, that is a <em>long</em> time per request. This may be because:</p> <ol> <li><strike>The CPU cost of each request is high in Django (which is highly unlikely given the low CPU value from the debug toolbar)</strike></li> <li>The OS is task switching a lot (especially if the load average is higher than 4-8), and the latency is purely down to having too many processes.</li> <li><strike>There are not enough DB connections serving the 16 processes so processes are waiting to have one come available. Do you have at least one connection available per process?</strike></li> <li><p><strike>There is <em>considerable</em> latency around the DB, either</strike>:</p> <ol> <li><strike>Tens of small requests each taking, say, 10ms, most of which is networking overhead. If so, can you introducing caching or reduce the SQL calls to a smaller number. Or</strike></li> <li><strike>One or a couple of requests are taking 100's of ms. To check this, run profiling on the DB. If so, you need to optimise that request.</strike></li> </ol></li> </ol></li> <li><p>The split between system and user CPU cost is unusually high in system, although the total CPU is low. This implies that most of the work in Django is kernel related, such as networking or disk. In this scenario, it might be network costs (eg receiving and sending HTTP requests and receiving and sending requests to the DB). Sometimes this will be high because of <em>paging</em>. If there's no paging going on, then you probably don't have to worry about this at all. </p></li> <li>You have set the processes at 16, but have a high load average <strike>(how high you don't state)</strike>. Ideally you should always have at least <em>one</em> process waiting for CPU (so that CPUs don't spin idly). Processes here don't seem CPU bound, but have a significant latency, so you need more processes than cores. How many more? Try running the uwsgi with different numbers of processors (1, 2, 4, 8, 12, 16, 24, etc) until you have the best throughput. If you change latency of the average process, you will need to adjust this again.</li> <li>The 500 concurrency level definitely is a problem<strike>, but is it the client or the server? The report says 50 (out of 100) had the incorrect content-length which implies a server problem. The non-2xx also seems to point there. Is it possible to capture the non-2xx responses for debugging - stack traces or the specific error message would be incredibly useful</strike> (EDIT) and is caused by the uwsgi request queue running with it's default value of 100.</li> </ol> <p>So, in summary:</p> <p><img src="https://i.stack.imgur.com/hIK9U.png" alt="enter image description here"></p> <ol> <li>Django seems fine</li> <li>Mismatch between concurrency of load test (100 or 500) vs. processes (16): You're pushing way too many concurrent requests into the system for the number of processes to handle. Once you are above the number of processes, all that will happen is that you will lengthen the HTTP Request queue in the web server</li> <li><p>There is a large latency, so either</p> <ol> <li><p>Mismatch between processes (16) and CPU cores (1): If the load average is >3, then it's probably too many processes. Try again with a smaller number of processes</p> <ol> <li><strike>Load average > 2 -> try 8 processes</strike></li> <li><strike>Load average > 4 -> try 4 processes</strike></li> <li>Load average > 8 -> try 2 processes</li> </ol></li> <li><p><strike>If the load average &lt;3, it may be in the DB, so profile the DB to see whether there are loads of small requests (additively causing the latency) or one or two SQL statements are the problem </p></li> </ol></li> <li>Without capturing the failed response, there's not much I can say about the failures at 500 concurrency</strike></li> </ol> <p><strong>Developing ideas</strong></p> <p>Your load averages >10 on a single cored machine is <em>really</em> nasty and (as you observe) leads to a lot of task switching and general slow behaviour. I personally don't remember seeing a machine with a load average of 19 (which you have for 16 processes) - congratulations for getting it so high ;)</p> <p>The DB performance is great, so I'd give that an all-clear right now.</p> <p><strong>Paging</strong>: To answer you question on how to see paging - you can detect OS paging in several ways. For example, in top, the header has page-ins and outs (see the last line):</p> <pre>Processes: 170 total, 3 running, 4 stuck, 163 sleeping, 927 threads 15:06:31 Load Avg: 0.90, 1.19, 1.94 CPU usage: 1.37% user, 2.97% sys, 95.65% idle SharedLibs: 144M resident, 0B data, 24M linkedit. MemRegions: 31726 total, 2541M resident, 120M private, 817M shared. PhysMem: 1420M wired, 3548M active, 1703M inactive, 6671M used, 1514M free. VM: 392G vsize, 1286M framework vsize, 1534241(0) pageins, 0(0) pageouts. Networks: packets: 789684/288M in, 912863/482M out. Disks: 739807/15G read, 996745/24G written.</pre> <p><strong>Number of processes</strong>: In your current configuration, the number of processes is <em>way</em> too high. <strong>Scale the number of processes back to a 2</strong>. We might bring this value up later, depending on shifting further load off this server. </p> <p><strong>Location of Apache Benchmark</strong>: The load average of 1.85 for one process suggests to me that you are running the load generator on the same machine as uwsgi - is that correct? </p> <p>If so, you really need to run this from another machine otherwise the test runs are not representative of actual load - you're taking memory and CPU from the web processes for use in the load generator. In addition, the load generator's 100 or 500 threads will generally stress your server in a way that does not happen in real life. Indeed this might be the reason the whole test fails.</p> <p><strong>Location of the DB</strong>: The load average for one process also suggest that you are running the DB on the same machine as the web processes - is this correct? </p> <p>If I'm correct about the DB, then the first and best way to start scaling is to move the DB to another machine. We do this for a couple of reasons:</p> <ol> <li><p>A DB server needs a different hardware profile from a processing node:</p> <ol> <li>Disk: DB needs a lot of fast, redundant, backed up disk, and a processing node needs just a basic disk</li> <li>CPU: A processing node needs the fastest CPU you can afford whereas a DB machine can often make do without (often its performance is gated on disk and RAM)</li> <li>RAM: a DB machine generally needs as much RAM as possible (and the fastest DB has <em>all</em> its data in RAM), whereas many processing nodes need much less (yours needs about 20MB per process - very small</li> <li>Scaling: <strong>Atomic</strong> DBs scale best by having monster machines with many CPUs whereas the web tier (not having state) can scale by plugging in many identical small boxen.</li> </ol></li> <li><p>CPU affinity: It's better for the CPU to have a load average of 1.0 and processes to have affinity to a single core. Doing so maximizes the use of the CPU cache and minimizes task switching overheads. By separating the DB and processing nodes, you are enforcing this affinity in HW.</p></li> </ol> <p><strong>500 concurrency with exceptions</strong> The request queue in the diagram above is at most 100 - if uwsgi receives a request when the queue is full, the request is rejected with a 5xx error. I think this was happening in your 500 concurrency load test - basically the queue filled up with the first 100 or so threads, then the other 400 threads issued the remaining 900 requests and received immediate 5xx errors. </p> <p>To handle 500 requests per second you need to ensure two things:</p> <ol> <li>The Request Queue size is configured to handle the burst: Use the <code>--listen</code> argument to <code>uwsgi</code></li> <li>The system can handle a throughput at above 500 requests per second if 500 is a normal condition, or a bit below if 500 is a peak. See scaling notes below.</li> </ol> <p>I imagine that uwsgi has the queue set to a smaller number to better handle DDoS attacks; if placed under huge load, most requests immediately fail with almost no processing allowing the box as a whole to still be responsive to the administrators. </p> <p><strong>General advice for scaling a system</strong></p> <p>Your most important consideration is probably to <strong>maximize throughput</strong>. Another possible need to minimize response time, but I won't discuss this here. In maximising throughput, you are trying to maximize the <em>system</em>, not individual components; some local decreases might improve overall system throughput (for example, making a change that happens to add latency in the web tier <em>in order to improve performance of the DB</em> is a net gain).</p> <p>Onto specifics:</p> <ol> <li><strong>Move the DB to a separate machine</strong>. After this, profile the DB during your load test by running <code>top</code> and your favorite MySQL monitoring tool. You need to be able to profile . Moving the DB to a separate machine will introduce some additional latency (several ms) per request, so expect to slightly increase the number of processes at the web tier to keep the same throughput.</li> <li>Ensure that <code>uswgi</code> request queue is large enough to handle a burst of traffic using the <code>--listen</code> argument. This should be several times the maximum steady-state requests-per-second your system can handle.</li> <li><p>On the web/app tier: <strong>Balance the number of processes with the number of CPU cores</strong> and the inherent latency in the process. Too many processes slows performance, too few means that you'll never fully utilize the system resources. There is no fixed balancing point, as every application and usage pattern is different, so benchmark and adjust. As a guide, use the processes' latency, if each task has:</p> <ul> <li>0% latency, then you need 1 process per core</li> <li>50% latency (i.e. the CPU time is half the actual time), then you need 2 processes per core</li> <li>67% latency, then you need 3 processes per core</li> </ul></li> <li><p>Check <code>top</code> during the test to ensure that you are above 90% cpu utilisation (for every core) <em>and</em> you have a load average a little above 1.0. If the load average is higher, scale back the processes. If all goes well, at some point you won't be able to achieve this target, and DB might now be the bottleneck</p></li> <li>At some point you will need more power in the web tier. You can either choose to add more CPU to the machine (relatively easy) and so add more processes, <strong>and/or</strong> you can add in more processing nodes (horizontal scaleability). The latter can be achieved in uwsgi using the method discussed <a href="https://stackoverflow.com/a/15050495/1395668">here</a> by <a href="https://stackoverflow.com/users/1154047/ukasz-mierzwa">Łukasz Mierzwa</a></li> </ol>
14,940,574
What do scale and precision mean when specifying a decimal field type in Doctrine 2?
<p>I'm creating a decimal field to hold a financial figure in Doctrine2 for my Symfony2 application.</p> <p>Currently, it looks like this:</p> <pre><code>/** * @ORM\Column(type=&quot;decimal&quot;) */ protected $rate; </code></pre> <p>When I entered a value and said value was persisted to the database, it was rounded to an integer. I'm guessing that I need to set the precision and scale types for the field, but I need someone to explain exactly what they do?</p> <p>The <a href="http://doctrine-orm.readthedocs.org/en/latest/reference/annotations-reference.html#column" rel="noreferrer">Doctrine2 documentation</a> says:</p> <blockquote> <p>precision: The precision for a decimal (exact numeric) column (Applies only for decimal column)</p> <p>scale: The scale for a decimal (exact numeric) column (Applies only for decimal column)</p> </blockquote> <p>But that doesn't tell me an awful lot.</p> <p>I'm guessing precision is the number of decimal places to round to, so I assume that should be 2, but what is scale? Is scale the significant figures?</p> <p>Should my field declaration be this? :-</p> <pre><code>/** * @ORM\Column(type=&quot;decimal&quot;, precision=2, scale=4) */ protected $rate; </code></pre>
14,940,635
5
0
null
2013-02-18 16:13:06.3 UTC
11
2019-10-23 10:37:33.75 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
767,912
null
1
80
database|symfony|orm|types|doctrine-orm
74,625
<p>Doctrine uses types similar to the SQL types. Decimal happens to be a fixed precision type (unlike floats).</p> <p>Taken from the <a href="http://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html" rel="noreferrer">MySQL documentation</a>:</p> <blockquote> <p>In a DECIMAL column declaration, the precision and scale can be (and usually is) specified; for example:</p> <p>salary DECIMAL(5,2)</p> <p>In this example, 5 is the precision and 2 is the scale. The precision represents the number of significant digits that are stored for values, and the scale represents the number of digits that can be stored following the decimal point.</p> <p>Standard SQL requires that DECIMAL(5,2) be able to store any value with five digits and two decimals, so values that can be stored in the salary column range from -999.99 to 999.99. </p> </blockquote>
27,980,373
How to use pagination in laravel 5?
<p>am trying to port my laravel4 application to laravel 5 . In the previous version i could use the following method for generating pagination urls .</p> <p><em>In controller</em>:</p> <pre><code>$this-&gt;data['pages']= Page::whereIn('area_id', $suburbs)-&gt;where('score','&gt;','0')-&gt;orderBy('score','desc')-&gt;paginate(12); </code></pre> <p>and after sharing the data array with the view, i could user </p> <p><em>In views</em> :</p> <pre><code>{{$pages-&gt;links()}} </code></pre> <p>In laravel 5 the doing that results in following error</p> <pre><code>ErrorException in AbstractPaginator.php line 445: call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Support\Collection' does not have a method 'links' </code></pre> <p>not sure what i am missing here, can somebody help ?</p>
27,987,515
8
4
null
2015-01-16 09:03:08.41 UTC
1
2022-05-01 07:47:51.733 UTC
null
null
null
null
939,299
null
1
34
php|laravel|pagination|laravel-5
101,228
<p>In Laravel 5 there is no method "links" you can try this</p> <pre><code>{!! $pages-&gt;render() !!} </code></pre>
8,990,216
HTML Rendering with TCPDF(PHP)
<p>I am using TCPDF's writeHtml function for a page that renders properly in the browser. In the output PDF, the fonts are too small. I've tried with setFont, but it doesn't seem to have an effect. Does anyone have experience with this?</p> <p>I'd like to add here that the HTML is not always in my control, so I would prefer to do this with TCPDF options(and not by modifying the source html)</p> <p><strong>UPDATE</strong>: I am able to change the font size by setting it on the body. The only remaining problem is that, to render correctly in the browser, it needs to be 12px. To render correctly in the PDF, it needs be something like 30px. Do I set the media on the css? What is the media type for TCPDF?</p>
8,990,380
3
3
null
2012-01-24 16:17:19.53 UTC
2
2013-06-20 07:00:11.8 UTC
2012-01-24 16:49:55.033 UTC
null
1,037,788
null
1,037,788
null
1
3
php|html|pdf|pdf-generation|tcpdf
38,927
<p>Are you using tags? tcpdf's HTML engine gives the <strong>tag precedence over any CSS</strong>, or other size-adjusting tags. If you remove any extraneous tags from the HTML and use straight CSS, things should render as expected. Or, if you aren't using CSS, you should. Just because a browser displays it correctly doesn't mean it will look the same on other formats. The browser has likely performed some magic of its own to fill in the gaps in your CSS specifications.</p> <hr> <p><strong>UPDATE</strong></p> <p>Here's an example of specifying CSS declarations with your HTML when using tcpdf. Note how all the styling is applied using the CSS declarations inside the <code>&lt;style&gt;</code> tag outside the actualy HTML body.</p> <pre><code>&lt;?php $html = &lt;&lt;&lt;EOF &lt;!-- EXAMPLE OF CSS STYLE --&gt; &lt;style&gt; h1 { color: navy; font-family: times; font-size: 24pt; text-decoration: underline; } p { color: red; font-family: helvetica; font-size: 12pt; } &lt;/style&gt; &lt;body&gt; &lt;h1&gt;Example of &lt;i&gt;HTML + CSS&lt;/i&gt;&lt;/h1&gt; &lt;p&gt;Example of 12pt styled paragraph.&lt;/p&gt; &lt;/body&gt; EOF; $pdf-&gt;writeHTML($html, true, false, true, false, ''); ?&gt; </code></pre>
8,955,869
why is plotting with Matplotlib so slow?
<p>I'm currently evaluating different python plotting libraries. Right now I'm trying matplotlib and I'm quite disappointed with the performance. The following example is modified from <a href="http://www.scipy.org/Cookbook/Matplotlib/Animations" rel="noreferrer">SciPy examples</a> and gives me only ~ 8 frames per second!</p> <p>Any ways of speeding this up or should I pick a different plotting library? </p> <pre><code>from pylab import * import time ion() fig = figure() ax1 = fig.add_subplot(611) ax2 = fig.add_subplot(612) ax3 = fig.add_subplot(613) ax4 = fig.add_subplot(614) ax5 = fig.add_subplot(615) ax6 = fig.add_subplot(616) x = arange(0,2*pi,0.01) y = sin(x) line1, = ax1.plot(x, y, 'r-') line2, = ax2.plot(x, y, 'g-') line3, = ax3.plot(x, y, 'y-') line4, = ax4.plot(x, y, 'm-') line5, = ax5.plot(x, y, 'k-') line6, = ax6.plot(x, y, 'p-') # turn off interactive plotting - speeds things up by 1 Frame / second plt.ioff() tstart = time.time() # for profiling for i in arange(1, 200): line1.set_ydata(sin(x+i/10.0)) # update the data line2.set_ydata(sin(2*x+i/10.0)) line3.set_ydata(sin(3*x+i/10.0)) line4.set_ydata(sin(4*x+i/10.0)) line5.set_ydata(sin(5*x+i/10.0)) line6.set_ydata(sin(6*x+i/10.0)) draw() # redraw the canvas print 'FPS:' , 200/(time.time()-tstart) </code></pre>
8,956,211
5
4
null
2012-01-21 19:11:13.33 UTC
82
2018-10-20 09:12:19.423 UTC
2017-02-14 10:10:51.003 UTC
null
1,079,075
null
561,766
null
1
124
python|matplotlib
168,070
<p>First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import time x = np.arange(0, 2*np.pi, 0.01) y = np.sin(x) fig, axes = plt.subplots(nrows=6) styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-'] lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)] fig.show() tstart = time.time() for i in xrange(1, 20): for j, line in enumerate(lines, start=1): line.set_ydata(np.sin(j*x + i/10.0)) fig.canvas.draw() print 'FPS:' , 20/(time.time()-tstart) </code></pre> <p>With the above example, I get around 10fps. </p> <p>Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display.</p> <p>However, there are a lot of things you can do to speed this example up.</p> <p>There are two main reasons why this is as slow as it is. </p> <p>1) Calling <code>fig.canvas.draw()</code> redraws <em>everything</em>. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc. </p> <p>2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw. </p> <p>Both these can be fixed by using blitting.</p> <p>To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue.</p> <p>However, without knowing a bit more about what you're doing, I can't help you there.</p> <p>Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import time x = np.arange(0, 2*np.pi, 0.1) y = np.sin(x) fig, axes = plt.subplots(nrows=6) fig.show() # We need to draw the canvas before we start animating... fig.canvas.draw() styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-'] def plot(ax, style): return ax.plot(x, y, style, animated=True)[0] lines = [plot(ax, style) for ax, style in zip(axes, styles)] # Let's capture the background of the figure backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes] tstart = time.time() for i in xrange(1, 2000): items = enumerate(zip(lines, axes, backgrounds), start=1) for j, (line, ax, background) in items: fig.canvas.restore_region(background) line.set_ydata(np.sin(j*x + i/10.0)) ax.draw_artist(line) fig.canvas.blit(ax.bbox) print 'FPS:' , 2000/(time.time()-tstart) </code></pre> <p>This gives me ~200fps.</p> <p>To make this a bit more convenient, there's an <code>animations</code> module in recent versions of matplotlib.</p> <p>As an example:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np x = np.arange(0, 2*np.pi, 0.1) y = np.sin(x) fig, axes = plt.subplots(nrows=6) styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-'] def plot(ax, style): return ax.plot(x, y, style, animated=True)[0] lines = [plot(ax, style) for ax, style in zip(axes, styles)] def animate(i): for j, line in enumerate(lines, start=1): line.set_ydata(np.sin(j*x + i/10.0)) return lines # We'd normally specify a reasonable "interval" here... ani = animation.FuncAnimation(fig, animate, xrange(1, 200), interval=0, blit=True) plt.show() </code></pre>
5,243,398
Will a using block close a database connection?
<pre><code>using (DbConnection conn = new DbConnection()) { // do stuff with database } </code></pre> <p>Will the <code>using</code> block call <code>conn.Close()</code>?</p>
5,243,420
4
0
null
2011-03-09 09:03:08.603 UTC
7
2019-12-25 21:38:55.157 UTC
2012-07-05 05:03:39.19 UTC
null
106,224
null
626,023
null
1
48
c#|database|using
28,092
<p>Yes, it will; the implementation of <code>DbConnection.Dispose()</code> calls <code>Close()</code> (and so do its derived implementations).</p>
5,098,580
implementing argmax in Python
<p>How should argmax be implemented in Python? It should be as efficient as possible, so it should work with iterables.</p> <p>Three ways it could be implemented:</p> <ul> <li>given an iterable of pairs return the key corresponding to the greatest value</li> <li>given an iterable of values return the index of the greatest value</li> <li>given an iterable of keys and a function <code>f</code>, return the key with largest <code>f(key)</code></li> </ul>
5,098,586
5
7
null
2011-02-23 23:22:44.85 UTC
9
2016-06-05 14:48:04.637 UTC
2011-02-24 00:00:53.287 UTC
null
99,989
null
99,989
null
1
25
python|itertools
18,790
<p>I modified the best solution I found:</p> <pre><code># given an iterable of pairs return the key corresponding to the greatest value def argmax(pairs): return max(pairs, key=lambda x: x[1])[0] # given an iterable of values return the index of the greatest value def argmax_index(values): return argmax(enumerate(values)) # given an iterable of keys and a function f, return the key with largest f(key) def argmax_f(keys, f): return max(keys, key=f) </code></pre>
4,873,873
Realtime currency webservice
<p>Anyone know of a real-time currency rate webservice with frequent update (multiple pr. min.). Needed for a small android app I'm building, so needs to be free.</p>
4,873,958
6
1
null
2011-02-02 11:26:07.673 UTC
10
2021-02-10 11:48:45.163 UTC
2013-01-19 19:28:00.52 UTC
null
356,440
null
45,687
null
1
20
web-services|currency|rate
52,687
<p>You can try Yahoo. It is free and easy to use. </p> <p>For example, to convert from GBP to EUR: <a href="http://download.finance.yahoo.com/d/quotes.csv?s=GBPEUR=X&amp;f=sl1d1t1ba&amp;e=.csv" rel="noreferrer">http://download.finance.yahoo.com/d/quotes.csv?s=GBPEUR=X&amp;f=sl1d1t1ba&amp;e=.csv</a></p> <p>gives you data in csv format which can easily be parsed.</p>
4,952,568
Is there a way to lower Java heap when not in use?
<p>I'm working on a Java application at the moment and working to optimize its memory usage. I'm following the guidelines for proper garbage collection as far as I am aware. However, it seems that my heap seems to sit at its maximum size, even though it is not needed.</p> <p>My program runs a resource intensive task once an hour, when the computer is not in use by a person. This task uses a decent chunk of memory, but then frees it all immediately after the task completes. The NetBeans profiler reveals that memory usage looks like this:</p> <p><img src="https://i.stack.imgur.com/YC2cf.png" alt="Java program memory usage"></p> <p>I'd really like to give all of that heap space back to the OS when not in use. There is no reason for me to hog it all while the program won't even be doing anything for at least another hour.</p> <p>Is this possible? Thanks.</p>
4,952,645
7
14
null
2011-02-10 01:40:00.92 UTC
21
2021-11-16 16:51:56.977 UTC
2021-11-16 16:51:56.977 UTC
null
5,459,839
null
97,964
null
1
59
java|memory-management|heap-memory
29,473
<p>You could perhaps play around with <code>-XX:MaxHeapFreeRatio</code> - this is the maximum percentage (default 70) of the heap that is free before the GC shrinks it. Perhaps setting it a bit lower (40 or 50?) and then using <code>System.gc()</code> might go some lengths to get you the desired behaviour?</p> <p>There's no way to force this to happen however, you can try and encourage the JVM to do so but you can't just yank memory away as and when you want to. And while the above may shrink the heap, that memory won't necessarily be handed straight back to the OS (though in recent implementations of the JVM it does.)</p>
5,264,949
Cannot push Git to remote repository with http/https
<p>I have a Git repository in a directory served by apache on a server. I have configured WebDAV and it seems to be running correctly. Litmus returns 100% success.</p> <p>I can clone my repository from a remote host, but when trying to push over http or https, I get the following error:</p> <p><em>error: Cannot access URL <a href="https://git.example.com/repo/" rel="noreferrer">https://git.example.com/repo/</a>, return code 22 fatal: git-http-push failed</em></p> <p>Any idea?</p>
5,265,730
8
0
null
2011-03-10 19:39:19.35 UTC
14
2018-09-24 16:35:14.753 UTC
null
null
null
null
654,179
null
1
25
git|http|https|push
71,901
<p>It is highly suggested NOT to use WebDAV if possible. If you must use HTTP/HTTPS then usage of the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-http-backend.html" rel="noreferrer">git-http-backend</a> CGI script is recommended over WebDAV.</p>
4,966,430
Rails 2: Model.find(1) gives ActiveRecord error when id 1 does not exist
<p>I am using Rails 2.3.5 and in that if I give <code>Model.find(1)</code> and if 1 is not in the database, it returns ActiveRecord error. Should it just be returning <code>nil</code> as in the case of <code>Model.find_by_column('..')</code>?</p>
4,966,553
8
1
null
2011-02-11 07:01:18.06 UTC
6
2016-12-19 11:50:18.283 UTC
2015-07-28 10:46:35.687 UTC
null
3,919,805
null
584,440
null
1
31
ruby-on-rails|ruby-on-rails-2
22,417
<p>This is the expected behavior. I think David explains this the best himself, so here is a quote from Ruby, S., Thomas, D. &amp; Hansson, D.H., 2009. <a href="https://rads.stackoverflow.com/amzn/click/com/1934356166" rel="noreferrer" rel="nofollow noreferrer"><em>Agile Web Development with Rails</em></a>, Third Edition Third Edition., Pragmatic Bookshelf (p.330).</p> <blockquote> <p>When you use a finder driven by primary keys, you’re looking for a particular record. You expect it to exist. A call to Person.find(5) is based on our knowledge of the people table. We want the row with an id of 5. If this call is unsuccessful—if the record with the id of 5 has been destroyed—we’re in an exceptional situation. This mandates the raising of an exception, so Rails raises RecordNotFound. </p> <p>On the other hand, finders that use criteria to search are looking for a match. So, Person.find(:first, :conditions=>"name=’Dave’") is the equivalent of telling the database (as a black box) “Give me the first person row that has the name Dave.” This exhibits a distinctly different approach to retrieval; we’re not certain up front that we’ll get a result. It’s entirely possible the result set may be empty. Thus, returning nil in the case of finders that search for one row and an empty array for finders that search for many rows is the natural, nonexceptional response.</p> </blockquote>
5,557,889
Console.ReadLine() max length?
<p>When running a small piece of C# code, when I try to input a long string into <code>Console.ReadLine()</code> it seems to cut off after a couple of lines.</p> <p>Is there a max length to Console.Readline(), if so is there a way to increase that? <img src="https://i.stack.imgur.com/UxPOp.png" alt="enter image description here"></p>
5,557,919
10
4
null
2011-04-05 20:12:42.523 UTC
11
2018-09-15 18:46:28.557 UTC
2013-10-01 13:17:23.027 UTC
null
639,455
null
107,156
null
1
50
c#
35,761
<p>Without any modifications to the code it will only take a maximum of 256 characters ie; It will allow 254 to be entered and will reserve 2 for CR and LF.</p> <p>The following method will help to increase the limit:</p> <pre><code>private static string ReadLine() { Stream inputStream = Console.OpenStandardInput(READLINE_BUFFER_SIZE); byte[] bytes = new byte[READLINE_BUFFER_SIZE]; int outputLength = inputStream.Read(bytes, 0, READLINE_BUFFER_SIZE); //Console.WriteLine(outputLength); char[] chars = Encoding.UTF7.GetChars(bytes, 0, outputLength); return new string(chars); } </code></pre>
5,253,643
Cannot install RVM . Permission denied in /usr/local/rvm
<p>Based on my previous thread : <a href="https://stackoverflow.com/questions/4911504/rvm-installed-by-ruby-not-working">RVM installed by Ruby not working?</a> where i had installed RVM using the root user, I then had to entirely remove the RVM install and now i am installing as a user.</p> <p>So i did :</p> <ol> <li>Create a new user by doing : useradd newuser</li> <li>Follow the instructions on the RVM website and execute the command : bash &lt; &lt;( curl <a href="http://rvm.beginrescueend.com/releases/rvm-install-head" rel="nofollow noreferrer">http://rvm.beginrescueend.com/releases/rvm-install-head</a> )</li> </ol> <p>Now, i get the error : <strong>mkdir: cannot create directory `/usr/local/rvm': Permission denied</strong></p> <p>The new user i created does not have access to this directory. I manually tried creating the folder but the same error. Please help.</p> <p>EDIT : The original problem occured because i did not restart the terminal and it was still using the old settings.</p> <p>Now, I got a new problem : After installing RVM, i cannot run it and it gives me an error : rvm command not found.</p> <p>Here is the output of my ~/.bash_profile</p> <pre><code># .bash_profile # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi # User specific environment and startup programs PATH=$PATH:$HOME/bin export PATH [[ -s "$HOME/.rvm/scripts/rvm" ]] &amp;&amp; source "$HOME/.rvm/scripts/rvm" # This loads RVM into a shell session. </code></pre> <p>And here is output from ~/.bashrc file</p> <pre><code># .bashrc # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fi # User specific aliases and functions [[ -s "$HOME/.rvm/scripts/rvm" ]] &amp;&amp; source "$HOME/.rvm/scripts/rvm" # This loads RVM into a shell session. </code></pre>
5,254,159
12
4
null
2011-03-09 23:31:52.193 UTC
8
2016-11-17 10:25:34.027 UTC
2017-05-23 11:46:07.02 UTC
null
-1
null
278,851
null
1
21
ruby-on-rails|rvm
49,383
<p>RVM is easy to install, but you are making it harder by trying to mix and match installation types. You do NOT need to create a new user. When run, RVM will create a directory in your home directory: <code>~/.rvm</code>, and install everything inside it. That means you will have all the correct permissions. You do NOT need to be running as root, you do NOT need to use sudo. I'd recommend closing all your command-lines and open one fresh and start at your home directory. If you are running as root, log out, and log back in to your normal account. For a single-user install you do NOT need to be root.</p> <p>For a single user, using RVM as their Ruby sandbox, use <a href="https://rvm.io/rvm/install/#explained">the single-user installation docs</a>. Follow <em>ALL</em> the instructions on that page, <em>INCLUDING</em> the "Post Install" section.</p> <p>Close your terminal window, and reopen it. If you have correctly followed the instructions above, typing <code>rvm info</code> should spit out a template of what is to come once you install a Ruby instance. If you see nothing output, or get an error, then retrace your steps in the "Post Install" section, and go through the "Troubleshooting" section. Most of the problems people have occur because they didn't bother to read the directions.</p> <p>Once RVM is installed, type <code>rvm notes</code> and read what dependencies you need to install. If you do not add those files your Rubies installed will be missing functionality. They will work, but some of the creature comforts you'll hear about won't work and you will wonder why.</p> <p>After installing the dependencies you should be in good shape to install Rubies. Type <code>rvm list known</code> for all the Rubies RVM can install. If you want 1.8.7 type <code>rvm install 1.8.7</code>, and, similarly, <code>rvm install 1.9.2</code> for Ruby 1.9.2. If you want a particular revision you can add that, based on the ones in the list.</p> <p>It's important to periodically update RVM using <code>rvm get head</code>. That will add features, fix bugs, and tell RVM about new versions of Ruby it can install if you request.</p> <p>After installing a Ruby, type <code>rvm list</code> and it should show up in the list, looking something like this:</p> <pre> rvm rubies ruby-1.8.7-p334 [ x86_64 ] ruby-1.9.2-p180 [ x86_64 ] </pre> <p>Type <code>rvm use 1.9.2 --default</code> to set a default Ruby that will be sticky between logins. Use the version of whatever Ruby you want to default to if 1.9.2 doesn't float your boat. Once you've defined a default it should look something like:</p> <pre> rvm rubies ruby-1.8.7-p334 [ x86_64 ] => ruby-1.9.2-p180 [ x86_64 ] </pre> <p>Before you begin installing gems into a RVM-managed Ruby, read <a href="https://rvm.io/rubies/rubygems/">"RVM and RubyGems "</a>, in particular the part that says "DO NOT use sudo... ". I repeat. Do NOT use sudo to install any gems, in spite of what some blog or web page says. RVM's author knows better when it comes to working with RVM controlled Rubies. That is another mistake people use with RVM, again as a result of not reading the directions.</p> <p>On Mac OS, you'll need the latest version of XCode for your OS. Do NOT use the XCode that came with Snow Leopard on the DVD. It is buggy. Download and install a new version from <a href="http://developer.apple.com/technologies/xcode.html">Apple's Developer site</a>. It's a free download requiring a free registration. It's a big file, approximately 8GB, so you'll want to start it and walk away. Install XCode, and you should be ready to have RVM install Rubies.</p> <p>Finally, RVM installs easily, as will the Rubies you ask it to install. I have it on about four or five different machines and VMs on Mac OS, Ubuntu and CentOS. It takes me about a minute to install it and another minute to configure it and start installing a new Ruby. It really is that easy.</p>
4,915,462
How should I do floating point comparison?
<p>I'm currently writing some code where I have something along the lines of:</p> <pre class="lang-c# prettyprint-override"><code>double a = SomeCalculation1(); double b = SomeCalculation2(); if (a &lt; b) DoSomething2(); else if (a &gt; b) DoSomething3(); </code></pre> <p>And then in other places I may need to do equality:</p> <pre class="lang-c# prettyprint-override"><code>double a = SomeCalculation3(); double b = SomeCalculation4(); if (a == 0.0) DoSomethingUseful(1 / a); if (b == 0.0) return 0; // or something else here </code></pre> <p>In short, I have lots of floating point math going on and I need to do various comparisons for conditions. I can't convert it to integer math because such a thing is meaningless in this context.</p> <p>I've read before that floating point comparisons can be unreliable, since you can have things like this going on:</p> <pre class="lang-c# prettyprint-override"><code>double a = 1.0 / 3.0; double b = a + a + a; if ((3 * a) != b) Console.WriteLine("Oh no!"); </code></pre> <p><strong>In short, I'd like to know: How can I reliably compare floating point numbers (less than, greater than, equality)?</strong></p> <p>The number range I am using is roughly from 10E-14 to 10E6, so I do need to work with small numbers as well as large.</p> <p>I've tagged this as language agnostic because I'm interested in how I can accomplish this no matter what language I'm using.</p>
4,915,891
12
5
null
2011-02-06 19:12:11.023 UTC
53
2021-03-22 16:26:56.93 UTC
2016-04-03 09:43:12.633 UTC
null
995,714
null
312,124
null
1
111
language-agnostic|comparison|floating-point
106,569
<p>Comparing for greater/smaller is not really a problem unless you're working right at the edge of the float/double precision limit.</p> <p>For a "fuzzy equals" comparison, this (Java code, should be easy to adapt) is what I came up with for <a href="http://floating-point-gui.de/errors/comparison/" rel="noreferrer">The Floating-Point Guide</a> after a lot of work and taking into account lots of criticism:</p> <pre class="lang-java prettyprint-override"><code>public static boolean nearlyEqual(float a, float b, float epsilon) { final float absA = Math.abs(a); final float absB = Math.abs(b); final float diff = Math.abs(a - b); if (a == b) { // shortcut, handles infinities return true; } else if (a == 0 || b == 0 || diff &lt; Float.MIN_NORMAL) { // a or b is zero or both are extremely close to it // relative error is less meaningful here return diff &lt; (epsilon * Float.MIN_NORMAL); } else { // use relative error return diff / (absA + absB) &lt; epsilon; } } </code></pre> <p>It comes with a test suite. You should immediately dismiss any solution that doesn't, because it is virtually guaranteed to fail in some edge cases like having one value 0, two very small values opposite of zero, or infinities.</p> <p>An alternative (see link above for more details) is to convert the floats' bit patterns to integer and accept everything within a fixed integer distance.</p> <p>In any case, there probably isn't any solution that is perfect for all applications. Ideally, you'd develop/adapt your own with a test suite covering your actual use cases.</p>
29,789,204
Bash: how to get real path of a symlink?
<p>Is it possible, executing a file symlinked in <code>/usr/local/bin</code> folder, to get the absolute path of original script? Well, .. I know where original file is, and I know it because I am linkging it. But, ... I want this script working, even if I move original source code (and symlink).</p> <pre><code>#!/bin/bash echo &quot;my path is ...&quot; </code></pre>
29,789,399
3
6
null
2015-04-22 06:14:32.407 UTC
6
2021-07-12 12:39:07.27 UTC
2021-07-12 12:39:07.27 UTC
null
4,298,200
null
1,420,625
null
1
38
bash|symlink
53,889
<p><code>readlink</code> is not a standard command, but it's common on Linux and BSD, including OS X, and it's the most straightforward answer to your question. BSD and GNU readlink implementations are different, so read the documentation for the one you have.</p> <p>If <code>readlink</code> is not available, or you need to write a cross-platform script that isn't bound to a specific implementation:</p> <p>If the symlink is also a directory, then</p> <pre><code>cd -P "$symlinkdir" </code></pre> <p>will get you into the dereferenced directory, so</p> <pre><code>echo "I am in $(cd -P "$symlinkdir" &amp;&amp; pwd)" </code></pre> <p>will echo the fully dereferenced directory. That said, <code>cd -P</code> dereferences the entire path, so if you have more than one symlink in the same path you can have unexpected results.</p> <p>If the symlink is to a file, not a directory, you may not need to dereference the link. Most commands follow symlinks harmlessly. If you simply want to check if a file is a link, use <code>test -L</code>.</p>
12,615,904
g++ "because the following virtual functions are pure" with abstract base class
<p>Here is my example code which produces the error:</p> <pre><code>struct Impl { int data_size_; int find(int var){return 0;} int get(int rowid){return 0;} }; class Container { public: Container() {} virtual ~Container() {} virtual int get_size() = 0; virtual int get(int rowid) = 0; }; class SortedContainer : virtual public Container { public: virtual int find(int var) = 0; }; class ContainerImpl : public Container { protected: Impl impl_; public: int get_size() {return impl_.data_size_;} int get(int rowid) {return impl_.get(rowid);} }; class SortedContainerImpl : public SortedContainer, public ContainerImpl { private: typedef ContainerImpl Base; public: int find(int var){return Base::impl_.find(var);} }; ContainerImpl ci; SortedContainerImpl sci; </code></pre> <p>it seems "SortedContainerImpl" went wrong while "ContainerImpl" is fine.</p> <p>g++ complains:</p> <pre><code>example_b.cpp:42:21: error: cannot declare variable ‘sci’ to be of abstract type ‘SortedContainerImpl’ example_b.cpp:32:7: note: because the following virtual functions are pure within ‘SortedContainerImpl’: example_b.cpp:13:15: note: virtual int Container::get_size() example_b.cpp:14:15: note: virtual int Container::get(int) </code></pre> <p>I inheret SortedContainerImpl from ContainerImpl in order to reuse get_size() and get(int)</p> <p>I'm not familiar with c++, What's the nature of this problem and How can I fix it?</p> <p>Thanks all.</p>
12,616,108
2
0
null
2012-09-27 07:06:14.337 UTC
3
2022-05-30 02:30:28.077 UTC
null
null
null
null
1,000,290
null
1
11
c++|polymorphism|virtual-functions|diamond-problem
71,403
<p>Your <code>SortedContainerImpl</code> class has two separate <code>Container</code> base classes. One is virtual (via the <code>SortedContainer</code> class) and the other is non-virtual (via the <code>ContainerImpl</code> class).</p> <p><code>SortedContainerImpl</code> has concrete implementations of <code>Container::get_size()</code> and <code>Container::get(int)</code> for the base that comes in from <code>ContainerImpl</code>, but not for the virtual base that comes in via <code>SortedContainer</code>.</p> <p>One way to fix the problem is to give concrete implementations in <code>SortedContainerImpl</code>:</p> <pre><code>class SortedContainerImpl : public SortedContainer, public ContainerImpl { private: typedef ContainerImpl Base; public: int find(int var){return Base::impl_.find(var);} int get_size() {return ContainerImpl::get_size();} int get(int rowid) {return ContainerImpl::get(rowid);} }; </code></pre> <p>Another way would be to make <code>Container</code> a virtual base class of <code>ContainerImpl</code>, so <code>SortedContainerImpl</code> would only get the one, virtual, base <code>Container</code>:</p> <pre><code>class ContainerImpl : virtual public Container { protected: Impl impl_; public: int get_size() {return impl_.data_size_;} int get(int rowid) {return impl_.get(rowid);} }; </code></pre>
12,314,438
Self referencing loop in Json.Net JsonSerializer from custom JsonConverter (Web API)
<p>The project is an Asp.Net Web API web service.</p> <p>I have a type hierarchy that I need to be able to serialize to and from Json, so I have taken the code from this SO: <a href="https://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base">How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?</a>, and applied the converter to my hierarchy's base class; something like this (there's pseudo-code here to hide irrelevancies):</p> <pre><code>[JsonConverter(typeof(TheConverter))] public class BaseType { // note the base of this type here is from the linked SO above private class TheConverter : JsonCreationConverter&lt;BaseType&gt; { protected override BaseType Create(Type objectType, JObject jObject) { Type actualType = GetTypeFromjObject(jObject); /*method elided*/ return (BaseType)Activator.CreateInstance(actualType); } } } public class RootType { public BaseType BaseTypeMember { get; set; } } public class DerivedType : BaseType { } </code></pre> <p>So if I deserialize a <code>RootType</code> instance whose <code>BaseTypeMember</code> was equal to an instance of <code>DerivedType</code>, then it will be deserialized back into an instance of that type.</p> <p>For the record, these JSON objects contain a <code>'$type'</code> field which contains virtual type names (not full .Net type names) so I can simultaneously support types in the JSON whilst controlling exactly which types can be serialized and deserialized.</p> <p>Now this works really well for deserializing values from the request; but I have an issue with serialization. If you look at the linked SO, and indeed the Json.Net discussion that is linked from the top answer, you'll see that the base code I'm using is entirely geared around deserialization; with examples of its use showing manual creation of the serializer. The <code>JsonConverter</code> implementation brought to the table by this <code>JsonCreationConverter&lt;T&gt;</code> simply throws a <code>NotImplementedException</code>.</p> <p>Now, because of the way that Web API uses a single formatter for a request, I need to implement 'standard' serialization in the <code>WriteObject</code> method.</p> <p>I must stress at this point that before embarking on this part of my project I had <strong><em>everything</em></strong> serializing properly <strong><em>without errors</em></strong>.</p> <p>So I did this: </p> <pre><code>public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value); } </code></pre> <p>But I get a <code>JsonSerializationException</code>: <code>Self referencing loop detected with type 'DerivedType'</code>, when one of the objects is serialized. Again - if I remove the converter attribute (disabling my custom creation) then it works fine...</p> <p>I have a feeling that this means that my serialization code is actually triggering the converter again on the same object, which in turn calls the serializer again - ad nauseam. <strong><em>Confirmed - see my answer</em></strong></p> <p>So what code <em>should</em> I be writing in <code>WriteObject</code> that'll do the same 'standard' serialization that works?</p>
12,315,435
7
2
null
2012-09-07 08:28:13.777 UTC
3
2018-06-22 07:09:52.033 UTC
2018-06-22 07:09:52.033 UTC
null
157,701
null
157,701
null
1
43
c#|asp.net-web-api|json.net
19,285
<p>Well this was fun...</p> <p>When I looked more closely at the stack trace for the exception, I noticed that the method <code>JsonSerializerInternalWriter.SerializeConvertable</code> was in there twice, indeed it was that method one off the top of the stack - invoking <code>JsonSerializerInternalWriter.CheckForCircularReference</code> - which in turn was throwing the exception. It was also, however, the source of the call to my own converter's <code>Write</code> method.</p> <p>So it would seem that the serializer was doing:</p> <ul> <li>1) If object has a converter <ul> <li>1a) Throw if circular reference</li> <li>1b) Invoke converter's Write method</li> </ul></li> <li>2) Else <ul> <li>2a) Use internal serializers</li> </ul></li> </ul> <p>So, in this case, the Json.Net is calling my converter which in turn is calling the Json.Net serializer which then blows up because it sees it's already serializing the object that was passed to it!</p> <p>Opening ILSpy on the DLL (yes I know it's open source - but I want the 'callers' functionality!) and moving up the call stack from <code>SerializeConvertable</code> to <code>JsonSerializerInternalWriter.SerializeValue</code>, the code that detects whether a converter should be used can be found right near the start:</p> <pre><code>if (((jsonConverter = ((member != null) ? member.Converter : null)) != null || (jsonConverter = ((containerProperty != null) ? containerProperty.ItemConverter : null)) != null || (jsonConverter = ((containerContract != null) ? containerContract.ItemConverter : null)) != null || (jsonConverter = valueContract.Converter) != null || (jsonConverter = this.Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null || (jsonConverter = valueContract.InternalConverter) != null) &amp;&amp; jsonConverter.CanWrite) { this.SerializeConvertable(writer, jsonConverter, value, valueContract, containerContract, containerProperty); return; } </code></pre> <p>Thankfully that very last condition in the <code>if</code> statement provides the solution to my issue: all I had to do was to add the following to either the base converter copied from the code in the linked SO in the question, or in the derived one:</p> <pre><code>public override bool CanWrite { get { return false; } } </code></pre> <p>And now it all works fine.</p> <p>The upshot of this, however, is that if you intend to have some custom JSON serialization on an object and you are injecting it with a converter <strong><em>and</em></strong> you intend to fallback to the standard serialization mechanism under some or all situations; then you can't because you will fool the framework into thinking you're trying to store a circular reference.</p> <p>I did try manipulating the <code>ReferenceLoopHandling</code> member, but if I told it to <code>Ignore</code> them then nothing was serialized and if I told it to save them, unsurprisingly, I got a stack overflow.</p> <p>It's possible that this is a bug in Json.Net - alright it's so much of an edge-case that it's in danger of falling off the edge of the universe - but if you do find yourself in this situation then you're kind of stuck!</p>
12,070,631
how to use json file in html code
<p>I have json file <code>mydata.json</code>, and in this file is some json-encoded data.</p> <p>I want obtain this data in file <code>index.html</code> and process this data in JavaScript. But a don't know how to connect.json file in .html file?</p> <p>Tell me please. Here is my <strong>json</strong> file:</p> <pre><code>{ "items": [ { "movieID": "65086", "title": "The Woman in Black", "poster": "/kArMj2qsOnpxBCpSa3RQ0XemUiX.jpg" }, { "movieID": "76726", "title": "Chronicle", "poster": "/853mMoSc5d6CH8uAV9Yq0iHfjor.jpg" } ] } </code></pre> <p>Thinking that I am getting json file from server, how to use that file in my html, so that I can display the data in tables in html page. I am using JavaScript to parse the json file. I am new to this field. Help out please.</p>
12,091,134
5
3
null
2012-08-22 09:57:04.953 UTC
32
2022-06-06 10:58:49.673 UTC
2013-05-22 13:10:18.237 UTC
null
2,139,775
null
1,595,415
null
1
67
javascript|jquery|html|json|get
364,419
<pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"&gt; &lt;/script&gt; &lt;script&gt; $(function() { var people = []; $.getJSON('people.json', function(data) { $.each(data.person, function(i, f) { var tblRow = "&lt;tr&gt;" + "&lt;td&gt;" + f.firstName + "&lt;/td&gt;" + "&lt;td&gt;" + f.lastName + "&lt;/td&gt;" + "&lt;td&gt;" + f.job + "&lt;/td&gt;" + "&lt;td&gt;" + f.roll + "&lt;/td&gt;" + "&lt;/tr&gt;" $(tblRow).appendTo("#userdata tbody"); }); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="wrapper"&gt; &lt;div class="profile"&gt; &lt;table id= "userdata" border="2"&gt; &lt;thead&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;th&gt;Email Address&lt;/th&gt; &lt;th&gt;City&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My <code>JSON</code> file:</p> <pre><code>{ "person": [ { "firstName": "Clark", "lastName": "Kent", "job": "Reporter", "roll": 20 }, { "firstName": "Bruce", "lastName": "Wayne", "job": "Playboy", "roll": 30 }, { "firstName": "Peter", "lastName": "Parker", "job": "Photographer", "roll": 40 } ] } </code></pre> <p>I succeeded in integrating a <code>JSON</code> file to <code>HTML</code> table after working a day on it!!!</p>
12,333,624
Can I use the same id in different layout in Android?
<p>I am new to Android development. Is it fine to use the same ID for images and <code>TextViews</code> in different <code>Layout</code> XML files?</p> <p>When eclipse auto-list them for me, it lists all the layout variables from the project, so will it collide? Till now I have not noticed any problems using the same ID in different layouts, but I am concerned in long run.</p>
12,333,737
4
2
null
2012-09-08 19:03:51.193 UTC
16
2022-01-12 11:28:39.933 UTC
2012-09-08 19:24:46.783 UTC
null
2,621,536
null
162,223
null
1
99
android|android-layout
39,304
<p>It is recommended that you use different ids for different layouts. On the long run, when you will have a lot of layouts and therefor a lot of ids it will get very complicated to differentiate them. </p> <p>I usually name my ids like this: <code>layoutName_elementId</code>. </p> <p>It works for me to easily find the id I'm looking for, especially when using autocomplete (I know on what layout I'm working, but I don't really know the id; in this case, with my naming strategy, I only type the layout name and it brings on all the ids of that layout). </p> <p>More information on layouts and ids can be found <a href="http://developer.android.com/guide/topics/ui/declaring-layout.html#id" rel="noreferrer">here</a>.</p> <p>Happy coding,</p>
44,249,419
I have got an AMD Ryzen CPU and Android emulator doesn't work
<p>I have got an AMD Ryzen CPU and Android emulator doesn't work. It doesn't start the emulator becouse the CPU doesn't support the x86 emulator</p>
45,550,230
10
5
null
2017-05-29 19:36:38.997 UTC
12
2020-04-25 22:42:11.893 UTC
2019-04-21 20:50:38.933 UTC
null
6,296,561
null
8,083,150
null
1
31
android-emulator|emulation
84,823
<p><strong>Update</strong> - My previous answer is no longer true. Google has added AMD and Hyper-V support into their latest beta. Thanks to <a href="https://stackoverflow.com/users/2214180/reversecold">ReverseCold</a> for letting me know. Please see <a href="https://stackoverflow.com/a/51548499/3107922">his answer below.</a></p> <p><strong>Update 2</strong> - I had to set this up today. To save some googling, here is the powershell command to enable Hyper-V. Pulled from <a href="https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/enable-hyper-v" rel="noreferrer">Microsoft's Docs</a></p> <pre class="lang-coffee prettyprint-override"><code>Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All </code></pre> <p>Make sure to run powershell as an administrator.</p> <p><strong>Update 3</strong> - Turns out there's a difference between <strong>Windows Hypervisor Platform</strong> and <strong>Hyper-V</strong>. You'll need to enable the first one for Android emulation to work. Just click start and type <em>Turn Windows features on or off</em> until you see the control panel option of the same name. Then enable the feature from the menu that pops up after clicking that.</p> <hr> <p>According to <a href="https://stackoverflow.com/questions/25263360/intels-haxm-equivalent-for-amd-on-windows-os">This answer</a>, AMD virtualization for Android is only supported on Linux. If Ryzen becomes hugely popular, maybe they'll write one for Windows, but I won't be holding my breath.</p>
24,327,544
How can clear screen in php cli (like cls command)
<p>When PHP script run from command line (windows) , how can clear the console screen from script . </p> <p>for example : </p> <pre><code>while(true){ // sleep for 10 seconds , then clear the console sleep(10); // below command execute to clear the console windows **COMMAND** } </code></pre>
29,193,143
4
5
null
2014-06-20 12:41:54.68 UTC
4
2017-11-18 12:42:57.05 UTC
null
null
null
null
951,440
null
1
27
php|windows
43,215
<p>For Windows users : </p> <pre><code>system('cls'); </code></pre> <p>For Linux users : </p> <pre><code>system('clear'); </code></pre>
8,612,266
Why can't DirectX/DirectWrite/Direct2D text rendering be as sharp as GDI?
<p>I already know that sub-pixel positioning causes <a href="http://blog.mozilla.com/nattokirai/2011/08/11/directwrite-text-rendering-in-firefox-6/" rel="nofollow noreferrer">DirectWrite text rendering to be blurry compared to GDI</a>.</p> <p>However, my question is a bit more fundamental: <strong><em>Why</em> can't DirectWrite (and related methods) be made to render text as sharply as GDI?</strong></p> <p>In other words:<br /> <em>What prevents</em> DirectWrite from being able to snap text to the nearest pixel, the way GDI can?</p> <p>Is it, for example, a hardware issue? A driver architecture issue? Is it simply not implemented? Or something else?</p> <hr /> <h3>Smaller sample:</h3> <p><img src="https://i.stack.imgur.com/cKVxW.png" alt="" /></p> <h3>Larger samples:</h3> <p>Direct2D, aliased:</p> <p><img src="https://i.stack.imgur.com/zUUU0.png" alt="" /></p> <p>Direct2D, default:</p> <p><img src="https://i.stack.imgur.com/94z4R.png" alt="" /></p> <p>Direct2D (&quot;classic GDI&quot;):</p> <p><img src="https://i.stack.imgur.com/ACOTu.png" alt="" /></p> <p>Direct2D (&quot;natural GDI&quot;):</p> <p><img src="https://i.stack.imgur.com/4YN2N.png" alt="" /></p> <p><em>Actual</em> classic GDI:</p> <p><a href="https://i.stack.imgur.com/WqlgV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WqlgV.png" alt="![](http://i.stack.imgur.com/kbdPb.png)" /></a></p> <p><em>Actual</em> ClearType GDI:</p> <p><a href="https://i.stack.imgur.com/xLVYs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xLVYs.png" alt="enter image description here" /></a></p> <hr /> <p><strong>Note: If <em>all</em> of these look blurry to you</strong>, run</p> <pre><code>document.body.style.zoom = 1 / window.devicePixelRatio </code></pre> <p>in Chrome's console and view it afterward.</p>
8,663,198
1
11
null
2011-12-23 04:31:34.343 UTC
10
2021-10-14 04:37:46.203 UTC
2021-10-14 04:37:46.203 UTC
user5483294
541,686
null
541,686
null
1
22
winapi|directx|gdi|smoothing|text-rendering
7,039
<p>You aren't comparing like with like. Your Direct2D samples are all rendered in grayscale, whereas the GDI and Linux samples are using sub-pixel anti-aliasing (aka ClearType on Windows).</p> <p>This page describes what you need to do to enable cleartype: <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd368170%28v=vs.85%29.aspx">http://msdn.microsoft.com/en-us/library/windows/desktop/dd368170%28v=vs.85%29.aspx</a></p> <p>N.B. When testing rendering like this, it's always worth using Windows Magnifier or similar to check that you are actually getting what you think you are getting.</p>
8,492,121
IE8 :nth-child and :before
<p>Here is my CSS:</p> <pre><code>#nav-primary ul li:nth-child(1) a:after { } </code></pre> <p>Works everywhere now (used <a href="http://code.google.com/p/ie7-js/" rel="noreferrer">this</a> on my website) except Internet Explorer 8...</p> <p>Is there possibly a way to use nth-child in IE8? This is the worst version of this browser... nothing works as it should and I can't find a way to fix it.</p> <p>@edit: Simplified version of what I want to achieve: <a href="http://jsfiddle.net/LvvNL/" rel="noreferrer">http://jsfiddle.net/LvvNL/</a>. Its just a start. CSS will be more complicated so I need to be able to aim every one of this links. Hope adding classes to every link is not the only way</p> <p>@edit2: I've just noticed that </p> <pre><code>#nav-primary ul li:nth-child(1) a { border-top: 5px solid #144201; } </code></pre> <p>IS actually working in IE8! But this:</p> <pre><code>#nav-primary ul li:nth-child(1) a:after { content: "Text"; display: block; font-weight: normal; padding-top: 5px; font-size: 12px; color: #666; } </code></pre> <p>is NOT working. So what is going on?</p>
8,492,882
6
11
null
2011-12-13 15:54:34.377 UTC
43
2014-07-17 13:11:57.217 UTC
2011-12-13 16:44:53.42 UTC
null
704,247
null
704,247
null
1
65
css|internet-explorer-8|css-selectors
82,299
<p>You can (ab)use the <a href="http://reference.sitepoint.com/css/adjacentsiblingselector" rel="noreferrer">adjacent sibling combinator (<code>+</code>)</a> to achieve this with CSS that works in IE7/8.</p> <p><strong>See:</strong> <a href="http://jsfiddle.net/thirtydot/LvvNL/64/" rel="noreferrer">http://jsfiddle.net/thirtydot/LvvNL/64/</a></p> <pre class="lang-css prettyprint-override"><code>/* equivalent to li:nth-child(1) */ #nav-primary ul li:first-child a { border-top: 5px solid red; } /* equivalent to li:nth-child(2) */ #nav-primary ul li:first-child + li a { border-top: 5px solid blue; } /* equivalent to li:nth-child(3) */ #nav-primary ul li:first-child + li + li a { border-top: 5px solid green; }​ </code></pre> <p>You cannot emulate more complex variations of <code>:nth-child()</code> such as <code>:nth-child(odd)</code> or <code>:nth-child(4n+3)</code> with this method.</p>
22,646,747
EventBus/PubSub vs (reactive extensions) RX with respect to code clarity in a single threaded application
<p>Currently, I am using an EventBus/<a href="http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern" rel="noreferrer">PubSub</a> architecture/pattern with Scala (and JavaFX) to implement a simple note organizing app (sort of like an Evernote client with some added mind mapping functionality) and I have to say that I really like EventBus over the observer pattern. </p> <p>Here are some EventBus libraries : </p> <p><a href="https://code.google.com/p/guava-libraries/wiki/EventBusExplained" rel="noreferrer">https://code.google.com/p/guava-libraries/wiki/EventBusExplained</a></p> <p><a href="http://eventbus.org" rel="noreferrer">http://eventbus.org</a> (currently seems to be down) this is the one I am using in my implementation.</p> <p><a href="http://greenrobot.github.io/EventBus/" rel="noreferrer">http://greenrobot.github.io/EventBus/</a></p> <p>Here is a comparison of EventBus libraries : <a href="http://codeblock.engio.net/37/" rel="noreferrer">http://codeblock.engio.net/37/</a> </p> <p>EventBus is related to the <a href="http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern" rel="noreferrer">publish-subscribe pattern</a>.</p> <p><strong>However !</strong></p> <p>Recently, I took the <a href="https://www.coursera.org/course/reactive" rel="noreferrer">Reactive course by Coursera</a> and started to wonder whether using <a href="https://github.com/Netflix/RxJava" rel="noreferrer">RXJava</a> instead of EventBus would simplify the event handling code even more in a <strong>single threaded</strong> application ?</p> <p>I would like to ask about the experiences of people who programmed using both technologies (some kind of eventbus library <strong>and</strong> some form of the <a href="https://rx.codeplex.com" rel="noreferrer">reactive extensions</a> (RX)): was it easier to tackle event handling complexity using RX than with an event bus architecture <strong>given that there was no need to use multiple threads</strong> ? </p> <p>I am asking this because I have heard in the <a href="https://www.coursera.org/course/reactive" rel="noreferrer">Reactive Lectures on Coursera</a> that <a href="https://rx.codeplex.com" rel="noreferrer">RX</a> leads to much cleaner code than using the observer pattern (i.e. there is no "callback hell"), however I did not find any comparison between EventBus architecture vs <a href="https://github.com/Netflix/RxJava" rel="noreferrer">RXJava</a>. So it's clear that both EventBus and RXJava are better than the observer pattern but <strong>which is better in a single threaded applications</strong> in terms of code clarity and maintainability ?</p> <p>If I understand correctly the main selling point of <a href="https://github.com/Netflix/RxJava" rel="noreferrer">RXJava</a> is that it can be used to produce responsive applications if there are blocking operations (e.g. waiting for response from a server).</p> <p>But I don't care about asychronicity at all, all I care about is keeping the code clean, untangled and easy to reason about in a <strong>single threaded application</strong>.</p> <p>In that case, is it still better to use RXJava than EventBus ? </p> <p>I think EventBus would be a simpler and cleaner solution and I don't see any reason why I should use RXJava for a <strong>single threaded application</strong> in favour of a simple EventBus architecture. </p> <p><strong>But I might be wrong!</strong></p> <p>Please correct me if I am wrong and explain why RXJava would be better than a simple EventBus in case of a <strong>single threaded application</strong> where no blocking operations are carried out.</p>
25,024,898
4
15
null
2014-03-25 21:33:03.657 UTC
27
2020-06-11 13:55:51.993 UTC
2014-08-09 07:38:40.533 UTC
null
1,198,559
null
1,198,559
null
1
39
event-handling|system.reactive|reactive-programming|event-bus|rx-java
13,547
<p>The following is what I see as benefits of using reactive event streams in a <em>single-threaded synchronous</em> application.</p> <h2>1. More declarative, less side-effects and less mutable state.</h2> <p>Event streams are capable of encapsulating logic and state, potentially leaving your code without side-effects and mutable variables.</p> <p>Consider an application that counts button clicks and displays the number of clicks as a label.</p> <p><strong>Plain Java solution:</strong></p> <pre><code>private int counter = 0; // mutable field!!! Button incBtn = new Button("Increment"); Label label = new Label("0"); incBtn.addEventHandler(ACTION, a -&gt; { label.setText(Integer.toString(++counter)); // side-effect!!! }); </code></pre> <p><strong>ReactFX solution:</strong></p> <pre><code>Button incBtn = new Button("Increment"); Label label = new Label("0"); EventStreams.eventsOf(incBtn, ACTION) .accumulate(0, (n, a) -&gt; n + 1) .map(Object::toString) .feedTo(label.textProperty()); </code></pre> <p>No mutable variable is used and the side-effectful assignment to <code>label.textProperty()</code> is hidden behind an abstraction.</p> <p>In his master thesis, <a href="https://stackoverflow.com/users/283607/eugen">Eugen Kiss</a> has proposed integration of ReactFX with Scala. Using his integration, the solution could look like this:</p> <pre><code>val incBtn = new Button("Increment") val label = new Label("0") label.text |= EventStreams.eventsOf(incBtn, ACTION) .accumulate(0, (n, a) =&gt; n + 1) .map(n =&gt; n.toString) </code></pre> <p>It is equivalent to the previous, with the additional benefit of eliminating inversion of control.</p> <h2>2. Means to eliminate <em>glitches</em> and redundant computations. (ReactFX only)</h2> <p>Glitches are temporary inconsistencies in observable state. ReactFX has means to suspend event propagation until all updates to an object have been processed, avoiding both glitches and redundant updates. In particular, have a look at <a href="https://github.com/TomasMikula/ReactFX#suspendable-streams" rel="nofollow noreferrer">suspendable event streams</a>, <a href="https://github.com/TomasMikula/ReactFX#indicator" rel="nofollow noreferrer">Indicator</a>, <a href="https://github.com/TomasMikula/ReactFX/wiki/InhiBeans" rel="nofollow noreferrer">InhiBeans</a> and <a href="http://tomasmikula.github.io/blog/2014/05/13/how-to-ensure-consistency-of-your-observable-state.html" rel="nofollow noreferrer">my blog post about InhiBeans</a>. These techniques rely on the fact that event propagation is synchronous, therefore do not translate to rxJava.</p> <h2>3. Clear connection between event producer and event consumer.</h2> <p>Event bus is a global object that anyone can publish to and subscribe to. The coupling between event producer and event consumer is indirect and therefore less clear. With reactive event streams, the coupling between producer and consumer is much more explicit. Compare:</p> <p><strong>Event bus:</strong></p> <pre><code>class A { public void f() { eventBus.post(evt); } } // during initialization eventBus.register(consumer); A a = new A(); </code></pre> <p>The relationship between <code>a</code> and <code>consumer</code> is not clear from looking at just the initialization code.</p> <p><strong>Event streams:</strong></p> <pre><code>class A { public EventStream&lt;MyEvent&gt; events() { /* ... */ } } // during initialization A a = new A(); a.events().subscribe(consumer); </code></pre> <p>The relationship between <code>a</code> and <code>consumer</code> is very explicit.</p> <h2>4. Events published by an object are manifested in its API.</h2> <p>Using the example from the previous section, in the event bus sample, <code>A</code>'s API does not tell you what events are published by instances of <code>A</code>. On the other hand, in the event streams sample, <code>A</code>'s API states that instances of <code>A</code> publish events of type <code>MyEvent</code>.</p>
43,539,718
Interesting interview exercise result: return, post increment and ref behavior
<p>Here's a simple console application code, which returns a result I do not understand completely.</p> <p>Try to think whether it outputs 0, 1 or 2 in console:</p> <pre><code>using System; namespace ConsoleApplication { class Program { static void Main() { int i = 0; i += Increment(ref i); Console.WriteLine(i); Console.ReadLine(); } static private int Increment(ref int i) { return i++; } } } </code></pre> <p>The answer is 0.</p> <p>What I don't understand is why post increment <code>i++</code>, from the <code>Increment</code> method, which is executed on a <code>ref</code> (not on a copy of the passed variable) does increment the variable, but it just gets ignored later.</p> <p>What I mean is in this video:</p> <p><a href="https://www.screencast.com/t/DkBvGmJv" rel="noreferrer"><img src="https://i.stack.imgur.com/o0mWk.gif" alt=""></a></p> <p>Can somebody explain this example and why during debug I see that value is incremented to 1, but then it goes back to 0?</p>
43,540,033
3
10
null
2017-04-21 10:02:07.007 UTC
10
2017-04-22 11:28:45.2 UTC
2017-04-22 11:28:45.2 UTC
null
1,549,818
null
1,433,660
null
1
60
c#|increment|operator-precedence|ref
4,016
<p><code>i += Increment(ref i);</code> is equivalent to</p> <pre><code>i = i + Increment(ref i); </code></pre> <p>The expression on the right hand side of the assignment is evaluated from left to right, so the next step is</p> <pre><code>i = 0 + Increment(ref i); </code></pre> <p><code>return i++</code> returns the current value of <code>i</code> (which is 0), then increments <code>i</code></p> <pre><code>i = 0 + 0; </code></pre> <p>Before the assignment the value of <code>i</code> is 1 (incremented in the <code>Increment</code> method), but the assignment makes it 0 again.</p>
11,078,850
@XmlRegistry - how does it work?
<p>I have found some examples of JAXB2 <code>@XmlRegistry</code> over the internet but no good in-depth tutorials that talk about the concept of using <code>@XmlRegistry</code> with <code>@XmlElementDecl</code>, wonder if its a concept not much explored in general.</p> <p>Anyways here is my question, first some sample classes that I am using to unmarshall an xml using JAXB:</p> <p>The main class I am trying to unmarshal using JAXB - Employee.java</p> <pre><code>package com.test.jaxb; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.namespace.QName; import com.test.jaxb.dto.Address; @XmlRootElement public class Employee { private int id; private String name; private String email; private List&lt;Address&gt; addresses; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List&lt;Address&gt; getAddresses() { return addresses; } public void setAddresses(List&lt;Address&gt; addresses) { this.addresses = addresses; } @SuppressWarnings("unused") @XmlRegistry public static class XMLObjectFactory { @XmlElementDecl(scope = Employee.class, name= "id") JAXBElement&lt;String&gt; createEmployeeId(String value) { return new JAXBElement&lt;String&gt;(new QName("id"), String.class, "100"); } @XmlElementDecl(scope = Employee.class, name= "name") JAXBElement&lt;String&gt; createName(String value) { return new JAXBElement&lt;String&gt;(new QName("name"), String.class, "Fake Name"); } @XmlElementDecl(scope = Employee.class, name= "email") JAXBElement&lt;String&gt; createEmail(String value) { return new JAXBElement&lt;String&gt;(new QName("email"), String.class, value); } @XmlElementDecl(scope = Employee.class, name= "addresses") JAXBElement&lt;List&gt; createAddresses(List value) { return new JAXBElement&lt;List&gt;(new QName("addresses"), List.class, value); } } } </code></pre> <p>The child class - Address.java</p> <pre><code>package com.test.jaxb.dto; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.namespace.QName; import com.test.jaxb.Employee; @XmlRootElement public class Address { private String addressLine1; private String addressLine2; private String addressLine3; public String getAddressLine1() { return addressLine1; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getAddressLine3() { return addressLine3; } public void setAddressLine3(String addressLine3) { this.addressLine3 = addressLine3; } @SuppressWarnings("unused") @XmlRegistry private static class XMLObjectFactory { @XmlElementDecl(scope = Employee.class, name= "addressLine1") JAXBElement&lt;String&gt; createAddressLine1(String value) { return new JAXBElement&lt;String&gt;(new QName("addressLine1"), String.class, value); } @XmlElementDecl(scope = Employee.class, name= "addressLine2") JAXBElement&lt;String&gt; createAddressLine2(String value) { return new JAXBElement&lt;String&gt;(new QName("addressLine2"), String.class, value); } @XmlElementDecl(scope = Employee.class, name= "addressLine3") JAXBElement&lt;String&gt; createAddressLine3(String value) { return new JAXBElement&lt;String&gt;(new QName("addressLine3"), String.class, value); } } } </code></pre> <p>The xml to be unmarshalled - employee.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;employee&gt; &lt;id&gt;1&lt;/id&gt; &lt;name&gt;Vaishali&lt;/name&gt; &lt;email&gt;[email protected]&lt;/email&gt; &lt;addresses&gt; &lt;address&gt; &lt;addressLine1&gt;300&lt;/addressLine1&gt; &lt;addressLine2&gt;Mumbai&lt;/addressLine2&gt; &lt;addressLine3&gt;India&lt;/addressLine3&gt; &lt;/address&gt; &lt;address&gt; &lt;addressLine1&gt;301&lt;/addressLine1&gt; &lt;addressLine2&gt;Pune&lt;/addressLine2&gt; &lt;addressLine3&gt;India&lt;/addressLine3&gt; &lt;/address&gt; &lt;/addresses&gt; &lt;/employee&gt; </code></pre> <p>Unmarshalling Code : </p> <pre><code>package com.test.jaxb; import java.io.FileReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; public class ObjectFactoryTest { public static void main(String[] args) throws Exception { FileReader reader = new FileReader("resources/employee.xml"); JAXBContext context = JAXBContext.newInstance(Employee.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Object obj = unmarshaller.unmarshal(reader); System.out.println(obj); } } </code></pre> <p>When I unmarshal the employee xml using above code, the address list does not get populated. The resulting employee object only has a blank list of adresses. Is there anything wrong with my mappings?</p> <p>To find out what is going on and see if the employee objects are actually being created using the Object Factory (having the @XMLRegistry annotation), I changed the value of id and name in factory methods, however that had no effect in the output, which tells me JAXB is not actually using the ObjectFactory, why?</p> <p>Am I going aboout this all wrong? Any help would be appreciated.</p>
11,083,864
2
0
null
2012-06-18 07:54:14.837 UTC
13
2012-06-18 14:27:10.14 UTC
2012-06-18 08:38:56.453 UTC
null
1,401,148
null
1,401,148
null
1
11
java|xml|jaxb|jaxb2
25,213
<blockquote> <p>@XmlRegistry - how does it work?</p> </blockquote> <p><code>@XmlRegistry</code> is used to mark a class that has <code>@XmlElementDecl</code> annotations. To have your JAXB implementation process this class you need to ensure that it is included in the list of classes used to bootstrap the <code>JAXBContext</code>. It is not enough for it to be a static inner class of one of your domain model classes:</p> <pre><code>JAXBContext context = JAXBContext.newInstance(Employee.class, Employee.XMLObjectFactory.class); </code></pre> <blockquote> <p>@XmlElementDecl - how does it work?</p> </blockquote> <p>If the value of the field/property is going to be a <code>JAXBElement</code> then you need to leverage <code>@XmlElementDecl</code>. A <code>JAXBElement</code> captures information that is can be useful:</p> <ul> <li>Element name, this is necessary if you are mapping to a choice structure where multiple elements are of the same type. If the element name does not correspond to a unique type then you would not be able to round-trip the document.</li> <li><code>JAXBElement</code> can be used to represent an element with <code>xsi:nil="true"</code>.</li> </ul> <p><strong>XmlObjectFactory</strong></p> <p><code>@XmlElementDecl</code> also allows you to specify a scope. I have modified the model from you post a bit. I have introduced an <code>XmlObjectFactory</code> class that has two <code>@XmlElementDecl</code>. Both specify a name of <code>address</code>. I have leveraged the <code>scope</code> property so that for properties within the <code>Employee</code> class the <code>@XmlElementDecl</code> corresponding to the <code>Address</code> class with be used. </p> <pre><code>package forum11078850; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; @XmlRegistry public class XmlObjectFactory { @XmlElementDecl(scope = Employee.class, name = "address") JAXBElement&lt;Address&gt; createAddress(Address value) { return new JAXBElement&lt;Address&gt;(new QName("address"), Address.class, value); } @XmlElementDecl(name = "address") JAXBElement&lt;String&gt; createStringAddress(String value) { return new JAXBElement&lt;String&gt;(new QName("address"), String.class, value); } } </code></pre> <p><strong>Employee</strong></p> <p>The <code>@XmlElementRef</code> annotation will cause the value of the property to be matched on its root element name. Possible matches will include classes mapped with <code>@XmlRootElement</code> or <code>@XmlElementDecl</code>.</p> <pre><code>package forum11078850; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.*; @XmlRootElement @XmlType(propOrder = { "id", "name", "email", "addresses" }) public class Employee { private int id; private String name; private String email; private List&lt;JAXBElement&lt;Address&gt;&gt; addresses; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @XmlElementWrapper @XmlElementRef(name="address") public List&lt;JAXBElement&lt;Address&gt;&gt; getAddresses() { return addresses; } public void setAddresses(List&lt;JAXBElement&lt;Address&gt;&gt; addresses) { this.addresses = addresses; } } </code></pre> <p><strong>ObjectFactoryTest</strong></p> <pre><code>package forum11078850; import java.io.FileReader; import javax.xml.bind.*; public class ObjectFactoryTest { public static void main(String[] args) throws Exception { FileReader reader = new FileReader("src/forum11078850/input.xml"); JAXBContext context = JAXBContext.newInstance(Employee.class, XmlObjectFactory.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Object obj = unmarshaller.unmarshal(reader); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(obj, System.out); } } </code></pre> <p>The <code>Address</code> class and <code>input.xml</code> from my original answer can be used to run this example.</p> <hr/> <p><strong>ORIGINAL ANSWER</strong></p> <p>I'm not sure how you are attempting to use <code>@XmlRegistry</code>, so I will focus on the following part of your post:</p> <blockquote> <p>When I unmarshal the employee xml using above code, the address list does not get populated. The resulting employee object only has a blank list of adresses. Is there anything wrong with my mappings?</p> </blockquote> <p>Your list of <code>Address</code> objects is wrapped in a grouping element (<code>addresses</code>), so you need to use the <code>@XmlElementWrapper</code> annotation to map this use case. Below is a complete example:</p> <p><strong>Employee</strong></p> <pre><code>package forum11078850; import java.util.List; import javax.xml.bind.annotation.*; @XmlRootElement @XmlType(propOrder = { "id", "name", "email", "addresses" }) public class Employee { private int id; private String name; private String email; private List&lt;Address&gt; addresses; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @XmlElementWrapper @XmlElement(name = "address") public List&lt;Address&gt; getAddresses() { return addresses; } public void setAddresses(List&lt;Address&gt; addresses) { this.addresses = addresses; } } </code></pre> <p><strong>Address</strong></p> <pre><code>package forum11078850; public class Address { private String addressLine1; private String addressLine2; private String addressLine3; public String getAddressLine1() { return addressLine1; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getAddressLine3() { return addressLine3; } public void setAddressLine3(String addressLine3) { this.addressLine3 = addressLine3; } } </code></pre> <p><strong>ObjectFactoryTest</strong></p> <pre><code>package forum11078850; import java.io.FileReader; import javax.xml.bind.*; public class ObjectFactoryTest { public static void main(String[] args) throws Exception { FileReader reader = new FileReader("src/forum11078850/input.xml"); JAXBContext context = JAXBContext.newInstance(Employee.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Object obj = unmarshaller.unmarshal(reader); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(obj, System.out); } } </code></pre> <p><strong>input.xml/Output</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;employee&gt; &lt;id&gt;1&lt;/id&gt; &lt;name&gt;Vaishali&lt;/name&gt; &lt;email&gt;[email protected]&lt;/email&gt; &lt;addresses&gt; &lt;address&gt; &lt;addressLine1&gt;300&lt;/addressLine1&gt; &lt;addressLine2&gt;Mumbai&lt;/addressLine2&gt; &lt;addressLine3&gt;India&lt;/addressLine3&gt; &lt;/address&gt; &lt;address&gt; &lt;addressLine1&gt;301&lt;/addressLine1&gt; &lt;addressLine2&gt;Pune&lt;/addressLine2&gt; &lt;addressLine3&gt;India&lt;/addressLine3&gt; &lt;/address&gt; &lt;/addresses&gt; &lt;/employee&gt; </code></pre>
11,317,474
Macro to count number of arguments
<p>I have a variadic function from a third-party C library:</p> <pre><code>int func(int argc, ...); </code></pre> <p><code>argc</code> indicates the number of passed optional arguments. I'm wrapping it with a macro that counts the number of arguments, as suggested <a href="https://groups.google.com/forum/?fromgroups#!topic/comp.std.c/d-6Mj5Lko_s" rel="nofollow noreferrer">here</a>. For reading convenience, here's the macro:</p> <pre><code>#define PP_ARG_N( \ _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, \ _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \ _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, \ _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \ _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, \ _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, \ _61, _62, _63, N, ...) N #define PP_RSEQ_N() \ 63, 62, 61, 60, \ 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, \ 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, \ 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, \ 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, \ 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, \ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 #define PP_NARG_(...) PP_ARG_N(__VA_ARGS__) #define PP_NARG(...) PP_NARG_(__VA_ARGS__, PP_RSEQ_N()) </code></pre> <p>and I'm wrapping it like so:</p> <pre><code>#define my_func(...) func(PP_NARG(__VA_ARGS__), __VA_ARGS__) </code></pre> <p>The <code>PP_NARG</code> macro works great for functions accepting one or more arguments. For instance, <code>PP_NARG(&quot;Hello&quot;, &quot;World&quot;)</code> evaluates to <code>2</code>.<br></p> <p>The problem is that when no arguments are passed, <code>PP_NARG()</code> evaluates to <code>1</code> instead of <code>0</code>.<br> I understand <a href="https://web.archive.org/web/20201001165923/http://efesx.com/2010/07/17/variadic-macro-to-count-number-of-arguments/" rel="nofollow noreferrer">how this macro works</a>, but I can't come up with an idea to modify it so that it behaves correctly for this case as well.</p> <p>Any ideas?</p> <hr /> <p><strong>EDIT</strong>:<br> I have found a workaround for <code>PP_NARG</code>, and posted it as an answer.<br> I still have problems with wrapping the variadic function though. When <code>__VA_ARGS__</code> is empty, <code>my_func</code> expands to <code>func(0, )</code> which triggers a compilation error.</p>
11,742,317
4
4
null
2012-07-03 19:04:16.217 UTC
10
2022-09-22 08:00:39.183 UTC
2022-09-22 08:00:39.183 UTC
null
4,751,173
null
1,336,150
null
1
13
c|macros|arguments|variadic
13,271
<p>Another possibility, which does not use <code>sizeof</code> nor a GCC extension is to add the following to your code</p> <pre><code>#define PP_COMMASEQ_N() \ 1, 1, 1, 1, \ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 #define PP_COMMA(...) , #define PP_HASCOMMA(...) \ PP_NARG_(__VA_ARGS__, PP_COMMASEQ_N()) #define PP_NARG(...) \ PP_NARG_HELPER1( \ PP_HASCOMMA(__VA_ARGS__), \ PP_HASCOMMA(PP_COMMA __VA_ARGS__ ()), \ PP_NARG_(__VA_ARGS__, PP_RSEQ_N())) #define PP_NARG_HELPER1(a, b, N) PP_NARG_HELPER2(a, b, N) #define PP_NARG_HELPER2(a, b, N) PP_NARG_HELPER3_ ## a ## b(N) #define PP_NARG_HELPER3_01(N) 0 #define PP_NARG_HELPER3_00(N) 1 #define PP_NARG_HELPER3_11(N) N </code></pre> <p>The result is</p> <pre><code>PP_NARG() // expands to 0 PP_NARG(x) // expands to 1 PP_NARG(x, 2) // expands to 2 </code></pre> <h3>Explanation:</h3> <p>The trick in these macros is that <code>PP_HASCOMMA(...)</code> expands to 0 when called with zero or one argument and to 1 when called with at least two arguments. To distinguish between these two cases, I used <code>PP_COMMA __VA_ARGS__ ()</code>, which returns a comma when <code>__VA_ARGS__</code> is empty and returns nothing when <code>__VA_ARGS__</code> is non-empty.</p> <p>Now there are three possible cases:</p> <ol> <li><p><code>__VA_ARGS__</code> is empty: <code>PP_HASCOMMA(__VA_ARGS__)</code> returns 0 and <code>PP_HASCOMMA(PP_COMMA __VA_ARGS__ ())</code> returns 1.</p></li> <li><p><code>__VA_ARGS__</code> contains one argument: <code>PP_HASCOMMA(__VA_ARGS__)</code> returns 0 and <code>PP_HASCOMMA(PP_COMMA __VA_ARGS__ ())</code> returns 0.</p></li> <li><p><code>__VA_ARGS__</code> contains two or more arguments: <code>PP_HASCOMMA(__VA_ARGS__)</code> returns 1 and <code>PP_HASCOMMA(PP_COMMA __VA_ARGS__ ())</code> returns 1.</p></li> </ol> <p>The <code>PP_NARG_HELPERx</code> macros are just needed to resolve these cases.</p> <h3>Edit:</h3> <p>In order to fix the <code>func(0, )</code> problem, we need to test whether we have supplied zero or more arguments. The <code>PP_ISZERO</code> macro comes into play here.</p> <pre><code>#define PP_ISZERO(x) PP_HASCOMMA(PP_ISZERO_HELPER_ ## x) #define PP_ISZERO_HELPER_0 , </code></pre> <p>Now let's define another macro which prepends the number of arguments to an argument list:</p> <pre><code>#define PP_PREPEND_NARG(...) \ PP_PREPEND_NARG_HELPER1(PP_NARG(__VA_ARGS__), __VA_ARGS__) #define PP_PREPEND_NARG_HELPER1(N, ...) \ PP_PREPEND_NARG_HELPER2(PP_ISZERO(N), N, __VA_ARGS__) #define PP_PREPEND_NARG_HELPER2(z, N, ...) \ PP_PREPEND_NARG_HELPER3(z, N, __VA_ARGS__) #define PP_PREPEND_NARG_HELPER3(z, N, ...) \ PP_PREPEND_NARG_HELPER4_ ## z (N, __VA_ARGS__) #define PP_PREPEND_NARG_HELPER4_1(N, ...) 0 #define PP_PREPEND_NARG_HELPER4_0(N, ...) N, __VA_ARGS__ </code></pre> <p>The many helpers are again needed to expand the macros to numeric values. Finally test it:</p> <pre><code>#define my_func(...) func(PP_PREPEND_NARG(__VA_ARGS__)) my_func() // expands to func(0) my_func(x) // expands to func(1, x) my_func(x, y) // expands to func(2, x, y) my_func(x, y, z) // expands to func(3, x, y, z) </code></pre> <h3>Online example:</h3> <p><a href="http://coliru.stacked-crooked.com/a/73b4b6d75d45a1c8" rel="noreferrer">http://coliru.stacked-crooked.com/a/73b4b6d75d45a1c8</a></p> <h3>See also:</h3> <p>Please have also a look at the <a href="http://p99.gforge.inria.fr/p99-html/index.html" rel="noreferrer">P99</a> project, which has much more advanced preprocessor solutions, <a href="http://p99.gforge.inria.fr/p99-html/p99__args_8h_source.html" rel="noreferrer">like these</a>.</p>
11,019,086
.net chart clear and re-add
<p>I have a chart and I need to clear it in order to populate it with different values. The chart has 3 series, all defined in the .aspx page. </p> <p>The problem is when I call</p> <pre><code>chart.Series.Clear(); </code></pre> <p>and then re-add the series like:</p> <pre><code>chart.Series.Add("SeriesName"); </code></pre> <p>It doesn't keep any of the attributes of the 3 initial series. How to just clear the values and keep the series attributes?</p>
11,019,109
5
0
null
2012-06-13 16:14:57.99 UTC
4
2020-01-16 07:10:13.943 UTC
null
null
null
null
1,315,427
null
1
19
c#|asp.net|charts
77,172
<p>This should work:</p> <pre><code>foreach(var series in chart.Series) { series.Points.Clear(); } </code></pre>
10,900,643
How can I construct a java.security.PublicKey object from a base64 encoded string?
<p>I have a bse64encoded string Public key from external source (Android Store) and I need to use it to verify signed content. How can I convert the string into an instance of the java.security.PublicKey interface. I am on Java 6 if that makes a difference. </p> <p>The key is (probably) generated using standard java lib and not bouncy castle (its from a remote team so I am not sure). Their sample code says to use Security.generatePublicKey(base64EncodedPublicKey); but the Security object in standard java has no such method. </p>
10,902,896
6
2
null
2012-06-05 15:56:18.587 UTC
14
2021-06-28 05:59:14.627 UTC
2012-06-05 16:18:04.927 UTC
null
706,727
null
706,727
null
1
41
java|security|rsa
45,931
<p>Ok for grins ... try this</p> <ul> <li>base64 decode the key data to get a byte array (byte[])</li> <li>Create a new X509EncodedKeySpec using the byte array</li> <li>Get an instance of KeyFactory using KeyFactory.getInstance("RSA") assuming RSA here</li> <li>call the method generatePublic(KeySpec) with the X509EncodedKeySpec</li> <li>Result /should/ be a public key for your usage.</li> </ul>
10,945,859
"Plain Style unsupported in a Navigation Item" warning with my customized Bar Button Item
<p>I drag a Round Rect Button to the position of the right Bar Button Item, and set an image to the Round Rect Button. All works well, except the warning "Plain Style unsupported in a Navigation Item". Even if i select the style of the Bar Button Item to "Bordered", warning still be there. What's the matter with Xcode 4.2? Thanks in advance!</p> <p>Ps. I customized many Bar Button Items with Round Rect Button, some times Xcode 4.2 shows only one warning on a Bar Button Item, some times shows warnings on all Bar Button Items. </p>
24,564,996
8
2
null
2012-06-08 09:00:58.49 UTC
11
2017-07-14 02:15:22.903 UTC
null
null
null
null
1,297,382
null
1
94
iphone|ios|xcode|uibarbuttonitem|uibarbuttonitemstyle
42,323
<p>I was able to remove these errors by manually editing the storyboard files and find the offending style="plain" entry on Bar Button items in the <code>&lt;navigationItem&gt;</code> element.</p> <p>Changed from:</p> <pre><code>&lt;barButtonItem key="rightBarButtonItem" style="plain" id="juB-DL-F9i"&gt; </code></pre> <p>To:</p> <pre><code>&lt;barButtonItem key="rightBarButtonItem" id="juB-DL-F9i"&gt; </code></pre> <p>This cleared the warnings... right or wrong.</p> <p>This may be a stupendous hack and the larger concern is I did not root cause it or remove the invisible bar button items from the overall document. This was after going through all the elements one by one and discovering some navigation bars were empty (without children) and likely occurred with the large amount of copy and paste (cmd+c|v) inheritance and not using duplicate (cmd+d) to build the interface. Although the source cause was not root caused, the symptom was the bar items did not show in the document "outline view" to be fixed. Interface Builder behavior strikes me as nuanced at times and an empty container where there should be something in an outline view is a smell. Well it is to me now. Sometimes deleting the offending node and rebuilding fixes the oddest issues.</p> <p>WARNING: back up your storyboards before you try this... version control is your friend... I take no responsibility when your storyboard is completely hosed and wont compile. All you'll get is an "I told you so!" I learned the hard way a few times, but diligent source control saved me a headache.</p> <p>EDIT: put brackets in code blocks</p>
10,989,005
Do I understand os.walk right?
<p>The loop for root, dir, file in <code>os.walk(startdir)</code> works through these steps?</p> <pre><code>for root in os.walk(startdir) for dir in root for files in dir </code></pre> <ol> <li><p>get root of start dir : C:\dir1\dir2\startdir</p> </li> <li><p>get folders in C:\dir1\dir2\startdir and return list of folders &quot;dirlist&quot;</p> </li> <li><p>get files in the first dirlist item and return the list of files &quot;filelist&quot; as the first item of a list of filelists.</p> </li> <li><p>move to the second item in dirlist and return the list of files in this folder &quot;filelist2&quot; as the second item of a list of filelists. etc.</p> </li> <li><p>move to the next root in the folder tree and start from 2. etc.</p> </li> </ol> <p>Right? Or does it just get all roots first, then all dirs second, and all files third?</p>
10,989,155
6
1
null
2012-06-12 00:01:53.07 UTC
36
2021-07-19 09:47:44.44 UTC
2021-06-23 02:27:40.147 UTC
null
1,652,819
null
1,433,983
null
1
94
python|file
154,048
<p><code>os.walk</code> returns a generator, that creates a tuple of values (current_path, directories in current_path, files in current_path).</p> <p>Every time the generator is called it will follow each directory recursively until no further sub-directories are available from the initial directory that walk was called upon.</p> <p>As such,</p> <pre><code>os.walk('C:\dir1\dir2\startdir').next()[0] # returns 'C:\dir1\dir2\startdir' os.walk('C:\dir1\dir2\startdir').next()[1] # returns all the dirs in 'C:\dir1\dir2\startdir' os.walk('C:\dir1\dir2\startdir').next()[2] # returns all the files in 'C:\dir1\dir2\startdir' </code></pre> <p>So</p> <pre><code>import os.path .... for path, directories, files in os.walk('C:\dir1\dir2\startdir'): if file in files: print('found %s' % os.path.join(path, file)) </code></pre> <p>or this</p> <pre><code>def search_file(directory = None, file = None): assert os.path.isdir(directory) for cur_path, directories, files in os.walk(directory): if file in files: return os.path.join(directory, cur_path, file) return None </code></pre> <p>or if you want to look for file you can do this:</p> <pre><code>import os def search_file(directory = None, file = None): assert os.path.isdir(directory) current_path, directories, files = os.walk(directory).next() if file in files: return os.path.join(directory, file) elif directories == '': return None else: for new_directory in directories: result = search_file(directory = os.path.join(directory, new_directory), file = file) if result: return result return None </code></pre>
13,039,437
loop through cells in named range
<p>I am trying to write code that will loop through all cells in a range. Eventually I want to do something more complicated, but since I was having trouble I decided to create some short test programs. The first example works fine but the second (with a named range) doesn't (gives a "Method Range of Object_Global Failed" error message). Any ideas as to what I'm doing wrong? I'd really like to do this with a named range... Thanks!</p> <p>Works:</p> <pre><code>Sub foreachtest() Dim c As Range For Each c In Range("A1:A3") MsgBox (c.Address) Next End Sub </code></pre> <p>Doesn't work:</p> <pre><code>Sub foreachtest2() Dim c As Range Dim Rng As Range Set Rng = Range("A1:A3") For Each c In Range("Rng") MsgBox (c.Address) Next End Sub </code></pre>
13,039,838
3
1
null
2012-10-23 21:20:33.92 UTC
null
2012-10-23 21:47:47.307 UTC
2012-10-23 21:25:39.07 UTC
null
1,742,119
null
1,742,119
null
1
6
excel|vba
51,964
<p>To adjust your second code, you need to recognize that your range rng is now a variable representing a range and treat it as such:</p> <pre><code>Sub foreachtest2() Dim c As Range Dim Rng As Range Set Rng = Range("A1:A3") For Each c In rng MsgBox (c.Address) Next End Sub </code></pre> <p>Warning: most of the time, your code will be faster if you can avoid looping through the range.</p>
12,815,231
Controlling the heartbeat timeout from the client in socket.io
<p>I have mobile clients connected to a node.js server, running socket.io via xhr-polling. I have two type of clients:</p> <ul> <li><p>Type A</p> <p>When the connection breaks up due to network problems (or that the client crashes) the default heart beat timeout is too long</p></li> <li><p>Type B</p> <p>When the connection breaks up for this client I need to give it more time to recover - it is more important that the client recovers than the server breaks the connection/session</p></li> </ul> <p>So my question is how to I configure (if it is possible) the heartbeat timeouts from the actual client?</p>
12,846,918
3
1
null
2012-10-10 08:36:22.19 UTC
15
2017-08-05 03:58:14.5 UTC
2015-12-10 16:23:40.92 UTC
null
1,039,919
null
298,435
null
1
27
node.js|client|socket.io
46,093
<p>As far as I can tell, there are 2 values that matter here: the server sends heartbeats to the client every <code>heartbeat interval</code> seconds; the client responds directly, if there is no response, the server decides the client is dead. The client waits for a heartbeat from the server for <code>heartbeat timeout</code> seconds since the last heartbeat (which should obviously be higher than the <code>heartbeat interval</code>). If it hasn't received word from the server in <code>heartbeat timeout</code> seconds, it assumes the server is dead (and will start disconnecting / reconnecting based on the other options you have set.</p> <p>Default values are <code>heartbeat interval = 25s</code> and <code>heartbeat timeout = 60s</code>. Both items are set on the server, the <code>heartbeat timeout</code> is sent to the client upon connecting.</p> <p>Changing the <code>heartbeat timeout</code> for a single client is easy:</p> <pre><code>var socket = io.connect(url); socket.heartbeatTimeout = 20000; // reconnect if not received heartbeat for 20 seconds </code></pre> <p>However on the server, the <code>heartbeat interval</code> value seems to be part of a shared object (the Manager, which is what you get back from your <code>var io = require("socket.io").listen(server)</code> call), which means that it can't easily be changed for individual sockets.</p> <p>I'm sure that with some socket.io hacking you should be able to make it happen, but you might break other stuff in the process...</p>
12,850,345
How do I combine two dataframes?
<p>I have a initial dataframe <code>D</code>. I extract two data frames from it like this:</p> <pre><code>A = D[D.label == k] B = D[D.label != k] </code></pre> <p>I want to combine <code>A</code> and <code>B</code> into one DataFrame. The order of the data is not important. However, when we sample <code>A</code> and <code>B</code> from <code>D</code>, they retain their indexes from <code>D</code>.</p>
12,850,453
7
2
null
2012-10-11 23:53:37.28 UTC
31
2022-08-23 09:41:36.057 UTC
2022-07-01 23:39:01.363 UTC
null
365,102
null
445,491
null
1
196
python|pandas
401,966
<blockquote> <p><strong>DEPRECATED:</strong> <code>DataFrame.append</code> and <code>Series.append</code> were <a href="https://pandas.pydata.org/pandas-docs/stable/whatsnew/v1.4.0.html#deprecated-dataframe-append-and-series-append" rel="noreferrer">deprecated in v1.4.0</a>.</p> </blockquote> <hr /> <p>Use <code>append</code>:</p> <pre><code>df_merged = df1.append(df2, ignore_index=True) </code></pre> <p>And to keep their indexes, set <code>ignore_index=False</code>.</p>
22,037,744
Named numbers as variables
<p>I've seen this a couple of times recently in <em>high profile</em> code, where constant values are defined as variables, named after the value, then used only once. I wondered why it gets done?</p> <p>E.g. Linux Source (resize.c)</p> <pre><code>unsigned five = 5; unsigned seven = 7; </code></pre> <p>E.g. C#.NET Source (Quaternion.cs)</p> <pre><code>double zero = 0; double one = 1; </code></pre>
22,059,732
10
15
null
2014-02-26 09:56:05.567 UTC
4
2014-02-27 18:39:46.633 UTC
null
null
null
null
3,058,105
null
1
50
c#|c++|conventions
3,405
<p>Short version:</p> <ul> <li>A constant <code>five</code> that just holds the number five is pretty useless. Don't go around making these for no reason (sometimes you have to because of syntax or typing rules, though).</li> <li>The named variables in Quaternion.cs aren't strictly necessary, but you can make the case for the code being significantly more readable with them than without.</li> <li>The named variables in ext4/resize.c aren't constants at all. They're tersely-named counters. Their names obscure their function a bit, but this code actually <strong>does</strong> correctly follow the project's specialized coding standards.</li> </ul> <h1>What's going on with Quaternion.cs?</h1> <p>This one's pretty easy.</p> <p>Right after this:</p> <pre><code>double zero = 0; double one = 1; </code></pre> <p>The code does this:</p> <pre><code>return zero.GetHashCode() ^ one.GetHashCode(); </code></pre> <p>Without the local variables, what does the alternative look like?</p> <pre><code>return 0.0.GetHashCode() ^ 1.0.GetHashCode(); // doubles, not ints! </code></pre> <p>What a mess! Readability is definitely on the side of creating the locals here. Moreover, I think explicitly naming the variables indicates "We've thought about this carefully" much more clearly than just writing a single confusing return statement would.</p> <h1>What's going on with resize.c?</h1> <p>In the case of ext4/resize.c, these numbers aren't actually constants at all. If you follow the code, you'll see that they're counters and their values actually change over multiple iterations of a while loop.</p> <p><a href="http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/fs/ext4/resize.c#L652">Note how they're initialized</a>:</p> <pre><code>unsigned three = 1; unsigned five = 5; unsigned seven = 7; </code></pre> <p>Three equals one, huh? What's that about?</p> <p>See, what actually happens is that <code>update_backups</code> passes these variables by reference to the function <a href="http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/fs/ext4/resize.c#L318"><code>ext4_list_backups</code></a>:</p> <pre><code>/* * Iterate through the groups which hold BACKUP superblock/GDT copies in an * ext4 filesystem. The counters should be initialized to 1, 5, and 7 before * calling this for the first time. In a sparse filesystem it will be the * sequence of powers of 3, 5, and 7: 1, 3, 5, 7, 9, 25, 27, 49, 81, ... * For a non-sparse filesystem it will be every group: 1, 2, 3, 4, ... */ static unsigned ext4_list_backups(struct super_block *sb, unsigned *three, unsigned *five, unsigned *seven) </code></pre> <p>They're counters that are preserved over the course of multiple calls. If you <a href="http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/fs/ext4/resize.c#L318">look at the function body</a>, you'll see that it's juggling the counters to find <em>the next power of 3, 5, or 7</em>, creating the sequence you see in the comment: 1, 3, 5, 7, 9, 25, 27, &amp;c.</p> <p>Now, for the weirdest part: the variable <code>three</code> is initialized to 1 because 3<sup>0</sup> = 1. The power 0 is a special case, though, because it's the only time 3<sup>x</sup> = 5<sup>x</sup> = 7<sup>x</sup>. Try your hand at rewriting <code>ext4_list_backups</code> to work with all three counters initialized to 1 (3<sup>0</sup>, 5<sup>0</sup>, 7<sup>0</sup>) and you'll see how much more cumbersome the code becomes. Sometimes it's easier to just tell the caller to do something funky (initialize the list to 1, 5, 7) in the comments.</p> <h1>So, is <code>five = 5</code> good coding style?</h1> <p>Is "five" a good name for the thing that the variable <code>five</code> represents in resize.c? In my opinion, it's not a style you should emulate in just any random project you take on. The simple name <code>five</code> doesn't communicate much about the purpose of the variable. If you're working on a web application or rapidly prototyping a video chat client or something and decide to name a variable <code>five</code>, you're probably going to create headaches and annoyance for anyone else who needs to maintain and modify your code.</p> <p>However, <strong>this is one example where generalities about programming don't paint the full picture</strong>. <a href="https://www.kernel.org/doc/Documentation/CodingStyle">Take a look at the kernel's coding style document</a>, particularly the chapter on naming.</p> <blockquote> <p>GLOBAL variables (to be used only if you <em>really</em> need them) need to have descriptive names, as do global functions. If you have a function that counts the number of active users, you should call that "count_active_users()" or similar, you should <em>not</em> call it "cntusr()".</p> <p>...</p> <p>LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called "i". Calling it "loop_counter" is non-productive, if there is no chance of it being mis-understood. Similarly, "tmp" can be just about any type of variable that is used to hold a temporary value.</p> <p>If you are afraid to mix up your local variable names, you have another problem, which is called the function-growth-hormone-imbalance syndrome. See chapter 6 (Functions).</p> </blockquote> <p>Part of this is C-style coding tradition. Part of it is purposeful social engineering. A lot of kernel code is sensitive stuff, and it's been revised and tested many times. Since Linux is a big open-source project, it's not really hurting for contributions &mdash; in most ways, the bigger challenge is checking those contributions for quality.</p> <p>Calling that variable <code>five</code> instead of something like <code>nextPowerOfFive</code> is a way to discourage contributors from meddling in code they don't understand. It's an attempt to force you to really read the code you're modifying in detail, line by line, before you try to make any changes.</p> <p>Did the kernel maintainers make the right decision? I can't say. But it's clearly a purposeful move.</p>
11,131,875
What is the cleanest way to disable CSS transition effects temporarily?
<p>I have a DOM element with some/all of the following effects applied: </p> <pre><code>#elem { -webkit-transition: height 0.4s ease; -moz-transition: height 0.4s ease; -o-transition: height 0.4s ease; transition: height 0.4s ease; } </code></pre> <p>I am writing a jQuery plugin that is resizing this element, I need to disable these effects temporarily so I can resize it smoothly. </p> <p>What is the most elegant way of disabling these effects temporarily (and then re-enabling them), given they may be applied from parents or may not be applied at all. </p>
16,575,811
11
2
null
2012-06-21 05:16:02.263 UTC
79
2021-09-22 06:03:55.89 UTC
2016-05-23 18:53:36.447 UTC
null
192,831
null
17,174
null
1
244
javascript|jquery|css
252,020
<h2>Short Answer</h2> <p><strong>Use this CSS:</strong></p> <pre><code>.notransition { -webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important; } </code></pre> <p><strong>Plus either this JS (without jQuery)...</strong></p> <pre><code>someElement.classList.add('notransition'); // Disable transitions doWhateverCssChangesYouWant(someElement); someElement.offsetHeight; // Trigger a reflow, flushing the CSS changes someElement.classList.remove('notransition'); // Re-enable transitions </code></pre> <p><strong>Or this JS with jQuery...</strong></p> <pre><code>$someElement.addClass('notransition'); // Disable transitions doWhateverCssChangesYouWant($someElement); $someElement[0].offsetHeight; // Trigger a reflow, flushing the CSS changes $someElement.removeClass('notransition'); // Re-enable transitions </code></pre> <p>... or equivalent code using whatever other library or framework you're working with.</p> <h2>Explanation</h2> <p>This is actually a fairly subtle problem.</p> <p>First up, you probably want to create a 'notransition' class that you can apply to elements to set their <code>*-transition</code> CSS attributes to <code>none</code>. For instance:</p> <pre><code>.notransition { -webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important; } </code></pre> <p><sub><i>(Minor aside - note the lack of an <code>-ms-transition</code> in there. You don't need it. The first version of Internet Explorer to support transitions <em>at all</em> was IE 10, which supported them unprefixed.)</i></sub></p> <p>But that's just style, and is the easy bit. When you come to try and use this class, you'll run into a trap. The trap is that code like this won't work the way you might naively expect:</p> <pre><code>// Don't do things this way! It doesn't work! someElement.classList.add('notransition') someElement.style.height = '50px' // just an example; could be any CSS change someElement.classList.remove('notransition') </code></pre> <p>Naively, you might think that the change in height won't be animated, because it happens while the 'notransition' class is applied. In reality, though, it <em>will</em> be animated, at least in all modern browsers I've tried. The problem is that the browser is caching the styling changes that it needs to make until the JavaScript has finished executing, and then making all the changes in a single reflow. As a result, it does a reflow where there is no net change to whether or not transitions are enabled, but there is a net change to the height. Consequently, it animates the height change.</p> <p>You might think a reasonable and clean way to get around this would be to wrap the removal of the 'notransition' class in a 1ms timeout, like this:</p> <pre><code>// Don't do things this way! It STILL doesn't work! someElement.classList.add('notransition') someElement.style.height = '50px' // just an example; could be any CSS change setTimeout(function () {someElement.classList.remove('notransition')}, 1); </code></pre> <p>but this doesn't reliably work either. I wasn't able to make the above code break in WebKit browsers, but on Firefox (on both slow and fast machines) you'll sometimes (seemingly at random) get the same behaviour as using the naive approach. I guess the reason for this is that it's possible for the JavaScript execution to be slow enough that the timeout function is waiting to execute by the time the browser is idle and would otherwise be thinking about doing an opportunistic reflow, and if that scenario happens, Firefox executes the queued function before the reflow.</p> <p>The only solution I've found to the problem is to <em>force</em> a reflow of the element, flushing the CSS changes made to it, before removing the 'notransition' class. There are various ways to do this - see <a href="http://gent.ilcore.com/2011/03/how-not-to-trigger-layout-in-webkit.html" rel="noreferrer">here</a> for some. The closest thing there is to a 'standard' way of doing this is to read the <code>offsetHeight</code> property of the element.</p> <p>One solution that actually works, then, is</p> <pre><code>someElement.classList.add('notransition'); // Disable transitions doWhateverCssChangesYouWant(someElement); someElement.offsetHeight; // Trigger a reflow, flushing the CSS changes someElement.classList.remove('notransition'); // Re-enable transitions </code></pre> <p>Here's a JS fiddle that illustrates the three possible approaches I've described here (both the one successful approach and the two unsuccessful ones): <a href="http://jsfiddle.net/2uVAA/131/" rel="noreferrer">http://jsfiddle.net/2uVAA/131/</a></p>
16,612,057
Is an empty textbox considered an empty string or null?
<p>The text box in question is involved in an if statement within my code, something to the effect of</p> <pre class="lang-c# prettyprint-override"><code>if (textbox.text != "") { do this } </code></pre> <p>I am curious if an empty text box will be considered an empty string or a null statement.</p>
16,612,115
6
0
null
2013-05-17 14:54:18.267 UTC
2
2018-07-30 19:18:08.52 UTC
2018-07-30 19:18:08.52 UTC
null
2,756,409
null
1,873,140
null
1
13
c#|asp.net|.net|null
75,249
<p>Try to use <code>IsNullOrWhiteSpace</code>, this will make sure of validating the whitespace too without having to trim it.</p> <pre><code>if (!string.IsNullOrWhiteSpace(textbox.Text)) { //code here } </code></pre> <p>According to documentation <code>string.IsNullOrWhiteSpace</code> evaluates to:</p> <pre><code>return String.IsNullOrEmpty(value) || value.Trim().Length == 0; </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx" rel="noreferrer">String.IsNullOrWhiteSpace</a>:</p> <blockquote> <p>Indicates whether a specified string is null, empty, or consists only of white-space characters.</p> </blockquote>
16,984,946
DateTime parsing
<p>I am writing a syslog server that receives syslog messages and stores them in a database.</p> <p>I am trying to parse the date string received in the message into a <code>DateTime</code> structure.</p> <p>For the following examples, I'll be using an underscore in place of whitespace for clarity; the actual strings received have spaces.</p> <p>The string I received is in the format <code>"Jun__7_08:09:10"</code> - please note the two whitespaces between the month and day.</p> <p>If the day is after the 10th, the strings become <code>"Jun_10_08:09:10"</code> (one whitespace).</p> <p>If I parse with:</p> <pre><code>DateTime.ParseExact(Log.Date, "MMM d HH:mm:ss", CultureInfo.InvariantCulture); </code></pre> <p>it works for strings from the 1st to 9th but throws exception from the 10th forward, and if I parse with one space, it throws an exception on the 1st to 9th (and works from the 10th on).</p> <p>What is the correct way to parse this string?</p>
16,984,996
5
4
null
2013-06-07 13:06:35.98 UTC
null
2013-06-07 18:18:42.04 UTC
2013-06-07 18:18:42.04 UTC
null
1,128,737
null
2,084,122
null
1
31
c#|parsing|datetime
3,171
<p>Consider using this line:</p> <pre><code>DateTime.ParseExact(Log.Date, "MMM d HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces); </code></pre> <p>Notice that I removed one of the spaces between the month and the day. That's because <code>AllowWhiteSpaces</code> literally means:</p> <blockquote> <p>Specifies that s may contain leading, inner, and trailing white spaces not defined by format.</p> </blockquote>
16,594,611
How do you add an SDK to Android Studio?
<p>I'm using Google's Android Studio 0.1 based on IntelliJ, and I cannot figure out how to add additional SDKs to my project.</p> <p>I exported my existing project from Eclipse to a Gradle project, which I imported into Android Studio, <a href="http://developer.android.com/sdk/installing/migrate.html" rel="noreferrer">as recommended by Google</a>.</p> <p>My project's SDK is Google APIs 2.3.3. However, I use a library called PullToRefresh which appears to need SDK 4.1, so I'm trying to add the SDK 16 to my project.</p> <p>I've already made sure to download the SDK using the SDK manager. These SDKs are added to the Android Studio.app's sdk folder automatically.</p> <p>I opened the Project Structure window, clicked "SDKs" under Platform Settings, and I currently see JDK 1.7 and Google APIs 2.3.3 shown. I click the + sign above that list to add a new SDK. I then navigate to the sdk directory that has android-16, as shown in the screenshot below. I am not quite sure what this wants me to add, but I've highlighted the android-16 folder (about the only thing I can select), and when I click "Choose," the window disappears, but no new SDK appears in the SDK list. </p> <p><img src="https://i.stack.imgur.com/feX49.png" alt="Screenshot of the SDK chooser"></p> <p>And here is a screenshot of my SDK Manager view, showing the installed SDKs:</p> <p><img src="https://i.stack.imgur.com/mr3ek.png" alt="Screenshot of SDK Manager"></p>
16,596,402
8
0
null
2013-05-16 18:16:52.21 UTC
10
2015-12-05 21:31:57.497 UTC
2013-05-16 18:42:50.533 UTC
null
264,775
null
650,558
null
1
43
android|android-studio
152,409
<p>I had opened a ticket also with Google's support, and received the solution. Instead of choosing the sdk/platform/android-16 folder, if you select the top-level "sdk" folder instead, you'll then be asked to choose which SDK you want to add. This worked!</p> <p><img src="https://i.stack.imgur.com/U9ZRq.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/ABy1p.png" alt="enter image description here"></p>
16,863,917
Check if class exists somewhere in parent
<p>I want to check if a class exsits somewhere in one of the parent elements of an element.</p> <p>I don't want to use any library, just vanilla JS.</p> <p>In the examples below it should return true if the element in question resides somewhere in the childs of an element with &quot;the-class&quot; as the class name.</p> <p>I think it would be something like this with jQuery:</p> <pre><code>if( $('#the-element').parents().hasClass('the-class') ) { return true; } </code></pre> <p>So this returns true:</p> <pre><code>&lt;div&gt; &lt;div class=&quot;the-class&quot;&gt; &lt;div id=&quot;the-element&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>So does this:</p> <pre><code>&lt;div class=&quot;the-class&quot;&gt; &lt;div&gt; &lt;div id=&quot;the-element&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>...but this returns false:</p> <pre><code>&lt;div&gt; &lt;div class=&quot;the-class&quot;&gt; &lt;/div&gt; &lt;div id=&quot;the-element&quot;&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
16,863,971
10
3
null
2013-05-31 18:50:11.007 UTC
8
2021-11-05 15:42:52.267 UTC
2021-11-05 15:42:52.267 UTC
null
13,860
null
2,143,356
null
1
55
javascript|dom
63,436
<p>You'll have to do it recursively :</p> <pre><code>// returns true if the element or one of its parents has the class classname function hasSomeParentTheClass(element, classname) { if (element.className.split(' ').indexOf(classname)&gt;=0) return true; return element.parentNode &amp;&amp; hasSomeParentTheClass(element.parentNode, classname); } </code></pre> <p><a href="http://jsbin.com/awudor/1/edit" rel="noreferrer">Demonstration</a> (open the console to see <code>true</code>)</p>
16,883,427
Why is Android Studio reporting "URI is not registered"?
<p>So I've given Android Studio a try, because I really like Resharper and noticed that the IDE had some of their functionality built into it. Having now created a default new project, I added a new layout file and wanted to change the existing default 'hello world' example layout, and I got an &quot;URI is not registered&quot; error on the following lines:</p> <pre class="lang-xml prettyprint-override"><code>&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; </code></pre> <p>I've done nothing else to the default generated project yet. I've come across another question that seems to be related (<a href="https://stackoverflow.com/questions/6147051/intellij-android-project-schema-uri-not-registered">Intellij Android project schema URI not registered?</a>), but just ignoring something feels odd to me. I actually tried it, but that causes <code>RelativeLayout</code> (and probably all other Android related stuff) to be not recognised any more (error message: &quot;Cannot find the declaration of element 'RelativeLayout'&quot;).</p> <p>Any ideas on how to solve this problem?</p> <p><img src="https://i.stack.imgur.com/95PWIl.jpg" alt="enter image description here" /></p> <p><img src="https://i.stack.imgur.com/vWksHl.jpg" alt="enter image description here" /></p> <p><img src="https://i.stack.imgur.com/GzDRsl.jpg" alt="enter image description here" /></p>
16,910,124
27
2
null
2013-06-02 13:56:57.283 UTC
30
2021-08-03 13:33:24.79 UTC
2021-08-03 13:33:24.79 UTC
null
1,041,046
null
605,538
null
1
174
android|android-studio
239,471
<p>You are having this issue because you are at the wrong destination! The correct directory for the Layout resource file has to be under "res-layout" not "res-all-layout"</p>
25,755,142
AppStore Submission - Missing or invalid signature - com.google.GPPSignIn3PResources
<p>I'm trying to submit an iOS app to AppStore and I'm having the following error:</p> <blockquote> <p>ERROR ITMS-9000: "Missing or invalid signature. The bundle 'com.google.GPPSignIn3PResources' at bundle path 'Payload/My_app_name.app/GooglePlus.bundle' is not signed using an Apple submission certificate."</p> </blockquote> <p>I've submitted this app before I've never had this problem. Does anybody know if there is any recent change?</p> <p><strong>Update:</strong> I could submit the app about 6 hours before having this error. Then, my app was rejected with this message:</p> <blockquote> <p><strong>This bundle is invalid</strong> - New apps and app updates submitted to the App Store must be built with public (GM) versions of Xcode 5.1.1 or higher and iOS 7 SDK. Do not submit apps built with beta software.</p> </blockquote> <p>After this, couldn't submit anymore.</p> <p><strong>Update2:</strong></p> <p>Google has made an announcement about this:</p> <p><a href="http://googledevelopers.blogspot.com.br/2014/09/an-important-announcement-for-ios.html" rel="noreferrer">http://googledevelopers.blogspot.com.br/2014/09/an-important-announcement-for-ios.html</a></p> <p>A new version was released, solving the problem.</p>
25,853,640
12
9
null
2014-09-09 23:36:13.793 UTC
10
2016-08-17 06:04:07.117 UTC
2014-09-16 22:23:02.793 UTC
null
420,700
null
420,700
null
1
44
ios|xcode|app-store|app-store-connect
10,310
<p>Google released the version 1.7.1 of the google plus sdk.</p> <p>I created a new podspec for the 1.7.1 version as the previous owner is not reachable.</p> <p>Just add into your Podfile: </p> <pre><code>pod 'googleplus-ios-sdk', '~&gt; 1.7.1' </code></pre>
4,529,810
How to document all exceptions a function might throw?
<p>If you have a public function which may throw an exception which uses other (private or public) helper functions which can also throw exceptions I think you should document what exceptions the public function can throw <em>and this includes exceptions thrown by the helper functions</em>.</p> <p>Something like this (using Doxygen):</p> <pre><code>/** * @throw Exception ... * @throw ExceptionThrownByHelper ... * @throw ExceptionThrownByHelpersHelper ... */ void theFunction() { helperWhichMayThrowException(); } </code></pre> <p>and <code>helperWhichMayThrowException()</code> also calls other functions which may throw exceptions.</p> <p>To do this you can:</p> <ol> <li>recursively follow all functions <code>theFunction()</code> calls and look for exceptions thown by that function. This is a lot of work and you might forget to document an exception somewhere when you add an exception to a helper.</li> <li>catch all exceptions thrown by helpers in <code>theFunction()</code> and convert them so you are sure only the exceptions you specify are thrown. But then why use exceptions?</li> <li>do not worry about exceptions thrown by helper functions but then you can not unittest all exceptions because you do not know which exceptions can be thrown by the public function</li> <li>have some tool which (semi)automatically lists all exceptions thrown by helpers etc. I looked in the documentation of Doxygen but did not find a way to do this.</li> </ol> <p>I would like to use option 4 but I have not found a good solution yet, maybe it is doable with Doxygen? Or maybe I just want to document to much???</p> <p><strong>edit:</strong> Maybe its not really clear but I am looking for an easy way to document all exceptions (preferably using Doxygen) a function might throw without manually checking all helper functions. An easy way includes 'do not document all exceptions' or 'catch and transform all exceptions in <code>theFunction()</code>'</p>
11,668,697
2
5
null
2010-12-25 08:59:43.12 UTC
10
2012-07-26 11:52:11.31 UTC
2011-02-05 00:53:07.26 UTC
null
4,928
null
79,455
null
1
34
c++|exception|documentation|doxygen
27,202
<p>I came up with the following manual solution. Basically I just copy the <code>@throw</code> documentation from members I call. It would be nice if Doxygen had a <code>@copythrows</code> similar to <code>@copydoc</code>, but the following will work:</p> <pre><code>class A { public: /** @defgroup A_foo_throws * * @throws FooException */ /** * @brief Do something. * * @copydetails A_foo_throws */ void foo(); }; class B { public: // This group contains all exceptions thrown by B::bar() // Since B::bar() calls A::foo(), we also copy the exceptions // thrown by A::foo(). /** @defgroup B_bar_throws * * @copydetails A_foo_throws * @throws BarException */ /** * @brief Do something else. * * @copydetails B_bar_throws */ void bar(); }; </code></pre> <p>Then in the <code>Doxyfile</code> configuration file add <code>*_throws</code> to <code>EXCLUDE_SYMBOLS</code>. This makes sure these groups do not show up as modules.</p> <p>Then <code>B::bar()</code> results in this documentation:</p> <blockquote> <p><strong>void B::bar()</strong><br/> Do something else.</p> <p><strong>Exceptions:</strong><br/> &nbsp;&nbsp;FooException <br/> <strong>Exceptions:</strong><br/> &nbsp;&nbsp;BarException</p> </blockquote>
9,700,646
I screwed up, how can I uninstall my program?
<p>My Wix installer worked installing my program, but it's broken for uninstallation. A file is removed too early, and it's needed further down the line. The uninstaller fails and reverts its changes. </p> <p>This means I can't remove the package from my machine, and hence can't install any further builds of my installer (a considerable inconvenience). How can I force removal of the package?</p>
9,709,964
7
5
null
2012-03-14 11:01:36.58 UTC
9
2020-03-12 01:15:30.69 UTC
2018-06-09 18:50:42.367 UTC
null
3,261,150
null
319,618
null
1
31
wix|windows-installer|uninstallation
7,664
<blockquote> <p><strong><em>Update, Stein Åsmul</em></strong>: <a href="https://stackoverflow.com/questions/53876550/wix-custom-action-dialogbox-on-silent-uninstall-of-application/53876981#53876981"><strong>Injecting this newer list of cleanup approaches</strong></a>.</p> </blockquote> <hr> <ol> <li><p>Find your package in <code>C:\Windows\Installer</code>, where Windows keeps copies of installed MSI packages. The names are generated randomly, so you'll have to look at the creation dates of the files.</p></li> <li><p>Open the MSI file with <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa370557(v=vs.85).aspx" rel="nofollow noreferrer">Orca</a>. (Unfortunately there is no simple download for the orca installer. You can get it by installing the "MSI Tools" of the <a href="https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk" rel="nofollow noreferrer">Windows 10 SDK</a>, and then searching for orca.msi in <code>C:\Program Files (x86)\Windows Kits</code>.)</p></li> <li><p>Delete the offending custom action from the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa368062(v=vs.85).aspx" rel="nofollow noreferrer">CustomAction table</a> </p></li> </ol> <p>Now you should be able to uninstall the package.</p> <p><strong><em>UPDATE</em></strong>: <a href="https://stackoverflow.com/a/47208200/129130">You can find the actual cache MSI file using Powershell</a>. That was for one package, <a href="https://stackoverflow.com/a/29937569/129130">you can also get for all packages</a> (scroll down to first screenshot).</p>
10,103,551
passing data to subprocess.check_output
<p>I want to invoke a script, piping the contents of a string to its stdin and retrieving its stdout.</p> <p>I don't want to touch the real filesystem so I can't create real temporary files for it.</p> <p>using <code>subprocess.check_output</code> I can get whatever the script writes; how can I get the input string into its stdin though?</p> <pre><code>subprocess.check_output([script_name,"-"],stdin="this is some input") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/subprocess.py", line 537, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/usr/lib/python2.7/subprocess.py", line 672, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "/usr/lib/python2.7/subprocess.py", line 1043, in _get_handles p2cread = stdin.fileno() AttributeError: 'str' object has no attribute 'fileno' </code></pre>
10,103,704
3
3
null
2012-04-11 09:48:36.613 UTC
4
2015-05-05 23:25:23.62 UTC
null
null
null
null
15,721
null
1
37
python
19,438
<p>Use <code>Popen.communicate</code> instead of <code>subprocess.check_output</code>.</p> <pre><code>from subprocess import Popen, PIPE p = Popen([script_name, "-"], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate("this is some input") </code></pre>
44,058,487
Why do gcc and clang each produce different output for this program? (conversion operator vs constructor)
<p>program:</p> <pre><code>#include &lt;stdio.h&gt; struct bar_t { int value; template&lt;typename T&gt; bar_t (const T&amp; t) : value { t } {} // edit: You can uncomment these if your compiler supports // guaranteed copy elision (c++17). Either way, it // doesn't affect the output. // bar_t () = delete; // bar_t (bar_t&amp;&amp;) = delete; // bar_t (const bar_t&amp;) = delete; // bar_t&amp; operator = (bar_t&amp;&amp;) = delete; // bar_t&amp; operator = (const bar_t&amp;) = delete; }; struct foo_t { operator int () const { return 1; } operator bar_t () const { return 2; } }; int main () { foo_t foo {}; bar_t a { foo }; bar_t b = static_cast&lt;bar_t&gt;(foo); printf("%d,%d\n", a.value, b.value); } </code></pre> <p>output for <strong>gcc</strong> 7/8:</p> <pre><code>2,2 </code></pre> <p>output for <strong>clang</strong> 4/5 (also for gcc 6.3)</p> <pre><code>1,1 </code></pre> <p>It seems that the following is happening when creating the instances of <code>bar_t</code>:</p> <p>For <strong>gcc</strong>, it <code>calls foo_t::operator bar_t</code> then <code>constructs bar_t with T = int</code>.</p> <p>For <strong>clang</strong>, it <code>constructs bar_t with T = foo_t</code> then <code>calls foo_t::operator int</code></p> <p>Which compiler is correct here? (or maybe they are both correct if this is some form of undefined behaviour)</p>
44,059,650
1
12
null
2017-05-18 22:07:24.45 UTC
6
2017-05-20 16:39:17.017 UTC
2017-05-20 16:39:17.017 UTC
null
3,547,503
null
3,547,503
null
1
35
c++|gcc|clang|language-lawyer|compiler-bug
4,433
<p>I believe clang's result is correct.</p> <p>In both <code>bar_t a { foo }</code> direct-list-initialization and in a static_cast between user defined types, constructors of the destination type are considered before user defined conversion operators on the source type (C++14 [dcl.init.list]/3 [expr.static.cast]/4). If overload resolution finds a suitable constructor then it's used.</p> <p>When doing overload resolution <code>bar_t::bar_t&lt;foo_t&gt;(const foo_t&amp;)</code> is viable and will be a better match than one to any instantiation of this template resulting in the use of the cast operators on foo. It will also be better than any default declared constructors since they take something other than <code>foo_t</code>, so <code>bar_t::bar_t&lt;foo_t&gt;</code> is used.</p> <hr> <p>The code as currently written depends on C++17 guaranteed copy elision; If you compile without C++17's guaranteed copy elision (e.g. <code>-std=c++14</code>) then clang does reject this code due to the copy-initialization in <code>bar_t b = static_cast&lt;bar_t&gt;(foo);</code>.</p>
9,829,175
Pip install Matplotlib error with virtualenv
<p>I am trying to install matplotlib in a new virtualenv. </p> <p>When I do: </p> <pre><code>pip install matplotlib </code></pre> <p>or</p> <pre><code>pip install http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz </code></pre> <p>I get this error:</p> <pre><code>building 'matplotlib._png' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -fPIC - DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/usr/local/include -I/usr/include -I. -I/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/numpy/core/include -I. -I/usr/include/python2.7 -c src/_png.cpp -o build/temp.linux-x86_64-2.7/src/_png.o src/_png.cpp:10:20: fatal error: png.h: No such file or directory compilation terminated. error: command 'gcc' failed with exit status 1 </code></pre> <p>Anyone have an idea what is going on?</p> <p>Any help much appreciated.</p>
9,843,560
12
1
null
2012-03-22 19:28:30.893 UTC
47
2021-11-23 12:10:44.63 UTC
2015-09-14 20:34:35.723 UTC
null
325,565
null
791,335
null
1
108
python|matplotlib|pip|virtualenv
132,319
<p>Building Matplotlib requires <code>libpng</code> (and <code>freetype</code>, as well) which isn't a python library, so <code>pip</code> doesn't handle installing it (or <code>freetype</code>). </p> <p>You'll need to install something along the lines of <code>libpng-devel</code> and <code>freetype-devel</code> (or whatever the equivalent is for your OS).</p> <p>See the <a href="http://matplotlib.sourceforge.net/users/installing.html#build-requirements">building requirements/instructions</a> for matplotlib.</p>
9,646,407
Two forward slashes in a url/src/href attribute
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4071117/uri-starting-with-two-slashes-how-do-they-behave">URI starting with two slashes &hellip; how do they behave?</a><br> <a href="https://stackoverflow.com/questions/4978235/absolute-urls-omitting-the-protocol-scheme-in-order-to-preserve-the-one-of-the">Absolute URLs omitting the protocol (scheme) in order to preserve the one of the current page</a><br> <a href="https://stackoverflow.com/questions/6503946/shorthand-http-as-for-script-and-link-tags-anyone-see-use-this-before">shorthand as // for script and link tags? anyone see / use this before?</a> </p> </blockquote> <p>I was looking through the source of <a href="https://github.com/murtaugh/HTML5-Reset" rel="noreferrer">HTML5 Reset</a> when I noticed the <a href="https://github.com/murtaugh/HTML5-Reset/blob/master/index.html#L113" rel="noreferrer">following line</a>:</p> <pre><code>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"&gt;&lt;/script&gt; </code></pre> <p>Why does the URL start with two forward slashes? Is this a shorthand for <code>http://</code>?</p>
9,646,435
2
2
null
2012-03-10 12:28:08.137 UTC
46
2022-01-04 00:31:05.65 UTC
2017-05-23 12:34:25.273 UTC
null
-1
null
597,130
null
1
162
html|http|https|relative-url
71,879
<h1>The &quot;two forward slashes&quot; are a common shorthand for &quot;request the referenced resource using whatever protocol is being used to load the current page&quot;.</h1> <p>Best known as &quot;protocol relative URLs&quot;, they are particularly useful when elements — such as the JS file in your example — could be served and/or requested from either a <code>http</code> or a <code>https</code> context. By using protocol relative URLs, you can avoid implementing</p> <pre><code>if (window.location.protocol === 'http:') { myResourceUrl = 'http://example.com/my-resource.js'; } else { myResourceUrl = 'https://example.com/my-resource.js'; } </code></pre> <p>type of logic all over your codebase (assuming, of course, that the server at <code>example.com</code> is able to serve content through both <code>http</code> and <code>https</code>).</p> <p>A prominent real-world example is the Magento 1.X E-Commerce engine: for performance reasons, the category and product pages use plain <code>http</code> by default, whereas the checkout is <code>https</code> enabled.</p> <p>If some resources (e.g. promotional banners in the site's header) are referenced via non protocol relative URLs (i.e. <code>http://example.com/banner.jpg</code>), customers reaching the <code>https</code> enabled checkout are greeted with a rather unfriendly</p> <blockquote> <p>&quot;there are insecure elements on this page&quot;</p> </blockquote> <p>prompt - which, one can safely assume, isn't exactly great for business.</p> <p>If the aforementioned resource is referenced via <code>//example.com/banner.jpg</code> though, the browser takes care of loading it via the proper protocol both on the plain http product/category pages and in the https-enabled checkout flow.</p> <p><strong>tl;dr: With even the slightest possibility of a mixed http/https environment, just use the double slash/protocol relative URLs to reference resources — assuming that the host serving them supports both http and https.</strong></p>
8,068,717
JRockit JVM versus HotSpot JVM
<p>If anyone can give me brief information about the advantages and disadvantages of the two JVM since they all depend on the Standard JVM Specification.</p>
9,542,679
3
0
null
2011-11-09 17:06:41.007 UTC
10
2015-08-16 17:13:31.887 UTC
2012-03-23 20:16:14.123 UTC
null
988
null
1,099,180
null
1
49
java|jvm|jvm-hotspot|jrockit
24,849
<p>JRockit was originally developed by Appeal and BEA Systems before being acquired by Oracle to run server software.<sup>1</sup> It was meant to be optimized for large applications requiring long running tasks, a lot of memory and a scalable environment, pushing optimizations for these scenarios even further than the Sun HotSpot JVM in <a href="http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#compiler_types" rel="noreferrer">server-mode</a> (see also: <a href="https://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client">Real differences between &quot;java -server&quot; and &quot;java -client&quot;?</a>).</p> <p>Since the acquisition of Sun Microsystems by Oracle, Oracle has communicated on a <a href="https://blogs.oracle.com/henrik/entry/oracles_jvm_strategy" rel="noreferrer">concrete plan and roadmap to have JRockit and the HotSpot JVM to converge</a> to be a "best of both worlds" implementation, mostly built on HotSpot but integrating the most popular features of JRockit.</p> <p>In fact, and as mentioned on the same blog, <a href="https://blogs.oracle.com/henrik/entry/java_7_questions_answers" rel="noreferrer">JRockit won't be released as a Java 7 JVM</a>; and some of JRockit's features are being incrementally brought into HotSpot (<a href="http://www.eclipsecon.org/2012/sessions/state-jrockit-hotspot-convergence-presented-oracle" rel="noreferrer">internally even sometimes now referred to as "HotRockit"</a>).</p> <p>For more details, read:</p> <ul> <li><a href="http://weblogicserveradministration.blogspot.com/2010/11/differences-between-bea-jrockit-sdk-and.html" rel="noreferrer">Differences Between BEA JRockit SDK and Sun HotSpot SDK</a></li> <li><a href="https://stackoverflow.com/questions/747360/difference-between-jvm-implementations">Differences between JVM implementations</a></li> </ul> <hr> <p><sup>1 <em>As partially pulled from <a href="http://en.wikipedia.org/wiki/JRockit" rel="noreferrer">Wikipedia</a> on March 3, 2012 at 1.50PM EST.</em></sup></p>
8,188,605
Mercurial (hg) commit only certain files
<p>I'm trying to commit only certain files with Mercurial. Because of of hg having auto-add whenever I try to commit a change it wants to commit all files. But I don't want that because certain files are not "ready" yet.</p> <p>There is</p> <pre><code>hg commit -I thefile.foo </code></pre> <p>but this is only for one file. The better way for me would be if I can turn off auto-add as in Git. Is this possible?</p>
8,341,651
3
4
null
2010-03-09 18:33:45.233 UTC
18
2018-02-22 09:51:33.243 UTC
2016-12-24 19:38:43.723 UTC
null
462,627
user287689
null
null
1
134
version-control|mercurial|commit
69,965
<p>You can specify the files on the command line, as tonfa writes:</p> <pre><code>$ hg commit foo.c foo.h dir/ </code></pre> <p>That just works and that's what I do all the time. You can also use the <code>--include</code> flag that you've found, and you can use it several times like this:</p> <pre><code>$ hg commit -I foo.c -I "**/*.h" </code></pre> <p>You can even use a <a href="http://www.selenic.com/mercurial/hg.1.html#filesets" rel="noreferrer">fileset</a> to select the files you want to commit:</p> <pre><code>$ hg commit "set:size(1k - 1MB) and not binary()" </code></pre> <p>There is no setting that will turn off the auto-add behavior and make Mercurial work like Git does. However, the <a href="https://www.mercurial-scm.org/wiki/MqExtension" rel="noreferrer">mq extension</a> might be of interest. That's an advanced extension, but it allows you do to</p> <pre><code>$ hg qnew feature-x # create new patch $ hg qrefresh -s foo.c # add a file to the current patch $ hg qrefresh -s bar.c # add another file to the patch $ hg qfinish -a # convert applied patches to normal changesets </code></pre> <p>I don't really use MQ for this purpose myself, though, since I think it's enough to just specify the filenames on the command line.</p>
11,697,709
Comparing two lists in Python
<p>So to give a rough example without any code written for it yet, I'm curious on how I would be able to figure out what both lists have in common.</p> <p>Example:</p> <pre><code>listA = ['a', 'b', 'c'] listB = ['a', 'h', 'c'] </code></pre> <p>I'd like to be able to return:</p> <pre><code>['a', 'c'] </code></pre> <p>How so?</p> <p>Possibly with variable strings like:</p> <pre><code>john = 'I love yellow and green' mary = 'I love yellow and red' </code></pre> <p>And return:</p> <pre><code>'I love yellow and' </code></pre>
11,697,720
4
0
null
2012-07-28 02:19:23.533 UTC
5
2020-07-07 10:40:05.707 UTC
null
null
null
null
710,489
null
1
10
python|string|list|variables|comparison
63,985
<p>Use set intersection for this:</p> <pre><code>list(set(listA) &amp; set(listB)) </code></pre> <p>gives:</p> <pre><code>['a', 'c'] </code></pre> <p>Note that since we are dealing with <em>sets</em> this may <em>not</em> preserve order:</p> <pre><code>' '.join(list(set(john.split()) &amp; set(mary.split()))) 'I and love yellow' </code></pre> <p>using <code>join()</code> to convert the resulting list into a string.</p> <p>--</p> <p>For your example/comment below, this <em>will preserve order</em> (inspired by comment from @DSM)</p> <pre><code>' '.join([j for j, m in zip(john.split(), mary.split()) if j==m]) 'I love yellow and' </code></pre> <p>For a case where the list aren't the same length, with the result as specified in the comment below:</p> <pre><code>aa = ['a', 'b', 'c'] bb = ['c', 'b', 'd', 'a'] [a for a, b in zip(aa, bb) if a==b] ['b'] </code></pre>
11,739,715
how to redirect in node.js
<p>I'm having some issues with redirecting between directories, the problem is I can manage to redirect to another file in different directory. My directory structure looks like this:</p> <pre><code>-views -add_user.jade -routes -index.js </code></pre> <p>I try to redirect to <em>add</em>_ <em>user.jade</em> from <em>index.js</em>, how would you guys do it</p> <pre><code>res.redirect('???'); </code></pre> <hr> <p>If <em>index.js</em> in the same directory as <strong>views</strong>, the code below works</p> <pre><code>-index.js -views -add_user.jade res.redirect('./add_users'); </code></pre>
11,740,264
4
0
null
2012-07-31 12:05:14.67 UTC
5
2022-07-17 11:09:08.82 UTC
null
null
null
null
1,326,868
null
1
26
javascript|node.js|redirect|web|express
44,996
<p>You want to redirect to the <strong>URL</strong> (not the view name) that you want the user to go to. </p> <p>For example, if the route <code>"/user/add"</code> renders the <code>"add_user.jade"</code> view then you want to use</p> <pre><code> res.redirect("/user/add"); </code></pre>
11,463,888
Compiler bug when using generics and forward declaration in Delphi XE2
<p>I started project on Delphi 2010, then migrated to XE and now I try to migrate to XE2. After compiling in XE2 (Update 4 Hotfix 1), unit tests began fail with AV. After some debugging, it became clear that the following code is not correctly compiled:</p> <pre><code>program ForwardDeclaration; {$APPTYPE CONSOLE} uses System.SysUtils; type TEntityBase = class(TObject) protected FModel: Integer; public constructor Create(const AModel: Integer); end; TEntity&lt;TKey&gt; = class(TEntityBase) end; TMyEntity2 = class; TMyEntity1 = class(TEntity&lt;Integer&gt;) FData: Integer; end; TMyEntity2 = class(TMyEntity1) end; constructor TEntityBase.Create(const AModel: Integer); begin inherited Create; FModel := AModel; end; var MyEntity: TMyEntity1; begin try Writeln(TEntityBase.ClassName, ': ', TEntityBase.InstanceSize, ' bytes'); Writeln(TMyEntity1.ClassName, ': ', TMyEntity1.InstanceSize, ' bytes'); MyEntity := TMyEntity1.Create(100); Assert(MyEntity.FData = 0); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. </code></pre> <p>Program outputs:</p> <pre><code>TEntityBase: 12 bytes TMyEntity1: 12 bytes &lt;-- Must be 16 bytes! EAssertionFailed: Assertion failure (ForwardDeclaration.dpr, line 41) </code></pre> <p>Is it possible to resolve the problem by tuning compiler options?</p> <p>Whether this problem repeats at someone else?</p> <p>P.S. <a href="http://qc.embarcadero.com/wc/qcmain.aspx?d=107110">QC107110</a></p>
18,747,276
1
7
null
2012-07-13 03:53:07.51 UTC
1
2013-09-11 17:09:43.38 UTC
2012-07-13 08:33:08.95 UTC
null
1,106,253
null
1,106,253
null
1
45
delphi|delphi-xe2
1,352
<blockquote> <p><em>Is it possible to resolve the problem by tuning compiler options?</em> </p> </blockquote> <p><strong>No</strong>, you cannot fix the error by tuning, it's a (very specific) bug in the compiler. </p> <blockquote> <p><em>[Can someone tell me] Whether this problem repeats at someone else?</em> </p> </blockquote> <p>I can reproduce the code, but only in XE2 update 4. </p> <p>I was not able to check it in XE3 (don't have that version). It is fixed in XE4 (as per the comments). </p> <p>So the only way to have the code to work is to: </p> <p>a. remove the unneeded forward declaration.<br> b. use a different version of Delphi.</p>
11,831,946
NSManagedObjectContext performBlockAndWait: doesn't execute on background thread?
<p>I have an NSManagedObjectContext declared like so:</p> <pre><code>- (NSManagedObjectContext *) backgroundMOC { if (backgroundMOC != nil) { return backgroundMOC; } backgroundMOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; return backgroundMOC; } </code></pre> <p>Notice that it is declared with a private queue concurrency type, so its tasks should be run on a background thread. I have the following code:</p> <pre><code>-(void)testThreading { /* ok */ [self.backgroundMOC performBlock:^{ assert(![NSThread isMainThread]); }]; /* CRASH */ [self.backgroundMOC performBlockAndWait:^{ assert(![NSThread isMainThread]); }]; } </code></pre> <p>Why does calling <code>performBlockAndWait</code> execute the task on the main thread rather than background thread?</p>
11,833,139
4
0
null
2012-08-06 16:07:09.113 UTC
47
2012-10-10 11:27:08.013 UTC
null
null
null
null
458,960
null
1
45
iphone|objective-c|ios|core-data
19,809
<p>Tossing in another answer, to try an explain why <code>performBlockAndWait</code> will always run in the calling thread.</p> <p><code>performBlock</code> is completely asynchronous. It will always enqueue the block onto the queue of the receiving MOC, and then return immediately. Thus,</p> <pre><code>[moc performBlock:^{ // Foo }]; [moc performBlock:^{ // Bar }]; </code></pre> <p>will place two blocks on the queue for moc. They will always execute asynchronously. Some unknown thread will pull blocks off of the queue and execute them. In addition, those blocks are wrapped within their own autorelease pool, and also they will represent a complete Core Data user event (<code>processPendingChanges</code>).</p> <p><code>performBlockAndWait</code> does NOT use the internal queue. It is a synchronous operation that executes in the context of the calling thread. Of course, it will wait until the current operations on the queue have been executed, and then that block will execute in the calling thread. This is documented (and reasserted in several WWDC presentations).</p> <p>Furthermore, <code>performBockAndWait</code> is re-entrant, so nested calls all happen right in that calling thread.</p> <p>The Core Data engineers have been very clear that the actual thread in which a queue-based MOC operation runs is not important. It's the synchronization by using the <code>performBlock*</code> API that's key.</p> <p>So, consider 'performBlock' as "This block is being placed on a queue, to be executed at some undetermined time, in some undetermined thread. The function will return to the caller as soon as it has been enqueued"</p> <p><code>performBlockAndWait</code> is "This block will be executed at some undetermined time, in this exact same thread. The function will return after this code has completely executed (which will occur after the current queue associated with this MOC has drained)."</p> <p><strong>EDIT</strong></p> <blockquote> <p>Are you sure of "performBlockAndWait does NOT use the internal queue"? I think it does. The only difference is that performBlockAndWait will wait until the block's completion. And what do you mean by calling thread? In my understanding, [moc performBlockAndWait] and [moc performBloc] both run on its private queue (background or main). The important concept here is moc owns the queue, not the other way around. Please correct me if I am wrong. – Philip007</p> </blockquote> <p>It is unfortunate that I phrased the answer as I did, because, taken by itself, it is incorrect. However, in the context of the original question it is correct. Specifically, when calling <code>performBlockAndWait</code> on a private queue, the block will execute on the thread that called the function - it will not be put on the queue and executed on the "private thread."</p> <p>Now, before I even get into the details, I want to stress that depending on internal workings of libraries is very dangerous. All you should really care about is that you can never expect a specific thread to execute a block, except anything tied to the main thread. Thus, expecting a <code>performBlockAndWait</code> to <em>not</em> execute on the main thread is not advised because it will execute on the thread that called it.</p> <p><code>performBlockAndWait</code> uses GCD, but it also has its own layer (e.g., to prevent deadlocks). If you look at the GCD code (which is open source), you can see how synchronous calls work - and in general they synchronize with the queue and invoke the block on the thread that called the function - unless the queue is the main queue or a global queue. Also, in the WWDC talks, the Core Data engineers stress the point that <code>performBlockAndWait</code> will run in the calling thread.</p> <p>So, when I say it does not use the internal queue, that does not mean it does not use the data structures at all. It must synchronize the call with the blocks already on the queue, and those submitted in other threads and other asynchronous calls. However, when calling <code>performBlockAndWait</code> it does not put the block on the queue... instead it synchronizes access and runs the submitted block on the thread that called the function.</p> <p>Now, SO is not a good forum for this, because it's a bit more complex than that, especially w.r.t the main queue, and GCD global queues - but the latter is not important for Core Data.</p> <p>The main point is that when you call any <code>performBlock*</code> or GCD function, you should not expect it to run on any particular thread (except something tied to the main thread) because queues are not threads, and only the main queue will run blocks on a specific thread.</p> <p>When calling the core data <code>performBlockAndWait</code> the block will execute in the calling thread (but will be appropriately synchronized with everything submitted to the queue).</p> <p>I hope that makes sense, though it probably just caused more confusion.</p> <p><strong>EDIT</strong></p> <p>Furthermore, you can see the unspoken implications of this, in that the way in which <code>performBlockAndWait</code> provides re-entrant support breaks the FIFO ordering of blocks. As an example...</p> <pre><code>[context performBlockAndWait:^{ NSLog(@"One"); [context performBlock:^{ NSLog(@"Two"); }]; [context performBlockAndWait:^{ NSLog(@"Three"); }]; }]; </code></pre> <p>Note that strict adherence to the FIFO guarantee of the queue would mean that the nested <code>performBlockAndWait</code> ("Three") would run after the asynchronous block ("Two") since it was submitted after the async block was submitted. However, that is not what happens, as it would be impossible... for the same reason a deadlock ensues with nested <code>dispatch_sync</code> calls. Just something to be aware of if using the synchronous version.</p> <p>In general, avoid sync versions whenever possible because <code>dispatch_sync</code> can cause a deadlock, and any re-entrant version, like <code>performBlockAndWait</code> will have to make some "bad" decision to support it... like having sync versions "jump" the queue.</p>
12,023,359
What do the return values of node.js process.memoryUsage() stand for?
<p>From the official documentation (<a href="http://nodejs.org/api/process.html#process_process_memoryusage">source</a>):</p> <blockquote> <p><strong>process.memoryUsage()</strong></p> <p>Returns an object describing the memory usage of the Node process measured in bytes.</p> <pre><code>var util = require('util'); console.log(util.inspect(process.memoryUsage())); </code></pre> <p>This will generate:</p> <pre><code>{ rss: 4935680, heapTotal: 1826816, heapUsed: 650472 } </code></pre> <p>heapTotal and heapUsed refer to V8's memory usage.</p> </blockquote> <p>Exactly what do <strong>rss</strong>, <strong>heapTotal</strong>, and <strong>heapUsed</strong> stand for? </p> <p>It might seem like a trivial question, but I've been looking and I could not find a clear answer so far.</p>
38,049,633
5
0
null
2012-08-19 00:45:58.527 UTC
40
2022-05-01 10:33:53.843 UTC
2016-06-27 08:57:13.57 UTC
null
1,074,944
null
1,329,367
null
1
161
node.js|v8
49,479
<p>In order to answer this question, one has to understand V8’s Memory Scheme first.</p> <p>A running program is always represented through some space allocated in memory. This space is called <strong>Resident Set</strong>. V8 uses a scheme similar to the Java Virtual Machine and divides the memory into segments: </p> <ul> <li><strong>Code</strong>: the actual code being executed </li> <li><strong>Stack</strong>: contains all value types (primitives like integer or Boolean) with pointers referencing objects on the heap and pointers defining the control flow of the program </li> <li><strong>Heap</strong>: a memory segment dedicated to storing reference types like objects, strings and closures. <a href="https://i.stack.imgur.com/I188N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/I188N.png" alt="enter image description here"></a></li> </ul> <p>Now it is easy to answer the question:</p> <ul> <li><strong>rss</strong>: Resident Set Size</li> <li><strong>heapTotal</strong>: Total Size of the Heap</li> <li><strong>heapUsed</strong>: Heap actually Used</li> </ul> <p><strong>Ref</strong>: <a href="http://apmblog.dynatrace.com/2015/11/04/understanding-garbage-collection-and-hunting-memory-leaks-in-node-js/" rel="noreferrer">http://apmblog.dynatrace.com/2015/11/04/understanding-garbage-collection-and-hunting-memory-leaks-in-node-js/</a></p>
3,302,434
capturing groups in sed
<p>I have many lines of the form</p> <pre><code>ko04062 ko:CXCR3 ko04062 ko:CX3CR1 ko04062 ko:CCL3 ko04062 ko:CCL5 ko04080 ko:GZMA </code></pre> <p>and would dearly like to get rid of the ko: bit of the right-hand column. I'm trying to use sed, as follows:</p> <pre><code>echo "ko05414 ko:ITGA4" | sed 's/\(^ko\d{5}\)\tko:\(.*$\)/\1\2/' </code></pre> <p>which simply outputs the original string I echo'd. I'm very new to command line scripting, sed, pipes etc, so please don't be too angry if/when I'm doing something extremely dumb. </p> <p>The main thing that is confusing me is that the same thing happens if I reverse the <code>\1\2</code> bit to read <code>\2\1</code> or just use one group. This, I guess, implies that I'm missing something about the mechanics of piping the output of echo into sed, or that my regexp is wrong or that I'm using sed wrong or that sed isn't printing the results of the substitution.</p> <p>Any help would be greatly appreciated!</p>
3,302,593
4
5
null
2010-07-21 18:17:46.49 UTC
3
2014-03-28 18:47:55.797 UTC
2014-01-13 19:09:03.917 UTC
null
1,339,987
null
270,572
null
1
24
command-line|sed
50,186
<p>sed is outputting its input because the substitution isn't matching. Since you're probably using GNU sed, try this:</p> <pre><code>echo "ko05414 ko:ITGA4" | sed 's/\(^ko[0-9]\{5\}\)\tko:\(.*$\)/\1\2/' </code></pre> <ul> <li>\d -> [0-9] since GNU sed doesn't recognize \d</li> <li>{} -> \{\} since GNU sed by default uses basic regular expressions.</li> </ul>
4,036,198
Does Task.Wait(int) stop the task if the timeout elapses without the task finishing?
<p>I have a task and I expect it to take under a second to run but if it takes longer than a few seconds I want to cancel the task. </p> <p>For example: </p> <pre><code>Task t = new Task(() =&gt; { while (true) { Thread.Sleep(500); } }); t.Start(); t.Wait(3000); </code></pre> <p>Notice that after 3000 milliseconds the wait expires. Was the task canceled when the timeout expired or is the task still running?</p>
4,036,380
5
4
null
2010-10-27 17:59:09.68 UTC
10
2021-09-27 05:47:00.397 UTC
2012-08-05 10:49:50.93 UTC
null
783,681
null
29,277
null
1
36
c#|.net|multithreading|task-parallel-library|task
46,851
<p>If you want to cancel a <code>Task</code>, you should pass in a <code>CancellationToken</code> when you create the task. That will allow you to cancel the <code>Task</code> from the outside. You could tie cancellation to a timer if you want. </p> <p>To create a Task with a Cancellation token see this example:</p> <pre><code>var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; var t = Task.Factory.StartNew(() =&gt; { // do some work if (token.IsCancellationRequested) { // Clean up as needed here .... } token.ThrowIfCancellationRequested(); }, token); </code></pre> <p>To cancel the <code>Task</code> call <code>Cancel()</code> on the <code>tokenSource</code>. </p>
3,969,059
SQL Case Sensitive String Compare
<p>How do you compare strings so that the comparison is true only if the cases of each of the strings are equal as well. For example:</p> <pre><code>Select * from a_table where attribute = 'k' </code></pre> <p>...will return a row with an attribute of 'K'. I do not want this behaviour.</p>
3,969,095
6
2
null
2010-10-19 13:52:58.307 UTC
49
2021-02-26 22:18:45.287 UTC
2019-05-17 19:52:36.033 UTC
null
73,794
null
228,489
null
1
295
sql|sql-server
257,827
<pre><code>Select * from a_table where attribute = 'k' COLLATE Latin1_General_CS_AS </code></pre> <p>Did the trick.</p>
3,769,781
std::pair of references
<p>Is it valid to have a <code>std::pair</code> of references ? In particular, are there issues with the assignment operator ? According to <a href="http://www.cplusplus.com/reference/std/utility/pair/" rel="noreferrer">this link</a>, there seems to be no special treatment with operator=, so default assignement operator will not be able to be generated.</p> <p>I'd like to have a <code>pair&lt;T&amp;, U&amp;&gt;</code> and be able to assign to it another pair (of values or references) and have the pointed-to objects modified.</p>
3,772,377
8
6
null
2010-09-22 13:35:15.653 UTC
6
2021-08-03 13:22:44.83 UTC
2018-08-25 12:02:30.097 UTC
null
3,204,551
null
373,025
null
1
41
c++|std
28,799
<p>No, you <strong>cannot</strong> do this reliably in C++03, because the constructor of <code>pair</code> takes references to <code>T</code>, and creating a <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#106" rel="nofollow noreferrer">reference to a reference is not legal</a> in C++03. </p> <p>Notice that I said "reliably". Some common compilers still in use (for GCC, I tested GCC4.1, <a href="https://stackoverflow.com/users/19563/charles-bailey">@Charles</a> reported GCC4.4.4) do not allow forming a reference to a reference, but more recently <em>do</em> allow it as they implement reference collapsing (<code>T&amp;</code> is <code>T</code> if <code>T</code> is a reference type). If your code uses such things, you cannot rely on it to work on other compilers until you try it and see.</p> <p>It sounds like you want to use <code>boost::tuple&lt;&gt;</code></p> <pre><code>int a, b; // on the fly boost::tie(a, b) = std::make_pair(1, 2); // as variable boost::tuple&lt;int&amp;, int&amp;&gt; t = boost::tie(a, b); t.get&lt;0&gt;() = 1; t.get&lt;1&gt;() = 2; </code></pre>
3,406,942
How exactly does java compilation take place?
<p>Confused by java compilation process</p> <p>OK i know this: We write java source code, the compiler which is platform independent translates it into bytecode, then the jvm which is platform dependent translates it into machine code.</p> <p>So from start, we write java source code. The compiler javac.exe is a .exe file. What exactly is this .exe file? Isn't the java compiler written in java, then how come there is .exe file which executes it? If the compiler code is written is java, then how come compiler code is executed at the compilation stage, since its the job of the jvm to execute java code. How can a language itself compile its own language code? It all seems like chicken and egg problem to me.</p> <p>Now what exactly does the .class file contain? Is it a abstract syntax tree in text form, is it tabular information, what is it?</p> <p>can anybody tell me clear and detailed way about how my java source code gets converted in machine code.</p>
3,407,196
9
4
null
2010-08-04 15:12:22.53 UTC
46
2019-07-26 15:24:20.813 UTC
null
null
null
null
410,942
null
1
64
java|compiler-construction|jvm
48,281
<blockquote> <p>OK i know this: We write java source code, the compiler which is platform independent translates it into bytecode,</p> </blockquote> <p>Actually the compiler itself <em>works</em> as a native executable (hence javac.exe). And true, it transforms source file into bytecode. The bytecode is platform independent, because it's targeted at Java Virtual Machine.</p> <blockquote> <p>then the jvm which is platform dependent translates it into machine code.</p> </blockquote> <p>Not always. As for Sun's JVM there are two jvms: client and server. They both can, but not certainly have to compile to native code.</p> <blockquote> <p>So from start, we write java source code. The compiler javac.exe is a .exe file. What exactly is this .exe file? Isn't the java compiler written in java, then how come there is .exe file which executes it?</p> </blockquote> <p>This <code>exe</code> file is a wrapped java bytecode. It's for convenience - to avoid complicated batch scripts. It starts a JVM and executes the compiler.</p> <blockquote> <p>If the compiler code is written is java, then how come compiler code is executed at the compilation stage, since its the job of the jvm to execute java code.</p> </blockquote> <p>That's exactly what wrapping code does.</p> <blockquote> <p>How can a language itself compile its own language code? It all seems like chicken and egg problem to me.</p> </blockquote> <p>True, confusing at first glance. Though, it's not only Java's idiom. The Ada's compiler is also written in Ada itself. It may look like a "chicken and egg problem", but in truth, it's only a bootstrapping problem.</p> <blockquote> <p>Now what exactly does the .class file contain? Is it an abstract syntax tree in text form, is it tabular information, what is it?</p> </blockquote> <p>It's not Abstract Syntax Tree. AST is only used by tokenizer and compiler at compiling time to represent code in memory. <code>.class</code> file is like an assembly, but for JVM. JVM, in turn, is an abstract machine which can run specialized machine language - targeted only at virtual machine. In it's simplest, <code>.class</code> file has a very similar structure to normal assembly. At the beginning there are declared all static variables, then comes some tables of extern function signatures and lastly the machine code.</p> <p>If You are really curious You can dig into classfile using "javap" utility. Here is sample (obfuscated) output of invoking <code>javap -c Main</code>:</p> <pre><code>0: new #2; //class SomeObject 3: dup 4: invokespecial #3; //Method SomeObject."&lt;init&gt;":()V 7: astore_1 8: aload_1 9: invokevirtual #4; //Method SomeObject.doSomething:()V 12: return </code></pre> <p>So You should have an idea already what it really is.</p> <blockquote> <p>can anybody tell me clear and detailed way about how my java source code gets converted in machine code.</p> </blockquote> <p>I think it should be more clear right now, but here's short summary:</p> <ul> <li><p>You invoke <code>javac</code> pointing to your source code file. The internal <em>reader</em> (or tokenizer) of javac reads your file and builds an actual AST out of it. All syntax errors come from this stage.</p></li> <li><p>The <code>javac</code> hasn't finished its job yet. When it has the AST the true compilation can begin. It's using visitor pattern to traverse AST and resolves external dependencies to add meaning (semantics) to the code. The finished product is saved as a <code>.class</code> file containing bytecode.</p></li> <li><p>Now it's time to run the thing. You invoke <code>java</code> with the name of .class file. Now the JVM starts again, but to <em>interpret</em> Your code. The JVM may, or may not compile Your abstract bytecode into the native assembly. The Sun's HotSpot compiler in conjunction with Just In Time compilation may do so if needed. The running code is constantly being profiled by the JVM and recompiled to native code if certain rules are met. Most commonly the <em>hot</em> code is the first to compile natively.</p></li> </ul> <p>Edit: Without the <code>javac</code> one would have to invoke compiler using something similar to this:</p> <pre><code>%JDK_HOME%/bin/java.exe -cp:myclasspath com.sun.tools.javac.Main fileToCompile </code></pre> <p>As you can see it's calling Sun's private API so it's bound to Sun JDK implementation. It would make build systems dependent on it. If one switched to any other JDK (wiki lists 5 other than Sun's) then above code should be updated to reflect the change (since it's unlikely the compiler would reside in com.sun.tools.javac package). Other compilers could be written in native code.</p> <p>So the standard way is to ship <code>javac</code> wrapper with JDK.</p>