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
17,945,341
How to auto generate uuid in cassandra CQL 3 command line
<p>Just learning cassandra, is there a way to insert a UUID using CQL, ie</p> <pre><code>create table stuff (uid uuid primary key, name varchar); insert into stuff (name) values('my name'); // fails insert into stuff (uid, name) values(1, 'my name'); // fails </code></pre> <p>Can you do something like</p> <pre><code>insert into stuff (uid, name) values(nextuid(), 'my name'); </code></pre>
17,945,443
4
0
null
2013-07-30 11:05:37.733 UTC
8
2019-02-12 18:25:26.717 UTC
null
null
null
null
84,118
null
1
51
cassandra|cql|cql3
73,696
<p>You can with time uuids (type 1 UUID) using the <a href="https://docs.datastax.com/en/cql/3.3/cql/cql_reference/timeuuid_functions_r.html" rel="noreferrer">now()</a> function e.g.</p> <pre><code>insert into stuff (uid, name) values(now(), 'my name'); </code></pre> <p>Works with uid or timeuuid. It generates a "guaranteed unique" UID value, which also contains the timestamp so is sortable by time.</p> <p>There isn't such a function for type 4 UUIDs though.</p> <hr> <p><strong>UPDATE:</strong> This note pertains to older versions of Cassandra. For newer versions, see below.</p>
18,078,159
android int to hex converting
<p>I have to convert an int to an hex value. This is for example the int value:</p> <pre><code>int_value = -13516; </code></pre> <p>To convert to a hex value i do:</p> <pre><code>hex_value = Integer.toHexString(int_value); </code></pre> <p>The value that I should get is : <code>-34CC</code> (I don't know if i should make it positive). </p> <p>The thing is that doing the conversion that way, the value that I get is: <code>ffff cb34</code></p> <p>Can't I use this function to make this conversion?</p>
18,078,246
6
3
null
2013-08-06 10:52:41.023 UTC
1
2017-11-17 11:47:52.377 UTC
null
null
null
null
2,587,708
null
1
19
android|int|hex
45,249
<p>Documentation says <code>Integer.toHexString</code> returns the hexadecimal representation of the <code>int</code> as an unsigned value.</p> <p>I believe <code>Integer.toString(value, 16)</code> will accomplish what you want.</p>
18,043,452
In jQuery, how do I get the value of a radio button when they all have the same name?
<p>Here is my code:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;Sales Promotion&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="1"&gt;1&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="2"&gt;2&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="3"&gt;3&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="4"&gt;4&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="5"&gt;5&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;button id="submit"&gt;submit&lt;/button&gt; </code></pre> <p>Here is JS:</p> <pre><code>$(function(){ $("#submit").click(function(){ alert($('input[name=q12_3]').val()); }); }); </code></pre> <p>Here is <a href="http://jsfiddle.net/ZkH8n/">JSFIDDLE</a>! Every time I click button it returns 1. Why? Can anyone help me?</p>
18,043,478
7
0
null
2013-08-04 13:29:58.063 UTC
22
2018-12-10 16:17:20.367 UTC
2015-06-19 16:42:30.077 UTC
null
952,580
null
741,395
null
1
108
javascript|jquery
277,900
<p>In your code, jQuery just looks for the first instance of an input with name <code>q12_3</code>, which in this case has a value of <code>1</code>. You want an input with name <code>q12_3</code> that is <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:checked" rel="noreferrer"><code>:checked</code></a>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("#submit").click(() =&gt; { const val = $('input[name=q12_3]:checked').val(); alert(val); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Sales Promotion&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="1"&gt;1&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="2"&gt;2&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="3"&gt;3&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="4"&gt;4&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="5"&gt;5&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;button id="submit"&gt;submit&lt;/button&gt;</code></pre> </div> </div> </p> <p>Note that the above code is <em>not</em> the same as using <code>.is(":checked")</code>. jQuery's <a href="http://api.jquery.com/is/" rel="noreferrer"><code>is()</code></a> function returns a boolean (true or false) and not (an) element(s).</p> <hr> <p>Because this answer keeps getting a lot of attention, I'll also include a vanilla JavaScript snippet.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelector("#submit").addEventListener("click", () =&gt; { const val = document.querySelector("input[name=q12_3]:checked").value; alert(val); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;Sales Promotion&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="1"&gt;1&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="2"&gt;2&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="3"&gt;3&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="4"&gt;4&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="q12_3" value="5"&gt;5&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;button id="submit"&gt;submit&lt;/button&gt;</code></pre> </div> </div> </p>
18,088,955
Markdown: continue numbered list
<p>In the following markdown code I want <code>item 3</code> to start with list number 3. But because of the code block in between markdown starts this list item as a new list. Is there any way to prevent that behaviour?</p> <p>Desired output:</p> <pre><code>1. item 1 2. item 2 ``` Code block ``` 3. item 3 </code></pre> <p>Produced output:</p> <ol> <li>item 1</li> <li>item 2</li> </ol> <p><code> Code block </code></p> <ol> <li>item 3</li> </ol>
18,089,124
15
2
null
2013-08-06 19:36:23.523 UTC
87
2022-06-06 04:21:26.827 UTC
null
null
null
null
1,159,747
null
1
675
markdown
231,190
<p>Use four spaces to indent content between bullet points</p> <pre><code>1. item 1 2. item 2 ``` Code block ``` 3. item 3 </code></pre> <p>Produces:</p> <ol> <li>item 1</li> <li><p>item 2</p> <p><code> Code block </code></p></li> <li>item 3</li> </ol>
6,356,234
If statement inside div tag with Razor MVC3
<p>I'm trying to have an if statement inside a class property of a div tag using the Razor View Engine. How can i get this working and is there perhaps a better way to do this?</p> <pre><code>&lt;div class="eventDay @if(e.Value.Count &lt; 1){Html.Raw("noEvents");}"&gt; </code></pre> <p>If there are no events the CSS class <em>noEvents</em> should be added. Expected result:</p> <pre><code>&lt;div class="eventDay noEvents"&gt; </code></pre>
6,356,295
3
0
null
2011-06-15 10:20:28.55 UTC
5
2011-06-15 10:34:36.143 UTC
2011-06-15 10:27:18.827 UTC
null
214
null
779,441
null
1
30
c#|asp.net-mvc-3|razor
42,874
<pre><code>&lt;div class='eventDay @(e.Value.Count&lt;1?"noEvents":"")'&gt; </code></pre>
11,052,132
Comparing two arrays in C#
<pre><code>bool hasDuplicate = false; int[] a = new int[] {1, 2, 3, 4}; int[] b = new int[] { 5, 6, 1, 2, 7, 8 }; </code></pre> <p>I need compare all elements of array A with element of array B and in case of a duplicate element in B, set hasDuplicate on TRUE.</p>
11,052,517
11
3
null
2012-06-15 14:01:23.6 UTC
3
2018-12-13 21:38:25.983 UTC
2012-10-18 15:15:38.28 UTC
null
783,681
null
379,008
null
1
1
c#|arrays
64,959
<p>Since this is Homework, I will give you a homework answer.</p> <p>Sure, you could use LINQ and rely on <code>SequenceEqual</code>, <code>Intersect</code>, etc, but that is likely not the point of the exercise.</p> <p>Given two arrays, you can iterate over the elements in an array using <code>foreach</code>.</p> <pre><code>int[] someArray; foreach(int number in someArray) { //number is the current item in the loop } </code></pre> <p>So, if you have two arrays that are fairly small, you could loop over each number of the first array, then loop over the all the items in the second array and compare. Let's try that. First, we need to correct your array syntax. It should look something like this:</p> <pre><code> int[] a = new int[] {1, 2, 3, 4}; int[] b = new int[] { 5, 6, 1, 2, 7, 8 }; </code></pre> <p>Note the use of the curly braces <code>{</code>. You were using the syntax to create a N-dimensional array.</p> <pre><code>bool hasDuplicate = false; int[] a = new int[] { 1, 2, 3, 4 }; int[] b = new int[] { 5, 6, 7, 8 }; foreach (var numberA in a) { foreach (var numberB in b) { //Something goes here } } </code></pre> <p>This gets us pretty close. I'd encourage you to try it on your own from here. If you still need help, keep reading.</p> <hr> <p>OK, so we basically need to just check if the numbers are the same. If they are, set <code>hasDuplicate</code> to true.</p> <pre><code>bool hasDuplicate = false; int[] a = new int[] { 8, 1, 2, 3, 4 }; int[] b = new int[] { 5, 6, 7, 8 }; foreach (var numberA in a) { foreach (var numberB in b) { if (numberA == numberB) { hasDuplicate = true; } } } </code></pre> <p>This is a very "brute" force approach. The complexity of the loop is O(n<sup>2</sup>), but that may not matter in your case. The other answers using LINQ are certainly more efficient, and if efficiency is important, you could consider those. Another option is to "stop" the loops using <code>break</code> if <code>hasDuplicate</code> is true, or place this code in a method and use <code>return</code> to exit the method.</p>
23,674,028
Include textbox value in SQL Query
<p>I am trying to search a GridView using a textbox and search button. I think I need a query something like </p> <pre><code>SELECT employeeID, name, position, hourlyPayRate FROM dbo.employee WHERE name LIKE 'textBox1.text+' </code></pre> <p>I have made the query using the query designer in visual studio 2013.</p> <p>I then have an event handler like this </p> <pre><code>private void btnSearch_Click(object sender, EventArgs e) { this.employeeTableAdapter.FillBy(this.personnelDataSet.employee); } </code></pre> <p>I am sure that the problem is in the query but I just don't know how to include the value of the textbox into the query.</p>
23,674,277
5
3
null
2014-05-15 09:17:07.663 UTC
1
2018-03-12 08:13:44.863 UTC
2014-05-15 09:18:19.707 UTC
null
1,928,264
null
3,418,076
null
1
2
c#|sql|textbox|visual-studio-2013
38,965
<p>To just change your query, it should look like:</p> <pre><code>string textboxValue = textbox1.Text; string query = "SELECT employeeID, name, position, hourlyPayRate " + "FROM dbo.employee " + "WHERE name LIKE '" + textboxValue + "'"; </code></pre> <p>But this is vulnerable to SQL injection, you should use a <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx" rel="nofollow"><strong>SqlCommand</strong></a> with <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters%28v=vs.110%29.aspx" rel="nofollow"><strong>parameters</strong></a>:</p> <pre><code>string commandText = "SELECT employeeID, name, position, hourlyPayRate " + "FROM dbo.employee WHERE name LIKE '%'+ @Name + '%'"; using (SqlConnection connection = new SqlConnection(connectionString)) { //Create a SqlCommand instance SqlCommand command = new SqlCommand(commandText, connection); //Add the parameter command.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = textbox1.Text; //Execute the query try { connection.Open(); command.ExecuteNonQuery(); } catch { //Handle exception, show message to user... } finally { connection.Close(); } } </code></pre> <p><strong>Update:</strong></p> <p>To execute this code on the click of a button, place the code here (Make sure youi have a button with name <code>YourButton</code>):</p> <pre><code>private void YourButton_Click(object sender, EventArgs e) { //Place above code here } </code></pre> <p><strong>Update2:</strong></p> <p>You should have a connection string to use in the SqlConnection, this string might look something like:</p> <pre><code>string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"; </code></pre> <p>Here, you have to replace the values that start with <code>my</code> with your own values. More info/examples on connectionstrings for SQL Server:</p> <ul> <li><a href="https://www.connectionstrings.com/sql-server/" rel="nofollow"><strong>SQL Server connection strings</strong></a></li> </ul>
15,950,616
Collecting extra user data in Django Social Auth pipeline
<p>I'm using Django Social Auth (v0.7.22) for registering users via Facebook, and that is working OK. </p> <p>My doubt is how to collect extra data for new users:</p> <ol> <li>How to detect a new user?</li> <li>Where to store the collected data (in the Django session or pass it through pipeline <code>**kwargs</code>)?</li> </ol> <p>My pipeline looks like:</p> <pre><code>SOCIAL_AUTH_PIPELINE = ( 'social_auth.backends.pipeline.social.social_auth_user', 'social_auth.backends.pipeline.misc.save_status_to_session', ## My customs ... 'myapp.pipeline.load_data_new_user', 'myapp.pipeline.handle_new_user', 'myapp.pipeline.username', ## 'social_auth.backends.pipeline.user.create_user', 'social_auth.backends.pipeline.social.associate_user', 'social_auth.backends.pipeline.social.load_extra_data', 'social_auth.backends.pipeline.user.update_user_details', ) </code></pre> <p>The first custom function just collect the Facebook profile picture:</p> <pre><code>def load_data_new_user(backend, response, user, *args, **kwargs): if user is None: if backend.name == "facebook": try: url = "http://graph.facebook.com/%s/picture?width=200&amp;height=200&amp;redirect=false" % response['id'] data = json.loads(urllib2.urlopen(url).read())['data'] return {'avatar': data} except StandardError: return {'avatar': None} else: raise ValueError() </code></pre> <p>My doubts:</p> <ol> <li>I'm checking if <code>user</code> is <code>None</code> for detecting new users (not sure if it's OK to assume that). </li> <li>I'm storing the avatar metadata in the pipeline's <code>**kwargs</code> instead of use sessions, is it OK? When should I use session.</li> </ol> <p>The other custom functions are based on the <a href="https://github.com/omab/django-social-auth/tree/master/example" rel="noreferrer">Matias Aguirre example</a>, and use sessions for storing the username of new users.</p> <pre><code>def handle_new_user(request, user, *args, **kwargs): if user is None and not request.session.get('saved_username'): return HttpResponseRedirect('/form/') def username(request, user, *args, **kwargs): if user is not None: username = user.username else: username = request.session.get('saved_username') return {'username': username} </code></pre> <p>So, I'm not sure when to use sessions or the "correct idiom" for resolve my problem. Thanks in advance.</p>
15,988,662
2
0
null
2013-04-11 13:53:39.987 UTC
9
2013-04-14 02:07:58.053 UTC
2013-04-11 14:00:05.97 UTC
null
623,913
null
623,913
null
1
5
django|django-socialauth
6,961
<p>Matias Aguirre (django socialauth creator) gently answered my question in the <a href="https://groups.google.com/forum/?hl=es&amp;fromgroups=#!topic/django-social-auth/xzDLi48weRM" rel="nofollow">DSA google mail list</a> </p> <p>His answer: </p> <blockquote> <p>Collecting the data is easy as you saw, but where to put it depends on your project, what you plan to do with the data, and where you expect it to be available. For example, if you plan to put the avatar image on a user profile model, then you should get the profile for the current user and store it there, if you use a custom user with an avatar_url field, then you should fill that field after the user was created, if you plan to download the image and store it local to the server using the username (id, etc) as the filename, then just do it that way too. </p> <p>The session is usually used as a mechanism of communication with a view. </p> <p>Regarding the "user is new", there's a flag "is_new" set to True/False when the user is new or not, but it's not updated until the "create_user" is called. </p> <p>The pipeline entry "save_status_to_session" should be placed before the method that breaks the pipeline flow, in your case handle_new_user.</p> </blockquote> <p>Thanks everyone. </p>
19,031,213
Java-get most common element in a list
<p>Does Java or Guava have something that will return most common element in a list?</p> <pre><code>List&lt;BigDecimal&gt; listOfNumbers= new ArrayList&lt;BigDecimal&gt;(); </code></pre> <p>[1,3,4,3,4,3,2,3,3,3,3,3]</p> <p>return 3</p>
19,031,350
10
3
null
2013-09-26 14:36:41.133 UTC
11
2021-05-04 07:36:36.883 UTC
null
null
null
null
748,656
null
1
23
java|guava
49,446
<p>This is fairly easy to implement yourself:</p> <pre><code>public static &lt;T&gt; T mostCommon(List&lt;T&gt; list) { Map&lt;T, Integer&gt; map = new HashMap&lt;&gt;(); for (T t : list) { Integer val = map.get(t); map.put(t, val == null ? 1 : val + 1); } Entry&lt;T, Integer&gt; max = null; for (Entry&lt;T, Integer&gt; e : map.entrySet()) { if (max == null || e.getValue() &gt; max.getValue()) max = e; } return max.getKey(); } </code></pre> <hr> <pre><code>List&lt;Integer&gt; list = Arrays.asList(1,3,4,3,4,3,2,3,3,3,3,3); System.out.println(mostCommon(list)); </code></pre> <pre> 3 </pre> <p>If you want to handle cases where there's more then one most frequent element, you can scan the list once to determine how many times the most frequent element(s) occur, and then scan the list again, put those elements in a set and return that.</p>
34,301,088
Reading/Writing out a dictionary to csv file in python
<p>Pretty new to python, and the documentation for csv files is a bit confusing.</p> <p>I have a dictionary that looks like the following:</p> <pre><code>key1: (value1, value2) key2: (value1, value2) key3: (value1, value2) .... </code></pre> <p>I would like to write these out to a csv file in the format where each line contains the key, followed by the two values.</p> <p>I would also like to be able to read them back into a dictionary from the file at a later date.</p>
34,302,107
3
5
null
2015-12-15 23:01:35.983 UTC
8
2020-01-09 13:28:20.253 UTC
2020-01-09 13:28:20.253 UTC
null
202,229
null
5,323,267
null
1
17
python|csv|dictionary
65,529
<p>I didn't find enough benefit to use Pandas here since the problem is simple. </p> <p>Also note to OP, if you want to store values to a file just for reading it back simply use JSON or Python's shelve module. Exporting to CSV should be minimised only when we need to interact potentially Excel users. </p> <p>The below code converts a dict into CSV</p> <pre><code>value1 = 'one' value2 = 'two' d = { 'key1': (value1, value2), 'key2': (value1, value2), 'key3': (value1, value2) } CSV ="\n".join([k+','+','.join(v) for k,v in d.items()]) #You can store this CSV string variable to file as below # with open("filename.csv", "w") as file: # file.write(CSV) </code></pre> <p>This code explains what happens inside the list comprehension.</p> <pre><code>CSV = "" for k,v in d.items(): line = "{},{}\n".format(k, ",".join(v)) CSV+=line print CSV </code></pre>
16,052,441
Can i host a shiny app on a windows machine?
<p>I've registered for the beta hosting. I've tried to follow the directions for creating the shinyapps/myapp folder on my widnows machine. I can run shiny apps locally. I've installed the node.js program shiny requires but I can get the config file? I think my error message requires python? Is there an easier way to host the shiny app on a windows machine? Thanks</p>
16,052,826
3
0
null
2013-04-17 05:45:08.437 UTC
12
2017-06-16 08:56:14.943 UTC
null
null
null
null
2,289,229
null
1
10
r|shiny
23,495
<p>Using </p> <p><a href="https://github.com/leondutoit/shiny-server-on-ubuntu" rel="nofollow">https://github.com/leondutoit/shiny-server-on-ubuntu</a></p> <p>deployment is fairly easy. Too bad, the author is not very responsive.</p>
111,700
6502 CPU Emulation
<p>It's the weekend, so I relax from spending all week programming by writing a hobby project.</p> <p>I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below)</p> <p>I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes.</p> <p>I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory.</p> <p>The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode, </p> <pre><code>0 - BRK 1 - ORA (D,X) 2 - COP b </code></pre> <p>etc</p> <p>However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short. </p> <p>Is anyone familiar with this CPU's memory model?</p> <p>EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here.</p> <p><strong>EDIT:</strong> Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :)</p> <p>I uploaded the source:</p> <p><a href="https://archive.codeplex.com/?p=cpu6502" rel="nofollow noreferrer">https://archive.codeplex.com/?p=cpu6502</a></p> <p>If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :)</p>
111,742
7
1
null
2008-09-21 18:50:06.32 UTC
11
2019-03-20 16:00:31.057 UTC
2019-03-20 16:00:31.057 UTC
steveth45
4,562,204
Jonathan Holland
1,965
null
1
20
emulation|machine-code|6502
6,768
<p>The opcode takes one byte, and the operands are in the following bytes. Check out the byte size column <a href="http://www.atariarchives.org/2bml/chapter_10.php" rel="noreferrer">here</a>, for instance.</p>
1,259,949
How do I implement a progress bar in C#?
<p>How do I implement a progress bar and backgroundworker for database calls in C#?</p> <p>I do have some methods that deal with large amounts of data. They are relatively long running operations, so I want to implement a progress bar to let the user know that something is actually happening.</p> <p>I thought of using progress bar or status strip label, but since there is a single UI thread, the thread where the database-dealing methods are executed, UI controls are not updated, making the progress bar or status strip label are useless to me.</p> <p>I've already seen some examples, but they deal with for-loops, ex:</p> <pre><code>for(int i = 0; i &lt; count; i++) { System.Threading.Thread.Sleep(70); // ... do analysis ... bgWorker.ReportProgress((100 * i) / count); } private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar.Value = Math.Min(e.ProgressPercentage, 100); } </code></pre> <p>I'm looking for better examples.</p>
1,260,173
7
2
null
2009-08-11 12:08:44.403 UTC
14
2022-05-10 09:07:48.687 UTC
2010-10-27 18:11:35.28 UTC
null
16,587
go-goo-go
null
null
1
20
c#|.net|winforms|progress-bar
148,439
<p>Some people may not like it, but this is what I do:</p> <pre><code>private void StartBackgroundWork() { if (Application.RenderWithVisualStyles) progressBar.Style = ProgressBarStyle.Marquee; else { progressBar.Style = ProgressBarStyle.Continuous; progressBar.Maximum = 100; progressBar.Value = 0; timer.Enabled = true; } backgroundWorker.RunWorkerAsync(); } private void timer_Tick(object sender, EventArgs e) { if (progressBar.Value &lt; progressBar.Maximum) progressBar.Increment(5); else progressBar.Value = progressBar.Minimum; } </code></pre> <p>The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.</p>
1,310,247
Do you use attach() or call variables by name or slicing?
<p>Many intro R books and guides start off with the practice of attaching a <code>data.frame</code> so that you can call the variables by name. I have always found it favorable to call variables with <code>$</code> notation or square bracket slicing <code>[,2]</code>. That way I can use multiple <code>data.frame</code>s without confusing them and/or use iteration to successively call columns of interest. I noticed Google recently posted <a href="http://google-styleguide.googlecode.com/svn/trunk/google-r-style.html" rel="nofollow noreferrer">coding guidelines for R</a> which included the line</p> <blockquote> <p>1) attach: avoid using it </p> </blockquote> <p>How do people feel about this practice?</p>
1,311,620
7
0
null
2009-08-21 05:45:34.667 UTC
11
2016-09-27 17:57:10.157 UTC
2016-03-07 21:27:30.307 UTC
null
4,205,652
null
76,235
null
1
26
r|coding-style
13,316
<p>I never use attach. <code>with</code> and <code>within</code> are your friends.</p> <p>Example code:</p> <pre><code>&gt; N &lt;- 3 &gt; df &lt;- data.frame(x1=rnorm(N),x2=runif(N)) &gt; df$y &lt;- with(df,{ x1+x2 }) &gt; df x1 x2 y 1 -0.8943125 0.24298534 -0.6513271 2 -0.9384312 0.01460008 -0.9238312 3 -0.7159518 0.34618060 -0.3697712 &gt; &gt; df &lt;- within(df,{ x1.sq &lt;- x1^2 x2.sq &lt;- x2^2 y &lt;- x1.sq+x2.sq x1 &lt;- x2 &lt;- NULL }) &gt; df y x2.sq x1.sq 1 0.8588367 0.0590418774 0.7997948 2 0.8808663 0.0002131623 0.8806532 3 0.6324280 0.1198410071 0.5125870 </code></pre> <p>Edit: hadley mentions transform in the comments. here is some code:</p> <pre><code> &gt; transform(df, xtot=x1.sq+x2.sq, y=NULL) x2.sq x1.sq xtot 1 0.41557079 0.021393571 0.43696436 2 0.57716487 0.266325959 0.84349083 3 0.04935442 0.004226069 0.05358049 </code></pre>
1,035,489
Python garbage collection
<p>I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?</p>
1,035,512
7
1
null
2009-06-23 21:59:01.74 UTC
10
2018-05-08 18:51:47.447 UTC
null
null
null
null
54,564
null
1
42
python|optimization|memory-management|garbage-collection
52,672
<p>You haven't provided enough information - this depends on the specifics of the object you are creating and what else you're doing with it in the loop. If the object does not create circular references, it should be deallocated on the next iteration. For example, the code</p> <pre><code>for x in range(100000): obj = " " * 10000000 </code></pre> <p>will not result in ever-increasing memory allocation.</p>
1,079,711
Best approach to save user preferences?
<p>I have seen two different approaches in saving user preferences. </p> <p><strong>APPROACH 1:</strong> Serializing them and saving in one of the column of USERS table</p> <p><strong>APPROACH 2:</strong> Creating a separate table PREFERENCES and make a has_many association from USERS to PREFERENCES.</p> <p>Which one of the above two approaches would you prefer and what are the pros and cons of each over other?</p>
1,079,728
7
7
null
2009-07-03 14:53:36.683 UTC
17
2017-11-23 15:31:50.86 UTC
2009-07-03 14:56:40.08 UTC
null
18,107
null
115,159
null
1
48
ruby-on-rails|preferences
11,697
<p>It's usually a good idea to favor normalization. The second solution keeps your models cleaner, allows for easy extensibility if new preferences are added, and keeps your tables uncluttered.</p>
85,569
.Net (dotNet) wrappers for OpenCV?
<p>I've seen there are a few of them. <a href="http://code.google.com/p/opencvdotnet/" rel="noreferrer">opencvdotnet</a>, <a href="http://www.cs.ru.ac.za/research/groups/SharperCV/" rel="noreferrer">SharperCV</a>, <a href="http://sourceforge.net/projects/emgucv" rel="noreferrer">EmguCV</a>, <a href="http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx#install" rel="noreferrer">One on Code Project</a>. </p> <p>Does anyone have any experience with any of these? I played around with the one on Code Project for a bit, but as soon as I tried to do anything complicated I got some nasty uncatchable exceptions (i.e. Msgbox exceptions). Cross platform (supports Mono) would be best.</p>
172,117
8
0
null
2008-09-17 17:22:15.75 UTC
26
2022-01-11 14:30:10.817 UTC
2012-06-11 20:53:04.083 UTC
null
744,859
Kris Erickson
3,798
null
1
74
c#|.net|opencv|mono|cross-platform
58,774
<p>I started out with opencvdotnet but it's not really actively developed any more. Further, support for the feature I needed (facedetection) was patchy. I'm using <a href="http://www.emgu.com/wiki/index.php/Main_Page" rel="noreferrer">EmguCV</a> now: It wraps a much greater part of the API and the guy behind it is very responsive to suggestions and requests. The code is a joy to look at and is known to work on Mono.</p> <p>I've wrote up a quick <a href="http://friism.com/webcam-face-detection-in-c-using-emgu-cv" rel="noreferrer">getting-started guide</a> on my blog.</p>
1,170,754
Or versus OrElse
<p>What's the difference between <strong>or</strong> and <strong>OrElse</strong>?</p> <pre><code>if temp is dbnull.value or temp = 0 </code></pre> <p>produces the error:</p> <blockquote> <p>Operator '=' is not defined for type 'DBNull' and type 'Integer'.</p> </blockquote> <p>while this one works like a charm!?</p> <pre><code>if temp is dbnull.value OrElse temp = 0 </code></pre>
1,170,790
8
0
null
2009-07-23 09:58:26.633 UTC
13
2018-12-20 18:21:42.567 UTC
2016-09-17 12:59:14.74 UTC
null
4,519,059
null
59,314
null
1
103
vb.net
72,627
<p><code>OrElse</code> is a <strong>short-circuiting</strong> operator, <code>Or</code> is not.</p> <p>By the definition of the boolean 'or' operator, if the first term is True then the whole is definitely true - so we don't need to evaluate the second term.</p> <p><code>OrElse</code> knows this, so doesn't try and evaluate <code>temp = 0</code> once it's established that <code>temp Is DBNull.Value</code></p> <p><code>Or</code> doesn't know this, and will always attempt to evaluate both terms. When <code>temp Is DBNull.Value</code>, it can't be compared to zero, so it falls over.</p> <p>You should use... well, whichever one makes sense.</p>
711,057
Learning about Computer Vision
<p>I am really intrigued by the field of computer vision and the potential it has. Are there any examples (preferably implemented in .NET) which I can study along with a reference book?</p>
711,076
9
0
null
2009-04-02 18:39:51.483 UTC
42
2013-07-06 01:52:52.867 UTC
2013-07-06 01:52:52.867 UTC
Gortok
2,405,463
Ali Kazmi
74,857
null
1
33
computer-vision
13,085
<p>OpenCV (Open Computer Vision) is the most popular library, and it has been wrapped for C#:</p> <p><a href="http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx</a></p> <p>Some discussion about this wrapper and the library in general is here: </p> <p><a href="http://coolthingoftheday.blogspot.com/2008/08/opencv-open-source-computer-vision-for.html" rel="noreferrer">http://coolthingoftheday.blogspot.com/2008/08/opencv-open-source-computer-vision-for.html</a></p> <p>-Adam</p>
103,654
Why don't languages raise errors on integer overflow by default?
<p>In several modern programming languages (including C++, Java, and C#), the language allows <a href="http://en.wikipedia.org/wiki/Integer_overflow" rel="noreferrer">integer overflow</a> to occur at runtime without raising any kind of error condition.</p> <p>For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow. (For brevity, the method also doesn't handle the case where the specified list is a null reference.)</p> <pre class="lang-c# prettyprint-override"><code>//Returns the sum of the values in the specified list. private static int sumList(List&lt;int&gt; list) { int sum = 0; foreach (int listItem in list) { sum += listItem; } return sum; } </code></pre> <p>If this method is called as follows:</p> <pre class="lang-c# prettyprint-override"><code>List&lt;int&gt; list = new List&lt;int&gt;(); list.Add(2000000000); list.Add(2000000000); int sum = sumList(list); </code></pre> <p>An overflow will occur in the <code>sumList()</code> method (because the <code>int</code> type in C# is a 32-bit signed integer, and the sum of the values in the list exceeds the value of the maximum 32-bit signed integer). The sum variable will have a value of -294967296 (not a value of 4000000000); this most likely is not what the (hypothetical) developer of the sumList method intended.</p> <p>Obviously, there are various techniques that can be used by developers to avoid the possibility of integer overflow, such as using a type like Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html" rel="noreferrer"><code>BigInteger</code></a>, or the <a href="http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx" rel="noreferrer"><code>checked</code></a> keyword and <a href="http://msdn.microsoft.com/en-us/library/h25wtyxf.aspx" rel="noreferrer"><code>/checked</code></a> compiler switch in C#.</p> <p>However, the question that I'm interested in is why these languages were designed to by default allow integer overflows to happen in the first place, instead of, for example, raising an exception when an operation is performed at runtime that would result in an overflow. It seems like such behavior would help avoid bugs in cases where a developer neglects to account for the possibility of overflow when writing code that performs an arithmetic operation that could result in overflow. (These languages could have included something like an "unchecked" keyword that could designate a block where integer overflow is permitted to occur without an exception being raised, in those cases where that behavior is explicitly intended by the developer; C# actually <a href="http://msdn.microsoft.com/en-us/library/a569z7k8.aspx" rel="noreferrer">does have this</a>.)</p> <p>Does the answer simply boil down to performance -- the language designers didn't want their respective languages to default to having "slow" arithmetic integer operations where the runtime would need to do extra work to check whether an overflow occurred, on every applicable arithmetic operation -- and this performance consideration outweighed the value of avoiding "silent" failures in the case that an inadvertent overflow occurs?</p> <p>Are there other reasons for this language design decision as well, other than performance considerations?</p>
108,776
9
0
null
2008-09-19 16:53:10.533 UTC
6
2020-03-17 21:31:43.873 UTC
2015-08-29 02:27:25.72 UTC
Jon Schneider
995,714
Jon Schneider
12,484
null
1
49
language-agnostic|integer|language-design|integer-overflow
5,337
<p>In C#, it was a question of performance. Specifically, out-of-box benchmarking.</p> <p>When C# was new, Microsoft was hoping a lot of C++ developers would switch to it. They knew that many C++ folks thought of C++ as being fast, especially faster than languages that "wasted" time on automatic memory management and the like. </p> <p>Both potential adopters and magazine reviewers are likely to get a copy of the new C#, install it, build a trivial app that no one would ever write in the real world, run it in a tight loop, and measure how long it took. Then they'd make a decision for their company or publish an article based on that result.</p> <p>The fact that their test showed C# to be slower than natively compiled C++ is the kind of thing that would turn people off C# quickly. The fact that your C# app is going to catch overflow/underflow automatically is the kind of thing that they might miss. So, it's off by default.</p> <p>I think it's obvious that 99% of the time we want /checked to be on. It's an unfortunate compromise.</p>
133,569
Hashtable in C++?
<p>I usually use C++ stdlib map whenever I need to store some data associated with a specific type of value (a key value - e.g. a string or other object). The stdlib map implementation is based on trees which provides better performance (O(log n)) than the standard array or stdlib vector.</p> <p>My questions is, do you know of any C++ "standard" hashtable implementation that provides even better performance (O(1))? Something similar to what is available in the Hashtable class from the Java API.</p>
133,591
9
0
null
2008-09-25 14:11:32.103 UTC
21
2018-02-20 14:35:22.763 UTC
2012-12-05 22:22:32.59 UTC
user317955
null
Marcos Bento
20,317
null
1
57
c++|performance|map|hashtable|complexity-theory
55,696
<p>If you're using C++11, you have access to the <code>&lt;unordered_map&gt;</code> and <code>&lt;unordered_set&gt;</code> headers. These provide classes <a href="http://en.cppreference.com/w/cpp/container/unordered_map" rel="noreferrer"><code>std::unordered_map</code></a> and <a href="http://en.cppreference.com/w/cpp/container/unordered_set" rel="noreferrer"><code>std::unordered_set</code></a>.</p> <p>If you're using C++03 with TR1, you have access to the classes <code>std::tr1::unordered_map</code> and <code>std::tr1::unordered_set</code>, using the same headers (unless you're using GCC, in which case the headers are <code>&lt;tr1/unordered_map&gt;</code> and <code>&lt;tr1/unordered_set&gt;</code> instead).</p> <p>In all cases, there are corresponding <code>unordered_multimap</code> and <code>unordered_multiset</code> types too.</p>
693,997
How to set HttpResponse timeout for Android in Java
<p>I have created the following function for checking the connection status:</p> <pre><code>private void checkConnectionStatus() { HttpClient httpClient = new DefaultHttpClient(); try { String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/" + strSessionString + "/ConnectionStatus"; Log.d("phobos", "performing get " + url); HttpGet method = new HttpGet(new URI(url)); HttpResponse response = httpClient.execute(method); if (response != null) { String result = getResponse(response.getEntity()); ... </code></pre> <p>When I shut down the server for testing the execution waits a long time at line</p> <pre><code>HttpResponse response = httpClient.execute(method); </code></pre> <p>Does anyone know how to set the timeout in order to avoid waiting too long?</p> <p>Thanks!</p>
1,565,243
10
0
null
2009-03-29 02:15:24.557 UTC
145
2019-03-23 09:40:18.697 UTC
2010-06-19 14:13:30.507 UTC
niko
244,296
niko
22,996
null
1
336
java|android|timeout|httpresponse
203,261
<p>In my example, two timeouts are set. The connection timeout throws <code>java.net.SocketTimeoutException: Socket is not connected</code> and the socket timeout <code>java.net.SocketTimeoutException: The operation timed out</code>.</p> <pre><code>HttpGet httpGet = new HttpGet(url); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(httpGet); </code></pre> <p>If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function <strong>setParams()</strong>.</p> <pre><code>httpClient.setParams(httpParameters); </code></pre>
1,131,758
NUnit - cleanup after test failure
<p>We have some NUnit tests that access the database. When one of them fails it can leave database in inconsistent state - which is not an issue, since we rebuild database for every test run - but it can cause other tests to fail in the same run.</p> <p>Is it possible to detect that one of the tests failed and perform some sort of cleanup?</p> <p>We don't want to write cleanup code in every test, we already do that now. I'd like to perfrom cleanup in Teardown but only if test failed, as cleanup might be expensive.</p> <p><strong>Update</strong>: To clarify - I would like tests to be simple and NOT include any cleanup or error handling logic. I also don't want to perform database reset on every test run - only if test fails. And this code should probably be executed in Teardown method but I am not aware of any way to get info if test we are currently tearing down from failed or was successful.</p> <p><strong>Update2</strong>:</p> <pre><code> [Test] public void MyFailTest() { throw new InvalidOperationException(); } [Test] public void MySuccessTest() { Assert.That(true, Is.True); } [TearDown] public void CleanUpOnError() { if (HasLastTestFailed()) CleanUpDatabase(); } </code></pre> <p>I am looking for implementation of HasLastTestFailed()</p>
1,134,689
11
1
null
2009-07-15 14:31:00.79 UTC
10
2015-10-09 17:02:38.017 UTC
2009-07-15 14:44:17.557 UTC
null
28,912
null
28,912
null
1
43
.net|nunit|nunit-2.5
25,555
<p>This idea got me interested, so I did a little digging. NUnit doesn't have this ability out of the box, but there is a whole extensibility framework supplied with NUnit. I found <a href="http://www.simple-talk.com/dotnet/.net-tools/testing-times-ahead-extending-nunit/" rel="noreferrer">this great article about extending NUnit</a> - it was a good starting point. After playing around with it, I came up with the following solution: a method decorated with a custom <code>CleanupOnError</code> attribute will be called if one of the tests in the fixture failed.</p> <p>Here's how the test looks like:</p> <pre><code> [TestFixture] public class NUnitAddinTest { [CleanupOnError] public static void CleanupOnError() { Console.WriteLine("There was an error, cleaning up..."); // perform cleanup logic } [Test] public void Test1_this_test_passes() { Console.WriteLine("Hello from Test1"); } [Test] public void Test2_this_test_fails() { throw new Exception("Test2 failed"); } [Test] public void Test3_this_test_passes() { Console.WriteLine("Hello from Test3"); } } </code></pre> <p>where the attribute is simply:</p> <pre><code> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class CleanupOnErrorAttribute : Attribute { } </code></pre> <p>And here is how it's executed from the addin:</p> <pre><code>public void RunFinished(TestResult result) { if (result.IsFailure) { if (_CurrentFixture != null) { MethodInfo[] methods = Reflect.GetMethodsWithAttribute(_CurrentFixture.FixtureType, CleanupAttributeFullName, false); if (methods == null || methods.Length == 0) { return; } Reflect.InvokeMethod(methods[0], _CurrentFixture); } } } </code></pre> <p>But here's the tricky part: the addin must be placed in the <code>addins</code> directory next to the NUnit runner. Mine was placed next to the NUnit runner in TestDriven.NET directory: </p> <blockquote> <p><code>C:\Program Files\TestDriven.NET 2.0\NUnit\addins</code></p> </blockquote> <p>(I created the <code>addins</code> directory, it wasn't there)</p> <p><strong>EDIT</strong> Another thing is that the cleanup method needs to be <code>static</code>!</p> <p>I hacked together a simple addin, you can download the source from <a href="http://cid-86665d02cd7ef5cf.skydrive.live.com/self.aspx/Public/NUnit.Addin.zip" rel="noreferrer">my SkyDrive</a>. You will have to add references to <code>nunit.framework.dll</code>, <code>nunit.core.dll</code> and <code>nunit.core.interfaces.dll</code> in the appropriate places.</p> <p>A few notes: The attribute class can be placed anywhere in your code. I didn't want to place it in the same assembly as the addin itself, because it references two <code>Core</code> NUnit assemblies, so I placed it in a different assembly. Just remember to change the line in the <code>CleanAddin.cs</code>, if you decide to put it anywhere else.</p> <p>Hope that helps.</p>
403,478
How to overlay images
<p>I want to overlay one image with another using CSS. An example of this is the first image (the background if you like) will be a thumbnail link of a product, with the link opening a lightbox / popup showing a larger version of the image. </p> <p>On top of this linked image I would like an image of a magnifying glass, to show people that the image can be clicked to enlarge it (apparently this isn't obvious without the magnifying glass).</p>
403,510
11
1
null
2008-12-31 17:00:08.337 UTC
59
2022-02-16 13:19:37.957 UTC
2013-10-24 21:45:14.133 UTC
Dreas Grech
243,557
null
1,349,865
null
1
129
html|css
316,439
<p>I just got done doing this exact thing in a project. The HTML side looked a bit like this:</p> <pre><code>&lt;a href="[fullsize]" class="gallerypic" title=""&gt; &lt;img src="[thumbnail pic]" height="90" width="140" alt="[Gallery Photo]" class="pic" /&gt; &lt;span class="zoom-icon"&gt; &lt;img src="/images/misc/zoom.gif" width="32" height="32" alt="Zoom"&gt; &lt;/span&gt; &lt;/a&gt; </code></pre> <p>Then using CSS:</p> <pre><code>a.gallerypic{ width:140px; text-decoration:none; position:relative; display:block; border:1px solid #666; padding:3px; margin-right:5px; float:left; } a.gallerypic span.zoom-icon{ visibility:hidden; position:absolute; left:40%; top:35%; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity: 0.5; } a.gallerypic:hover span.zoom-icon{ visibility:visible; } </code></pre> <p>I left a lot of the sample in there on the CSS so you can see how I decided to do the style. Note I lowered the opacity so you could see through the magnifying glass.</p> <p>Hope this helps.</p> <p>EDIT: To clarify for your example - you could ignore the <code>visibility:hidden;</code> and kill the <code>:hover</code> execution if you wanted, this was just the way I did it.</p>
941,832
Is it safe to delete a void pointer?
<p>Suppose I have the following code:</p> <pre><code>void* my_alloc (size_t size) { return new char [size]; } void my_free (void* ptr) { delete [] ptr; } </code></pre> <p>Is this safe? Or must <code>ptr</code> be cast to <code>char*</code> prior to deletion?</p>
941,953
13
10
null
2009-06-02 20:47:47.1 UTC
27
2019-06-25 14:41:27.877 UTC
null
null
null
null
17,035
null
1
100
c++|memory-management|casting|void-pointers
69,663
<p>It depends on "safe." It will usually work because information is stored along with the pointer about the allocation itself, so the deallocator can return it to the right place. In this sense it is "safe" as long as your allocator uses internal boundary tags. (Many do.) </p> <p>However, as mentioned in other answers, deleting a void pointer will not call destructors, which can be a problem. In that sense, it is not "safe."</p> <p>There is no good reason to do what you are doing the way you are doing it. If you want to write your own deallocation functions, you can use function templates to generate functions with the correct type. A good reason to do that is to generate pool allocators, which can be extremely efficient for specific types.</p> <p>As mentioned in other answers, this is <a href="https://en.cppreference.com/w/cpp/language/ub" rel="noreferrer">undefined behavior</a> in C++. In general it is good to avoid undefined behavior, although the topic itself is complex and filled with conflicting opinions.</p>
704,564
Disable Drag and Drop on HTML elements?
<p>I'm working on a web application for which I'm attempting to implement a full featured windowing system. Right now it's going very well, I'm only running into one minor issue. Sometimes when I go to drag a part of my application (most often the corner div of my window, which is supposed to trigger a resize operation) the web browser gets clever and thinks I mean to drag and drop something. End result, my action gets put on hold while the browser does its drag and drop thing.</p> <p>Is there an easy way to disable the browser's drag and drop? I'd ideally like to be able to turn it off while the user is clicking on certain elements, but re-enable it so that users can still use their browser's normal functionality on the contents of my windows. I'm using jQuery, and although I wasn't able to find it browsing the docs, if you know a pure jQuery solution it would be excellent.</p> <p>In short: I need to disable browser text selection and drag-and-drop functions while my user has the mouse button down, and restore that functionality when the user releases the mouse.</p>
704,582
13
1
null
2009-04-01 08:21:30.41 UTC
38
2022-04-16 11:33:46.377 UTC
2020-12-29 23:06:47.94 UTC
null
3,345,644
Nicholas Flynt
19,521
null
1
132
javascript|css
243,343
<p>Try preventing default on mousedown event:</p> <pre><code>&lt;div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false"&gt;asd&lt;/div&gt; </code></pre> <p>or</p> <pre><code>&lt;div onmousedown="return false"&gt;asd&lt;/div&gt; </code></pre>
1,189,007
removing strange characters from php string
<p>this is what i have right now</p> <p>Drawing an RSS feed into the php, the raw xml from the rss feed reads:</p> <pre><code>Paul&amp;#8217;s Confidence </code></pre> <p>The php that i have so far is this.</p> <pre><code>$newtitle = $item-&gt;title; $newtitle = utf8_decode($newtitle); </code></pre> <p>The above returns;</p> <pre><code>Paul?s Confidence </code></pre> <p>If i remove the utf_decode, i get this</p> <pre><code>Paul’s Confidence </code></pre> <p>When i try a str_replace;</p> <pre><code>$newtitle = str_replace("&amp;#8221;", "", $newtitle); </code></pre> <p>It doesnt work, i get;</p> <pre><code>Paul’s Confidence </code></pre> <p>Any thoughts?</p>
1,189,066
14
3
null
2009-07-27 15:58:24.157 UTC
10
2020-09-21 16:40:30.51 UTC
null
null
null
null
115,949
null
1
27
php
65,240
<p>Try this:</p> <pre><code>$newtitle = html_entity_decode($newtitle, ENT_QUOTES, "UTF-8") </code></pre> <p>If this is not the solution browse this page <a href="http://us2.php.net/manual/en/function.html-entity-decode.php" rel="noreferrer">http://us2.php.net/manual/en/function.html-entity-decode.php</a></p>
253,492
Static nested class in Java, why?
<p>I was looking at the Java code for <code>LinkedList</code> and noticed that it made use of a static nested class, <code>Entry</code>.</p> <pre><code>public class LinkedList&lt;E&gt; ... { ... private static class Entry&lt;E&gt; { ... } } </code></pre> <p>What is the reason for using a static nested class, rather than an normal inner class?</p> <p>The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation. </p> <p>But I thought there might be other reasons, maybe performance. What might it be?</p> <p>Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html" rel="noreferrer">http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html</a></p>
253,521
14
1
null
2008-10-31 13:36:51.153 UTC
110
2020-09-30 08:21:57.293 UTC
2011-01-23 16:38:40.213 UTC
John Topley
63,550
David Turner
10,171
null
1
230
java|class|static|member
124,093
<p>The Sun page you link to has some key differences between the two:</p> <blockquote> <p>A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.<br> ...</p> <p>Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. <strong>In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.</strong></p> </blockquote> <p>There is no need for <code>LinkedList.Entry</code> to be top-level class as it is <em>only</em> used by <code>LinkedList</code> (there are some other interfaces that also have static nested classes named <code>Entry</code>, such as <code>Map.Entry</code> - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.</p> <p>As <a href="https://stackoverflow.com/a/253507/4249">Jon Skeet points out</a>, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.</p>
446,892
How to find event listeners on a DOM node in JavaScript or in debugging?
<p>I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node and for what event?</p> <p>Events are attached using:</p> <ol> <li><a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="noreferrer">Prototype's</a> <code>Event.observe</code>;</li> <li>DOM's <code>addEventListener</code>;</li> <li>As element attribute <code>element.onclick</code>.</li> </ol>
3,426,352
20
4
null
2009-01-15 14:19:44.42 UTC
384
2022-09-11 16:07:56.92 UTC
2021-08-11 04:11:26.72 UTC
Navneet
1,253,298
Navneet
54,540
null
1
1,026
javascript|events|dom
769,370
<p>If you just need to inspect what's happening on a page, you might try the <a href="http://www.sprymedia.co.uk/article/Visual+Event" rel="noreferrer">Visual Event</a> bookmarklet.</p> <p><strong>Update</strong>: <a href="http://www.sprymedia.co.uk/article/Visual+Event+2" rel="noreferrer">Visual Event 2</a> available.</p>
735,204
Convert a String In C++ To Upper Case
<p>How could one convert a string to upper case. The examples I have found from googling only have to deal with chars.</p>
735,241
31
0
null
2009-04-09 17:38:23.653 UTC
77
2021-06-01 15:30:31.627 UTC
2012-07-17 12:31:59.22 UTC
null
321,731
null
83,246
null
1
310
c++|string
668,915
<p><a href="https://www.boost.org/doc/libs/1_73_0/boost/algorithm/string/case_conv.hpp" rel="noreferrer">Boost string algorithms</a>:</p> <pre><code>#include &lt;boost/algorithm/string.hpp&gt; #include &lt;string&gt; std::string str = &quot;Hello World&quot;; boost::to_upper(str); std::string newstr = boost::to_upper_copy&lt;std::string&gt;(&quot;Hello World&quot;); </code></pre>
6,459,861
Razor Helper Syntax Auto Formatting Ugly. How to fix?
<p>So I just have a beef with the way Visual Studio formats razor code. I've always had some problems with visual studio and how it formats UI code, it always seems to do a real super bad job that the industry doesn't want to follow.</p> <p>So the example looks real real stupid. And I'm trying to figure out if there are mods or ways to fix this issue. It just looks real real bad.</p> <p>Anyone know anything about this? lol</p> <pre><code>@using Company.Mobile2.Enums @helper BidsByShipment(string generatedId, int bidsCount, int activeBidsCount) { if (bidsCount &gt; 0) { &lt;a class="Company-listview-link Company-listview-bids" href="/Shipping/Bids/ByShipment?id={0}"&gt; @if (activeBidsCount &gt; 0) { &lt;text&gt;@bidsCount (@activeBidsCount @GetStr("Company"))&lt;/text&gt; } else { &lt;text&gt;@bidsCount&lt;/text&gt; } &lt;/a&gt; } else { &lt;text&gt;0 @GetStr("Company")&lt;/text&gt; } } </code></pre>
6,917,891
5
5
null
2011-06-23 19:57:12.913 UTC
1
2018-04-19 06:06:56.48 UTC
null
null
null
null
745,537
null
1
43
visual-studio|syntax|formatting|razor
12,570
<p>Apparently there's no way around it for the moment, this is what they have answered in another related question: <a href="https://stackoverflow.com/questions/6902204/why-doesnt-visual-studio-code-formatting-work-properly-for-razor-markup">Why doesn&#39;t Visual Studio code formatting work properly for Razor markup?</a></p>
6,750,017
How to query database by id using SqlAlchemy?
<p>I need to query a SQLAlchemy database by its <code>id</code> something similar to</p> <pre><code>User.query.filter_by(username='peter') </code></pre> <p>but for id. How do I do this? [Searching over Google and SO didn't help]</p>
6,756,723
5
2
null
2011-07-19 15:43:42.213 UTC
7
2022-04-18 21:52:57.707 UTC
2022-04-18 21:52:57.707 UTC
null
6,243,352
user507220
null
null
1
127
python|sql|model|sqlalchemy
131,243
<p>Query has a <a href="https://docs.sqlalchemy.org/en/stable/orm/query.html#sqlalchemy.orm.Query.get" rel="noreferrer">get function</a> that supports querying by the primary key of the table, which I assume that <code>id</code> is.</p> <p>For example, to query for an object with ID of 23:</p> <pre class="lang-py prettyprint-override"><code>User.query.get(23) </code></pre> <hr /> <p>Note: As a few other commenters and answers have mentioned, this is not simply shorthand for &quot;Perform a query filtering on the primary key&quot;. Depending on the state of the SQLAlchemy session, running this code may query the database and return a new instance, or it may return an instance of an object queried earlier in your code without actually querying the database. If you have not already done so, consider reading the <a href="https://docs.sqlalchemy.org/en/latest/orm/session_basics.html#is-the-session-a-cache" rel="noreferrer">documentation on the SQLAlchemy Session</a> to understand the ramifications.</p>
6,885,990
Rails params explained?
<p>Could anyone explain <code>params</code> in Rails controller: where they come from, and what they are referencing?</p> <pre><code> def create @vote = Vote.new(params[:vote]) item = params[:vote][:item_id] uid = params[:vote][:user_id] @extant = Vote.find(:last, :conditions =&gt; ["item_id = ? AND user_id = ?", item, uid]) last_vote_time = @extant.created_at unless @extant.blank? curr_time = Time.now end </code></pre> <p>I would like to be able to read this code line-by-line and understand what's going on.</p>
6,886,073
5
2
null
2011-07-30 21:13:22.037 UTC
133
2022-07-05 07:37:03.673 UTC
2014-02-08 10:21:33.437 UTC
null
727,208
null
830,554
null
1
238
ruby-on-rails|ruby
194,896
<p>The params come from the user's browser when they request the page. For an HTTP GET request, which is the most common, the params are encoded in the URL. For example, if a user's browser requested</p> <p><code>http://www.example.com/?foo=1&amp;boo=octopus</code></p> <p>then <code>params[:foo]</code> would be &quot;1&quot; and <code>params[:boo]</code> would be &quot;octopus&quot;.</p> <p>In HTTP/HTML, the params are really just a series of key-value pairs where the key and the value are strings, but Ruby on Rails has a special syntax for making the params be a hash with hashes inside. For example, if the user's browser requested</p> <p><code>http://www.example.com/?vote[item_id]=1&amp;vote[user_id]=2</code></p> <p>then <code>params[:vote]</code> would be a hash, <code>params[:vote][:item_id]</code> would be &quot;1&quot; and <code>params[:vote][:user_id]</code> would be &quot;2&quot;.</p> <p>The Ruby on Rails params are the equivalent of the <a href="http://php.net/manual/en/reserved.variables.request.php" rel="nofollow noreferrer">$_REQUEST array in PHP</a>.</p>
6,722,850
Querying internal array size in MongoDB
<p>Consider a MongoDB document in <code>users</code> collection: </p> <pre><code>{ username : 'Alex', tags: ['C#', 'Java', 'C++'] } </code></pre> <p>Is there any way, to get the length of the <code>tags</code> array from the server side (without passing the tags to the client) ? </p> <p>Thank you! </p>
22,940,330
6
0
null
2011-07-17 09:04:07.437 UTC
17
2020-02-28 15:34:32.527 UTC
2020-02-28 15:34:32.527 UTC
null
6,904,888
null
240,950
null
1
41
mongodb|mongodb-query|nosql
36,725
<p>Now MongoDB (2.6 release) <a href="http://docs.mongodb.org/manual/reference/operator/aggregation/size/#exp._S_size" rel="noreferrer">supports</a> <code>$size</code> operation in aggregation. </p> <p>From the documentation:</p> <pre><code>{ &lt;field&gt;: { $size: &lt;array&gt; } } </code></pre> <p>What you want can be accomplished as following with either by using this:</p> <pre><code>db.users.aggregate( [ { $group: { _id: "$username", tags_count: {$first: {$size: "$tags" }} } } ] ) </code></pre> <p>or</p> <pre><code>db.users.aggregate( [ { $project: { tags_count: {$size: "$tags"} } } ] ) </code></pre>
6,402,393
Screenshot from a UITableView
<p>I know there are many questions about this theme but I really read all of them but not found an answer.</p> <p>I want make a screenshot from the current table view. and i do it this way:</p> <pre><code>-(UIImage *)imageFromCurrentView { UIGraphicsBeginImageContextWithOptions(self.tableView.bounds.size, YES, 1); [self.tableView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; } </code></pre> <p>Everything works fine, but when i scroll down in the tableview and make the screenshot, half of the image is black. I don't know how to make the screenshot from the actual tableview area.</p>
6,402,465
7
0
null
2011-06-19 12:37:14.417 UTC
10
2020-03-27 08:25:10.07 UTC
2011-06-19 12:59:07.573 UTC
null
41,116
user656219
null
null
1
11
iphone|objective-c|ios|uitableview|ios4
8,553
<p>Because UITableViewCell is reusable, when scrolling the table view, the cells outside the view ports will be enqueued for reusing and removed from the table view. So try to keep the cells only be reusable on its index path:</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *cellIdentifier = [NSString stringWithFormat:@"Cell_%d_%d", indexPath.section, indexPath.row]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithReuseIdentifier:cellIdentifier] autorelease]; } ... return cell; } </code></pre> <p>Not tested yet, give it a try. Yes, this will consume much more memory, do it with screenshot purpose only.</p> <p>Edit: if you care the memory usage, may be you can take screenshot of current view port, then programmatically scroll top and down to take other parts of screenshots, and combine all the screen shots at last.</p>
38,257,907
Can C# nameof operator reference instance property without instance?
<p>I regularly want to get the name of an instance property of a type, when I have no instance. Currently to do this, I use the following inhouse function which interprets the <code>Expression[Func[T, object]]</code> parameter and returns the property name:</p> <pre><code>var str = LinqExtensions.NameOf&lt;ClientService&gt;(x =&gt; x.EndDate); // Now str == "EndDate" </code></pre> <p>However it seems a shame not to use the built in <code>nameof</code> operator.</p> <p>Unfortunately it seems that the <code>nameof</code> operator requires either an instance, or, to reference a static properties.</p> <p>Is there a neat way to use the <code>nameof</code> operator instead of our in house function? For example:</p> <pre><code>nameof(ClientService.EndDate) // ClientService.EndDate not normally syntactically valid as EndDate is instance member </code></pre> <p>EDIT</p> <p>I was completely wrong, the syntax <code>nameof(ClientService.EndDate)</code> as described actually works as is.</p>
38,258,644
2
2
null
2016-07-08 02:02:34.62 UTC
null
2020-08-07 01:59:26.673 UTC
2016-07-08 07:23:11.927 UTC
null
833,070
null
1,872,194
null
1
43
c#|c#-6.0|nameof
15,496
<p>In the past, the documentation explicitly explained this, reading in part:</p> <blockquote> <p>In the examples you see that <strong>you can use a type name and access an instance method name. You do not need to have an instance of the type</strong>… <em>[emphasis mine]</em></p> </blockquote> <p>This has been omitted in <a href="https://msdn.microsoft.com/en-us/library/dn986596.aspx" rel="noreferrer">the current documentation</a>. However, the examples still make this clear. Code samples such as <code>Console.WriteLine(nameof(List&lt;int&gt;.Count)); // output: Count</code> and <code>Console.WriteLine(nameof(List&lt;int&gt;.Add)); // output: Add</code> show how to use <code>nameof</code> to obtain the <code>string</code> value with the name of an instance member of a class.</p> <p>I.e. you should be able to write <code>nameof(ClientService.EndDate)</code> and have it work, contrary to your observation in the question that this would be <em>&quot;not normally syntactically valid&quot;</em>.</p> <p>If you are having trouble with the syntax, please provide a good <a href="https://stackoverflow.com/help/mcve">Minimal, Complete, and Verifiable code example</a> that reliably reproduces whatever error you're getting, and provide the <em>exact</em> text of the error message.</p>
45,345,146
Is it secure to send username and password in a Json object in the body of a post request?
<p>I am building a web application and my web server is secure, meaning that it uses an ssl cert with the front end to encrypt the connection.</p> <p>When a user logs in, a JSON object which looks like this is created, and sent to the server.</p> <pre><code>{ username:"the user's username", password:"the user's password" } </code></pre> <p>On the server this is verified with a hashing algorithm that uses a salt. Once it is verified an api token is created which is valid for a certain amount of time, and is passed back and forth in the header in order to verify the user when requests are being made. Is sending the username and password like this best practice/secure, or is it better to send it in the header?</p>
45,348,798
2
4
null
2017-07-27 08:21:28.327 UTC
14
2017-07-27 11:32:42.25 UTC
2017-07-27 09:02:33.207 UTC
null
207,421
null
4,415,079
null
1
31
json|security|passwords
34,715
<p>Lets divide it to many points:</p> <p><strong>1)</strong> you use a valid SSL certificate to secure the communication between the user and the server (It must be valid)</p> <p><strong>2)</strong> Sending the username and password in the body of the POST request is the best practice (Never use GET to send sensitive information such as Credentials)</p> <p><strong>3)</strong> Sending the api token in the HTTP request and response headers is the best practice (Again never use GET to send sensitive information such as session tokens)</p> <p><strong>So based on the points above, it seems that there is no risk in this implementation but you need to take the following points in your consideration:</strong></p> <p><strong>1)</strong> The time out of the API token should be short in case of idle user. (5 ~ 15 mins are the averages based on the criticality of the application)</p> <p><strong>2)</strong> The length of the API token should be long string approx. 30 ~ 40 characters.</p> <p><strong>3)</strong> The API token generation must be randomized and hard to predict to protect from (session prediction attacks.)</p> <p>Hope this help you.</p>
41,387,085
Could not resolve all dependencies for configuration ':app:_debugApkCopy'
<p>I'm new in Android Studio, I've tried to write to fire base and when android offered me something I accepted and then everything stop working and he didn't recognize any object.</p> <p>I get this error:</p> <pre><code>**Error: A problem occurred configuring project ':app'.** &gt; Could not resolve all dependencies for configuration ':app:_debugApkCopy'. &gt; Could not find com.google.android.gms:play-services-appindexing:10.0.1. </code></pre> <p>I've already updated ths SDK and I think my dependencies are fine. Any other suggestion?</p> <p><strong>edit</strong>: i find out that it happen after i copied code from somewhere and click on "alt + enter" and then accidentally click on some option whit "...api..." (i can't restore that).</p> <p>I copy the code to other computer and now it's working.</p> <p>Dependencies: <a href="https://i.stack.imgur.com/1DfSC.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/1DfSC.jpg" alt="dependencies"></a></p>
41,387,352
4
2
null
2016-12-29 20:58:45.6 UTC
1
2018-06-13 10:20:37.073 UTC
2017-01-02 12:05:58.01 UTC
null
7,355,601
null
7,355,601
null
1
8
java|android|android-studio|sdk
39,791
<p>Try removing your dependencies and rebuilding the app again. Try Clean and rebuild. </p>
15,488,350
Programmatically creating Markdown tables in R with KnitR
<p>I am just starting to learn about KnitR and the use of Markdown in generating R documents and reports. This looks to be perfect for a lot of the day to day reporting that I have to do with my job. However, one thing that I'm not seeing is an easy way to print data frames and tables using Markdown formatting (sort of like <code>xtable</code>, but with Markdown instead of LaTeX or HTML). I know that I can just embed the HTML output from xtable, but I was wondering if there were any Markdown-based solutions?</p>
19,859,769
8
7
null
2013-03-18 22:41:19.603 UTC
62
2020-08-10 08:42:50.29 UTC
null
null
null
null
1,332,389
null
1
106
r|markdown|knitr|r-markdown
74,773
<p>Now <code>knitr</code> (since version 1.3) package include the <code>kable</code> function for a creation tables:</p> <pre><code>&gt; library(knitr) &gt; kable(head(iris[,1:3]), format = "markdown") | Sepal.Length| Sepal.Width| Petal.Length| |-------------:|------------:|-------------:| | 5,1| 3,5| 1,4| | 4,9| 3,0| 1,4| | 4,7| 3,2| 1,3| | 4,6| 3,1| 1,5| | 5,0| 3,6| 1,4| | 5,4| 3,9| 1,7| </code></pre> <p><strong>UPDATED</strong>: if you get raw markdown in a document try setup <code>results = "asis"</code> chunk option.</p>
35,966,844
PreferenceFragmentCompat custom layout
<p>I need a custom layout for my PreferenceFragmentCompat. In the docs for <a href="http://developer.android.com/reference/android/support/v7/preference/PreferenceFragmentCompat.html#onCreateView(android.view.LayoutInflater,%20android.view.ViewGroup,%20android.os.Bundle)" rel="noreferrer">PreferenceFragmentCompat</a> it seems that you can possibly inflate and return a view in onCreateView().</p> <p>However a NPE results:-</p> <pre><code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference at android.support.v7.preference.PreferenceFragmentCompat.bindPreferences(PreferenceFragmentCompat.java:511) at android.support.v7.preference.PreferenceFragmentCompat.onActivityCreated(PreferenceFragmentCompat.java:316) at com.cls.example.MyPrefFrag.onActivityCreated(MyPrefFrag.java:42) </code></pre> <p>After I checked the source of PreferenceFragmentCompat:onCreateView I found the following piece of code :-</p> <pre><code> RecyclerView listView = this.onCreateRecyclerView(themedInflater, listContainer, savedInstanceState); if(listView == null) { throw new RuntimeException("Could not create RecyclerView"); } else { this.mList = listView; //problem ... return view; } </code></pre> <p>So if you override onCreateView() and return a custom layout the onCreateRecyclerView() is not called plus the RecyclerView private field mList will not be set. So the NPE on setAdapter() results.</p> <p>Should I assume that having a custom layout is not feasible for PreferenceFragmentCompat ?</p>
36,286,426
2
7
null
2016-03-13 05:25:42.573 UTC
9
2018-06-22 13:27:11.863 UTC
null
null
null
null
546,700
null
1
20
android|android-support-library|preferencefragment
9,202
<p>You can specify a custom layout in your theme.</p> <p>For example:</p> <p><strong>styles.xml</strong></p> <pre><code>&lt;style name="YourTheme" parent="Theme.AppCompat"&gt; &lt;!-- ... --&gt; &lt;item name="preferenceTheme"&gt;@style/YourTheme.PreferenceThemeOverlay&lt;/item&gt; &lt;/style&gt; &lt;style name="YourTheme.PreferenceThemeOverlay" parent="@style/PreferenceThemeOverlay"&gt; &lt;item name="android:layout"&gt;@layout/fragment_your_preferences&lt;/item&gt; &lt;/style&gt; </code></pre> <p><strong>fragment_your_preferences.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/custom_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;!-- Required ViewGroup for PreferenceFragmentCompat --&gt; &lt;FrameLayout android:id="@android:id/list_container" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;/FrameLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>And then in <code>onViewCreated()</code> of your fragment class you can start using the views:</p> <pre><code>@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Toolbar toolbar = (Toolbar)view.findViewById(R.id.custom_toolbar); if (toolbar != null) { getMainActivity().setSupportActionBar(toolbar); } } </code></pre>
10,606,854
How can I connect an iOS device to non iOS device (Arduino devices) via Bluetooth?
<p>After searching on Google, I found that people say it's only possible to connect an iOS device with a non iOS device with the 'MFi program'. Is that true?</p> <p>My project is mainly focused on sending and receiving information with the Arduino device via Bluetooth directly.</p> <p>Is communication between iOS and non iOS devices without <a href="http://en.wikipedia.org/wiki/IOS_jailbreaking" rel="nofollow noreferrer">jailbreak</a> possible? If yes, is there a reference?</p> <p>(I viewed Stack&nbsp;Overflow question <em><a href="https://stackoverflow.com/questions/1065459/how-can-an-iphone-access-another-non-iphone-device-over-wireless-or-bluetooth/1066375#1066375">How can an iPhone access another non-iPhone device over wireless or Bluetooth?</a></em>.)</p>
10,626,375
2
3
null
2012-05-15 18:40:02.85 UTC
10
2012-05-25 15:33:45.84 UTC
2017-05-23 12:11:28.33 UTC
null
-1
null
411,604
null
1
8
iphone|bluetooth|arduino|ios5|mfi
6,992
<p>As I stated in the above-linked question, general Bluetooth communication to external devices on non-jailbroken iOS devices is restricted to MFi-compliant Bluetooth hardware. </p> <p>However, newer iOS devices (iPhone 4S, new iPad) are capable of Bluetooth 4.0 LE communication with external devices without the need for those devices to be MFi-compliant. This interaction is done through the new Core Bluetooth framework, which lets you send and receive arbitrary data to and from Bluetooth LE devices. This only works with those listed newer iOS devices, though.</p> <p>Tim points out an interesting hack that you might be able to get away with in making your device appear like a Bluetooth HID keyboard. Devices like <a href="http://ftp.opticonusa.com/OPN2002/Documents/OPN2002%20iPad%20&amp;%20iPhone%20QSG.pdf" rel="noreferrer">this barcode scanner</a> have special modes to appear as HID devices to iOS. You might be able to pull something together based on this, but all data transfer will be one-way from your device, and it looks like this will require entering that data into text fields as if you had a keyboard connected.</p>
10,286,056
What is the command to exit a console application in C#?
<p>What is the command in C# for exiting a console application?</p>
10,286,091
4
3
null
2012-04-23 18:20:47.653 UTC
41
2022-01-17 22:46:48.303 UTC
2022-01-17 22:40:24.677 UTC
null
63,550
null
1,352,015
null
1
312
c#|console-application|exit
446,762
<p>You can use <code>Environment.Exit(0);</code> and <code>Application.Exit</code></p> <p><code>Environment.Exit(0)</code> <a href="https://web.archive.org/web/20201029173358/http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx" rel="noreferrer">is cleaner</a>.</p>
10,284,103
How to declare a variable in the scope of a given function with GDB?
<p>I know that gdb allows for an already declared variable to be <em>set</em> using the <code>set</code> command.</p> <p>Is it possible for gdb to dynamically declare a new variable inside the scope of a given function?</p>
10,284,162
3
5
null
2012-04-23 16:05:35.407 UTC
5
2022-08-03 00:28:44.113 UTC
2017-04-26 12:34:09.227 UTC
null
895,245
null
707,381
null
1
29
c|gdb
23,816
<p>For C (and probably C++) code, that would be very hard, since doing so in most implementations would involve shifting the stack pointer, which would make the function's exit code fail due to it no longer matching the size of the stack frame. Also all the code in the function that accesses local variables would suddenly risk hitting the wrong location, which is also bad.</p> <p>So, I don't think so, no.</p>
10,803,685
Eclipse CDT: Symbol 'cout' could not be resolved
<p>The error is as above. I have what should be all the necessary files include in the eclipse project:</p> <pre><code>/usr/include/c++/4.6 /usr/include /usr/include/linux /usr/local/include </code></pre> <p>etc. </p> <p>I tried <code>std::cout</code> and <code>using namespace std;</code> <code>cout</code> but it still says unresolved. </p> <p>I have imported <code>iostream</code> and <code>cstdlib</code>.</p> <p>Also, I'm on Ubuntu 12.04 with eclipse 3.7.2.</p> <p>Code snippet:</p> <pre><code>#include &lt;cstdio&gt; #include &lt;cstdlib&gt; #include &lt;cstring&gt; #include &lt;iostream&gt; #include "XPLMDisplay.h" #include "XPLMGraphics.h" int XPluginStart(char * outName, char * outSig, char * outDesc) { /* ... */ std::cout &lt;&lt; "test" &lt;&lt; std::endl; /* ... */ } </code></pre> <p>using namespace std;</p> <hr> <p>UPDATE: I had created the eclipse project from existing code. Creating a new c++ project fixes it. I'll accept an answer that explains what setting in the existing project could cause this (so I don't have to cut &amp; paste all my projects).</p>
10,804,034
15
11
null
2012-05-29 17:10:40.213 UTC
26
2019-08-19 22:26:24.693 UTC
2012-05-29 17:26:17.443 UTC
null
616,827
null
616,827
null
1
64
c++|eclipse|include|eclipse-cdt|include-path
199,149
<p>Most likely you have some system-specific include directories missing in your settings which makes it impossible for indexer to correctly parse iostream, thus the errors. Selecting <code>Index -&gt; Search For Unresolved Includes</code> in the context menu of the project will give you the list of unresolved includes which you can search in <code>/usr/include</code> and add containing directories to <code>C++ Include Paths and Symbols</code> in Project Properties.</p> <p>On my system I had to add <code>/usr/include/c++/4.6/x86_64-linux-gnu</code> for <code>bits/c++config.h</code> to be resolved and a few more directories.</p> <p>Don't forget to rebuild the index (Index -> Rebuild) after adding include directories.</p>
53,162,001
TypeError during Jest's spyOn: Cannot set property getRequest of #<Object> which has only a getter
<p>I'm writing a React application with TypeScript. I do my unit tests using Jest.</p> <p>I have a function that makes an API call:</p> <pre><code>import { ROUTE_INT_QUESTIONS } from "../../../config/constants/routes"; import { intQuestionSchema } from "../../../config/schemas/intQuestions"; import { getRequest } from "../../utils/serverRequests"; const intQuestionListSchema = [intQuestionSchema]; export const getIntQuestionList = () =&gt; getRequest(ROUTE_INT_QUESTIONS, intQuestionListSchema); </code></pre> <p>The <code>getRequest</code> function looks like this:</p> <pre><code>import { Schema } from "normalizr"; import { camelizeAndNormalize } from "../../core"; export const getRequest = (fullUrlRoute: string, schema: Schema) =&gt; fetch(fullUrlRoute).then(response =&gt; response.json().then(json =&gt; { if (!response.ok) { return Promise.reject(json); } return Promise.resolve(camelizeAndNormalize(json, schema)); }) ); </code></pre> <p>I wanted to try the API function using Jest like this:</p> <pre><code>import fetch from "jest-fetch-mock"; import { ROUTE_INT_QUESTIONS } from "../../../config/constants/routes"; import { normalizedIntQuestionListResponse as expected, rawIntQuestionListResponse as response } from "../../../config/fixtures"; import { intQuestionSchema } from "../../../config/schemas/intQuestions"; import * as serverRequests from "./../../utils/serverRequests"; import { getIntQuestionList } from "./intQuestions"; const intQuestionListSchema = [intQuestionSchema]; describe("getIntQuestionList", () =&gt; { beforeEach(() =&gt; { fetch.resetMocks(); }); it("should get the int question list", () =&gt; { const getRequestMock = jest.spyOn(serverRequests, "getRequest"); fetch.mockResponseOnce(JSON.stringify(response)); expect.assertions(2); return getIntQuestionList().then(res =&gt; { expect(res).toEqual(expected); expect(getRequestMock).toHaveBeenCalledWith(ROUTE_INT_QUESTIONS, intQuestionListSchema); }); }); }); </code></pre> <p>The problem is that the line with <code>spyOn</code> throws the following error:</p> <pre><code> ● getRestaurantList › should get the restaurant list TypeError: Cannot set property getRequest of #&lt;Object&gt; which has only a getter 17 | 18 | it("should get the restaurant list", () =&gt; { &gt; 19 | const getRequestMock = jest.spyOn(serverRequests, "getRequest"); | ^ 20 | fetch.mockResponseOnce(JSON.stringify(response)); 21 | 22 | expect.assertions(2); at ModuleMockerClass.spyOn (node_modules/jest-mock/build/index.js:706:26) at Object.spyOn (src/services/api/IntQuestions/intQuestions.test.ts:19:33) </code></pre> <p>I googled this and only found posts about hot reloading. So what could cause this during Jest test? How can I get this test to pass?</p>
53,307,822
7
4
null
2018-11-05 20:49:54.003 UTC
7
2021-04-09 19:41:01.013 UTC
null
null
null
null
8,331,756
null
1
62
reactjs|unit-testing|jestjs|spy|spyon
48,332
<p>This one was interesting.</p> <h2>Issue</h2> <p><code>Babel</code> generates properties with only <code>get</code> defined for re-exported functions.</p> <p><code>utils/serverRequests/index.ts</code> re-exports functions from other modules so an error is thrown when <code>jest.spyOn</code> is used to spy on the re-exported functions.</p> <hr> <h2>Details</h2> <p>Given this code re-exporting everything from <code>lib</code>:</p> <pre class="lang-js prettyprint-override"><code>export * from './lib'; </code></pre> <p>...<code>Babel</code> produces this:</p> <pre class="lang-js prettyprint-override"><code>'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _lib = require('./lib'); Object.keys(_lib).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _lib[key]; } }); }); </code></pre> <p>Note that the properties are all defined with only <code>get</code>.</p> <p>Trying to use <code>jest.spyOn</code> on any of those properties will generate the error you are seeing because <code>jest.spyOn</code> tries to replace the property with a spy wrapping the original function but can't if the property is defined with only <code>get</code>.</p> <hr> <h2>Solution</h2> <p>Instead of importing <code>../../utils/serverRequests</code> (which re-exports <code>getRequest</code>) into the test, import the module where <code>getRequest</code> is defined and use that module to create the spy.</p> <h2>Alternate Solution</h2> <p>Mock the entire <code>utils/serverRequests</code> module as suggested by @Volodymyr and @TheF</p>
13,580,561
Sublime text 2 - Change side bar color
<p>What is the way to change the color of the side bar (file browser)? What do I need to add to my <code>.tmTheme</code> file to modify the defaults?</p> <p>Using a dark theme the side bar can be too bright for my taste.</p>
13,584,477
7
0
null
2012-11-27 09:01:51.823 UTC
12
2019-06-25 13:04:57.21 UTC
2012-11-27 09:21:43.817 UTC
null
416,947
null
416,947
null
1
25
sublimetext2
40,528
<p>You want to go into your </p> <pre><code>~/Library/Application Support/Sublime Text 2/Packages/Default/Default.sublime-theme </code></pre> <p>(old version) or </p> <pre><code>~/Library/Application Support/Sublime Text 2/Packages/Theme-Default/Default.sublime-theme </code></pre> <p>(new version) and edit these things:</p> <ul> <li><code>"class": "sidebar_container"</code></li> <li><code>"class": "sidebar_tree"</code></li> <li><code>"class": "sidebar_heading"</code></li> <li><code>"class": "sidebar_label"</code></li> </ul> <p>Therein you can change the RGB colors until you get what you want. </p> <p><a href="http://sublimetext.userecho.com/topic/19274-theming-of-the-sidebar/" rel="nofollow noreferrer">Here is a thread that discusses this in greater detail.</a></p> <p>edit: added the correct location provided by @Michael Tunnell</p> <p>edit: Sample Dark SideBar Configuration.</p> <p><a href="https://i.stack.imgur.com/9AZpm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9AZpm.png" alt="Image with Dark SideBar"></a></p> <p>Click to See Larger Image for Settings <a href="https://i.stack.imgur.com/NSzsF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NSzsF.png" alt="Click to See Larger Image for Settings"></a></p>
13,480,846
how to modify the install-path without running the configure script/cmake again
<p>I am working on a project which takes considerable time to build (10-15) minutes. I have recompiled to verify if there is a compilation error. Now I want to change the install directory so that I have a new version of executable with the new changes. Is there a method to just modify the install path so that the 'make install' installs to a new location rather than the old one?</p>
13,488,348
5
1
null
2012-11-20 19:42:25.147 UTC
14
2014-06-15 21:38:25.93 UTC
null
null
null
null
811,335
null
1
41
makefile|cmake|configure|build-system
42,626
<p>CMake generated makefiles support the <a href="http://www.gnu.org/prep/standards/html_node/DESTDIR.html">DESTDIR coding convention</a> for makefiles. Thus you can override the default installation location by setting the <code>DESTDIR</code> variable upon invoking make:</p> <pre><code>$ make install DESTDIR=/opt/local </code></pre> <p>There is no need to re-run CMake.</p>
13,432,717
Enter Interactive Mode In Python
<p>I'm running my Python program and have a point where it would be useful to jump in and see what's going on, and then step out again. Sort of like a temporary console mode.</p> <p>In Matlab, I'd use the <a href="http://www.mathworks.com/help/matlab/ref/keyboard.html"><code>keyboard</code></a> command to do this, but I'm not sure what the command is in python.</p> <p>Is there a way to do this?</p> <p>For instance:</p> <pre><code>for thing in set_of_things: enter_interactive_mode_here() do_stuff_to(thing) </code></pre> <p>When <code>enter_interactive_mode()</code> calls, I'd like to go there, look around, and then leave and have the program continue running.</p>
13,432,868
7
2
null
2012-11-17 17:04:34.233 UTC
21
2020-05-08 18:40:50.907 UTC
2012-11-17 17:11:49.787 UTC
null
752,843
null
752,843
null
1
65
python|interactive
40,993
<p><code>code.interact()</code> seems to work somehow:</p> <pre><code>&gt;&gt;&gt; import code &gt;&gt;&gt; def foo(): ... a = 10 ... code.interact(local=locals()) ... return a ... &gt;&gt;&gt; foo() Python 3.6.5 (default, Apr 1 2018, 05:46:30) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) &gt;&gt;&gt; a 10 </code></pre> <p><kbd>Ctrl</kbd>+<kbd>Z</kbd> returns to the "main" interpreter.</p> <p>You can read the locals, but modifying them doesn't seem to work this way.</p>
16,531,093
Conditional Formatting (IF not empty)
<p>How do I conditionally format a cell so if not blank it is grey? </p> <p>I tried to do 'not equal', but it didn't work.</p> <p>I am using Windows Office 2003 with Windows XP at work. I don't see the same feature as below:</p> <p><img src="https://i.stack.imgur.com/qL9xBm.jpg" alt="enter image description here"></p> <p>What I have tried so far: </p> <p><img src="https://i.stack.imgur.com/YKInKm.jpg" alt="enter image description here"></p> <p>Edit: Figured what was wrong. In my production (actual work Excel), they were filled with white color. It wasn't my Excel file, so I was not aware of this before.</p>
16,537,964
6
5
null
2013-05-13 21:03:12.24 UTC
2
2018-05-23 12:48:09.497 UTC
2015-10-19 10:50:48.08 UTC
null
1,505,120
null
1,276,534
null
1
15
excel|excel-2003|conditional-formatting
279,720
<p>You can use Conditional formatting with the option "Formula Is". One possible formula is</p> <pre><code>=NOT(ISBLANK($B1)) </code></pre> <p><img src="https://i.stack.imgur.com/zgzlg.png" alt="enter image description here"></p> <p>Another possible formula is</p> <pre><code>=$B1&lt;&gt;"" </code></pre> <p><img src="https://i.stack.imgur.com/XrpKS.png" alt="enter image description here"></p>
16,501,010
How to organize different versioned REST API controllers in Laravel 4?
<p>I know there's a way to create versioned URLs for REST APIs with routes, but what's the best way to organize controllers and controller files? I want to be able to create new versions of APIs, and still keep the old ones running for at least some time.</p>
16,533,940
1
0
null
2013-05-11 19:36:34.083 UTC
19
2013-05-14 01:53:57.143 UTC
null
null
null
null
928,001
null
1
20
php|laravel|laravel-4
9,247
<p>I ended up using namespaces and directories under app/controllers:</p> <pre><code>/app /controllers /Api /v1 /UserController.php /v2 /UserController.php </code></pre> <p>And in UserController.php files I set the namespace accordingly:</p> <pre><code>namespace Api\v1; </code></pre> <p>or</p> <pre><code>namespace Api\v2; </code></pre> <p>Then in my routes I did something like this:</p> <pre><code>Route::group(['prefix' =&gt; 'api/v1'], function () { Route::get('user', 'Api\v1\UserController@index'); Route::get('user/{id}', 'Api\v1\UserController@show'); }); Route::group(['prefix' =&gt; 'api/v2'], function () { Route::get('user', 'Api\v2\UserController@index'); Route::get('user/{id}', 'Api\v2\UserController@show'); }); </code></pre> <p>I'm not positive this is the best solution. However, it has allowed versioning of the controllers in a way that they do not interfere with each other. You could probably do something verify similar with the models if needed.</p>
16,484,796
draw a circle over image opencv
<p>Im usign python and opencv to get a image from the webcam, and I want to know how to draw a circle over my image, just a simple green circle with transparent fill</p> <p><img src="https://i.stack.imgur.com/tkgoD.gif" alt="enter image description here"></p> <p>my code:</p> <pre><code>import cv2 import numpy import sys if __name__ == '__main__': #get current frame from webcam cam = cv2.VideoCapture(0) img = cam.read() #how draw a circle???? cv2.imshow('WebCam', img) cv2.waitKey() </code></pre> <p>Thanks in advance.</p>
16,485,466
4
2
null
2013-05-10 14:38:24.09 UTC
4
2021-05-26 15:34:16.467 UTC
null
null
null
null
1,679,166
null
1
23
python|opencv|drawing
105,841
<pre><code>cv2.circle(img, center, radius, color, thickness=1, lineType=8, shift=0) → None Draws a circle. Parameters: img (CvArr) – Image where the circle is drawn center (CvPoint) – Center of the circle radius (int) – Radius of the circle color (CvScalar) – Circle color thickness (int) – Thickness of the circle outline if positive, otherwise this indicates that a filled circle is to be drawn lineType (int) – Type of the circle boundary, see Line description shift (int) – Number of fractional bits in the center coordinates and radius value </code></pre> <p>Use "thickness" parameter for only the border.</p>
16,481,884
How do I convert NSUInteger value to int value in objectiveC?
<p>How do I convert <code>NSUInteger</code> value to <code>int</code> value in objectiveC?</p> <p>and also how to print <code>NSUInteger</code> value in <code>NSLog</code> , I tried <code>%@,%d,%lu</code> these are not working and throwing <strong>Ex-Bad Access</strong> error.</p> <p>Thank you</p>
16,482,036
4
1
null
2013-05-10 12:07:56.163 UTC
4
2013-05-11 02:52:26.92 UTC
2013-05-10 15:01:08.557 UTC
null
1,226,963
null
1,776,435
null
1
30
ios|objective-c|int|nsuinteger
67,128
<pre><code>NSUInteger intVal = 10; int iInt1 = (int)intVal; NSLog(@"value : %lu %d", (unsigned long)intVal, iInt1); </code></pre> <p>for more reference, look <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html">here</a></p>
16,392,765
Delete directory regardless of 260 char limit
<p>I'm writing a simple script to delete USMT migration folders after a certain amount of days:</p> <pre><code>## Server List ## $servers = "Delorean","Adelaide","Brisbane","Melbourne","Newcastle","Perth" ## Number of days (-3 is over three days ago) ## $days = -3 $timelimit = (Get-Date).AddDays($days) foreach ($server in $servers) { $deletedusers = @() $folders = Get-ChildItem \\$server\USMT$ | where {$_.psiscontainer} write-host "Checking server : " $server foreach ($folder in $folders) { If ($folder.LastWriteTime -lt $timelimit -And $folder -ne $null) { $deletedusers += $folder Remove-Item -recurse -force $folder.fullname } } write-host "Users deleted : " $deletedusers write-host } </code></pre> <p>However I keep hitting the dreaded <code>Remove-Item : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.</code></p> <p>I've been looking at workarounds and alternatives but they all revolve around me caring what is in the folder.</p> <p>I was hoping for a more simple solution as I don't really care about the folder contents if it is marked for deletion.</p> <p>Is there any native Powershell cmdlet other than <strong>Remove-Item -recurse</strong> that can accomplish what I'm after?</p>
16,393,037
17
0
null
2013-05-06 05:57:17.56 UTC
12
2018-08-01 11:23:15.27 UTC
2016-09-20 07:15:10.697 UTC
null
1,163,423
null
1,740,026
null
1
55
powershell|limit
83,002
<p>This is a known limitation of <code>PowerShell</code>. The work around is to use <code>dir</code> cmd (sorry, but this is true).</p> <p><a href="http://asysadmin.tumblr.com/post/17654309496/powershell-path-length-limitation" rel="nofollow noreferrer">http://asysadmin.tumblr.com/post/17654309496/powershell-path-length-limitation</a></p> <p>or as mentioned by AaronH answer use \?\ syntax is in this example to delete build</p> <pre><code>dir -Include build -Depth 1 | Remove-Item -Recurse -Path "\\?\$($_.FullName)" </code></pre>
16,164,736
height: calc(100%) not working correctly in CSS
<p>I have a div that I want to fill the whole height of the body less a set number in pixels. But I can't get <code>height: calc(100% - 50px)</code> to work. </p> <p>The reason I want to do this is I have elements that have dynamic heights based on some varying criteria, e.g. height of the header changes based on different elements it can contain. A content div then needs to stretch to fill the rest of the available space available.</p> <p>The div element, however, stays the height of the content - it doesn't seem as if it interprets 100% to be the height of the body element.</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-css lang-css prettyprint-override"><code>body { background: blue; height: 100%; } header { background: red; height: 20px; width: 100%; } h1 { font-size: 1.2em; margin: 0; padding: 0; height: 30px; font-weight: bold; background: yellow; } #theCalcDiv { background: green; height: calc(100% - (20px + 30px)); display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header&gt;Some nav stuff here&lt;/header&gt; &lt;h1&gt;This is the heading&lt;/h1&gt; &lt;div id="theCalcDiv"&gt;This blocks needs to have a CSS calc() height of 100% - the height of the other elements.&lt;/div&gt;</code></pre> </div> </div> </p> <p>I would appreciate any help or pointers in the right direction.</p>
16,165,110
7
5
null
2013-04-23 08:40:44.587 UTC
15
2020-04-23 06:36:46.787 UTC
2020-04-23 06:36:46.787 UTC
null
6,904,888
null
2,159,828
null
1
66
css
253,276
<p>You need to ensure the html and body are set to 100% and also be sure to add vendor prefixes for calc, so -moz-calc, -webkit-calc.</p> <p>Following CSS works:</p> <pre><code>html,body { background: blue; height:100%; padding:0; margin:0; } header { background: red; height: 20px; width:100% } h1 { font-size:1.2em; margin:0; padding:0; height: 30px; font-weight: bold; background:yellow } #theCalcDiv { background:green; height: -moz-calc(100% - (20px + 30px)); height: -webkit-calc(100% - (20px + 30px)); height: calc(100% - (20px + 30px)); display:block } </code></pre> <p>I also set your margin/padding to 0 on html and body, otherwise there would be a scrollbar when this is added on.</p> <p>Here's an updated fiddle</p> <p><a href="http://jsfiddle.net/UF3mb/10/">http://jsfiddle.net/UF3mb/10/</a></p> <p>Browser support is: IE9+, Firefox 16+ and with vendor prefix Firefox 4+, Chrome 19+, Safari 6+</p>
16,225,177
Error: Selection does not contain a main type
<p>I am trying to run some java files in a new project. So I make the project, put the files in it and I try to run the main file so my game starts. </p> <p>I get an error that says <code>selection does not contain a main type</code>.</p> <p>I have tried several ways to run it:</p> <ul> <li>Some say to launch eclipse again, tried this a dozen times. </li> <li>Somewhere else someone pointed to open a new project and make a build path to the old project. </li> </ul> <p>Didn't work either. </p> <p>I am pretty sure it must work because I ran it a few hours ago at school. How do I get this working? Thank you in advance! </p>
16,230,316
23
6
null
2013-04-25 21:38:52.987 UTC
12
2022-03-26 15:19:59.57 UTC
2014-09-30 05:44:29.21 UTC
null
608,639
null
2,321,611
null
1
70
java|eclipse|project|startup|startup-error
306,137
<p>I hope you are trying to run the main class in this way, see screenshot:<br /> <img src="https://i.stack.imgur.com/aoCV9.png" alt="screenshot of Eclipse file context menu" /></p> <p>If not, then try this way. If yes, then please make sure that your class you are trying to run has a main method, that is, the same method definition as below:</p> <pre class="lang-java prettyprint-override"><code>public static void main(String[] args) { // some code here } </code></pre> <p>I hope this will help you.</p>
16,323,032
Why can't I capture this by-reference ('&this') in lambda?
<p>I understand the correct way to capture <code>this</code> (to modify object properties) in a lambda is as follows:</p> <pre><code>auto f = [this] () { /* ... */ }; </code></pre> <p>But I'm curious as to the following peculiarity I've seen:</p> <pre><code>class C { public: void foo() { // auto f = [] () { // this not captured auto f = [&amp;] () { // why does this work? // auto f = [&amp;this] () { // Expected ',' before 'this' // auto f = [this] () { // works as expected x = 5; }; f(); } private: int x; }; </code></pre> <p>The oddity that I am confused by (and would like answered) is why the following works:</p> <pre><code>auto f = [&amp;] () { /* ... */ }; // capture everything by reference </code></pre> <p>And why I cannot explicitly capture <code>this</code> by reference:</p> <pre><code>auto f = [&amp;this] () { /* ... */ }; // a compiler error as seen above. </code></pre>
16,323,119
2
1
null
2013-05-01 17:19:05.45 UTC
29
2022-08-31 10:30:53.577 UTC
2016-08-11 10:56:16.72 UTC
null
194,894
null
812,183
null
1
100
c++|c++11|lambda
74,109
<p>The reason <code>[&amp;this]</code> doesn't work is because it is a syntax error. Each comma-seperated parameter in the <code>lambda-introducer</code> is a <code>capture</code>:</p> <pre><code>capture: identifier &amp; identifier this </code></pre> <p>You can see that <code>&amp;this</code> isn't allowed syntactically. The reason it isn't allowed is because you would never want to capture <code>this</code> by reference, as it is a small const pointer. You would only ever want to pass it by value - so the language just doesn't support capturing <code>this</code> by reference.</p> <p>To capture <code>this</code> explicitly you can use <code>[this]</code> as the <code>lambda-introducer</code>.</p> <p>The first <code>capture</code> can be a <code>capture-default</code> which is:</p> <pre><code>capture-default: &amp; = </code></pre> <p>This means capture automatically whatever I use, by reference (<code>&amp;</code>) or by value (<code>=</code>) respectively - however the treatment of <code>this</code> is special - in both cases it is captured by value for the reasons given previously (even with a default capture of <code>&amp;</code>, which usually means capture by reference).</p> <p>5.1.2.7/8:</p> <blockquote> <p>For purposes of name lookup (3.4), determining the type and value of <code>this</code> (9.3.2) and transforming id- expressions referring to non-static class members into class member access expressions using <code>(*this)</code> (9.3.1), the compound-statement [OF THE LAMBDA] is considered in the context of the lambda-expression.</p> </blockquote> <p>So the lambda acts as if it is part of the enclosing member function when using member names (like in your example the use of the name <code>x</code>), so it will generate "implicit usages" of <code>this</code> just like a member function does.</p> <blockquote> <p>If a lambda-capture includes a capture-default that is <code>&amp;</code>, the identifiers in the lambda-capture shall not be preceded by <code>&amp;</code>. If a lambda-capture includes a capture-default that is <code>=</code>, the lambda-capture shall not contain <code>this</code> and each identifier it contains shall be preceded by <code>&amp;</code>. An identifier or <code>this</code> shall not appear more than once in a lambda-capture.</p> </blockquote> <p>So you can use <code>[this]</code>, <code>[&amp;]</code>, <code>[=]</code> or <code>[&amp;,this]</code> as a <code>lambda-introducer</code> to capture the <code>this</code> pointer by value.</p> <p>However <code>[&amp;this]</code> and <code>[=, this]</code> are ill-formed. In the last case gcc forgivingly warns for <code>[=,this]</code> that <code>explicit by-copy capture of ‘this’ redundant with by-copy capture default</code> rather than errors.</p>
12,856,845
Iterating through const char* array
<p>I have an really simple example of array of const char's and one function supposed to print them out (iterate through the chosen one). Contrary all my expectations, it's iterating through all of them and not only the one that was passed as argument.</p> <pre><code>#include &lt;iostream&gt; const char* oranges[] = { "ORANGE", "RED ORANGE" }; const char* apples[] = { "APPLE" }; const char* lemons[] = { "LEMON" }; void printFruit(const char** fruit){ int i =0; while (fruit[i] != '\0'){ std::cout &lt;&lt; "---------------------\n"; std::cout &lt;&lt; fruit[i] &lt;&lt; "\n"; i++; } } int main (int argc, const char * argv[]) { printFruit(oranges); return 0; } </code></pre> <p>The result i would expect is that the function printFruit with oranges given as argument will print ORANGE and RED ORANGE, meanwhile i get printed ALL of the fruits defined (from other arrays), like this:</p> <pre><code>--------------------- ORANGE --------------------- RED ORANGE --------------------- APPLE --------------------- LEMON </code></pre> <p>Sorry for my ignorance but why is this happening ? </p> <p>Edit: I followed this question: <a href="https://stackoverflow.com/questions/6812242/defining-and-iterating-through-array-of-strings-in-c">defining and iterating through array of strings in c</a> that is similar to mine.</p>
12,856,903
5
1
null
2012-10-12 10:11:53.24 UTC
2
2018-04-15 18:02:16.457 UTC
2017-05-23 12:10:02.417 UTC
null
-1
null
434,837
null
1
3
c++
41,593
<p>You are checking that <code>fruit[i] != '\0'</code>. That is wrong because <code>fruit[i]</code> is a <code>char *</code>, not a char. Furthermore, your vectors aren't terminated. You probably wanted to check whether <code>fruit[i] != 0</code>, or <code>*fruit[i] != '\0'</code>. In the first case, you need to terminate the vectors like this:</p> <pre><code>const char* oranges[] = { "ORANGE", "RED ORANGE", 0 // or NULL }; </code></pre> <p>In the second:</p> <pre><code>const char* oranges[] = { "ORANGE", "RED ORANGE", "" }; </code></pre>
17,538,910
How can I pass a parameter to an ng-click function?
<p>I have a function in my controller that looks like the following:</p> <p>AngularJS:</p> <pre><code>$scope.toggleClass = function(class){ $scope.class = !$scope.class; } </code></pre> <p>I want to keep it general by passing the name of the class that I want to toggle:</p> <pre><code>&lt;div class="myClass"&gt;stuff&lt;/div&gt; &lt;div ng-click="toggleClass(myClass)"&gt;&lt;/div&gt; </code></pre> <p>But <code>myClass</code> is not being passed to the angular function. How can I get this to work? The above code works if I write it like this:</p> <pre><code>$scope.toggleClass = function(){ $scope.myClass = !$scope.myClass; } </code></pre> <p>But, this is obviously not general. I don't want to hard-code in the class named <code>myClass</code>.</p>
17,539,205
1
1
null
2013-07-09 02:20:34.84 UTC
null
2013-07-09 04:19:58.277 UTC
null
null
null
null
2,547,946
null
1
13
angularjs|angularjs-ng-click
41,656
<p>In the function</p> <pre class="lang-javascript prettyprint-override"><code>$scope.toggleClass = function(class){ $scope.class = !$scope.class; } </code></pre> <p><code>$scope.class</code> doesn't have anything to do with the paramter <code>class</code>. It's literally a property on <code>$scope</code> called <code>class</code>. If you want to access the property on <code>$scope</code> that is <em>identified</em> by the variable <code>class</code>, you'll need to use the array-style accessor:</p> <pre class="lang-javascript prettyprint-override"><code>$scope.toggleClass = function(class){ $scope[class] = !$scope[class]; } </code></pre> <p>Note that this is not Angular specific; this is just how JavaScript works. Take the following example:</p> <pre class="lang-javascript prettyprint-override"><code>&gt; var obj = { a: 1, b: 2 } &gt; var a = 'b' &gt; obj.a 1 &gt; obj[a] // the same as saying: obj['b'] 2 </code></pre> <hr> <p>Also, the code</p> <pre class="lang-html prettyprint-override"><code>&lt;div ng-click="toggleClass(myClass)"&gt;&lt;/div&gt; </code></pre> <p>makes the assumption that there is a variable on your scope, e.g. <code>$scope.myClass</code> that evaluates to a string that has the name of the property you want to access. If you <em>literally</em> want to pass in the string <code>myClass</code>, you'd need</p> <pre class="lang-html prettyprint-override"><code>&lt;div ng-click="toggleClass('myClass')"&gt;&lt;/div&gt; </code></pre> <p>The example doesn't make it super clear which you're looking for (since there is a class named <code>myClass</code> on the top <code>div</code>).</p>
22,104,955
bash fork error (Resource temporarily unavailable) does not stop, and keeps showing up every time I try to kill/reboot
<p>I mistakenly used a limited server as an iperf server for 5000 parallel connections. (limit is 1024 processes) Now every time I log in, I see this:</p> <pre><code>-bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: Resource temporarily unavailable </code></pre> <p>Then, I try to kill them, but when I do ps, I get this:</p> <pre><code>-bash-4.1$ ps -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: Resource temporarily unavailable </code></pre> <p>Same happens when I do a killall or similar things. I have even tried to reboot the system but again this is what I get after reboot:</p> <pre><code>-bash-4.1$ sudo reboot -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: retry: Resource temporarily unavailable -bash: fork: Resource temporarily unavailable -bash-4.1$ </code></pre> <p>So Basically I cannot do anything. all the commands get this error :/ I can, however, do "exit".</p> <p>This is an off-site server that I do not have physical access to, so I cannot turn it off/on physically.</p> <p>Any ideas how I can fix this problem? I highly appreciate any help.</p>
22,105,071
2
2
null
2014-02-28 20:14:01.977 UTC
7
2014-09-25 16:44:06.503 UTC
null
null
null
null
2,662,165
null
1
14
linux|bash|process|fork|ulimit
39,044
<p>Given that you can login, you may want to try using <code>exec</code> to execute all your commands. After executing <code>exec</code> you will have to log in again, since <code>exec</code> will kill your shell (by replacing it with the command you run).</p> <p><code>exec</code> won't take up an extra process slot because it will replaces the running shell with the program to run. Thus, it should be able to bypass the <code>ulimit</code> restriction.</p>
19,398,625
Read data from Excel file in Selenium Java
<p>I am trying to read data from excel sheet to automate my testing(with a number of login credentials). I am using a utility that I found on web. But it is not running successfully. </p> <p>Here is the utility</p> <pre><code> package google; import java.io.File; import java.io.IOException; import java.util.Hashtable; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class class2 { static Sheet wrksheet; static Workbook wrkbook =null; static Hashtable dict= new Hashtable(); //Create a Constructor public class2(String ExcelSheetPath) throws BiffException, IOException { //Initialize wrkbook = Workbook.getWorkbook(new File(ExcelSheetPath)); //For Demo purpose the excel sheet path is hardcoded, but not recommended :) wrksheet = wrkbook.getSheet("Sheet1"); } //Returns the Number of Rows public static int RowCount() { return wrksheet.getRows(); `enter code here` } //Returns the Cell value by taking row and Column values as argument public static String ReadCell(int column,int row) { return wrksheet.getCell(column,row).getContents(); } //Create Column Dictionary to hold all the Column Names public static void ColumnDictionary() {`enter code here` //Iterate through all the columns in the Excel sheet and store the value for(int col=0; col &lt;= wrksheet.getColumns();col++) { dict.put(ReadCell(col,0), col); } } //Read Column Names public static int GetCell(String colName) { try { int value; value = ((Integer) dict.get(colName)).intValue(); return value; } catch (NullPointerException e) { return (0); } } } </code></pre> <p>And following is the class that calls this utility.</p> <pre><code>package google; import java.io.IOException; import jxl.read.biff.BiffException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import google.class2; public class class3 { //Global initialization of Variables static class2 xlsUtil; WebDriver driver = new InternetExplorerDriver(); //Constructor to initialze Excel for Data source public class3() throws BiffException, IOException { //Let's assume we have only one Excel File which holds all Testcases. Demo !!! xlsUtil = new class2("C:/Users/admin/workspace/login.xls"); //Load the Excel Sheet Col in to Dictionary for Further use in our Test cases. xlsUtil.ColumnDictionary(); } @BeforeTest public void EnvironmentalSetup() { System.setProperty("webdriver.chrome.driver", "C:/Users/admin/Downloads/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://192.168.1.20/dental/userlogin"); } @Test public void GmailLoginPage() throws InterruptedException { //Create a for loop.. for iterate through our Excel sheet for all the test cases. for(int rowCnt = 1;rowCnt &lt;= xlsUtil.RowCount();rowCnt++) { //Enter User Name by reading data from Excel WebElement userName = driver.findElement(By.name("UserName")); userName.clear(); userName.sendKeys(xlsUtil.ReadCell(xlsUtil.GetCell("EmailUserName"), rowCnt)); //Enter Password WebElement password = driver.findElement(By.name("Password")); password.clear(); password.sendKeys(xlsUtil.ReadCell(xlsUtil.GetCell("Emailpassword"), rowCnt)); //Click on the Sign In Button // WebElement signin = driver.findElement(By.name("signIn")); password.submit(); //Sleep for some time,so that we can see things in action @ Screen :) Thread.sleep(2000); } } } </code></pre> <p>But when I run dis cass it says 'cant instantiate google.class3 I don't get the mistake here. Please help me run this code successfully.</p>
19,582,123
3
5
null
2013-10-16 08:33:36.87 UTC
1
2019-01-15 08:49:59.483 UTC
2014-10-19 18:38:53.02 UTC
null
3,885,376
null
2,825,603
null
1
1
java|eclipse|excel|selenium
44,569
<pre><code>FileInputStream file = newFileInputStream(newFile("C:/Users/admin/workspace/login.xls")); //Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(file); //Get first sheet from the workbook HSSFSheet sheet = workbook.getSheetAt(0); //Iterate through each rows from first sheet Iterator&lt;Row&gt; rowIterator = sheet.iterator(); while(rowIterator.hasNext()) { Row row = rowIterator.next(); //For each row, iterate through each columns Iterator&lt;Cell&gt; cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { Cell cell = cellIterator.next(); if(cell.getColumnIndex() == 0){ driver.findElement(By.name("UserName")).sendKeys(cell.getStringCellValue()); } else driver.findElement(By.name("Password")).sendKeys(cell.getStringCellValue()); } </code></pre>
19,661,157
How to add header data in XMLHttpRequest when using formdata?
<p>I'm trying to implement a file upload API, given here : <br> <a href="http://www.mediafire.com/developers/core_api/1.4/upload/#upload_top" rel="noreferrer">Mediafire file Upload</a></p> <p>I am successfully able to upload the <em>Post data</em> &amp; <em>Get data</em>, but have no clue how to send the <strong>x-filename</strong> attribute, which is meant to be <em>Header data</em> as given in API guide.</p> <p>My Code : </p> <pre><code>xmlhttp=new XMLHttpRequest(); var formData = new FormData(); formData.append("Filedata", document.getElementById("myFile").files[0]); var photoId = getCookie("user"); // formData.append("x-filename", photoId); //tried this but doesn't work // xmlhttp.setRequestHeader("x-filename", photoId); //tried this too (gives error) [edited after diodeous' answer] xmlhttp.onreadystatechange=function() { alert("xhr status : "+xmlhttp.readyState); } var url = "http://www.mediafire.com/api/upload/upload.php?"+"session_token="+getCookie("mSession")+"&amp;action_on_duplicate=keep"; xmlhttp.open("POST", url); // xmlhttp.setRequestHeader("x-filename", photoId); //tried this too, doesnt work. Infact nothing gets uploaded on mediafire. [edited after apsillers' answer] // cant get response due to same origin policy xmlhttp.send(formData); </code></pre>
19,662,150
3
5
null
2013-10-29 14:33:23.777 UTC
12
2018-01-16 23:13:26.547 UTC
2015-07-12 18:32:00.297 UTC
null
1,329,213
null
1,329,213
null
1
63
javascript|http-headers|xmlhttprequest|form-data|mediafire
162,209
<p>Your error</p> <blockquote> <p>InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable</p> </blockquote> <p>appears because you must call <code>setRequestHeader</code> <em>after</em> calling <code>open</code>. Simply move your <code>setRequestHeader</code> line below your <code>open</code> line (but before <code>send</code>):</p> <pre><code>xmlhttp.open("POST", url); xmlhttp.setRequestHeader("x-filename", photoId); xmlhttp.send(formData); </code></pre>
17,590,226
Finding length of array inside a function
<p>In the program below the length of the array <code>ar</code> is correct in main but in <code>temp</code> it shows the length of the pointer to <code>ar</code> which on my computer is 2 (in units of <code>sizeof(int)</code>). </p> <pre><code>#include &lt;stdio.h&gt; void temp(int ar[]) // this could also be declared as `int *ar` { printf("%d\n", (int) sizeof(ar)/sizeof(int)); } int main(void) { int ar[]={1,2,3}; printf("%d\n", (int) sizeof(ar)/sizeof(int)); temp(ar); return 0; } </code></pre> <p>I wanted to know how I should define the function so the length of the array is read correctly in the function.</p>
17,590,328
7
8
null
2013-07-11 09:48:24.657 UTC
9
2018-03-10 21:27:39.647 UTC
2018-01-01 13:41:40.537 UTC
null
107,625
null
1,111,034
null
1
24
c|arrays
44,164
<p>There is no 'built-in' way to determine the length inside the function. However you pass <code>arr</code>, <code>sizeof(arr)</code> will always return the pointer size. So the best way is to pass the number of elements as a seperate argument. Alternatively you could have a special value like <code>0</code> or <code>-1</code> that indicates the end (like it is <code>\0</code> in strings, which are just <code>char []</code>). But then of course the 'logical' array size was <code>sizeof(arr)/sizeof(int) - 1</code> </p>
17,201,170
PHP how to get the base domain/url?
<pre><code>function url(){ if(isset($_SERVER['HTTPS'])){ $protocol = ($_SERVER['HTTPS'] &amp;&amp; $_SERVER['HTTPS'] != "off") ? "https" : "http"; } else{ $protocol = 'http'; } return $protocol . "://" . $_SERVER['HTTP_HOST']; } </code></pre> <p>For example with the function above, it works fine if I work with the same directory, but if I make a sub directory, and work in it, it will give me the location of the sub directory also for example. I just want <code>example.com</code> but it gives me <code>example.com/sub</code> if I'm working in the folder <code>sub</code>. If I'm using the main directory,the function works fine. Is there an alternative to <code>$_SERVER['HTTP_HOST']</code>?</p> <p>Or how could I fix my function/code to get the main url only? Thanks.</p>
17,201,254
13
1
null
2013-06-19 20:56:43.62 UTC
15
2021-01-11 00:02:26.433 UTC
null
null
null
null
1,761,023
null
1
71
php
269,860
<p>Use <code>SERVER_NAME</code>.</p> <pre><code>echo $_SERVER['SERVER_NAME']; //Outputs www.example.com </code></pre>
17,173,864
How to make a list of associative array in yaml
<p>I'm trying to store some configuration variables in yaml represented as an associative array aka dictionary. Here is how I did:</p> <pre><code>content_prices: - {country: AU, price: 6990000} - {country: AT, price: 4990000} - {country: BE, price: 4990000} </code></pre> <p>This produce an exception when I try to parse it from my ROR init files:</p> <blockquote> <p>undefined method `symbolize_keys!' for nil:NilClass</p> </blockquote> <p>Here is how I init it:</p> <pre><code>Config = YAML.load_file("#{Rails.root}/config/prices.yml")[Rails.env].symbolize_keys! </code></pre> <p>I guess my yaml syntax is wrong, then how to write it properly ?</p>
17,173,956
3
1
null
2013-06-18 16:10:37.803 UTC
19
2019-04-17 16:21:55.93 UTC
2017-04-08 14:07:53.587 UTC
null
42,223
null
1,485,230
null
1
97
ruby-on-rails|dictionary|yaml|associative-array
57,837
<p>Your YAML looks okay, or you can configure an array of hashes like this :</p> <pre><code>content_prices: - country: AU price: 6990000 - country: AT price: 4990000 - country: BE price: 4990000 </code></pre> <p>Which will load as the following hash:</p> <pre><code>{"content_prices"=&gt;[ {"country"=&gt;"AU", "price"=&gt;6990000}, {"country"=&gt;"AT", "price"=&gt;4990000}, {"country"=&gt;"BE", "price"=&gt;4990000}]} </code></pre> <p>But that still doesn't give you any reference to the <code>Rails.env</code> in the main hash. The problem seems to be what you're expecting to be in your hash rather than the format of the YAML.</p>
17,194,301
Is there any way to show the dependency trees for pip packages?
<p>I have a project with multiple package dependencies, the main requirements being listed in <code>requirements.txt</code>. When I call <code>pip freeze</code> it prints the currently installed packages as plain list. I would prefer to also get their dependency relationships, something like this:</p> <pre><code>Flask==0.9 Jinja2==2.7 Werkzeug==0.8.3 Jinja2==2.7 Werkzeug==0.8.3 Flask-Admin==1.0.6 Flask==0.9 Jinja2==2.7 Werkzeug==0.8.3 </code></pre> <p>The goal is to detect the dependencies of each specific package:</p> <pre><code>Werkzeug==0.8.3 Flask==0.9 Flask-Admin==1.0.6 </code></pre> <p>And insert these into my current <code>requirements.txt</code>. For example, for this input:</p> <pre><code>Flask==0.9 Flask-Admin==1.0.6 Werkzeug==0.8.3 </code></pre> <p>I would like to get:</p> <pre><code>Flask==0.9 Jinja2==2.7 Flask-Admin==1.0.6 Werkzeug==0.8.3 </code></pre> <p>Is there any way show the dependencies of installed pip packages?</p>
24,903,067
3
0
null
2013-06-19 14:44:50.873 UTC
20
2021-08-04 15:57:51.98 UTC
2017-08-09 12:33:04.257 UTC
null
1,000,551
null
880,326
null
1
152
python|pip|requirements.txt
73,473
<p>You should take a look at <a href="https://pypi.python.org/pypi/pipdeptree" rel="noreferrer"><code>pipdeptree</code></a>:</p> <pre><code>$ pip install pipdeptree $ pipdeptree -fl Warning!!! Cyclic dependencies found: ------------------------------------------------------------------------ xlwt==0.7.5 ruamel.ext.rtf==0.1.1 xlrd==0.9.3 openpyxl==2.0.4 - jdcal==1.0 pymongo==2.7.1 reportlab==3.1.8 - Pillow==2.5.1 - pip - setuptools </code></pre> <p>It doesn't generate a <code>requirements.txt</code> file as you indicated directly. However the source (255 lines of python code) should be relatively easy to modify to your needs, or alternatively you can (as @MERose indicated is in the pipdeptree 0.3 README ) out use:</p> <pre><code>pipdeptree --freeze --warn silence | grep -P '^[\w0-9\-=.]+' &gt; requirements.txt </code></pre> <p>The 0.5 version of <code>pipdeptree</code> also allows JSON output with the <code>--json</code> option, that is more easily machine parseble, at the expense of being less readable.</p>
25,972,910
JAR - extracting specific files
<p>I have .class and .java files in JAR archive. Is there any way to extract only .java files from it? I've tried this command but it doesn't work:</p> <pre><code>jar xf jar-file.jar *.java </code></pre>
25,973,296
3
3
null
2014-09-22 11:22:54.83 UTC
5
2015-04-22 10:29:52.983 UTC
null
null
null
null
3,521,479
null
1
36
java|jar|extract|archive
62,097
<p>You can use the <code>unzip</code> command which accepts wildcards in its arguments (which is not the case of the <code>jar</code> command). Something like this should do the trick ( disclaimer : not tested)</p> <pre><code>unzip youFile.jar "*.java" </code></pre>
10,157,983
Javascript: Does not change the div innerHTML
<p>I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; alert('Hey'); var vText = document.getElementById("results"); vText.innerHTML = 'Changed'; alert(vText.innerHTML); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="results"&gt; hey there &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
10,158,010
5
5
null
2012-04-14 22:47:49.547 UTC
1
2012-04-14 23:02:28.713 UTC
2012-04-14 22:50:47.633 UTC
null
82,548
null
1,019,342
null
1
4
javascript|html
42,368
<p>This is working as you can see here:</p> <p><a href="http://jsfiddle.net/gHbss/">http://jsfiddle.net/gHbss/</a></p> <p>It's important that you put the JavaScript after your HTML div container.</p>
5,533,131
Creating a professional-looking (and behaving!) form designer
<p>When I began programming (some 10+ years ago), three things amazed me:</p> <ul> <li>Compilers/interpreters (back then I knew them as "programs that make my programs work", often followed by the qualifier "whatever they are")</li> <li>Code editors</li> <li>Form designers</li> </ul> <p>Back then, I accepted all of them as facts of life. I was able to make my own special-purpose programs, but "programs that made my programs work", code editors and form editors were made by the Gods and there was no way I could mess with them.</p> <p>Then I went to university, and took a course on formal language processing. After learning formal grammars, parsers, abstract syntax trees, etc.; all the magic about compilers, interpreters and code editors was soon gone. Compilers and interpreters could be written in sane and simple ways, and the only non-sane thing a syntax highlighting code editor could require were Windows API hacks.</p> <p>However, to this day, form editors remain a mystery to me. Either I lack the technical knowledge required to make a form designer, or I have such knowledge, but cannot find a way to use it to implement a form designer.</p> <p>Using Visual C++ and the MFC, I would like to implement a form designer inspired by the best form designer ever:</p> <p><img src="https://i.stack.imgur.com/9kZXK.jpg" alt="Visual Basic 6&#39;s form designer"></p> <p>In particular, I would like to imitate its two features that I like the most:</p> <ul> <li><p>The form being designed is inside a container. Thus, an arbitrarily large form may be designed without wasting too much screen real estate, by simply resizing the container to an appropriate size.</p></li> <li><p>The "Align to Grid" option makes designing professional-looking user interfaces a lot less frustrating. In fact, I would go as far as saying creating professional-looking user interfaces using Visual Basic's form designer is actually easy, fun and enjoyable. Even for left-brained programmers like me.</p></li> </ul> <p>So, I have the following questions: </p> <ol> <li><p>How do I make a form designer, in which the form being designed is inside a container? Is the form being designed an actual window contained inside another window? Or is it just a mockup "manually" painted by the form designer?</p></li> <li><p>Do the Windows API and/or the MFC contain functions, classes, whatever that make it easy to create "selectable" items (surrounded by little white or blue boxes when they are selected, resizable when they are "grabbed" by one of these "edges")?</p></li> <li><p>How do I implement the "Align to Grid" functionality?</p></li> </ol>
5,534,688
3
5
null
2011-04-03 23:05:19.32 UTC
9
2012-01-06 17:30:54.323 UTC
null
null
null
null
46,571
null
1
27
c++|windows|winapi|mfc|form-designer
4,224
<p>Both the answers here are good, but left out what I consider to be the really interesting bits (including a couple that you didn't ask directly, but you might find of interest anyhow), so here's my 2c:</p> <h2>Drawing the controls</h2> <p>Ideally, you just go ahead and create a regular instance of the control. You want something that looks like a button? Create a real button. The tricky thing is stopping it from behaving like a button: you want clicks to activate it for moving, not actually 'click' it.</p> <p>One way of dealing with this - assuming that the controls in question are 'HWND-based' (eg. the standard windows set of button, edit, static, listbox, treeview, etc.) - is to create the control, and then subclass it - ie. override the wndproc with SetWindowLongPtr(GWLP_WNDPROC, ...), so that the designer code can intercept mouse and keyboard input and use it to initiate a move, for example, instead of having the mouse input go through to the actual button code, which would instead interpret it as a 'click' event.</p> <p>An alternative approach to subclassing is to place an invisible window above the button to capture the input. Same idea of intercepting input, just different implementation.</p> <p>The above applies to both managed (VB.Net, C#) and unmanaged (C/C++) controls; they're both essentially stock windows HWNDs; the managed versions just have a managed wrapper code handing off to the underlying unmanaged control.</p> <p>The old (pre-managed code) ActiveX controls, as used in pre-.Net VB, were a whole different ball game. There's a fairly complex relationship between an ActiveX container and the ActiveX controls within it, with many COM interfaces handling things like negotiation of properties, events, painting, and so on. (There's event a set of interfaces that allows an ActiveX control to receive input and draw itself without having its own HWND.) One benefit you get from this complexity, however, is that ActiveX controls have an explicit 'design mode'; so a control knows to respond appropriately in that case and can cooperate with the whole procedure.</p> <h2>The Form Itself...</h2> <p>So basically the controls are just regular controls. So you'd expect the form itself to be a regular form? - Almost. As far as I know, its just another HWND-based window, that's a child of the designer (so it gets clipped, and can be scrolled within it); but I think the designer is doing a bit of 'cheating' here, because usually Windows only draws frames like - with titlebar and min/max buttons that for actual top-level windows. I don't know offhand the exact technique that they're using here, but some options could include: painting it manually to mimic the Windows look; using the Windows "theme" APIs, which allow you to access the graphic elements used for the bits and pieces of titlebars and paint them wherever you want to; or, perhaps less likely, setting the window up as a "MDI Child window" - this is one exception case where windows will draw a frame around a nested window.</p> <h2>Draggable Handles</h2> <p>Simplest approach here is for the designer to create eight small square title-bar-less popup windows that sit above all the other elements - which initiate the appropriate resize code when they are clicked. As the user clicks from control to control, just move the drag handle windows to the currently active control. (Note that in all the above, Windows itself is figuring out who's been clicked, you never have to actually compare mouse coords against element rectangle coordinates and work it out yourself.)</p> <h2>Saving & Recreating</h2> <p>For plain windows system controls that are used by unmanaged C/C++, it's relatively easy: there's a well-known text-based file format - .rc - that describes the controls and locations. Have the designer spit out that (and likely a resource.h file also) and you're done: any C/C++ project can pick up those files and compile them in. Managed code (C#, VB.Net) has a somewhat more complex scheme, but it's still the same basic idea: write out a description in the style that the managed tools expect, and they'll happily compile it and use it.</p> <p>(ActiveX controls are - you've guessed it - a whole 'nother story. There isn't a standard format that I'm aware of, so the form editor and runtime that consumes the data would be closely tied together - eg. the form editor from pre-.Net VB6 produces forms that only VB can use. - I think. It's been some time ago...)</p> <p>As for recreating the form: if you have a .rc file, it gets compiled into a dialog resource, Windows has built in support to recreate those. Likewise, the managed code support libraries know how to recreate a form from its particular format. Both basically parse the description, and for each item, create elements of the appropriate classes, and set the appropriate style, text, and other properties as specified. It's not doing anything you can't do yourself, its just helper utility code.</p> <h2>Handling Focus</h2> <p>For a collection of HWNDs in any container, whether in 'test' mode or actually running in the real app, and regardless of whether you let Windows or Winforms handle the form creation or whether you created each HWNDs yourself, you can add tabbing support by calling <A HREF="http://msdn.microsoft.com/en-us/library/ms645498(v=vs.85).aspx">IsDialogMessage</A> in your message loop: see the MSDN page remarks section for details. (While WinForms could do this, I <i>think</i> it actually does its own focus handling, so that it can have tab order independent from visual stacking Z-Order.)</p> <h2>Other Things To Explore...</h2> <p>Make friends with the Spy++ app (part of the SDK, installs with Visual Studio). If you're going to do anything with HWNDs, managed or unmanaged, it's a real good idea to know how to use this tool: you can point it at any piece of UI on Windows, and see how it's constructed out of a tree of different types of HWNDs. Point it at the VB designer and see what's really happening for yourself. (Click the 'binoculars' icon on the toolbar, then drag the crosshairs the the window you're interested in.)</p> <p>Also take a look at the resource files that the designer spits out. Everything that you can tweak or move or edit in the forms designer corresponds to some item somewhere in one of those resource files. Make a copy of them, tweak some settings, and then file-compare the two sets, and see what's changed. Try changing some things in the files by hand (I think they're nearly all text), reload, and see if the designer picked up your changes.</p> <p><H2>Other Things To Note...</h2> Much of the above is specific to Windows - notably the fact that since we're using Window's own building blocks - HWNDs - we can get Windows itself to do some of the hard work for us: it gives us the facilities to reuse the controls themselves at design time so we don't have to draw mock-ups; to intercept input on other controls so we can make a click into a move or whatever other action we want, or figure out which control is clicked without having to do the location math ourselves. If this was a designer for some other UI framework - say Flash - which doesn't use HWNDs internally, it would likely instead use <i>that</i> framework's own internal facilities to do similar work.</p> <p>Also, it's far easier if you limit the number of controls in the palette to a small finite set, at least at first. If you want to allow any control at all to be dragged in - eg. a 3rd party one, or one you've used in another project; you typically first need some way for that control to be 'registered' so that the designer knows that it's available in the first place. And you may also need some way to discover what icon it uses in the toolbar, what its name is, what properties it supports - and so on. </p> <p>Have fun exploring!</p>
5,266,272
Non-lazy image loading in iOS
<p>I'm trying to load UIImages in a background thread and then display them on the iPad. However, there's a stutter when I set the imageViews' view property to the image. I soon figured out that image loading is lazy on iOS, and found a partial solution in this question:</p> <p><a href="https://stackoverflow.com/questions/1815476/cgimage-uiimage-lazily-loading-on-ui-thread-causes-stutter">CGImage/UIImage lazily loading on UI thread causes stutter</a></p> <p>This actually forces the image to be loaded in the thread, but there's still a stutter when displaying the image.</p> <p>You can find my sample project here: <a href="http://www.jasamer.com/files/SwapTest.zip" rel="nofollow noreferrer">http://www.jasamer.com/files/SwapTest.zip</a> (edit: <a href="http://www.jasamer.com/files/SwapTest-Fixed.zip" rel="nofollow noreferrer">fixed version</a>), check the SwapTestViewController. Try dragging the picture to see the stutter.</p> <p>The test-code I created that stutters is this (the forceLoad method is the one taken from the stack overflow question I posted above):</p> <pre><code>NSArray* imagePaths = [NSArray arrayWithObjects: [[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil], [[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil], nil]; NSOperationQueue* queue = [[NSOperationQueue alloc] init]; [queue addOperationWithBlock: ^(void) { int imageIndex = 0; while (true) { UIImage* image = [[UIImage alloc] initWithContentsOfFile: [imagePaths objectAtIndex: imageIndex]]; imageIndex = (imageIndex+1)%2; [image forceLoad]; //What's missing here? [self performSelectorOnMainThread: @selector(setImage:) withObject: image waitUntilDone: YES]; [image release]; } }]; </code></pre> <p>There are two reasons why I know the stuttering can be avoided: </p> <p>(1) Apple is able to load images without stuttering in the Photos app</p> <p>(2) This code does not cause stutter after placeholder1 and placeholder2 have been displayed once in this modified version of the above code: </p> <pre><code> UIImage* placeholder1 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil]]; [placeholder1 forceLoad]; UIImage* placeholder2 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil]]; [placeholder2 forceLoad]; NSArray* imagePaths = [NSArray arrayWithObjects: [[NSBundle mainBundle] pathForResource: @"a.png" ofType: nil], [[NSBundle mainBundle] pathForResource: @"b.png" ofType: nil], nil]; NSOperationQueue* queue = [[NSOperationQueue alloc] init]; [queue addOperationWithBlock: ^(void) { int imageIndex = 0; while (true) { //The image is not actually used here - just to prove that the background thread isn't causing the stutter UIImage* image = [[UIImage alloc] initWithContentsOfFile: [imagePaths objectAtIndex: imageIndex]]; imageIndex = (imageIndex+1)%2; [image forceLoad]; if (self.imageView.image==placeholder1) { [self performSelectorOnMainThread: @selector(setImage:) withObject: placeholder2 waitUntilDone: YES]; } else { [self performSelectorOnMainThread: @selector(setImage:) withObject: placeholder1 waitUntilDone: YES]; } [image release]; } }]; </code></pre> <p>However, I can't keep all my images in memory.</p> <p>This implies that forceLoad doesn't do the complete job - there's something else going on before the images are actually displayed. Does anyone know what that is, and how I can put that into the background thread?</p> <p>Thanks, Julian</p> <p><strong>Update</strong></p> <p>Used a few of Tommys tips. What I figured out is that it's CGSConvertBGRA8888toRGBA8888 that's taking so much time, so it seems it's a color conversion that's causing the lag. Here's the (inverted) call stack of that method.</p> <pre><code>Running Symbol Name 6609.0ms CGSConvertBGRA8888toRGBA8888 6609.0ms ripl_Mark 6609.0ms ripl_BltImage 6609.0ms RIPLayerBltImage 6609.0ms ripc_RenderImage 6609.0ms ripc_DrawImage 6609.0ms CGContextDelegateDrawImage 6609.0ms CGContextDrawImage 6609.0ms CA::Render::create_image_by_rendering(CGImage*, CGColorSpace*, bool) 6609.0ms CA::Render::create_image(CGImage*, CGColorSpace*, bool) 6609.0ms CA::Render::copy_image(CGImage*, CGColorSpace*, bool) 6609.0ms CA::Render::prepare_image(CGImage*, CGColorSpace*, bool) 6609.0ms CALayerPrepareCommit_(CALayer*, CA::Transaction*) 6609.0ms CALayerPrepareCommit_(CALayer*, CA::Transaction*) 6609.0ms CALayerPrepareCommit_(CALayer*, CA::Transaction*) 6609.0ms CALayerPrepareCommit_(CALayer*, CA::Transaction*) 6609.0ms CALayerPrepareCommit 6609.0ms CA::Context::commit_transaction(CA::Transaction*) 6609.0ms CA::Transaction::commit() 6609.0ms CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) 6609.0ms __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ 6609.0ms __CFRunLoopDoObservers 6609.0ms __CFRunLoopRun 6609.0ms CFRunLoopRunSpecific 6609.0ms CFRunLoopRunInMode 6609.0ms GSEventRunModal 6609.0ms GSEventRun 6609.0ms -[UIApplication _run] 6609.0ms UIApplicationMain 6609.0ms main </code></pre> <p>The last bit-mask changes he proposed didn't change anything, sadly.</p>
5,266,551
3
2
null
2011-03-10 21:43:14.617 UTC
47
2014-04-17 06:28:02.413 UTC
2017-05-23 12:02:30.897 UTC
null
-1
null
654,352
null
1
39
objective-c|ios
17,908
<p>UIKit may be used on the main thread only. Your code is therefore technically invalid, since you use UIImage from a thread other than the main thread. You should use CoreGraphics alone to load (and non-lazily decode) graphics on a background thread, post the CGImageRef to the main thread and turn it into a UIImage there. It may appear to work (albeit with the stutter you don't want) in your current implementation, but it isn't guaranteed to. There seems to be a lot of superstition and bad practice advocated around this area, so it's not surprising you've managed to find some bad advice...</p> <p>Recommended to run on a background thread:</p> <pre><code>// get a data provider referencing the relevant file CGDataProviderRef dataProvider = CGDataProviderCreateWithFilename(filename); // use the data provider to get a CGImage; release the data provider CGImageRef image = CGImageCreateWithPNGDataProvider(dataProvider, NULL, NO, kCGRenderingIntentDefault); CGDataProviderRelease(dataProvider); // make a bitmap context of a suitable size to draw to, forcing decode size_t width = CGImageGetWidth(image); size_t height = CGImageGetHeight(image); unsigned char *imageBuffer = (unsigned char *)malloc(width*height*4); CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef imageContext = CGBitmapContextCreate(imageBuffer, width, height, 8, width*4, colourSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little); CGColorSpaceRelease(colourSpace); // draw the image to the context, release it CGContextDrawImage(imageContext, CGRectMake(0, 0, width, height), image); CGImageRelease(image); // now get an image ref from the context CGImageRef outputImage = CGBitmapContextCreateImage(imageContext); // post that off to the main thread, where you might do something like // [UIImage imageWithCGImage:outputImage] [self performSelectorOnMainThread:@selector(haveThisImage:) withObject:[NSValue valueWithPointer:outputImage] waitUntilDone:YES]; // clean up CGImageRelease(outputImage); CGContextRelease(imageContext); free(imageBuffer); </code></pre> <p>There's no need to do the malloc/free if you're on iOS 4 or later, you can just pass NULL as the relevant parameter of CGBitmapContextCreate, and let CoreGraphics sort out its own storage.</p> <p>This differs from the solution you post to because it:</p> <ol> <li>creates a CGImage from a PNG data source — lazy loading applies, so this isn't necessarily a fully loaded and decompressed image</li> <li>creates a bitmap context of the same size as the PNG</li> <li>draws the CGImage from the PNG data source onto the bitmap context — this should force full loading and decompression since the actual colour values have to be put somewhere we could access them from a C array. This step is as far as the forceLoad you link to goes.</li> <li>converts the bitmap context into an image</li> <li>posts that image off to the main thread, presumably to become a UIImage</li> </ol> <p>So there's no continuity of object between the thing loaded and the thing displayed; pixel data goes through a C array (so, no opportunity for hidden shenanigans) and only if it was put into the array correctly is it possible to make the final image.</p>
5,475,209
Get class methods using reflection
<p>How can I get all the public methods of class using reflection when class name is passed as a string as shown in the below method. ?</p> <pre><code> private MethodInfo[] GetObjectMethods(string selectedObjClass) { MethodInfo[] methodInfos; Assembly assembly = Assembly.GetAssembly(typeof(sampleAdapater)); Type _type = assembly.GetType("SampleSolution.Data.MyData." + selectedObjClass); ///get all the methods for the classname passed as string return methodInfos; } </code></pre> <p>Please help. Thanks</p>
5,475,262
3
0
null
2011-03-29 15:42:42.757 UTC
7
2017-02-25 21:13:50.32 UTC
2011-03-29 15:43:39.477 UTC
null
329,637
null
461,535
null
1
48
c#|reflection
63,067
<pre><code>MethodInfo[] methodInfos = Type.GetType(selectedObjcClass) .GetMethods(BindingFlags.Public | BindingFlags.Instance); </code></pre>
25,820,698
How do I import an .accdb file into Python and use the data?
<p>I am trying to figure out a way to create a program that allows me to find the best combination of data based on several different factors. </p> <p>I have a Microsoft Access file with creature data in it. Attack, Defense, Health, Required Battle skill to use and several other bits of info.</p> <p>I am trying to import this .accdb (Access 2013) file and be able to access the stored data. </p> <p>I am going to try to make a program that scans all the data and runs all possible combinations (sets of 5 creatures) to find the strongest combination of creatures for different required battle skills (ex: 100 battle skill would use creature 1, 2, 3, 4 and 5 where 125 battle skill would use creature 3, 5, 6, 8, and 10)</p> <p>The main thing I need help with first is being able to import the data base for easy access so I do not have to recreate the data in python and so I can use the same program for new access databases in the future. </p> <p>I have installed <a href="https://code.google.com/p/pypyodbc/" rel="noreferrer">https://code.google.com/p/pypyodbc/</a> but can't seem to figure out how to get it to load an existing file.</p> <h2>Edit</h2> <p>I tried to use the code from Gord's answer, modified to fit my info. </p> <pre class="lang-python prettyprint-override"><code># -*- coding: utf-8 -*- import pypyodbc pypyodbc.lowercase = False conn = pypyodbc.connect( r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" + r"Dbq=C:\Users\Ju\Desktop\Dark Summoner.accdb;") cur = conn.cursor() cur.execute("SELECT Number, Name, Atk, Def, HP, BP, Species, Special FROM Impulse AA+"); while True: row = cur.fetchone() if row is None: break print (u"Creature with Number {1} is {1} ({2})".format( row.get("CreatureID"), row.get("Name_EN"), row.get("Name_JP"))) cur.close() conn.close() </code></pre> <p>Was getting an error with the print line so added () around it. </p> <p>I am now getting this error, similar to what I was getting in the past. </p> <pre class="lang-python prettyprint-override"><code>Traceback (most recent call last): File "C:\Users\Ju\Desktop\Test.py", line 6, in &lt;module&gt; r"Dbq=C:\Users\Ju\Desktop\Dark Summoner.accdb;") File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 2434, in __init__ self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly) File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 2483, in connect check_success(self, ret) File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 988, in check_success ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi) File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 964, in ctrl_err raise Error(state,err_text) pypyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified') </code></pre> <p>I looked through the pypyodbc.py file at the lines mentioned in the error code, but could not figure it out. I tried to remove the "r" from the beginning of r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" and tried a space between r and "Driver because I did not know what it was for, But got a different error. </p> <h2>Edit</h2> <p>I checked my files as suggested. I believe I am running 64bit. I checked both the 32 bit and 64 bit versions. I have Microsoft Access Driver (*.mdb, *.accdb) in the 64 bit but not in the 32 bit. I am using the 2013 version of Microsoft Visual Studios.</p> <h2>Edit</h2> <p>Working now!</p> <p>My final working code in case it helps anyone in the future. </p> <pre class="lang-python prettyprint-override"><code># -*- coding: utf-8 -*- import pypyodbc pypyodbc.lowercase = False conn = pypyodbc.connect( r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" + r"Dbq=C:\Users\Ju\Desktop\Dark Summoner.accdb;") cur = conn.cursor() cur.execute("SELECT Number, ID, Name, Atk, Def, HP, BP, Species, Special FROM Impulse_AA"); while True: row = cur.fetchone() if row is None: break print (u"ID: {1} {2} Atk:{3} Def:{4} HP:{5} BP:{6} Species: {7} {8}".format( row.get("Number"), row.get("ID"), row.get("Name"), row.get("Atk"), row.get("Def"), row.get("HP"), row.get("BP"), row.get("Species"), row.get("Special") )) cur.close() conn.close() </code></pre>
25,822,910
1
3
null
2014-09-13 06:58:04.15 UTC
9
2014-09-22 23:32:54.927 UTC
2014-09-22 23:32:54.927 UTC
null
4,037,096
null
4,037,096
null
1
15
python|database|ms-access|ms-access-2013|pypyodbc
39,342
<p>Say you have a database file named "Database1.accdb" with a table named "Creatures" containing the following data:</p> <pre class="lang-none prettyprint-override"><code>CreatureID Name_EN Name_JP ---------- -------- ------- 1 Godzilla ゴジラ 2 Mothra モスラ </code></pre> <p>A minimalist Python script to read the data via pypyodbc on a Windows machine would look something like this:</p> <pre class="lang-python prettyprint-override"><code># -*- coding: utf-8 -*- import pypyodbc pypyodbc.lowercase = False conn = pypyodbc.connect( r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" + r"Dbq=C:\Users\Public\Database1.accdb;") cur = conn.cursor() cur.execute("SELECT CreatureID, Name_EN, Name_JP FROM Creatures"); while True: row = cur.fetchone() if row is None: break print(u"Creature with ID {0} is {1} ({2})".format( row.get("CreatureID"), row.get("Name_EN"), row.get("Name_JP"))) cur.close() conn.close() </code></pre> <p>The resulting output is</p> <pre class="lang-none prettyprint-override"><code>Creature with ID 1 is Godzilla (ゴジラ) Creature with ID 2 is Mothra (モスラ) </code></pre> <p><strong>Edit</strong></p> <p>Note that to use the "Microsoft Access Driver (*.mdb, *.accdb)" driver you need to have the Access Database Engine (a.k.a "ACE") installed on your machine. You can check whether you have 32-bit or 64-bit Python by running the following script:</p> <pre class="lang-python prettyprint-override"><code>import struct print("running as {0}-bit".format(struct.calcsize("P") * 8)) </code></pre> <p>Armed with that information you can download and install the matching (32-bit or 64-bit) version of the Access Database Engine from here</p> <p><a href="http://www.microsoft.com/en-US/download/details.aspx?id=13255" rel="noreferrer">Microsoft Access Database Engine 2010 Redistributable</a></p>
25,446,628
AJAX jQuery refresh div every 5 seconds
<p>I got this code from a website which I have modified to my needs:</p> <pre><code>&lt;head&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;div id="links"&gt; &lt;/div&gt; &lt;script language="javascript" type="text/javascript"&gt; var timeout = setTimeout(reloadChat, 5000); function reloadChat () { $('#links').load('test.php #links',function () { $(this).unwrap(); timeout = setTimeout(reloadChat, 5000); }); } &lt;/script&gt; </code></pre> <p>In test.php:</p> <pre><code>&lt;?php echo 'test'; ?&gt; </code></pre> <p>So I want test.php to be called every 5 seconds in links div. How can I do this right?</p>
25,446,696
5
4
null
2014-08-22 12:04:33.327 UTC
11
2018-06-10 10:18:22.45 UTC
2014-08-22 12:08:39.713 UTC
null
3,838,972
null
3,838,972
null
1
28
javascript|php|jquery|ajax
204,602
<p>Try this out.</p> <pre><code>function loadlink(){ $('#links').load('test.php',function () { $(this).unwrap(); }); } loadlink(); // This will run on page load setInterval(function(){ loadlink() // this will run after every 5 seconds }, 5000); </code></pre> <p>Hope this helps.</p>
9,087,116
Which Ruby on Rails is compatible with which Ruby version?
<p>I have an old 2.1.1 Ruby on Rails application, with the system upgraded to use Ruby 1.8.7. It originally used 1.8.5 or so.</p> <p>I want to upgrade it to Ruby 1.9.x for performance reasons, and possibly to a newer Ruby on Rails as well.</p> <p>I cannot find any easy chart of compatibility between different Ruby versions and Ruby on Rails versions.</p> <p>Will 2.1.1 work with Ruby 1.9.x? If not, how far do I need to upgrade it first, and what kind of issues am I likely to encounter? My application does complicated things to database layer, but the rest is fairly straightforward.</p>
51,810,150
11
3
null
2012-01-31 21:19:15.457 UTC
34
2022-03-30 17:04:41.537 UTC
2012-01-31 22:27:43.173 UTC
null
128,421
null
52,751
null
1
98
ruby-on-rails|ruby
63,921
<p>This is an old question, but the fact that rails is tested against a version of ruby is a good indication that it should work on that version of ruby.</p> <p>Since 9th April 2019, stable branches of Rails use Buildkite for automated testing, and the list of tested ruby versions, by rails branch, is:</p> <p>Rails 6.1</p> <ul> <li><code>&gt;= 2.5.0</code></li> </ul> <p>Rails 6.0</p> <ul> <li><code>&gt;= 2.5.0</code></li> </ul> <p>Rails 5.2</p> <ul> <li><code>&gt;= 2.2.2</code></li> <li><code>&lt; 2.7</code> (see <a href="https://github.com/rails/rails/issues/38426" rel="noreferrer">https://github.com/rails/rails/issues/38426</a>)</li> </ul> <p>Rails 5.1</p> <ul> <li><code>&gt;= 2.2.2</code></li> </ul> <p>Rails 5.0</p> <ul> <li><code>&gt;= 2.2.2</code></li> </ul> <p>Rails 4.2</p> <ul> <li><code>&gt;= 1.9.3</code></li> </ul> <p>Rails 4.1</p> <ul> <li><code>&gt;= 1.9.3</code></li> </ul> <p>Prior to 9th April 2019, stable branches of Rails since 3.0 use travis-ci for automated testing, and the list of tested ruby versions, by rails branch, is:</p> <p>Rails 3.0</p> <ul> <li>1.8.7</li> <li>1.9.2</li> <li>1.9.3</li> </ul> <p>Rails 3.1</p> <ul> <li>1.8.7</li> <li>1.9.2</li> <li>1.9.3</li> </ul> <p>Rails 3.2</p> <ul> <li>1.8.7</li> <li>1.9.2</li> <li>1.9.3</li> <li>2.0.0</li> <li>2.1.8</li> <li>2.2.6</li> <li>2.3.3</li> </ul> <p>Rails 4.0</p> <ul> <li>1.9.3</li> <li>2.0.0</li> <li>2.1</li> <li>2.2</li> </ul> <p>Rails 4.1</p> <ul> <li>1.9.3</li> <li>2.0.0</li> <li>2.1</li> <li>2.2.4</li> <li>2.3.0</li> </ul> <p>Rails 4.2</p> <ul> <li>1.9.3</li> <li>2.0.0-p648</li> <li>2.1.10</li> <li>2.2.10</li> <li>2.3.8</li> <li>2.4.5</li> </ul> <p>Rails 5.0</p> <ul> <li>2.2.10</li> <li>2.3.8</li> <li>2.4.5</li> </ul> <p>Rails 5.1</p> <ul> <li>2.2.10</li> <li>2.3.7</li> <li>2.4.4</li> <li>2.5.1</li> </ul> <p>Rails 5.2</p> <ul> <li>2.2.10</li> <li>2.3.7</li> <li>2.4.4</li> <li>2.5.1</li> </ul> <p>Rails 6.0</p> <ul> <li>2.5.3</li> <li>2.6.0</li> </ul> <p>(From <a href="https://www.hmallett.co.uk/2018/08/ruby-and-ruby-on-rails-version-compatibility/" rel="noreferrer">https://www.hmallett.co.uk/2018/08/ruby-and-ruby-on-rails-version-compatibility/</a>)</p>
18,358,980
Getting radio button value by ajax
<p>I want to get radio button values and send them through AJAX to PHP.</p> <p>My AJAX is running but is currently inserting a <code>0</code> in each row, so it's not picking up the value from the radio button. Any help would be appreciated.</p> <pre class="lang-js prettyprint-override"><code>$("#save_privacy").submit(function() { var message_pri = $("#message_pri").val(); var follow_pri = $("#follow_pri").val(); var post_pri = $("#post_pri").val(); var check7 = $("#check7").val(); var s = { "message_pri": message_pri, "follow_pri": follow_pri, "post_pri": post_pri, "check": check7 } $.ajax({ url: 'edit_check.php', type: 'POST', data: s, beforeSend: function() { $(".privacy_info").html("&lt;img src=\"style/img/ajax/load2.gif\" alt=\"Loading ....\" /&gt;"); }, success: function(data) { $(".privacy_info").html(data); } }); return false; }); </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;form id="save_privacy"&gt; &lt;table align="center" width="70%" cellpadding="0" cellspacing="0" border="0"&gt; &lt;tr&gt; &lt;td style="padding: 5px;"&gt; &lt;b&gt;Message Buttun: &lt;/b&gt; &lt;/td&gt; &lt;td style="padding: 5px;"&gt; &lt;input type="radio" id="message_pri" name="message_pri" value="1" /&gt; ON &lt;input type="radio" id="message_pri" name="message_pri" value="2" /&gt; OFF &lt;input type="radio" id="message_pri" name="message_pri" value="3" /&gt; FOLLOWERS &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="padding: 5px;"&gt; &lt;b&gt;Follow Buttun: &lt;/b&gt; &lt;/td&gt; &lt;td style="padding: 5px;"&gt; &lt;input type="radio" id="follow_pri" name="follow_pri" value="1" /&gt; ON &lt;input type="radio" id="follow_pri" name="follow_pri" value="2" /&gt; OFF &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="padding: 5px;"&gt; &lt;b&gt;Who Can Post On Your Profile: &lt;/b&gt; &lt;/td&gt; &lt;td style="padding: 5px;"&gt; &lt;input type="radio" id="post_pri" name="post_pri" value="1" /&gt; Evry one &lt;input type="radio" id="post_pri" name="post_pri" value="2" /&gt; Followers &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2" style="padding: 5px;"&gt; &lt;input type="hidden" id="check7" value="save_privacy" name="check7" /&gt; &lt;input class="small color blue button" type="submit" value="Save" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div class="privacy_info"&gt;&lt;/div&gt; &lt;/form&gt; </code></pre>
18,359,059
4
1
null
2013-08-21 13:38:03.22 UTC
3
2018-04-26 10:28:01.467 UTC
2017-10-26 12:45:50.56 UTC
null
519,413
null
2,623,520
null
1
8
php|jquery|ajax
64,218
<p>Firstly you have a lot of duplicated <code>id</code> attributes, which is incorrect. Use classes instead, then use the <code>:checked</code> selector to get the specific instance of the radio which was selected.</p> <p>Try this:</p> <pre><code>&lt;input type="radio" class="message_pri" name="message_pri" value="1" /&gt; ON &lt;input type="radio" class="message_pri" name="message_pri" value="2" /&gt; OFF &lt;input type="radio" class="message_pri" name="message_pri" value="3" /&gt; FOLLOWERS </code></pre> <pre class="lang-js prettyprint-override"><code>var message_pri = $(".message_pri:checked").val(); </code></pre> <p>And so on for your other <code>radio</code> inputs.</p>
18,223,931
How can a dead thread be restarted?
<p>What are all the different possibilities to bring the <strong>dead thread</strong> back to <strong>runnable state</strong>.</p>
18,223,979
7
7
null
2013-08-14 05:36:53.383 UTC
10
2017-06-27 20:23:04.43 UTC
null
null
null
null
2,628,956
null
1
19
java|multithreading
59,144
<p><img src="https://i.stack.imgur.com/sVreJ.jpg" alt="Thread lifecycle image"></p> <p>If you look at the Thread Life Cycle Image, there is no way you can go back to new position once your thread has terminated.</p> <p>So <strong>there is no way to bring back the dead thread to runnable state</strong>,instead you should create a new Thread instance.</p>
18,247,289
What is the difference between querySelectorAll and getElementsByTagName?
<p>I was wondering about two different syntax of selecting element in JavaScript.</p> <p>suppose if I want to select all divs from current document then:</p> <pre><code>var divs = document.getElementsByTagName(&quot;div&quot;); console.log(&quot;There are &quot;+divs.length+&quot; Divs in Document !&quot;); </code></pre> <p>Will work fine. But there is also another way of doing so, like:</p> <pre><code>var divs = document.querySelectorAll(&quot;div&quot;); console.log(&quot;There are &quot;+divs.length+&quot; Divs in Document !&quot;); </code></pre> <p>When both of them works in the same way. What's the difference between them ?</p> <li>Which one is faster?</li> <li>Why?</li> <li>How both works?</li> <p>Thanks in advance. I've seen the questions like this but they didn't satisfied the need.</p>
18,247,327
8
3
null
2013-08-15 06:16:38.783 UTC
13
2022-04-18 11:48:06.017 UTC
2021-06-06 06:54:37.497 UTC
null
2,010,838
null
2,010,838
null
1
28
javascript
23,417
<h1>Selections</h1> <p><code>getElementsByTagName</code> only selects elements based on their tag name. <code>querySelectorAll</code> can use <a href="http://www.w3.org/TR/css3-selectors/" rel="noreferrer">any selector</a> which gives it much more flexibility and power.</p> <h1>Return value</h1> <ul> <li>gEBTN returns a <strong>live</strong> node list.</li> <li>qSA returns a <strong>static</strong> node list.</li> </ul> <p>Live node lists can be useful (you can query once, store the value, and have it update as the DOM changes) but are responsible for a lot of confusion such as the example <a href="https://stackoverflow.com/questions/28316289/javascript-remove-not-removing-all-elements">in this question</a>.</p> <p>Usually a static list is easier to deal with.</p> <h1>Support</h1> <p>See caniuse for <a href="https://caniuse.com/mdn-api_element_getelementsbytagname" rel="noreferrer">gEBTN</a> and <a href="https://caniuse.com/queryselector" rel="noreferrer">qSA</a>.</p> <p>gEBTN has more support, but qSA has support in all browsers that are relevant for most use cases today.</p> <h1>Performance</h1> <p><a href="https://stackify.com/premature-optimization-evil/" rel="noreferrer">You probably shouldn't care</a>. These functions are unlikely to be a bottleneck in your code.</p> <p>I've seen conflicting reports about which is faster. It likely varies between browsers anyway.</p>
18,362,260
A SQL Query to select a string between two known strings
<p>I need a SQL query to get the value between two known strings (the returned value should start and end with these two strings).</p> <p>An example.</p> <p>"All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought."</p> <p>In this case the known strings are "the dog" and "immediately". So my query should return "the dog had been very bad and required harsh punishment immediately"</p> <p>I've come up with this so far but to no avail:</p> <pre><code>SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text), CHARINDEX('immediately', @Text)) </code></pre> <p>@Text being the variable containing the main string.</p> <p>Can someone please help me with where I'm going wrong?</p>
18,363,002
16
2
null
2013-08-21 15:57:41.94 UTC
19
2022-05-13 12:40:41.387 UTC
2013-08-21 16:18:35.067 UTC
null
1,162,620
null
1,338,949
null
1
51
sql|sql-server|substring
290,126
<p>The problem is that the second part of your substring argument is including the first index. You need to subtract the first index from your second index to make this work.</p> <pre><code>SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text) , CHARINDEX('immediately',@text) - CHARINDEX('the dog', @Text) + Len('immediately')) </code></pre>
15,415,076
SQL.js in javascript
<p>I want to store data in a SQLite database directly from a javascript script. I found this <a href="https://github.com/kripken/sql.js" rel="noreferrer">SQL.js</a> library that is a port for javascript. However, apparently it's only available for coffeescript. Does anyone know how to use it in javascript? Other ideas about how to store data in SQLite DB are welcomed too.</p>
23,874,858
2
3
null
2013-03-14 16:37:11.803 UTC
8
2020-10-12 08:40:09.333 UTC
2013-03-14 16:53:36.487 UTC
null
1,336,939
null
1,336,939
null
1
9
javascript|sqlite
23,011
<h2>Update</h2> <p>sql.js now has its own github organisation, where both the original author and I are members: <a href="https://github.com/sql-js/sql.js/" rel="nofollow noreferrer">https://github.com/sql-js/sql.js/</a> .</p> <p>The API itself itself is now written in javascript.</p> <h2>Original answer</h2> <p>I am the author of this port of the latest version of sqlite to javascript: <a href="https://github.com/lovasoa/sql.js" rel="nofollow noreferrer">https://github.com/lovasoa/sql.js</a></p> <p>It is based on the one you mentioned (<a href="https://github.com/kripken/sql.js" rel="nofollow noreferrer">https://github.com/kripken/sql.js</a>), but includes many improvements, including a full documentation: <a href="http://lovasoa.github.io/sql.js/documentation/" rel="nofollow noreferrer">http://lovasoa.github.io/sql.js/documentation/</a></p> <p>Here is an example of how to use this version of <code>sql.js</code></p> <pre><code>&lt;script src='js/sql.js'&gt;&lt;/script&gt; &lt;script&gt; //Create the database var db = new SQL.Database(); // Run a query without reading the results db.run(&quot;CREATE TABLE test (col1, col2);&quot;); // Insert two rows: (1,111) and (2,222) db.run(&quot;INSERT INTO test VALUES (?,?), (?,?)&quot;, [1,111,2,222]); // Prepare a statement var stmt = db.prepare(&quot;SELECT * FROM test WHERE col1 BETWEEN $start AND $end&quot;); stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111} // Bind new values stmt.bind({$start:1, $end:2}); while(stmt.step()) { // var row = stmt.getAsObject(); // [...] do something with the row of result } &lt;/script&gt; </code></pre>
14,958,606
CSS/HTML - Horizontal list - Remove this mystery gap between list items?
<p>I am having trouble with a menu bar that I am making. It seems that there is a gap between the menu items and for the life of me I do not understand what the reason for this is.</p> <p>As a description to the screenshot below, the first link (home) is the current page and it is highlighted. The second link (page1) is a hover effect while my cursor is over this item. You will notice that there is a gap (what on earth is causing this?!) between these two items that shows the background color of div that contains the menu.</p> <p>It may be worthwhile to note that I am using the latest version of firefox.</p> <p>Here is a screenshot of my problem:</p> <p><img src="https://i.stack.imgur.com/0yhUZ.jpg" alt="Mystery Gap"></p> <p>Here is the html for the list:</p> <pre><code>&lt;div class="nav"&gt; &lt;ul&gt; &lt;li class="selectedPage"&gt;&lt;a href="#"&gt;HOME&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;PAGE1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;PAGE2&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!-- end .nav --&gt;&lt;/div&gt; </code></pre> <p>And here is the css:</p> <pre><code>div.nav { width: 750px; background: #52b5f0; /* Old browsers */ /* IE9 SVG, needs conditional override of 'filter' to 'none' */ background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSI1JSIgc3RvcC1jb2xvcj0iIzUyYjVmMCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjQ5JSIgc3RvcC1jb2xvcj0iIzM2OTlkMCIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9Ijk1JSIgc3RvcC1jb2xvcj0iIzE5NjM4YSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgPC9saW5lYXJHcmFkaWVudD4KICA8cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMSIgaGVpZ2h0PSIxIiBmaWxsPSJ1cmwoI2dyYWQtdWNnZy1nZW5lcmF0ZWQpIiAvPgo8L3N2Zz4=); background: -moz-linear-gradient(top, #52b5f0 5%, #3699d0 49%, #19638a 95%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(5%,#52b5f0), color-stop(49%,#3699d0), color-stop(95%,#19638a)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #52b5f0 5%,#3699d0 49%,#19638a 95%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #52b5f0 5%,#3699d0 49%,#19638a 95%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #52b5f0 5%,#3699d0 49%,#19638a 95%); /* IE10+ */ background: linear-gradient(to bottom, #52b5f0 5%,#3699d0 49%,#19638a 95%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#52b5f0', endColorstr='#19638a',GradientType=0 ); /* IE6-8 */ } div.nav ul { list-style: none; /* this removes the list marker */ } div.nav li { display: inline-block; } div.nav li.selectedPage { background: #41ff5f; } div.nav li.selectedPage a { color: #10653b; } div.nav a, div.nav a:visited { padding: 5px; display: block; width: 120px; text-decoration: none; color: #FFFFFF; font-weight: bold; text-align: center; } div.nav a:hover, div.nav a:active, div.nav a:focus { background: #41ff5f; color: #10653b; } </code></pre> <p>EDIT: </p> <p>I do have this in place earlier in the css:</p> <pre><code>ul, li { padding: 0; margin: 0; } </code></pre> <hr> <p>JsFiddle Link:</p> <p><a href="http://jsfiddle.net/Gbg7J/" rel="nofollow noreferrer">http://jsfiddle.net/Gbg7J/</a></p>
14,958,751
1
5
null
2013-02-19 13:22:21.967 UTC
10
2018-09-23 18:59:59.757 UTC
2018-09-23 18:59:59.757 UTC
null
1,033,581
null
2,110,294
null
1
18
html|css
17,740
<p>The gap is caused by the tabs and line feeds separating your list items; inline block elements (or any element that participates within the <a href="http://www.w3.org/TR/CSS2/visuren.html#inline-formatting" rel="nofollow noreferrer">inline formatting context</a>) are sensitive to their structure in your HTML.</p> <p>You can either <a href="http://jsfiddle.net/Gbg7J/5/" rel="nofollow noreferrer">remove the spaces completely</a>:</p> <pre><code> &lt;ul&gt; &lt;li class="selectedPage"&gt;&lt;a href="#"&gt;HOME&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#"&gt;PAGE1&lt;/a&gt;&lt;/li&lt;li&gt;&lt;a href="#"&gt;PAGE2&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Use comments:</p> <pre><code>&lt;div class="nav"&gt; &lt;ul&gt; &lt;li class="selectedPage"&gt;&lt;a href="#"&gt;HOME&lt;/a&gt;&lt;/li&gt;&lt;!-- --&gt;&lt;li&gt;&lt;a href="#"&gt;PAGE1&lt;/a&gt;&lt;/li&gt;&lt;!-- --&gt;&lt;li&gt;&lt;a href="#"&gt;PAGE2&lt;/a&gt;&lt;/li&gt;&lt;!-- --&gt;&lt;/ul&gt; &lt;!-- end .nav --&gt;&lt;/div&gt; </code></pre> <p>Leave the HTML alone and use <code>float</code> <a href="http://jsfiddle.net/8pG27/1/" rel="nofollow noreferrer">instead</a> (and clear the container):</p> <pre><code>.nav ul li { float: left; /*display: inline-block;*/ } .nav ul { overflow: hidden; } </code></pre> <p>Or set <code>font-size: 0;</code> on the parent and <a href="http://jsfiddle.net/8pG27/3/" rel="nofollow noreferrer">then reset it</a> on the <code>li</code></p> <pre><code>.nav ul { font-size: 0; } .nav li { display: inline-block; font-size: 16px; } </code></pre> <hr> <p><sup>Also, take a look at both: <a href="https://stackoverflow.com/questions/5078239/how-to-remove-the-space-between-inline-block-elements/5078297#5078297">How to remove the space between inline-block elements?</a> &amp; <a href="http://css-tricks.com/fighting-the-space-between-inline-block-elements/" rel="nofollow noreferrer">http://css-tricks.com/fighting-the-space-between-inline-block-elements/</a></sup></p>
15,470,452
Is it possible to play video using Avplayer in Background?
<p>I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video? </p> <p>I have search about background task &amp; background thread ,IOS only support music in background (Not video) <a href="http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html">http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html</a></p> <p>here is some discussion about play video in background </p> <p>1) <a href="https://discussions.apple.com/thread/2799090?start=0&amp;tstart=0">https://discussions.apple.com/thread/2799090?start=0&amp;tstart=0</a></p> <p>2) <a href="http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html">http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html</a> </p> <p>But there are many apps in AppStore, that play video in Background like </p> <p>Swift Player : <a href="https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&amp;ign-mpt=uo%3D2">https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&amp;ign-mpt=uo%3D2</a></p> <p>SpeedUpTV : <a href="https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8">https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8</a></p>
15,564,454
8
1
null
2013-03-18 05:47:18.257 UTC
13
2017-10-01 01:21:51.537 UTC
null
null
null
null
1,647,942
null
1
18
iphone|ios|ios5|video|avplayer
13,660
<p>This method supports all the possibilities:</p> <ul> <li>Screen locked by the user;</li> <li>List item</li> <li>Home button pressed;</li> </ul> <p>As long as you have an instance of AVPlayer running iOS prevents auto lock of the device.</p> <p>First you need to configure the application to support audio background from the Info.plist file adding in the UIBackgroundModes array the audio element.</p> <p>Then put in your AppDelegate.m into</p> <p><strong>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:</strong></p> <p>these methods</p> <pre><code>[[AVAudioSession sharedInstance] setDelegate: self]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; </code></pre> <p>and <strong>#import &lt; AVFoundation/AVFoundation.h ></strong></p> <p>Then in your view controller that controls AVPlayer</p> <pre><code>-(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder]; } </code></pre> <p>and</p> <pre><code>- (void)viewWillDisappear:(BOOL)animated { [mPlayer pause]; [super viewWillDisappear:animated]; [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; [self resignFirstResponder]; } </code></pre> <p>then respond to the</p> <pre><code> - (void)remoteControlReceivedWithEvent:(UIEvent *)event { switch (event.subtype) { case UIEventSubtypeRemoteControlTogglePlayPause: if([mPlayer rate] == 0){ [mPlayer play]; } else { [mPlayer pause]; } break; case UIEventSubtypeRemoteControlPlay: [mPlayer play]; break; case UIEventSubtypeRemoteControlPause: [mPlayer pause]; break; default: break; } } </code></pre> <p>Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out).</p> <p>When you control the reproduction of the video (I have play methods) set</p> <pre><code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; </code></pre> <p>and the corresponding method to be invoked that will launch a timer and resume the reproduction.</p> <pre><code>- (void)applicationDidEnterBackground:(NSNotification *)notification { [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01]; } </code></pre> <p>Its works for me to play video in Backgorund. Thanks to all.</p>
15,063,636
How to make a vertical scrolling view on iOS?
<p>Can someone please guide me to a tutorial , on how to implement a vertical scrolling view on my iOS app?</p> <p>I can't believe that the last 2 days , I can't find a single working example on just a vertical scrolling view. All the tutorials are about horizontal scrolling, zooming etc etc.</p> <p>What I am looking for would be something like this tutorial <a href="http://www.edumobile.org/iphone/iphone-programming-tutorials/scrollview-example-in-iphone-2/">http://www.edumobile.org/iphone/iphone-programming-tutorials/scrollview-example-in-iphone-2/</a>, which shows how to make a uiscrollView and add objects to it, from the Builder and not programmatically. The only flaw I found was , that when trying to add a map down in the scrolling area, the map would appear up and not in the position I placed it. Maybe any ideas on that too?</p> <p>Anything in mind?</p>
15,064,338
4
3
null
2013-02-25 09:20:01.767 UTC
7
2014-09-17 07:07:39.427 UTC
2014-08-23 16:36:36.737 UTC
user1498477
1,450
user1498477
null
null
1
19
ios|uiscrollview|vertical-scrolling
56,135
<p>So you want to create a scroll view in xib. </p> <ol> <li>Add a scroll view to the nib file </li> <li><p>set its size to to whatever you want </p> <p><img src="https://i.stack.imgur.com/hbQ5M.png" alt="enter image description here"></p></li> <li><p>Add your controls (Buttons,labels..)</p> <p><img src="https://i.stack.imgur.com/fmCIy.png" alt="enter image description here"></p></li> <li><p>Add it as a sub view of main view </p> <p><img src="https://i.stack.imgur.com/nVldj.png" alt="enter image description here"> </p></li> <li><p>Finally create a property of scroll view and in <code>viewDidLoad</code> set the content size of the scroll view </p> <pre><code> self.scrollView.contentSize =CGSizeMake(320, 700); </code></pre></li> </ol>
15,080,078
'NoneType' object has no attribute 'group'
<p>Can somebody help me with this code? I'm trying to make a python script that will play videos and I found this file that download's Youtube videos. I am not entirely sure what is going on and I can't figure out this error.</p> <p>Error:</p> <pre class="lang-python prettyprint-override"><code>AttributeError: 'NoneType' object has no attribute 'group' </code></pre> <p>Traceback:</p> <pre class="lang-python prettyprint-override"><code>Traceback (most recent call last): File "youtube.py", line 67, in &lt;module&gt; videoUrl = getVideoUrl(content) File "youtube.py", line 11, in getVideoUrl grps = fmtre.group(0).split('&amp;amp;') </code></pre> <p>Code snippet:</p> <p>(lines 66-71)</p> <pre class="lang-python prettyprint-override"><code>content = resp.read() videoUrl = getVideoUrl(content) if videoUrl is not None: print('Video URL cannot be found') exit(1) </code></pre> <p>(lines 9-17)</p> <pre class="lang-python prettyprint-override"><code>def getVideoUrl(content): fmtre = re.search('(?&lt;=fmt_url_map=).*', content) grps = fmtre.group(0).split('&amp;amp;') vurls = urllib2.unquote(grps[0]) videoUrl = None for vurl in vurls.split('|'): if vurl.find('itag=5') &gt; 0: return vurl return None </code></pre>
15,080,093
4
2
null
2013-02-26 02:00:23.027 UTC
5
2020-05-13 13:46:59.883 UTC
null
null
null
null
1,691,556
null
1
26
python|youtube|download
137,764
<p>The error is in your line 11, your <code>re.search</code> is returning no results, ie <code>None</code>, and then you're trying to call <code>fmtre.group</code> but <code>fmtre</code> is <code>None</code>, hence the <code>AttributeError</code>.</p> <p>You could try:</p> <pre><code>def getVideoUrl(content): fmtre = re.search('(?&lt;=fmt_url_map=).*', content) if fmtre is None: return None grps = fmtre.group(0).split('&amp;amp;') vurls = urllib2.unquote(grps[0]) videoUrl = None for vurl in vurls.split('|'): if vurl.find('itag=5') &gt; 0: return vurl return None </code></pre>
14,957,419
Select2 doesn't show selected value
<p>Select2 loads all items from my list successful, the issue I found when try to select a specific value when page loads. Example:</p> <p>:: put select2 in a specific html element, no value is selected even all items are loaded.</p> <pre><code>$('#my_id').select2(); </code></pre> <p>:: When the page is loaded I'm trying to show a specific item selected, but doesn't work as expected, because even selected, the select2 doesn't show it.</p> <pre><code>$('#my_id').val('3'); //select the right option, but doesn't render it on page loads. </code></pre> <p>How to make a selected option to pop up when pages loads?</p> <p>Thanks in advance.</p> <h1>UPDATED</h1> <p>:: How I load all select2 items (sorry, its jade, not pure HTML):</p> <pre><code>label(for='category') Category span.required * select(id='category', style='width:230px', name='category') option(value='') - Select - each cat in categories option(value='#{cat.id}') #{cat.description} </code></pre> <p>P.S.: All items from my list are loaded.</p> <p>:: How I initialize the select2:</p> <p>Just put the following line code on my javascript and it does successful:</p> <pre><code>$('#category').select2(); </code></pre> <p>:: How I'm trying to select a specific value:</p> <ul> <li><p>First attempt:</p> <pre><code>$('#category').select2( { initSelection: function(element, callback) { callback($('#field-category').val()); } } ); </code></pre></li> <li><p>Second attempt:</p> <pre><code>$('#category').val($('#field-category').val()); </code></pre></li> </ul> <p>P.S.: <code>#field-category</code> has a value its a hidden input field and works OK.</p> <p>Thanks, guys!</p>
14,957,510
13
3
null
2013-02-19 12:23:57.647 UTC
9
2022-07-07 06:12:46.207 UTC
2013-07-14 00:11:39.077 UTC
null
356,895
null
621,883
null
1
40
jquery-select2
111,084
<p>You need to use the <a href="https://select2.org/advanced/default-adapters/data#initselection" rel="nofollow noreferrer">initSelection</a> option to set the initial value.</p> <p>If you are using a pre-defined <code>select</code> element to create the select2, you can use the following method</p> <pre><code>$('select').select2().select2('val','3') </code></pre> <p>Demo: <a href="http://jsfiddle.net/arunpjohny/AeXYN/" rel="nofollow noreferrer">Fiddle</a></p>
15,065,093
An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4
<p>As the title mentioned I have the following problem: I use <code>Eclipse</code> with <code>Maven Nature</code> and when I update my Maven Project, I get this error:</p> <blockquote> <p>An internal error occurred during: "Updating Maven Project".<br> Unsupported IClasspathEntry kind=4</p> </blockquote> <p>The solution that always comes back is the following:</p> <ul> <li>rightclick project, remove maven nature</li> <li><code>mvn eclipse:clean</code> (with project open in eclipse/STS)</li> <li>(sometimes they suggest to do <code>mvn eclipse:eclipse</code> next)</li> <li>rightclick project and reenable maven nature</li> </ul> <p>Now I exhaustively tried all combinations several times. But I always keep getting the above error. The error starting occurring when I had to <code>mvn eclipse:eclipse</code> the project. Before it was always running fine using only <strong>m2eclipse</strong> features and setting everything in eclipse.</p>
15,068,384
13
2
null
2013-02-25 10:42:03.577 UTC
30
2016-06-25 09:11:08.99 UTC
2016-06-25 09:11:08.99 UTC
null
3,951,782
null
1,467,482
null
1
67
eclipse|maven|m2eclipse|pom.xml
125,827
<p>I had to do it slightly different to work for me:</p> <ol> <li>rightclick project, remove maven nature (or in newer eclipse, "Maven->Disable Maven Nature")</li> <li><code>mvn eclipse:clean</code> (with project open in eclipse/STS)</li> <li>delete the project in eclipse (but do not delete the sources)</li> <li><strong>Import existing Maven project</strong></li> </ol>
15,017,072
pandas read_csv and filter columns with usecols
<p>I have a csv file which isn't coming in correctly with <code>pandas.read_csv</code> when I filter the columns with <code>usecols</code> and use multiple indexes.<br> </p> <pre><code>import pandas as pd csv = r"""dummy,date,loc,x bar,20090101,a,1 bar,20090102,a,3 bar,20090103,a,5 bar,20090101,b,1 bar,20090102,b,3 bar,20090103,b,5""" f = open('foo.csv', 'w') f.write(csv) f.close() df1 = pd.read_csv('foo.csv', header=0, names=["dummy", "date", "loc", "x"], index_col=["date", "loc"], usecols=["dummy", "date", "loc", "x"], parse_dates=["date"]) print df1 # Ignore the dummy columns df2 = pd.read_csv('foo.csv', index_col=["date", "loc"], usecols=["date", "loc", "x"], # &lt;----------- Changed parse_dates=["date"], header=0, names=["dummy", "date", "loc", "x"]) print df2 </code></pre> <p>I expect that df1 and df2 should be the same except for the missing dummy column, but the columns come in mislabeled. Also the date is getting parsed as a date. </p> <pre><code>In [118]: %run test.py dummy x date loc 2009-01-01 a bar 1 2009-01-02 a bar 3 2009-01-03 a bar 5 2009-01-01 b bar 1 2009-01-02 b bar 3 2009-01-03 b bar 5 date date loc a 1 20090101 3 20090102 5 20090103 b 1 20090101 3 20090102 5 20090103 </code></pre> <p>Using column numbers instead of names give me the same problem. I can workaround the issue by dropping the dummy column after the read_csv step, but I'm trying to understand what is going wrong. I'm using pandas 0.10.1.</p> <p>edit: fixed bad header usage.</p>
27,791,362
4
4
null
2013-02-22 04:50:55.607 UTC
35
2021-02-14 18:28:15.237 UTC
2018-05-11 00:43:28.723 UTC
null
202,229
null
653,689
null
1
119
python|pandas|csv|csv-import
313,214
<p>The solution lies in understanding these two keyword arguments:</p> <ul> <li><strong>names</strong> is only necessary when there is no header row in your file and you want to specify other arguments (such as <code>usecols</code>) using column names rather than integer indices.</li> <li><strong>usecols</strong> is supposed to provide a filter before reading the whole DataFrame into memory; if used properly, there should never be a need to delete columns after reading.</li> </ul> <p>So because you have a header row, passing <code>header=0</code> is sufficient and additionally passing <code>names</code> appears to be confusing <code>pd.read_csv</code>.</p> <p>Removing <code>names</code> from the second call gives the desired output:</p> <pre><code>import pandas as pd from StringIO import StringIO csv = r&quot;&quot;&quot;dummy,date,loc,x bar,20090101,a,1 bar,20090102,a,3 bar,20090103,a,5 bar,20090101,b,1 bar,20090102,b,3 bar,20090103,b,5&quot;&quot;&quot; df = pd.read_csv(StringIO(csv), header=0, index_col=[&quot;date&quot;, &quot;loc&quot;], usecols=[&quot;date&quot;, &quot;loc&quot;, &quot;x&quot;], parse_dates=[&quot;date&quot;]) </code></pre> <p>Which gives us:</p> <pre><code> x date loc 2009-01-01 a 1 2009-01-02 a 3 2009-01-03 a 5 2009-01-01 b 1 2009-01-02 b 3 2009-01-03 b 5 </code></pre>
8,301,741
How to identify a USB device given its VID and PID
<p>In the Windows Device Manager, I can look up the VID and PID of each USB device connected to my system. What is a good way to look up the vendor of the device using this information?</p> <p>My motivation is that I want to deploy an application to my users that will identify all USB devices connected to their systems.</p>
8,301,879
2
1
null
2011-11-28 20:13:47.897 UTC
2
2018-10-11 10:36:32.397 UTC
null
null
null
null
238,260
null
1
16
usb
40,418
<p>It's just one of those things you have to keep an updated list on, although having slightly outdated information wouldn't be terrible, since the most popular vendors have been around forever. <a href="http://www.linux-usb.org/usb.ids">Here's</a> one source you could use that appears to be regularly updated.</p>
23,870,478
How to correctly determine that an object is a lambda?
<p>I see that the class of a lambda is <code>isSynthetic() &amp;&amp; !isLocalOrAnonymousClass()</code>, but I presume that the same may be true for proxy classes.</p> <p>Of course, I could check that <code>getDeclaredMethods().length == 1</code> and apply <code>regexp</code> to the class name.</p> <p>However I want to know if there is a more elegant and robust option to find out if a given object is a lambda.</p>
23,870,800
3
5
null
2014-05-26 12:44:01.24 UTC
6
2019-06-30 02:31:29.223 UTC
2014-05-26 13:02:52.89 UTC
null
829,571
null
2,756,547
null
1
51
java|lambda|java-8
6,285
<p>There is no official way to do this, by design. Lambdas are part of the language; and are integrated into the type system through functional interfaces. There should be no need to distinguish a <code>Runnable</code> that began life as a lambda, a named class, or an inner class -- they're all Runnables. If you think you have to "deal with lambda" by taking apart the class file, you're almost certainly doing something wrong! </p>
23,629,888
Validation failed: Upload file has an extension that does not match its contents
<p>I am using paperclip gem to upload files. and my paperclip gem version is paperclip-4.1.1. While uploading a file its throwing </p> <pre><code>Validation failed: Upload file has an extension that does not match its contents. </code></pre> <p>I am trying to upload a xlsx file. and also i have mentioned that into the model content_type.</p> <pre><code> validates_attachment_content_type :upload_file, :content_type =&gt; %w(application/msword application/vnd.ms-office application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet), :message =&gt; ', Only XML,EXCEL files are allowed. ' </code></pre> <p>I don't know why this error is happening. If you have any idea about this error please share.</p> <p>Excerpt from log to show validation failure:</p> <pre><code>Command :: file -b --mime-type '/tmp/5249540099071db4e41e119388e9dd6220140513-24023-1jlg4zy' [paperclip] Content Type Spoof: Filename file_for_bulk_upload1.xlsx (["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]), content type discovered from file command: . See documentation to allow this combination. Command :: file -b --mime-type '/tmp/6f19a4f96154ef7ce65db1d585abdb2820140513-24023-tt4u1e' [paperclip] Content Type Spoof: Filename file_for_bulk_upload1.xlsx (["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]), content type discovered from file command: </code></pre>
23,630,815
3
6
null
2014-05-13 11:23:55.577 UTC
8
2021-11-13 20:31:47.04 UTC
2014-05-13 12:14:26.313 UTC
user740584
null
null
1,968,826
null
1
13
ruby-on-rails|ruby|validation|paperclip
8,672
<p>The Paperclip spoofing validation checks are failing because the <code>file</code> command is not able to accurately determine the filetype.</p> <p>In your log <code>content type discovered from file command: .</code> - the blank space before the period is the result of the output - i.e. blank. However the other side of the comparison uses purely the file extension which is being correctly picked up as an excel file. Hence your validation failure.</p> <p>The current version of Paperclip is using <code>file -b --mime-type</code> to determine the file, however <code>--mime-type</code> is not supported by all implementations. There is a change to use <code>--mime</code> instead but it's not in a milestone yet.</p> <p>I think you have a some options. Which you choose depends on how concerned you are about some dodgy file being uploaded and being called an excel file. If you are worried about this then try option 1; if you are not worried go for option 2 or 3.</p> <p><strong>1) Override the spoofing check to use <code>--mime</code> instead of <code>--mime-type</code>.</strong></p> <p>Override the <code>type_from_file_command</code> in an initializer:</p> <pre><code>module Paperclip class MediaTypeSpoofDetector private def type_from_file_command # -- original code removed -- # begin # Paperclip.run("file", "-b --mime-type :file", :file =&gt; @file.path) # rescue Cocaine::CommandLineError # "" # end # -- new code follows -- begin Paperclip.run("file", "-b --mime :file", :file =&gt; @file.path) rescue Cocaine::CommandLineError "" end end end end </code></pre> <p><strong>2) Bypass the <code>file</code> check by setting the file type totally from it's file extension.</strong></p> <p>Set this Paperclip option somewhere that is read during initialisation of the application (e.g. <code>config/application.rb</code>, <code>config/environments/&lt;environment&gt;.rb</code> or an <code>config/initializers/paperclip.rb</code>):</p> <pre><code>Paperclip.options[:content_type_mappings] = { xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' } </code></pre> <p><strong>3) Disable spoofing altogether.</strong></p> <p>Override the spoofing check by creating something like this in an initializer:</p> <pre><code>module Paperclip class MediaTypeSpoofDetector def spoofed? false end end end </code></pre> <p><strong>Update:</strong></p> <p>The validation you have in your model is not the cause of this problem. This validates which types of files you are allowed to load; what you are seeing is Paperclip calculating that the type of the file is valid but its content do not match the type of the file.</p> <p>Assuming you can get the spoofing validation to work, there is one anomaly with your content validation. The error message you output says "only XML, EXCEL files are allowed", however your actual validation is checking for MS word and excel files, not xml.</p> <p>If your message is correct and you do want to allow only xml and excel files you should change the content_type validation to be: </p> <pre><code>validates_attachment_content_type :upload_file, :content_type =&gt; %w(application/xml application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet), :message =&gt; ', Only XML,EXCEL files are allowed. ' </code></pre>
8,678,254
datetimepicker is not a function jquery
<p>I working with datetimepicker jquery ui, when code below html , datetimepicker is not displaying and when i inspect with <code>firebug console</code> it displayed an error ``</p> <pre><code>$("#example1").datetimepicker is not a function [Break On This Error] $("#example1").datetimepicker(); </code></pre> <p>and below is the code</p> <pre><code>&lt;link href="css/styles.css" rel="stylesheet" type="text/css"&gt; &lt;link href="css/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css"&gt; &lt;style&gt; .ui-timepicker-div .ui-widget-header { margin-bottom: 8px; } .ui-timepicker-div dl { text-align: left; } .ui-timepicker-div dl dt { height: 25px; margin-bottom: -25px; } .ui-timepicker-div dl dd { margin: 0 10px 10px 65px; } .ui-timepicker-div td { font-size: 90%; } .ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; } &lt;/style&gt; &lt;script type="text/javascript" src="scripts/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="scripts/jquery/ui/jquery.ui.datepicker.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="scripts/jquery/ui/jquery-ui-1.8.16.custom.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="scripts/jquery/ui/jquery-ui-timepicker-addon.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="scripts/jquery/ui/jquery-ui-sliderAccess.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function(){ $("#example1").datetimepicker(); }); &lt;/script&gt; &lt;script&gt; &lt;/script&gt; &lt;input type="text" id="example1" class="hasDatePicker"&gt; </code></pre>
8,684,192
6
3
null
2011-12-30 09:59:10.847 UTC
2
2018-11-19 07:09:35.72 UTC
null
null
null
null
630,316
null
1
19
jquery-ui|datetimepicker
152,813
<p>Keep in mind, the jQuery UI's datepicker is not initialized with datetimepicker(), there appears to be a plugin/addon here: <a href="http://trentrichardson.com/examples/timepicker/" rel="noreferrer">http://trentrichardson.com/examples/timepicker/</a>. </p> <p>However, with just jquery-ui it's actually initialized as <code>$("#example").datepicker()</code>. See jQuery's demo site here: <a href="http://jqueryui.com/demos/datepicker/" rel="noreferrer">http://jqueryui.com/demos/datepicker/</a></p> <pre><code> $(document).ready(function(){ $("#example1").datepicker(); }); </code></pre> <p>To use the datetimepicker at the link referenced above, you will want to be certain that your scripts path is correct for the plugin. </p>
8,853,727
call Fancybox in parent from iframe
<p>I have 2 pages, my index.html and social.html. I cleaned out my index and left only the jquery code need for <a href="http://fancybox.net/" rel="noreferrer">fancybox</a> What I am trying to do is to have images inside social.html and when clicked on it, it would open fancybox and show it but in index.html not inside the iframe. The error that comes up is:</p> <pre><code>Uncaught TypeError: Property 'showImage' of object [object DOMWindow] is not a function (anonymous function)social.html:103 onclick </code></pre> <p>this is my index.html:</p> <pre><code>&lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery.fancybox-1.3.4.pack.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="css/jquery.fancybox-1.3.4.css" media="screen" /&gt; &lt;script type="text/javascript" src="js/video.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function showImage(image) { $.fancybox('&lt;img src="img/' + image + '" alt="" border="0" /&gt;'); }; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;iframe src="social.html" scrolling="no" border="0" width="579" height="505" allowtransparency="true"&gt;&lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>in IFrame page:</p> <pre><code> &lt;img src="img/picture1.jpg" alt="" class="thumbs" onclick="parent.showImage('picture1.jpg');"/&gt; </code></pre> <p>PS: both pages are on same domain... EDIT: video.js -> this is from fancybox I didn't make this.</p> <pre><code>jQuery(document).ready(function() { $(".video").click(function() { $.fancybox({ 'padding' : 0, 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'title' : this.title, 'width' : 640, 'height' : 385, 'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'), 'type' : 'swf', 'swf' : { 'wmode' : 'transparent', 'allowfullscreen' : 'true' } }); return false; }); }); </code></pre>
8,855,410
4
4
null
2012-01-13 16:21:33.05 UTC
5
2021-10-03 04:42:59.333 UTC
2012-01-13 16:37:28.567 UTC
null
933,552
null
933,552
null
1
11
jquery|html|iframe|fancybox
44,971
<p>First, you should be using fancybox v2.x to seamlessly do that (patching fancybox v1.3.x doesn't worth the effort)</p> <p>Second, you need to have in both pages, the parent page and the iframed page, loaded jquery and fancybox css and js files in order to transcend fancybox properly, </p> <p>so in both pages you should have at least something like:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="fancybox2.0.4/jquery.fancybox.css" /&gt; </code></pre> <p>and</p> <pre><code>&lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="fancybox2.0.4/jquery.fancybox.js"&gt;&lt;/script&gt; </code></pre> <p>then in your iframed (child) page your script is basically the same (but with the right fancybox options for v2.x ... <a href="http://fancyapps.com/fancybox/#docs" rel="noreferrer">check the documentation here</a>)</p> <pre><code>$(".video").click(function() { $.fancybox({ 'padding' : 0, // more options (v2.x) etc </code></pre> <p>but instead of this</p> <pre><code> $.fancybox({ </code></pre> <p>do this:</p> <pre><code> parent.$.fancybox({ </code></pre> <p>then fancybox will show in the parent page out of the boundaries of the iframed page</p> <p><strong>UPDATE</strong>: <a href="http://picssel.com/playground/jquery/fancyboxFromIframe_16Jan12.html" rel="noreferrer">Demo page here</a></p>
8,460,862
What does "Packed Now Forces Byte Alignment of Records" mean?
<p>The What's New for Delphi XE2 contains the <a href="http://docwiki.embarcadero.com/RADStudio/XE2/en/Delphi_Compiler_Changes_for_XE2#.27Packed.27_Now_Forces_Byte_Alignment_of_Records">following</a>.</p> <blockquote> <h3>Packed Now Forces Byte Alignment of Records</h3> <p>If you have legacy code that uses the packed record type and you want to link with an external DLL or with C++, you need to remove the word "packed" from your code. The packed keyword now forces byte alignment, whereas in the past it did not necessarily do this. The behavior change is related to C++ alignment compatibility changes in Delphi 2009.</p> </blockquote> <p>I don't understand this. I'm struggling with this point: <em>whereas in the past it did not necessarily do this</em>. What I cannot reconcile is that packed has always resulted in byte alignment of records to the best of my knowledge. Can anyone give an example of a packed record that is not byte aligned? Obviously this would have to be in an earlier version.</p> <p>Why do the docs say "if you want to link with an external DLL or with C++, you need to remove the the word packed from your code"? If the external code uses <code>#pragma pack(1)</code> then what are we to do if packed is off limits?</p> <p>What about the <code>$ALIGN</code> directive? Are <code>{$A1} and {$A-}</code> equivalent to <code>packed</code> or is there some extra meaning with <code>packed</code>?</p> <p>It seems that I'm missing something and would appreciate it if somebody could explain this. Or is the documentation just really poor?</p> <p><strong>Update</strong></p> <p>I'm reasonably convinced that the documentation is referring to <em>alignment</em> of the record itself rather than the <em>layout</em> of the record. Here's a little program that shows that the the use of <code>packed</code> on a record forces the alignment of the record to be 1.</p> <pre><code>program PackedRecords; {$APPTYPE CONSOLE} type TPackedRecord = packed record I: Int64; end; TPackedContainer = record B: Byte; R: TPackedRecord; end; TRecord = record I: Int64; end; TContainer = record B: Byte; R: TRecord; end; var pc: TPackedContainer; c: TContainer; begin Writeln(NativeInt(@pc.R)-NativeInt(@pc.B));//outputs 1 Writeln(NativeInt(@c.R)-NativeInt(@c.B));//outputs 8 Readln; end. </code></pre> <p>This produces the same output on Delphi 6, 2010, XE and XE2 32 bit and XE 64 bit.</p>
15,831,864
4
4
null
2011-12-10 23:53:27.457 UTC
9
2013-04-05 10:43:12.28 UTC
2011-12-12 21:33:29.433 UTC
null
505,088
null
505,088
null
1
21
delphi|delphi-xe2
4,520
<p>The latest updates to the documentation have removed all of the text on which this question was based. My conclusion is that the original text was simply a documentation error. </p>
5,293,850
Fragment duplication on Fragment Transaction
<p>Ok, whenever I try to replace a fragment in my application, it only adds the fragment inside of the container the other fragment is, and leaves the current fragment. I've tried calling replace and referencing the view the contains the fragment, and by referencing the fragment itself. Neither of these work. I can add a fragment to a view with the fragment transaction manager, but even if I try to remove it after its been added, it doesn't work. Any help would be appreciated. Here are my files.</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Setup the actionabar. Use setDrawableBackground to set a background image for the actionbar. final ActionBar actionbar = getActionBar(); actionbar.setDisplayShowTitleEnabled(false); actionbar.setDisplayUseLogoEnabled(true); actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionbar.addTab(actionbar.newTab().setText(R.string.home_tab_text).setTabListener(this),true); actionbar.addTab(actionbar.newTab().setText(R.string.insert_tab_text).setTabListener(this)); Fragment fragment = new insert_button_frag(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.button_fragment, fragment); transaction.addToBackStack(null); transaction.commit(); } </code></pre> <p>Here is the layout</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;LinearLayout android:orientation="vertical" android:id="@+id/button_fragment_container" android:layout_width="fill_parent" android:layout_height="wrap_content" &gt; &lt;fragment android:name="com.bv.silveredittab.home_button_frag" android:id="@+id/button_fragment" android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;fragment android:name="com.bv.silveredittab.quick_insert_frag" android:id="@+id/quick_insert_frag" android:layout_width="350dip" android:layout_height="fill_parent" /&gt; &lt;fragment android:name="com.bv.silveredittab.editor_frag" android:id="@+id/editor_frag" android:layout_width="fill_parent" android:layout_height="fill_parent" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>And here is the fragment code</p> <pre><code>public class insert_button_frag extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); return inflater.inflate(R.layout.insert_buttons,container, false); } } </code></pre> <p>Like I have said. I have tried referencing the fragments parent view to replace it, and the fragment itself (by id) and still, it only adds the new fragment, inside the containing view the original fragment is in.</p>
5,345,946
4
1
null
2011-03-14 01:31:06.023 UTC
11
2016-07-20 09:32:52.143 UTC
2016-01-22 11:40:02.517 UTC
null
356,895
null
587,009
null
1
48
android|transactions|android-fragments
34,584
<p>I solved this by using a placeholder in my Layout and then attaching my Fragment to it at runtime.</p> <p>Like you, if I instantiated my Fragment within my xml layout then the contents would remain visible after replacing it with another Fragment at runtime.</p>
5,134,975
What can make C++ RTTI undesirable to use?
<p>Looking at the LLVM documentation, they mention that <a href="http://llvm.org/docs/ProgrammersManual.html#isa" rel="noreferrer">they use "a custom form of RTTI"</a>, and this is the reason they have <code>isa&lt;&gt;</code>, <code>cast&lt;&gt;</code> and <code>dyn_cast&lt;&gt;</code> templated functions.</p> <p>Usually, reading that a library reimplements some basic functionality of a language is a terrible code smell and just invites to run. However, this is LLVM we're talking of: the guys are working on a C++ compiler <em>and</em> a C++ runtime. If they don't know what they're doing, I'm pretty much screwed because I prefer <code>clang</code> to the <code>gcc</code> version that ships with Mac OS.</p> <p>Still, being less experienced than them, I'm left wondering what are the pitfalls of the normal RTTI. I know that it works only for types that have a v-table, but that only raises two questions:</p> <ul> <li>Since you just need a virtual method to have a vtable, why don't they just mark a method as <code>virtual</code>? Virtual destructors seem to be good at this.</li> <li>If their solution doesn't use regular RTTI, any idea how it was implemented?</li> </ul>
5,138,926
4
5
null
2011-02-27 18:20:47.433 UTC
25
2018-08-31 16:47:18.607 UTC
2018-08-31 16:47:18.607 UTC
null
3,980,929
null
251,153
null
1
72
c++|llvm|rtti
17,335
<p>There are several reasons why LLVM rolls its own RTTI system. This system is simple and powerful, and described in a section of <a href="http://llvm.org/docs/ProgrammersManual.html#isa" rel="noreferrer">the LLVM Programmer's Manual</a>. As another poster has pointed out, the <a href="http://llvm.org/docs/CodingStandards.html#ci_rtti_exceptions" rel="noreferrer">Coding Standards</a> raises two major problems with C++ RTTI: 1) the space cost and 2) the poor performance of using it.</p> <p>The space cost of RTTI is quite high: every class with a vtable (at least one virtual method) gets RTTI information, which includes the name of the class and information about its base classes. This information is used to implement the <a href="http://en.wikipedia.org/wiki/Typeid" rel="noreferrer">typeid</a> operator as well as <a href="http://en.wikipedia.org/wiki/Dynamic_cast" rel="noreferrer">dynamic_cast</a>. Because this cost is paid for every class with a vtable (and no, PGO and link-time optimizations don't help, because the vtable points to the RTTI info) LLVM builds with -fno-rtti. Empirically, this saves on the order of 5-10% of executable size, which is pretty substantial. LLVM doesn't need an equivalent of typeid, so keeping around names (among other things in type_info) for each class is just a waste of space.</p> <p>The poor performance is quite easy to see if you do some benchmarking or look at the code generated for simple operations. The LLVM isa&lt;> operator typically compiles down to a single load and a comparison with a constant (though classes control this based on how they implement their classof method). Here is a trivial example:</p> <pre><code>#include "llvm/Constants.h" using namespace llvm; bool isConstantInt(Value *V) { return isa&lt;ConstantInt&gt;(V); } </code></pre> <p>This compiles to:</p> <pre> $ clang t.cc -S -o - -O3 -I$HOME/llvm/include -D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS -mkernel -fomit-frame-pointer ... __Z13isConstantIntPN4llvm5ValueE: cmpb $9, 8(%rdi) sete %al movzbl %al, %eax ret </pre> <p>which (if you don't read assembly) is a load and compare against a constant. In contrast, the equivalent with dynamic_cast is:</p> <pre><code>#include "llvm/Constants.h" using namespace llvm; bool isConstantInt(Value *V) { return dynamic_cast&lt;ConstantInt*&gt;(V) != 0; } </code></pre> <p>which compiles down to:</p> <pre> clang t.cc -S -o - -O3 -I$HOME/llvm/include -D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS -mkernel -fomit-frame-pointer ... __Z13isConstantIntPN4llvm5ValueE: pushq %rax xorb %al, %al testq %rdi, %rdi je LBB0_2 xorl %esi, %esi movq $-1, %rcx xorl %edx, %edx callq ___dynamic_cast testq %rax, %rax setne %al LBB0_2: movzbl %al, %eax popq %rdx ret </pre> <p>This is a lot more code, but the killer is the call to __dynamic_cast, which then has to grovel through the RTTI data structures and do a very general, dynamically computed walk through this stuff. This is several orders of magnitude slower than a load and compare.</p> <p>Ok, ok, so it's slower, why does this matter? This matters because LLVM does a LOT of type checks. Many parts of the optimizers are built around pattern matching specific constructs in the code and performing substitutions on them. For example, here is some code for matching a simple pattern (which already knows that Op0/Op1 are the left and right hand side of an integer subtract operation):</p> <pre><code> // (X*2) - X -&gt; X if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt&lt;2&gt;()))) return Op1; </code></pre> <p>The match operator and m_* are template metaprograms that boil down to a series of isa/dyn_cast calls, each of which has to do a type check. Using dynamic_cast for this sort of fine-grained pattern matching would be brutally and showstoppingly slow.</p> <p>Finally, there is another point, which is one of expressivity. The <a href="http://llvm.org/docs/ProgrammersManual.html#isa" rel="noreferrer">different 'rtti' operators</a> that LLVM uses are used to express different things: type check, dynamic_cast, forced (asserting) cast, null handling etc. C++'s dynamic_cast doesn't (natively) offer any of this functionality.</p> <p>In the end, there are two ways to look at this situation. On the negative side, C++ RTTI is both overly narrowly defined for what many people want (full reflection) and is too slow to be useful for even simple things like what LLVM does. On the positive side, the C++ language is powerful enough that we can define abstractions like this as library code, and opt out of using the language feature. One of my favorite things about C++ is how powerful and elegant libraries can be. RTTI isn't even very high among my least favorite features of C++ :) !</p> <p>-Chris</p>
5,138,110
emacs create new file with ido enabled
<p>I reciently switched to emacs starter kit which includes the ido package.</p> <p>ido has a nice feature that suggests paths when find-file which is usually very handy except when trying to create a new file. When the new file name matches a suggestion in another path ido automatically switches to that path assuming that's what I wanted, but usually its not and I find it annoying. </p> <p>To workaround the issue I either touch newfile from shell, create a new buffer and save as, or M-x find-file to get the original behavior. I could of course rebind C-x C-f to find-file again but must of the time I like ido-find-file, I just want it to stop automatically switching paths when I type the path explicitly. </p> <p>I figure there is probably some simple key I can press during ido-find-file to tell it that the file I'm looking for does not exist and to stop making suggestions, or some var I can set to get more desirable behavior?</p>
5,138,216
4
2
null
2011-02-28 04:13:50.673 UTC
22
2011-12-31 12:21:34.033 UTC
null
null
null
null
226,020
null
1
113
emacs|ido-mode|ido
13,861
<p>Try:</p> <p>C-x C-f C-f</p> <p>It should kick you out of ido mode into "normal" find file mode</p>
5,042,516
How to implement a blinking label on a form
<p>I have a form that displays queue of messages and number this messages can be changed. Really I want to blink label (queue length) when the number of messages were increased to improve form usability. Should I implement custom control and use additional thread or timer to change color of label? Has anybody implemented so functionality? What is the best solution (less resources and less performance degradation) to implement so behaviour?</p> <p><strong>SOLUTION:</strong></p> <p>Form's component with timer that can <a href="http://www.w3.org/TR/WCAG20/#seizure" rel="noreferrer">restrict number of animations per second</a> and implement fade out effect to external control background color.</p>
5,042,538
7
7
null
2011-02-18 14:32:44.1 UTC
9
2020-06-26 15:06:03.087 UTC
2011-02-21 14:38:43.61 UTC
null
183,600
null
183,600
null
1
17
c#|winforms|controls|usability|user-experience
75,762
<p>You can create a custom component and events to start blinking --which I think is a good solution. The Blinking you can implement with a timer.</p>
5,074,063
Maven error "Failure to transfer..."
<p>I am trying to set up a project using Maven (m2eclipse), but I get this error in Eclipse:</p> <blockquote> <p>Description Resource Path Location Type Could not calculate build plan: Failure to transfer org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2 from <a href="http://repo1.maven.org/maven2" rel="noreferrer">http://repo1.maven.org/maven2</a> was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2 from/to central (<a href="http://repo1.maven.org/maven2" rel="noreferrer">http://repo1.maven.org/maven2</a>): No response received after 60000 ExampleProject Unknown Maven Problem</p> </blockquote> <p>Any ideas? It would be helpful if you could show me how to check if everything is configured fine...</p>
7,108,536
24
0
null
2011-02-22 04:39:45.257 UTC
210
2021-05-09 17:25:09.08 UTC
2012-11-18 13:44:51.483 UTC
null
446,215
null
446,215
null
1
325
eclipse|maven
547,790
<p>Remove all your failed downloads:</p> <pre><code>find ~/.m2 -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \; </code></pre> <p>For windows:</p> <pre><code>cd %userprofile%\.m2\repository for /r %i in (*.lastUpdated) do del %i </code></pre> <p>Then rightclick on your project in eclipse and choose Maven->"Update Project ...", make sure "Update Dependencies" is checked in the resulting dialog and click OK.</p>
12,112,276
SQL Agent Job - "Run As" drop down list is empty
<p>Why is the "Run As" drop down list is always empty when I try to set up a SQL Agent Job? I am trying to set up some SQL Agent Jobs to run using a proxy account. I am a member of the SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole. When I try to add a step to to the job, I select SQL Integration Services Package and the Run As drop down list is empty.</p> <p>Anyone who is a sysadmin can view the proxy. Shouldn't I be able to use the proxy as a member of SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole? What am I missing here?</p> <p>(The proxy account is active to the subsystem: SQL Integration Service Packages and this is SQL Server 2008 R2) </p> <p>EDIT -</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms190926.aspx" rel="noreferrer">MSDN</a>: "Members of these database roles (SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole) can view and execute jobs that they own, and create job steps that run as an existing proxy account." And this other article on fixed server roles mentions that access can be granted to proxies, but it does not mention how to do it: <a href="http://msdn.microsoft.com/en-us/library/ms188283.aspx" rel="noreferrer">MSDN</a>.</p>
12,143,054
5
0
null
2012-08-24 15:23:01.277 UTC
5
2022-08-12 12:23:21.073 UTC
2012-08-24 20:24:52.933 UTC
null
1,440,089
null
1,440,089
null
1
24
sql|sql-server-2008|proxy|jobs|agent
93,029
<p>I found the answer to this. Users who are not sysadmin have to have access to the proxy account explicitly granted to their role or username:</p> <p>To grant access to proxy accounts for non-sysadmins</p> <ol> <li>In Object Explorer, expand a server.</li> <li>Expand SQL Server Agent.</li> <li>Expand Proxies, expand the subsystem node for the proxy, right-click the proxy you wish to modify, and click Properties.</li> </ol> <p>On the General page, you can change the proxy account name, credential, or the subsystem it uses. On the Principals page, you can add or remove logins or roles to grant or remove access to the proxy account.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms187890(v=sql.100).aspx">http://msdn.microsoft.com/en-us/library/ms187890(v=sql.100).aspx</a></p>
12,588,010
How do I go to "next occurrence" in Eclipse
<p>In Eclipse you can turn on "Mark Occurrences", and then it will highlight every occurrence of a given variable in the current scope. That's great, but I'd really like to move from one such occurrence to the next.</p> <p>I've found two suggestions on how to do this so far, and neither have worked. First there was this SO post: <a href="https://stackoverflow.com/questions/4019818/eclipse-navigate-to-next-previous-marked-occurrence">Eclipse navigate to next/previous marked occurrence</a>, which suggested <code>ctrl+k</code>. However, that doesn't work for me: in my Eclipse that key-mapping is bound to "find next", not "next occurrence" (there doesn't even seem to be a "next occurrence" in the Eclipse keybindings, but maybe I'm not calling it by the right name).</p> <p>Then I found a forum post which suggested clicking on the yellow up arrow in the tool bar and checking occurrences, then using <code>ctrl+,</code>. This would have been sub-optimal if it had worked, because I already use <code>ctrl+,</code> to move between errors/warnings, but at least it would have been something ... but it didn't work at all (<code>ctrl+,</code> just moved me to the next warning).</p> <p>So, my question is: how can I move (preferably via keyboard shortcut) from one occurrence to the next in Eclipse?</p>
12,588,275
5
2
null
2012-09-25 17:22:58.547 UTC
8
2016-11-28 09:27:15.37 UTC
2017-05-23 12:25:21.577 UTC
null
-1
null
5,921
null
1
27
eclipse
20,402
<p>You didn't mention how exactly <code>ctrl+k</code> didn't work for you, but it's what I use in similar circumstances. I put the cursor into or select the word that I'm looking for in the editor and then press <code>ctrl+k</code> to move me to the next occurrence. Since the next occurrence gets selected, I can use the same combination to move forward or press <code>ctrl+shift+k</code> (Find Previous) to move back. (Sorry if that sounds patronizing, but <code>ctrl+k</code> sounds exactly like what you're looking for and I don't know the details of the difficulty you had with it.)</p> <p>I agree about the other combinations. If I have to take my hand off the keyboard, I may as well use the scrollbar.</p> <p>Best of luck. </p>
12,562,152
Replacement for "purpose" property of CLLocationManager
<p>In iOS 6, the <code>purpose</code> property of CLLocationManager, to describe the reason for using location services (<code>@property(copy, nonatomic) NSString *purpose</code>) has been deprecated. </p> <p>What replacement, if any, is proposed by Apple?</p>
12,582,916
2
1
null
2012-09-24 09:23:23.913 UTC
6
2014-01-10 10:39:24.13 UTC
2012-09-25 12:39:02.217 UTC
user467105
null
null
272,342
null
1
43
ios|cocoa-touch|ios6|cllocationmanager|deprecated
7,707
<p>The replacement for the <code>purpose</code> property in iOS 6 is a new Info.plist key named <code>NSLocationUsageDescription</code> (aka "Privacy - Location Usage Description").</p> <p>The key is <a href="https://developer.apple.com/library/mac/#documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html" rel="noreferrer">documented in the Information Property List Key Reference</a> but unfortunately it's not mentioned with the deprecation note of the <code>purpose</code> property.</p> <p>However, the <code>CLLocationManager.h</code> does have this comment:</p> <blockquote> <p><code>*</code> Deprecated. Set the purpose string in Info.plist using key NSLocationUsageDescription.</p> </blockquote> <p>In your code, you could set both the key and the <code>purpose</code> property (but you may want to check if the location manager responds to that selector first if/when that method is actually removed in the future).</p> <p>If running under iOS 6, the location manager will use the key.<br> When running under less than iOS 6, the key will be ignored and the <code>purpose</code> property will be used.</p>
12,369,615
$_SERVER['HTTP_REFERER'] missing
<p>I want to use <code>$_SERVER['HTTP_REFERER']</code> in my site but i get the following:</p> <pre><code>Notice: Undefined index: HTTP_REFERER </code></pre> <p>I have tried printing <code>$_SERVER</code>. This outputs the following:</p> <pre><code>Array ( [HTTP_HOST] =&gt; 192.168.1.10 [HTTP_USER_AGENT] =&gt; Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0 [HTTP_ACCEPT] =&gt; text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [HTTP_ACCEPT_LANGUAGE] =&gt; en-us,en;q=0.5 [HTTP_ACCEPT_ENCODING] =&gt; gzip, deflate [HTTP_CONNECTION] =&gt; keep-alive [PATH] =&gt; /sbin:/usr/sbin:/bin:/usr/bin [SERVER_SIGNATURE] =&gt; Apache/2.2.3 (CentOS) Server at 192.168.1.10 Port 80 [SERVER_SOFTWARE] =&gt; Apache/2.2.3 (CentOS) [SERVER_NAME] =&gt; 192.168.1.10 [SERVER_ADDR] =&gt; 192.168.1.10 [SERVER_PORT] =&gt; 80 [REMOTE_ADDR] =&gt; 192.168.1.77 [DOCUMENT_ROOT] =&gt; /var/www/html [SERVER_ADMIN] =&gt; root@localhost [SCRIPT_FILENAME] =&gt; /var/www/html/sandeep/test/hash.php [REMOTE_PORT] =&gt; 53851 [GATEWAY_INTERFACE] =&gt; CGI/1.1 [SERVER_PROTOCOL] =&gt; HTTP/1.1 [REQUEST_METHOD] =&gt; GET [QUERY_STRING] =&gt; [REQUEST_URI] =&gt; /sandeep/test/hash.php [SCRIPT_NAME] =&gt; /sandeep/test/hash.php [PHP_SELF] =&gt; /sandeep/test/hash.php [REQUEST_TIME] =&gt; 1347365919 ) </code></pre> <p>Can anyone help me to find <code>HTTP_REFERER</code> or suggest an alternative to <code>HTTP_REFERER</code>?</p>
12,369,682
6
6
null
2012-09-11 12:22:29.703 UTC
7
2020-05-03 21:41:36.26 UTC
2012-09-12 07:49:26.033 UTC
null
569,101
null
1,492,794
null
1
47
php
195,570
<p>From the documentation:</p> <blockquote> <p>The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.</p> </blockquote> <p><a href="http://php.net/manual/en/reserved.variables.server.php" rel="noreferrer">http://php.net/manual/en/reserved.variables.server.php</a></p>