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
1,399,605
How can I make my layout scroll both horizontally and vertically?
<p>I am using a TableLayout. I need to have both horizontal and vertical scrolling for this layout. By default I am able to get vertical scrolling in the view but horizontal scrolling is not working.</p> <p>I am using Android SDK 1.5 r3. I have already tried <code>android:scrollbars="horizontal"</code>.</p> <p>I have read on some forums that in the cupcake update, horizontal scrolling is possible.</p> <p>How can I make my layout scroll in both directions?</p>
1,409,629
8
0
null
2009-09-09 13:11:21.503 UTC
27
2022-02-15 14:43:19.547 UTC
2013-03-27 19:24:03.017 UTC
null
1,401,895
null
152,867
null
1
75
android|android-widget|android-scrollview
125,144
<p>I was able to find a simple way to achieve both scrolling behaviors.</p> <p>Here is the xml for it:</p> <pre><code>&lt;ScrollView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot; android:scrollbars=&quot;vertical&quot;&gt; &lt;HorizontalScrollView android:layout_width=&quot;320px&quot; android:layout_height=&quot;fill_parent&quot;&gt; &lt;TableLayout android:id=&quot;@+id/linlay&quot; android:layout_width=&quot;320px&quot; android:layout_height=&quot;fill_parent&quot; android:stretchColumns=&quot;1&quot; android:background=&quot;#000000&quot;/&gt; &lt;/HorizontalScrollView&gt; &lt;/ScrollView&gt; </code></pre>
1,853,284
What's the difference between the message passing and shared memory concurrency models?
<p>Correct me if I'm wrong, but I'm surprised this hasn't been asked before on here ...</p>
1,853,317
10
0
null
2009-12-05 20:04:31.457 UTC
33
2020-05-14 11:29:04.807 UTC
null
null
null
null
1,348
null
1
58
concurrency|shared-memory|message-passing
83,046
<p>It's a pretty simple difference. In a shared memory model, multiple workers all operate on the same data. This opens up a lot of the concurrency issues that are common in parallel programming.</p> <p>Message passing systems make workers communicate through a messaging system. Messages keep everyone seperated, so that workers cannot modify each other's data.</p> <p>By analogy, lets say we are working with a team on a project together. In one model, we are all crowded around a table, with all of our papers and data layed out. We can only communicate by changing things on the table. We have to be careful not to all try to operate on the same piece of data at once, or it will get confusing and things will get mixed up.</p> <p>In a message passing model, we all sit at our desks, with our own set of papers. When we want to, we can pass a paper to someone else as a "message", and that worker can now do what they want with it. We only ever have access to whatever we have in front of us, so we never have to worry that someone is going to reach over and change one of the numbers while we are in the middle of summing them up.</p> <p>Ok, silly analogy!</p>
1,979,957
Maven dependency for Servlet 3.0 API?
<p>How can I tell Maven 2 to load the Servlet 3.0 API?</p> <p>I tried:</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;3.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>I use <a href="http://repository.jboss.com/maven2/" rel="noreferrer">http://repository.jboss.com/maven2/</a> but what repository would be correct?</p> <p><strong>Addendum:</strong></p> <p>It works with a dependency for the entire Java EE 6 API and the following settings:</p> <pre class="lang-xml prettyprint-override"><code>&lt;repository&gt; &lt;id&gt;java.net&lt;/id&gt; &lt;url&gt;http://download.java.net/maven/2&lt;/url&gt; &lt;/repository&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>I'd prefer to only add the Servlet API as dependency, but "Brabster" may be right that separate dependencies have been replaced by Java EE 6 Profiles. Is there a source that confirms this assumption?</p>
1,980,718
11
3
null
2009-12-30 12:29:40.633 UTC
81
2020-11-05 23:18:20.763 UTC
2012-09-26 13:24:31.74 UTC
null
384,674
null
238,134
null
1
236
java|maven-2|servlets|jakarta-ee
283,344
<blockquote> <p>I'd prefer to only add the Servlet API as dependency, </p> </blockquote> <p>To be honest, I'm not sure to understand why but never mind...</p> <blockquote> <p><a href="https://stackoverflow.com/users/2362/brabster">Brabster</a> separate dependencies have been replaced by Java EE 6 Profiles. Is there a source that confirms this assumption?</p> </blockquote> <p>The maven repository from Java.net indeed offers the following artifact for the WebProfile:</p> <pre class="lang-xml prettyprint-override"><code>&lt;repositories&gt; &lt;repository&gt; &lt;id&gt;java.net2&lt;/id&gt; &lt;name&gt;Repository hosting the jee6 artifacts&lt;/name&gt; &lt;url&gt;http://download.java.net/maven/2&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-web-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>This jar includes Servlet 3.0, EJB Lite 3.1, JPA 2.0, JSP 2.2, EL 1.2, JSTL 1.2, JSF 2.0, JTA 1.1, JSR-45, JSR-250.</p> <p>But to my knowledge, nothing allows to say that these APIs won't be distributed separately (in java.net repository or somewhere else). For example (ok, it may a particular case), the JSF 2.0 API is available separately (in the java.net repository):</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;com.sun.faces&lt;/groupId&gt; &lt;artifactId&gt;jsf-api&lt;/artifactId&gt; &lt;version&gt;2.0.0-b10&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>And actually, you could get <code>javax.servlet-3.0.jar</code> from <a href="http://download.java.net/maven/glassfish/org/glassfish/javax.servlet/3.0" rel="noreferrer">there</a> and install it in your own repository.</p>
1,538,523
How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?
<p>I am using the Ajax.BeginForm to create a form the will do an ajax postback to a certain controller action and then if the action is successful, the user should get redirected to another page (if the action fails then a status message gets displayed using the AjaxOptions UpdateTargetId).</p> <pre><code>using (Ajax.BeginForm("Delete", null, new { userId = Model.UserId }, new AjaxOptions { UpdateTargetId = "UserForm", LoadingElementId = "DeletingDiv" }, new { name = "DeleteForm", id = "DeleteForm" })) { [HTML DELETE BUTTON] } </code></pre> <p>If the delete is successful I am returning a Redirect result:</p> <pre><code>[Authorize] public ActionResult Delete(Int32 UserId) { UserRepository.DeleteUser(UserId); return Redirect(Url.Action("Index", "Home")); } </code></pre> <p>But the Home Controller Index view is getting loaded into the UpdateTargetId and therefore I end up with a page within a page. Two things I am thinking about:</p> <ol> <li>Either I am architecting this wrong and should handle this type of action differently (not using ajax).</li> <li>Instead of returning a Redirect result, return a view which has javascript in it that does the redirect on the client side.</li> </ol> <p>Does anyone have comments on #1? Or if #2 is a good solution, what would the "redirect javascript view" look like?</p>
7,070,055
15
0
null
2009-10-08 15:23:09 UTC
30
2021-01-29 01:14:12.82 UTC
2019-04-26 11:53:45.633 UTC
null
9,020,340
null
21,579
null
1
93
c#|ajax|asp.net-mvc|asp.net-mvc-ajax
152,831
<p>You can use <code>JavascriptResult</code> to achieve this.</p> <p>To redirect:</p> <pre><code>return JavaScript("window.location = 'http://www.google.co.uk'"); </code></pre> <p>To reload the current page:</p> <pre><code>return JavaScript("location.reload(true)"); </code></pre> <p>Seems the simplest option.</p>
2,150,078
How to check visibility of software keyboard in Android?
<p>I need to do a very simple thing - find out if the software keyboard is shown. Is this possible in Android?</p>
4,737,265
45
12
null
2010-01-27 20:39:30.22 UTC
278
2022-01-09 20:50:06.89 UTC
2016-07-03 07:03:03.263 UTC
null
6,343,685
null
243,225
null
1
553
android|visibility|android-softkeyboard
299,942
<p><strong>NEW ANSWER</strong> <em>added Jan 25th 2012</em></p> <p>Since writing the below answer, someone clued me in to the existence of <a href="http://developer.android.com/reference/android/view/ViewTreeObserver.html" rel="noreferrer">ViewTreeObserver</a> and friends, APIs which have been lurking in the SDK since version 1.</p> <p>Rather than requiring a custom Layout type, a much simpler solution is to give your activity's root view a known ID, say <code>@+id/activityRoot</code>, hook a GlobalLayoutListener into the ViewTreeObserver, and from there calculate the size diff between your activity's view root and the window size:</p> <pre><code>final View activityRootView = findViewById(R.id.activityRoot); activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight(); if (heightDiff &gt; dpToPx(this, 200)) { // if more than 200 dp, it's probably a keyboard... // ... do something here } } }); </code></pre> <p>Using a utility such as: </p> <pre><code>public static float dpToPx(Context context, float valueInDp) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics); } </code></pre> <p>Easy!</p> <p><strong>Note:</strong> Your application must set this flag in Android Manifest <code>android:windowSoftInputMode="adjustResize"</code> otherwise above solution will not work.</p> <p><strong>ORIGINAL ANSWER</strong></p> <p>Yes it's possible, but it's far harder than it ought to be.</p> <p>If I need to care about when the keyboard appears and disappears (which is quite often) then what I do is customize my top-level layout class into one which overrides <code>onMeasure()</code>. The basic logic is that if the layout finds itself filling significantly less than the total area of the window, then a soft keyboard is probably showing. </p> <pre><code>import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.widget.LinearLayout; /* * LinearLayoutThatDetectsSoftKeyboard - a variant of LinearLayout that can detect when * the soft keyboard is shown and hidden (something Android can't tell you, weirdly). */ public class LinearLayoutThatDetectsSoftKeyboard extends LinearLayout { public LinearLayoutThatDetectsSoftKeyboard(Context context, AttributeSet attrs) { super(context, attrs); } public interface Listener { public void onSoftKeyboardShown(boolean isShowing); } private Listener listener; public void setListener(Listener listener) { this.listener = listener; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = MeasureSpec.getSize(heightMeasureSpec); Activity activity = (Activity)getContext(); Rect rect = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); int statusBarHeight = rect.top; int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight(); int diff = (screenHeight - statusBarHeight) - height; if (listener != null) { listener.onSoftKeyboardShown(diff&gt;128); // assume all soft keyboards are at least 128 pixels high } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } </code></pre> <p>Then in your Activity class...</p> <pre><code>public class MyActivity extends Activity implements LinearLayoutThatDetectsSoftKeyboard.Listener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... LinearLayoutThatDetectsSoftKeyboard mainLayout = (LinearLayoutThatDetectsSoftKeyboard)findViewById(R.id.main); mainLayout.setListener(this); ... } @Override public void onSoftKeyboardShown(boolean isShowing) { // do whatever you need to do here } ... } </code></pre>
33,701,823
Chrome Mobile color bar theme-color meta tag not working
<p>I'm trying to implement the <code>theme-color</code> meta tag but I can't see it working in my Motorola smartphone with Chrome and Android Lollipop. </p> <p>I started with a <code>theme-color</code> tag then I wrote the other tags, but have had no success at all.</p> <pre><code>&lt;meta name="theme-color" content="#5f5eaa"&gt; &lt;meta name="msapplication-TileColor" content="#5f5eaa"&gt; &lt;meta name="msapplication-navbutton-color" content="#5f5eaa"&gt; &lt;meta name="apple-mobile-web-app-status-bar-style" content="#5f5eaa"&gt; </code></pre> <p>This webpage is running over HTTPS with an invalid certificate (it's an intranet tool), but I don't think it would affect that feature, right?</p>
52,778,270
6
5
null
2015-11-13 21:11:46.927 UTC
3
2022-03-09 14:38:50.02 UTC
2018-11-09 18:14:12.49 UTC
null
397,817
null
3,489,993
null
1
31
html|google-chrome
23,131
<h2>Always check actual browsers versions.</h2> <p>Here is table of supporting this meta tag. <a href="https://caniuse.com/#feat=meta-theme-color" rel="nofollow noreferrer">https://caniuse.com/#feat=meta-theme-color</a></p> <p><a href="https://i.stack.imgur.com/UFHZo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UFHZo.jpg" alt="enter image description here" /></a></p>
8,923,174
OpenGL VAO best practices
<p>Im facing an issue which I believe to be VAO-dependant, but Im not sure..</p> <p>I am not sure about the correct usage of a VAO, what I used to do during GL initialization was a simple</p> <pre><code>glGenVertexArrays(1,&amp;vao) </code></pre> <p>followed by a</p> <pre><code>glBindVertexArray(vao) </code></pre> <p>and later, in my drawing pipeline, I just called <strong>glBindBuffer(), glVertexAttribPointer(), glEnableVertexAttribArray()</strong> and so on.. without caring about the initally bound VAO</p> <p>is this a correct practice?</p>
8,923,298
4
2
null
2012-01-19 08:42:55.417 UTC
45
2014-10-24 12:28:36.633 UTC
2014-07-21 21:07:15.27 UTC
null
1,642,975
null
815,129
null
1
83
opengl|opengl-3|vao
46,676
<p>VAOs act similarly to VBOs and textures with regard to how they are bound. Having a single VAO bound for the entire length of your program will yield no performance benefits because you might as well just be rendering without VAOs at all. In fact it may be slower depending on how the implementation intercepts vertex attribute settings as they're being drawn.</p> <p>The point of a VAO is to run all the methods necessary to draw an object once during initialization and cut out all the extra method call overhead during the main loop. The point is to have multiple VAOs and switch between them when drawing.</p> <p>In terms of best practice, here's how you should organize your code:</p> <pre><code>initialization: for each batch generate, store, and bind a VAO bind all the buffers needed for a draw call unbind the VAO main loop/whenever you render: for each batch bind VAO glDrawArrays(...); or glDrawElements(...); etc. unbind VAO </code></pre> <p>This avoids the mess of binding/unbinding buffers and passing all the settings for each vertex attribute and replaces it with just a single method call, binding a VAO.</p>
18,192,114
How to use vertical align in bootstrap
<p>Simple problem: How do I vertically align a col within a col using bootstrap? Example here (I want to vertically align child1a and child1b): </p> <p><a href="http://bootply.com/73666">http://bootply.com/73666</a></p> <p>HTML</p> <pre><code>&lt;div class="col-lg-12"&gt; &lt;div class="col-lg-6 col-md-6 col-12 child1"&gt; &lt;div class="col-12 child1a"&gt;Child content 1a&lt;/div&gt; &lt;div class="col-12 child1b"&gt;Child content 1b&lt;/div&gt; &lt;/div&gt; &lt;div class="col-lg-6 col-md-6 col-12 child2"&gt; Child content 2&lt;br&gt; Child content 2&lt;br&gt; Child content 2&lt;br&gt; Child content 2&lt;br&gt; Child content 2&lt;br&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>UPDATE</strong></p> <p>Some CSS:</p> <pre><code>.col-lg-12{ top:40px; bottom:0px; border:4px solid green; } .child1a, .child1b{ border:4px solid black; display:inline-block !important; } .child1{ border:4px solid blue; height:300px; display:table-cell !important; vertical-align:middle; } .child2{ border:4px solid red; } </code></pre>
19,154,569
8
1
null
2013-08-12 16:31:41.033 UTC
18
2017-05-10 13:24:47.017 UTC
2013-08-12 17:32:08.94 UTC
null
2,274,357
null
2,429,989
null
1
51
css|twitter-bootstrap|twitter-bootstrap-3
240,324
<pre><code>.parent { display: table; table-layout: fixed; } .child { display:table-cell; vertical-align:middle; text-align:center; } </code></pre> <p><code>table-layout: fixed</code> prevents breaking the functionality of the col-* classes.</p>
17,902,483
Show values from a MySQL database table inside a HTML table on a webpage
<p>I want to retrieve the values from a database table and show them in a html table in a page. I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading. The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number. How can I get it to show all the values from the db in a html table like this:</p> <pre><code>&lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt;Submission ID&lt;/th&gt; &lt;th&gt;Form ID&lt;/th&gt; &lt;th&gt;IP&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;E-mail&lt;/th&gt; &lt;th&gt;Message&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;123456789&lt;/td&gt; &lt;td&gt;12345&lt;/td&gt; &lt;td&gt;123.555.789&lt;/td&gt; &lt;td&gt;John Johnny&lt;/td&gt; &lt;td&gt;johnny@example.com&lt;/td&gt; &lt;td&gt;This is the message John sent you&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>And then all the other values below 'john'.</p>
17,902,527
9
4
null
2013-07-27 21:08:40.19 UTC
49
2022-01-14 15:13:51.313 UTC
2018-04-24 17:47:56.683 UTC
null
4,370,109
null
2,601,086
null
1
52
php|mysql|database|html-table
651,800
<p>Example taken from W3Schools: <a href="http://www.w3schools.com/php/php_mysql_select.asp" rel="noreferrer">PHP Select Data from MySQL</a></p> <pre><code>&lt;?php $con=mysqli_connect("example.com","peter","abc123","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = mysqli_query($con,"SELECT * FROM Persons"); echo "&lt;table border='1'&gt; &lt;tr&gt; &lt;th&gt;Firstname&lt;/th&gt; &lt;th&gt;Lastname&lt;/th&gt; &lt;/tr&gt;"; while($row = mysqli_fetch_array($result)) { echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $row['FirstName'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['LastName'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } echo "&lt;/table&gt;"; mysqli_close($con); ?&gt; </code></pre> <p>It's a good place to learn from!</p>
18,103,769
How can I obtain the cube root in C++?
<p>I know how to obtain the <em>square root</em> of a number using the <code>sqrt</code> function.</p> <p>How can I obtain the <em>cube root</em> of a number?</p>
18,103,837
9
15
null
2013-08-07 12:46:23.243 UTC
6
2022-05-08 21:27:39.367 UTC
2013-08-07 13:52:02.65 UTC
null
560,648
null
2,654,303
null
1
33
c++
69,628
<p><code>sqrt</code> stands for "square root", and "square root" means raising to the power of <code>1/2</code>. There is no such thing as "square root with root 2", or "square root with root 3". For <a href="http://en.wikipedia.org/wiki/Nth_root" rel="noreferrer">other roots</a>, you change the first word; <strong>in your case, you are seeking how to perform <em>cube rooting</em></strong>.</p> <p>Before C++11, there is no specific function for this, but you can go back to first principles:</p> <ul> <li>Square root: <code>std::pow(n, 1/2.)</code> (or <a href="http://en.cppreference.com/w/cpp/numeric/math/sqrt" rel="noreferrer"><code>std::sqrt(n)</code></a>)</li> <li>Cube root: <code>std::pow(n, 1/3.)</code> (or <a href="http://en.cppreference.com/w/cpp/numeric/math/cbrt" rel="noreferrer"><code>std::cbrt(n)</code></a> since C++11)</li> <li>Fourth root: <code>std::pow(n, 1/4.)</code></li> <li><em>etc.</em></li> </ul> <hr> <p>If you're expecting to pass negative values for <code>n</code>, avoid the <code>std::pow</code> solution &mdash; <a href="https://stackoverflow.com/a/4269119/560648">it doesn't support negative inputs with fractional exponents</a>, and this is why <code>std::cbrt</code> was added:</p> <pre><code>std::cout &lt;&lt; std::pow(-8, 1/3.) &lt;&lt; '\n'; // Output: -nan std::cout &lt;&lt; std::cbrt(-8) &lt;&lt; '\n'; // Output: -2 </code></pre> <hr> <p><sup>N.B. That <code>.</code> is really important, because otherwise <code>1/3</code> uses integer division and results in <code>0</code>.</sup></p>
6,557,794
How to access value of map with a key if key was not found in scala?
<p>Assume I have </p> <pre><code>var mp = Map[String,String]() ..... val n = mp("kk") </code></pre> <p>The above will throw runtime error in case key "kk" did not exist.</p> <p>I expected n will be null in case key did not exist. I want n to be null if key did not exist.</p> <p>What is the proper way to handle this situation in scala with a short code sample?</p>
6,557,829
3
1
null
2011-07-02 15:13:31.717 UTC
4
2018-05-15 18:13:32.907 UTC
null
null
null
null
821,764
null
1
25
scala
43,231
<p>First of all, you probably don't really want null, as that's almost always a sign of bad coding in Scala. What you want is for n to be of type Option[String], which says that the value is either a String or is missing. The right way to do that is with the .get() method on you map</p> <pre><code>val n = mp.get("kk") </code></pre> <p>If you really do need null (for interop with Java libraries, for example), you can use .getOrElse()</p> <pre><code>val n = mp.getOrElse("kk", null) </code></pre>
6,403,737
Fixed Button below a scrollable ListView
<p>I have a scrollable ListView with items (like in <a href="http://developer.android.com/resources/tutorials/views/hello-listview.html">http://developer.android.com/resources/tutorials/views/hello-listview.html</a>). I am using an <code>ArrayAdapter</code> for the items and use it as a parameter in <code>setListAdapter</code>. Now I would like to add a button at the bottom of the screen, which does not scroll with the list. Could someone give me some hints or post a code snippet how it could possibly be done?</p>
6,404,148
3
0
null
2011-06-19 16:48:33.86 UTC
11
2017-01-17 00:21:46.807 UTC
null
null
null
null
603,841
null
1
30
android|listview
34,356
<p>If your activity extends ListActivity then you need something like this:</p> <pre><code>&lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;ListView android:id="@android:id/list" android:layout_height="0dip" android:layout_width="match_parent" android:layout_weight="1" /&gt; &lt;Button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>Notice that the listview has a layout_weight set to 1. That will keep the button fixed in its place at the bottom. Hope that helps. Good luck!</p>
6,585,373
Django multiple and dynamic databases
<p>I've been evaluating django and wondered if the following is possible. I've already looked at the regular multiple database docs so please don't point me to that because this use case isn't mentioned as far as i can make out. If i'm wrong i take it back :)</p> <p>I want one main database in which most of my app's models will reside, however one of the app's will need to dynamically create databases, these will be customer specific databases. </p> <p>The database path (i plan to use sqlite) will be stored in primary database and so the cursor would need to be changed but the model will remain the same.</p> <p>I would welcome any thoughts on ways to achieve this?</p>
11,292,526
3
3
null
2011-07-05 15:41:59.16 UTC
28
2022-01-30 07:10:18.43 UTC
null
null
null
null
148,508
null
1
44
django|django-database
19,360
<p>I will open with "<a href="https://docs.djangoproject.com/en/dev/topics/settings/#altering-settings-at-runtime" rel="noreferrer">You should not edit settings at runtime</a>".</p> <p>Having said that, I have exactly this same issue, where I want to create a unique database for each user. The reason for doing this is I am offering the ability for the user to save/access to/from a database not stored on my server, which entails having multiple databases, and thus one for each user.</p> <p>This answer is NOT the recommended way to achieve the desired goal. I would love to hear from a django-guru how to best approach this problem. However, this is a solution I have been using and it has worked well so far. I am using sqlite however it can be easily modified for any of the databases.</p> <p>In summary, this is the process:</p> <ol> <li>Add the new database to settings (at runtime)</li> <li>Create a file to store these settings for reloading when the server is restarted (at runtime)</li> <li>Run a script which loads the saved settings files (whenever the server is restarted)</li> </ol> <p>Now, how to achieve this:</p> <p>1) Firstly, when a new user is created, I create a new database in the settings. This code lives in my view where new users are created.</p> <pre><code>from YOUR_PROJECT_NAME import settings database_id = user.username #just something unique newDatabase = {} newDatabase["id"] = database_id newDatabase['ENGINE'] = 'django.db.backends.sqlite3' newDatabase['NAME'] = '/path/to/db_%s.sql' % database_id newDatabase['USER'] = '' newDatabase['PASSWORD'] = '' newDatabase['HOST'] = '' newDatabase['PORT'] = '' settings.DATABASES[database_id] = newDatabase save_db_settings_to_file(newDatabase) #this is for step 2) </code></pre> <p>This script loads the database settings 'at runtime' into the django project settings. However if the server is restarted, this database will no longer be in settings.</p> <p>2) To facilitate reloading these settings automatically whenever the server is restarted, I create a file for each database which will be loaded whenever the server is started. Creating this file is performed by the function <code>save_db_settings_to_file</code>:</p> <pre><code>def save_db_settings_to_file(db_settings): path_to_store_settings = "/path/to/your/project/YOUR_PROJECT_NAME/database_settings/" newDbString = """ DATABASES['%(id)s'] = { 'ENGINE': '%(ENGINE)s', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '%(NAME)s', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } """ % db_settings file_to_store_settings = os.path.join(path_to_store_settings, db_settings['id'] + ".py") write_file(file_to_store_settings, newDbString) #psuedocode for compactness </code></pre> <p>3) To actually load these settings when the server is started, I add a single line to the very bottom of <code>/path/to/your/project/YOUR_PROJECT_NAME/settings.py</code>, which loads each file in the settings folder and runs it, having the effect of loading the database details into the settings.</p> <pre><code>import settings_manager </code></pre> <p>Then, <code>import settings_manager</code> will load the file at <code>/path/to/your/project/YOUR_PROJECT_NAME/settings_manager.py</code>, which contains the following code:</p> <pre><code>from settings import DATABASES import os path_to_store_settings = "/path/to/your/project/YOUR_PROJECT_NAME/database_settings/" for fname in os.listdir(path_to_settings): full_path = os.path.join(path_to_settings, fname) f = open(full_path) content = f.read() f.close() exec(content) #you'd better be sure that the file doesn't contain anything malicious </code></pre> <p>Note that you could put this code directly at the bottom of settings.py instead of the import statement, but using the import statement keeps the abstraction level of settings.py consistent.</p> <p>This is a convenient way to load each database setting because to remove a database from the settings all you have to do is delete the settings file, and the next time the server restarts it won't load those details into the settings, and the database will not be accessible.</p> <p>As I said, this works and I have had success using it so far, but this is NOT the ideal solution. I would really appreciate if someone could post a better solution.</p> <p>What's bad about it:</p> <ul> <li>It explicitly defies advice from django team not to modify settings at runtime. I do not know the reason for why this advice is given.</li> <li>It uses an <code>exec</code> statement to load the data into settings. This should be OK, but if you get some corrupt or malicious code in one of those files you will be a sad panda.</li> </ul> <p>Note that I still use the default database for auth and sessions data, but all the data from my own apps is stored in the user-specific database.</p>
6,587,712
django url patterns with 2 parameters
<p>This is simple and obvious but I can't get it right:</p> <p>I have the following view function declared in urls.py</p> <pre><code> (r'^v1/(\d+)$', r'custom1.views.v1'), </code></pre> <p>originally I was passing a single parameter to the view function v1. I want to modify it to pass 2 parameters. How do I declare the entry in urls.py to take two parameters?</p>
6,587,781
4
0
null
2011-07-05 19:17:08.323 UTC
1
2020-05-07 18:29:53.907 UTC
null
null
null
null
773,389
null
1
16
django
42,389
<p>I believe each group in the regex is passed as a parameter (and you can name them if you want):</p> <pre><code>(r'^v1/(\d+)/(\d+)/$', r'custom1.views.v1') </code></pre> <p>Check out the examples at: <a href="https://docs.djangoproject.com/en/dev/topics/http/urls/" rel="noreferrer">https://docs.djangoproject.com/en/dev/topics/http/urls/</a>. You can also name your groups.</p>
36,212,901
VS 2015 Razor Autocomplete/Intellisense dropdown hides immediately after dropdown
<p>In VS 2015, only when in Razor (.cshtml) files, roughly half of the time the autocomplete/suggestion list/intellisense doesn't work correctly (sorry, not sure the actual term... when you type an object and hit <code>.</code> and the list of properties and methods shows to select from)</p> <p>The behavior is that when I hit <code>.</code>, the list popups up for a fraction of a second and then closes. It happens so fast I try to do a quick <code>Backspace</code>, <code>.</code>, <code>Backspace</code>, <code>.</code> cycle a few times to at least <em>see</em> the name I need, but I usually cant' get it and end up having to find the exact name elsewhere from code. Extremely irritating...</p> <p>It happens sporadically with no real pattern I can find. Here's patterns that I've ruled out:</p> <ul> <li>The file that's open doesn't seem to matter.</li> <li>Whether or not I close/reopen the file doesn't seem to matter</li> <li>Whether I navigate to another file and back doesn't seem to matter</li> <li>It will work/not work multiple times on and off throughout the same file</li> <li>It doesn't seem to be relevant to any particular object/property/method</li> </ul> <p>I've checked all my options (there doesn't seem to be Text Editing options for Razor?), have tried clearing caches, the reloading solution/projects, restarting VS, all of which seem to still provide no pattern.</p> <p>Has anyone come across this and have any ideas of where else I can look to fix it?</p> <p><strong>Example</strong> Here's an extremely simple example... new project, very little code/files, very simple view. Where the <code>Model.</code> stops, I should have the usual base methods, and an 'Items' collection. It pops up for a split second then disappears... no lambdas/complex view parsing involved (this is reproducible as well):</p> <p><a href="https://i.stack.imgur.com/3k23t.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/3k23t.jpg" alt="enter image description here"></a></p> <p><strong>Update: Patterns</strong></p> <p>Things I've noticed:</p> <ul> <li>If I'm entering a <code>@model ns.ns.ns.type</code>, it rarely happens toward the "base" end of the namespaces. It's as I get further towards the type that it happens. This one is intermittent.</li> <li>In some cases, it works perfectly fine, every single time. For example, I often use DevExpress tools, and have never seen the behavior on any of their extensions (so, <code>@Html.DevExpress().</code> (and other similar, not necessarily DevEx models) will never cause a problem)</li> <li>It happens almost all the time when I'm accessing my <code>@Model</code> (which is where I most want it!). I've found some cases where this is reproducible every time (see above example), but it's about 90%+</li> <li>Occasionally, as I work through the object tree, one will fail while the next works (ex: <code>@models ProjName.Web.App.Subscriptions.Models.AccountCreateVM</code>... it might fail on <code>Subscriptions</code> but work fine on <code>Models</code>)</li> <li>Occasionally, beginning to type the name within autocomplete kicks it back into gear and it starts working again. In the above example, starting to type <code>Acc</code> for <code>AccountCreateVM</code> causes it to start working again.</li> </ul>
38,750,315
8
3
null
2016-03-25 01:55:21.01 UTC
12
2017-08-24 09:22:22.917 UTC
2016-07-22 19:12:54.29 UTC
null
4,155,665
null
4,155,665
null
1
43
razor|visual-studio-2015|intellisense
4,457
<p>I haven't found the root cause, but in all cases, <code>CTRL+SPACE</code> works. This isn't the best, but light years better than nothing at all.</p> <p>(this shortcut is not one I've used in the past, so this is likely standard behavior, but...) If you're at the dot <code>Model.</code> and autocomplete list disappears, <strong>CTRL+SPACE consistently brings it back up, and when it does come back, it stays!</strong> If there's only one possible autocomplete member, it'll auto-fill the member for you upon CTRL+SPACE</p>
18,727,186
How to load classes based on pretty URLs in MVC-like page?
<p>I would like to ask for some tips, on how solve this problem. I'm trying to build my own MVC website. I learned the basics of the URL.</p> <pre><code>http://example.com/blog/cosplay/cosplayer-expo-today </code></pre> <p>blog -> the controller<br/>cosplay -> the method in controller<br/>cosplayer-expo-today ->variable in method</p> <p>What if i dynamically extend the category in my blog controller? Will I need to create the method, or is there some trick to do that automatically? I mean... i have these categories now: cosplay,game,movie,series. So I need to create these methods in controller, but they all do the same thing, namely select other category from database.</p> <ul> <li>function cosplay() = example.com/blog/cosplay/</li> <li>function game() = example.com/blog/game/</li> <li>function movie() = example.com/blog/movie/</li> <li>function series() = example.com/blog/series/</li> </ul> <p>Is there any good advice on how can i write my controller to do that automatically? I mean if I upload a new category in my database, but i don't want to modify the controller. Is it possible? Thanks for the help!</p> <p>UPDATE</p> <p>Here is my URL exploder class</p> <pre><code>class Autoload { var $url; var $controller; function __construct() { $this-&gt;url = $_GET['url']; //HNEM ÜRES AZ URL if($this-&gt;url!='' &amp;&amp; !empty($this-&gt;url)) { require 'application/config/routes.php'; //URL VIZSGÁLATA $this-&gt;rewrite_url($this-&gt;url); //URL SZÉTBONTÁSA $this-&gt;url = explode('/', $this-&gt;url); $file = 'application/controllers/'.$this-&gt;url[0].'.php'; //LÉTEZIK A CONTROLLER? if(file_exists($file)) { require $file; $this-&gt;controller = new $this-&gt;url[0]; //KÉRELEM ALATT VAN AZ ALOLDAL? if(isset($this-&gt;url[1])) { //LÉTEZIK A METÓDUS? ENGEDÉLYEZVE VAN? if(method_exists($this-&gt;controller, $this-&gt;url[1]) &amp;&amp; in_array($this-&gt;url[1], $route[$this-&gt;url[0]])) { if(isset($this-&gt;url[2])) { $this-&gt;controller-&gt;{$this-&gt;url[1]}($this-&gt;url[2]); } else { $this-&gt;controller-&gt;{$this-&gt;url[1]}(); } } else { header('location:'.SITE.$this-&gt;url[0]); die(); } } } else { header('location:'.SITE); die(); } } else { header('location:'.SITE.'blog'); die(); } } /** * Első lépésben megvizsgáljuk, hogy a kapott szöveg tartalmaz-e nagybetűt. Amennyiben igen átalakítjuk kisbetűsre.&lt;br/&gt; * Második lépésben megnézzük, hogy a kapott szöveg '/'-re végződik-e. Amennyiben igen levágjuk azt.&lt;br/&gt; * Harmadik lépésben újra töltjük az oldalt a formázott szöveggel. * * @param string $url Korábban beolvasott URL. */ private function rewrite_url($url) { //HA NAGYBETŰ VAN AZ URL-BEN VAGY '/'-RE VÉGZŐDIK if(preg_match('/[A-Z]/', $url) || substr($url, -1)=='/') { //NAGYBETŰS AZ URL KICSIRE ALAKÍTJUK if(preg_match('/[A-Z]/', $url)) { $url = strtolower($url); } //HA '/'-RE VÉGZŐDIK LEVÁGJUK if(substr($url, -1)=='/') { $url = substr($url, 0, strlen($url)-1); } header('location:'.SITE.$url); die(); } } } </code></pre> <p>And here is my .htacces</p> <pre><code>Options +FollowSymLinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.+)$ index.php?url=$1 [QSA,L] </code></pre>
19,309,893
2
5
null
2013-09-10 19:21:36.42 UTC
18
2017-11-30 16:57:05.39 UTC
2013-12-06 11:44:04.363 UTC
null
727,208
user2432700
null
null
1
6
php|.htaccess|url-routing
6,239
<blockquote> <p><sub><strong>FYI:</strong> There are several things that you are doing wrong. I will try to go through each of them and explain the problems, the misconceptions and the possible solution(s).</sub></p> </blockquote> <h2>The autoloading and routing are separate things.</h2> <p>From the look of you posted code, it's obvious, that you have a single class, which is responsible the following tasks:</p> <ul> <li>routing: it splits the URL in parts that have some significance for the rest of applications</li> <li>autoloading: class takes the separated URL segments and attempts to include related code</li> <li>factory: new instances are initialized and some method are called on them</li> <li>response: in some cases, the class sends a response to user in form of HTTP header</li> </ul> <p>In OOP there is this thing, called: <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer">Single Responsibility Principle</a> <sup>[<a href="https://i.stack.imgur.com/myc48.jpg" rel="noreferrer">short version</a>]</sup>. Basically it means that a class should be handling one specific are thing. The list above constitutes at least <strong>4</strong> different responsibilities for your <code>Autoload</code> class.</p> <p>Instead of what you have now, each of these general tasks should be handled by a separate class. And in case of autoloader, you could get away with a single function.</p> <h2>How to do write your own autoloading code ?</h2> <p>Part of the problem that I see is the confusion about how autoload actually works in PHP. The call of <code>include</code> or <code>require</code> doesn't need to be done where the instance will be created. Instead you register a handler (using <a href="http://www.php.net/manual/en/function.spl-autoload-register.php" rel="noreferrer"><code>spl_autoload_register()</code></a> function), which then is **automatically* called, when you try to use previously-undefined class.</p> <p>The simplest example for it is:</p> <pre><code>spl_autoload_register( function( $name ) use ( $path ) { $filename = $path . '/' . $name . '.php'; if ( file_exists( $filename ) === true ) { require $filename; return true; } return false; }); </code></pre> <p>This particular example uses <a href="http://www.php.net/manual/en/functions.anonymous.php" rel="noreferrer">anonymous function</a>, which is one of features that was introduced in PHP 5.3, but the manual page for the <code>spl_autoload_register()</code> will also show you examples how to achieve the same with objects or ordinary functions.</p> <p>Another new feature that is closely related to autoloading is <a href="http://www.php.net/manual/en/language.namespaces.php" rel="noreferrer">namespaces</a>. In this context the namespaces would give you two immediate benefits: ability to have multiple classes with same name and options to load class file from multiple directories.</p> <p>For example, you can have code like this:</p> <pre><code>$controller = new \Controllers\Overview; $view = new \Views\Overview; $controller-&gt;doSomething( $request ); </code></pre> <p>.. in this case you can have autoloader fetching classes from <code>/project/controllers/overview.php</code> and <code>/project/views/overview.php</code> files respectively. Because the <code>spl_autoload_register()</code> will pass <code>"\Controllers\Overview"</code> and <code>"\Views\Overview"</code> to the handler function.</p> <p>There is also a <a href="http://www.php-fig.org/" rel="noreferrer">FIG</a> recommendation for how to implement autoloaders. You can find it <a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md" rel="noreferrer">here</a>. While it has some significant problems, it should provide you with good base on which to build upon.</p> <h2>How to parse pretty URLs ?</h2> <p>It is no secret, that Apache's <em>mod_rewrite</em> is quite limited in what it can do with <em>pretty URLs</em>. And, while it's a widespread server, it is not the only option for webservers. This is why for maximum flexibility PHP developers opt to handle URLs on the PHP end.</p> <p>And the first thing any newbie will do is <code>explode('/', ... )</code>. It is a natural choice, but you will soon notice that it is also <strong>extremely limited</strong> in what it can really do. The routing mechanism will start to grow. At first based on count of segments, later - adding different conditional values in segments, that require different behavior.</p> <p>Essentially, this will turn in huge, fragile and uncontrollable mess. Bad idea.</p> <p>Instead what you should do is have a list of regular expressions, that you match against given pretty URL. For example:</p> <pre><code>'#/(?P&lt;resource&gt;[^/\\\\.,;?\n]+)/foobar#' </code></pre> <p>The above defined pattern would match all the URL that have two segments, with some text in first segment and <code>"foobar"</code> in the second ... like <code>"/testme/foobar"</code>.</p> <p>Additionally you can link each pattern with corresponding default values for each match. When you put this all together, you might end up with configuration like this (uses 5.4+ array syntax, because <em>that's how I like to write</em> .. deal with it):</p> <pre><code>$routes = [ 'primary' =&gt; [ 'pattern' =&gt; '#/(?P&lt;resource&gt;[^/\\\\.,;?\n]+)/foobar#', 'default' =&gt; [ 'action' =&gt; 'standard', ], ], 'secundary' =&gt; [ 'pattern' =&gt; '#^/(?P&lt;id&gt;[0-9]+)(?:/(?P&lt;resource&gt;[^/\\\\.,;?\n]+)(?:/(?P&lt;action&gt;[^/\\\\.,;?\n]+))?)?$#', 'default' =&gt; [ 'resource' =&gt; 'catalog', 'action' =&gt; 'view', ] ], 'fallback' =&gt; [ 'pattern' =&gt; '#^.*$#', 'default' =&gt; [ 'resource' =&gt; 'main', 'action' =&gt; 'landing', ], ], ]; </code></pre> <p>Which you could handle using following code:</p> <pre><code>// CHANGE THIS $url = '/12345/product'; $current = null; // matching the route foreach ($routes as $name =&gt; $route) { $matches = []; if ( preg_match( $route['pattern'], $url, $matches ) ) { $current = $name; $matches = $matches + $route['default']; break; } } // cleaning up results foreach ( array_keys($matches) as $key ) { if ( is_numeric($key) ) { unset( $matches[$key] ); } } // view results var_dump( $current, $matches ); </code></pre> <p><kbd>Live code: <a href="http://3v4l.org/T7i3l" rel="noreferrer">here</a> or <a href="http://codepad.viper-7.com/VOCWZh" rel="noreferrer">here</a></kbd></p> <blockquote> <p><sub><strong>Note:</strong><br>If you use <strong><code>'(?P&lt;name&gt; .... )'</code></strong> notation, the matches will return array with <strong><code>'name'</code></strong> as a key. Useful trick for more then routing.</sub></p> </blockquote> <p>You probably will want to generate the regular expressions for the matching from some more-readable notations. For example, in configuration file, this expression:</p> <pre><code>'#^/(?P&lt;id&gt;[0-9]+)(?:/(?P&lt;resource&gt;[^/\\\\.,;?\n]+)(?:/(?P&lt;action&gt;[^/\\\\.,;?\n]+))?)?$#' </code></pre> <p>.. should probably look something like </p> <pre><code>'/:id[[/:resource]/:action]' </code></pre> <p>Where the <code>:param</code> would indication an URL segment and <code>[...]</code> would signify an optional part of URL. </p> <p>Based on this you should be able to flesh out your own routing system. The code fragments above is just example of simplified core functionality. To get some perspective on how it might look when fully implemented, you could look at code in <a href="https://stackoverflow.com/a/18416136/727208">this answer</a>. It should give you some ideas for your own API version.</p> <h2>Calling the stuff on controllers ..</h2> <p>It is quite common mistake to bury the execution of controllers somewhere deep in the routing class (or classes).This causes two problems:</p> <ul> <li>confusion: it makes harder to find where the "real work" begins in the application</li> <li>coupling: your router ends up chained to that specific interpretation of MVC-like architecture</li> </ul> <p>Routing is a task which even in custom-written application will naturally gravitate toward the "framework-ish" part of codebase.</p> <p>The (really) simplified versions would look like:</p> <pre><code>$matches = $router-&gt;parse( $url ); $controller = new {'\\Controller\\'.$matches['controller']}; $controller-&gt;{$matches['action']( $matches ); </code></pre> <p>This way there is nothing that requires your routing results to be used in some MVC-like architecture. Maybe you just need a glorified fetching mechanism for serving static HTML files.</p> <h2>What about those dynamically extend categories?</h2> <p>You are looking at it the wrong way. <strong>There is no need for dynamically adding methods to controller.</strong> In your example there is actually one controller method ... something along the lines of:</p> <pre><code>public function getCategory( $request ) { $category = $request-&gt;getParameter('category'); // ... rest of your controller method's code } </code></pre> <p>Where <code>$category</code> would end up containing <code>"cosplay"</code>, <code>"game"</code>, <code>"movie"</code>, <code>"series"</code> or any other category that you have added. It is something that your controller would pass to the model layer, to filter out articles.</p> <h2>What people actually use professionally?</h2> <p>These days, since everyone (well .. everyone with some clue) uses <a href="https://getcomposer.org" rel="noreferrer">composer</a>, for autoloading the best option is to use the loader that is comes bundled with composer.</p> <p>You simply add <code>require __DIR__ . '/vendor/autoload.php'</code> and with some configuration it will just work. </p> <p>As for routing, there are two major "standalone" solutions: <a href="https://github.com/nikic/FastRoute" rel="noreferrer">FastRoute</a> or <a href="http://symfony.com/doc/current/components/routing.html" rel="noreferrer">Symfony's Routing Component</a>. These ones can be included in you project without additional headaches. </p> <p>But since some of people will be using frameworks, each of those will also contain capability of routing the requests.</p> <h2>Some further reading ..</h2> <p>If you want to learn more about MVC architectural pattern, I would strongly recommend for you to go though all the materials listed in <a href="https://stackoverflow.com/a/16356866/727208"><strong>this post</strong></a>. Think of it as mandatory reading/watching list. You also might find somewhat beneficial these old posts of mine on the MVC related subjects: <a href="https://stackoverflow.com/a/5864000/727208">here</a>, <a href="https://stackoverflow.com/a/16596704/727208">here</a> and <a href="https://stackoverflow.com/a/13396866/727208">here</a></p> <blockquote> <p><sub><strong>P.S.:</strong> since PHP 5.0 was released (some time in 2004th), class's variables should be defined using <strong><code>public</code></strong>, <strong><code>private</code></strong> or <strong><code>protected</code></strong> instead of <strong><code>var</code></strong>. </sub></p> </blockquote>
27,507,678
In angular $http service, How can I catch the "status" of error?
<p>I'm reading a book called, "Pro Angular JS". However, I have a question about how to catch a status of error.</p> <p>What I coded is :</p> <pre><code>$http.get(dataUrl) .success(function (data){ $scope.data.products = data; }) .error(function (error){ $scope.data.error=error; console.log($scope.data.error.status); // Undefined! // (This is the spot that I don't get it.) }); </code></pre> <p>If I code "console.log($scope.data.error.status);" , why does the argument of console.log is undefined?</p> <p>In the book, there are sentence, "The object passed to the error function defines status and message properties."</p> <p>So I did $scope.data.error.status</p> <p>Why is it wrong?</p>
27,507,822
6
4
null
2014-12-16 15:08:53.29 UTC
11
2017-08-28 09:45:22.05 UTC
2017-08-28 09:45:22.05 UTC
user8317956
null
null
3,868,638
null
1
48
javascript|angularjs
110,452
<p>Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.</p> <p>Taken from the <a href="https://docs.angularjs.org/api/ng/service/$http">angular docs</a>:</p> <ul> <li>data – {string|Object} – The response body transformed with the transform functions. </li> <li>status – {number} – HTTP status code of the response.</li> <li>headers – {function([headerName])} – Header getter function.</li> <li>config – {Object} – The configuration object that was used to generate the request. </li> <li>statusText – {string} – HTTP status text of the response.</li> </ul> <p>So you'd need to change your code to:</p> <pre><code>$http.get(dataUrl) .success(function (data){ $scope.data.products = data; }) .error(function (error, status){ $scope.data.error = { message: error, status: status}; console.log($scope.data.error.status); }); </code></pre> <p>Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.</p>
5,027,403
Vim show strange  characters over putty
<p>When I am editing a file in Vim I have some lines with a bunch of  displayed.</p> <p>I have already checked the encoding with </p> <pre><code>:set encoding </code></pre> <p>It says utf8</p> <pre><code>encoding=utf8 </code></pre> <p>Anybody knows where this is comming from and how to stop this behaviour?</p> <p>Regards,</p> <p>Jeremy</p>
5,027,543
2
1
null
2011-02-17 09:59:29.577 UTC
10
2011-02-18 00:13:08.107 UTC
null
null
null
null
231,982
null
1
27
vim|encoding|character|putty
19,230
<p>Make sure that PuTTY is set for UTF-8 as well. You can do this under Window -> Translation -> Remote Character Set. You may need to choose a font that supports a reasonable portion of the Unicode range as well -- Terminal isn't necessarily going to cut it.</p>
787,776
Find free disk space in python on OS/X
<p>I'm looking for the number of free bytes on my HD, but have trouble doing so on python.</p> <p>I've tried the following:</p> <pre><code>import os stat = os.statvfs(path) print stat.f_bsize * stat.f_bavail </code></pre> <p>But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.</p> <p>What's the best way to get to this figure?</p>
787,832
7
1
null
2009-04-24 22:17:32.313 UTC
10
2015-07-19 10:57:34.693 UTC
2015-01-01 00:10:29.36 UTC
null
1,505,120
null
80,911
null
1
25
python|diskspace
33,614
<p>Try using <code>f_frsize</code> instead of <code>f_bsize</code>.</p> <pre><code>&gt;&gt;&gt; s = os.statvfs('/') &gt;&gt;&gt; (s.f_bavail * s.f_frsize) / 1024 23836592L &gt;&gt;&gt; os.system('df -k /') Filesystem 1024-blocks Used Available Capacity Mounted on /dev/disk0s2 116884912 92792320 23836592 80% / </code></pre>
1,096,862
Print directly from browser without print popup window
<p>As it said in the subject I've to create a feature for a web-based application that will allow users to send print directly without prompting any dialog boxe just make the print i.e click and print, simple! but not for me :(. </p> <p>Please, suggest what would be the best option and how should I write it up (technology).</p> <p>Suggest please!</p> <p>Thanks.</p> <p><strong>EDIT:</strong> The print should be send on the user's default printer.</p>
1,124,848
7
4
null
2009-07-08 08:40:55.717 UTC
12
2013-06-06 03:31:41.857 UTC
2009-07-22 05:26:22.173 UTC
null
134,743
null
134,743
null
1
25
browser|printing|activex|client-side
175,191
<blockquote> <p>I couldn't find solution for other browsers. When I posted this question, IE was on the higher priority and gladly I found one for it. If you have a solution for other browsers (firefox, safari, opera) please do share here. Thanks.</p> </blockquote> <p>VBSCRIPT is much more convenient than creating an ActiveX on VB6 or C#/VB.NET:</p> <pre><code>&lt;script language='VBScript'&gt; Sub Print() OLECMDID_PRINT = 6 OLECMDEXECOPT_DONTPROMPTUSER = 2 OLECMDEXECOPT_PROMPTUSER = 1 call WB.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER,1) End Sub document.write "&lt;object ID='WB' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'&gt;&lt;/object&gt;" &lt;/script&gt; </code></pre> <p>Now, calling:</p> <pre><code>&lt;a href="javascript:window.print();"&gt;Print&lt;/a&gt; </code></pre> <p>will send print without popup print window.</p>
1,002,073
an array of strings as a jQuery selector?
<p>I have an array of strings that are valid jQuery selectors (i.e. IDs of elements on the page): </p> <pre><code>["#p1", "#p2", "#p3", "#p4", "#p5"] </code></pre> <p>I want to select elements with those IDs into a jQuery array. This is probably elementary, but I can't find anything online. I could have a for-loop which creates a string <code>"#p1,#p2,#p3,#p4,#p5"</code> which could then be passed to jQuery as a single selector, but isn't there another way? Isn't there a way to pass an array of strings as a selector?</p> <p><strong>EDIT:</strong> Actually, there is <a href="https://stackoverflow.com/questions/201724/easy-way-to-turn-javascript-array-into-comma-separated-list/201733">an answer out there already</a>.</p>
1,002,099
7
0
null
2009-06-16 15:03:05.313 UTC
10
2022-08-27 15:52:58.257 UTC
2017-05-23 11:54:39.773 UTC
null
-1
null
65,232
null
1
34
javascript|jquery
33,466
<p>Well, there's 'join':</p> <pre><code>["#p1", "#p2", "#p3", "#p4", "#p5"].join(", ") </code></pre> <p>EDIT - Extra info:</p> <p>It is possible to select an array of elements, problem is here you don't have the elements yet, just the selector strings. Any way you slice it you're gonna have to execute a search like .getElementById or use an actual jQuery select.</p>
560,811
How To Use DateTimePicker In WPF?
<p>I have no idea how to use the DateTimePicker control in WPF. It is not available in the Toolbox.</p>
560,824
8
0
null
2009-02-18 12:14:24.377 UTC
6
2021-09-19 08:17:38.767 UTC
2012-05-10 13:55:35.917 UTC
John
72,882
Saransh
null
null
1
26
wpf|datetimepicker
113,085
<p><strong>Please Note:</strong> The following answer only applied to WPF under the 3.5 Framework as NET 4.0 runtime has it's own <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.datepicker.aspx" rel="nofollow noreferrer">datetime control</a>.</p> <p>By default WPF 3.5 does not come with a date time picker like winforms.</p> <p>However a date picker has been added in the <a href="http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=22567" rel="nofollow noreferrer">WPF tool kit</a> produced by Microsoft which can be <a href="http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=22567" rel="nofollow noreferrer">downloaded here</a>. I guess it will become part of the framework in a future release.</p> <p>It is simple to add a reference to the WPFToolkit.dll, see it in the tool box and distribute with your application by following the instructions on the website.</p> <p>Before this was available other people had created 3rd party pickers (which you may prefer) or alternatively used the less ideal solution of using the winforms control in a WPF application.</p> <p><strong>Update:</strong> This so question is very similar <a href="https://stackoverflow.com/questions/534845/does-anyone-have-a-wpf-net-3-0-date-picker">this one</a> which also has a link to a <a href="http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx" rel="nofollow noreferrer">walk through for the datepicker</a> along with other links.</p>
80,084
In Javascript, why is the "this" operator inconsistent?
<p>In JavaScript, the "this" operator can refer to different things under different scenarios. </p> <p>Typically in a method within a JavaScript "object", it refers to the current object.</p> <p>But when used as a callback, it becomes a reference to the calling object.</p> <p>I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.</p> <p>Can someone clarify usage and best practices regarding how to get around this problem?</p> <pre><code> function TestObject() { TestObject.prototype.firstMethod = function(){ this.callback(); YAHOO.util.Connect.asyncRequest(method, uri, callBack); } TestObject.prototype.callBack = function(o){ // do something with "this" //when method is called directly, "this" resolves to the current object //when invoked by the asyncRequest callback, "this" is not the current object //what design patterns can make this consistent? this.secondMethod(); } TestObject.prototype.secondMethod = function() { alert('test'); } } </code></pre>
80,127
8
1
null
2008-09-17 04:46:25.487 UTC
28
2018-11-15 19:30:14.077 UTC
2008-09-17 05:13:28.073 UTC
JasonBunting
1,790
Chris
null
null
1
30
javascript
11,707
<p>In JavaScript, <code>this</code> always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, <code>this</code> will refer to the node that fired the event. But if you have an object and call a function on it like:</p> <pre><code>myObject.myFunction(); </code></pre> <p>Then <code>this</code> inside <code>myFunction</code> will refer to <code>myObject</code>. Does it make sense?</p> <p>To get around it you need to use closures. You can change your code as follows:</p> <pre><code>function TestObject() { TestObject.prototype.firstMethod = function(){ this.callback(); YAHOO.util.Connect.asyncRequest(method, uri, callBack); } var that = this; TestObject.prototype.callBack = function(o){ that.secondMethod(); } TestObject.prototype.secondMethod = function() { alert('test'); } } </code></pre>
535,056
How to get started with version control and PHP
<p>I have absolutely no idea about version control. Only that it can be very useful in many ways. </p> <p>I have found a few related questions but none that start from the absolute beginning.</p> <p>I am the only developer at my work using Mac OS X and traditionally just been using FTP.</p> <p>Can anyone help me with version control in relation to PHP projects (does it matter)?</p>
535,244
9
2
null
2009-02-11 01:21:04.037 UTC
14
2014-07-18 00:50:20.813 UTC
2014-07-18 00:50:20.813 UTC
alex
31,671
alex
31,671
null
1
35
php|version-control
23,110
<p>Yes, try it out, it's worth it. And the language you are using doesn't matter. It's working great with PHP for me and it will for you too.</p> <p><strong>Benefits</strong></p> <p>If you are the only developer, it is indeed easier to go without version control. However, you will find great benefits to using a version control system. Some of the easiest benefits will be:</p> <ol> <li>Never wondering what is your latest version once you go back to a project (no more myproject090201-archive2-final6.zip)</li> <li>Never fear to start off some major refactoring, if you make a mistake on your file, you'll just rollback to the latest version</li> <li>If something stops working in your project and you have the feeling it worked at one point, you can test some of the prior versions easily and look at the difference between the working version and the non-working version to find what broke the code</li> <li>Additional backup of your current project, and even better if it's not on your machine... of course, additional points for backing up your version control system, we're never too cautious, you don't want to have to restart that month-long project do you?</li> </ol> <p><strong>Choices</strong></p> <p>As some have said, you have a few choices for your version control system and I guess you'll want a free one to begin. There are a few excellent commercial products but the free ones have nothing to be ashamed of. So here are some very popular free version control systems:</p> <ul> <li><a href="http://subversion.tigris.org/" rel="noreferrer">Subversion</a> (also called SVN)</li> <li><a href="http://git-scm.com/" rel="noreferrer">Git</a></li> <li><a href="http://www.selenic.com/mercurial/wiki/" rel="noreferrer">Mercurial</a></li> <li><a href="http://bazaar-vcs.org/" rel="noreferrer">Bazaar</a></li> </ul> <p><strong>Centralized versus distributed</strong></p> <p>Subversion has been there for a while and it's one classified as 'centralized'. Meaning everyone will always go fetch the latest version and commit their latest work to one central system, often on another system although it can easily be on your own machine. It's a process easy to understand.</p> <p>The three others are called 'distributed'. There's a lot of different possible processes as it's a more flexible system and that's why those three newcomers are getting a lot of traction these days in open source projects where a lot of people are interacting with one another. Basically you are working with your own revisions on your own machine, making as many copies as you need and deciding which versions you share with other people on other computers.</p> <p>The trend definitely seems go towards distributed system but as those systems are more recent, they are still missing the GUI tools that makes it really user friendly to use and you might sometimes find the documentation to be a bit lighter. On the other hand, this all seems to be getting corrected quickly.</p> <p>In your case, as you are working alone, it probably won't make a big difference, and although you'll hear very good points for centralized and distributed systems, you'll be able to work with one or the other without any problems.</p> <p><strong>Tools</strong></p> <p>If you absolutely need a GUI tool for your Mac, I'd then choose SVN to get initiated to source control. There are two very good products for that (commercial):</p> <ul> <li><a href="http://versionsapp.com/" rel="noreferrer">Versions</a></li> <li><a href="http://www.zennaware.com/cornerstone/" rel="noreferrer">Cornerstone</a></li> </ul> <p>And a few <a href="http://osx.iusethis.com/tag/subversion" rel="noreferrer">other ones</a> (such as the free <a href="http://www.lachoseinteractive.net/en/community/subversion/svnx/features/" rel="noreferrer">svnX</a>) that are becoming a little bit old and unfriendly in my opinion but that might be interesting trying anyway.</p> <p>If you don't mind not using the GUI tools, with the help of Terminal you'll be able to do all the same things with a few simple command lines with any of the aforementioned systems.</p> <p><strong>Starting points</strong></p> <p>In any cases, you'll want some starting points.</p> <ul> <li><p>For Subversion, your first stop must be their free book, <a href="http://svnbook.red-bean.com/" rel="noreferrer">Version Control with Subversion</a>. Take a few hours of your day to go through the chapters, it'll be time well invested. The introduction chapters are a good read even you don't want to use Subversion specifically because it'll get you to understand version control a little bit better.</p></li> <li><p>For a distributed system, I've had fun with Mercurial but it's an easily flammable subject so I'll let you make your own choice there. But if you end up looking at Mercurial, have a look at <a href="http://blog.medallia.com/2007/02/a_guided_tour_of_mercurial.html" rel="noreferrer">this blog post</a>, it was an excellent starter for me that'll get you up and running with the basics in a few minutes if you're already a bit accustomed to version control in general. Anyway, drop by <a href="http://www.selenic.com/mercurial/wiki/" rel="noreferrer">Mercurial's homepage</a> and have a look at the Getting Started section of the page.</p></li> </ul> <p><strong>Conclusion</strong></p> <p>Give it a go, invest a day trying it out with a few bogus files. Try out renaming files and directory, erasing, moving things around, committing binary files versus text files, resolving conflicts and reverting to older versions to get a hang of it. These are often the first few hurdles you'll encounter when playing with version control and it'll be painless if it's on a non-production project.</p> <p>In any cases, it's something well-worth learning that'll be helpful with your solo projects as well as if you end up working with other developers at your current job or your next one.</p> <p>Good luck!</p>
140,550
What is the best way to store a large amount of text in a SQL server table?
<p>What is the best way to store a large amount of text in a table in SQL server?</p> <p>Is varchar(max) reliable?</p>
140,558
9
0
null
2008-09-26 16:28:22.07 UTC
4
2022-09-22 16:17:53.997 UTC
2008-09-26 16:55:40.583 UTC
Rich B
5,640
Bruno
17,648
null
1
51
sql-server
109,583
<p>In SQL 2005 and higher, VARCHAR(MAX) is indeed the preferred method. The TEXT type is still available, but primarily for backward compatibility with SQL 2000 and lower.</p>
433,302
Convert a String to Variable
<p>I've got a multidimensional associative array which includes an elements like</p> <pre><code>$data["status"] $data["response"]["url"] $data["entry"]["0"]["text"] </code></pre> <p>I've got a strings like:</p> <pre><code>$string = 'data["status"]'; $string = 'data["response"]["url"]'; $string = 'data["entry"]["0"]["text"]'; </code></pre> <p>How can I convert the strings into a variable to access the proper array element? This method will need to work across any array at any of the dimensions.</p>
433,316
10
0
null
2009-01-11 17:52:30.64 UTC
11
2022-01-04 17:09:27.223 UTC
2011-05-25 11:21:02.04 UTC
null
560,648
Gilean
6,305
null
1
20
php|arrays|string|variables
81,947
<p>Quick and dirty: </p> <pre><code>echo eval('return $'. $string . ';'); </code></pre> <p>Of course the input string would need to be be sanitized first.</p> <p>If you don't like quick and dirty... then this will work too and it doesn't require eval which makes even me cringe.</p> <p>It does, however, make assumptions about the string format:</p> <pre><code>&lt;?php $data['response'] = array( 'url' =&gt; 'http://www.testing.com' ); function extract_data($string) { global $data; $found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches); if (!$found_matches) { return null; } $current_data = $data; foreach ($matches[1] as $name) { if (key_exists($name, $current_data)) { $current_data = $current_data[$name]; } else { return null; } } return $current_data; } echo extract_data('data["response"]["url"]'); ?&gt; </code></pre>
175,881
SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails
<p>When I try to install a new instance of SQL Server 2008 Express on a development machine with SQL 2005 Express already up and running, the install validation fails because the "SQL 2005 Express tools" are installed and I'm told to remove them.</p> <p><strong>What exactly does that mean?</strong> </p> <p>After reading this article:</p> <p><a href="http://www.asql.biz/Articoli/SQLX08/Art1_5.aspx" rel="noreferrer">http://www.asql.biz/Articoli/SQLX08/Art1_5.aspx</a> </p> <p>I uninstalled the 2005 version of the SQL Management Studio but received the same error from the 2008 installer during my follow-up attempt.</p> <p><strong>Updates</strong></p> <p>1) Uninstalled the SQL 2005 Management Studio only. Received the same error from the 2008 install.</p> <p>2) Removed all SQL 2005 common components. Received the same error from the 2008 install.</p> <p>3) Installed the shared components from the SQL 2008 installation program. Received the same error from the 2008 install when trying to install the new SQL 2008 instance.</p> <p>4) Uninstalled SQL 2008 components, rebooted, re-installed SQL 2005 Management Studio from installation media, rebooted, un-installed SQL 2005 Workstation Components from Control Panel, re-booted.</p> <p>Installation of SQL 2008 is now proceeding as it should.</p> <p>Seems likely that if I'd re-booted after update 2 above things would have gone more smoothly. :-(</p>
175,894
10
1
null
2008-10-06 19:46:38.027 UTC
11
2014-12-14 23:35:23.087 UTC
2008-10-07 13:59:20.69 UTC
marc
12,260
marc
12,260
null
1
41
sql-server
101,993
<p>Although you should have no problem running a 2005 instance of the database engine beside a 2008 instance, The tools are installed into a shared directory, so you can't have two versions of the tools installed. Fortunately, the 2008 tools are backwards-compatible. As we speak, I'm using SSMS 2008 and Profiler 2008 to manage my 2005 Express instances. Works great.</p> <p>Before installing the 2008 tools, you need to remove any and all "shared" components from 2005. Try going to your Add/Remove programs control panel, find Microsoft SQL Server 2005, and click "Change." Then choose "Workstation Components" and remove everything there (this will not remove your database engine).</p> <p>I believe the 2008 installer also has an option to upgrade shared components only. You might try that. Good luck!</p>
805,720
Newbie teaching self python, what else should I be learning?
<p>I'm a newbie to programming. I had 1 semester of computer science (we used java). I got an A in the course and was able to do everything assigned, however I'm not sure I really understood it. I ignored the text and learned by looking at sample programs and then trial and error. I was ahead of the class except for two guys who came in knowing java or another OOP language.</p> <p>I'd like to learn Python. I'm also going to build a second PC from extra parts I have and use linux. Basically, I want to enhance my knowledge of computers. Thats my motivation.</p> <p>Now on learning python are there any good programming theory books that would be useful? Or should I read up on more on how computers operate on the lowest levels? I don't think I know enough to ask the question I want. </p> <p>I guess to make it simple, I am asking what should I know to make the most of learning python. This is not for a career. This is from a desire to know. I am no longer a computer science major (it also would not have any direct applications to my anticipated career.)</p> <p>I'm not looking to learn in "30 days" or "1 week" or whatever. So, starting from a very basic level is fine with me. </p> <p>Thanks in advance. I did a search and didn't quite find what I was looking for. </p> <p>UPDATE: Thanks for all the great advice. I found this site at work and couldn't find it on my home computer, so I am just getting to read now. </p>
805,775
11
0
null
2009-04-30 07:08:06.503 UTC
9
2013-10-22 08:10:45.693 UTC
2009-08-05 18:40:39.41 UTC
null
120,888
null
98,312
null
1
10
python|theory
3,411
<p>My recommendation is always to start at the high level of abstraction. You don't need to know how logic gates work and how you can use them to build a CPU -- it's cool stuff, but it's cool stuff that makes a <em>lot</em> more sense once you've messed around at the higher levels. Python is therefore an excellent choice as a learning aid.</p> <p><a href="http://www.greenteapress.com/thinkpython/thinkCSpy/" rel="nofollow noreferrer">How to Think Like A Computer Scientist: Learning With Python</a> is available on the Internet and is an excellent introduction to the high-level concepts that make computers go. And it's even Python-specific.</p> <p>If you're looking to have your brain turned inside-out, <a href="http://mitpress.mit.edu/sicp/full-text/book/book.html" rel="nofollow noreferrer">SICP</a> will do a good job of it. I don't recommend it as a first text, though; it's heavy going.</p> <p>Both of these books are high-level. They won't teach you anything about the low-level details like memory structures or what a CPU actually does, but that's something I would reserve for later anyway.</p> <p>D'A</p>
409,256
Working with byte arrays in C#
<p>I have a byte array that represents a complete TCP/IP packet. For clarification, the byte array is ordered like this:</p> <p>(IP Header - 20 bytes)(TCP Header - 20 bytes)(Payload - X bytes)</p> <p>I have a <code>Parse</code> function that accepts a byte array and returns a <code>TCPHeader</code> object. It looks like this:</p> <pre><code>TCPHeader Parse( byte[] buffer ); </code></pre> <p>Given the original byte array, here is the way I'm calling this function right now.</p> <pre><code>byte[] tcpbuffer = new byte[ 20 ]; System.Buffer.BlockCopy( packet, 20, tcpbuffer, 0, 20 ); TCPHeader tcp = Parse( tcpbuffer ); </code></pre> <p>Is there a convenient way to pass the TCP byte array, i.e., bytes 20-39 of the complete TCP/IP packet, to the <code>Parse</code> function without extracting it to a new byte array first?</p> <p>In C++, I could do the following:</p> <pre><code>TCPHeader tcp = Parse( &amp;packet[ 20 ] ); </code></pre> <p>Is there anything similar in C#? I want to avoid the creation and subsequent garbage collection of the temporary byte array if possible.</p>
409,269
11
2
null
2009-01-03 16:00:03.28 UTC
4
2018-01-29 02:01:21.873 UTC
2011-05-26 18:27:22.053 UTC
Matt Davis
50,776
Matt Davis
51,170
null
1
13
c#|.net|networking|.net-3.5|bytearray
44,010
<p>A common practice you can see in the .NET framework, and that I recommend using here, is specifying the offset and length. So make your Parse function also accept the offset in the passed array, and the number of elements to use.</p> <p>Of course, the same rules apply as if you were to pass a pointer like in C++ - the array shouldn't be modified or else it may result in undefined behavior if you are not sure when exactly the data will be used. But this is no problem if you are no longer going to be modifying the array.</p>
1,068,881
jQuery remove HTML table column
<p>I have a HTML table like this: </p> <pre><code>&lt;table border="1"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;a href="#" class="delete"&gt;DELETE ROW&lt;/a&gt;COL 1&lt;/td&gt; &lt;td&gt;&lt;a href="#" class="delete"&gt;DELETE COL&lt;/a&gt;COL 2&lt;/td&gt; &lt;td&gt;&lt;a href="#" class="delete"&gt;DELETE COL&lt;/a&gt;COL 3&lt;/td&gt; &lt;td&gt;&lt;a href="#" class="delete"&gt;DELETE COL&lt;/a&gt;COL 4&lt;/td&gt; &lt;td&gt;&lt;a href="#" class="delete"&gt;DELETE COL&lt;/a&gt;COL 5&lt;/td&gt; &lt;td&gt;&lt;a href="#" class="delete"&gt;DELETE COL&lt;/a&gt;COL 6&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;ROW 1&lt;/td&gt; &lt;td&gt;ROW 1&lt;/td&gt; &lt;td&gt;ROW 1&lt;/td&gt; &lt;td&gt;ROW 1&lt;/td&gt; &lt;td&gt;ROW 1&lt;/td&gt; &lt;td&gt;ROW 1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;ROW 2&lt;/td&gt; &lt;td&gt;ROW 2&lt;/td&gt; &lt;td&gt;ROW 2&lt;/td&gt; &lt;td&gt;ROW 2&lt;/td&gt; &lt;td&gt;ROW 2&lt;/td&gt; &lt;td&gt;ROW 2&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I need a function to remove the specified column when I click on the link with the class "delete". Can you help ? </p>
1,068,902
11
0
null
2009-07-01 12:25:57.007 UTC
12
2016-09-29 16:01:36.123 UTC
2016-09-29 16:01:36.123 UTC
null
4,370,109
null
56,409
null
1
24
jquery|html-table
73,105
<p>After a few years, it's probably time to update the answer on this question.</p> <pre><code>// Listen for clicks on table originating from .delete element(s) $("table").on("click", ".delete", function ( event ) { // Get index of parent TD among its siblings (add one for nth-child) var ndx = $(this).parent().index() + 1; // Find all TD elements with the same index $("td", event.delegateTarget).remove(":nth-child(" + ndx + ")"); }); </code></pre>
127,477
Detecting WPF Validation Errors
<p>In WPF you can setup validation based on errors thrown in your Data Layer during Data Binding using the <code>ExceptionValidationRule</code> or <code>DataErrorValidationRule</code>.</p> <p>Suppose you had a bunch of controls set up this way and you had a Save button. When the user clicks the Save button, you need to make sure there are no validation errors before proceeding with the save. If there are validation errors, you want to holler at them.</p> <p>In WPF, how do you find out if any of your Data Bound controls have validation errors set?</p>
4,650,392
11
0
null
2008-09-24 14:22:10.7 UTC
53
2022-09-01 19:33:29.767 UTC
2015-04-22 11:17:24.12 UTC
null
1,468,295
Kevin Berridge
4,407
null
1
120
wpf|validation|data-binding
66,921
<p>This post was extremely helpful. Thanks to all who contributed. Here is a LINQ version that you will either love or hate.</p> <pre><code>private void CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = IsValid(sender as DependencyObject); } private bool IsValid(DependencyObject obj) { // The dependency object is valid if it has no errors and all // of its children (that are dependency objects) are error-free. return !Validation.GetHasError(obj) &amp;&amp; LogicalTreeHelper.GetChildren(obj) .OfType&lt;DependencyObject&gt;() .All(IsValid); } </code></pre>
664,432
How do I programmatically change file permissions?
<p>In Java, I'm dynamically creating a set of files and I'd like to change the file permissions on these files on a linux/unix file system. I'd like to be able to execute the Java equivalent of <code>chmod</code>. Is that possible Java 5? If so, how?</p> <p>I know in Java 6 the <code>File</code> object has <code>setReadable()</code>/<code>setWritable()</code> methods. I also know I could make a system call to do this, but I'd like to avoid that if possible. </p>
664,443
11
1
null
2009-03-19 23:21:21.833 UTC
37
2021-02-03 14:55:50.183 UTC
2018-05-09 08:43:17.253 UTC
Roy Rico
1,685,157
Roy Rico
1,580
null
1
143
java|filesystems
210,477
<p>Full control over file attributes is available in Java 7, as part of the "new" New IO facility (<a href="http://jcp.org/en/jsr/detail?id=203" rel="noreferrer">NIO.2</a>). For example, POSIX permissions can be set on an existing file with <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#setPosixFilePermissions%28java.nio.file.Path,%20java.util.Set%29" rel="noreferrer"><code>setPosixFilePermissions()</code>,</a> or atomically at file creation with methods like <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createFile(java.nio.file.Path,%20java.nio.file.attribute.FileAttribute...)" rel="noreferrer"><code>createFile()</code></a> or <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newByteChannel(java.nio.file.Path,%20java.util.Set,%20java.nio.file.attribute.FileAttribute...)" rel="noreferrer"><code>newByteChannel()</code>.</a></p> <p>You can create a set of permissions using <code>EnumSet.of()</code>, but the helper method <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFilePermissions.html#fromString(java.lang.String)" rel="noreferrer"><code>PosixFilePermissions.fromString()</code></a> will uses a conventional format that will be more readable to many developers. For APIs that accept a <code>FileAttribute</code>, you can wrap the set of permissions with with <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFilePermissions.html#asFileAttribute(java.util.Set)" rel="noreferrer"><code>PosixFilePermissions.asFileAttribute()</code>.</a></p> <pre><code>Set&lt;PosixFilePermission&gt; ownerWritable = PosixFilePermissions.fromString("rw-r--r--"); FileAttribute&lt;?&gt; permissions = PosixFilePermissions.asFileAttribute(ownerWritable); Files.createFile(path, permissions); </code></pre> <p>In earlier versions of Java, using native code of your own, or <code>exec</code>-ing command-line utilities are common approaches.</p>
201,893
WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance
<p>I'm working to set up Panda on an Amazon EC2 instance. I set up my account and tools last night and had no problem using SSH to interact with my own personal instance, but right now I'm not being allowed permission into Panda's EC2 instance. <a href="http://pandastream.com/docs/getting_started" rel="noreferrer">Getting Started with Panda</a></p> <p>I'm getting the following error:</p> <pre><code>@ WARNING: UNPROTECTED PRIVATE KEY FILE! @ Permissions 0644 for '~/.ec2/id_rsa-gsg-keypair' are too open. It is recommended that your private key files are NOT accessible by others. This private key will be ignored. </code></pre> <p>I've chmoded my keypair to 600 in order to get into my personal instance last night, and experimented at length setting the permissions to 0 and even generating new key strings, but nothing seems to be working.</p> <p>Any help at all would be a great help!</p> <hr> <p>Hm, it seems as though unless permissions are set to 777 on the directory, the ec2-run-instances script is unable to find my keyfiles. I'm new to SSH so I might be overlooking something.</p>
217,729
12
5
null
2008-10-14 16:31:01.35 UTC
49
2022-01-12 17:33:01.347 UTC
2013-02-28 08:03:04.117 UTC
Stu Thompson
650,722
Bryan Woods
2,293
null
1
237
ssh|amazon-web-services|amazon-ec2|chmod
220,917
<blockquote> <p>I've chmoded my keypair to 600 in order to get into my personal instance last night,</p> </blockquote> <p>And this is the way it is supposed to be. </p> <p>From the <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html" rel="noreferrer">EC2 documentation</a> we have <em>"If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you."</em> The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.</p> <p>The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.</p> <p>Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.</p> <p>Any problems you are having are client side, so be sure to include local OS information with any follow up questions! </p>
463,642
How can I convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?
<p>How can I convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?</p> <p>Let's say I have 80 seconds; are there any specialized classes/techniques in .NET that would allow me to convert those 80 seconds into (00h:00m:00s:00ms) format like <code>Convert.ToDateTime</code> or something?</p>
463,668
13
0
null
2009-01-21 00:10:42.95 UTC
57
2022-04-06 22:40:29.04 UTC
2022-04-06 22:40:29.04 UTC
null
17,142,802
John Gates
null
null
1
339
c#|datetime
392,195
<p>For <strong>.Net &lt;= 4.0</strong> Use the TimeSpan class.</p> <pre><code>TimeSpan t = TimeSpan.FromSeconds( secs ); string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", t.Hours, t.Minutes, t.Seconds, t.Milliseconds); </code></pre> <p>(As noted by Inder Kumar Rathore) For <strong>.NET > 4.0</strong> you can use</p> <pre><code>TimeSpan time = TimeSpan.FromSeconds(seconds); //here backslash is must to tell that colon is //not the part of format, it just a character that we want in output string str = time .ToString(@"hh\:mm\:ss\:fff"); </code></pre> <p>(From Nick Molyneux) Ensure that seconds is less than <code>TimeSpan.MaxValue.TotalSeconds</code> to avoid an exception.</p>
1,063,497
Hidden Features of Erlang
<p>In the spirit of:</p> <ul> <li>Hidden Features of C#</li> <li>Hidden Features of Java</li> <li>Hidden Features of ASP.NET</li> <li>Hidden Features of Python</li> <li>Hidden Features of HTML</li> <li>and other Hidden Features questions</li> </ul> <p>What are the hidden features of Erlang that every Erlang developer should be aware of?</p> <p>One hidden feature per answer, please.</p>
1,064,479
17
3
2009-07-28 16:20:36.093 UTC
2009-06-30 12:52:10.173 UTC
59
2011-02-28 11:17:02.14 UTC
2009-12-14 21:11:38.693 UTC
null
13,531
null
64,253
null
1
17
erlang|hidden-features
10,482
<p>The magic commands in the shell. The full list is in <a href="http://www.erlang.org/doc/man/shell.html" rel="nofollow noreferrer">the manual</a>, but the ones I use most are:</p> <ul> <li>f() - forget all variables</li> <li>f(X) - forget X</li> <li>v(42) - recall result from line 42</li> <li>v(-1) - recall result from previous line</li> <li>e(-1) - reexecute expression on previous line</li> <li>rr(foo) - read record definitions from module foo</li> <li>rr("*/*") - read record definitions from every module in every subdirectory</li> <li>rp(<em>expression</em>) - print full expression with record formating</li> </ul>
122,407
What's the nearest substitute for a function pointer in Java?
<p>I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?</p>
122,414
22
6
null
2008-09-23 17:20:10.7 UTC
119
2020-09-07 11:54:54.703 UTC
2012-07-09 16:47:43.637 UTC
null
1,288
Bill the Lizard
1,288
null
1
306
java|closures|function-pointers
91,211
<p>Anonymous inner class</p> <p>Say you want to have a function passed in with a <code>String</code> param that returns an <code>int</code>.<br> First you have to define an interface with the function as its only member, if you can't reuse an existing one.</p> <pre><code>interface StringFunction { int func(String param); } </code></pre> <p>A method that takes the pointer would just accept <code>StringFunction</code> instance like so:</p> <pre><code>public void takingMethod(StringFunction sf) { int i = sf.func("my string"); // do whatever ... } </code></pre> <p>And would be called like so:</p> <pre><code>ref.takingMethod(new StringFunction() { public int func(String param) { // body } }); </code></pre> <p><em>EDIT:</em> In Java 8, you could call it with a lambda expression:</p> <pre><code>ref.takingMethod(param -&gt; bodyExpression); </code></pre>
436,014
Why should I use templating system in PHP?
<p>Why should I use templating system in PHP?</p> <p>The reasoning behind my question is: PHP itself is feature rich templating system, why should I install another template engine?</p> <p>The only two pros I found so far are:</p> <ol> <li>A bit cleaner syntax (sometimes)</li> <li>Template engine is not usually powerful enough to implement business logic so it forces you to separate concerns. Templating with PHP can lure you to walk around the templating principles and start writing code soup again.</li> </ol> <p>... and both are quite negligible when compared to cons.</p> <p>Small example:</p> <p><strong>PHP</strong></p> <pre><code>&lt;h1&gt;&lt;?=$title?&gt;&lt;/h1&gt; &lt;ul&gt; &lt;? foreach ($items as $item) {?&gt; &lt;li&gt;&lt;?=$item?&gt;&lt;/li&gt; &lt;? } ?&gt; &lt;/ul&gt; </code></pre> <p><strong>Smarty</strong></p> <pre><code>&lt;h1&gt;{$title}&lt;/h1&gt; &lt;ul&gt; {foreach item=item from=$items} &lt;li&gt;{$item}&lt;/li&gt; {/foreach} &lt;/ul&gt; </code></pre> <p>I really don't see any difference at all.</p>
436,055
25
4
null
2009-01-12 16:37:12.68 UTC
27
2020-01-04 13:30:56.893 UTC
2016-12-21 14:48:50.59 UTC
JS
53,864
JS
53,864
null
1
61
php|smarty|template-engine
13,592
<p>Yes, as you said, if you don't force yourself to use a templating engine inside PHP ( the templating engine ) it becomes easy to slip and stop separating concerns. </p> <p><strong>However</strong>, the same people who have problems separating concerns end up generating HTML and feeding it to smarty, or executing PHP code in Smarty, so Smarty's hardly solving your concern separation problem. </p> <p>See also:</p> <ul> <li><a href="https://stackoverflow.com/questions/62605/php-as-a-template-language-or-some-other-php-templating-script">PHP as a template language or some other templating script </a></li> <li><a href="https://stackoverflow.com/questions/261338/what-is-the-best-way-to-insert-html-via-php">What is the best way to insert HTML via PHP</a></li> </ul>
6,647,166
How do I pattern match arrays in Scala?
<p>My method definition looks as follows</p> <pre><code>def processLine(tokens: Array[String]) = tokens match { // ... </code></pre> <p>Suppose I wish to know whether the second string is blank</p> <pre><code>case "" == tokens(1) =&gt; println("empty") </code></pre> <p>Does not compile. How do I go about doing this?</p>
6,647,649
4
1
null
2011-07-11 07:49:04.99 UTC
10
2014-01-29 23:58:07.08 UTC
2011-07-11 19:10:48.243 UTC
null
65,299
null
144,152
null
1
74
scala
41,004
<p>If you want to pattern match on the array to determine whether the second element is the empty string, you can do the following:</p> <pre><code>def processLine(tokens: Array[String]) = tokens match { case Array(_, "", _*) =&gt; "second is empty" case _ =&gt; "default" } </code></pre> <p>The <code>_*</code> binds to any number of elements including none. This is similar to the following match on Lists, which is probably better known:</p> <pre><code>def processLine(tokens: List[String]) = tokens match { case _ :: "" :: _ =&gt; "second is empty" case _ =&gt; "default" } </code></pre>
6,833,558
Replace Console.WriteLine in NUnit
<p>I haven't done much with NUnit before, but I just wanted to dump some text to a window in a console type fashion. For example:</p> <pre class="lang-cs prettyprint-override"><code>Console.WriteLine(&quot;... some information...&quot;); </code></pre> <p>That won't work of course because NUnit is driving things.</p> <p>I'm in the middle of building some unit tests and want to dump a list of variable values for inspection during debug. It isn't strictly a unit test if I need to do this, I admit that, but it would be convenient.</p>
6,833,590
5
0
null
2011-07-26 16:43:56.19 UTC
8
2022-05-12 15:18:25.3 UTC
2020-12-30 00:08:47.57 UTC
null
1,402,846
null
685,711
null
1
60
c#|.net|debugging|nunit
57,610
<p>You can see the console output. You just have to select the &quot;Text Output&quot; tab in the NUnit GUI runner.</p> <p><img src="https://i.stack.imgur.com/vIjTv.png" alt="Enter image description here" /></p> <p>If you are using the ReSharper test runner, the console output should be displayed. Ensure that the test runner output window is displayed by clicking the <a href="https://www.jetbrains.com/help/resharper/Reference__Windows__Unit_Test_Sessions.html#showOutputRow-1-td-0-control" rel="nofollow noreferrer">&quot;Show Output&quot; button</a> in the test runner tool bar:</p> <p><img src="https://i.stack.imgur.com/wQWtf.png" alt="Enter image description here" /></p> <p>You should then get something as follows:</p> <p><img src="https://i.stack.imgur.com/TCqY1.png" alt="Enter image description here" /></p>
6,754,919
JSON.stringify function
<p>I have an object that has some properties and methods, like so:</p> <pre><code>{name: "FirstName", age: "19", load: function () {}, uniq: 0.5233059714082628} </code></pre> <p>and I have to pass this object to another function. So I tried to use JSON.stringify(obj) but the load function (which of course isn't empty, this is just for the purpose of this example) is being "lost".</p> <p>Is there any way to <code>stringify</code> and object and maintain the methods it has?</p> <p>Thanks!</p>
6,755,006
6
2
null
2011-07-19 22:34:07.193 UTC
14
2021-10-08 14:26:26.013 UTC
2015-09-30 12:34:27.137 UTC
null
3,154,233
null
848,941
null
1
42
javascript|json|object
46,684
<p>Why exactly do you want to stringify the object? JSON doesn't understand functions (and it's not supposed to). If you want to pass around objects why not do it one of the following ways?</p> <pre><code>var x = {name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628}; function y(obj) { obj.load(); } // works y({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628}); // "safer" y(({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628})); // how it's supposed to be done y(x); </code></pre>
6,747,176
How can I remove a background-image attribute?
<p>I have this code :</p> <pre><code>if (pansel.val() == "1") $(#myDiv).css('background-image', 'url(/private_images/guida_check_category.jpg)'); else $(#myDiv).css({ 'background-color': '#ffffff' }); </code></pre> <p>and I see that, when I apply the background-image, the follow code :</p> <pre><code>$(#myDiv).css({ 'background-color': '#ffffff' }); </code></pre> <p>doesnt remove the image and put the white background color. The image still present! </p> <p>How can I totally remove that background-image attribute?</p>
6,747,190
7
0
null
2011-07-19 12:33:11.973 UTC
null
2020-06-28 19:08:59.32 UTC
null
null
null
null
365,251
null
1
21
jquery|css
74,776
<p>Try this:</p> <pre><code>if (pansel.val() == "1") $("#myDiv").css('background-image', 'url(/private_images/guida_check_category.jpg)'); else { $("#myDiv").css({ 'background-color': '#ffffff' }); $("#myDiv").css('background-image', 'none'); } </code></pre>
6,800,894
Django returns 403 error when sending a POST request
<p>when I'm using following Python code to send a POST request to my Django website I'm getting 403: Forbidden error.</p> <pre><code>url = 'http://www.sub.example.com/' values = { 'var': 'test' } try: data = urllib.urlencode(values, doseq=True) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() except: the_page = sys.exc_info() raise </code></pre> <p>When I'm opening any other website it works properly. <code>example.com</code> is Django website too, and it works properly too. I think, that's Django config problem, can anyone tell me what should I do to provide access to my script?</p>
6,801,207
7
4
null
2011-07-23 14:04:54.67 UTC
11
2022-07-05 09:12:08.527 UTC
2022-07-05 09:12:08.527 UTC
null
1,145,388
null
855,472
null
1
49
python|django|http-status-code-403|http-post
83,268
<p>Does the view that you are posting to have a Django Form on it? If so, I wonder if it's giving a csrf error. I think that manifests itself as a 403. In that case, you'd need to add the {{ csrf_token }} tag. Just a thought. </p>
6,980,906
Android Color Picker
<p>I am looking for a Color Picker framework which can return color HEX on selection.</p> <p>I have looked at <a href="https://github.com/danielnilsson9/color-picker-view" rel="noreferrer">this</a> wondering if there is some other library I can use.</p>
6,981,145
8
0
null
2011-08-08 10:39:06.453 UTC
21
2021-06-12 09:50:29.373 UTC
2015-08-19 08:54:36.817 UTC
null
1,196,908
null
155,196
null
1
48
java|android|colors|picker
132,975
<p>try this open source projects that might help you</p> <p><a href="https://github.com/QuadFlask/colorpicker" rel="noreferrer">https://github.com/QuadFlask/colorpicker</a></p>
6,825,943
Difference between Console.Read() and Console.ReadLine()?
<p>I'm new to this field and I'm very confused: what is the real difference between <code>Console.Read()</code> and <code>Console.ReadLine()</code>?</p>
6,825,957
12
3
null
2011-07-26 06:05:49.843 UTC
17
2021-04-15 06:56:51.25 UTC
2014-01-29 13:51:36.71 UTC
null
114,770
null
709,458
null
1
38
c#|input|console|inputstream
200,295
<p><a href="http://msdn.microsoft.com/en-us/library/system.console.read.aspx" rel="noreferrer"><code>Console.Read()</code></a> reads only the next character from standard input, and <a href="http://msdn.microsoft.com/en-us/library/system.console.readline.aspx" rel="noreferrer"><code>Console.ReadLine()</code></a> reads the next line of characters from the standard input stream.</p> <p>Standard input in case of Console Application is input from the user typed words in console UI of your application. Try to create it by Visual studio, and see by yourself.</p>
6,811,372
How to code a BAT file to always run as admin mode?
<p>I have this line inside my BAT file:</p> <pre><code>"Example1Server.exe" </code></pre> <p>I would like to execute this in Administrator mode. How to modify the bat code to run this as admin?</p> <p>Is this correct? Do I need to put the quotes?</p> <pre><code>runas /user:Administrator invis.vbs Example1Server.exe </code></pre>
6,811,394
12
2
null
2011-07-25 02:51:29.8 UTC
53
2022-02-10 12:17:18.74 UTC
2011-07-25 02:59:25.157 UTC
null
192,173
null
192,173
null
1
181
windows|batch-file
806,918
<p>You use <code>runas</code> to launch a program as a specific user:</p> <pre><code>runas /user:Administrator Example1Server.exe </code></pre>
6,745,919
UITableViewCell subview disappears when cell is selected
<p>I'm implementing a color-chooser table view where the user can select amongst, say, 10 colors (depends on the product). The user can also select other options (like hard drive capacity, ...).</p> <p>All color options are inside their own tableview section.</p> <p>I want to display a little square on the left of the textLabel showing the actual color.</p> <p>Right now I'm adding a simple square UIView, give it the correct background color, like this :</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RMProductAttributesCellID]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:RMProductAttributesCellID] autorelease]; cell.indentationWidth = 44 - 8; UIView *colorThumb = [[[UIView alloc] initWithFrame:CGRectMake(8, 8, 28, 28)] autorelease]; colorThumb.tag = RMProductAttributesCellColorThumbTag; colorThumb.hidden = YES; [cell.contentView addSubview:colorThumb]; } RMProductAttribute *attr = (RMProductAttribute *)[_product.attributes objectAtIndex:indexPath.section]; RMProductAttributeValue *value = (RMProductAttributeValue *)[attr.values objectAtIndex:indexPath.row]; cell.textLabel.text = value.name; cell.textLabel.backgroundColor = [UIColor clearColor]; UIView *colorThumb = [cell viewWithTag:RMProductAttributesCellColorThumbTag]; colorThumb.hidden = !attr.isColor; cell.indentationLevel = (attr.isColor ? 1 : 0); if (attr.isColor) { colorThumb.layer.cornerRadius = 6.0; colorThumb.backgroundColor = value.color; } [self updateCell:cell atIndexPath:indexPath]; return cell; } </code></pre> <p>This displays fine without problems.</p> <p>My only problem is that when I select a "color" row, during the fade-to-blue selection animation, my custom UIView (colorThumb) is hidden. It gets visible again just after the selection/deselection animation ended, but this produces an ugly artifact.</p> <p>What should I do to correct this? Don't I insert the subview at the right place?</p> <p>(There's nothing special in the didSelectRowAtIndexPath, I just change the cell's accessory to a checkbox or nothing, and deselect the current indexPath).</p>
27,717,607
20
3
null
2011-07-19 10:45:07.3 UTC
47
2022-07-30 07:32:20.887 UTC
null
null
null
null
526,547
null
1
177
iphone|ios|uitableview
57,475
<p><code>UITableViewCell</code> changes the background color of all sub views when cell is selected or highlighted ,You can Solve this problem by overriding Tableview cell's <code>setSelected:animated</code> and <code>setHighlighted:animated</code> and resetting view background color.</p> <p><strong>In Objective C :</strong></p> <pre><code>- (void)setSelected:(BOOL)selected animated:(BOOL)animated { UIColor *color = self.yourView.backgroundColor; [super setSelected:selected animated:animated]; if (selected){ self.yourView.backgroundColor = color; } } -(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{ UIColor *color = self.yourView.backgroundColor; [super setHighlighted:highlighted animated:animated]; if (highlighted){ self.yourView.backgroundColor = color; } } </code></pre> <p><strong>In Swift 3.1 :</strong></p> <pre><code>override func setSelected(_ selected: Bool, animated: Bool) { let color = yourView.backgroundColor super.setSelected(selected, animated: animated) if selected { yourView.backgroundColor = color } } override func setHighlighted(_ highlighted: Bool, animated: Bool) { let color = yourView.backgroundColor super.setHighlighted(highlighted, animated: animated) if highlighted { yourView.backgroundColor = color } } </code></pre>
38,263,406
What are differences between SystemJS and Webpack?
<p>I'm creating my first Angular application and I would figure out what is the role of the module loaders. Why we need them? I tried to search and search on Google and I can't understand why we need to install one of them to run our application?</p> <p>Couldn't it be enough to just use <code>import</code> to load stuff from node modules?</p> <p>I have followed <a href="https://angular.io/docs/ts/latest/quickstart.html#!#systemjs" rel="noreferrer">this tutorial</a> (that uses SystemJS) and it makes me to use <code>systemjs.config.js</code> file:</p> <pre><code>/** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function(global) { // map tells the System loader where to look for things var map = { 'app': 'transpiled', // 'dist', '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', 'rxjs': 'node_modules/rxjs' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }, }; var ngPackageNames = [ 'common', 'compiler', 'core', 'forms', 'http', 'platform-browser', 'platform-browser-dynamic', 'router', 'router-deprecated', 'upgrade', ]; // Individual files (~300 requests): function packIndex(pkgName) { packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' }; } // Bundled (~40 requests): function packUmd(pkgName) { packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' }; } // Most environments should use UMD; some (Karma) need the individual index files var setPackageConfig = System.packageWithIndex ? packIndex : packUmd; // Add package entries for angular packages ngPackageNames.forEach(setPackageConfig); var config = { map: map, packages: packages }; System.config(config); })(this); </code></pre> <p>Why we need this configuration file?<br> Why we need SystemJS (or WebPack or others)?<br> Finally, in your opinion what is the better?</p>
38,263,593
3
2
null
2016-07-08 09:36:18.147 UTC
91
2021-11-29 23:31:06.057 UTC
2021-11-29 23:31:06.057 UTC
null
1,205,871
null
2,516,399
null
1
234
javascript|angular|webpack|node-modules|systemjs
98,625
<p>If you go to the SystemJS Github page, you will see the description of the tool:</p> <blockquote> <p>Universal dynamic module loader - loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS.</p> </blockquote> <p>Because you use modules in TypeScript or ES6, you need a module loader. In the case of SystemJS, the <code>systemjs.config.js</code> allows us to configure the way in which module names are matched with their corresponding files.</p> <p>This configuration file (and SystemJS) is necessary if you explicitly use it to import the main module of your application:</p> <pre><code>&lt;script&gt; System.import('app').catch(function(err){ console.error(err); }); &lt;/script&gt; </code></pre> <p>When using TypeScript, and configuring the compiler to the <code>commonjs</code> module, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:</p> <pre><code>{ "compilerOptions": { "target": "es5", "module": "commonjs", // &lt;------ "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false } } </code></pre> <p>Webpack is a flexible module bundler. This means that it goes further and doesn't only handle modules but also provides a way to package your application (concat files, uglify files, ...). It also provides a dev server with load reload for development.</p> <p>SystemJS and Webpack are different but with SystemJS, you still have work to do (with <a href="http://gulpjs.com/" rel="noreferrer">Gulp</a> or <a href="https://github.com/systemjs/builder" rel="noreferrer">SystemJS builder</a> for example) to package your Angular2 application for production.</p>
15,874,366
Could not load file or assembly 'System.Web.Razor' or one of its dependencies
<p>I used Umbraco 4.11.6 in my website(web application).My website is worked in localhost(tested from Visual studio 2012 and IIS(v7)) but when I run it from internet space I got an error. The error was:</p> <h2>Could not load file or assembly 'System.Web.Razor' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</h2> <blockquote> <p>Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Razor' could not be loaded.</p> <p><strong>WRN:</strong> Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].</p> </blockquote> <p>Stack Trace: </p> <blockquote> <blockquote> <p>[FileLoadException: Could not load file or assembly 'System.Web.Razor' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]</p> </blockquote> <p>[FileLoadException: Could not load file or assembly 'System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)] System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark&amp; stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0<br> System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark&amp; stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210<br> System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark&amp; stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242<br> System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark&amp; stackMark, Boolean forIntrospection) +17 System.Reflection.Assembly.Load(String assemblyString) +35<br> System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122</p> <p>[ConfigurationErrorsException: Could not load file or assembly 'System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]<br> System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12761078<br> System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334<br> System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203<br> System.Web.Compilation.BuildManager.ExecutePreAppStart() +152<br> System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151</p> <p>[HttpException (0x80004005): Could not load file or assembly 'System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]<br> System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12881540 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12722601</p> <p>Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929</p> </blockquote> <p>a part of WebConfig:</p> <pre><code>&lt;runtime&gt; &lt;!-- Old asp.net ajax assembly bindings --&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="4.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="4.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;/assemblyBinding&gt; </code></pre> <p></p>
15,887,969
6
3
null
2013-04-08 08:18:00.247 UTC
4
2020-04-03 14:56:57.797 UTC
2013-04-08 08:29:52.5 UTC
null
1,817,640
null
1,817,640
null
1
26
c#|asp.net|asp.net-mvc|deployment|umbraco
67,560
<p>Quite a few ways to fix this:</p> <ol> <li><p>Install MVC on the web server (which is not always possible).</p></li> <li><p>In visual studio you can set dlls to copy to local on build, see the following article (please note MVC dlls have changed names slightly but it gives you the process) <a href="http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx">http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx</a></p></li> <li><p>Copy the appropriate dlls from your GAC into the bin folder of the umbraco site. To do this open "%windir%\Microsoft.NET\assembly\GAC_MSIL" in explorer and you will find all of the dlls installed in the GAC and you can copy the appropriate versions into your project. This is similar to the above method but bypasses building the project.</p></li> </ol> <p>In terms of files you will likely need more than just System.Web.Razor.dll however this will work for all of the missing files.</p>
35,817,558
Why does C# allow making an override async?
<p>In C#, when you override a method, it is permitted to make the override async when the original method was not. This seems like poor form. </p> <p>The problem that makes me wonder is this: I was brought in to assist with a load test problem. At around 500 concurrent users, the login process would break down into a redirect loop. IIS was logging exceptions with the message "An asynchronous module or handler completed while an asynchronous operation was still pending". Some searching led me to think that someone was abusing <code>async void</code>, but my quick searches through the source found nothing.</p> <p>Sadly, I was searching for <code>async\s*void</code> (regex search) when I should have been looking for something more like <code>async\s*[^T]</code> (assuming Task wasn't fully qualified.. you get the point). </p> <p>What I later found was <code>async override void onActionExecuting</code> in a base controller. Clearly that had to be the problem, and it was. Fixing that up (making it synchronous for the moment) resolved the problem.</p> <p>But it left me with a question: Why can you mark an override as async when the calling code could never await it?</p>
35,818,404
3
21
null
2016-03-05 17:48:08.23 UTC
2
2017-07-24 21:06:37.13 UTC
2017-07-24 20:59:37.613 UTC
null
1,459,996
null
8,513
null
1
45
c#|async-await
22,258
<p>When the base class (or interface) declares a virtual method that returns a Task, you can override it as long as you return Task. The <code>async</code> keyword is just a hint to the compiler to transform your method into a state machine. Although the compiler does it's black magic on your method, the compiled method <strong>still returns a Task</strong>. </p> <hr> <p>As for <code>void</code> virtual methods, you can override one <strong>without</strong> the <code>async</code> keyword (obviously) and start a non-awaited Task within it. That's kind of what happens when you override it <strong>with</strong> the <code>async</code> keyword and use <code>await</code> in the body. The caller would not await the created Task (since the "original" signature is <code>void</code>). Both cases are similar*:</p> <pre><code>public override void MyVirtualMethod() { // Will create a non awaited Task (explicitly) Task.Factory.StartNew(()=&gt; SomeTaskMethod()); } public override async void MyVirtualMethod() { // Will create a non awaited Task (the caller cannot await void) await SomeTaskMethod(); } </code></pre> <p><a href="https://msdn.microsoft.com/en-us/magazine/jj991977.aspx" rel="noreferrer">Stephen Cleary's article</a> has some notes regarding this: </p> <ul> <li><em>Void-returning async methods have a specific purpose: to make asynchronous event handlers possible.</em></li> <li><em>You should prefer async Task to async void.</em></li> </ul> <p>*The implementation of <code>SomeTaskMethod</code>, the underlying framework, the SynchronizationContext and other factors might and will cause different outcomes for each of the above methods.</p>
10,321,393
jquery function on toggleClass complete?
<p>How can I do a function once a toggleClass has completed? I've tried the following but with no luck:</p> <pre><code>$("#loader").toggleClass('fadeOut', function () {     alert('a'); }); </code></pre>
10,321,923
2
3
null
2012-04-25 18:15:24.78 UTC
12
2018-07-05 15:09:59.647 UTC
2012-04-25 18:20:39.943 UTC
null
572,939
null
1,013,512
null
1
32
jquery
37,625
<p>jQuery has a promise method that returns a promise that resolves after all running animations on selected elements are complete. At that point, you can bind to it's done method.</p> <pre><code>$("#loader").toggleClass('fadeOut',600).promise().done(function(){ console.log('a'); }); </code></pre> <p><a href="http://jsfiddle.net/skram/4x76J/" rel="nofollow noreferrer">http://jsfiddle.net/skram/4x76J/</a></p> <p><em>Note:</em> Animations using <code>toggleClass</code> require jQuery UI.</p>
10,805,589
Convert JSON date string to Python datetime
<p>When translating dates to JSON, javascript is saving dates in this format:</p> <pre><code>2012-05-29T19:30:03.283Z </code></pre> <p>However, I am not sure how to get this into a python datetime object. I've tried these:</p> <pre><code># Throws an error because the 'Z' isn't accounted for: datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f') # Throws an error because '%Z' doesn't know what to do with the 'Z' # at the end of the string datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f%Z') </code></pre> <p>I believe that javascript is saving the string in official ISO format, so it seems that there should be a way to get python's <code>datetime.strptime()</code> to read it?</p>
10,805,633
3
3
null
2012-05-29 19:40:21.783 UTC
9
2022-07-21 16:39:18.12 UTC
2017-05-28 03:54:29.42 UTC
null
832,230
null
84,131
null
1
50
python|json|datetime|date|iso
50,649
<p>Try the following format:</p> <pre><code>%Y-%m-%dT%H:%M:%S.%fZ </code></pre> <p>For example:</p> <pre><code>&gt;&gt;&gt; datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ') datetime.datetime(2012, 5, 29, 19, 30, 3, 283000) </code></pre> <p>The <code>Z</code> in the date just means that it should be interpreted as a UTC time, so ignoring it won't cause any loss of information. You can find this information here: <a href="http://www.w3.org/TR/NOTE-datetime" rel="noreferrer">http://www.w3.org/TR/NOTE-datetime</a></p>
10,419,530
Multi line preprocessor macros
<p>How to make multi line preprocessor macro? I know how to make one line:</p> <pre><code>#define sqr(X) (X*X) </code></pre> <p>but I need something like this:</p> <pre><code>#define someMacro(X) class X : public otherClass { int foo; void doFoo(); }; </code></pre> <p>How can I get this to work?</p> <p>This is only an example, the real macro may be very long.</p>
10,419,556
7
3
null
2012-05-02 18:25:57.503 UTC
24
2022-08-22 17:12:43.53 UTC
2015-10-23 14:09:52.69 UTC
null
2,246,488
null
1,023,753
null
1
97
c++|c|c-preprocessor
92,479
<p>You use <code>\</code> as a line continuation escape character.</p> <pre><code>#define swap(a, b) { \ (a) ^= (b); \ (b) ^= (a); \ (a) ^= (b); \ } </code></pre> <p>EDIT: As @abelenky pointed out in the comments, the <code>\</code> character <strong>must be the last character on the line</strong>. If it is not (even if it is just white space afterward) you will get confusing error messages on each line after it.</p>
10,520,772
In R, how to get an object's name after it is sent to a function?
<p>I am looking for the reverse of <code>get()</code>.</p> <p>Given an object name, I wish to have the character string representing that object extracted directly from the object.</p> <p>Trivial example with <code>foo</code> being the placeholder for the function I am looking for.</p> <pre><code>z &lt;- data.frame(x=1:10, y=1:10) test &lt;- function(a){ mean.x &lt;- mean(a$x) print(foo(a)) return(mean.x)} test(z) </code></pre> <p>Would print:</p> <pre><code> "z" </code></pre> <p>My work around, which is harder to implement in my current problem is:</p> <pre><code>test &lt;- function(a="z"){ mean.x &lt;- mean(get(a)$x) print(a) return(mean.x)} test("z") </code></pre>
10,520,832
5
4
null
2012-05-09 17:05:40.323 UTC
46
2022-09-16 15:08:48.667 UTC
2015-11-09 02:30:26.743 UTC
null
3,576,984
null
742,447
null
1
169
r
67,320
<p>The old deparse-substitute trick:</p> <pre><code>a&lt;-data.frame(x=1:10,y=1:10) test&lt;-function(z){ mean.x&lt;-mean(z$x) nm &lt;-deparse(substitute(z)) print(nm) return(mean.x)} test(a) #[1] &quot;a&quot; ... this is the side-effect of the print() call # ... you could have done something useful with that character value #[1] 5.5 ... this is the result of the function call </code></pre> <p>Edit: Ran it with the new test-object</p> <p>Note: this will not succeed inside a local function when a set of list items are passed from the first argument to <code>lapply</code> (and it also fails when an object is passed from a list given to a <code>for</code>-loop.) You would be able to extract the &quot;.Names&quot;-attribute and the order of processing from the structure result, if it were a named vector that were being processed.</p> <pre><code>&gt; lapply( list(a=4,b=5), function(x) {nm &lt;- deparse(substitute(x)); strsplit(nm, '\\[')} ) $a # This &quot;a&quot; and the next one in the print output are put in after processing $a[[1]] [1] &quot;X&quot; &quot;&quot; &quot;1L]]&quot; # Notice that there was no &quot;a&quot; $b $b[[1]] [1] &quot;X&quot; &quot;&quot; &quot;2L]]&quot; &gt; lapply( c(a=4,b=5), function(x) {nm &lt;- deparse(substitute(x)); strsplit(nm, '\\[')} ) $a $a[[1]] # but it's theoretically possible to extract when its an atomic vector [1] &quot;structure(c(4, 5), .Names = c(\&quot;a\&quot;, \&quot;b\&quot;))&quot; &quot;&quot; [3] &quot;1L]]&quot; $b $b[[1]] [1] &quot;structure(c(4, 5), .Names = c(\&quot;a\&quot;, \&quot;b\&quot;))&quot; &quot;&quot; [3] &quot;2L]]&quot; </code></pre>
24,990,554
How to include a font .ttf using CSS?
<p>I have a problem with my code. Because I want to include a global font for my page and I downloaded a .ttf file. And I include it in my main CSS but my font wont change.</p> <p>Here's my simple code:</p> <pre><code>@font-face { font-family: 'oswald'; src: url('/font/oswald.regular.ttf'); } html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin:0; padding:0; border:0; font-size:100%; font:inherit; font-family: oswald; vertical-align:baseline } </code></pre> <p>I don't know where did I go wrong. Can you help me with this? Thanks.</p>
24,990,647
4
8
null
2014-07-28 07:39:22.1 UTC
43
2022-09-01 06:17:02.477 UTC
2014-07-28 07:49:50.763 UTC
null
2,706,036
null
2,706,036
null
1
191
html|css
369,877
<p>Only providing .ttf file for webfont won't be good enough for cross-browser support. The best possible combination at present is using the combination as :</p> <pre class="lang-css prettyprint-override"><code>@font-face { font-family: 'MyWebFont'; src: url('webfont.eot'); /* IE9 Compat Modes */ src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('webfont.woff') format('woff'), /* Modern Browsers */ url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */ url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */ } </code></pre> <p>This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use : <a href="https://transfonter.org" rel="nofollow noreferrer">Transfonter.org</a>.</p> <p>Also , modern browsers are shifting towards .woff font , so you can probably do this too :</p> <pre class="lang-css prettyprint-override"><code>@font-face { font-family: 'MyWebFont'; src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */ } </code></pre> <p>Read more here : <a href="http://css-tricks.com/snippets/css/using-font-face/" rel="nofollow noreferrer">http://css-tricks.com/snippets/css/using-font-face/</a></p> <hr /> <p><strong>Look for browser support : <a href="http://caniuse.com/#feat=fontface" rel="nofollow noreferrer">Can I Use fontface</a></strong></p>
46,629,170
Firestore security rule get() not work
<h1>The solution is in the end of the post. Check it out.</h1> <h1>Решение проблемы в конце поста. Дочитайте.</h1> <p>just a simple question: whats wrong with this and why this is not working?</p> <p>Trying to get access with user who has role 'admin' in users section to the <strong>/titles/{anyTitle}</strong> but still get </p> <blockquote> <p><strong>Missing or insufficient permissions</strong>.</p> </blockquote> <pre><code>service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow write: if false; allow read: if false; } function userCanWrite () { return get(/databases/{database}/documents/users/$(request.auth.uid)).data.role == "admin"; } match /titles/{anyTitle=**} { allow read: if request.auth != null; allow write: if userCanWrite(); } } } </code></pre> <p><a href="https://i.stack.imgur.com/j30cP.png" rel="noreferrer">Here is my database structure</a></p> <h2><strong>P.S.</strong></h2> <p>I tried another rule from official documents <code>get(/databases/{database}/documents/users/$(request.auth.uid‌​)).data.isAdmin == true;</code></p> <p>and this is not working too</p> <h1>UPDATE: CORRECT WAY TO DO IT</h1> <p>Support helped me find the solution this is how you should do:</p> <p><strong>db structure:</strong></p> <blockquote> <p>users -> {{ userid }} -> { role: "admin" }</p> </blockquote> <p><strong>database rule settings:</strong></p> <blockquote> <p>get(usersPath/$(request.auth.uid)).role == "admin" || get(usersPath/$(request.auth.uid)).data.role == "admin";</p> </blockquote>
46,681,577
5
11
null
2017-10-08 08:45:57.677 UTC
10
2020-04-08 08:15:34.513 UTC
2017-10-13 09:14:16.563 UTC
null
8,740,159
null
8,740,159
null
1
17
firebase|firebase-security|google-cloud-firestore
9,993
<p>I contacted to the Firebase support to report that bug and they gave me a temporary solution on this. It seems that they are having a bug in their systems on the security rules side. They say that the documentation is ok, but for now we should workaround this way:</p> <pre><code>get(path).data.field == true || get(path).field == true; </code></pre> <p>Because the bug is that data object isn't populated, you should check both properties. There's no ETA for launching a solution on this bug, so I asked they if they could give me an advice when they solved this issue, so I'll keep this answer up-to-date with their information.</p>
33,854,103
Why were Javascript `atob()` and `btoa()` named like that?
<p>In Javascript, <code>window.atob()</code> method decodes a <em>base64</em> string and <code>window.btoa()</code> method encodes a <code>string</code> into <em>base64</em>.</p> <p>Then why weren't they named like <code>base64Decode()</code> and <code>base64Encode()</code>? <code>atob()</code> and <code>btoa()</code> don't make sense because they're not semantic at all.</p> <p>I want to know the reason.</p>
33,854,127
5
6
null
2015-11-22 11:11:59.28 UTC
46
2022-01-21 17:49:37.95 UTC
2018-10-06 08:54:55.25 UTC
null
4,510,033
null
4,510,033
null
1
396
javascript
105,685
<p>The <code>atob()</code> and <code>btoa()</code> methods allow authors to transform content to and from the base64 encoding.</p> <blockquote> <p>In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.</p> </blockquote> <p>From : <a href="http://www.w3.org/TR/html/webappapis.html#atob">http://www.w3.org/TR/html/webappapis.html#atob</a></p>
33,431,953
How is conditional_wait() implemented at the kernel and hardware/assembly level?
<p>I understand that the thread that waits on a conditional variable, atomically releases the lock and goes to sleep until is waken by a conditional signal from another thread (when a particular condition is met). After it wakes up, it atomically re-acquires the lock (somehow magically) and updates as required and unlocks the critical section.</p> <p>It would be great if someone could explain how this conditional_wait() procedure implemented at the kernel and the hardware/assembly level? </p> <p>How is the lock released and re-acquired atomically? How does the kernel ensure it? </p> <p>What does sleep here actually mean? Does it mean a context switch to another process/thread? </p> <p>During thread sleep, how is this <strong>thread awaken by signaling</strong> implemented at the kernel level and if any hardware specific support is provided for these mechanisms?</p> <p>Edit:</p> <p>It seems "futex" is the guy managing this wait/signal stuff. To narrow down my question: How the futex system call for waiting and notifying condition variables is implemented/works at the low level? </p>
33,438,201
1
10
null
2015-10-30 08:50:51.257 UTC
10
2018-07-04 17:19:11.81 UTC
2015-10-30 12:42:40.067 UTC
null
2,733,779
null
2,733,779
null
1
20
c|multithreading|linux-kernel|synchronization|mutex
4,162
<p>On a high level (and since you are asking this question, high level is what you need) it is not that complicated. First, you need to know the layers of responsibility. There are basically 3 layers:</p> <ul> <li>Hardware level - usually something which can be coded in a single ASM instruction</li> <li>Kernel level - something which OS kernel does</li> <li>Application level - something which application does</li> </ul> <p>Generally, those responsibilities are not overlapping - kernel can not do what only hardware can do, hardware can not do what only kernel can do. Having this in mind, it is useful to remember that when it comes to locking, there is very little hardware knows about it. It pretty much boils down to </p> <ul> <li>atomic arithmetics - hardware can lock a particular memory region (make sure no other threads access it), perform arithmetic operation on it and unlock the region. This can only work on the arithmetics natively supported by the chip (no square roots!) and on the sizes natively supported by hardware</li> <li>Memory barriers or fences - that is, introduce a barrier within a flow of instructions, so that when CPU reorders instructions or uses memory caches, they will not cross those fences and the cache will be fresh</li> <li>Conditional setting (compare-and-set) - set memory region to value A if it is B and report the status of this operation (was it set or not)</li> </ul> <p>That's pretty much all CPU can do. As you see, there is no futex, mutex or conditional variables here. This stuff is made by kernel having CPU-supported operations at it's disposal.</p> <p>Let's look in a very high level how kernel might implement futex call. Actually, futex is slightly complicated, because it is mixture of user-level calls and kernel-level calls as needed. Let's look into 'pure' mutex, implemented solely in kernel space. On a high level, it will be demonstrational enough.</p> <p>When mutex is initially created, kernel associates a memory region with it. This region will hold a value of mutex being locked or unlocked. Later, kernel is asked to lock the mutex, it first instructs CPU to issue memory barrier. A mutex must serve as a barrier, so that everything read/written after mutex is acquired (or released) is visible to the rest of CPUs. Then, it uses CPU-supported compare-and-set instruction to set memory region value to 1 if it was set to 0. (there are more complicated reentrant mutexes, but let's not complicate the picture with them). It is guaranteed by CPU that even if more then one thread attempts to do this at the same time, only one will succeed. If the operation succeeds, we now 'hold the mutex'. Once kernel is asked to release the mutex, memory region is set to 0 (there is no need to do this conditionally, since we know we hold the mutex!) and another memory barrier is issued. Kernel also updates the mutex status in it's tables - see below.</p> <p>If mutex locking fails, kernel adds the thread to it's tables which list threads waiting on particular mutex to be released. When the mutex is released, kernel checks what thread(s) are waiting on this mutex, and 'schedules' (i.e. prepares for execution) one of those (in case there is more than one, which one will be scheduled or awaken depends on multitude of factors, in the simplest case it is simply random). The thread scheduled begins executing, locks the mutex again (at this point it can fail again!) and the cycle of life continues.</p> <p>Hope it does make at least half-sense :)</p>
13,294,468
Alter column in SQL Server
<p>What is correct syntax for an <code>ALTER</code> statement to add a default value to an existing column?</p> <p>I can add new column with no errors:</p> <pre><code>ALTER TABLE tb_TableName ADD Record_Status varchar(20) </code></pre> <p>But If I try to alter existing column to apply default value by using the following statement:</p> <pre><code>ALTER TABLE tb_TableName ALTER COLUMN Record_Status VARCHAR(20) NOT NULL DEFAULT '' </code></pre> <p>or</p> <pre><code>ALTER TABLE tb_TableName ALTER Record_Status VARCHAR(20) NOT NULL DEFAULT '' </code></pre> <p>I have get an error: </p> <blockquote> <p>Incorrect syntax near 'Record_Status'.</p> </blockquote>
13,294,539
3
0
null
2012-11-08 17:31:26.913 UTC
3
2018-05-01 12:31:44.177 UTC
2012-11-08 18:22:35.58 UTC
null
13,302
null
201,889
null
1
29
sql|sql-server-2008
107,661
<p>I think you want this syntax:</p> <pre><code>ALTER TABLE tb_TableName add constraint cnt_Record_Status Default '' for Record_Status </code></pre> <p>Based on some of your comments, I am going to guess that you might already have <code>null</code> values in your table which is causing the alter of the column to <code>not null</code> to fail. If that is the case, then you should run an <code>UPDATE</code> first. Your script will be:</p> <pre><code>update tb_TableName set Record_Status = '' where Record_Status is null ALTER TABLE tb_TableName ALTER COLUMN Record_Status VARCHAR(20) NOT NULL ALTER TABLE tb_TableName ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status </code></pre> <p>See <a href="http://sqlfiddle.com/#!18/d7797/1" rel="noreferrer">SQL Fiddle with demo</a></p>
13,593,900
How to get around lack of covariance with IReadOnlyDictionary?
<p>I'm trying to expose a read-only dictionary that holds objects with a read-only interface. Internally, the dictionary is write-able, and so are the objects within (see below example code). My problem is that IReadOnlyDictionary doesn't support covariant conversions because of the reason outlined in the question <a href="https://stackoverflow.com/questions/2149589/idictionarytkey-tvalue-in-net-4-not-covariant">here</a>. This means I can't just expose my internal dictionary as a read only one.</p> <p>So my question is, is there an efficient way to convert my internal dictionary to an IReadOnlyDictionary, or some other way to handle this? The options I can think of are:</p> <ol> <li>Hold two internal dictionaries and keep them in sync.</li> <li>Create a new dictionary when the property is accessed and cast all the objects within.</li> <li>Cast the IReadOnly's back to NotReadOnly when using it internally.</li> </ol> <p>1 seems like a pain, 2 seems highly inefficient. 3 sounds like the most promising at the moment, but is still ugly. Do I have any other options?</p> <pre><code>public class ExposesReadOnly { private Dictionary&lt;int, NotReadOnly&gt; InternalDict { get; set; } public IReadOnlyDictionary&lt;int, IReadOnly&gt; PublicList { get { // This doesn't work... return this.InternalDict; } } // This class can be modified internally, but I don't want // to expose this functionality. private class NotReadOnly : IReadOnly { public string Name { get; set; } } } public interface IReadOnly { string Name { get; } } </code></pre>
13,602,918
5
0
null
2012-11-27 21:59:17.617 UTC
3
2017-11-15 04:39:59.937 UTC
2017-05-23 12:17:09.54 UTC
null
-1
null
306,918
null
1
32
c#|.net|dictionary|readonly|covariance
6,936
<p>You could write your own read-only wrapper for the dictionary, e.g.:</p> <pre><code>public class ReadOnlyDictionaryWrapper&lt;TKey, TValue, TReadOnlyValue&gt; : IReadOnlyDictionary&lt;TKey, TReadOnlyValue&gt; where TValue : TReadOnlyValue { private IDictionary&lt;TKey, TValue&gt; _dictionary; public ReadOnlyDictionaryWrapper(IDictionary&lt;TKey, TValue&gt; dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _dictionary = dictionary; } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public IEnumerable&lt;TKey&gt; Keys { get { return _dictionary.Keys; } } public bool TryGetValue(TKey key, out TReadOnlyValue value) { TValue v; var result = _dictionary.TryGetValue(key, out v); value = v; return result; } public IEnumerable&lt;TReadOnlyValue&gt; Values { get { return _dictionary.Values.Cast&lt;TReadOnlyValue&gt;(); } } public TReadOnlyValue this[TKey key] { get { return _dictionary[key]; } } public int Count { get { return _dictionary.Count; } } public IEnumerator&lt;KeyValuePair&lt;TKey, TReadOnlyValue&gt;&gt; GetEnumerator() { return _dictionary .Select(x =&gt; new KeyValuePair&lt;TKey, TReadOnlyValue&gt;(x.Key, x.Value)) .GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } </code></pre>
13,629,507
Celery: How to ignore task result in chord or chain?
<p>I'm using celery, I have several tasks which needed to be executed in order.</p> <p>For example I have this task:</p> <pre><code>@celery.task def tprint(word): print word </code></pre> <p>And I want to do something like this:</p> <pre><code>&gt;&gt;&gt; chain(tprint.s('a') | tprint.s('b'))() </code></pre> <p>Then I get <code>TypeError: tprint() takes exactly 1 argument (2 given)</code>.</p> <p>The same with chord, in this situation which I need a task to be executed after a group of tasks:</p> <pre><code>&gt;&gt;&gt; chord([tprint.s('a'), tprint.s('b')])(tprint.s('c')) </code></pre> <p>So how to deal with this situation? I don't care the result of each task, but they need to be executed in order.</p> <hr> <p>Add a second parameter won't work:</p> <pre><code>@celery.task def tprint(word, ignore=None): print word &gt;&gt;&gt; chain(tprint.s('a', 0) | tprint.s('b'))() </code></pre> <p>This will print out 'a' and 'None'.</p>
13,788,495
4
1
null
2012-11-29 15:51:06.267 UTC
9
2016-10-10 09:37:18.083 UTC
2012-12-04 08:58:13.163 UTC
null
543,492
null
543,492
null
1
43
python|asynchronous|task|celery
17,618
<p>There is a built-in functionality to ignore result in chaining and others - immutable subtask. You can use .si() shortcut instead of .s() or .subtask(immutable=True)</p> <p>More details here: <a href="http://docs.celeryproject.org/en/master/userguide/canvas.html#immutability">http://docs.celeryproject.org/en/master/userguide/canvas.html#immutability</a></p>
13,357,765
Does ConfigurationManager.AppSettings[Key] read from the web.config file each time?
<p>I'm wondering how the <code>ConfigurationManager.AppSettings[Key]</code> works.</p> <p>Does it read from the physical file each time I need a key? If so, should I be reading all the app settings of my web.config in a cache and then read from it?</p> <p>Or does ASP.NET or IIS load the web.config file only once at application startup?</p> <p>How do I verify whether the physical file is accessed by each read? If I change the web.config, IIS restarts my application, so I can't verify it that way.</p>
13,358,044
3
0
null
2012-11-13 08:48:01.473 UTC
10
2020-06-25 14:03:14.45 UTC
2020-06-25 14:03:14.45 UTC
null
5,405,967
null
133,212
null
1
76
c#|asp.net|web-config|configurationmanager
33,346
<p>It gets cached, on first access of a property, so it does not read from the physical file each time you ask for a value. This is why it is necessary to restart an Windows app (or <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.refreshsection.aspx" rel="noreferrer">Refresh</a> the config) to get the latest value, and why an ASP.Net app automatically restarts when you edit web.config. Why ASP.Net is hard wired to restart is discussed in the references in the answer <a href="https://stackoverflow.com/a/613836/1073107">How to prevent an ASP.NET application restarting when the web.config is modified</a>.</p> <p>We can verify this using <a href="http://ilspy.net/" rel="noreferrer">ILSpy</a> and looking at the internals of System.Configuration:</p> <pre><code>public static NameValueCollection AppSettings { get { object section = ConfigurationManager.GetSection("appSettings"); if (section == null || !(section is NameValueCollection)) { throw new ConfigurationErrorsException(SR.GetString("Config_appsettings_declaration_invalid")); } return (NameValueCollection)section; } } </code></pre> <p>At first, this does indeed look like it will get the section every time. Looking at GetSection:</p> <pre><code>public static object GetSection(string sectionName) { if (string.IsNullOrEmpty(sectionName)) { return null; } ConfigurationManager.PrepareConfigSystem(); return ConfigurationManager.s_configSystem.GetSection(sectionName); } </code></pre> <p>The critical line here is the <code>PrepareConfigSystem()</code> method; this initializes an instance of the <code>IInternalConfigSystem</code> field held by the ConfigurationManager - the concrete type is <code>ClientConfigurationSystem</code> </p> <p>As part of this load, an instance of the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx" rel="noreferrer">Configuration</a> class is instantiated. This class is effectively an object representation of the config file, and appears to be held by the ClientConfigurationSystem's ClientConfigurationHost property in a static field - hence it is cached.</p> <p>You could test this empirically by doing the following (in a Windows Form or WPF app):</p> <ol> <li>Starting your App up </li> <li>Access a value in app.config </li> <li>Make a change to app.config </li> <li>Check to see whether the new value is present </li> <li>Call <code>ConfigurationManager.RefreshSection("appSettings")</code></li> <li>Check to see if the new value is present.</li> </ol> <p>In fact, I could have saved myself some time if I'd just read the comment on the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.refreshsection.aspx" rel="noreferrer">RefreshSection</a> method :-)</p> <pre><code>/// &lt;summary&gt;Refreshes the named section so the next time that it is retrieved it will be re-read from disk.&lt;/summary&gt; /// &lt;param name="sectionName"&gt;The configuration section name or the configuration path and section name of the section to refresh.&lt;/param&gt; </code></pre>
51,951,641
Swagger..Unable to render this definition The provided definition does not specify a valid version field
<blockquote> <p>Unable to render this definition The provided definition does not specify a valid version field.</p> <p>Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).</p> </blockquote> <p>Where do I need to insert the correct version to the stop the error below. Swagger editor works ok, but when launching a particular project I receive this error.First time using Swagger. Many Thanks</p>
51,952,309
10
4
null
2018-08-21 15:05:22.4 UTC
1
2022-08-17 13:33:52.603 UTC
null
null
null
null
6,345,993
null
1
31
javascript|api|swagger
67,438
<p>Your <a href="https://github.com/HaiderMalik12/build-and-secure-restful-api/blob/master/src/config/swagger.json" rel="noreferrer">API definition</a> is missing the OpenAPI/Swagger version number, in this case <code>"swagger": "2.0"</code>. Add it at the beginning, like so:</p> <pre><code>{ "swagger": "2.0", "title" : "Music API Documentation", ... </code></pre>
24,062,123
MongoDB Syntax Error Unexpected Token
<p>I am new to MongoDB. I am just following tutorialspoint.com for learning mongoDB. </p> <p>I executed these two commands exactly as given :</p> <pre><code>db.test.save( { a: 1 } ) db.test.find(){ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 } </code></pre> <p>I am getting error SyntaxError: Unexpected Token {</p> <p>Any help is appreciated. Thanks. </p>
24,063,747
3
2
null
2014-06-05 13:53:55.69 UTC
0
2018-11-17 20:45:48.28 UTC
2014-06-05 15:13:33.367 UTC
null
3,276,627
null
2,844,579
null
1
4
mongodb|syntax
54,103
<p>Your query:</p> <pre><code> test.find() { "_id" : ObjectId(5879b0f65a56a454), "a" : 1 } </code></pre> <p>Correct query:</p> <pre><code> test.find( { "_id" : ObjectId("5879b0f65a56a454"), "a" : 1 }) </code></pre> <p>you need to include curly braces in the round brackets like ({}) second thing enclose id in quotes, please refer the mongodb manual</p> <p><a href="http://docs.mongodb.org/manual/reference/method/db.collection.find/" rel="nofollow noreferrer">http://docs.mongodb.org/manual/reference/method/db.collection.find/</a></p>
24,049,020
NSNotificationCenter addObserver in Swift
<p>How do you add an observer in Swift to the default notification center? I'm trying to port this line of code that sends a notification when the battery level changes.</p> <pre><code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil]; </code></pre>
24,049,111
16
3
null
2014-06-04 23:02:04.91 UTC
147
2022-08-05 06:16:13.567 UTC
2017-04-09 16:23:30.577 UTC
null
2,303,865
null
284,714
null
1
442
ios|swift|nsnotificationcenter
384,851
<p>It's the same as the Objective-C API, but uses Swift's syntax.</p> <p><strong>Swift 4.2 &amp; Swift 5:</strong></p> <pre><code>NotificationCenter.default.addObserver( self, selector: #selector(self.batteryLevelChanged), name: UIDevice.batteryLevelDidChangeNotification, object: nil) </code></pre> <p>If your observer does not inherit from an Objective-C object, you must prefix your method with <code>@objc</code> in order to use it as a selector.</p> <pre><code>@objc private func batteryLevelChanged(notification: NSNotification){ //do stuff using the userInfo property of the notification object } </code></pre> <p>See <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/" rel="noreferrer">NSNotificationCenter Class Reference</a>, <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-XID_36" rel="noreferrer">Interacting with Objective-C APIs</a></p>
9,614,109
How to calculate an angle from points?
<p>I want to get a simple solution to calculate the angle of a line (like a pointer of a clock).</p> <p>I have 2 points:</p> <pre><code>cX, cY - the center of the line. eX, eY - the end of the line. The result is angle (0 &lt;= a &lt; 360). </code></pre> <p>Which function is able to provide this value?</p>
9,614,122
5
2
null
2012-03-08 07:16:55.15 UTC
10
2018-11-13 14:37:36.443 UTC
2012-03-08 07:19:37.523 UTC
null
814,761
null
362,214
null
1
64
javascript|function|coordinates|angle
82,254
<p>You want the arctangent:</p> <pre><code>dy = ey - cy dx = ex - cx theta = arctan(dy/dx) theta *= 180/pi // rads to degs </code></pre> <p>Erm, note that the above is obviously not compiling Javascript code. You'll have to look through documentation for the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan" rel="noreferrer">arctangent</a> function.</p> <p><strong>Edit:</strong> Using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2" rel="noreferrer">Math.atan2(y,x)</a> will handle all of the special cases and extra logic for you:</p> <pre><code>function angle(cx, cy, ex, ey) { var dy = ey - cy; var dx = ex - cx; var theta = Math.atan2(dy, dx); // range (-PI, PI] theta *= 180 / Math.PI; // rads to degs, range (-180, 180] //if (theta &lt; 0) theta = 360 + theta; // range [0, 360) return theta; } </code></pre>
9,224,056
Android Bitmap to Base64 String
<p>How do I convert a large Bitmap (photo taken with the phone's camera) to a Base64 String?</p>
9,224,180
7
2
null
2012-02-10 07:08:20.843 UTC
32
2020-02-20 12:01:21.193 UTC
2018-10-15 20:45:54.463 UTC
null
3,623,128
null
1,187,193
null
1
162
android|bitmap|base64|android-bitmap
144,538
<p>use following method to convert bitmap to byte array:</p> <pre><code>ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream .toByteArray(); </code></pre> <p>to encode base64 from byte array use following method</p> <pre><code>String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT); </code></pre>
16,437,872
fxml combobox, get the selected value into javafx
<p>how can i catch the selected value of a fxml combobox and implement it into a javafx class?</p> <p>i gave the combobox the fx:id "sample" and created a button with onAction="#test" and tried .getValue and .getPromptText.</p> <pre><code>@FXML private ComboBox&lt;String&gt; Sample; @FXML protected void test( ActionEvent event ) { String output = (String) Sample.getValue(); System.out.println(output); String output = (String) Sample.getPromptText(); System.out.println(output); } </code></pre> <p>If i try to run it i get an error:</p> <pre><code>java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1440) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:28) at javafx.event.Event.fireEvent(Event.java:171) at javafx.scene.Node.fireEvent(Node.java:6863) at javafx.scene.control.Button.fire(Button.java:179) at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:193) at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:336) at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:329) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:64) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33) at javafx.event.Event.fireEvent(Event.java:171) at javafx.scene.Scene$MouseHandler.process(Scene.java:3324) at javafx.scene.Scene$MouseHandler.process(Scene.java:3164) at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3119) at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1559) at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2261) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:228) at com.sun.glass.ui.View.handleMouseEvent(View.java:528) at com.sun.glass.ui.View.notifyMouse(View.java:922) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29) at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73) at java.lang.Thread.run(Thread.java:722) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435) ... 45 more Caused by: java.lang.NullPointerException at TW_JAVAFX_Undecorator.ButtonController.pruefen(ButtonController.java:60) ... 50 more </code></pre> <p>Thanks in advance</p> <p>Zombie</p>
16,455,891
4
0
null
2013-05-08 10:04:55.727 UTC
1
2020-09-19 14:11:55.033 UTC
null
null
null
null
2,361,460
null
1
14
combobox|javafx|fxml
89,227
<p>I think the code you have in your question should work as long as the case of the combobox identifier in the code matches that of your fxml <code>fx:id</code>.</p> <p>I modified this <a href="https://gist.github.com/jewelsea/3062859">JavaFX fxml combo box selection demonstration app</a> to add a button with an onAction method to retrieve a value from the combo box using the comboBox <code>getValue()</code> method and it worked fine for me.</p> <p>Check the case of things, I notice that you say the <code>fx:id</code> is <code>sample</code>, yet in your code you use <code>Sample</code> - and the cases must match otherwise the fxml loader won't inject the node into your controller correctly.</p> <p>Hard to say if the <code>NullPointerException</code> in your code is related to your combo box value retrieval issue as you don't say what the code at <code>TW_JAVAFX_Undecorator.ButtonController.pruefen(ButtonController.java:60)</code> is or provide full executable code to replicate the issue.</p>
16,383,776
Detect in-app browser (WebView) with PHP / Javascript
<p>I developed an app for iOS and Android which accesses an HTML file from my webserver using the in-app browser (Webview).</p> <p>I don't want that a user can access this file without using the app. Is there a possibility to detect, if the user is accessing the file with the app or directly via a browser on this smartphone / tablet / computer? I think that a solution with PHP is much better, because Javascript can be switched off. At least Google Analytics can differentiate between Safari and Safari (in-app). It should work with every version of iOS and Android.</p> <p>Thanks for your help.</p> <hr> <p><strong>Solution</strong></p> <p>After many attempts I finally found a working solution for me!</p> <p><strong>iOS:</strong> You can detect the difference between Safari and the in-app browser using the user agent. Probably there's a nicer solution, but it works.</p> <pre><code>// Safari (in-app) if ((strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile/') !== false) &amp;&amp; (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari/') == false) { echo 'Safari (in-app)'; } </code></pre> <p><strong>Android:</strong> The package name from the app is stored in the PHP variable <code>$_SERVER['HTTP_X_REQUESTED_WITH']</code>.</p> <pre><code>// Android (in-app) if($_SERVER['HTTP_X_REQUESTED_WITH'] == "com.company.app") { echo 'Android (in-app)'; } </code></pre> <p>As Tim van Elsloo already noted HTTP headers can be faked and this is not absolutely secure.</p>
16,383,808
3
2
null
2013-05-05 10:56:04.103 UTC
8
2020-02-18 17:41:43.463 UTC
2013-05-05 12:13:45.7 UTC
null
2,165,970
null
2,165,970
null
1
19
php|javascript|android|ios|xcode
33,615
<p>I'm not sure about Android, but when you're using the iOS SDK's <code>UIWebView</code>, it sends the name and version of your app as part of the user agent (<code>YourApp/1.0</code>).</p> <p>You can then use PHP to check if your in-app webview is being used or not:</p> <pre><code>if (strpos($_SERVER['HTTP_USER_AGENT'], 'YourApp/') !== false) </code></pre> <p>I think Android does something similar as well.</p>
16,310,588
How to clean completely select2 control?
<p>I'm working with the awesome <a href="http://ivaynberg.github.io/select2/" rel="noreferrer">select2 control</a>.</p> <p>I'm trying to clean and disable the select2 with the content too so I do this:</p> <pre><code>$("#select2id").empty(); $("#select2id").select2("disable"); </code></pre> <p>Ok, it works, but if i had a value selected all the items are removed, the control is disabled, but the selected value is still displayed. I want to clear all content so the placeholder would be showed. Here is a example I did where you can see the issue: <a href="http://jsfiddle.net/BSEXM/" rel="noreferrer">http://jsfiddle.net/BSEXM/</a></p> <p>HTML:</p> <pre><code>&lt;select id="sel" data-placeholder="This is my placeholder"&gt; &lt;option&gt;&lt;/option&gt; &lt;option value="a"&gt;hello&lt;/option&gt; &lt;option value="b"&gt;all&lt;/option&gt; &lt;option value="c"&gt;stack&lt;/option&gt; &lt;option value="c"&gt;overflow&lt;/option&gt; &lt;/select&gt; &lt;br&gt; &lt;button id="pres"&gt;Disable and clear&lt;/button&gt; &lt;button id="ena"&gt;Enable&lt;/button&gt; </code></pre> <p>Code:</p> <pre><code>$(document).ready(function () { $("#sel").select2(); $("#pres").click(function () { $("#sel").empty(); $("#sel").select2("disable"); }); $("#ena").click(function () { $("#sel").select2("enable"); }); }); </code></pre> <p>CSS:</p> <pre><code>#sel { margin: 20px; } </code></pre> <p>Do you have any idea or advice to this?</p>
19,546,463
11
1
null
2013-04-30 23:31:16.74 UTC
5
2022-05-24 07:58:56.653 UTC
2018-03-01 20:23:52.58 UTC
null
5,731,992
null
1,709,738
null
1
51
javascript|jquery|jquery-ui|jquery-select2
92,924
<p>Why all this trouble???</p> <p>use: </p> <pre><code> $('#sel').select2('data', null); </code></pre>
16,149,803
Working with big data in python and numpy, not enough ram, how to save partial results on disc?
<p>I am trying to implement algorithms for 1000-dimensional data with 200k+ datapoints in python. I want to use numpy, scipy, sklearn, networkx, and other useful libraries. I want to perform operations such as pairwise distance between all of the points and do clustering on all of the points. I have implemented working algorithms that perform what I want with reasonable complexity but when I try to scale them to all of my data I run out of RAM. Of course, I do, creating the matrix for pairwise distances on 200k+ data takes a lot of memory.</p> <p>Here comes the catch: I would really like to do this on crappy computers with low amounts of RAM.</p> <p>Is there a feasible way for me to make this work without the constraints of low RAM? That it will take a much longer time is really not a problem, as long as the time reqs don't go to infinity!</p> <p>I would like to be able to put my algorithms to work and then come back an hour or five later and not have it stuck because it ran out of RAM! I would like to implement this in python, and be able to use the numpy, scipy, sklearn, and networkx libraries. I would like to be able to calculate the pairwise distance to all my points etc</p> <p>Is this feasible? And how would I go about it, what can I start to read up on?</p>
16,633,274
1
3
null
2013-04-22 14:36:25.78 UTC
39
2021-07-20 16:22:28 UTC
2021-07-20 16:22:28 UTC
null
2,452,869
null
1,469,829
null
1
67
python|arrays|numpy|scipy|bigdata
40,374
<p>Using <code>numpy.memmap</code> you create arrays directly mapped into a file:</p> <pre><code>import numpy a = numpy.memmap('test.mymemmap', dtype='float32', mode='w+', shape=(200000,1000)) # here you will see a 762MB file created in your working directory </code></pre> <p>You can treat it as a conventional array: a += 1000.</p> <p>It is possible even to assign more arrays to the same file, controlling it from mutually sources if needed. But I've experiences some tricky things here. To open the full array you have to "close" the previous one first, using <code>del</code>:</p> <pre><code>del a b = numpy.memmap('test.mymemmap', dtype='float32', mode='r+', shape=(200000,1000)) </code></pre> <p>But openning only some part of the array makes it possible to achieve the simultaneous control:</p> <pre><code>b = numpy.memmap('test.mymemmap', dtype='float32', mode='r+', shape=(2,1000)) b[1,5] = 123456. print a[1,5] #123456.0 </code></pre> <p>Great! <code>a</code> was changed together with <code>b</code>. And the changes are already written on disk.</p> <p>The other important thing worth commenting is the <code>offset</code>. Suppose you want to take not the first 2 lines in <code>b</code>, but lines 150000 and 150001.</p> <pre><code>b = numpy.memmap('test.mymemmap', dtype='float32', mode='r+', shape=(2,1000), offset=150000*1000*32/8) b[1,2] = 999999. print a[150001,2] #999999.0 </code></pre> <p>Now you can access and update any part of the array in simultaneous operations. Note the byte-size going in the offset calculation. So for a 'float64' this example would be 150000*1000*64/8.</p> <p>Other references:</p> <ul> <li><p><a href="https://stackoverflow.com/a/16597695/832621">Is it possible to map a discontiuous data on disk to an array with python?</a></p></li> <li><p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html#numpy.memmap" rel="noreferrer"><code>numpy.memmap</code> documentation here</a>.</p></li> </ul>
16,195,871
How do I see the current encoding of a file in Sublime Text?
<p>How do I see the current encoding of a file in Sublime Text?</p> <p>This seems like a pretty simple thing to do but searching has not yielded much. Any pointers would be appreciated!</p>
20,657,899
6
1
null
2013-04-24 15:20:41.08 UTC
70
2018-05-30 04:01:53.773 UTC
2018-01-30 19:36:16.19 UTC
null
1,787,434
null
583,834
null
1
372
encoding|sublimetext2
238,869
<p>Since this thread is a popular result in google search, here is the way to do it for sublime text 3 build 3059+: in user preferences, add the line:</p> <pre><code>"show_encoding": true </code></pre>
16,522,111
Python syntax for "if a or b or c but not all of them"
<p>I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.)</p> <p>What's the ideal syntax for something like:</p> <pre><code>if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): </code></pre> <p>?</p>
16,522,194
15
9
null
2013-05-13 12:30:20.82 UTC
28
2022-02-25 02:58:07.867 UTC
2015-09-07 01:35:40.06 UTC
null
1,832,942
null
1,779,735
null
1
142
python|if-statement
267,048
<p>If you mean a minimal form, go with this:</p> <pre><code>if (not a or not b or not c) and (a or b or c): </code></pre> <p>Which translates the title of your question.</p> <p>UPDATE: as correctly said by Volatility and Supr, you can apply De Morgan's law and obtain equivalent:</p> <pre><code>if (a or b or c) and not (a and b and c): </code></pre> <p>My advice is to use whichever form is more significant to you and to other programmers. The first means <em>"there is something false, but also something true"</em>, the second <em>"There is something true, but not everything"</em>. If I were to optimize or do this in hardware, I would choose the second, here just choose the most readable (also taking in consideration the conditions you will be testing and their names). I picked the first.</p>
16,244,969
How to tell git to ignore individual lines, i.e. gitignore for specific lines of code
<p><code>.gitignore</code> can ignore whole files, but is there a way to ignore specific lines of code while coding?</p> <p>I frequently and repeatedly add the same debug lines in a project, only to have to remember to remove them before committing. I'd like to just keep the lines in the code and have git disregard them.</p>
16,244,970
2
8
null
2013-04-26 20:47:17.183 UTC
88
2020-05-20 07:32:38.337 UTC
null
null
null
null
234,593
null
1
229
git|gitignore|ignore
85,560
<p>This is how you can kind of do it with <a href="https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html#_tt_filter_tt" rel="noreferrer">git filters</a>:</p> <ol> <li>Create/Open gitattributes file: <ul> <li><code>&lt;project root&gt;/.gitattributes</code> (will be committed into repo)<br> OR</li> <li><code>&lt;project root&gt;/.git/info/attributes</code> (won't be committed into repo)</li> </ul></li> <li>Add a line defining the files to be filtered: <ul> <li><code>*.rb filter=gitignore</code>, i.e. run filter named <code>gitignore</code> on all <code>*.rb</code> files</li> </ul></li> <li>Define the <code>gitignore</code> filter in your <code>gitconfig</code>: <ul> <li><code>$ git config --global filter.gitignore.clean "sed '/#gitignore$/d'"</code>, i.e. delete these lines</li> <li><code>$ git config --global filter.gitignore.smudge cat</code>, i.e. do nothing when pulling file from repo</li> </ul></li> </ol> <p>Notes:<br> Of course, this is for ruby files, applied when a line ends with <code>#gitignore</code>, applied globally in <code>~/.gitconfig</code>. Modify this however you need for your purposes.</p> <p>Warning!!<br> This leaves your working file different from the repo (of course). Any checking out or rebasing will mean these lines will be lost! This trick may seem useless since these lines are repeatedly lost on check out, rebase, or pull, but I've a specific use case in order to make use of it.</p> <p>Just <code>git stash save "proj1-debug"</code> <em>while the filter is inactive</em> (just temporarily disable it in <code>gitconfig</code> or something). This way, my debug code can always be <code>git stash apply</code>'d to my code at any time without fear of these lines ever being accidentally committed.</p> <p>I have a possible idea for dealing with these problems, but I'll try implementing it some other time.</p> <p>Thanks to Rudi and jw013 for mentioning git filters and gitattributes.</p>
15,392,423
java.lang.IllegalStateException on response.SendRedirect("Location")
<p>I am a beginner in the world of Java EE. I have been trying to create a simple login System using Servlets and JSP following the guide provided here <a href="http://come2niks.com/?p=1589" rel="noreferrer">http://come2niks.com/?p=1589</a>. This is how my doPost() look like.</p> <pre><code>@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); processRequest(request, response); try { System.out.println("In the Login Servlet"); LoginBean user = new LoginBean(); user.setUserName(request.getParameter("username")); user.setPassword(request.getParameter("pass")); LoginDAO db = new LoginDAO(); user = db.login(user); System.err.println("I am Back !"); if(user.isValid()) { System.err.println("VALIDED.. ReDirecting.."); System.err.println("Getting Session"); HttpSession session = request.getSession(true); System.err.println("Got Session"); session.setAttribute("currentSessionUser",user); System.err.println("Attribute Set"); response.sendRedirect("Login_Success.jsp"); }else { System.err.println(" NOT VALIDED.. ReDirecting.."); response.sendRedirect("Login_Failed.jsp"); out.println(" NOT VALIDED.. ReDirecting.."); } } catch (Throwable exc) { System.out.println(exc); } } </code></pre> <p>I have added some System.err to get some more info on the flow of the code.</p> <p>This is what my glassfish says</p> <pre><code>INFO: In the Login Servlet INFO: Driver loaded! INFO: Database connected! INFO: Welcome Ramesh SEVERE: I am Back ! SEVERE: VALIDED.. ReDirecting.. SEVERE: Getting Session SEVERE: Got Session SEVERE: Attribute Set INFO: java.lang.IllegalStateException at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:524) at groovers.LoginServlet.doPost(LoginServlet.java:100) at javax.servlet.http.HttpServlet.service(HttpServlet.java:688) at javax.servlet.http.HttpServlet.service(HttpServlet.java:770) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231) at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:722) </code></pre> <p>Please help me solve this problem.</p>
15,392,646
3
2
null
2013-03-13 17:34:05.203 UTC
2
2013-03-17 09:09:08.947 UTC
2013-03-17 09:09:08.947 UTC
null
472,792
null
1,306,343
null
1
6
jakarta-ee|servlets
57,915
<p>I think before you call <code>sendRedirect()</code> the response is getting committed. It means the server has already flush the headers to the client. This will usually happen when either the response buffer has reached max size or someone has called flush() explicitly.</p> <p>Since the response is already committed you cannot add any more headers. And because <code>sendRedirect()</code> requires <code>Location</code> header to be added to the response.</p> <p>The server will throw <code>IllegalSateException</code> exception.</p> <p><strong>How to Fix it?</strong></p> <p>Make sure you are not writing any data before you do <code>sendRedirect()</code>. In your code, i suspect <code>processRequest()</code> method is writing to the response.</p> <p>Please find here why the Response will get committed.</p> <p><a href="https://stackoverflow.com/questions/11305563/cause-of-servlets-response-already-committed">Cause of Servlet&#39;s &#39;Response Already Committed&#39;</a></p>
22,238,368
How can I require at least one checkbox be checked before a form can be submitted?
<p>I have a list of multiple check boxes. The user can check all of them, but at least one should be checked to allow form submission. How can I enforce that requirement?</p> <pre><code>&lt;p&gt;Box Set 1&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 1" required&gt;&lt;label&gt;Box 1&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 2" required&gt;&lt;label&gt;Box 2&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 3" required&gt;&lt;label&gt;Box 3&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 4" required&gt;&lt;label&gt;Box 4&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Box Set 2&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 5" required&gt;&lt;label&gt;Box 5&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 6" required&gt;&lt;label&gt;Box 6&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 7" required&gt;&lt;label&gt;Box 7&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 8" required&gt;&lt;label&gt;Box 8&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Box Set 3&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 9" required&gt;&lt;label&gt;Box 9&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Box Set 4&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 10" required&gt;&lt;label&gt;Box 10&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
22,238,811
11
2
null
2014-03-06 23:27:03.72 UTC
11
2022-06-14 11:20:13.85 UTC
2019-10-28 19:59:54.69 UTC
null
2,756,409
null
2,110,210
null
1
49
html|css|validation|checkbox
168,641
<p>Here's an example using jquery and your html.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; $(document).ready(function () { $('#checkBtn').click(function() { checked = $("input[type=checkbox]:checked").length; if(!checked) { alert("You must check at least one checkbox."); return false; } }); }); &lt;/script&gt; &lt;p&gt;Box Set 1&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 1" required&gt;&lt;label&gt;Box 1&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 2" required&gt;&lt;label&gt;Box 2&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 3" required&gt;&lt;label&gt;Box 3&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 4" required&gt;&lt;label&gt;Box 4&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Box Set 2&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 5" required&gt;&lt;label&gt;Box 5&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 6" required&gt;&lt;label&gt;Box 6&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 7" required&gt;&lt;label&gt;Box 7&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 8" required&gt;&lt;label&gt;Box 8&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Box Set 3&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 9" required&gt;&lt;label&gt;Box 9&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Box Set 4&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;input name="BoxSelect[]" type="checkbox" value="Box 10" required&gt;&lt;label&gt;Box 10&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;input type="button" value="Test Required" id="checkBtn"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
21,708,339
Avoid Jackson serialization on non fetched lazy objects
<p>I have a simple controller that return a User object, this user have a attribute coordinates that have the hibernate property FetchType.LAZY.</p> <p>When I try to get this user, I always have to load all the coordinates to get the user object, otherwise when Jackson try to serialize the User throws the exception:</p> <blockquote> <p>com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session</p> </blockquote> <p>This is due to Jackson is trying to fetch this unfetched object. Here are the objects:</p> <pre><code>public class User{ @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") @JsonManagedReference("user-coordinate") private List&lt;Coordinate&gt; coordinates; } public class Coordinate { @ManyToOne @JoinColumn(name = "user_id", nullable = false) @JsonBackReference("user-coordinate") private User user; } </code></pre> <p>And the controller:</p> <pre><code>@RequestMapping(value = "/user/{username}", method=RequestMethod.GET) public @ResponseBody User getUser(@PathVariable String username) { User user = userService.getUser(username); return user; } </code></pre> <p>There is a way to tell Jackson to not serialize the unfetched objects? I've been looking other answers posted 3 years ago implementing jackson-hibernate-module. But probably it could be achieved with a new jackson feature.</p> <p>My versions are:</p> <ul> <li>Spring 3.2.5 </li> <li>Hibernate 4.1.7 </li> <li>Jackson 2.2</li> </ul> <p>Thanks in advance.</p>
21,760,361
15
6
null
2014-02-11 17:07:14.193 UTC
62
2021-05-27 16:48:57.387 UTC
2016-05-11 14:59:38.367 UTC
null
1,426,227
null
1,416,034
null
1
93
java|spring|hibernate|serialization|jackson
89,786
<p>I finally found the solution! thanks to indybee for giving me a clue.</p> <p>The tutorial <a href="http://blog.pastelstudios.com/2012/03/12/spring-3-1-hibernate-4-jackson-module-hibernate/">Spring 3.1, Hibernate 4 and Jackson-Module-Hibernate</a> have a good solution for Spring 3.1 and earlier versions. But since version 3.1.2 Spring have his own <strong>MappingJackson2HttpMessageConverter</strong> with almost the same functionality as the one in the tutorial, so we don't need to create this custom HTTPMessageConverter.</p> <p>With javaconfig we don't need to create a <strong>HibernateAwareObjectMapper</strong> too, we just need to add the <strong>Hibernate4Module</strong> to the default <strong>MappingJackson2HttpMessageConverter</strong> that Spring already have and add it to the HttpMessageConverters of the application, so we need to:</p> <ol> <li><p>Extend our spring config class from <strong>WebMvcConfigurerAdapter</strong> and override the method <strong>configureMessageConverters</strong>. </p></li> <li><p>On that method add the <strong>MappingJackson2HttpMessageConverter</strong> with the <strong>Hibernate4Module</strong> registered in a previus method.</p></li> </ol> <p>Our config class should look like this:</p> <pre><code>@Configuration @EnableWebMvc public class MyConfigClass extends WebMvcConfigurerAdapter{ //More configuration.... /* Here we register the Hibernate4Module into an ObjectMapper, then set this custom-configured ObjectMapper * to the MessageConverter and return it to be added to the HttpMessageConverters of our application*/ public MappingJackson2HttpMessageConverter jacksonMessageConverter(){ MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); //Registering Hibernate4Module to support lazy objects mapper.registerModule(new Hibernate4Module()); messageConverter.setObjectMapper(mapper); return messageConverter; } @Override public void configureMessageConverters(List&lt;HttpMessageConverter&lt;?&gt;&gt; converters) { //Here we add our custom-configured HttpMessageConverter converters.add(jacksonMessageConverter()); super.configureMessageConverters(converters); } //More configuration.... } </code></pre> <p>If you have an xml configuration, you don't need to create your own MappingJackson2HttpMessageConverter either, but you do need to create the personalized mapper that appears in the tutorial (HibernateAwareObjectMapper), so your xml config should look like this:</p> <pre><code>&lt;mvc:message-converters&gt; &lt;bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"&gt; &lt;property name="objectMapper"&gt; &lt;bean class="com.pastelstudios.json.HibernateAwareObjectMapper" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/mvc:message-converters&gt; </code></pre> <p>Hope this answer be understandable and helps someone find the solution for this problem, any questions feel free to ask!</p>
17,620,405
The annotation @Index is disallowed for this location
<p>When trying to use the <code>@Index</code> annotation from <code>javax.persistence</code>, Eclipse gives me this error.</p> <p>I'm using it right before a <code>java.util.Date</code> field, inside a class annotated with <code>@Entity</code>.</p> <p>Before, I was using <code>org.hibernate.annotations.Index</code> in the exact same place and it was fine.</p> <p>The problem started after I've upgraded <em>hibernate-core</em> from <em>4.1.9.Final</em> to <em>4.3.0.Beta3</em> and <em>hibernate-commons-annotation</em>s from <em>4.0.1</em> to <em>4.0.2</em>. It says <code>@Index</code> is deprecated and recommends the <code>javax.persistence</code> one.</p> <p>All docs and examples I've found put <code>@Index</code> before class members. What am I missing?</p>
17,620,465
3
0
null
2013-07-12 17:12:25.38 UTC
4
2017-11-13 09:02:32.93 UTC
2017-11-13 09:02:32.93 UTC
null
4,813,586
null
2,004,857
null
1
30
java|jpa|hibernate-annotations
23,481
<p>The JPA Index annotation can only be used as part of another annotation like <code>@Table</code>, <code>@SecondaryTable</code>, etc. (see the See Also section in the <a href="http://docs.oracle.com/javaee/7/api/javax/persistence/Index.html" rel="noreferrer">javadoc</a>):</p> <pre><code>@Table(indexes = { @Index(...) }) </code></pre>
18,321,244
Is C++11 atomic<T> usable with mmap?
<p>I want to add network control of a handful of parameters used by a service (daemon) running on a Linux embedded system. There's no need for procedure calls, each parameter can be polled in a very natural way. Shared memory seems a nice way to keep networking code out of the daemon, and limit shared access to a carefully controlled set of variables.</p> <p>Since I don't want partial writes to cause visibility of values never written, I was thinking of using <code>std::atomic&lt;bool&gt;</code> and <code>std::atomic&lt;int&gt;</code>. However, I'm worried that <code>std::atomic&lt;T&gt;</code> might be implemented in a way that only works with C++11 threads and not with multiple processes (potentially, not even with OS threads). Specifically, if the implementation uses any data structures stored outside the shared memory block, in a multi-process scenario this would fail.</p> <p>I do see some requirements which suggest to be that <code>std::atomic</code> won't hold an embedded lock object or pointer to additional data:</p> <blockquote> <p>The atomic integral specializations and the specialization <code>atomic&lt;bool&gt;</code> shall have standard layout. They shall each have a trivial default constructor and a trivial destructor. They shall each support aggregate initialization syntax.</p> <p>There shall be pointer partial specializations of the atomic class template. These specializations shall have standard layout, trivial default constructors, and trivial destructors. They shall each support aggregate initialization syntax.</p> </blockquote> <p>Trivial default construction and destruction seems to me to exclude associated per-object data, whether stored inside the object, via a pointer member variable, or via an external mapping.</p> <p>However, I see nothing that excludes an implementation from using a single global mutex / critical section (or even a global collection, as long as the collection elements aren't associated with individual atomic objects -- something along the lines of a cache association scheme could be used to reduce false conflicts). Obviously, access from multiple processes would fail on an implementation using a global mutex, because the users would have independent mutexes and not actually synchronize with each other.</p> <p>Is an implementation of <code>atomic&lt;T&gt;</code> allowed to do things that are incompatible with inter-process shared memory, or are there other rules that make it safe?</p> <hr /> <p>I just noticed that trivial default construction leaves the object in a not-ready state, and a call to <code>atomic_init</code> is required. And the Standard mentions initialization of locks. If these are stored inside the object (and dynamic memory allocation seems impossible, since the destructor remains trivial) then they would be shared between processes. But I'm still concerned about the possibility of a global mutex.</p> <p>In any case, guaranteeing a single call to <code>atomic_init</code> for each variable in a shared region seems difficult... so I suppose I'll have to steer away from the C++11 atomic types.</p>
19,937,333
2
8
null
2013-08-19 19:07:47.19 UTC
15
2013-11-12 18:41:27.567 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
103,167
null
1
34
c++|multithreading|c++11|shared-memory|atomic
6,893
<p>I'm two months late, but I'm having the exact same problem right now and I think I've found some sort of an answer. The short version is that it should work, but I'm not sure if I'd depend on it.</p> <p>Here's what I found:</p> <ul> <li><p>The C++11 standard defines a new memory model, but it has no notion of OS-level "process", so anything multiprocessing-related is non-standard.</p></li> <li><p>However, section 29.4 "Lock-free property" of the standard (or at least the draft I have, N3337) ends with this note:</p> <blockquote> <p>[ Note: Operations that are lock-free should also be address-free. That is, atomic operations on the same memory location via two different addresses will communicate atomically. The implementation should not depend on any per-process state. This restriction enables communication by memory that is mapped into a process more than once and by memory that is shared between two processes. — end note ]</p> </blockquote> <p>This sounds very promising. :)</p></li> <li><p>That note appears to come from <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2427.html">N2427</a>, which is even more explicit:</p> <blockquote> <p>To facilitate inter-process communication via shared memory, it is our intent that lock-free operations also be address-free. That is, atomic operations on the same memory location via two different addresses will communicate atomically. The implementation shall not depend on any per-process state. While such a definition is beyond the scope of the standard, a clear statement of our intent will enable a portable expression of class of a programs already extant. </p> </blockquote> <p>So it appears that yes, all lock-free operations are supposed to work in this exact scenario.</p></li> <li><p>Now, operations on <code>std::atomic&lt;type&gt;</code> are atomic but they may or may not be lock-free for particular <code>type</code>, depending on capabilities of the platform. And We can check any variable <code>x</code> by calling <code>x.is_lock_free()</code>.</p></li> <li><p>So why did I write that I would not depend on this? I can't find any kind of documentation for gcc, llvm or anyone else that's explicit about this.</p></li> </ul>
23,430,395
Glob search files in date order?
<p>I have this line of code in my python script. It searches all the files in in a particular directory for * cycle *.log. </p> <pre><code>for searchedfile in glob.glob("*cycle*.log"): </code></pre> <p>This works perfectly, however when I run my script to a network location it does not search them in order and instead searches randomly. </p> <p>Is there a way to force the code to search by date order?</p> <p>This question has been asked for php but I am not sure of the differences.</p> <p>Thanks</p>
23,430,865
6
4
null
2014-05-02 14:21:18.977 UTC
10
2018-03-25 13:05:34.41 UTC
null
null
null
null
3,524,351
null
1
42
python|date|search|glob
52,607
<p>To sort files by date:</p> <pre><code>import glob import os files = glob.glob("*cycle*.log") files.sort(key=os.path.getmtime) print("\n".join(files)) </code></pre> <p>See also <a href="https://docs.python.org/3/howto/sorting.html">Sorting HOW TO</a>.</p>
23,420,795
Why would a button click event cause site to reload in a Bootstrap form?
<p>I'm using <strong>jQuery</strong>'s <code>show()</code> and <code>hide()</code> functions on <code>divs</code> in order to <em>code</em> or <em>simulate</em> different consecutive form sections.</p> <p>I've made a button that hides a <code>div</code> when it's clicked. What's strange is that once the button is clicked, the page will reload and come back to the div shown at first <code>$(document).ready()</code>.</p> <p>What's even more strange is that this problem mentioned above won't happen if you click in the nav bar text before clicking in the "continuar" button (Then the expected page will appear without reloading and showing the first page again).</p> <p><strong>The form can be visited here:</strong></p> <blockquote> <p><code>http://registropsicologos.maricelaaguilarflores.com:20791</code></p> </blockquote> <p>The blue button is the responsible for the page reload problem, unless you click <em>Visualizar</em> at nav bar before clicking in "continuar".</p> <p>I can't understand why this is happening, I've used <code>.show()</code> and <code>.hide()</code> before and this problem wasn't happening.</p> <p><strong>Here's the relevant JavaScript code:</strong></p> <pre><code>$(document).ready(function () { mostrarFormularioRegistro() $(".btnSeccion").click(function() { btnMostrarSeccion($(this)) }) }) function mostrarFormularioRegistro () { $("#formularioRegistro").show() mostrarSeccion(1) $("#DB").hide() } function mostrarSeccion (seccion) { for (var i = 1; i &lt;4; i++) { if (i===seccion) $("#seccionRegistro"+i).show() else $("#seccionRegistro"+i).hide() } } function btnMostrarSeccion (idBtnSeccion) { var seccion = parseInt(idBtnSeccion.attr("id").slice(-1)) if (seccion == 3) mostrarSeccion(1) else mostrarSeccion(seccion+1) } </code></pre> <p><strong>This is the body markup:</strong></p> <pre><code>&lt;body&gt; &lt;div class="container" id="proyecto"&gt; &lt;ul class="nav nav-tabs"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Registrar&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Visualizar&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="formulario"&gt; &lt;div class="container" id="seccionRegistro1"&gt; &lt;form class="form-horizontal" role="form"&gt; &lt;div class="form-group"&gt; &lt;label for="inputNombre" class="col-sm-2 control-label"&gt;Nombre(s)&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputNombre" placeholder="Nombre(s)"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputApellidos" class="col-sm-2 control-label"&gt;Apellidos&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputApellidos" placeholder="Apellidos"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputEdad" class="col-sm-2 control-label"&gt;Edad&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputEdad" placeholder="Apellidos"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputTel" class="col-sm-2 control-label"&gt;Teléfono&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputTel" placeholder="Teléfono"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputCel" class="col-sm-2 control-label"&gt;Celular&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputCel" placeholder="Celular"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-offset-2 col-sm-10"&gt; &lt;button class="btn btn-primary btnSeccion" id="btnSeccion1"&gt;Continuar&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="container" id="seccionRegistro2"&gt; &lt;form class="form-horizontal" role="form"&gt; &lt;div class="form-group"&gt; &lt;label for="inputEscolaridad" class="col-sm-2 control-label"&gt;Escolaridad&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputEscolaridad" placeholder="Escolaridad"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputAlmaMater" class="col-sm-2 control-label"&gt;Egresado de&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputAlmaMater" placeholder="Egresado de"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputAñoEgreso" class="col-sm-2 control-label"&gt;Año de egreso&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputAñoEgreso" placeholder="Año de egreso"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputCedula" class="col-sm-2 control-label"&gt;Cédula Profesional&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputCedula" placeholder="Cédula Profesional"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="checkPosgrado" class="col-sm-2 control-label"&gt;Estudios de Posgrado&lt;/label&gt; &lt;div class="col-sm-1"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox"&gt; Sí &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-8"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-4"&gt; &lt;input type="text" class="form-control" placeholder="Posgrado" id="inputPosgrado1"&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;input type="text" class="form-control" placeholder="Posgrado" id="inputPosgrado2"&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;input type="text" class="form-control" placeholder="Posgrado" id="inputPosgrado3"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputCedula" class="col-sm-2 control-label"&gt;Cédula Profesional&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoClinica" value="option1"&gt; Clínica &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoSocial" value="option1"&gt; Social &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoLaboral" value="option1"&gt; Laboral &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoEducativa" value="option1"&gt; Educativa &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputTrabajo" class="col-sm-2 control-label"&gt;Institución de trabajo&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputTrabajo" placeholder="Institución de trabajo"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="trabajoIndependiente" class="col-sm-2 control-label"&gt;Desarrollo Profesional Independiente&lt;/label&gt; &lt;div class="col-sm-1"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox" id="trabajoIndependiente"&gt; Sí &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-8"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;input type="text" class="form-control" placeholder="Actividad independiente" id="inputActividadIndependiente1" disabled="true"&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input type="text" class="form-control" placeholder="Actividad independiente" id="inputActividadIndependiente2" disabled="true"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="checkPosgrado" class="col-sm-2 control-label"&gt;Actividades de trabajo no relacionadas con la psicología&lt;/label&gt; &lt;div class="col-sm-1"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox" id="actividadesAjenasPsicologia"&gt; Sí &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-8"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;input type="text" class="form-control" placeholder="Actividad" id="actividadNoPsicologia1" disabled="true"&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input type="text" class="form-control" placeholder="Actividad" id="actividadNoPsicologia2" disabled="true"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-offset-2 col-sm-10"&gt; &lt;button class="btn btn-primary btnSeccion" id="btnSeccion2"&gt;Continuar&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="container" id="seccionRegistro3"&gt; &lt;form class="form-horizontal" role="form"&gt; &lt;div class="form-group"&gt; &lt;label for="actividadesInteres" class="col-sm-2 control-label"&gt;Actvidades profesionales en las que le gustaría participar&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoClinica" value="option1"&gt; Conferencias y encuentros &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoSocial" value="option1"&gt; Cursos &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoLaboral" value="option1"&gt; Talleres &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoEducativa" value="option1"&gt; Diplomados &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoEducativa" value="option1"&gt; Maestría &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoEducativa" value="option1"&gt; Doctorado &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="capacitacionInteres" class="col-sm-2 control-label"&gt;Areas de la psicología en las que le gustaría capacitarse&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoClinica" value="Clínica"&gt; Clínica &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoSocial" value="Social"&gt; Social &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoLaboral" value="Laboral"&gt; Laboral &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoEducativa" value="Educativa"&gt; Educativa &lt;/label&gt; &lt;label class="checkbox-inline"&gt; &lt;input type="checkbox" id="inputAreaTrabajoEducativa" value="Todas"&gt; Todas &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="inputNombre" class="col-sm-2 control-label"&gt;¿Alguna temática en particular que le gustaría conocer o capacitarse?&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="inputInteresCapacitacion" placeholder="Temática de interés"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="checkPosgrado" class="col-sm-2 control-label"&gt;¿Pertenece a alguna agrupación relacionada con el campo de la psicología?&lt;/label&gt; &lt;div class="col-sm-1"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox" id="actividadesAjenasPsicologia"&gt; Sí &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-8"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;input type="text" class="form-control" placeholder="Actividad" id="Agrupación" disabled="true"&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input type="text" class="form-control" placeholder="Actividad" id="Agrupación" disabled="true"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="checkPosgrado" class="col-sm-2 control-label"&gt;¿Ha participado con anterioridad en algún evento de la Asociación de Psicólogos de Tuxtepec?&lt;/label&gt; &lt;div class="col-sm-1"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox" id="participacionEventos"&gt; Sí &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-8"&gt; &lt;select multiple class="form-control" id="eventosAsistidos"&gt; &lt;option value="abrazoterapia"&gt;Abrazoterapia&lt;/option&gt; &lt;option value="tallerMujeres"&gt;Taller autoestima mujeres&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;p class="bg-success"&gt; ¿Le gustaría pertenecer como miembro activo de la Asociación de Psicólogos de Tuxtepec, A.C. "Manos Unidas por un vivir más pleno?" &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;label&gt; &lt;input type="checkbox" id="idInteresMiembro"&gt;&lt;strong&gt;Sí&lt;/strong&gt; &lt;/label&gt; &lt;/p&gt; &lt;div class="col-sm-offset-2 col-sm-10"&gt; &lt;button class="btn btn-primary btnSeccion" id="btnSeccion3"&gt;Continuar&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
23,420,958
8
4
null
2014-05-02 04:33:56.86 UTC
4
2021-05-06 16:51:23.963 UTC
2014-05-02 05:03:42.013 UTC
null
742,560
null
742,560
null
1
36
javascript|jquery|html
40,129
<p>A <code>&lt;button&gt;</code> tag uses Submit behavior by default. Thus your page submits the form when the button is clicked and this looks like a page refresh itself. To work around this you can either use an <code>input</code> tag</p> <pre><code>&lt;input type="button" class="btn btn-primary btnSeccion" id="btnSeccion3" value="Continuar"/&gt; </code></pre> <p>to do the same effect. Or you can cancel the Submit in your button's click Event Handler (if that's what you want) like this: </p> <pre><code>$(".btnSeccion").click(function(event) { btnMostrarSeccion($(this)); event.preventDefault(); }) </code></pre>
43,224,012
.NET Core SDK versions - which to uninstall?
<p>I have the following versions of .NET Core SDKs installed on my machine:</p> <p><a href="https://i.stack.imgur.com/kPQYJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kPQYJ.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/BxJn0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BxJn0.png" alt="enter image description here"></a></p> <p>Please confirm that I understand what each of these is (and if I can uninstall them):</p> <p><strong>.NET Core SDK 1.0.0 (x64) Installer (x64)</strong>: This was installed along with VS2017</p> <p><strong>.NET Core SDK 1.0.1 (x64)</strong>: Downloaded somewhere <a href="https://www.microsoft.com/net/core" rel="noreferrer">here</a> and installed manually. Exactly the same as the 1.0.0 SDK above except that it <a href="https://github.com/dotnet/core/blob/master/release-notes/1.1/1.1.1.md" rel="noreferrer">includes support for Fedora 24 and OpenSUSE 42.1</a>. <strong>So as a Windows user, can I uninstall this?</strong></p> <p>The other four <strong>Microsoft .NET Core 1.x.x SDKs</strong> are various versions of the VS2015 (and project.json) preview tooling and can thus be uninstalled?</p>
43,225,707
4
3
null
2017-04-05 07:00:03.747 UTC
7
2021-12-14 11:43:27.62 UTC
null
null
null
null
589,558
null
1
31
asp.net-core|.net-core
26,549
<p>First of all, this is the page I find the most useful to understand the complicated versioning of .NET CORE: <a href="https://github.com/dotnet/core/blob/master/release-notes/download-archive.md" rel="noreferrer">https://github.com/dotnet/core/blob/master/release-notes/download-archive.md</a></p> <p>Then, something that you might already know but that was unclear to me at some point: there is a different versioning between runtimes and SDK and it's sometime complicated to follow. When you install some SDKs it's coming with associated runtimes, for instance .NET CORE SDK 1.0.1 comes with the runtime FTS 1.1.1 and LTS 1.0.4 ... to see that, the creation date of folders installed here can be informative: 'C:\Program Files\dotnet\sdk' for the SDK and 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App' for the runtimes. </p> <p>So, let me tell you what I think of your statement.</p> <blockquote> <p>.NET Core SDK 1.0.0 (x64) Installer (x64): This was installed along with VS2017</p> </blockquote> <p>Agreed. It corresponds to the ".NET Core SDK 1.0.0 and 1.0.1" part of <a href="https://github.com/dotnet/core/blob/master/release-notes/1.0/1.0.4.md" rel="noreferrer">https://github.com/dotnet/core/blob/master/release-notes/1.0/1.0.4.md</a>.</p> <blockquote> <p>.NET Core SDK 1.0.1 (x64): Downloaded somewhere here and installed manually. Exactly the same as the 1.0.0 SDK above except that it includes support for Fedora 24 and OpenSUSE 42.1. So as a Windows user, can I uninstall this?</p> </blockquote> <p>Agreed, as stated on the same link as above. My concern is that <strong>if you uninstall that you might end up uninstalling the associated runtimes: FTS 1.1.1 and LTS 1.0.4</strong>. On my machine, those have been installed at the same date as this SDK and haven't been reinstalled with VS2017 so I'm not sure how the uninstaller would behave.</p> <blockquote> <p>The other four Microsoft .NET Core 1.x.x SDKs are various versions of the VS2015 (and project.json) preview tooling and can thus be uninstalled?</p> </blockquote> <p>Visual Studio 2015 is compatible with all SDKs up to preview 2.X based on project.json, preview 3 and upward removed the .json support and moved to .csproj, only compatible with Visual 2017. So if you are only using VS2017 and the latest runtimes 1.0.4/1.1.1 you can safely removed all those. Just <strong>make sure that your project is not targeting a particular runtime that you would be removing doing so</strong>, see the <code>frameworks</code> of <a href="https://docs.microsoft.com/en-us/dotnet/articles/core/tools/project-json-to-csproj" rel="noreferrer">https://docs.microsoft.com/en-us/dotnet/articles/core/tools/project-json-to-csproj</a></p> <p>A generic comment: .NET CORE is supposed to be portable, so its deployement is supposed to be very easy, you don't really have to install it, just copy the proper folder and then set the right env variables and it should be working, it is not deeply modofying your env (no registry entries, no registration of tons of components ...) so you should be able to install / uninstall and test it quite safely. At least, that's my understanding of what MS is trying to do.</p>
43,074,144
Vue.js Input field loses its focus after entry of one character
<p>I have a view with an input field, which can be multiplicated by a given button. The problem is that after any entry of a char, the focus of the input field is lost. You have to click again to enter another char.</p> <p>Do someone have a clue what could be the problem?</p> <p>My model:</p> <pre><code>'model': [ ..., 'filter': [ ..., 'something': [ 'string' ] ] ] </code></pre> <p>My code:</p> <pre><code>&lt;div v-for="(something, index) in model.filter.something" v-bind:key="something"&gt; &lt;input type="text" v-model.trim="model.filter.something[index]"/&gt; &lt;/div&gt; </code></pre>
43,095,557
1
4
null
2017-03-28 15:47:55.38 UTC
8
2017-03-31 13:28:25.93 UTC
2017-03-31 13:28:25.93 UTC
null
3,219,606
null
5,436,452
null
1
40
javascript|focus|vue.js
14,799
<p>The problem is that you are using a changing value as <code>key</code>. Vue expects <code>key</code> to indicate a unique identifier for the item. When you change it, it becomes a new item and must be re-rendered.</p> <p>In the snippet below, I have two loops, both using the same data source. The first is keyed the way you have it set up. The second uses <code>index</code> instead (that may not be what you need, but the point is to use something other than what you're editing; in this example, <code>key</code> isn't needed anyway). The first exhibits the loss-of-focus you describe, the second works as expected.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>new Vue({ el: '#app', data: { 'model': { 'filter': { 'something': [ 'string' ] } } } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"&gt;&lt;/script&gt; &lt;div id="app"&gt; &lt;div v-for="(something, index) in model.filter.something" v-bind:key="something"&gt; &lt;input type="text" v-model.trim="model.filter.something[index]" /&gt; {{something}} &lt;/div&gt; &lt;div v-for="(something, index) in model.filter.something"&gt; &lt;input type="text" v-model.trim="model.filter.something[index]" :key="index" /&gt; {{something}} &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
9,154,671
Distinction between processes and threads in Linux
<p>After reading up on <a href="https://stackoverflow.com/questions/807506/threads-vs-processes-in-linux">this answer</a> and "Linux Kernel Development" by Robert Love and, subsequently, on the <code>clone()</code> system call, I discovered that processes and threads in Linux are (almost) indistinguishable to the kernel. There are a few tweaks between them (discussed as being "more sharing" or "less sharing" in the quoted SO question), but I do still have some questions yet to be answered.</p> <p>I recently worked on a program involving a couple of POSIX threads and decided to experiment on this premise. On a process that creates two threads, all threads of course get a unique value returned by <code>pthread_self()</code>, <em>however</em>, not by <code>getpid()</code>.</p> <p>A sample program I created follows:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;unistd.h&gt; #include &lt;pthread.h&gt; void* threadMethod(void* arg) { int intArg = (int) *((int*) arg); int32_t pid = getpid(); uint64_t pti = pthread_self(); printf("[Thread %d] getpid() = %d\n", intArg, pid); printf("[Thread %d] pthread_self() = %lu\n", intArg, pti); } int main() { pthread_t threads[2]; int thread1 = 1; if ((pthread_create(&amp;threads[0], NULL, threadMethod, (void*) &amp;thread1)) != 0) { fprintf(stderr, "pthread_create: error\n"); exit(EXIT_FAILURE); } int thread2 = 2; if ((pthread_create(&amp;threads[1], NULL, threadMethod, (void*) &amp;thread2)) != 0) { fprintf(stderr, "pthread_create: error\n"); exit(EXIT_FAILURE); } int32_t pid = getpid(); uint64_t pti = pthread_self(); printf("[Process] getpid() = %d\n", pid); printf("[Process] pthread_self() = %lu\n", pti); if ((pthread_join(threads[0], NULL)) != 0) { fprintf(stderr, "Could not join thread 1\n"); exit(EXIT_FAILURE); } if ((pthread_join(threads[1], NULL)) != 0) { fprintf(stderr, "Could not join thread 2\n"); exit(EXIT_FAILURE); } return 0; } </code></pre> <p>(This was compiled [<code>gcc -pthread -o thread_test thread_test.c</code>] on 64-bit Fedora; due to the 64-bit types used for <code>pthread_t</code> sourced from <code>&lt;bits/pthreadtypes.h&gt;</code>, the code will require minor changes to compile on 32-bit editions.)</p> <p>The output I get is as follows:</p> <pre><code>[bean@fedora ~]$ ./thread_test [Process] getpid() = 28549 [Process] pthread_self() = 140050170017568 [Thread 2] getpid() = 28549 [Thread 2] pthread_self() = 140050161620736 [Thread 1] getpid() = 28549 [Thread 1] pthread_self() = 140050170013440 [bean@fedora ~]$ </code></pre> <p>By using scheduler locking in <code>gdb</code>, I can keep the program and its threads alive so I can capture what <code>top</code> says, which, <em>just showing processes</em>, is:</p> <pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 28602 bean 20 0 15272 1112 820 R 0.4 0.0 0:00.63 top 2036 bean 20 0 108m 1868 1412 S 0.0 0.0 0:00.11 bash 28547 bean 20 0 231m 16m 7676 S 0.0 0.4 0:01.56 gdb 28549 bean 20 0 22688 340 248 t 0.0 0.0 0:00.26 thread_test 28561 bean 20 0 107m 1712 1356 S 0.0 0.0 0:00.07 bash </code></pre> <p>And when showing threads, says:</p> <pre><code> PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 28617 bean 20 0 15272 1116 820 R 47.2 0.0 0:00.08 top 2036 bean 20 0 108m 1868 1412 S 0.0 0.0 0:00.11 bash 28547 bean 20 0 231m 16m 7676 S 0.0 0.4 0:01.56 gdb 28549 bean 20 0 22688 340 248 t 0.0 0.0 0:00.26 thread_test 28552 bean 20 0 22688 340 248 t 0.0 0.0 0:00.00 thread_test 28553 bean 20 0 22688 340 248 t 0.0 0.0 0:00.00 thread_test 28561 bean 20 0 107m 1860 1432 S 0.0 0.0 0:00.08 bash </code></pre> <p>It seems to be quite clear that programs, or perhaps the kernel, have a distinct way of defining threads in contrast to processes. Each thread has its own PID according to <code>top</code> - why?</p>
9,154,725
3
3
null
2012-02-06 01:22:10.563 UTC
13
2017-03-09 05:57:50.313 UTC
2017-05-23 11:54:06.34 UTC
null
-1
null
402,390
null
1
20
c|linux|multithreading
10,096
<p>These confusions all stem from the fact that the kernel developers originally held an irrational and wrong view that threads could be implemented almost entirely in userspace using kernel processes as the primitive, as long as the kernel offered a way to make them share memory and file descriptors. This lead to the notoriously bad LinuxThreads implementation of POSIX threads, which was rather a misnomer because it did not give anything remotely resembling POSIX thread semantics. Eventually LinuxThreads was replaced (by NPTL), but a lot of the confusing terminology and misunderstandings persist.</p> <p>The first and most important thing to realize is that "PID" means different things in kernel space and user space. What the kernel calls PIDs are actually kernel-level thread ids (often called TIDs), not to be confused with <code>pthread_t</code> which is a separate identifier. Each thread on the system, whether in the same process or a different one, has a unique TID (or "PID" in the kernel's terminology).</p> <p>What's considered a PID in the POSIX sense of "process", on the other hand, is called a "thread group ID" or "TGID" in the kernel. Each process consists of one or more threads (kernel processes) each with their own TID (kernel PID), but all sharing the same TGID, which is equal to the TID (kernel PID) of the initial thread in which <code>main</code> runs.</p> <p>When <code>top</code> shows you threads, it's showing TIDs (kernel PIDs), not PIDs (kernel TGIDs), and this is why each thread has a separate one.</p> <p>With the advent of NPTL, most system calls that take a PID argument or act on the calling <em>process</em> were changed to treat the PID as a TGID and act on the whole "thread group" (POSIX process).</p>
9,620,278
How do I make calls to a REST API using C#?
<p>This is the code I have so far:</p> <pre><code> public class Class1 { private const string URL = &quot;https://sub.domain.com/objects.json?api_key=123&quot;; private const string DATA = @&quot;{&quot;&quot;object&quot;&quot;:{&quot;&quot;name&quot;&quot;:&quot;&quot;Name&quot;&quot;}}&quot;; static void Main(string[] args) { Class1.CreateObject(); } private static void CreateObject() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = &quot;POST&quot;; request.ContentType = &quot;application/json&quot;; request.ContentLength = DATA.Length; StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); requestWriter.Write(DATA); requestWriter.Close(); try { WebResponse webResponse = request.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); Console.Out.WriteLine(response); responseReader.Close(); } catch (Exception e) { Console.Out.WriteLine(&quot;-----------------&quot;); Console.Out.WriteLine(e.Message); } } } </code></pre> <p>The problem is that I think the exception block is being triggered (because when I remove the try-catch, I get a server error (500) message. But I don't see the Console.Out lines I put in the catch block.</p> <p>My Console:</p> <pre class="lang-none prettyprint-override"><code>The thread 'vshost.NotifyLoad' (0x1a20) has exited with code 0 (0x0). The thread '&lt;No Name&gt;' (0x1988) has exited with code 0 (0x0). The thread 'vshost.LoadReference' (0x1710) has exited with code 0 (0x0). 'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'c:\users\l. preston sego iii\documents\visual studio 11\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe', Symbols loaded. 'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. A first chance exception of type 'System.Net.WebException' occurred in System.dll The thread 'vshost.RunParkingWindow' (0x184c) has exited with code 0 (0x0). The thread '&lt;No Name&gt;' (0x1810) has exited with code 0 (0x0). The program '[2780] ConsoleApplication1.vshost.exe: Program Trace' has exited with code 0 (0x0). The program '[2780] ConsoleApplication1.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0). </code></pre>
17,459,045
17
3
null
2012-03-08 15:35:01.27 UTC
190
2022-02-03 18:39:16.84 UTC
2021-01-30 21:54:29.867 UTC
null
285,795
null
356,849
null
1
423
c#|.net|rest|.net-4.5
1,353,423
<p>The ASP.NET Web API has replaced the <a href="https://en.wikipedia.org/wiki/Windows_Communication_Foundation" rel="noreferrer">WCF</a> Web API previously mentioned.</p> <p>I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for &quot;call restful service C#&quot;.</p> <p>Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a <a href="https://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_services" rel="noreferrer">RESTful</a> service. This is available as a <a href="https://en.wikipedia.org/wiki/NuGet" rel="noreferrer">NuGet</a> package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.</p> <p>Here's how your example would look when implemented using the ASP.NET Web API Client Library:</p> <pre><code>using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; namespace ConsoleProgram { public class DataObject { public string Name { get; set; } } public class Class1 { private const string URL = &quot;https://sub.domain.com/objects.json&quot;; private string urlParameters = &quot;?api_key=123&quot;; static void Main(string[] args) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(URL); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;)); // List data response. HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. if (response.IsSuccessStatusCode) { // Parse the response body. var dataObjects = response.Content.ReadAsAsync&lt;IEnumerable&lt;DataObject&gt;&gt;().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll foreach (var d in dataObjects) { Console.WriteLine(&quot;{0}&quot;, d.Name); } } else { Console.WriteLine(&quot;{0} ({1})&quot;, (int)response.StatusCode, response.ReasonPhrase); } // Make any other calls using HttpClient here. // Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous. client.Dispose(); } } } </code></pre> <p>If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: <em><a href="https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed">Do HttpClient and HttpClientHandler have to be disposed between requests?</a></em></p> <p>For more details, including other examples, see <em><a href="http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client" rel="noreferrer">Call a Web API From a .NET Client (C#)</a></em></p> <p>This blog post may also be useful: <em><a href="http://johnnycode.com/2012/02/23/consuming-your-own-asp-net-web-api-rest-service/" rel="noreferrer">Using HttpClient to Consume ASP.NET Web API REST Services</a></em></p>
18,228,324
I need to generate uuid for my rails application. What are the options(gems) I have?
<p>I use Rails 3.0.20 and ruby 1.8.7 (2011-06-30 patchlevel 352)</p> <p>Please suggest me the best plugin to generate guid.</p>
18,228,453
4
3
null
2013-08-14 09:44:25.133 UTC
13
2022-05-27 06:40:24.263 UTC
null
null
null
null
948,299
null
1
110
ruby-on-rails|ruby|ruby-on-rails-3|guid|uuid
82,368
<p>There are plenty of options, I recommend not to add additional dependencies and use <code>SecureRandom</code> which is builtin:</p> <pre><code>SecureRandom.uuid #=&gt; &quot;1ca71cd6-08c4-4855-9381-2f41aeffe59c&quot; </code></pre> <p>See other possible formats <a href="https://apidock.com/rails/ActiveSupport/SecureRandom" rel="noreferrer">here</a>.</p>
18,234,378
Using sed to split a string with a delimiter
<p>I have a string in the following format:</p> <p><code>string1:string2:string3:string4:string5</code></p> <p>I'm trying to use <code>sed</code> to split the string on <code>:</code> and print each sub-string on a new line. Here is what I'm doing:</p> <p><code>cat ~/Desktop/myfile.txt | sed s/:/\\n/</code> </p> <p>This prints:</p> <pre><code>string1 string2:string3:string4:string5 </code></pre> <p>How can I get it to split on each delimiter?</p>
18,234,407
6
1
null
2013-08-14 14:22:55.637 UTC
18
2019-01-07 06:43:28.67 UTC
null
null
null
null
1,492,471
null
1
62
linux|bash|sed|string-split
214,328
<p>To split a string with a delimiter with GNU sed you say:</p> <pre><code>sed 's/delimiter/\n/g' # GNU sed </code></pre> <p>For example, to split using <code>:</code> as a delimiter:</p> <pre><code>$ sed 's/:/\n/g' &lt;&lt;&lt; "he:llo:you" he llo you </code></pre> <p>Or with a non-GNU sed:</p> <pre><code>$ sed $'s/:/\\\n/g' &lt;&lt;&lt; "he:llo:you" he llo you </code></pre> <hr> <p>In this particular case, you missed the <code>g</code> after the substitution. Hence, it is just done once. See:</p> <pre><code>$ echo "string1:string2:string3:string4:string5" | sed s/:/\\n/g string1 string2 string3 string4 string5 </code></pre> <p><code>g</code> stands for <code>g</code>lobal and means that the substitution has to be done globally, that is, for any occurrence. See that the default is 1 and if you put for example 2, it is done 2 times, etc.</p> <p>All together, in your case you would need to use:</p> <pre><code>sed 's/:/\\n/g' ~/Desktop/myfile.txt </code></pre> <p>Note that you can directly use the <code>sed ... file</code> syntax, instead of unnecessary piping: <code>cat file | sed</code>.</p>
15,313,469
Java Keyboard Keycodes list
<p>Can anybody provide me with the Key Code integer list for individual keys used on the Keyboard for the KeyEvent class in java?</p> <p>I want to create a dropdown list of all the keyboard keys for the user to select. I need the list specific to Keyboard. The VK constants does not help in this case because I need a 'list' of Keys used on the Keyboard. <a href="https://stackoverflow.com/questions/1627925/where-can-i-find-a-list-of-keyboard-keycodes">This post here</a> didn't come of use because it's for Javascript and the codes aren't the same for all keys comparing with the <a href="http://docs.oracle.com/javase/7/docs/api/constant-values.html#java.awt.event.KeyEvent.VK_M" rel="noreferrer">javadoc</a>. Also the KeyCode values used in <a href="http://docs.oracle.com/javase/7/docs/api/constant-values.html#java.awt.event.KeyEvent.VK_M" rel="noreferrer">javadoc</a> are all arranged in Alphabetical Order, so it's hard to find the Keyboard keys over there. I tried googling for sources but nothing interesting came up just the Javascript one. Should I just compile them one by one myself or is there an easier way?</p> <p>Edit: I know about VK. I need to use KeyEvent.getKeyText function to store each of the keyboard keys in a dropdown menu. So i need the list. That's why I asked should I need to compile them myself. I should have mentioned that earlier. It would be a waste of time doing that for each key. </p>
15,313,498
5
0
null
2013-03-09 17:04:29.203 UTC
5
2021-07-02 09:10:07.73 UTC
2017-05-23 12:16:43.803 UTC
null
-1
null
1,440,535
null
1
9
java|applet|keylistener|keyevent
111,334
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html" rel="noreferrer">KeyEvent</a> class has static fields with these values.</p> <p>For example, <code>KeyEvent.VK_A</code> represent "A" key.</p> <p>To get the fields names you can use reflection:</p> <pre><code>Field[] fields = java.awt.event.KeyEvent.class.getDeclaredFields(); for (Field f : fields) { if (Modifier.isStatic(f.getModifiers())) { System.out.println(f.getName()); } } </code></pre>
15,249,492
How to organize resources (styles, ...) in a complex WPF scenario?
<p>How can WPF resources - including styles, templates, etc. - be organized, so that I can use them across Windows, Pages or even Projects. What options do I have to achieve maximum re-usability of my resources and a maintainable structure (for example one file per Template)? </p> <p>For example: I am creating a WPF application and I want to use a TabControl, but I want to make major changes to it. So I could create a style in and apply it to the TabControl and TabItem. That's ok, but where can I place my resources to keep my Window XAML clear and have the style accessible from other Windows or projects as well?</p> <p>I found that I can add it to App.xaml but that is only a solution for one project and allows sharing just between items of this project. Also, I think it would be better to have these templates a little separate from other code, than placing it all in some page or app.xaml?</p>
15,249,742
3
1
null
2013-03-06 14:09:16.957 UTC
8
2017-06-01 12:27:52.34 UTC
2013-03-07 09:11:52.613 UTC
null
645,104
null
367,593
null
1
17
c#|wpf|templates|styles
10,142
<p>I usually create a seperate styling project, which I reference from the projects, which I want to style. The styling project has a fixed structure like this:</p> <p><img src="https://i.stack.imgur.com/YmGpQ.png" alt="Styling project"></p> <p>For every control, I create a styling <code>ResourceDictionary</code>. For example for my buttons:</p> <pre class="lang-xml prettyprint-override"><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Style x:Key="PrimaryButtonStyle" TargetType="Button"&gt; &lt;/Style&gt; &lt;Style x:Key="ToolbarButton" TargetType="Button"&gt; &lt;Setter Property="BorderThickness" Value="0" /&gt; &lt;Setter Property="Margin" Value="3"/&gt; &lt;Setter Property="Background" Value="Transparent"&gt;&lt;/Setter&gt; &lt;/Style&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>In one main <code>ResourceDictionary</code>, I merge all the other dictionaries, in this case in the file IncaDesign.xaml, which you can see in the picture above:</p> <pre class="lang-xml prettyprint-override"><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="clr-namespace:Commons.Controls;assembly=Commons"&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="Converter/Converter.xaml" /&gt; &lt;ResourceDictionary Source="Styles/Button.xaml" /&gt; &lt;ResourceDictionary Source="BitmapGraphics/Icons.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;!-- Default Styles --&gt; &lt;Style TargetType="Button" BasedOn="{StaticResource PrimaryButtonStyle}"&gt;&lt;/Style&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>Notice how I defined the default styles, which are applied automatically, unless you specify otherwise. In every window or control, that you want to style, you only need to reference this one <code>ResourceDictionary</code>. Note the definition of the source, which is a reference to the assembly (<code>/Commons.Styling;component...</code>)</p> <pre class="lang-xml prettyprint-override"><code>&lt;UserControl.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="/Commons.Styling;component/IncaDesign.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;/UserControl.Resources&gt; </code></pre> <p>Default styles will be set automatically now, and if you want to access a resource explicitly, you can do this, using <code>StaticResource</code>.</p> <pre class="lang-xml prettyprint-override"><code>&lt;Viewbox Height="16" Width="16" Margin="0,0,10,0"&gt; &lt;ContentControl Content="{StaticResource FileIcon32}" /&gt; &lt;/Viewbox&gt; </code></pre> <p>This is very nice solution in my opinion, which works for very complex solutions, including modular solutions, for example built with PRISM.</p>
15,283,523
Reshaping a 1-d array to a multidimensional array
<p>Taking into consideration the entire C++11 standard, is it possible for any conforming implementation to succeed the first assertion below but fail the latter?</p> <pre><code>#include &lt;cassert&gt; int main(int, char**) { const int I = 5, J = 4, K = 3; const int N = I * J * K; int arr1d[N] = {0}; int (&amp;arr3d)[I][J][K] = reinterpret_cast&lt;int (&amp;)[I][J][K]&gt;(arr1d); assert(static_cast&lt;void*&gt;(arr1d) == static_cast&lt;void*&gt;(arr3d)); // is this necessary? arr3d[3][2][1] = 1; assert(arr1d[3 * (J * K) + 2 * K + 1] == 1); // UB? } </code></pre> <p>If not, is this technically UB or not, and does that answer change if the first assertion is removed (is <code>reinterpret_cast</code> guaranteed to preserve addresses here?)? Also, what if the reshaping is done in the opposite direction (3d to 1d) or from a 6x35 array to a 10x21 array?</p> <p><strong>EDIT:</strong> If the answer is that this is UB because of the <code>reinterpret_cast</code>, is there some other strictly compliant way of reshaping (e.g., via <code>static_cast</code> to/from an intermediate <code>void *</code>)?</p>
15,284,276
2
6
null
2013-03-07 23:01:37.59 UTC
12
2021-03-20 22:15:48.127 UTC
2013-03-07 23:50:07.62 UTC
null
2,008,149
null
2,008,149
null
1
19
c++|c++11|multidimensional-array|language-lawyer
5,225
<p><strong>Update 2021-03-20:</strong></p> <p>This same question was <a href="https://www.reddit.com/r/cpp_questions/comments/m9a7fs/reinterpret_a_1d_array_as_a_2d_array/" rel="nofollow noreferrer">asked on Reddit</a> recently and it was pointed out that my original answer is flawed because it does not take into account this <a href="https://eel.is/c++draft/expr#basic.lval-11" rel="nofollow noreferrer">aliasing rule</a>:</p> <blockquote> <p>If a program attempts to access the stored value of an object through a glvalue whose type is not similar to one of the following types the behavior is undefined:</p> <ul> <li>the dynamic type of the object,</li> <li>a type that is the signed or unsigned type corresponding to the dynamic type of the object, or</li> <li>a char, unsigned char, or std​::​byte type.</li> </ul> </blockquote> <p>Under the rules for <a href="https://eel.is/c++draft/expr#conv.qual-2" rel="nofollow noreferrer">similarity</a>, these two array types are not similar for any of the above cases and therefore it is technically undefined behaviour to access the 1D array through the 3D array. (This is definitely one of those situations where, in practice, it will almost certainly work with most compilers/targets)</p> <p><em>Note that the references in the original answer refer to an older C++11 draft standard</em></p> <h1>Original answer:</h1> <h2><code>reinterpret_cast</code> of references</h2> <p>The standard states that an lvalue of type <code>T1</code> can be <code>reinterpret_cast</code> to a reference to <code>T2</code> if a pointer to <code>T1</code> can be <code>reinterpret_cast</code> to a pointer to <code>T2</code> (§5.2.10/11):</p> <blockquote> <p>An lvalue expression of type <code>T1</code> can be cast to the type “reference to <code>T2</code>” if an expression of type “pointer to <code>T1</code>” can be explicitly converted to the type “pointer to <code>T2</code>” using a reinterpret_cast.</p> </blockquote> <p>So we need to determine if a <code>int(*)[N]</code> can be converted to an <code>int(*)[I][J][K]</code>.</p> <h2><code>reinterpret_cast</code> of pointers</h2> <p>A pointer to <code>T1</code> can be <code>reinterpret_cast</code> to a pointer to <code>T2</code> if both <code>T1</code> and <code>T2</code> are standard-layout types and <code>T2</code> has no stricter alignment requirements than <code>T1</code> (§5.2.10/7):</p> <blockquote> <p>When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is <code>static_cast&lt;cv T2*&gt;(static_cast&lt;cv void*&gt;(v))</code> if both <code>T1</code> and <code>T2</code> are standard-layout types (3.9) and the alignment requirements of <code>T2</code> are no stricter than those of <code>T1</code>, or if either type is void.</p> </blockquote> <ol> <li><p>Are <code>int[N]</code> and <code>int[I][J][K]</code> standard-layout types?</p> <p><code>int</code> is a scalar type and arrays of scalar types are considered to be <em>standard-layout types</em> (§3.9/9).</p> <blockquote> <p>Scalar types, standard-layout class types (Clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called <em>standard-layout types</em>.</p> </blockquote> </li> <li><p>Does <code>int[I][J][K]</code> have no stricter alignment requirements than <code>int[N]</code>.</p> <p>The result of the <code>alignof</code> operator gives the alignment requirement of a complete object type (§3.11/2).</p> <blockquote> <p>The result of the <code>alignof</code> operator reflects the alignment requirement of the type in the complete-object case.</p> </blockquote> <p>Since the two arrays here are not subobjects of any other object, they are complete objects. Applying <code>alignof</code> to an array gives the alignment requirement of the element type (§5.3.6/3):</p> <blockquote> <p>When <code>alignof</code> is applied to an array type, the result shall be the alignment of the element type.</p> </blockquote> <p>So both array types have the same alignment requirement.</p> </li> </ol> <p>That makes the <code>reinterpret_cast</code> valid and equivalent to:</p> <pre><code>int (&amp;arr3d)[I][J][K] = *reinterpret_cast&lt;int (*)[I][J][K]&gt;(&amp;arr1d); </code></pre> <p>where <code>*</code> and <code>&amp;</code> are the built-in operators, which is then equivalent to:</p> <pre><code>int (&amp;arr3d)[I][J][K] = *static_cast&lt;int (*)[I][J][K]&gt;(static_cast&lt;void*&gt;(&amp;arr1d)); </code></pre> <h2><code>static_cast</code> through <code>void*</code></h2> <p>The <code>static_cast</code> to <code>void*</code> is allowed by the standard conversions (§4.10/2):</p> <blockquote> <p>A prvalue of type “pointer to cv <code>T</code>,” where <code>T</code> is an object type, can be converted to a prvalue of type “pointer to cv void”. The result of converting a “pointer to cv <code>T</code>” to a “pointer to cv void” points to the start of the storage location where the object of type <code>T</code> resides, as if the object is a most derived object (1.8) of type <code>T</code> (that is, not a base class subobject).</p> </blockquote> <p>The <code>static_cast</code> to <code>int(*)[I][J][K]</code> is then allowed (§5.2.9/13):</p> <blockquote> <p>A prvalue of type “pointer to cv1 <code>void</code>” can be converted to a prvalue of type “pointer to cv2 <code>T</code>,” where <code>T</code> is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.</p> </blockquote> <p><strong>So the cast is fine!</strong> But are we okay to access objects through the new array reference?</p> <h2>Accessing array elements</h2> <p>Performing array subscripting on an array like <code>arr3d[E2]</code> is equivalent to <code>*((E1)+(E2))</code> (§5.2.1/1). Let's consider the following array subscripting:</p> <pre><code>arr3d[3][2][1] </code></pre> <p>Firstly, <code>arr3d[3]</code> is equivalent to <code>*((arr3d)+(3))</code>. The lvalue <code>arr3d</code> undergoes array-to-pointer conversion to give a <code>int(*)[2][1]</code>. There is no requirement that the underlying array must be of the correct type to do this conversion. The pointers value is then accessed (which is fine by §3.10) and then the value 3 is added to it. This pointer arithmetic is also fine (§5.7/5):</p> <blockquote> <p>If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.</p> </blockquote> <p>This this pointer is dereferenced to give an <code>int[2][1]</code>. This undergoes the same process for the next two subscripts, resulting in the final <code>int</code> lvalue at the appropriate array index. It is an lvalue due to the result of <code>*</code> (§5.3.1/1):</p> <blockquote> <p>The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.</p> </blockquote> <p>It is then perfectly fine to access the actual <code>int</code> object through this lvalue because the lvalue is of type <code>int</code> too (§3.10/10):</p> <blockquote> <p>If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:</p> <ul> <li>the dynamic type of the object</li> <li>[...]</li> </ul> </blockquote> <p>So unless I've missed something. I'd say this program is well-defined.</p>
15,379,860
"Close Others" command shortcut in Sublime Text 2
<p>I am trying to add a shortcut for "Close Others" tabs, but can't seem to find the command, here is what I am trying:</p> <pre><code>{ "keys": ["super+alt+w"], "command": "close_others" } </code></pre> <p><kbd>Cmd</kbd>+<kbd>Option</kbd>+<kbd>W</kbd> - sort of like <kbd>Cmd</kbd>+<kbd>Option</kbd>+<kbd>H</kbd> in OS X, close all <em>except</em> the current tab, see?</p> <p>Anyway, <code>close_others</code> doesn't seem to do anything. I have tried <code>close_other_windows</code>, <code>close_other_tabs</code>, nothing works. What is the right command to do that? </p> <p>And while we're on it, how do you know what commands are available? My next one will be <kbd>Cmd</kbd>+<kbd>Option</kbd>+<kbd>Shift</kbd>+<kbd>W</kbd> - "Close Tabs to the Right".</p> <p>For some improvements in Sublime window management see "<a href="https://stackoverflow.com/questions/13561487/solved-sublime-text-2-close-all-tabs-but-not-the-window-how">Close all tabs, but not the window, in Sublime Text</a>"</p> <p>Thanks!</p>
15,380,759
2
0
null
2013-03-13 08:03:45.863 UTC
9
2015-01-30 13:07:32.84 UTC
2017-05-23 12:09:37.75 UTC
null
-1
null
166,484
null
1
21
command|keyboard-shortcuts|sublimetext2|sublimetext
5,373
<p>The command is <code>close_others_by_index</code>. Unfortunately, it takes arguments that cannot be passed via a simple key binding.</p> <p>To make it work, you have to create a plugin. <code>Tools/New Plugin...</code>:</p> <pre class="lang-py prettyprint-override"><code>import sublime_plugin class CloseOthersCommand(sublime_plugin.TextCommand): def run(self, edit): window = self.view.window() group_index, view_index = window.get_view_index(self.view) window.run_command("close_others_by_index", { "group": group_index, "index": view_index}) </code></pre> <p>Save it in <code>Packages/User</code> directory. Then you can add your key binding:</p> <pre><code>{ "keys": ["super+alt+w"], "command": "close_others" } </code></pre> <p>The same is true for "Close tabs to the right". The command is <code>close_to_right_by_index</code>.</p> <p>The plugin:</p> <pre class="lang-py prettyprint-override"><code>import sublime_plugin class CloseToRightCommand(sublime_plugin.TextCommand): def run(self, edit): window = self.view.window() group_index, view_index = window.get_view_index(self.view) window.run_command("close_to_right_by_index", { "group": group_index, "index": view_index}) </code></pre> <p>The key binding:</p> <pre><code>{ "keys": ["super+alt+shift+w"], "command": "close_to_right" } </code></pre>
15,200,362
When to use Single method Interfaces in Java
<p>I have seen in many libraries like <code>Spring</code> which use a lot of interfaces with <strong>single methods</strong> in them like <code>BeanNameAware</code>, etc. </p> <p>And the implementer class will implement many interfaces with single methods.</p> <p>In what scenarios does it make sense to keep single method interfaces? Is it done to avoid making one single interface bulky for example <code>ResultSet</code>? Or is there some design standard which advocates the use of these type of interfaces?</p>
15,200,760
5
0
null
2013-03-04 11:21:21.437 UTC
9
2017-12-21 06:50:21.953 UTC
null
null
null
null
1,719,067
null
1
24
java|oop|design-patterns|interface
15,999
<p>With Java 8, keeping the single method interface is quite useful, since single method interfaces will allow the usage of closures and "function pointers". So, whenever your code is written against a single method interface, the client code may hand in a closure or a method (which must have a compatible signature to the method declared in the single method interface) instead of having to create an anonymous class. In contrast, if you make one interface with more than one method, the client code will not have that possibility. It must always use a class that implements all methods of the interface.</p> <p>So as a common guideline, one can say: If a class that only exposes a single method to the client code might be useful to some client, then using a single method interface for that method is a good idea. A counter example to this is the <code>Iterator</code> interface: Here, it would not be useful having only a <code>next()</code> method without a <code>hasNext()</code> method. Since having a class that only implements one of these methods is no use, splitting this interface is not a good idea here.</p> <p>Example:</p> <pre><code>interface SingleMethod{ //The single method interface void foo(int i); } class X implements SingleMethod { //A class implementing it (and probably other ones) void foo(int i){...} } class Y { //An unrelated class that has methods with matching signature void bar(int i){...} static void bar2(int i){...} } class Framework{ // A framework that uses the interface //Takes a single method object and does something with it //(probably invoking the method) void consume(SingleMethod m){...} } class Client{ //Client code that uses the framework Framework f = ...; X x = new X(); Y y = new Y(); f.consume(x); //Fine, also in Java 7 //Java 8 //ALL these calls are only possible since SingleMethod has only ONE method! f.consume(y::bar); //Simply hand in a method. Object y is bound implicitly f.consume(Y::bar2); //Static methods are fine, too f.consume(i -&gt; { System.out.println(i); }) //lambda expression. Super concise. //This is the only way if the interface has MORE THAN ONE method: //Calling Y.bar2 Without that closure stuff (super verbose) f.consume(new SingleMethod(){ @Override void foo(int i){ Y.bar2(i); } }); } </code></pre>
15,109,958
Understanding convertPoint:toView:
<p>I do not quite understand the method <code>convertPoint:toView:</code>.</p> <p>In Apple's documentation it is written that</p> <blockquote> <p><code>convertPoint:toView:</code></p> <p>Converts a point from the receiver’s coordinate system to that of the specified view.</p> <pre><code>- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view </code></pre> </blockquote> <p>But what does converting a point from one to the other actually mean? </p> <p>Does it imply that the points in both bounds have <strong>different units</strong>? Or just different values? </p> <p>If it is the latter, why is there such a method when we can simply assign the value of a's <code>contentOffset</code> to b's ?</p> <pre><code>CGPoint a = [a contentOffset]; [b setContentOffset:a]; </code></pre> <p>How is <code>convertPoint:toView:</code> different from simply assigning <code>contentOffset</code>? Or did I misunderstand the entire concept? What does <strong>converting points</strong> actually do? When should this method be used?</p>
15,114,612
1
6
null
2013-02-27 10:39:45.57 UTC
14
2015-12-18 06:10:30.883 UTC
2015-12-18 06:10:30.883 UTC
null
603,977
null
2,024,727
null
1
46
ios|cocoa-touch|uiview|geometry
22,399
<p>Every UIView has its own coordinates system. So if you have a UIView_1 that contains another UIView_2, they both have a point (10,10) within them.</p> <p>convertPoint:toView: allows the developer to take a point in one view and convert the point to another view coordinate system.</p> <p>Example: view1 contains view2. The top left corner of view2 is located at view1 point (10,10), or better to say view2.frame.orgin = {10,10}. That {10,10} is based in the view1 coordinate system. So far so good.</p> <p>The user touches the view2 at point {20,20} inside the view2. Now those coordinates are in the view2 coordinate system. You can now use covertPoint:toView: to convert {20,20} into the coordinate system of view1. touchPoint = {20,20}</p> <pre><code>CGPoint pointInView1Coords = [view2 convertPoint:touchPoint toView:view1]; </code></pre> <p>So now pointInView1Coords should be {30,30} in the view1 coordinate systems. Now that was just simple math on this example, but there are all sorts of things that contribute to the conversion. Transforms and scaling come to mind.</p> <p>Read about UIView frame, bounds, and center. They are all related and they deal with coordinate systems for a view. Its confusing until you start doing stuff with them. Remember this frame and center are in the parent's coordinate system. Bounds is in the view's coordinate system.</p> <p>John</p>
15,300,572
Saving lists to txt file
<p>I'm trying to save a list to a text file.</p> <p>This is my code:</p> <pre><code>public void button13_Click(object sender, EventArgs e) { TextWriter tw = new StreamWriter("SavedLists.txt"); tw.WriteLine(Lists.verbList); tw.Close(); } </code></pre> <p>This is what I get in the text file:</p> <blockquote> <p>System.Collections.Generic.List`1[System.String]</p> </blockquote> <p>Do I have to use <code>ConvertAll&lt;&gt;</code>? If so, I'm not sure how to use that.</p>
15,300,618
3
3
null
2013-03-08 18:13:16.233 UTC
6
2016-05-13 13:29:04.853 UTC
2013-03-08 18:28:35.927 UTC
null
1,159,478
null
2,061,451
null
1
75
c#|list
166,326
<p>Assuming your Generic List is of type String:</p> <pre><code>TextWriter tw = new StreamWriter("SavedList.txt"); foreach (String s in Lists.verbList) tw.WriteLine(s); tw.Close(); </code></pre> <p>Alternatively, with the using keyword:</p> <pre><code>using(TextWriter tw = new StreamWriter("SavedList.txt")) { foreach (String s in Lists.verbList) tw.WriteLine(s); } </code></pre>
7,735,635
Real example of TryUpdateModel, ASP .NET MVC 3
<p>I can't understand, how to use TryUpdateModel and save the MVC architecture at the same time.</p> <p>If I am not mistaken, work with datacontexts must be in the Model. So, such code</p> <pre><code>var db=new TestEverybody();//it is class, which was generated by EntityFramework var currentTesting=db.Testing.(t =&gt; t.id == id).First(); </code></pre> <p>must be situated in the Model, not in the Controller, mustn't it?</p> <p>But the ussual examples of TryUpdateModel usage is following:</p> <pre><code> public ActionResult Edit(Testing obj)//Testing collection { var db = new TestEverybody(); var currentTesting=db.Testing.(t =&gt; t.id == obj.id).First(); TryUpdateModel(currentTesting); db.SaveChanges(); return RedirectToAction("Index"); } </code></pre> <p>Doesn't this way break the MVC architecture? We work with database in the controller, not in the special Model class.</p> <p>So, what is the best way to use TryUpdateModel in a real project?</p>
7,777,059
2
3
null
2011-10-12 05:26:27.037 UTC
37
2011-10-15 09:45:34.097 UTC
null
null
null
null
352,130
null
1
30
asp.net-mvc|model|controller
41,493
<p>Since the OP asked, here's an example of the ViewModel pattern, or as I like to call it - ASP.NET MVC done properly.</p> <p>So why use a view specific model</p> <ol> <li>You should only pass the information to your view that it needs.</li> <li>Often you'll need to add additional view-meta-data (such as title/description attributes). These do not belong on your entities.</li> <li>Using TryUpdateModel/UpdateModel is wrong. Don't use (I'll explain why).</li> <li>It's very rare that your view-models will exactly match your entities. People often end up adding additional cruft to their entities or (not much better) just using ViewBag rather than strongly typed view model properties.</li> <li>If you're using an ORM you can run into issues with Lazy loaded properties (N+1). Your views should not issue queries.</li> </ol> <p>We'll start with a simple entity:</p> <pre><code>public class Product { public int Id {get;set;} public string Name {get;set;} public string Description {get;set;} public decimal Price {get;set;} } </code></pre> <p>And let's say you have a simple form where the user can <strong>only</strong> update the <code>Name</code> and <code>Description</code> of the product. But you're using (the very greedy) TryUpdateModel.</p> <p>So I use any number of tools (like Fiddler) to construct a POST myself and send the following:</p> <blockquote> <p>Name=WhatverIWant&amp;Description=UnluckyFool&amp;Price=0</p> </blockquote> <p>Well the ASP.NET MVC model binder is going to inspect the input form collection, see that these properties exist on your entity and automatically bind them for you. So when you call "TryUpdateModel" on the entity you've just retrieved from your database, all of the matching properties will be updated (including the Price!). Time for a new option.</p> <h3>View Specific Model</h3> <pre><code>public class EditProductViewModel { [HiddenInput] public Guid Id {get;set;} [Required] [DisplayName("Product Name")] public string Name {get;set;} [AllowHtml] [DataType(DataType.MultilineText)] public string Description {get;set;} } </code></pre> <p>This contains just the properties we need in our view. Notice we've also added some validation attributes, display attributes and some mvc specific attributes.</p> <p>By not being restricted in what we have in our view model it can make your views much cleaner. For example, we could render out our entire edit form by having the following in our view:</p> <pre><code>@Html.EditorFor(model =&gt; model) </code></pre> <p>Mvc will inspect all of those attributes we've added to our view model and automatically wire up validation, labels and the correct input fields (i.e. a textarea for description).</p> <h3>POSTing the form</h3> <pre><code>[HttpPost] public ActionResult EditProduct(EditProductViewModel model) { var product = repository.GetById(model.Id); if (product == null) { return HttpNotFound(); } // input validation if (ModelState.IsValid) { // map the properties we **actually** want to update product.Name = model.Name; product.Description = model.Description; repository.Save(product); return RedirectToAction("index"); } return View(model) } </code></pre> <p>It's fairly obvious from this code what it does. We don't have any undesirable effects when we update our entity since we are explicitly setting properties on our entity.</p> <p>I hope this explains the View-Model pattern enough for you to want to use it.</p>
65,134,181
Why does a Java string comparison behave different in Java 15 and Java 11?
<p>Please consider the following class:</p> <pre><code>class Eq { public static void main(String[] args) { System.out.println(&quot;&quot; == &quot;.&quot;.substring(1)); } } </code></pre> <p>The example is supposed to show that multiple copies of the empty string may exist in memory. I still have an old OpenJDK 11 where the program outputs <code>false</code> as expected. Under OpenJDK 15, the program outputs <code>true</code>. The generated bytecode for the class files looks similar (even though they differ in register values):</p> <p>Java 11:</p> <pre><code>public static void main(java.lang.String[]); Code: 0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #13 // String 5: ldc #15 // String . 7: iconst_1 8: invokevirtual #17 // Method java/lang/String.substring:(I)Ljava/lang/String; 11: if_acmpne 18 14: iconst_1 15: goto 19 18: iconst_0 19: invokevirtual #23 // Method java/io/PrintStream.println:(Z)V 22: return </code></pre> <p>Java 15:</p> <pre><code>public static void main(java.lang.String[]); Code: 0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3 // String 5: ldc #4 // String . 7: iconst_1 8: invokevirtual #5 // Method java/lang/String.substring:(I)Ljava/lang/String; 11: if_acmpne 18 14: iconst_1 15: goto 19 18: iconst_0 19: invokevirtual #6 // Method java/io/PrintStream.println:(Z)V 22: return </code></pre> <p>I tried to exclude static compiler optimizations by reading &quot;.&quot; from stdin but this does not change the outcome. I have tried to disable the JIT via <code>-Djava.compiler=NONE</code> and played around with adjusting the string table size via <code>-XX:StringTableSize=100000</code>. I now have the following questions:</p> <ul> <li>Can someone reproduce the issue (i.e. did I do it correctly? I can provide the class files if that helps)</li> <li>How do I find out the exact reason for the different behaviour?</li> <li>What (in your opinion) is the source for the different behaviour?</li> </ul> <p>I think just strategies to approach how to find the reason for the behaviour that don't answer the question might also be interesting.</p>
65,134,318
1
4
null
2020-12-03 21:08:52.89 UTC
4
2021-01-04 11:25:37.857 UTC
2021-01-04 11:25:37.857 UTC
null
1,109,583
null
1,109,583
null
1
28
java|string|memory|equality
1,825
<p>This is mentioned in the <a href="https://www.oracle.com/java/technologies/javase/15-relnote-issues.html#JDK-8240094" rel="noreferrer">JDK 15 Release Notes</a>.</p> <p>It was changed as requested by JDK-8240094:</p> <blockquote> <p><strong><a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8240094" rel="noreferrer">JDK-8240094</a> : Optimize empty substring handling</strong></p> <p><code>String.substring</code> return <code>&quot;&quot;</code> in some cases, but could be improved to do so in all cases when the substring length is zero.</p> </blockquote> <p>Related:</p> <blockquote> <p><strong><a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8240225" rel="noreferrer">JDK-8240225</a> : Optimize empty substring handling</strong></p> <p>Optimize <code>String.substring</code> and related operations like <code>stripLeading</code>, <code>stripTrailing</code> to avoid redundantly creating a new empty String.</p> </blockquote> <p>Sub Task:</p> <blockquote> <p><strong><a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8251556" rel="noreferrer">JDK-8251556</a> : Release Note: Optimized Empty Substring Handling</strong></p> <p>The implementation of <code>String.substring</code> and related methods <code>stripLeading</code> and <code>stripTrailing</code> have changed in this release to avoid redundantly creating a new empty String. This may impact code that depends on unspecified behaviour and the identity of empty sub-strings.</p> </blockquote>
5,445,847
List available COM ports
<p>I have a very small code that shows available COM ports.</p> <p>My question is:</p> <p>Is there an easy way to have the program to run in the tray and only popup when a new COM port is available and is it possible to add the name for the COM port that you can see in device manager ec "USB serial port"?</p> <p>I often add/remove a USB->RS232 comverter and find it a pain in the ass because I must go into the device manger to see what COM port it is assigned to. It's not the same each time</p> <p>Maybe there already is a small app that can do this but I havent found it on Google yet</p> <pre><code>using System; using System.Windows.Forms; using System.IO.Ports; namespace Available_COMports { public partial class Form1 : Form { public Form1() { InitializeComponent(); //show list of valid com ports foreach (string s in SerialPort.GetPortNames()) { listBox1.Items.Add(s); } } private void Form1_Load(object sender, EventArgs e) { } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { } } </code></pre> <p>}</p>
5,446,366
4
0
null
2011-03-26 22:42:56.233 UTC
5
2018-04-17 16:44:49.737 UTC
null
null
null
null
302,935
null
1
20
c#|windows|forms
77,317
<p>Take a look at <a href="https://stackoverflow.com/questions/1081871/how-to-find-available-com-ports">this question</a>. It uses WMI to find available COM ports. You could keep track of what COM ports exist, and only notify about new ones.</p>
5,010,191
Using DataContractSerializer to serialize, but can't deserialize back
<p>I have the following 2 functions:</p> <pre><code>public static string Serialize(object obj) { DataContractSerializer serializer = new DataContractSerializer(obj.GetType()); MemoryStream memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, obj); return Encoding.UTF8.GetString(memoryStream.GetBuffer()); } public static object Deserialize(string xml, Type toType) { MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); // memoryStream.Position = 0L; XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null); DataContractSerializer dataContractSerializer = new DataContractSerializer(toType); return dataContractSerializer.ReadObject(reader); } </code></pre> <p>The first one seems to serialize an object to an xml string just fine. The XML appears valid, no broken tags, no white spaces at the beginning or at the end, etc. Now the second function doesn't want to deserialize my xml string back to the object. On the last line I get:</p> <blockquote> <p>There was an error deserializing the object of type [MY OBJECT TYPE HERE]. The data at the root level is invalid. Line 1, position 1.</p> </blockquote> <p>What am I doing wrong? I tried rewriting the Deserialize function a few times, and it always seems to be the same kind of error. Thank you!</p> <p>Oh, and this is how I'm calling the 2 functions:</p> <pre><code>SomeObject so = new SomeObject(); string temp = SerializationManager.Serialize(so); so = (SomeObject)SerializationManager.Deserialize(temp, typeof(SomeObject)); </code></pre>
5,010,376
4
0
null
2011-02-15 22:20:22.573 UTC
29
2012-01-02 08:30:55.23 UTC
null
null
null
null
431,937
null
1
66
c#|c#-4.0|xml-serialization|datacontractserializer
109,231
<p>Here is how I've always done it:</p> <pre><code> public static string Serialize(object obj) { using(MemoryStream memoryStream = new MemoryStream()) using(StreamReader reader = new StreamReader(memoryStream)) { DataContractSerializer serializer = new DataContractSerializer(obj.GetType()); serializer.WriteObject(memoryStream, obj); memoryStream.Position = 0; return reader.ReadToEnd(); } } public static object Deserialize(string xml, Type toType) { using(Stream stream = new MemoryStream()) { byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); stream.Write(data, 0, data.Length); stream.Position = 0; DataContractSerializer deserializer = new DataContractSerializer(toType); return deserializer.ReadObject(stream); } } </code></pre>
4,953,272
How to match exact "multiple" strings in Python
<p>I've got a list of exact patterns that I want to search in a given string. Currently I've got a real bad solution for such a problem.</p> <pre><code>pat1 = re.compile('foo.tralingString') mat1 = pat1.match(mystring) pat2 = re.compile('bar.trailingString') mat2 = pat2.match(mystring) if mat1 or mat2: # Do whatever pat = re.compile('[foo|bar].tralingString') match = pat.match(mystring) # Doesn't work </code></pre> <p>The only condition is that I've got a list of strings which are to be matched exactly. Whats the best possible solution in Python.</p> <p>EDIT: The search patterns have some trailing patterns common.</p>
4,953,289
5
0
null
2011-02-10 04:09:48.693 UTC
7
2011-02-10 04:28:51.423 UTC
2011-02-10 04:17:11.267 UTC
null
1,678,010
null
1,678,010
null
1
19
python|regex
61,476
<p>You could do a trivial regex that combines those two:</p> <pre><code>pat = re.compile('foo|bar') if pat.match(mystring): # Do whatever </code></pre> <p>You could then expand the regex to do whatever you need to, using the <code>|</code> separator (which means <em>or</em> in regex syntax)</p> <p><strong>Edit:</strong> Based upon your recent edit, this should do it for you:</p> <pre><code>pat = re.compile('(foo|bar)\\.trailingString'); if pat.match(mystring): # Do Whatever </code></pre> <p>The <code>[]</code> is a character class. So your <code>[foo|bar]</code> would match a string with <strong>one</strong> of the included characters (since there's no * or + or ? after the class). <code>()</code> is the enclosure for a sub-pattern.</p>
5,144,110
Concatenating a variable and a string literal without a space in PowerShell
<p>How can I write a variable to the console without a space after it? There are problems when I try:</p> <pre><code>$MyVariable = "Some text" Write-Host "$MyVariableNOSPACES" </code></pre> <p>I'd like the following output:</p> <pre><code>Some textNOSPACES </code></pre>
5,149,170
7
1
null
2011-02-28 15:43:37.053 UTC
9
2020-01-14 13:59:16.147 UTC
2017-06-05 21:58:48.4 UTC
null
63,550
null
111,327
null
1
56
string|powershell
87,813
<p>Another option and possibly the more canonical way is to use curly braces to delineate the name:</p> <pre><code>$MyVariable = "Some text" Write-Host "${MyVariable}NOSPACES" </code></pre> <p>This is particular handy for paths e.g. <code>${ProjectDir}Bin\$Config\Images</code>. However, if there is a <code>\</code> after the variable name, that is enough for PowerShell to consider that <em>not</em> part of the variable name.</p>
5,431,413
Difference between protocol and delegates?
<p>What is the difference between a <code>protocol</code> and a <code>delegate</code>?</p> <p>and,</p> <p>How can we declare <code>variables</code> in a <code>protocol class</code>?</p>
5,431,545
7
0
null
2011-03-25 10:48:41.647 UTC
38
2020-06-10 21:17:13.7 UTC
2019-08-19 12:15:59.453 UTC
null
5,175,709
null
649,317
null
1
58
ios|objective-c|delegates|protocols
59,965
<p>A protocol, declared with the (<code>@protocol</code> syntax in Objective-C) is used to declare a set of methods that a class "adopts" (declares that it will use this protocol) will implement. This means that you can specify in your code that, "you don't care which class is used as long as it implements a particular protocol". This can be done in Objective-C as follows:</p> <p><code>id&lt;MyProtocol&gt; instanceOfClassThatImplementsMyProtocol;</code></p> <p>If you state this in your code, then any class that "conforms" to the protocol <em>MyProtocol</em> can be used in the variable <em>instanceOfClassThatImplementsMyProtocol</em>. This means that the code that uses this variable knows that it can use whichever methods are defined in <em>MyProtocol</em> with this particular variable, regardless of what class it is. This is a great way of avoiding the inheritance design pattern, and avoids tight coupling.</p> <p>Delegates are a use of the language feature of protocols. The <a href="http://en.wikipedia.org/wiki/Delegation_pattern" rel="noreferrer">delegation design pattern</a> is a way of designing your code to use protocols where necessary. In the Cocoa frameworks, the delegate design pattern is used to specify an instance of a class which conforms to a particular protocol. This particular protocol specifies methods that the delegate class should implement to perform specific actions at given events. The class that uses the delegate knows that its delegate coforms to the protocol, so it knows that it can call the implemented methods at given times. This design pattern is a great way of decoupling the classes, because it makes it really easy to exchange one delegate instance for another - all the programmer has to do is ensure that the replacement instance or class conforms to the necessary protocol (i.e. it implements the methods specified in the protocol)!</p> <p>Protocols and delegates are not restricted only to Objective-C and Mac/iOS development, but the Objective-C language and the Apple frameworks make heavy use of this awesome language feature and design pattern.</p> <p><strong>Edit:</strong></p> <p>Here's an example. In the UIKit framework of Cocoa Touch, there is a <em>UITextFieldDelegate</em> protocol. This protocol defines a series of methods that classes which are delegates of a <em>UITextField</em> instance should implement. In other words, if you want to assign a delegate to a <em>UITextField</em> (using the <code>delegate</code> property), you'd better make sure that this class conforms to <em>UITextFieldDelegate</em>. In fact, because the delegate property of <em>UITextField</em> is defined as:</p> <p><code>@property(nonatomic, weak) id&lt;UITextFieldDelegate&gt; delegate</code></p> <p>Then the compiler will give warnings if you assign a class to it that doesn't implement the protocol. This is really useful. You have to state that a class implements a protocol, and in saying that it does, you're letting other classes know that they can interact in a particular way with your class. So, if you assign an instance of <em>MyTextFieldDelegateClass</em> to the <code>delegate</code> property of <em>UITextField</em>, the <em>UITextField</em> <strong>knows</strong> that it can call some particular methods (related to text entry, selection etc.) of your <em>MyTextFieldDelegateClass</em>. It knows this because <em>MyTextFieldDelegateClass</em> has said that it will implement the <em>UITextFieldDelegate</em> protocol.</p> <p>Ultimately, this all leads to much greater flexibility and adaptability in your project's code, which I'm sure you'll soon realise after using this technology! :)</p>