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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,950,128 | How to implement INotifyDataErrorInfo in WPF 4.5? | <p>I realized that appears this interface in .NET Framework 4.5</p>
<p>I was looking first for about how to implemented in Silverlight (I can imagine that it's implemented in the same way), but I can't find a compact demo of this new interface. Is it possible to show how can I use it?</p>
<p>I really want to find a small demo to understand it</p> | 9,950,236 | 2 | 1 | null | 2012-03-30 20:38:31.847 UTC | 12 | 2019-05-10 15:10:04.94 UTC | null | null | null | null | 1,118,485 | null | 1 | 31 | c#|wpf|silverlight|inotifydataerrorinfo | 42,595 | <p>Beside the very detailed description on MSDN about the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo%28v=vs.95%29.aspx" rel="nofollow noreferrer">Silverlight version of INotifyDataErrorInfo</a> </p>
<p>There are already some blog posts with samples how to use/implement it in WPF 4.5:</p>
<ul>
<li>WPF 4.5 – Asynchronous validation <a href="http://burnaftercoding.com/post/asynchronous-validation-with-wpf-4-5/" rel="nofollow noreferrer">(original link no longer working)</a> <a href="https://web.archive.org/web/20190209072409/http://burnaftercoding.com/post/asynchronous-validation-with-wpf-4-5/" rel="nofollow noreferrer">Wayback Link</a></li>
<li><a href="http://www.jonathanantoine.com/2011/09/18/wpf-4-5-asynchronous-data-validation/" rel="nofollow noreferrer">WPF 4.5 – Part 1 : Asynchronous data validation</a> (the author has a <a href="http://www.jonathanantoine.com/2011/09/20/wpf-4-5-is-here-check-out-the-new-features/" rel="nofollow noreferrer">nice series</a> about the new fetaures in WPF 4.5)</li>
</ul> |
7,747,934 | Can someone explain Polymorphism to me? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/210460/try-to-describe-polymorphism-as-easy-as-you-can">Try to describe polymorphism as easy as you can</a> </p>
</blockquote>
<p>I've never been able to fully comprehend what polymorphism is. Can someone explain, perhaps with use of an example, what it is and how it works? Just the basics.</p> | 7,748,957 | 3 | 0 | null | 2011-10-12 23:55:17.363 UTC | 8 | 2011-10-13 02:52:15.117 UTC | 2017-05-23 12:26:07.92 UTC | null | -1 | null | 386,869 | null | 1 | 14 | oop|polymorphism | 20,315 | <p>Perhaps it's easiest to start with a non-computer analogy.</p>
<p>Consider if you told somebody to "Go to the store and buy some of your favorite food for supper."</p>
<p>If you said this to a 14 year-old son, he'd probably ride his bike to the store, have to pay cash for the food, and you'd be having pizza for supper.</p>
<p>If you said it to your wife, she'd probably drive to the store, use a card to pay for the food, and you might be eating chicken Cordon Bleu with Chardonnay instead.</p>
<p>In a program, things work out a bit the same way: you specify something at a relatively abstract level (go to the store and get supper). Each object provides its own concrete implementation of how to implement that, and in many cases provides for some variation in exactly what it's going to do (e.g., like the differences in favorite foods above).</p>
<p>Of course, when you're programming, most of that requires a specification that's a lot more detailed and unambiguous. The general idea remains the same though. For the scenario above, you might have a <code>person</code> base class (or interface) that defined methods like <code>go to store</code> and <code>select favorite food</code> and <code>pay for purchase</code>. You'd then have implementations of that like <code>adult</code> and <code>teenager</code>, each of which defined its own method of going to the store, selecting favorite food, and paying for a purchase. Those methods would be polymorphic, because each implementation would have its own way of carrying out the higher-level command you gave.</p> |
11,893,826 | How to refresh image view immediately | <p>In my android app, I download an image from the cloud. The download is performed in a thread and in that same thread I also set an image view with the newly downloaded image. After setting the image, I then call <code>postinvalidate()</code>.</p>
<p>However the image does not immediately show up. Is there a way to make the redraw happen immediately? I need a way to trigger a drawing cycle.</p> | 11,894,378 | 4 | 0 | null | 2012-08-10 00:20:00.747 UTC | 3 | 2018-12-23 16:57:53.34 UTC | 2012-08-10 21:38:09.57 UTC | null | 366,313 | null | 1,583,075 | null | 1 | 14 | android|multithreading|image | 48,807 | <p>Each class which is derived from the View class has the <code>invalidate()</code> and the <code>postInvalidate()</code> method. If <code>invalidate()</code> gets called it tells the system that the current view has changed and it should be redrawn <strong>as soon as possible</strong>. As this method can only be called from your <strong>UIThread</strong> another method is needed for when you are <strong>not</strong> in the <strong>UIThread</strong> and still want to notify the system that your View has been changed. The <code>postInvalidate()</code> method notifies the system from a <strong>non-UIThread</strong> and the View gets redrawn in the <strong>next eventloop</strong> on the UIThread as soon as possible. </p>
<p>In your case you can achieve what you want with the help of <code>AsyncTask</code> (an intelligent backround thread).AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations (download image in background in your case) and publish results (set your bitmap to your ImageView) on the UI thread without having to manipulate threads and/or handlers.</p>
<p>An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by <strong>3 generic types</strong>, called Params, Progress and Result, and <strong>4 steps</strong>, called begin, doInBackground, processProgress and end.</p>
<p>The 4 steps</p>
<p>When an asynchronous task is executed, the task goes through 4 steps:</p>
<p><code>onPreExecute()</code>, invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface before downloading the image from cloud and that's used to provide a good user experience .</p>
<p><code>doInBackground(Params...)</code>, invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.</p>
<p><code>onProgressUpdate(Progress...)</code>, invoked on the UI thread after a call to <code>publishProgress(Progress...)</code>. The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing.</p>
<p><code>onPostExecute(Result)</code>, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter in that method you can set the bitmap to your imageView and invalidate your views</p> |
11,600,006 | How to Create a configuration File For MongoDB | <p>I have installed mongodb for mac os through 10gen and I have gone through the documentation to do so. Everything seems fine apart from the configuration file. I can not see it in /etc/mongod.config. Do I have to manually create this config file? And if so how can I go about it? </p>
<p>cheers</p> | 11,600,283 | 4 | 0 | null | 2012-07-22 11:45:34.177 UTC | 13 | 2020-05-04 20:29:07.87 UTC | null | null | null | null | 1,460,625 | null | 1 | 34 | macos|mongodb|configuration-files | 64,437 | <p>Unless you have installed a packaged version of MongoDB (for example, using <a href="http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/#id1" rel="noreferrer">Homebrew or Mac Ports</a>) you will have to create a config file manually, or just pass the appropriate <a href="http://www.mongodb.org/display/DOCS/Command+Line+Parameters" rel="noreferrer">command line parameters</a> when starting up MongoDB.</p>
<p>If you want a commented example of a config file to start with, the <a href="https://github.com/mongodb/mongo/blob/v2.4/debian/mongodb.conf" rel="noreferrer">mongodb.conf</a> in the Debian/Ubuntu package should be a good starting point. Important options to check are the <code>dbpath</code> and <code>logpath</code> which will likely be different for you.</p>
<p>It would also be worth looking at the <a href="https://github.com/mxcl/homebrew/blob/master/Library/Formula/mongodb.rb" rel="noreferrer">Homebrew mongodb formula</a> which includes setting up a LaunchAgent script to manage the mongod service.</p> |
20,165,954 | Read into std::string using scanf | <p>As the title said, I'm curious if there is a way to read a C++ string with scanf.</p>
<p>I know that I can read each char and insert it in the deserved string, but I'd want something like:</p>
<pre><code>string a;
scanf("%SOMETHING", &a);
</code></pre>
<p><code>gets()</code> also doesn't work.</p>
<p>Thanks in advance!</p> | 20,166,048 | 7 | 5 | null | 2013-11-23 18:06:42.107 UTC | 5 | 2021-02-03 07:52:38.78 UTC | 2021-02-03 07:52:38.78 UTC | null | 1,030,410 | null | 1,977,897 | null | 1 | 35 | c++|c|string | 106,365 | <p>There is no situation under which <code>gets()</code> is to be used! It is <strong>always</strong> wrong to use <code>gets()</code> and it is removed from C11 and being removed from C++14.</p>
<p><code>scanf()</code> doens't support any C++ classes. However, you can store the result from <code>scanf()</code> into a <code>std::string</code>:</p>
<blockquote>
<p><em>Editor's note: The following code is wrong, as explained in the <a href="https://stackoverflow.com/questions/20165954/read-c-string-with-scanf#comment61590562_20166048">comments</a>. See the answers by <a href="https://stackoverflow.com/questions/20165954/read-c-string-with-scanf#20166003">Patato</a>, <a href="https://stackoverflow.com/questions/20165954/read-c-string-with-scanf#60437601">tom</a>, and <a href="https://stackoverflow.com/questions/20165954/read-c-string-with-scanf#62504517">Daniel Trugman</a> for correct approaches.</em></p>
</blockquote>
<pre><code>std::string str(100, ' ');
if (1 == scanf("%*s", &str[0], str.size())) {
// ...
}
</code></pre>
<p>I'm not entirely sure about the way to specify that buffer length in <code>scanf()</code> and in which order the parameters go (there is a chance that the parameters <code>&str[0]</code> and <code>str.size()</code> need to be reversed and I may be missing a <code>.</code> in the format string). Note that the resulting <code>std::string</code> will contain a terminating null character and it won't have changed its size.</p>
<p>Of course, I would just use <code>if (std::cin >> str) { ... }</code> but that's a different question.</p> |
3,294,475 | Is there a way to shift highlighted lines left or right in Notepad++ | <p>In the Eclipse IDE (and many others I would imagine) there is a simple shortcut to shift highlighted lines either right or left by one tab length.</p>
<p>I have looked through all of the TextFX in Notepad++ and only found the ability to shift highlighted lines up or down. Is there a built in way to shift highlighted lines left or right? </p>
<p>Thanks for reading</p> | 3,294,513 | 4 | 0 | null | 2010-07-20 21:24:12.83 UTC | 9 | 2022-07-13 04:09:15.62 UTC | null | null | null | null | 352,374 | null | 1 | 32 | notepad++ | 51,087 | <p>Shift highlighted lines to the right one tab length by pressing the tab key. Shift them to the left by pressing shift-tab.</p>
<p>When lines are highlighted, the tab key doesn't replace them with a tab. It shifts them left/right instead.</p> |
4,003,604 | How to set class on div that is inside of repeater in code behind? | <p><a href="http://paste.org/pastebin/view/24218" rel="nofollow">CSS & html</a></p>
<p>id0 is the class for the div that's got background as a sprite image and inside of this div..there's a list of links (in repeater)..when the user hovers over links..the background image of div displays diff parts of sprite image accordingly</p>
<p>Now I want that the classes id1 to id5 be set as the classes of the repeater's list...now how do I go abut it?</p>
<p>like the list of links inside of repeater is coming from the DB..how do I create div tags inside of this repeater</p>
<p>and how do I set the class for each of the 5 divs that will be created and set these classes on them ?</p>
<p>like earlier I had simple markup but now I have to generate that list of links using a repeater..so how do I apply the CSS now ??</p>
<p>Please give some ideas..thnx</p>
<p><strong>[EDIT]
ok tried this..
added div tag in repeater after label and in code behind :-
rpt1.FindControl("myDiv").Controls.Add(class= ??) //what to type here
use for loop or what ?</strong>
[edit] this doesnt work..whats wrong ?**</p>
<pre><code>for(int i=1;i<6;i++)
{
rpt1.FindControl("myDiv").Controls.Add("class=id[i]");
}
</code></pre>
<p>The above's giving the following error:-</p>
<p>The best overloaded method match for 'System.Web.UI.ControlCollection.Add(System.Web.UI.Control)' has some invalid arguments</p>
<p>Now how do I set classes for the divs?</p>
<p>pch..made dilly mistake..made changes ..</p>
<pre><code> for (int i = 1; i < 6; i++)
{
string divClass = "id";
rpt1.FindControl("myDiv").Controls.Add("class=id" + i);
}
</code></pre>
<p>still the same error..</p>
<p>[edit]</p>
<p>tried the following..doesnt work</p>
<pre><code>rpt1.FindControl("myDiv").Attributes.Add("class","id" +i);
</code></pre>
<p>[edit]</p>
<p>I tried the following now..</p>
<pre><code>rpt1.FindControl("myDiv").Attributes["class"] = "id" + i;
</code></pre>
<p>it says "Cannot apply indexing with [] to an expression of type 'method group'" ???</p> | 4,003,779 | 5 | 1 | null | 2010-10-23 10:53:33.603 UTC | 5 | 2015-11-17 17:11:25.093 UTC | 2010-10-30 12:06:39.047 UTC | null | 1,427,536 | null | 1,427,536 | null | 1 | 4 | c#|asp.net|html|css | 41,243 | <p><strong>The ItemDataBinding way</strong></p>
<p>In order to get hold of an element inside the repeater's ItemTemplate you have to declare it runat="Server" and set an id for it (id isn't really neccessary, but simplifies things). If you do that with your div you can get it inside your <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx">ItemDataBound event</a> and set the class.</p>
<pre><code>void Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item
|| e.Item.ItemType == ListItemType.AlternatingItem)
{
((HtmlGenericControl)(e.Item.FindControl("myDiv"))).
Attributes["class"] = "id" + index++;
}
}
</code></pre>
<p>You need to declare the index variable and increment it as you set each class. </p>
<hr>
<p><strong>Alternative way</strong></p>
<p>An even simpler and cleaner way IMHO is to set the class directly in the View using data binding</p>
<pre><code><asp:Repeater ID="rpt" runat="server">
<ItemTemplate><div class="<%# GetDivClass() %>">a div</div></ItemTemplate>
</asp:Repeater>
</code></pre>
<p>and in the code behind declare the method for getting the data</p>
<pre><code>private int index = 1;
protected string GetDivClass()
{
return "div" + index++;
}
</code></pre> |
3,566,176 | Salting passwords 101 | <p>Could someone please help me understand how salting works?</p>
<p>So far I understand the following:</p>
<ol>
<li>Validate password</li>
<li>Generate a random string</li>
<li>Hash the password and the random string and concat them, then store them in the password field...</li>
</ol>
<p>How do we store the salt, or know what it is when a user logs in? Do we store it in its own field? If we don't, how does the application figure out what the salt is? And if we do store it, doesn't it defeat the whole purpose?</p> | 3,566,375 | 5 | 1 | null | 2010-08-25 13:15:20.83 UTC | 9 | 2020-02-26 14:28:03.253 UTC | 2014-01-30 09:44:22.393 UTC | null | 445,517 | null | 276,959 | null | 1 | 24 | salt|password-hash | 9,992 | <p>Salt is combined with the password before hashing. the password and salt clear values are concatenated and the resulting string is hashed. this guarantees that even if two people were to have the same password you would have different resulting hashes. (also makes attacks known as dictionary attacks using rainbow tables much more difficult).</p>
<p>The salt is then stored in original/clear format along with the hash result. Then later, when you want to verify the password you would do the original process again. Combine the salt from the record with the password the user provided, hash the result, compare the hash.</p>
<p>You probably already know this. but it's important to remember. the salt must be generated randomly each time. It must be different for each protected hash. Often times the RNG is used to generate the salt.</p>
<p>So..for example:<br>
user-password: "mypassword"<br>
random salt: "abcdefg12345"<br>
resulting-cleartext: "mypassword:abcdefg12345" (how you combine them is up to you. as long as you use the same combination format every time).<br>
hash the resulting cleartext: "somestandardlengthhashbasedonalgorithm" </p>
<p>In your database now you would store the hash and salt used. I've seen it two ways:</p>
<p>method 1:<br>
field1 - salt = "abcdefg12345"<br>
field2 - password_hash = "somestandardlengthhashbasedonalgorithm" </p>
<p>method 2:<br>
field1 - password_hash = "abcdefg12345:somestandardlengthhashbasedonalgorithm" </p>
<p>In either case you have to load the salt and password hash out of your database and redo the hash for comparison</p> |
3,805,474 | What is a closure? Does java have closures? | <p>I was reading Object Oriented Javascript and found the concept of closures. I didn't quite understand why and when it is used. Do other languages like Java also have closures? I basically want to understand how knowing the concept of closures can help me improve my coding.</p> | 3,805,576 | 5 | 2 | null | 2010-09-27 15:48:36.163 UTC | 18 | 2016-03-18 10:56:09.003 UTC | 2010-09-27 16:11:49.62 UTC | null | 140,185 | null | 337,522 | null | 1 | 36 | java|javascript|closures | 26,194 | <p>A closure is a first class function with bound variables.</p>
<p>Roughly that means that:</p>
<ul>
<li>You can pass the closure as a parameter to other functions</li>
<li>The closure stores the value of some variables from the lexical scope that existed at the time that is was created</li>
</ul>
<p>Java initially didn't have syntactic support for closures (these were introduced in Java 8), although it was fairly common practice to simulate them using anonymous inner classes. Here's an example:</p>
<pre><code>import java.util.Arrays;
import java.util.Comparator;
public class StupidComparator {
public static void main(String[] args) {
// this is a value used (bound) by the inner class
// note that it needs to be "final"
final int numberToCompareTo=10;
// this is an inner class that acts like a closure and uses one bound value
Comparator<Integer> comp=new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
int result=0;
if (a<numberToCompareTo) result=result-1;
if (b<numberToCompareTo) result=result+1;
return result;
}
};
Integer[] array=new Integer[] {1,10, 5 , 15, 6 , 20, 21, 3, 7};
// this is a function call that takes the inner class "closure" as a parameter
Arrays.sort(array,comp);
for (int i:array) System.out.println(i);
}
}
</code></pre> |
3,447,536 | How to determine the OS | <p>how to implement a function that will return the OS name? detect the environment where the program running on?</p>
<p>win2000/xp/vista/win7 etc...?</p> | 3,447,622 | 7 | 1 | null | 2010-08-10 09:22:30.007 UTC | 9 | 2022-07-05 09:18:00.803 UTC | null | null | null | null | 318,249 | null | 1 | 12 | delphi|operating-system | 9,412 | <p>Something like this:</p>
<pre><code>function osver: string;
begin
result := 'Unknown (Windows ' + IntToStr(Win32MajorVersion) + '.' + IntToStr(Win32MinorVersion) + ')';
case Win32MajorVersion of
4:
case Win32MinorVersion of
0: result := 'Windows 95';
10: result := 'Windows 98';
90: result := 'Windows ME';
end;
5:
case Win32MinorVersion of
0: result := 'Windows 2000';
1: result := 'Windows XP';
end;
6:
case Win32MinorVersion of
0: result := 'Windows Vista';
1: result := 'Windows 7';
2: result := 'Windows 8';
3: result := 'Windows 8.1';
end;
10:
case Win32MinorVersion of
0: result := 'Windows 10';
end;
end;
end;
</code></pre>
<p>There is really no need to call <code>GetVersionEx</code> because <code>SysUtils.pas</code> has <code>InitPlatformID</code> in its <code>initialization</code> clause. Hence the global constants <code>Win32MajorVersion</code> and <code>Win32MinorVersion</code> (and friends) will be populated already.</p> |
3,727,420 | Significance of Sleep(0) | <p>I used to see <code>Sleep(0)</code> in some part of my code where some infinite/long <code>while</code> loops are available. I was informed that it would make the time-slice available for other waiting processes. Is this true? Is there any significance for <code>Sleep(0)</code>?</p> | 3,727,460 | 8 | 1 | null | 2010-09-16 14:00:36.077 UTC | 9 | 2016-11-09 04:59:25.837 UTC | 2014-02-25 15:34:22.8 UTC | null | 321,731 | null | 139,909 | null | 1 | 54 | c++|visual-c++|process|sleep | 36,799 | <p>According to MSDN's documentation for <a href="http://msdn.microsoft.com/en-us/library/ms686298(VS.85).aspx" rel="noreferrer">Sleep</a>:</p>
<blockquote>
<p>A value of zero causes the thread to
relinquish the remainder of its time
slice to any other thread that is
ready to run. If there are no other
threads ready to run, the function
returns immediately, and the thread
continues execution.</p>
</blockquote>
<p>The important thing to realize is that yes, this gives other threads a chance to run, but if there are none ready to run, then your thread continues -- leaving the CPU usage at 100% since <em>something</em> will always be running. If your while loop is just spinning while waiting for some condition, you might want to consider using a synchronization primitive like an event to sleep until the condition is satisfied or sleep for a small amount of time to prevent maxing out the CPU.</p> |
3,944,505 | Detecting signed overflow in C/C++ | <p>At first glance, this question may seem like a duplicate of <a href="https://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-c-c">How to detect integer overflow?</a>, however it is actually significantly different.</p>
<p>I've found that while detecting an unsigned integer overflow is pretty trivial, detecting a <em>signed</em> overflow in C/C++ is actually more difficult than most people think.</p>
<p>The most obvious, yet naive, way to do it would be something like:</p>
<pre><code>int add(int lhs, int rhs)
{
int sum = lhs + rhs;
if ((lhs >= 0 && sum < rhs) || (lhs < 0 && sum > rhs)) {
/* an overflow has occurred */
abort();
}
return sum;
}
</code></pre>
<p>The problem with this is that according to the C standard, signed integer overflow is <em>undefined behavior.</em> In other words, according to the standard, as soon as you even cause a signed overflow, your program is just as invalid as if you dereferenced a null pointer. So you can't cause undefined behavior, and then try to detect the overflow after the fact, as in the above post-condition check example.</p>
<p>Even though the above check is likely to work on many compilers, you can't count on it. In fact, because the C standard says signed integer overflow is undefined, some compilers (like GCC) will <a href="http://patrakov.blogspot.com/2008_10_01_archive.html" rel="noreferrer">optimize away the above check</a> when optimization flags are set, because the compiler assumes a signed overflow is impossible. This totally breaks the attempt to check for overflow.</p>
<p>So, another possible way to check for overflow would be:</p>
<pre><code>int add(int lhs, int rhs)
{
if (lhs >= 0 && rhs >= 0) {
if (INT_MAX - lhs <= rhs) {
/* overflow has occurred */
abort();
}
}
else if (lhs < 0 && rhs < 0) {
if (lhs <= INT_MIN - rhs) {
/* overflow has occurred */
abort();
}
}
return lhs + rhs;
}
</code></pre>
<p>This seems more promising, since we don't actually add the two integers together until we make sure in advance that performing such an add will not result in overflow. Thus, we don't cause any undefined behavior. </p>
<p>However, this solution is unfortunately a lot less efficient than the initial solution, since you have to perform a subtract operation just to test if your addition operation will work. And even if you don't care about this (small) performance hit, I'm still not entirely convinced this solution is adequate. The expression <code>lhs <= INT_MIN - rhs</code> seems exactly like the sort of expression the compiler might optimize away, thinking that signed overflow is impossible. </p>
<p>So is there a better solution here? Something that is guaranteed to 1) not cause undefined behavior, and 2) not provide the compiler with an opportunity to optimize away overflow checks? I was thinking there might be some way to do it by casting both operands to unsigned, and performing checks by rolling your own two's-complement arithmetic, but I'm not really sure how to do that.</p> | 3,944,774 | 13 | 17 | null | 2010-10-15 17:16:11.36 UTC | 32 | 2021-10-15 19:08:26.22 UTC | 2017-05-23 12:17:35.543 UTC | null | -1 | null | 469,408 | null | 1 | 95 | c++|c|undefined-behavior|signed|integer-overflow | 37,321 | <p>Your approach with subtraction is correct and well-defined. A compiler cannot optimize it away.</p>
<p>Another correct approach, if you have a larger integer type available, is to perform the arithmetic in the larger type and then check that the result fits in the smaller type when converting it back</p>
<pre><code>int sum(int a, int b)
{
long long c;
assert(LLONG_MAX>INT_MAX);
c = (long long)a + b;
if (c < INT_MIN || c > INT_MAX) abort();
return c;
}
</code></pre>
<p>A good compiler should convert the entire addition and <code>if</code> statement into an <code>int</code>-sized addition and a single conditional jump-on-overflow and never actually perform the larger addition.</p>
<p><strong>Edit:</strong> As Stephen pointed out, I'm having trouble getting a (not-so-good) compiler, gcc, to generate the sane asm. The code it generates is not terribly slow, but certainly suboptimal. If anyone knows variants on this code that will get gcc to do the right thing, I'd love to see them.</p> |
3,232,904 | Using reCAPTCHA on localhost | <p>I'm developing a website using PHP and I want to make a human verification in one of the sessions. For the development, I'm initially running the system locally and when it is ready, I'm going to put it on some domain.</p>
<p>In the <a href="https://www.google.com/recaptcha/admin/create" rel="noreferrer">reCAPTCHA website</a> it is said that the plugin will only work at the given domain (and subdomains).</p>
<p>Is there a way to use the reCAPTCHA plugin on a localhost?</p> | 9,987,136 | 24 | 1 | null | 2010-07-12 22:53:02.827 UTC | 62 | 2022-07-18 10:20:42.387 UTC | 2021-07-20 19:59:05.33 UTC | null | 63,550 | null | 313,721 | null | 1 | 382 | localhost|recaptcha | 439,905 | <h3>Update</h3>
<p>The original answer is no longer correct. The developer's guide now states:</p>
<blockquote>
<p>"If you would like to use "localhost" for development, you must add it to the list of domains."</p>
</blockquote>
<p>This will only work if you access localhost using <code>127.0.0.1/...</code> rather than <code>localhost/...</code>. </p>
<p>The original answer is preserved below.</p>
<hr>
<p>According to <a href="https://developers.google.com/recaptcha/docs/faq#localhost_support" rel="noreferrer">the reCAPTCHA Developer's Guide</a>:</p>
<blockquote>
<p>"localhost domains are no longer supported by default. If you wish to continue supporting them for development you can add them to the list of supported domains for your site key. Go to the admin console to update your list of supported domains. We advise to use a separate key for development and production and to not allow localhost on your production site key."</p>
</blockquote>
<p>In other words, simply use the same key.</p> |
8,032,293 | How to install 3rd party module for postgres pl/python? | <p>I need to import a 3rd party module inside my pl/python function.
It seems pl/python uses an internal python that does not have any 3rd party modules.</p>
<p>I get this kind of error:</p>
<pre><code>ERROR: PL/Python: PL/Python function "to_tsvector_luc" failed
DETAIL: <type 'exceptions.ImportError'>: No module named lucene
********** Error **********
ERROR: PL/Python: PL/Python function "to_tsvector_luc" failed
SQL state: XX000
Detail: <type 'exceptions.ImportError'>: No module named lucene
</code></pre>
<p>How do I install the module into pl/python, so that I can import it from inside my stored procedure code?</p> | 8,036,067 | 4 | 1 | null | 2011-11-07 02:54:23.953 UTC | 5 | 2021-11-09 11:13:43.223 UTC | null | null | null | null | 496,852 | null | 1 | 31 | postgresql|plpython | 12,084 | <p>pl/python has access to the all the modules that the normal Python interpreter would have as long as they are in the <code>$PYTHONPATH</code> on the server (and the user that runs the postgres service). Does <code>import lucene</code> work if you run it in the Python interpreter on the server?</p>
<p>If your module is installed somewhere else (e.g. not dist-packages etc.), then you would need to edit your <code>/etc/postgresql/9.1/main/environment</code> (adjust to your PostgreSQL version) file on the server and add something like <code>PYTHONPATH='<path to your module>'</code>. </p> |
8,107,000 | Jshint.com requires "use strict". What does this mean? | <p>Jshint.com is giving the error:</p>
<blockquote>
<p>Line 36: var signin_found; Missing "use strict" statement.</p>
</blockquote> | 8,107,071 | 4 | 2 | null | 2011-11-12 19:34:15.857 UTC | 5 | 2015-06-27 23:03:57.953 UTC | 2015-06-27 23:03:57.953 UTC | user656925 | 815,724 | user656925 | null | null | 1 | 87 | javascript|jshint | 58,393 | <p>Add "use strict" at the top of your js file (at line 1 of your .js file):</p>
<pre><code>"use strict";
...
function initialize_page()
{
var signin_found;
/*Used to determine which page is loaded / reloaded*/
signin_found=document.getElementById('signin_button');
if(signin_found)
{
</code></pre>
<p>More about "use strict" in another question here on stackoverflow:</p>
<p><a href="https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it">What does "use strict" do in JavaScript, and what is the reasoning behind it?</a></p>
<p>UPDATE.</p>
<p>There is something wrong with jshint.com, it requires you to put "use strict" inside each function, but it should be allowed to set it globally for each file.</p>
<p>jshint.com thinks this is wrong.</p>
<pre><code>"use strict";
function asd()
{
}
</code></pre>
<p>But there is nothing wrong with it...</p>
<p>It wants you to put "use strict" to each function:</p>
<pre><code>function asd()
{
"use strict";
}
function blabla()
{
"use strict";
}
</code></pre>
<p>Then it says: </p>
<blockquote>
<p>Good job! JSHint hasn't found any problems with your code.</p>
</blockquote> |
8,223,560 | How to find the size of any object in iOS? | <p>I was optimizing my app and wanted to know that how much is the size of the object, so that I can also show it in log.</p>
<p>suppose I have</p>
<pre><code>NSDictionary *temp=(NSDictionary*)[Data objectAtIndex:i];
//data is defined in the .h file
</code></pre>
<p>now how will I know that how much is the size of the object temp?</p>
<p>I tried using the variable view and in the temp section I found:</p>
<p><code>instance_size=(long int)30498656</code></p>
<p>Is the <code>instance_size</code> the exact size of my temp object?.</p>
<p>I also tried</p>
<pre><code>sizeof(temp);
</code></pre>
<p>but it crashed on that point. Any help...?</p> | 8,223,612 | 5 | 4 | null | 2011-11-22 07:50:44.473 UTC | 14 | 2019-08-28 02:27:15.09 UTC | 2019-08-28 02:27:15.09 UTC | null | 1,265,393 | null | 1,021,896 | null | 1 | 22 | iphone|objective-c|cocoa-touch|ios4 | 16,632 | <p>The compiler knows only about the pointer, and that is why it will always return size of the pointer. To find the size of the allocated object try something like</p>
<pre><code>NSLog(@"size of Object: %zd", malloc_size(myObject));
</code></pre> |
8,232,922 | ASP pages in IIS using Localhost 401.3 Error do not have permission | <p>I have just installed the IIS so I can view asp files in a browser but when I put the address in a browser as : <a href="http://localhost/index.asp" rel="noreferrer">http://localhost/index.asp</a> I get an error. </p>
<p>The error shows this:</p>
<blockquote>
<p>HTTP Error 401.3 - Unauthorized
You do not have permission to view this directory or page because of the access control list (ACL) configuration or encryption settings for this resource on the Web server.</p>
</blockquote>
<p>I really need to get this sorted out, I would highly appreciate any advice on this. </p> | 8,234,073 | 6 | 9 | null | 2011-11-22 19:55:39.793 UTC | 14 | 2017-03-21 00:41:36.983 UTC | 2017-02-18 01:11:12.43 UTC | null | 497,418 | null | 763,179 | null | 1 | 64 | iis|asp-classic | 95,241 | <p>OK, working from memory here as I am not in front of a Windows machine. </p>
<p>If you right click on your webroot folder /inetpub/wwwroot/ or the website directory you are working on open properties and select security, I think it is, you will see the list of users with their permissions for that folder. There is a section to add new users where you can add the <code>IIS_IUSRS</code> account (search from the list of users if you need to) which will be the default user used when anonymous authentication is enabled. Give this account the relevant permissions (read, write, execute) ensuring you apply to file and subfolders. Refresh the website in IIS and you should hopefully be good to go.</p> |
7,871,425 | Is there a way to zoom into a D3 force layout graph? | <p>D3 has a force directed layout <a href="http://mbostock.github.com/d3/ex/force.html" rel="nofollow noreferrer">here</a>. Is there a way to add zooming to this graph? Currently, I was able to capture the mouse wheel event but am not really sure how to write the redraw function itself. Any suggestions?</p>
<pre><code>var vis = d3.select("#graph")
.append("svg:svg")
.call(d3.behavior.zoom().on("zoom", redraw)) // <-- redraw function
.attr("width", w)
.attr("height", h);
</code></pre> | 7,907,043 | 6 | 2 | null | 2011-10-24 04:51:18.79 UTC | 52 | 2022-01-12 05:58:07.753 UTC | 2022-01-12 05:58:07.753 UTC | null | 7,036,713 | null | 184,046 | null | 1 | 82 | javascript|jquery|d3.js|zooming|force-layout | 44,666 | <p><strong>Update 6/4/14</strong></p>
<p>See also <a href="https://stackoverflow.com/a/17976205/380487">Mike Bostock's answer here</a> for changes in D3 v.3 and the <a href="http://bl.ocks.org/mbostock/6123708" rel="nofollow noreferrer">related example</a>. I think this probably supersedes the answer below.</p>
<p><strong>Update 2/18/2014</strong></p>
<p>I think @ahaarnos's answer is preferable if you want the entire SVG to pan and zoom. The nested <code>g</code> elements in my answer below are really only necessary if you have non-zooming elements in the same SVG (not the case in the original question). If you <em>do</em> apply the behavior to a <code>g</code> element, then a background <code>rect</code> or similar element is required to ensure that the <code>g</code> receives pointer events.</p>
<p><strong>Original Answer</strong></p>
<p>I got this working based on the <a href="http://bl.ocks.org/4062045" rel="nofollow noreferrer">zoom-pan-transform</a> example - you can see my jsFiddle here: <a href="http://jsfiddle.net/nrabinowitz/QMKm3/" rel="nofollow noreferrer">http://jsfiddle.net/nrabinowitz/QMKm3/</a></p>
<p>It was a bit more complex than I had hoped - you have to nest several <code>g</code> elements to get it to work, set the SVG's <code>pointer-events</code> attribute to <code>all</code>, and then append a background rectangle to receive the pointer events (otherwise it only works when the pointer is over a node or link). The <code>redraw</code> function is comparatively simple, just setting a transform on the innermost <code>g</code>:</p>
<pre><code>var vis = d3.select("#chart")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("pointer-events", "all")
.append('svg:g')
.call(d3.behavior.zoom().on("zoom", redraw))
.append('svg:g');
vis.append('svg:rect')
.attr('width', w)
.attr('height', h)
.attr('fill', 'white');
function redraw() {
console.log("here", d3.event.translate, d3.event.scale);
vis.attr("transform",
"translate(" + d3.event.translate + ")"
+ " scale(" + d3.event.scale + ")");
}
</code></pre>
<p>This effectively scales the entire SVG, so it scales stroke width as well, like zooming in on an image.</p>
<p>There is another <a href="http://jsfiddle.net/56RDx/2" rel="nofollow noreferrer">example</a> that illustrates a similar technique.</p> |
8,116,951 | Any reason to use auto-implemented properties over manual implemented properties? | <p>I understand the advantages of PROPERTIES over FIELDS, but I feel as though using AUTO-implemented properties over MANUAL implemented properties doesn't really provide any advantage other than making the code a little more concise to look at it.</p>
<p>I feel much more comfortable using:</p>
<pre><code> private string _postalCode;
public string PostalCode
{
get { return _postalCode; }
set { _postalCode = value; }
}
</code></pre>
<p>Instead of:</p>
<pre><code>public string PostalCode { get; set; }
</code></pre>
<p>primarily because if I ever want to do any kind of custom implementation of get and set, I have to create my own property anyway backed by a private field. So why not just bite the bullet from the start and give all properties this flexibility straight away, for consistency? This really doesn't take but an extra second, considering that all you have to do in Visual Studio is click your private field name, and hit Ctrl+E, and you're done. And if I do it manually, then I end up with inconsistency in which there are SOME manually created public properties backed by private fields, and SOME auto-implemented properties. I feel much better with it being consistent all around, either all auto or all manual.</p>
<p>Is this just me? Am I missing something? Am I mistaken about something? Am I placing too much emphasis on consistency? I can always find legitimate discussions about C# features, and there are almost always pros and cons to everything, but in this case, I really couldn't find anyone who recommended against using auto-implemented properties.</p> | 8,116,967 | 7 | 6 | null | 2011-11-14 03:22:04.803 UTC | 4 | 2019-11-01 00:44:15.807 UTC | 2011-11-14 03:29:33.953 UTC | null | 120,243 | null | 1,044,866 | null | 1 | 33 | c#|properties|field|encapsulation | 18,627 | <p>It doesn't grant you anything extra beyond being concise. If you prefer the more verbose syntax, then by all means, use that.</p>
<p>One advantage to using auto props is that it can potentially save you from making a silly coding mistake such as accidentally assigning the wrong private variable to a property. Trust me, I've done it before!</p>
<p>Your point about auto props not being very flexible is a good one. The only flexibility you have is by either using <code>private get</code> or <code>private set</code> to limit scope. If your getters or setters have any complexity to them then the auto props are no longer a viable option.</p> |
8,006,250 | Copy path/file name in Eclipse to clipboard | <p>Is there a shortcut to copy the current path/file to the clipboard?</p> | 8,007,500 | 10 | 2 | null | 2011-11-04 07:49:05.227 UTC | 6 | 2020-04-23 16:43:05.137 UTC | 2015-03-05 07:30:24.943 UTC | null | 441,652 | null | 710,818 | null | 1 | 38 | eclipse|file|path-finding | 28,110 | <p>There is <code>Copy Qualified Name</code> function in Eclipse, it will copy the full name of the element you select (or element on cursor).</p>
<p>For example :</p>
<p><code>/MyProject/src/app/Application.java</code> : when you select Application.java in <code>Package Explorer</code></p>
<p><code>java.util.HashSet<String></code> : when you copy while cursor at <code>HashSet<String></code></p>
<p>However, it required you to <strong>select</strong> the element you want.</p>
<p>So, here is what I do.</p>
<ol>
<li><p>Make your <code>Package Explorer</code> link with editor, you can active this by click the double-arrow icon at top-right corner.</p></li>
<li><p>Set up a hot-key for <code>Show View (Package Explorer)</code> ex : <kbd>Alt</kbd> + <kbd>1</kbd></p></li>
<li><p>Set up a hot-key for <code>Copy Qualified Name</code> ex : <kbd>Alt</kbd> + <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>c</kbd></p></li>
</ol>
<p>Whenever I need these information in current file, I just press the hot-key to call my <code>Package Explorer</code> Since it links with editor and will always select the file in current editor, you can just copy with the hot-key. Then you can use <kbd>F12</kbd> back to your editor, or simply <kbd>ESC</kbd> if you use fast view.</p>
<p>Not perfect, but it works :D</p> |
8,218,230 | PHP DOMDocument loadHTML not encoding UTF-8 correctly | <p>I'm trying to parse some HTML using DOMDocument, but when I do, I suddenly lose my encoding (at least that is how it appears to me).</p>
<pre><code>$profile = "<div><p>various japanese characters</p></div>";
$dom = new DOMDocument();
$dom->loadHTML($profile);
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
echo $dom->saveHTML($div);
}
</code></pre>
<p>The result of this code is that I get a bunch of characters that are not Japanese. However, if I do:</p>
<pre><code>echo $profile;
</code></pre>
<p>it displays correctly. I've tried saveHTML and saveXML, and neither display correctly. I am using PHP 5.3.</p>
<p>What I see:</p>
<pre><code>ã¤ãªãã¤å·ã·ã«ã´ã«ã¦ãã¢ã¤ã«ã©ã³ãç³»ã®å®¶åºã«ã9人åå¼ã®5çªç®ã¨ãã¦çã¾ãããå½¼ãå«ãã¦4人ã俳åªã«ãªã£ããç¶è¦ªã¯æ¨æã®ã»ã¼ã«ã¹ãã³ã§ãæ¯è¦ªã¯éµä¾¿å±ã®å®¢å®¤ä¿ã ã£ããé«æ ¡æ代ã¯ãã£ãã£ã®ã¢ã«ãã¤ãã«å¤ãã¿ãæè²è³éãåããªããã«ããªãã¯ç³»ã®é«æ ¡ã¸é²å¦ã
</code></pre>
<p>What should be shown:</p>
<pre><code>イリノイ州シカゴにて、アイルランド系の家庭に、9人兄弟の5番目として生まれる。彼を含めて4人が俳優になった。父親は木材のセールスマンで、母親は郵便局の客室係だった。高校時代はキャディのアルバイトに勤しみ、教育資金を受けながらカトリック系の高校へ進学
</code></pre>
<p>EDIT: I've simplified the code down to five lines so you can test it yourself.</p>
<pre><code>$profile = "<div lang=ja><p>イリノイ州シカゴにて、アイルランド系の家庭に、</p></div>";
$dom = new DOMDocument();
$dom->loadHTML($profile);
echo $dom->saveHTML();
echo $profile;
</code></pre>
<p>Here is the html that is returned:</p>
<pre><code><div lang="ja"><p>イリノイ州シカゴã«ã¦ã€ã‚¢ã‚¤ãƒ«ãƒ©ãƒ³ãƒ‰ç³»ã®å®¶åºã«ã€</p></div>
<div lang="ja"><p>イリノイ州シカゴにて、アイルランド系の家庭に、</p></div>
</code></pre> | 8,218,649 | 11 | 4 | null | 2011-11-21 20:37:52.58 UTC | 81 | 2022-01-07 23:04:27.71 UTC | 2013-10-17 22:31:35.65 UTC | null | 283,078 | null | 519,204 | null | 1 | 242 | php|utf-8|character-encoding | 131,246 | <p><code>DOMDocument::loadHTML</code> will treat your string as being in ISO-8859-1 (the HTTP/1.1 default character set) unless you tell it otherwise. This results in UTF-8 strings being interpreted incorrectly.</p>
<p>If your string doesn't contain an XML encoding declaration, you can prepend one to cause the string to be treated as UTF-8:</p>
<pre><code>$profile = '<p>イリノイ州シカゴにて、アイルランド系の家庭に、9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();
</code></pre>
<p>If you cannot know if the string will contain such a declaration already, there's a workaround in <a href="http://beerpla.net/projects/smartdomdocument-a-smarter-php-domdocument-class/" rel="noreferrer">SmartDOMDocument</a> which should help you:</p>
<pre><code>$profile = '<p>イリノイ州シカゴにて、アイルランド系の家庭に、9</p>';
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8'));
echo $dom->saveHTML();
</code></pre>
<p>This is not a great workaround, but since not all characters can be represented in ISO-8859-1 (like these katana), it's the safest alternative.</p> |
7,783,341 | Run script with rc.local: script works, but not at boot | <p>I have a node.js script which need to start at boot <em>and</em> run under the www-data user. During development I always started the script with:</p>
<pre><code>su www-data -c 'node /var/www/php-jobs/manager.js
</code></pre>
<p>I saw exactly what happened, the manager.js works now great. Searching SO I found I had to place this in my <code>/etc/rc.local</code>. Also, I learned to point the output to a log file and to append the <code>2>&1</code> to "redirect stderr to stdout" and it should be a daemon so the last character is a <code>&</code>.</p>
<p>Finally, my <code>/etc/rc.local</code> looks like this:</p>
<pre><code>#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
su www-data -c 'node /var/www/php-jobs/manager.js >> /var/log/php-jobs.log 2>&1 &'
exit 0
</code></pre>
<p>If I run this myself (<code>sudo /etc/rc.local</code>): yes, it works! However, if I perform a reboot no <code>node</code> process is running, the <code>/var/log/php-jobs.log</code> does not exist and thus, the manager.js does not work. What is happening?</p> | 8,331,447 | 17 | 6 | null | 2011-10-16 09:10:07.46 UTC | 25 | 2022-07-25 14:44:37.703 UTC | null | null | null | null | 434,223 | null | 1 | 40 | linux|bash|ubuntu|boot|autorun | 172,939 | <p>I ended up with <a href="http://kevin.vanzonneveld.net/techblog/article/run_nodejs_as_a_service_on_ubuntu_karmic/" rel="noreferrer">upstart</a>, which works fine.</p> |
4,375,302 | Using imagejpeg to save & serve image file | <p>I'm doing a bit of an experiment with PHP + Image manipulation. I'm trying to convert some images into black and white versions. I'm mostly figured it out but have one slight issue.</p>
<p>In order to reduce the strain on the server, I wanted to save the B&W versions and only run the image filtering on images that haven't been run through the script before. So, I have something like this:</p>
<pre><code><?php
header("Content-type: image/jpeg");
$file = $_GET['img'];
$name = md5($file).".jpg";
if(file_exists("/path/to/file" . $name)) {
ob_clean();
flush();
readfile("path/to/file" . $name);
exit;
}
else {
$image = imagecreatefromjpeg($file);
imagefilter($image, IMG_FILTER_GRAYSCALE);
imagejpeg($image, "/path/to/file" . $name);
imagedestroy($image);
};
?>
</code></pre>
<p>This does create the B&W versions of the file and save them to the server. The initial "if" statement is also working - it correctly serves the image if it already exists.</p>
<p>The issue is that for new images that are run through, this saves them but doesn't output them to the browser. What can I use/change in order to do that?</p>
<p>Also, this is my first time doing anything like this. Any general tips you have about doing the above would be appreciated.</p> | 4,375,465 | 3 | 0 | null | 2010-12-07 09:53:26.02 UTC | 1 | 2013-03-07 02:52:59.293 UTC | null | null | null | null | 280,869 | null | 1 | 4 | php|image-processing | 49,309 | <p>A compact and correct form for above function can be:</p>
<pre><code><?php
header("Content-type: image/jpeg");
$file = $_GET['img'];
$name = md5($file).".jpg";
if(!file_exists("/path/to/file" . $name)) {
imagefilter($image, IMG_FILTER_GRAYSCALE);
imagejpeg($image, "/path/to/file" . $name);
} else {
$image = imagecreatefromjpeg("/path/to/file" . $name);
}
imagejpeg($image);
imagedestroy($image);
?>
</code></pre> |
4,358,213 | How does one intercept a request during the Jersey lifecycle? | <p>I've used Jersey for the better part of a year now and have just stumbled upon a problem to which I can't find the answer: how do you intercept (or hook into) the Jersey request lifecycle?</p>
<p>Ideally, I'd be able to perform some custom filtering/validation/rejection between the time the container accepts the request from the network and the time my handler methods are called. Bonus points if there's an easy way to filter the interceptors by sub-path (e.g. have one interceptor for anything under /, another for anything under /user/, etc.).</p>
<p>Thanks!</p>
<p>Edit: To be a bit clearer, the general idea here is to be able to write some code that will be run for many API calls without having to explicitly call that code from each handler method. This would reduce extra code and eliminate the need to pass request contexts around.</p> | 4,362,323 | 4 | 3 | null | 2010-12-05 09:47:17.16 UTC | 10 | 2016-08-11 07:48:33.043 UTC | 2010-12-05 10:07:52.587 UTC | null | 394,496 | null | 394,496 | null | 1 | 49 | java|api|jax-ws|jersey|jax-rs | 35,617 | <p>I've found the answer.</p>
<p>First, create a class that implements ContainerRequestFilter. The interface specifies the following method, in which the filtering takes place. The ContainerRequest object contains information about the current request.</p>
<pre><code>public ContainerRequest filter(ContainerRequest req);
</code></pre>
<p>After that, include the following XML in the servlet configuration in web.xml</p>
<pre><code><init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>path.to.filtering.class</param-value>
</init-param>
</code></pre>
<p>Sources:</p>
<p><a href="http://jersey.576304.n2.nabble.com/ContainerRequestFilter-and-Resources-td4419975.html" rel="noreferrer">http://jersey.576304.n2.nabble.com/ContainerRequestFilter-and-Resources-td4419975.html</a>
<a href="http://markmail.org/message/p7yxygz4wpakqno5" rel="noreferrer">http://markmail.org/message/p7yxygz4wpakqno5</a></p> |
4,507,893 | Django filter many-to-many with contains | <p>I am trying to filter a bunch of objects through a many-to-many relation. Because the <code>trigger_roles</code> field may contain multiple entries I tried the <code>contains</code> filter. But as that is designed to be used with strings I'm pretty much helpless how i should filter this relation (you can ignore the <code>values_list()</code> atm.).</p>
<p>This function is attached to the user profile:</p>
<pre><code>def getVisiblePackages(self):
visiblePackages = {}
for product in self.products.all():
moduleDict = {}
for module in product.module_set.all():
pkgList = []
involvedStatus = module.workflow_set.filter(trigger_roles__contains=self.role.id,allowed=True).values_list('current_state', flat=True)
</code></pre>
<p>My workflow model looks like this (simplified):</p>
<pre><code>class Workflow(models.Model):
module = models.ForeignKey(Module)
current_state = models.ForeignKey(Status)
next_state = models.ForeignKey(Status)
allowed = models.BooleanField(default=False)
involved_roles = models.ManyToManyField(Role, blank=True, null=True)
trigger_roles = models.ManyToManyField(Role, blank=True, null=True)
</code></pre>
<p>Though the solution might be quiet simple, my brain won't tell me.</p>
<p>Thanks for your help.</p> | 4,508,083 | 4 | 0 | null | 2010-12-22 09:44:26.03 UTC | 14 | 2020-06-15 14:41:50.287 UTC | 2020-06-15 14:41:50.287 UTC | null | 4,720,018 | null | 508,474 | null | 1 | 108 | python|django|django-models|many-to-many|django-orm | 101,531 | <p>Have you tried something like this:</p>
<pre><code>module.workflow_set.filter(trigger_roles__in=[self.role], allowed=True)
</code></pre>
<p>or just if <code>self.role.id</code> is not a list of pks:</p>
<pre><code>module.workflow_set.filter(trigger_roles__id__exact=self.role.id, allowed=True)
</code></pre> |
4,690,986 | RegEx needed to match number to exactly two decimal places | <p>I need some regex that will match only numbers that are decimal to two places. For example:</p>
<ul>
<li>123 = No match</li>
<li>12.123 = No match</li>
<li>12.34 = Match</li>
</ul> | 4,691,005 | 5 | 0 | null | 2011-01-14 12:24:52.513 UTC | 5 | 2020-12-03 12:46:48.497 UTC | 2019-10-28 15:53:38.537 UTC | null | 59,087 | null | 449,568 | null | 1 | 25 | regex | 90,333 | <pre><code>^[0-9]*\.[0-9]{2}$ or ^[0-9]*\.[0-9][0-9]$
</code></pre> |
4,128,001 | Is it ok for an HTML element to have the same [name] as its [id]? | <p>I'm working on embedding a flash app in a webpage using the Satay method:</p>
<pre><code><object type="application/x-shockwave-flash" data="embeddy.swf"
<i>id="embeddy" name="embeddy"</i>>
<param name="movie" value="embeddy.swf" />
</object></code></pre>
<p>I want flash to provide the correct <code>objectID</code> in <code>ExternalInterface.objectID</code>, which means I need to set both the <code>name</code> and <code>id</code> attributes for the <code>object</code>.</p>
<p>Normally I try to avoid naming collisions with elements in HTML, but is there anything wrong with setting both attributes to the same value in this case?</p>
<p>What about HTML forms? Does anyone feel that it's worthwhile to set a(n) ( <code>input</code> | <code>select</code> | <code>textarea</code> ) element's <code>name</code> and <code>id</code> attributes to the same value?</p> | 4,128,017 | 5 | 0 | null | 2010-11-08 20:57:31.153 UTC | 6 | 2015-05-27 15:41:06.79 UTC | null | null | null | null | 497,418 | null | 1 | 42 | html|flash|embedding|object-tag | 19,668 | <p>You use IDs for JavaScript manipulation.</p>
<p>You use Names for form field submission.</p>
<p>The two are not related. So setting both to the same value is OK, but it is not required.</p> |
4,592,166 | What does the term "empty loop" refer to exactly in C and C++? | <p>Is it this kind of thing:</p>
<pre><code>for(;;)
{
statements;
}
</code></pre>
<p>Or is it this:</p>
<pre><code>for(initialisation;condition;updation)
{
}
</code></pre>
<p>I am looking for answers with references to a variety of sources.</p> | 4,592,201 | 6 | 1 | null | 2011-01-04 09:33:19.017 UTC | null | 2019-10-03 07:11:18.417 UTC | 2015-08-15 20:30:58.983 UTC | null | 895,245 | null | 562,325 | null | 1 | 34 | c++|c | 49,874 | <p>Your first case (<em>for</em> with empty expressions) is an <strong>infinite</strong> loop and the second one (with empty body of the <em>for</em> statement) is an <strong>empty</strong> loop</p> |
4,309,533 | Why do I get "Database logon failed" in Crystal Reports when using .NET object as datasource? | <p>I am creating a simple report using a .NET object from my project as datasource, using <code>SetDatasource()</code> method. However, when I run the report I get "Database logon failed" error. This report is not connecting to a DB at all - have I missed something here?</p>
<p>Many thanks,
D.</p>
<p>ADDED:
I guess it will probably help if I include the Controller action. It's a quick and dirty test, not what the final method will look like:</p>
<pre class="lang-cs prettyprint-override"><code>public ActionResult StewardSheets(int showId, int groupId)
{
ReportClass rptH = new ReportClass();
rptH.FileName = DataHelper.getReportFilePath("Test.rpt",this);
NZDSDataContext dataContext = new NZDSDataContext();
var showDetails = (from s in dataContext.Shows
where s.ID == showId
select new StewardSheetModel
{
EventDate = s.EventDate.ToLongDateString(),
Region = s.Region.Name,
ShowTitle = s.Name
}).FirstOrDefault();
List<StewardSheetModel> details = new List<StewardSheetModel>();
details.Add(showDetails);
rptH.SetDataSource(details);
rptH.Refresh();
Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
return File(stream, "application/pdf");
}
</code></pre>
<p>FIXED:
D'oh! I used ReportClass instead of ReportDocument. Changed that line, and also use Refresh() since Load() is not a valid method. Now it works just fine!</p> | 4,374,049 | 12 | 2 | null | 2010-11-30 00:38:50.767 UTC | 6 | 2020-07-30 13:05:46.7 UTC | 2020-04-15 09:18:06.75 UTC | null | 3,705,348 | null | 150,061 | null | 1 | 10 | crystal-reports | 78,304 | <p>Fixed by using the appropriate class: ReportDocument instead of ReportClass.</p> |
4,313,841 | Insert a string at a specific index | <p>How can I insert a string at a specific index of another string? </p>
<pre><code> var txt1 = "foo baz"
</code></pre>
<p>Suppose I want to insert "bar " after the "foo" how can I achieve that?</p>
<p>I thought of <code>substring()</code>, but there must be a simpler more straight forward way.</p> | 4,314,050 | 18 | 1 | null | 2010-11-30 12:40:59.553 UTC | 75 | 2022-01-25 17:39:14.64 UTC | 2018-10-26 19:49:58.13 UTC | null | 3,345,644 | null | 292,291 | null | 1 | 435 | javascript|string | 693,130 | <p>You could prototype your own <code>splice()</code> into String.</p>
<h2>Polyfill</h2>
<pre><code>if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* @this {String}
* @param {number} start Index at which to start changing the string.
* @param {number} delCount An integer indicating the number of old chars to remove.
* @param {string} newSubStr The String that is spliced in.
* @return {string} A new string with the spliced substring.
*/
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
</code></pre>
<h2>Example</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
var result = "foo baz".splice(4, 0, "bar ");
document.body.innerHTML = result; // "foo bar baz"</code></pre>
</div>
</div>
</p>
<hr>
<p><strong>EDIT:</strong> Modified it to ensure that <code>rem</code> is an absolute value.</p> |
14,615,712 | Toggle classname onclick JavaScript | <p>I am nearly there, just a little unsure as to my code setup, I basically want to remove a class on click, and add it back again onclick, then remove onclick, then add onclick. And so on! Here's what I have, it's nearly there, but if there is a nicer way to do this then please help! Thank you.</p>
<pre><code>document.getElementById('myButton').onclick = function() {
myButton.className = myButton.className.replace(/(?:^|\s)active(?!\S)/g, '') ? 'active': jbar.className.replace(/(?:^|\s)active(?!\S)/g, '') ;
}
</code></pre>
<p>Any help much appreciated!</p> | 14,615,765 | 5 | 0 | null | 2013-01-30 23:20:07.937 UTC | 5 | 2017-01-31 16:47:32.427 UTC | null | null | null | user1323595 | null | null | 1 | 11 | javascript|toggle | 48,731 | <p>If you want to use a ternary operator, use this:</p>
<pre><code>document.getElementById('myButton').onclick = function() {
var className = ' ' + myButton.className + ' ';
this.className = ~className.indexOf(' active ') ?
className.replace(' active ', ' ') :
this.className + ' active';
}
</code></pre>
<hr>
<p>For clarity, I'd use a regular if/else:</p>
<pre><code>document.getElementById('myButton').onclick = function() {
var className = ' ' + myButton.className + ' ';
if ( ~className.indexOf(' active ') ) {
this.className = className.replace(' active ', ' ');
} else {
this.className += ' active';
}
}
</code></pre>
<p>Here's the fiddle: <a href="http://jsfiddle.net/ttEGY/">http://jsfiddle.net/ttEGY/</a></p> |
14,537,286 | Event driven design in c | <p>this is a little theoretical question.
Imagine a device full of sensors. Now, in case a sensor x detects something, something should happen. Meanwhile, in case something else is detected, like two sensors detects two different things, then, this device must behave differently.</p>
<p>From webdesign (so javascript) I learned about Events, for example (using jquery) <code>$(".x").on("click", function(){})</code> or from angularjs <code>$scope.watch("name_of_var", function())</code>.</p>
<p>Is there any possibility to replicate this behaviour in C, without using complex libraries?</p>
<p>Thanks.</p> | 14,537,499 | 4 | 8 | null | 2013-01-26 13:14:17.53 UTC | 8 | 2022-08-24 16:42:12.247 UTC | null | null | null | null | 985,383 | null | 1 | 13 | c|events|event-driven-design | 24,361 | <p>I would assume you're owning an embedded system with access to interrupts or a major event loop in a separate thread, otherwise this isn't possible..</p>
<p>A basic model for event handling is here:</p>
<pre><code>#define NOEVENT 0
typedef void *(*EventHandler)(void *);
void *doNothing(void *p){/*do nothing absolutely*/ return NULL; }
typedef struct _event{
EventHandler handler;
}Event, *PEvent;
Event AllEvents[1000];
unsigned short counter = 0;
void InitEvents()
{
LOCK(AllEvents);
for(int i = 0; i < 1000; i++){
AllEvents[i].handler = doNothing;
}
UNLOCK(AllEvents);
}
void AddEvent(int EventType, EventHandler ev_handler)
{
LOCK(AllEvents);
AllEvents[EventType].handler = ev_handler;
UNLOCK(AllEvents);
}
void RemoveEvent(int EventType, EventHandler ev_handler)
{
LOCK(AllEvents);
AllEvents[EventType] = doNothing;
UNLOCK(AllEvents); /*to safeguard the event loop*/
}
/*to be run in separate thread*/
void EventLoop()
{
int event = NOEVENT;
EventHandler handler;
while(1){
while(event == NOEVENT)event=GetEvents();
handler = AllEvents[event].handler;
handler();/*perform on an event*/
}
}
</code></pre> |
14,481,032 | where is hardware timer interrupt? | <p>this is Exceptions and Interrupts table(which I understand as IDT)
from the "Intel Architecture Software Developer Manual"</p>
<p><img src="https://i.stack.imgur.com/ZKye4.png" alt="Exceptions and Interrupts"></p>
<p>where is Timer interrupt which makes context switching possible??
(for multi-tasking)</p>
<p>if this is a stupid question, please fix my understanding.
thank you in advance</p> | 14,481,859 | 2 | 0 | null | 2013-01-23 13:36:00.897 UTC | 8 | 2014-07-31 17:01:46.097 UTC | null | null | null | null | 1,528,889 | null | 1 | 16 | linux|operating-system|kernel|interrupt | 7,397 | <p>Well, yes, if we are talking about the traditional 8254 PIT timer, it is at IRQ0, which is vector 32. But that is not generally used as the timer in the Linux operating system on modern machines. [Note that the vector assignment of 32 is really quite arbitrary. It is set when programming the 8259 (PIC) or APIC - but it's not a bad choice, since 32 is the first vector AFTER the reserved ones. It's certainly better than mixing the hardware interrupts with exception vectors, as DOS would do - so there was no way to tell a General Protection fault (vector 13 in the table above) from a INTR 5 (also vector 13, as the INT0 was mapped to Vector 8, and 5 + 8 = 13). From memory, INTR5 wasn't particularly well used - something like LPT2: (Second parallel port). But it's still a good idea to not overlap them... Henc the "reserved" for the vectors 20 to 31. </p>
<p>The IRQ that actually controls the timing of the system is most likely a Local APIC timer, and it's vector is not fixed in hardware in the same way as the original PC. </p>
<p>Also, with the advent of "message signalled interrupts", it is entirely possible to have (much) more than 256 interrupt vectors. </p>
<p>I don't agree with the wording "vector 0-19 are non-maskable interrupts". Aside from NMI (vector 2), they are all EXCEPTIONS (aka TRAPS or FAULTS) - that is, an event driven by some error condition in the system - vector zero is the result of an integer divide by zero, vector 1 is a "single step" instruction interrupt [and a few other "debug" traps, such as "write to any address matching an enabled debug register"], vector 3 is the result of a "int3" instruction (opcode 0xcc), vector 4 is the result of executing "INTO"(that's 'o' as in overflow, not <code>0</code> as in zero). When accessing a piece of memory not marked as present in the page-tables, vector 14 is used. They are indeed "non-maskable", but they are, with a few exceptions, direct consequences of the instructon executing at the time - so they are synchronous to the program itself. </p>
<p>The exceptions are the "Double fault" exception and "machine check fault".</p>
<p>Double fault is when the processor detects a fault during the handling of another exception - typically because the operating system has done something daft, like set the stack to somewhere invalid, and thus gets a page-fault, tries to use the stack to store the page-fault return address and that fails because the stack is not accessible. Double fault handlers, thus, tends to be set as "task switch interrupts", and load a new stack to make sure the double fault can continue. If the double fault handler can't run correctly, the processor will "triple-fault". This usually means "reboot" on PC platforms. Double faults are normally not recoveriable - the handler will (try to) provide some information about what happened, and how it got into this state, but once that's done, the system either reboots or waits for someone to come and push the reset button. </p>
<p>Machine check fault is where the processor detects an unrecoverable error - such as irrecoverable memory error or a cache parity error, etc. These are typically also non-recoverable, but not DIRECTLY coupled with the instruction being executed, but more on a combination of different events (memory read of an address where the memory content has gone bad, or similar).</p> |
14,827,398 | Converting byte array values in little endian order to short values | <p>I have a byte array where the data in the array is actually short data. The bytes are ordered in little endian:</p>
<p>3, 1, -48, 0, -15, 0, 36, 1</p>
<p>Which when converted to short values results in:</p>
<p>259, 208, 241, 292</p>
<p>Is there a simple way in Java to convert the byte values to their corresponding short values? I can write a loop that just takes every high byte and shift it by 8 bits and OR it with its low byte, but that has a performance hit.</p> | 14,827,440 | 2 | 5 | null | 2013-02-12 07:18:10.583 UTC | 3 | 2020-04-22 01:51:39.423 UTC | 2015-02-07 10:17:33.533 UTC | null | 318,054 | null | 753,632 | null | 1 | 25 | java|arrays|byte|endianness | 51,728 | <p>With <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html" rel="noreferrer">java.nio.ByteBuffer</a> you may specify the endianness you want: <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#order%28java.nio.ByteOrder%29" rel="noreferrer">order()</a>.</p>
<p>ByteBuffer have methods to extract data as byte, char, <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getShort%28%29" rel="noreferrer">getShort()</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getInt%28%29" rel="noreferrer">getInt()</a>, long, double...</p>
<p>Here's an example how to use it:</p>
<pre><code>ByteBuffer bb = ByteBuffer.wrap(byteArray);
bb.order( ByteOrder.LITTLE_ENDIAN);
while( bb.hasRemaining()) {
short v = bb.getShort();
/* Do something with v... */
}
</code></pre> |
14,873,227 | Escaping colons in YAML | <p>Does anyone know how to escape colons in YAML? The key in my yml is the
domain with port number, but the yml file isn't working with this setup:</p>
<pre><code>###BEGIN
production:
### THIS IS THE ONE I'm HAVING TROUBLE WITH ###
8.11.32.120:8000: GoogleMapsKeyforThisDomain
exampledomain.com: GoogleMapsAPIKeyforThatDomain
development:
GoogleMapsAPIKeyforDevelopmentDomain
###END
</code></pre>
<p>I'm using a google maps plugin called YM4R that uses a .yml file to
select the different Google Maps API key depending on where my app is
being hosted...</p>
<p>So, I'm trying to make <code>8.11.32.120:8000 the key</code>. Any idea how to do
this? (It's in the gmaps_api_key.yml file if you care)</p> | 14,873,305 | 2 | 4 | null | 2013-02-14 10:57:15.547 UTC | 3 | 2019-06-22 18:58:31.223 UTC | 2017-12-11 23:11:41.77 UTC | null | 42,223 | user2071444 | null | null | 1 | 35 | escaping|yaml|delimiter | 27,070 | <p>You'll need to put quotes around the key you're having trouble with. I.e.:</p>
<pre><code>"8.11.32.120:8000": GoogleMapsKeyforThisDomain
</code></pre> |
3,185,217 | Error Code: 1136 Column count doesn't match value count at row 1) inside sp | <p>i have some troubles filling a predefined table with a stored procedure.
mytable has 6 fields: uid,testrun,exp1,exp2,exp3,weightedvalue where uid is an autoincrement PK. My sp contains an insert statement like: </p>
<pre><code>CREATE PROCEDURE test (IN testrun INT)
BEGIN
.... some declare statements ...
INSERT INTO exp_factors(testrun,exp1,exp2,exp3,weightedvalue) VALUES
(testrun,
exp1,
exp2_1 + exp2_2,
exp3_1 + exp3_2,
exp1 * 0,2 + (exp2_1+exp2_2) * 0.5 + (exp3_1+exp3_2) * 0.3);
END
</code></pre>
<p>Unfortunately this results in the error stated in the title. I understand that I insert only 5 of 6 fields but obviously I do not want to enter the autoincrement PK uid manually.
How can I enter my exp values to this table without passing on the autoincrement id.
Of course I could just create a table without an extra PK, but that´s not what i want. </p>
<p>Thanks for any suggestions in advance!</p> | 3,185,230 | 2 | 0 | null | 2010-07-06 09:58:01.15 UTC | 1 | 2013-08-05 07:59:09.62 UTC | null | null | null | null | 366,256 | null | 1 | 3 | mysql | 53,365 | <p>You have a comma in the last line of your insert, making 6 columns instead of 5:</p>
<pre><code>exp1 * 0,2 + (exp2_1+exp2_2) * 0.5 + (exp3_1+exp3_2) * 0.3
^
</code></pre>
<p>I guess that this should be a decimal point, not a comma.</p> |
2,355,025 | jQuery get img source attributes from list and push into array | <p>I have this thumbnail list and would like push the image paths (sources) into an array: tn_array</p>
<pre><code><ul id="thumbnails">
<li><img src="somepath/tn/004.jpg" alt="fourth caption" /></a></li>
<li><img src="somepath/tn/005.jpg" alt="fifth caption" /></a></li>
<li><img src="somepath/tn/006.jpg" alt="sixth caption" /></a></li>
</ul>
</code></pre> | 2,355,045 | 2 | 0 | null | 2010-03-01 10:08:07.24 UTC | 11 | 2015-03-10 21:12:05.407 UTC | null | null | null | null | 238,898 | null | 1 | 20 | jquery|arrays|loops|attributes|push | 36,920 | <p>You can create the array of src attributes more directly using <a href="http://api.jquery.com/map/" rel="noreferrer"><code>map()</code></a>:</p>
<pre><code>var tn_array = $("#thumbnails img").map(function() {
return $(this).attr("src");
});
</code></pre>
<p><strong>Edit:</strong> <code>tn_array</code> is an object here rather than a strict Javascript array but it will act as an array. For example, this is legal code:</p>
<pre><code>for (int i=0; i<tn_array.length; i++) {
alert(tn_array[i]);
}
</code></pre>
<p>You can however call <a href="http://api.jquery.com/get/" rel="noreferrer"><code>get()</code></a>, which will make it a strict array:</p>
<pre><code>var tn_array = $("#thumbnails img").map(function() {
return $(this).attr("src");
}).get();
</code></pre>
<p>How do you tell the difference? Call:</p>
<pre><code>alert(obj.constructor.toString());
</code></pre>
<p>The first version will be:</p>
<pre><code>function Object() { [native code] }
</code></pre>
<p>The second:</p>
<pre><code>function Array() { [native code] }
</code></pre> |
32,843,099 | Jackson Not Overriding Getter with @JsonProperty | <p><code>JsonProperty</code> isn't overriding the default name jackson gets from the getter. If I serialize the class below with <code>ObjectMapper</code> and jackson I get</p>
<pre><code>{"hi":"hello"}
</code></pre>
<p>As you can see the JsonProperty annotation has no effect</p>
<pre><code>class JacksonTester {
String hi;
@JsonProperty("hello")
public String getHi() {
return hi;
}
}
</code></pre>
<p>Putting <code>@JsonProperty</code> on the String itself doesn't work either. The only way it seems that I can change the name is by renaming the getter, the only problem is that it then will always be lowercase for the first letter</p> | 32,844,950 | 11 | 0 | null | 2015-09-29 11:45:18.04 UTC | 5 | 2022-06-22 10:29:00.23 UTC | 2015-09-29 12:10:33.463 UTC | null | 4,093,621 | null | 4,093,621 | null | 1 | 33 | java|json|serialization|jackson|getter | 76,913 | <p>The problem was that I was using both the old and new jackson libraries</p>
<p>i.e. before I had
<code>import org.codehaus.jackson.annotate.JsonProperty;</code>
Which I had to change to below, to be consistent with the library I was using. </p>
<p>Since I was using maven that also meant updating my maven dependencies.
<code>import com.fasterxml.jackson.annotation.JsonProperty;</code></p>
<p>For it to work, I needed the <code>@JsonProperty</code> annotation on the getter (putting it on the object didn't work)</p>
<p>I found the answer here (thanks to francescoforesti)
<a href="https://stackoverflow.com/questions/21125173/jsonproperty-not-working-as-expected">@JsonProperty not working as expected</a></p> |
33,713,680 | SSH – Force Command execution on login even without Shell | <p>I am creating a restricted user without shell for port forwarding only and I need to execute a script on login via pubkey, even if the user is connected via <code>ssh -N user@host</code> which doesn't asks SSH server for a shell.</p>
<p>The script should warn admin on connections authenticated with pubkey, so the user connecting shouldn't be able to skip the execution of the script (e.g., by connecting with <code>ssh -N</code>).</p>
<p>I have tried to no avail:</p>
<ul>
<li>Setting the command at <code>/etc/ssh/sshrc</code>.</li>
<li>Using command="COMMAND" in <code>.ssh/authorized_keys</code> (man authorized_keys)</li>
<li>Setting up a script with the command as user's shell. (<code>chsh -s /sbin/myscript.sh USERNAME</code>)</li>
<li>Matching user in <code>/etc/ssh/sshd_config</code> like:
<code>
Match User MYUSERNAME
ForceCommand "/sbin/myscript.sh"
</code></li>
</ul>
<p>All work when user asks for shell, but if logged only for port forwarding and no shell (<code>ssh -N</code>) it doesn't work.</p> | 61,079,746 | 4 | 1 | null | 2015-11-14 21:38:08.45 UTC | 14 | 2020-04-08 09:51:12.393 UTC | 2017-05-08 11:07:33.877 UTC | null | 1,640,661 | null | 371,160 | null | 1 | 19 | ssh|sshd | 49,409 | <p>If you only need to run a script you can rely on <code>pam_exec</code>.</p>
<p>Basically you reference the script you need to run in the <code>/etc/pam.d/sshd</code> configuration:</p>
<pre><code>session optional pam_exec.so seteuid /path/to/script.sh
</code></pre>
<p>After some testing you may want to change <code>optional</code> to <code>required</code>.</p>
<p>Please refer to this answer "<a href="https://askubuntu.com/a/448602">bash - How do I set up an email alert when a ssh login is successful? - Ask Ubuntu</a>" for a similar request.</p>
<p>Indeed in the script only a limited subset on the environment variables is available:</p>
<pre><code>LANGUAGE=en_US.UTF-8
PAM_USER=bitnami
PAM_RHOST=192.168.1.17
PAM_TYPE=open_session
PAM_SERVICE=sshd
PAM_TTY=ssh
LANG=en_US.UTF-8
LC_ALL=en_US.UTF-8
PWD=/
</code></pre>
<p>If you want to get the user info from <code>authorized_keys</code> this script could be helpful:</p>
<pre><code>#!/bin/bash
# Get user from authorized_keys
# pam_exec_login.sh
# * [ssh - What is the SHA256 that comes on the sshd entry in auth.log? - Server Fault](https://serverfault.com/questions/888281/what-is-the-sha256-that-comes-on-the-sshd-entry-in-auth-log)
# * [bash - How to get all fingerprints for .ssh/authorized_keys(2) file - Server Fault](https://serverfault.com/questions/413231/how-to-get-all-fingerprints-for-ssh-authorized-keys2-file)
# Setup log
b=$(basename $0| cut -d. -f1)
log="/tmp/${b}.log"
function timeStamp () {
echo "$(date '+%b %d %H:%M:%S') ${HOSTNAME} $b[$$]:"
}
# Check if opening a remote session with sshd
if [ "${PAM_TYPE}" != "open_session" ] || [ $PAM_SERVICE != "sshd" ] || [ $PAM_RHOST == "::1" ]; then
exit $PAM_SUCCESS
fi
# Get info from auth.log
authLogLine=$(journalctl -u ssh.service |tail -100 |grep "sshd\[${PPID}\]" |grep "${PAM_RHOST}")
echo ${authLogLine} >> ${log}
PAM_USER_PORT=$(echo ${authLogLine}| sed -r 's/.*port (.*) ssh2.*/\1/')
PAM_USER_SHA256=$(echo ${authLogLine}| sed -r 's/.*SHA256:(.*)/\1/')
# Get details from .ssh/authorized_keys
authFile="/home/${PAM_USER}/.ssh/authorized_keys"
PAM_USER_authorized_keys=""
while read l; do
if [[ -n "$l" && "${l###}" = "$l" ]]; then
authFileSHA256=$(ssh-keygen -l -f <(echo "$l"))
if [[ "${authFileSHA256}" == *"${PAM_USER_SHA256}"* ]]; then
PAM_USER_authorized_keys=$(echo ${authFileSHA256}| cut -d" " -f3)
break
fi
fi
done < ${authFile}
if [[ -n ${PAM_USER_authorized_keys} ]]
then
echo "$(timeStamp) Local user: ${PAM_USER}, authorized_keys user: ${PAM_USER_authorized_keys}" >> ${log}
else
echo "$(timeStamp) WARNING: no matching user in authorized_keys" >> ${log}
fi
</code></pre> |
30,089,675 | Clustering cosine similarity matrix | <p>A few questions on stackoverflow mention this problem, but I haven't found a concrete solution.</p>
<p>I have a square matrix which consists of cosine similarities (values between 0 and 1), for example:</p>
<pre><code> | A | B | C | D
A | 1.0 | 0.1 | 0.6 | 0.4
B | 0.1 | 1.0 | 0.1 | 0.2
C | 0.6 | 0.1 | 1.0 | 0.7
D | 0.4 | 0.2 | 0.7 | 1.0
</code></pre>
<p>The square matrix can be of any size. I want to get clusters (I don't know how many) which maximize the values between the elements in the cluster. I.e. for the above example I should get two clusters:</p>
<ol>
<li>B</li>
<li>A, C, D</li>
</ol>
<p>The reason being because C & D have the highest value between them, and A & C also have the highest value between them.</p>
<p>An item can be in only one cluster.</p>
<p>Recall is not that important for this problem, but precision is very important. It is acceptable to output three clusters: 1) B, 2) A, 3) C, D . But it is not acceptable to output any solution where B is in a cluster with another element.</p>
<p>I think the diagonal (1.0) is confusing me. My data is guaranteed to have at least one cluster of 2+ elements, and I want to find as many clusters as possible without sacrificing precision.</p>
<p>I will have to implement this in Python.</p> | 30,093,501 | 1 | 1 | null | 2015-05-06 23:58:16.383 UTC | 13 | 2018-08-21 23:57:19.383 UTC | 2015-05-07 21:07:12.263 UTC | null | 1,060,350 | null | 1,430,038 | null | 1 | 20 | python|math|scikit-learn|cluster-analysis|data-mining | 23,871 | <p>You can easily do this using spectral clustering. You can use the ready implementations such as the one in sklearn or implement it yourself. It is rather an easy algorithm.</p>
<p>Here is a piece of code doing it in python using sklearn:</p>
<pre><code>import numpy as np
from sklearn.cluster import SpectralClustering
mat = np.matrix([[1.,.1,.6,.4],[.1,1.,.1,.2],[.6,.1,1.,.7],[.4,.2,.7,1.]])
SpectralClustering(2).fit_predict(mat)
>>> array([0, 1, 0, 0], dtype=int32)
</code></pre>
<p>As you can see it returns the clustering you have mentioned.</p>
<p>The algorithm takes the top k eigenvectors of the input matrix corresponding to the largest eigenvalues, then runs the k-mean algorithm on the new matrix. Here is a simple code that does this for your matrix:</p>
<pre><code>from sklearn.cluster import KMeans
eigen_values, eigen_vectors = np.linalg.eigh(mat)
KMeans(n_clusters=2, init='k-means++').fit_predict(eigen_vectors[:, 2:4])
>>> array([0, 1, 0, 0], dtype=int32)
</code></pre>
<p>Note that the implementation of the algorithm in the sklearn library may differ from mine. The example I gave is the simplest way of doing it. There are some good tutorial available online describing the spectral clustering algorithm in depth.</p>
<p>For the cases you want the algorithm to figure out the number of clusters by itself, you can use <strong>Density Based Clustering Algorithms</strong> like <strong>DBSCAN</strong>:</p>
<pre><code>from sklearn.cluster import DBSCAN
DBSCAN(min_samples=1).fit_predict(mat)
array([0, 1, 2, 2])
</code></pre> |
20,854,231 | Angular JS issue with string.length in templates | <p>I have an issue with AngularJS (version 1.2.6).</p>
<p>For some reason that I could not understand I cannot access the <code>length</code> property of a string variable stored in the <code>$scope</code>.</p>
<p>In the template:</p>
<pre><code>String '{{myObject.someVariable}}' has length '{{myObject.someVariable.length}}'.
</code></pre>
<p>In the controller: </p>
<pre><code>$scope.myObject = {} ;
//asynchronuous loading of myObject
SomeService.loadObject(function(result)){
$scope.myObject = result ;
console.log("Content: '%s', length:'%i'",$scope.myObject.someVariable,$scope.myObject.someVariable.length);
$scope.$apply();
});
</code></pre>
<p>The result is : </p>
<pre><code>String 'aaaa' has length ''.
</code></pre>
<p>In the console I correctly see <code>Content:'aaaa', length:'4'</code> </p>
<p>This is ennoying because I display (or not) some parts of the template depending on the string size.</p>
<p><em>Update</em></p>
<p><code>$scope.myObject.someVariable</code> is a string. I added a breakpoint in the callback function with two watches : </p>
<ul>
<li><code>$scope.myObject.someVariable</code> : "aaaa"</li>
<li><code>typeof($scope.myObject.someVariable)</code> : "string"</li>
</ul> | 20,854,303 | 2 | 0 | null | 2013-12-31 08:26:12.507 UTC | 2 | 2013-12-31 08:45:12.377 UTC | 2013-12-31 08:45:12.377 UTC | null | 766,848 | null | 766,848 | null | 1 | 14 | javascript|angularjs | 44,123 | <p>Is <code>someVariable</code> a string? If not, you might have to cast it to a string before accessing the length property. Any easy way is to concatenate it with an empty string:</p>
<pre><code>{{(myObject.someVariable + '').length}}
</code></pre> |
38,567,796 | How to determine if asp.net core has been installed on a windows server | <p>I'm setting up various windows servers to host asp.net core apps, and I need to be able to determine if they have the asp.net hosting bundle installed.</p>
<p><a href="https://docs.asp.net/en/latest/publishing/iis.html#install-the-net-core-windows-server-hosting-bundle" rel="noreferrer">https://docs.asp.net/en/latest/publishing/iis.html#install-the-net-core-windows-server-hosting-bundle</a> says:</p>
<blockquote>
<p>"Install the .NET Core Windows Server Hosting bundle on the server.
The bundle will install the .NET Core Runtime, .NET Core Library, and
the ASP.NET Core Module. The module creates the reverse-proxy between
IIS and the Kestrel server."</p>
</blockquote>
<p>I'm setting up a deployment, and I need to make sure my server is configured so I can run asp.net core apps.</p>
<p>I'm looking, basically, for a registry key or some other way to tell me if I should run the installer setup. (something like the way we'd tell if older versions of the framework are installed, like
<code>https://support.microsoft.com/en-us/kb/318785</code>
does for earlier versions)</p> | 43,357,798 | 7 | 0 | null | 2016-07-25 12:28:03.38 UTC | 6 | 2020-09-10 20:40:59.177 UTC | 2016-07-25 15:09:10.973 UTC | null | 81,377 | null | 81,377 | null | 1 | 35 | asp.net-core|.net-core | 48,999 | <p>You can use powershell to check if the hosting module is registered with IIS</p>
<p>In the local powershell session</p>
<pre><code>Import-module WebAdministration
$vm_dotnet_core_hosting_module = Get-WebGlobalModule | where-object { $_.name.ToLower() -eq "aspnetcoremodule" }
if (!$vm_dotnet_core_hosting_module)
{
throw ".Net core hosting module is not installed"
}
</code></pre>
<p>If you want to do in the remote session replace first 2 lines with</p>
<pre><code>Invoke-Command -Session $Session {Import-module WebAdministration}
$vm_dotnet_core_hosting_module = Invoke-Command -Session $Session {Get-WebGlobalModule | where-object { $_.name.ToLower() -eq "aspnetcoremodule" }}
</code></pre> |
38,790,154 | Keyboard shortcut to convert selection to uppercase (or lowercase) in the atom editor | <p>What is the keyboard shortcut to convert the currently selected text to uppercase (or lowercase) in the Atom editor?</p> | 38,790,155 | 2 | 0 | null | 2016-08-05 13:11:24.16 UTC | 21 | 2020-10-06 03:31:24.83 UTC | 2017-08-01 08:42:01.783 UTC | null | 203,797 | null | 203,797 | null | 1 | 111 | atom-editor | 55,524 | <p>On Windows and Linux:</p>
<ul>
<li><kbd>Ctrl</kbd> + <kbd>K</kbd> then <kbd>Ctrl</kbd> + <kbd>U</kbd> for uppercase</li>
<li><kbd>Ctrl</kbd> + <kbd>K</kbd> then <kbd>Ctrl</kbd> + <kbd>L</kbd> for lowercase</li>
</ul>
<p>On Mac:</p>
<ul>
<li><kbd>Cmd</kbd> + <kbd>K</kbd> then <kbd>Cmd</kbd> + <kbd>U</kbd> for uppercase</li>
<li><kbd>Cmd</kbd> + <kbd>K</kbd> then <kbd>Cmd</kbd> + <kbd>L</kbd> for lowercase</li>
</ul> |
50,161,551 | Set python version when creating virtualenv using pipenv | <p>Using a Raspberry Pi using Debian 4.14.34-v7+, I am trying to get <code>pipenv</code> set up with Python 3.6.5 as the default version of Python. I first install Python 3.6 by compiling it on the Pi (hours...). After making a 'robot' directory, I then install <code>pipenv</code> with <code>sudo pip3 install pipenv</code> and <code>pipenv install --three</code>.</p>
<p>Then I start the shell and open up Python, getting Python 3.5.3…</p>
<pre class="lang-none prettyprint-override"><code>pi@raspberrypi:~/robot $ pipenv shell
Spawning environment shell (/bin/bash). Use 'exit' to leave.
. /home/pi/.local/share/virtualenvs/robot-XZ3Md9g0/bin/activate
pi@raspberrypi:~/robot $ . /home/pi/.local/share/virtualenvs/robot-XZ3Md9g0/bin/activate
(robot-XZ3Md9g0) pi@raspberrypi:~/robot $ python
Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170124] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
</code></pre>
<p>I then change the virtualenv by <code>pipenv --python 3.6</code>, but after it correctly (apparently) installs, I immediately get the warning that pipenv still expects Python 3.5…</p>
<pre class="lang-none prettyprint-override"><code>(robot-XZ3Md9g0) pi@raspberrypi:~/robot $ pipenv --python 3.6
Virtualenv already exists!
Remove existing virtualenv? [Y/n]: y
Removing existing virtualenv…
Creating a virtualenv for this project…
Using /usr/local/bin/python3.6m (3.6.5) to create virtualenv…
⠋Running virtualenv with interpreter /usr/local/bin/python3.6m
Using base prefix '/usr/local'
New python executable in /home/pi/.local/share/virtualenvs/robot-XZ3Md9g0/bin/python3.6m
Also creating executable in /home/pi/.local/share/virtualenvs/robot-XZ3Md9g0/bin/python
Installing setuptools, pip, wheel...done.
Virtualenv location: /home/pi/.local/share/virtualenvs/robot-XZ3Md9g0
Warning: Your Pipfile requires python_version 3.5, but you are using 3.6.5 (/home/pi/.local/share/v/r/bin/python).
$ pipenv check will surely fail.
(robot-XZ3Md9g0) pi@raspberrypi:~/robot $ python
Python 3.6.5 (default, May 3 2018, 11:25:17)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>How do I set up <code>pipenv</code> to look for Python 3.6, when I first create the virtualenv? I can manually go in and edit the Pipfile, but that seems to be defeating the purpose of having <code>pipenv</code> take care of things for me.</p> | 50,163,474 | 5 | 0 | null | 2018-05-03 18:18:51.98 UTC | 16 | 2022-06-21 14:32:21.877 UTC | 2020-05-06 17:28:03.127 UTC | null | 241,211 | null | 4,565,870 | null | 1 | 47 | python-3.x|pipenv | 98,980 | <p>"Edit the Pipfile" is the right way to go if you want to change the Python version of an existing environment.</p>
<p>If you want to create a <em>new</em> environment using Python 3.6, you can run</p>
<pre><code>pipenv install --python 3.6
</code></pre>
<p>rather than</p>
<pre><code>pipenv install --three
</code></pre>
<p>and that should do the trick.</p>
<p>Just be certain to delete the old Pipfile(s) if you create the new environment or else the commands will fail.</p> |
44,793,523 | How to edit all lines in Visual Studio Code | <p>I have a list of data to which I need to put a <code>'</code> symbol at the start of the line and at the end of the line. So the original data looks like this:</p>
<pre><code>abcde
cdeab
deabc
eabcd
</code></pre>
<p>And I want all of the lines to look like this:</p>
<pre><code>'abcde'
'cdeab'
'deabc'
'eabcd'
</code></pre>
<p>In my real data, I would have 10,000 of lines. So if I can do something like <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>A</kbd> to select the entire document and then have some magic shortcut to change from selecting all lines to editing all lines that would be perfect!</p> | 44,793,837 | 8 | 0 | null | 2017-06-28 04:12:20.453 UTC | 22 | 2021-06-23 16:08:44.27 UTC | 2020-03-20 16:10:29.577 UTC | null | 996,081 | null | 4,989,544 | null | 1 | 44 | visual-studio-code | 43,116 | <p>You could edit and replace with a regex:</p>
<p>Find (<kbd>Ctrl</kbd>+<kbd>F</kbd>):</p>
<pre><code>^(.+)$
</code></pre>
<p>Replace:</p>
<pre><code>'$1'
</code></pre>
<p>This regex finds any content on a line and wraps it inside quotes. The <code>$1</code> refers to whatever is matched inside the parentheses in the regex. In this case, it's "one or more characters" i.e. everything on the line. Be sure to tick the regex icon.</p>
<p><a href="https://i.stack.imgur.com/kXJrl.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/kXJrl.gif" alt="Video demonstration of the replacement" /></a></p>
<p>If every line may or may not have a space before the content, and you want every line to have a space, try this:</p>
<p>Find:</p>
<pre><code>^ ?(.+)$
</code></pre>
<p>Replace (notice the space before the first quote):</p>
<pre><code> '$1'
</code></pre> |
26,320,525 | Prettify json data in textarea input | <p>I've searched for this particular topic and couldn't find anything similar to it. If there is please close this and give a link.</p>
<p>I'm creating a json data api simulator. I want users to be able to copy and paste a json object request into a textarea where they can also modify it before sending it to the server. </p>
<p>Problem is json obj copy and patses often results in extra spaces and is never aligned properly, even with the pre tag. I also want a good color scheme applied to keys and values.</p>
<p>I've seen plugins, other questions and snippets of code, but they don't apply to textareas where the text is editable. Is there to keep it styled while in edit mode without it showing all the html tags that styled it? I want to be able to write it from scratch with javascript or jquery.</p> | 26,324,037 | 6 | 0 | null | 2014-10-12 00:07:12.933 UTC | 15 | 2022-03-22 15:26:05.5 UTC | 2018-05-02 09:09:54.993 UTC | null | 4,281,779 | null | 1,881,088 | null | 1 | 76 | javascript|jquery|html|css|json | 119,885 | <p>The syntax highlighting is tough but check out this <a href="http://jsfiddle.net/psasik/x3hcdq97/1/">fiddle for pretty printing a json object</a> entered in a text area. Do note that the JSON has to be valid for this to work. (Use the dev console to catch errors.) Check <a href="http://jsonlint.com/">jsLint</a> for valid json.</p>
<p>The HTML:</p>
<pre><code><textarea id="myTextArea" cols=50 rows=10></textarea>
<button onclick="prettyPrint()">Pretty Print</button>
</code></pre>
<p>The js:</p>
<pre><code>function prettyPrint() {
var ugly = document.getElementById('myTextArea').value;
var obj = JSON.parse(ugly);
var pretty = JSON.stringify(obj, undefined, 4);
document.getElementById('myTextArea').value = pretty;
}
</code></pre>
<p>First try simple input like: {"a":"hello","b":123}</p>
<p>Simple pretty printing of JSON can be done rather easily. Try this js code: (<a href="http://jsfiddle.net/psasik/5f9xkywg/">jsFiddle here</a>)</p>
<pre><code>// arbitrary js object:
var myJsObj = {a:'foo', 'b':'bar', c:[false,2,null, 'null']};
// using JSON.stringify pretty print capability:
var str = JSON.stringify(myJsObj, undefined, 4);
// display pretty printed object in text area:
document.getElementById('myTextArea').innerHTML = str;
</code></pre>
<p>For this HTML:</p>
<pre><code><textarea id="myTextArea" cols=50 rows=25></textarea>
</code></pre>
<p>And check out <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify documentation</a>.</p> |
28,384,680 | Scikit-Learn's Pipeline: A sparse matrix was passed, but dense data is required | <p>I'm finding it difficult to understand how to fix a Pipeline I created (read: largely pasted from a tutorial). It's python 3.4.2:</p>
<pre><code>df = pd.DataFrame
df = DataFrame.from_records(train)
test = [blah1, blah2, blah3]
pipeline = Pipeline([('vectorizer', CountVectorizer()), ('classifier', RandomForestClassifier())])
pipeline.fit(numpy.asarray(df[0]), numpy.asarray(df[1]))
predicted = pipeline.predict(test)
</code></pre>
<p>When I run it, I get:</p>
<pre><code>TypeError: A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.
</code></pre>
<p>This is for the line <code>pipeline.fit(numpy.asarray(df[0]), numpy.asarray(df[1]))</code>.</p>
<p>I've experimented a lot with solutions through numpy, scipy, and so forth, but I still don't know how to fix it. And yes, similar questions have come up before, but not inside a pipeline.
Where is it that I have to apply <code>toarray</code> or <code>todense</code>?</p> | 28,384,887 | 5 | 0 | null | 2015-02-07 16:43:17.853 UTC | 20 | 2021-04-21 10:03:00.78 UTC | null | null | null | null | 4,540,977 | null | 1 | 48 | python|numpy|pandas|scikit-learn | 38,738 | <p>Unfortunately those two are incompatible. A <code>CountVectorizer</code> produces a sparse matrix and the RandomForestClassifier requires a dense matrix. It is possible to convert using <code>X.todense()</code>. Doing this will substantially increase your memory footprint.</p>
<p>Below is sample code to do this based on <a href="http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of-pipelines.html" rel="noreferrer">http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of-pipelines.html</a> which allows you to call <code>.todense()</code> in a pipeline stage.</p>
<pre><code>class DenseTransformer(TransformerMixin):
def fit(self, X, y=None, **fit_params):
return self
def transform(self, X, y=None, **fit_params):
return X.todense()
</code></pre>
<p>Once you have your <code>DenseTransformer</code>, you are able to add it as a pipeline step.</p>
<pre><code>pipeline = Pipeline([
('vectorizer', CountVectorizer()),
('to_dense', DenseTransformer()),
('classifier', RandomForestClassifier())
])
</code></pre>
<p>Another option would be to use a classifier meant for sparse data like <code>LinearSVC</code>. </p>
<pre><code>from sklearn.svm import LinearSVC
pipeline = Pipeline([('vectorizer', CountVectorizer()), ('classifier', LinearSVC())])
</code></pre> |
22,711,087 | Flask - ImportError: No module named app | <p>First I created <code>__init__.py</code></p>
<pre><code>from flask import Flask
app = Flask(__name__)
</code></pre>
<p>Then in a separate file, in the same directory, <code>run.py</code></p>
<pre><code>from app import app
app.run(
debug = True
)
</code></pre>
<p>When I try to run <code>run.py</code>, I get the error</p>
<pre><code>Traceback (most recent call last):
File "run.py", line 1, in <module>
from app import app
ImportError: No module named app
</code></pre> | 22,711,701 | 9 | 0 | null | 2014-03-28 11:05:31.887 UTC | 11 | 2022-06-21 01:37:26.937 UTC | 2014-03-28 14:32:20.547 UTC | null | 1,572,562 | null | 1,661,745 | null | 1 | 54 | python|python-import | 157,239 | <p><code>__init__.py</code> is imported using a directory. if you want to import it as <code>app</code> you should put <code>__init__.py</code> file in directory named <code>app</code> </p>
<p>a better option is just to rename <code>__init__.py</code> to <code>app.py</code></p> |
39,370,879 | extract hour from timestamp with python | <p>I have a dataframe df_energy2</p>
<pre><code>df_energy2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29974 entries, 0 to 29973
Data columns (total 4 columns):
TIMESTAMP 29974 non-null datetime64[ns]
P_ACT_KW 29974 non-null int64
PERIODE_TARIF 29974 non-null object
P_SOUSCR 29974 non-null int64
dtypes: datetime64[ns](1), int64(2), object(1)
memory usage: 936.8+ KB
</code></pre>
<p>with this structure :</p>
<pre><code>df_energy2.head()
TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR
2016-01-01 00:00:00 116 HC 250
2016-01-01 00:10:00 121 HC 250
</code></pre>
<p>Is there any python fucntion which can extract hour from <code>TIMESTAMP</code>?</p>
<p>Kind regards</p> | 39,370,905 | 2 | 0 | null | 2016-09-07 13:12:21.51 UTC | 1 | 2016-09-07 13:44:15.6 UTC | 2016-09-07 13:15:17.24 UTC | null | 2,901,002 | null | 2,278,337 | null | 1 | 10 | python|datetime|pandas|extract|hour | 44,546 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.hour.html" rel="noreferrer"><code>dt.hour</code></a>:</p>
<pre><code>print (df.TIMESTAMP.dt.hour)
0 0
1 0
Name: TIMESTAMP, dtype: int64
df['hours'] = df.TIMESTAMP.dt.hour
print (df)
TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR hours
0 2016-01-01 00:00:00 116 HC 250 0
1 2016-01-01 00:10:00 121 HC 250 0
</code></pre> |
38,966,105 | Jenkins Setup Wizard Blank Page | <p>I have just installed Jenkins on my RHEL 6.0 server via npm:</p>
<pre><code>npm -ivh jenkins-2.7.2-1.1.noarch.rpm
</code></pre>
<p>I have also configured my port to be 9917 to avoid clashing with my Tomcat server, allowing me to access the Jenkins page at <code>ipaddress:9917</code>. After entering the initial admin password at the <strong>Unlock Jenkins</strong> page, I am presented with a blank page, with the header "SetupWizard [Jenkins]".</p>
<p>Anyone knows why am I getting a blank page, and how do I solve it?</p> | 38,968,807 | 14 | 0 | null | 2016-08-16 03:15:48.87 UTC | 4 | 2020-02-07 11:11:06.65 UTC | 2019-02-13 12:47:07.67 UTC | null | 5,277,820 | null | 6,488,062 | null | 1 | 37 | jenkins|jenkins-plugins | 25,465 | <p>I found out that after I opened the port 9917 in my firewall,the blank pages error stopped and I can continue with the setup just fine.</p> |
20,939,089 | no operator "<<" matches these operands | <p>No idea what's going on. I looked at other posts that are similar to this issue but no solution helped so far. Here's the code with comments by the parts giving errors. At one point it says that != doesn't work and in the rest of the code it's saying that << isn't working.</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
//Hangman
int main()
{
//setup
vector<string> words;
words.push_back("GUITAR");
words.push_back("VIRGINIA");
words.push_back("LAPTOP");
words.push_back("WIFEY");
words.push_back("IPHONE");
srand(static_cast<unsigned int>(time(0))); //randomly select a word
random_shuffle(words.begin(), words.end());
const string THE_WORD = words[0];
const int MAX_WRONG = 8; //initialize wrong guesses
int wrong = 0;
string soFar(THE_WORD.size(), '-'); //initalize the word so far with dashes
string used = " "; //initalize letters used
cout << "Welcome to Hangman. Good luck!/n";
//game loop
//continues until a player guesses the word or gets too many wrong guesses
while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) //ERROR on the "!="
{
cout << "\n\nYou have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
cout << "\nYou've used the following letters:\n" << used << endl; //ERROR on "<<" between the string and used
cout << "\nSo far, the word is:\n" << soFar << endl; //ERROR on "<<" between the string and soFar
//recieve the player's guess
char guess;
cout << "\n\nEnter your guess: ";
cin >> guess;
guess = toupper(guess); //makes the guess uppercase since the secret word is uppercase
while (used.find(guess) != string::npos)
{
cout << "\nYou've already guessed " << guess << endl;
cout << "Enter your guess: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
if (THE_WORD.find(guess) != string::npos)
{
cout << "That's right! " << guess << " is in the word.\n";
//updated soFar to include newly guessed letter
for (int i=0; i < THE_WORD.length(); ++i)
{
if (THE_WORD[i] == guess)
{
soFar[i] = guess;
}
}
}
else
{
cout << "Sorry, " << guess << " isn't in the word.\n";
++wrong;
}
}
//shut down
if (wrong == MAX_WRONG)
{
cout << "\nYou've been hanged!";
}
else
{
cout << "\nYou guessed it!";
}
cout << "\nThe word was " << THE_WORD << endl; //ERROR on "<<" between the string and THE_WORD
int pause;
cin >> pause; //this is here just so my compiler will stay open so I can see what's going on
return 0;
}
</code></pre> | 20,939,121 | 3 | 0 | null | 2014-01-05 20:58:37.96 UTC | 6 | 2014-01-11 22:24:29.7 UTC | 2014-01-11 22:24:29.7 UTC | null | 923,854 | null | 1,146,984 | null | 1 | 26 | c++ | 127,516 | <p>If you want to use <code>std::string</code> reliably, you must <code>#include <string></code>.</p> |
47,812,526 | PySpark - Sum a column in dataframe and return results as int | <p>I have a pyspark dataframe with a column of numbers. I need to sum that column and then have the result return as an int in a python variable. </p>
<pre><code>df = spark.createDataFrame([("A", 20), ("B", 30), ("D", 80)],["Letter", "Number"])
</code></pre>
<p>I do the following to sum the column. </p>
<pre><code>df.groupBy().sum()
</code></pre>
<p>But I get a dataframe back. </p>
<pre><code>+-----------+
|sum(Number)|
+-----------+
| 130|
+-----------+
</code></pre>
<p>I would 130 returned as an int stored in a variable to be used else where in the program. </p>
<pre><code>result = 130
</code></pre> | 51,855,775 | 9 | 0 | null | 2017-12-14 11:43:05.77 UTC | 16 | 2021-10-06 23:15:36.76 UTC | null | null | null | null | 2,402,501 | null | 1 | 53 | python|dataframe|sum|pyspark | 147,315 | <p>The simplest way really : </p>
<pre><code>df.groupBy().sum().collect()
</code></pre>
<p>But it is very slow operation: <a href="https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/best_practices/prefer_reducebykey_over_groupbykey.html" rel="noreferrer">Avoid groupByKey</a>, you should use RDD and reduceByKey: </p>
<pre><code>df.rdd.map(lambda x: (1,x[1])).reduceByKey(lambda x,y: x + y).collect()[0][1]
</code></pre>
<p>I tried on a bigger dataset and i measured the processing time: </p>
<p>RDD and ReduceByKey : <strong>2.23 s</strong></p>
<p>GroupByKey: 30.5 s</p> |
5,728,164 | when to use CABasicAnimation and CAKeyFrameAnimation and CGAffineTransform? | <p>when to use CABasicAnimation and CAKeyFrameAnimation and CGAffineTransform?</p> | 5,728,249 | 1 | 0 | null | 2011-04-20 09:26:43.407 UTC | 9 | 2011-12-26 09:06:23.013 UTC | 2011-04-20 16:44:59.737 UTC | null | 603,977 | null | 189,006 | null | 1 | 8 | cgaffinetransform|cakeyframeanimation|cabasicanimation | 2,673 | <p><strong>CABasicAnimation</strong>
: provides basic, single-keyframe animation capabilities for a layer property.</p>
<p><strong>CAKeyFrameAnimation</strong>:CAKeyframeAnimation provides generic keyframe animation capabilities for a layer property in the render tree. </p>
<p><strong>CGAffineTransform:</strong>
The CGAffineTransform data structure represents a matrix used for affine transformations. A transformation specifies how points in one coordinate system map to points in another coordinate system. An affine transformation is a special type of mapping that preserves parallel lines in a path but does not necessarily preserve lengths or angles. Scaling, rotation, and translation are the most commonly used manipulations supported by affine transforms, but skewing is also possible.</p>
<p>For more read <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreAnimation_guide/Articles/AnimatingLayers.html" rel="noreferrer">Core Animation Programming Guide</a></p> |
24,718,557 | Get the description of a status code in Python Requests | <p>I would like to be able to enter a server response code and have Requests tell me what the code means. For example, code 200 --> ok</p>
<p>I found a link to the <a href="https://github.com/kennethreitz/requests/blob/master/requests/status_codes.py" rel="noreferrer">source code</a> which shows the dictionary structure of the codes and descriptions. I see that Requests will return a response code for a given description:</p>
<pre><code>print requests.codes.processing # returns 102
print requests.codes.ok # returns 200
print requests.codes.not_found # returns 404
</code></pre>
<p>But not the other way around:</p>
<pre><code>print requests.codes[200] # returns None
print requests.codes.viewkeys() # returns dict_keys([])
print requests.codes.keys() # returns []
</code></pre>
<p>I thought this would be a routine task, but cannot seem to find an answer to this in online searching, or in the <a href="http://docs.python-requests.org/en/latest/user/quickstart/" rel="noreferrer">documentation</a>.</p> | 24,718,791 | 4 | 0 | null | 2014-07-13 00:42:05.237 UTC | 11 | 2021-02-05 14:26:14.323 UTC | 2014-12-26 18:51:46.22 UTC | null | 771,848 | null | 2,683,104 | null | 1 | 43 | python|http|python-requests | 32,799 | <p>One possibility:</p>
<pre><code>>>> import requests
>>> requests.status_codes._codes[200]
('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '\xe2\x9c\x93')
</code></pre>
<p>The first value in the tuple is used as the conventional code key.</p> |
53,118,316 | angular 6 or 7: How to import RequestOptions and ResponseContentType in '@angular/common/http' | <p>I have migrated angular 4 code to angular 6 and I want to know how to import below code in angular 6 or 7?</p>
<pre><code>import { RequestOptions, ResponseContentType } from '@angular/common/http';
</code></pre> | 53,118,376 | 1 | 0 | null | 2018-11-02 12:06:34.437 UTC | 4 | 2019-07-11 15:28:28.567 UTC | 2019-07-11 15:28:28.567 UTC | null | 8,134,164 | null | 7,539,550 | null | 1 | 12 | angular|angular6|angular7 | 39,264 | <p>Pass this way ... </p>
<pre><code>import { HttpClient, HttpHeaders } from '@angular/common/http';
let headers = new HttpHeaders({
'Content-Type': 'application/json'
});
let options = {
headers: headers
}
this.http.post(URL, param, options)
.subscribe(data => {
console.log(data);
});
// For pass blob in API
return this.http.get(url, { headers: new HttpHeaders({
'Authorization': '{data}',
'Content-Type': 'application/json',
}), responseType: 'blob'}).pipe (
tap (
// Log the result or error
data => console.log('You received data'),
error => console.log(error)
)
);
</code></pre> |
35,400,674 | Find Neo4j nodes where the property is not set | <p>Using Cypher, how can I find a node where a property doesn't exist?</p>
<p>For example, I have two nodes:</p>
<pre><code>A = {foo: true, name: 'A'}, B = { name: 'B'}
</code></pre>
<p>Now I'd like to find B, selecting it on the basis of not having the <code>foo</code> property set. How can I do this?</p> | 35,402,908 | 3 | 0 | null | 2016-02-15 02:36:24.817 UTC | null | 2022-04-30 04:02:08.037 UTC | 2019-07-18 04:26:55.527 UTC | null | 3,668,967 | null | 68,672 | null | 1 | 32 | neo4j|cypher | 23,400 | <p>As Michael Hunger mentioned</p>
<pre><code>MATCH (n) WHERE NOT EXISTS(n.foo) RETURN n
</code></pre>
<p>On older versions of Neo4j you can use HAS:</p>
<pre><code># Causes error with later versions of Neo4j
MATCH (n) WHERE NOT HAS(n.foo) RETURN n
</code></pre> |
28,759,454 | Enabling Location mode High Accuracy or Battery saving, programmatically, without user needing to visit Settings | <p><strong><em>Why i ask this:</em></strong>(also the reason for trying it in an app) </p>
<p><strong>It happens</strong> when we use <strong>Google Maps in Lollipop</strong>. <em>Even if the Location is disabled, it is turned on, in high accuracy mode after user's input from the Maps app, without having to visit Settings.</em> </p>
<p>A similar functionality can be achieved for enabling Bluetooth, where the action is initiated in my app; user needs to make a choice but user is not redirected to Settings, using: </p>
<p><code>startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));</code> </p>
<p>which could be found on <a href="http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#ACTION_REQUEST_ENABLE" rel="noreferrer">BluetoothAdapter</a>, now we know there is no LocationAdapter, so i looked around <a href="https://developer.android.com/reference/com/google/android/gms/location/LocationServices.html" rel="noreferrer">gms->LocationServices</a>, basically almost everything under <a href="https://developer.android.com/reference/com/google/android/gms/location/package-summary.html" rel="noreferrer">Location API references</a>, <a href="https://developer.android.com/reference/android/location/LocationManager.html" rel="noreferrer">android.location.LocationManager</a> but doesn't seem anything like <code>ACTION_REQUEST_ENABLE</code> is available as yet. </p>
<p>Hope there is some other method for the same, and more people have tried it.</p>
<p>Please note:<br>
<code>context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));</code> does not work like that. </p> | 29,002,760 | 3 | 0 | null | 2015-02-27 07:11:09.56 UTC | 22 | 2019-01-29 04:22:16.373 UTC | 2017-04-07 06:34:49.67 UTC | null | 2,450,263 | null | 2,450,263 | null | 1 | 21 | android|google-play-services|android-5.0-lollipop|android-location|android-settings | 34,057 | <p><strong><em>UPDATE 3</em></strong>: </p>
<p><strong><em><a href="https://developer.android.com/training/location/change-location-settings#prompt" rel="nofollow noreferrer">Prompt the user to change location settings</a></em></strong>
as @patrickandroid, mentioned in comments, the link from second update is broken</p>
<p><strong><em><a href="https://github.com/googlesamples/android-play-location" rel="nofollow noreferrer">GoogleSamples; android Location and options - for code reference.</a></em></strong></p>
<p><strong><em>UPDATE 2</em></strong>: </p>
<p><strong><em><a href="https://github.com/googlesamples/android-play-location/tree/master/LocationSettings" rel="nofollow noreferrer">GoogleSamples; - for code reference.</a></em></strong></p>
<blockquote>
<p>This sample builds on the LocationUpdates sample included in this
repo, and allows the user to update the device's location settings
using a location dialog.</p>
<p>Uses the SettingsApi to ensure that the device's system settings are
properly configured for the app's location needs.</p>
</blockquote>
<hr>
<p><strong><em>UPDATE 1</em></strong>: </p>
<p><strong><a href="https://developer.android.com/google/play-services/index.html" rel="nofollow noreferrer">Google Play services, Version 7.0 (March 2015) released...</a></strong> </p>
<blockquote>
<p><strong>Location settings</strong> - While the FusedLocationProviderApi combines multiple sensors to give you the optimal location, the accuracy of the
location your app receives still depends greatly on the settings
enabled on the device (GPS, wifi, airplane mode, and others). Using
the new SettingsApi class, you can bring up a Location Settings dialog
which displays a one-touch control for users to change their settings
without leaving your app.</p>
</blockquote>
<p>Using the <strong><a href="https://developer.android.com/reference/com/google/android/gms/location/SettingsApi.html" rel="nofollow noreferrer">public interface SettingsApi</a></strong> </p>
<blockquote>
<ul>
<li>Determine if the relevant system settings are enabled on the device to carry out the desired location request.</li>
<li>Optionally, invoke a dialog that allows the user to enable the necessary location settings with a single tap.</li>
</ul>
</blockquote>
<hr>
<hr>
<p>Leaving the previous part for reference:<br>
<strong><em>Update/Answer</em></strong><br>
For everybody looking for this answer, <strong>Google Play Services 7.0</strong><br>
It Adds APIs For Detecting Places And Connecting To Nearby Devices, Improves On Mobile Ads, Fitness Data, Location Settings, And More </p>
<blockquote>
<p>In Google Play services 7.0, we’re introducing a standard mechanism to
check that the necessary location settings are enabled for a given
LocationRequest to succeed. If there are possible improvements, you
can display a one touch control for the user to change their settings
without leaving your app.</p>
<p><img src="https://i.stack.imgur.com/81TfP.png" alt="exactly this"></p>
<p>This API provides a great opportunity to make for a much better user
experience, particularly if location information is critical to the
user experience of your app such as was the case with Google Maps when
they integrated the Location Settings dialog and saw a dramatic
increase in the number of users in a good location state.</p>
</blockquote>
<p><strong>Source:</strong> <a href="http://android-developers.blogspot.in/2015/03/google-play-services-70-places-everyone.html" rel="nofollow noreferrer">Android developers blog: Google Play services 7.0 - Places Everyone!</a></p>
<blockquote>
<p><strong>SDK Coming Soon!</strong><br>
We will be rolling out Google Play services 7.0 over
the next few days. Expect an update to this blog post, published
documentation, and the availability of the SDK once the rollout is
completed.</p>
</blockquote>
<p>will update the programmatic l-o-c after implementation </p> |
23,925,968 | Tomcat vs Vert.x | <p>For the past few days I have been reading Vert.x documents. I know that Vert.x is polyglot, single threaded, non-blocking IO, modular architecture, high scalability. </p>
<p>Is there any other major differences between tomcat and Vert.x?</p>
<p>Also when we should use tomcat and when to use Vert.x?</p> | 24,441,534 | 2 | 0 | null | 2014-05-29 05:00:00.667 UTC | 9 | 2020-05-30 16:59:46.883 UTC | 2020-05-07 20:06:17.337 UTC | null | 452,775 | null | 1,280,039 | null | 1 | 29 | java|tomcat|webserver|vert.x | 12,555 | <p>Tomcat is a servlet container, so it offers you a platform that helps you to develop and deploy HTTP based applications like web sites or web services.</p>
<p>Vert.x instead helps you to develop and deploy any kind of asynchronous applications. It's true that modern versions of Tomcat support asynchronous servlets, but Vert.x comes with a far larger amount of user friendly asynchronous APIs plus other goodness:</p>
<ul>
<li>Complete Filesystem asynchronous API</li>
<li>TCP (server and client)</li>
<li>UDP (server and client)</li>
<li>HTTP(S) (server and client)</li>
<li>Shared data service (share objects between polyglot modules)</li>
<li>HA and Clustering</li>
<li>Cluster-wide messaging (event loop)</li>
<li>Event bus bridge (the extension of the event loop to browsers via SockJS)</li>
<li>A growing ecosystem of Vert.x modules</li>
<li>Possibility to embed Vert.x in legacy code</li>
<li>Leveraging the existing rich and solid ecosystem of Java libraries (Vert.x runs on the JVM, unlike Node.js)</li>
</ul>
<p>Personally I think learning Vert.x is very useful. At work I reused the same knowledge with great success to realise three very different products: a zero-copy ultrafast Redis proxy, a JPA-backed REST API, and a reactive single-page web application.</p>
<p>Have a look at the <a href="https://github.com/vert-x/vertx-examples/tree/master/src/raw" rel="noreferrer">example code</a>, it's pretty straight forward and the boilerplate is close to zero.</p>
<p>One more thing: where did you read Vert.x is single threaded? It's not true! Vert.x has a very <a href="http://vertx.io/docs/vertx-core/java/#_reactor_and_multi_reactor" rel="noreferrer">neat concurrency model</a> that makes sure all the cores are equally used (again, unlike Node.js). </p>
<p>Enjoy!</p> |
378,281 | Lat/Lon + Distance + Heading --> Lat/Lon | <p>So: I have the following function, adapted from a formula found online, which takes two lat/lon coordinates and finds the distance between them in miles (along a spherical Earth):</p>
<pre><code>public static double distance (double lat1, double lon1, double lat2, double lon2) {
double theta = toRadians(lon1-lon2);
lat1 = toRadians(lat1);
lon1 = toRadians(lon1);
lat2 = toRadians(lat2);
lon2 = toRadians(lon2);
double dist = sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(theta);
dist = toDegrees(acos(dist)) * 60 * 1.1515 * 1.609344 * 1000;
return dist;
}
</code></pre>
<p>As far as I can tell this works just fine.</p>
<p>What I need is a second function which, using the exact same model of the Earth's geometry, takes a single lat/lon pair [A], a heading, and a distance, and outputs a new lat/lon pair [B] such that if you started at point [A], and traveled the given distance at the given heading, you'd wind up at point [B].</p>
<p>This is where the fact that my geometry skills have left me entirely comes into play :)</p>
<p>Any help would be much appreciated!</p>
<p>Thanks,
-Dan</p> | 378,315 | 1 | 2 | null | 2008-12-18 15:53:55.283 UTC | 15 | 2018-03-05 04:49:51.227 UTC | null | null | null | null | 47,450 | null | 1 | 17 | function|geometry|geospatial | 13,699 | <p>I get most of those types of formulas from <a href="http://edwilliams.org/avform.htm" rel="nofollow noreferrer">The Aviation Formulary</a>.</p>
<p>The formula he gives is:</p>
<blockquote>
<h3>Lat/lon given radial and distance</h3>
<p>A point {lat,lon} is a distance d out on
the tc radial from point 1 if: </p>
<pre><code> lat=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc))
IF (cos(lat)=0)
lon=lon1 // endpoint a pole
ELSE
lon=mod(lon1-asin(sin(tc)*sin(d)/cos(lat))+pi,2*pi)-pi
ENDIF
</code></pre>
<p>This algorithm is limited to distances such that dlon < pi/2, i.e
those that extend around less than one
quarter of the circumference of the
earth in longitude. A completely
general, but more complicated
algorithm is necessary if greater
distances are allowed: </p>
<pre><code> lat =asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc))
dlon=atan2(sin(tc)*sin(d)*cos(lat1),cos(d)-sin(lat1)*sin(lat))
lon=mod( lon1-dlon +pi,2*pi )-pi
</code></pre>
</blockquote>
<p>Note that he's using "tc" to stand for true course (in radians clockwise from North) and the distances he gives are in radians of arc along the surface of the earth. This is explained (along with formulas to convert back and forth from nautical miles) in the first section of the Formulary. Also, check out the "Implementation Notes" and "Worked Examples" on that page.</p> |
38,650,315 | why $(window).load() is not working in jQuery? | <p>I'm learning jQuery using visual studio and testing my code in Chrome browser. This is my HTML code</p>
<pre><code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="jquery-3.1.0.js"></script>
<script type="text/javascript">
$(window).load(function () {
alert("Window Loaded");
});
</script>
</head>
<body>
</body>
</html>
</code></pre>
<p>This is my solution explorer</p>
<p><a href="https://i.stack.imgur.com/Nv3f3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Nv3f3.png" alt="Solution Explorer"></a></p>
<p>Now why my browser doesn't alert "window Loaded"?</p> | 38,650,372 | 4 | 6 | null | 2016-07-29 04:01:30.04 UTC | 8 | 2021-08-09 18:06:14.717 UTC | 2016-07-29 05:22:39.6 UTC | null | 3,329,664 | null | 5,361,646 | null | 1 | 69 | jquery | 149,548 | <p>You're using jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from <a href="https://api.jquery.com/load-event/">jQuery 3.0</a>. Instead you can use <a href="http://api.jquery.com/on">on</a> method and bind the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/Events/load">load event</a>:</p>
<pre><code> $(window).on('load', function () {
alert("Window Loaded");
});
</code></pre> |
38,532,483 | Where is /var/lib/docker on Mac/OS X | <p>I´m looking for the folder <code>/var/lib/docker</code> on my Mac after installing docker for Mac.</p>
<p>With <code>docker info</code> I get</p>
<pre><code> Containers: 5
...
Server Version: 1.12.0-rc4
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 339
Dirperm1 Supported: true
...
Name: moby
ID: LUOU:5UHI:JFNI:OQFT:BLKR:YJIC:HHE5:W4LP:YHVP:TT3V:4CB2:6TUS
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
....
</code></pre>
<p>But I don´t have a directory <code>/var/lib/docker</code> on my host.</p>
<p>I have checked <code>/Users/myuser/Library/Containers/com.docker.docker/</code> but couldn´t find anything there. Any idea where it is located?</p> | 39,287,126 | 13 | 6 | null | 2016-07-22 17:44:39.8 UTC | 72 | 2022-04-11 14:29:20.513 UTC | 2019-11-28 01:21:04.147 UTC | null | 868,975 | null | 2,425,939 | null | 1 | 199 | macos|docker|docker-for-mac | 101,936 | <p>See <a href="https://stackoverflow.com/a/37642236/2380457">this answer</a></p>
<p>When using Docker for Mac Application, it appears that the containers are stored within the VM located at:</p>
<blockquote>
<p>~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/Docker.qcow2</p>
</blockquote> |
43,767,866 | SLURM `srun` vs `sbatch` and their parameters | <p>I am trying to understand what the difference is between SLURM's <a href="https://slurm.schedmd.com/srun.html" rel="noreferrer"><code>srun</code></a> and <a href="https://slurm.schedmd.com/sbatch.html" rel="noreferrer"><code>sbatch</code></a> commands. I will be happy with a general explanation, rather than specific answers to the following questions, but here are some specific points of confusion that can be a starting point and give an idea of what I'm looking for. </p>
<p>According to the <a href="https://slurm.schedmd.com/quickstart.html" rel="noreferrer">documentation</a>, <code>srun</code> is for submitting jobs, and <code>sbatch</code> is for submitting jobs for later execution, but the practical difference is unclear to me, and their behavior seems to be the same. For example, I have a cluster with 2 nodes, each with 2 CPUs. If I execute <code>srun testjob.sh &</code> 5x in a row, it will nicely queue up the fifth job until a CPU becomes available, as will executing <code>sbatch testjob.sh</code>.</p>
<p>To make the question more concrete, I think a good place to start might be: <strong>What are some things that I can do with one that I cannot do with the other, and why?</strong></p>
<p>Many of the arguments to both commands are the same. The ones that seem the most relevant are <code>--ntasks</code>, <code>--nodes</code>, <code>--cpus-per-task</code>, <code>--ntasks-per-node</code>. <strong>How are these related to each other, and how do they differ for <code>srun</code> vs <code>sbatch</code>?</strong></p>
<p>One particular difference is that <code>srun</code> will cause an error if <code>testjob.sh</code> does not have executable permission i.e. <code>chmod +x testjob.sh</code> whereas <code>sbatch</code> will happily run it. <strong>What is happening "under the hood" that causes this to be the case?</strong></p>
<p>The documentation also mentions that <code>srun</code> is commonly used inside of <code>sbatch</code> scripts. This leads to the question: <strong>How do they interact with each other, and what is the "canonical" usecase for each them? Specifically, would I ever use <code>srun</code> by itself?</strong></p> | 43,799,481 | 2 | 0 | null | 2017-05-03 18:49:40.337 UTC | 51 | 2021-01-23 19:02:51.13 UTC | 2017-05-03 21:50:27.833 UTC | null | 2,593,878 | null | 2,593,878 | null | 1 | 143 | parallel-processing|scheduler|jobs|slurm|sbatch | 65,642 | <p>The documentation says</p>
<pre><code>srun is used to submit a job for execution in real time
</code></pre>
<p>while</p>
<pre><code>sbatch is used to submit a job script for later execution.
</code></pre>
<p>They both accept practically the same set of parameters. The main difference is that <code>srun</code> is interactive and blocking (you get the result in your terminal and you cannot write other commands until it is finished), while <code>sbatch</code> is batch processing and non-blocking (results are written to a file and you can submit other commands right away).</p>
<p>If you use <code>srun</code> in the background with the <code>&</code> sign, then you remove the 'blocking' feature of <code>srun</code>, which becomes interactive but non-blocking. It is still interactive though, meaning that the output will clutter your terminal, and the <code>srun</code> processes are linked to your terminal. If you disconnect, you will loose control over them, or they might be killed (depending on whether they use <code>stdout</code> or not basically). And they will be killed if the machine to which you connect to submit jobs is rebooted.</p>
<p>If you use <code>sbatch</code>, you submit your job and it is handled by Slurm ; you can disconnect, kill your terminal, etc. with no consequence. Your job is no longer linked to a running process.</p>
<blockquote>
<p>What are some things that I can do with one that I cannot do with the other, and why?</p>
</blockquote>
<p>A feature that is available to <code>sbatch</code> and not to <code>srun</code> is <a href="https://slurm.schedmd.com/job_array.html" rel="noreferrer">job arrays</a>. As <code>srun</code> can be used within an <code>sbatch</code> script, there is nothing that you cannot do with <code>sbatch</code>.</p>
<blockquote>
<p>How are these related to each other, and how do they differ for srun vs sbatch?</p>
</blockquote>
<p>All the parameters <code>--ntasks</code>, <code>--nodes</code>, <code>--cpus-per-task</code>, <code>--ntasks-per-node</code> have the same meaning in both commands. That is true for nearly all parameters, with the notable exception of <code>--exclusive</code>.</p>
<blockquote>
<p>What is happening "under the hood" that causes this to be the case?</p>
</blockquote>
<p><code>srun</code> immediately executes the script on the remote host, while <code>sbatch</code> copies the script in an internal storage and then uploads it on the compute node when the job starts. You can check this by modifying your submission script after it has been submitted; changes will not be taken into account (see <a href="https://stackoverflow.com/questions/32216228/after-submitting-a-m-batch-job-with-slurm-can-i-edit-my-m-file-without-changi">this</a>).</p>
<blockquote>
<p>How do they interact with each other, and what is the "canonical" use-case for each of them?</p>
</blockquote>
<p>You typically use <code>sbatch</code> to submit a job and <code>srun</code> in the submission script to create job steps as Slurm calls them. <code>srun</code> is used to launch the processes. If your program is a parallel MPI program, <code>srun</code> takes care of creating all the MPI processes. If not, <code>srun</code> will run your program as many times as specified by the <code>--ntasks</code> option. There are many use cases depending on whether your program is paralleled or not, has a long-running time or not, is composed of a single executable or not, etc. Unless otherwise specified, <code>srun</code> inherits by default the pertinent options of the <code>sbatch</code> or <code>salloc</code> which it runs under (from <a href="https://groups.google.com/forum/#!topic/slurm-devel/wKaUEOzuQq4" rel="noreferrer">here</a>).</p>
<blockquote>
<p>Specifically, would I ever use srun by itself?</p>
</blockquote>
<p>Other than for small tests, no. A common use is <code>srun --pty bash</code> to get a shell on a compute job.</p> |
34,462,065 | Crashlytics (Fabric) separate organizations for application variants (build types, product flavors) | <p><em>This is self-answered question to share my knowledge.</em></p>
<p>I have a project with multiple product flavors and I want to integrate Fabric using separate organizations for each product flavor.</p>
<p>I tried to integrate Fabric using Android Studio Fabric Plugin. It adds </p>
<pre><code><meta-data
android:name="io.fabric.ApiKey"
android:value="DEFAULT_ORGANIZATION_API_KEY" />
</code></pre>
<p>entry to <code>AndroidManifest.xml</code> of <code>main</code> source set.</p>
<p>I decided to rewrite this entry in application variant specific source sets:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application>
<meta-data
android:name="io.fabric.ApiKey"
android:value="SECOND_ORGANIZATION_API_KEY"
tools:replace="android:value" />
</application>
</manifest>
</code></pre>
<p>Then I discovered that Fabric Gradle plugin generates <code>crashlytics.properties</code> file with fabric api secret (AKA build secret) during build and I should include this file to source control. But this file is overwritten each time I build specific application variant because api secret is unique for each application.</p>
<p>How can I integrate Fabric using separate organizations for each application variant?</p> | 34,462,066 | 3 | 0 | null | 2015-12-25 10:34:40.62 UTC | 12 | 2019-01-15 01:55:39.017 UTC | 2016-03-11 13:31:03.89 UTC | null | 746,347 | null | 746,347 | null | 1 | 32 | android|gradle|crashlytics|twitter-fabric|android-productflavors | 7,096 | <p>During the build <code>fabricGenerateResources</code> task is called and it looks for a file named <code>fabric.properties</code> with following content:</p>
<pre><code>apiSecret=YOUR_BUILD_SECRET
apiKey=YOUR_API_KEY
</code></pre>
<p>So all we need is to generate <code>fabric.properties</code> file before this.</p>
<p>I found <a href="https://gist.github.com/alexsinger/2b5b1b7ae2d2fca1ffdb" rel="noreferrer">this solution</a> and slightly modified it to fully support application variants not only build types.</p>
<p>Add this code to <code>android</code> section of <code>build.gradle</code>:</p>
<pre><code>File crashlyticsProperties = new File("${project.projectDir.absolutePath}/fabric.properties")
applicationVariants.all { variant ->
variant.productFlavors.each { flavor ->
def variantSuffix = variant.name.capitalize()
def generatePropertiesTask = task("fabricGenerateProperties${variantSuffix}") << {
Properties properties = new Properties()
properties.put("apiKey", flavor.fabricApiKey)
properties.put("apiSecret", flavor.fabricApiSecret)
properties.store(new FileWriter(crashlyticsProperties), "")
}
def generateResourcesTask = project.tasks.getByName("fabricGenerateResources${variantSuffix}")
generateResourcesTask.dependsOn generatePropertiesTask
generateResourcesTask.doLast {
println "Removing fabric.properties"
crashlyticsProperties.delete()
}
}
}
</code></pre>
<p>It iterates over application variants and for each application variant creates task that generates <code>fabric.properties</code> file and task that deletes this file after Fabric Gradle plugin generates application resources.</p>
<p>All you need now is to define product flavor or build type specific <code>fabricApiKey</code> and <code>fabricApiSecret</code>:</p>
<pre><code>productFlavors {
flavor1 {
ext.fabricApiKey = "FLAVOR1_API_KEY"
ext.fabricApiSecret = "FLAVOR1_API_SECRET"
}
}
</code></pre>
<p><code>ext</code> is an <a href="https://docs.gradle.org/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html" rel="noreferrer">ExtraPropertiesExtention</a> object provided by every <a href="https://docs.gradle.org/current/dsl/org.gradle.api.plugins.ExtensionAware.html" rel="noreferrer">ExtensionAware</a> object. It allows new properties to be added to existing object. In my case <code>flavor1</code> is <code>ExtensionAware</code> object and it can be extended with new properties by using <code>ext.someProperty = "value"</code> syntax and later these properties can be used as <code>flavor.someProperty, flavor.fabricApiKey</code>.</p>
<p>Also it's better to include <code>fabric.properties</code> to <code>.gitignore</code>.</p>
<p>And do not forget to remove <code>ext.enableCrashlytics = false</code> from debug build type if you used it to disable Crashlytics during debug. Instead of this you can disable it in <code>Application.onCreate</code>:</p>
<pre><code>Fabric.with(this, new Crashlytics.Builder().core(
new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()).build());
</code></pre> |
7,586,384 | Color states with Python's matplotlib/basemap | <p>I want to generate a map of the United States and color each state in using a different shade. Is there a way to do this using Python's basemap?</p> | 29,397,692 | 1 | 0 | null | 2011-09-28 16:23:41.953 UTC | 10 | 2015-04-01 18:03:13.03 UTC | null | null | null | null | 404,792 | null | 1 | 14 | python|matplotlib|gis | 19,458 | <p>There is a nicely formated example in the Basemap repo on GitHub: <a href="https://github.com/matplotlib/basemap/blob/master/examples/fillstates.py">fillstates.py</a>. The shapefile (<a href="https://github.com/matplotlib/basemap/raw/master/examples/st99_d00.dbf">dbf</a> | <a href="https://github.com/matplotlib/basemap/raw/master/examples/st99_d00.shp">shp</a> | <a href="https://github.com/matplotlib/basemap/raw/master/examples/st99_d00.shx">shx</a>) is also included in the <a href="https://github.com/matplotlib/basemap/blob/master/examples/">examples folder</a>.</p>
<p>Here is an abbreviated version of the example:</p>
<pre class="lang-python prettyprint-override"><code>import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
# create the map
map = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('st99_d00', name='states', drawbounds=True)
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
# get Texas and draw the filled polygon
seg = map.states[state_names.index('Texas')]
poly = Polygon(seg, facecolor='red',edgecolor='red')
ax.add_patch(poly)
plt.show()
</code></pre>
<p>Resulting plot with Texas filled red:</p>
<p><img src="https://i.stack.imgur.com/ZUat5.png" alt="Resulting plot with Texas filled red"></p>
<p>Note that when we load a shapefile the shapes and attributes are stored in <code>map.states</code> and <code>map.states_info</code> respectively as lists based on the <code>name</code> parameter used in the <code>readshapefile</code> call. So to look up the shape for a specific state we had to build a corresponding list of the state names from the attributes.</p> |
22,922,891 | Vagrant ssh authentication failure | <p>The problem with ssh authentication:</p>
<pre><code>==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
default: Adapter 2: bridged
==> default: Forwarding ports...
default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Error: Connection timeout. Retrying...
default: Error: Connection timeout. Retrying...
default: Error: Connection timeout. Retrying...
default: Error: Connection timeout. Retrying...
default: Error: Authentication failure. Retrying...
default: Error: Authentication failure. Retrying...
default: Error: Authentication failure. Retrying...
default: Error: Authentication failure. Retrying...
default: Error: Authentication failure. Retrying...
</code></pre>
<p>I can <code>Ctrl+C</code> out of the authentication loop and then successfully ssh in manually.</p>
<p>I performed the following steps on the guest box:</p>
<ul>
<li><p>Enabled <code>Remote Login</code> for <code>All Users</code>.</p></li>
<li><p>Created the <code>~/.ssh</code> directory with <code>0700</code> permissions.</p></li>
<li><p>Created the <code>~/.ssh/authorized_keys</code> file with <code>0600</code> permissions.</p></li>
<li><p>Pasted <a href="https://github.com/mitchellh/vagrant/blob/master/keys/vagrant.pub" rel="noreferrer">this public key</a>
into <code>~/.ssh/authorized_keys</code></p></li>
</ul>
<p>I've also tried using a private (hostonly) network instead of the public (bridged) network, using this line in the Vagrantfile:</p>
<p><code>config.vm.network "private_network", ip: "172.16.177.7"</code></p>
<p>I get the same output (except <code>Adapter 2: hostonly</code>) but then cannot ssh in manually.</p>
<p>I also tried <code>config.vm.network "private_network", ip: "10.0.0.100"</code>.</p>
<p>I also tried setting <code>config.ssh.password</code> in the Vagrantfile. This does output <code>SSH auth method: password</code> but still doesn't authenticate.</p>
<p>And I also tried rebuilding the box and rechecking all the above.</p>
<p>It looks like <a href="https://groups.google.com/forum/#!topic/vagrant-up/HKL0FXR6QmE" rel="noreferrer">others have had success with this configuration</a>, so there must be something I'm doing wrong.</p>
<p>I <a href="https://stackoverflow.com/questions/22575261/vagrant-stuck-connection-timeout-retrying">found this thread</a> and enabled the GUI, but that doesn't help.</p> | 22,925,947 | 32 | 0 | null | 2014-04-07 20:53:35.033 UTC | 75 | 2022-08-08 13:05:03.063 UTC | 2017-05-23 10:31:29.493 UTC | null | -1 | null | 753,237 | null | 1 | 164 | ssh|vagrant|virtualbox|private-key|vagrantfile | 208,033 | <p>Make sure your first network interface is NAT. The other second network interface can be anything you want when you're building box. Don't forget the Vagrant user, as discussed in the Google thread. </p>
<p>Good luck. </p> |
24,924,002 | How to put a background image on a Bootstrap form? | <p>I'm trying to put a background image on my form (like behind the text and inputs, just like a background image of my web site), using the Bootstrap framework but the image appears at the bottom and I want it inside the "container". </p>
<p>My code is something like this:</p>
<pre><code><div class="container">
<div class="thumbnail">
<form....>
<fieldset>
.
.
.
</form>
<img src="cs.jpg" class="img-responsive">
</div>
<div>
</code></pre> | 24,924,064 | 2 | 0 | null | 2014-07-24 02:07:01.507 UTC | 1 | 2022-02-03 12:56:28.467 UTC | 2014-12-28 01:26:53.56 UTC | null | 1,476,885 | null | 2,621,320 | null | 1 | 3 | html|css|twitter-bootstrap|twitter-bootstrap-3 | 79,743 | <p>Have you tried setting the background image of that container as the image? IE:</p>
<pre><code>.container {
background-image: url("cs.jpg");
}
</code></pre>
<p>Or you can do it inline:</p>
<pre><code><div class="container" style="background-image: url('cs.jpg');">
...
</div>
</code></pre> |
45,734,357 | routing with params in vuejs using router-link | <p>I am trying to build a spa using vuejs in which I have a list of users now when I click a user it should route to a new page with user details of the particular user how to params the user id in router-link</p> | 45,734,750 | 7 | 1 | null | 2017-08-17 11:50:05.423 UTC | 11 | 2022-09-15 02:55:32.153 UTC | null | null | null | null | 7,906,583 | null | 1 | 27 | vue.js | 44,874 | <p>You can pass params in router link using</p>
<pre class="lang-html prettyprint-override"><code><router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
</code></pre>
<p>Here "name" key parameter defines the name of the route and "params" key defines the parameters you need to send with that route.</p>
<p>If you need to use Route Path instead of Route name, You can use.</p>
<pre class="lang-html prettyprint-override"><code><router-link :to="{ path: 'home', params: { userId: 123 }}">Home</router-link>
</code></pre>
<p><a href="https://router.vuejs.org/api/#to" rel="nofollow noreferrer">Reference</a></p> |
2,622,804 | How to indefinitely pause a thread in Java and later resume it? | <p>Maybe this question has been asked many times before, but I never found a satisfying answer.</p>
<p><H3>The problem:</H3><br>
<BLOCKQUOTE><P>
I have to simulate a process scheduler, using the round robin strategy. I'm using threads to simulate processes and multiprogramming; everything works fine with the JVM managing the threads. But the thing is that now I want to have control of all the threads so that I can run each thread alone by a certain quantum (or time), just like real OS processes schedulers.
</P></BLOCKQUOTE></p>
<p><H3>What I'm thinking to do:</H3>
<BLOCKQUOTE>
<P>
I want have a list of all threads, as I iterate the list I want to execute each thread for their corresponding quantum, but as soon the time's up I want to pause that thread indefinitely until all threads in the list are executed and then when I reach the same thread again resume it and so on.
</P>
</BLOCKQUOTE></p>
<p><H3>The question:</H3>
<BLOCKQUOTE>
<P>
So is their a way, without using deprecated methods stop(), suspend(), or resume(), to have this control over threads?
</P>
</BLOCKQUOTE></p> | 2,622,935 | 3 | 3 | null | 2010-04-12 14:29:52.143 UTC | 9 | 2015-11-29 10:41:08.267 UTC | null | null | null | null | 314,603 | null | 1 | 20 | java|multithreading | 14,776 | <p>Who said Java is not low level enough?</p>
<p>Here is my 3 minute solution. I hope it fits your needs.</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
public class ThreadScheduler {
private List<RoundRobinProcess> threadList
= new ArrayList<RoundRobinProcess>();
public ThreadScheduler(){
for (int i = 0 ; i < 100 ; i++){
threadList.add(new RoundRobinProcess());
new Thread(threadList.get(i)).start();
}
}
private class RoundRobinProcess implements Runnable{
private final Object lock = new Object();
private volatile boolean suspend = false , stopped = false;
@Override
public void run() {
while(!stopped){
while (!suspend){
// do work
}
synchronized (lock){
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
}
public void suspend(){
suspend = true;
}
public void stop(){
suspend = true;stopped = true;
synchronized (lock){
lock.notifyAll();
}
}
public void resume(){
suspend = false;
synchronized (lock){
lock.notifyAll();
}
}
}
}
</code></pre>
<p>Please note that "do work" should not be blocking.</p> |
3,093,576 | false / FALSE — any difference? | <p>I noticed that some PHP frameworks use exclusively lowercase <code>true</code>/<code>false</code> and others upper.</p>
<p>Does it make any difference at all? I for one prefer lowercase.</p> | 3,093,581 | 3 | 2 | null | 2010-06-22 13:34:56.487 UTC | 5 | 2018-08-29 16:32:40.72 UTC | 2016-11-23 11:23:24.133 UTC | null | 107,625 | null | 276,315 | null | 1 | 38 | php | 11,525 | <p>No difference, some people consider FALSE to be a constant and thus use the old screaming caps notation.</p> |
3,162,318 | Does anyone know of a fork of iText? | <p>Now that iText has gone <a href="http://itextpdf.com/terms-of-use/index.php" rel="noreferrer">AGPL</a>, I'm assuming someone is going to take the old (2.1.7 or <a href="http://itext.svn.sourceforge.net/viewvc/itext/tags/iText_4_2_0/" rel="noreferrer">4.2.0</a>) code and fork it to keep an LGPL version going. Does anyone know of such a fork already started?</p> | 3,313,191 | 4 | 2 | null | 2010-07-01 23:11:19.437 UTC | 11 | 2019-08-07 14:15:55.077 UTC | null | null | null | null | 77,779 | null | 1 | 46 | java|pdf|itext | 10,308 | <p>I discussed some practical issues with the iText AGPL license in my blog (which is linked from my SO profile). Why not just buy IText? It is certainly an option among many commercial PDF libraries out there, although they really need to standardize their pricing against the competition.</p>
<p>The truth is I never really used iText much in the past. It always either lacked certain features, or the API was much more difficult than other (non-free) alternatives to wrap your head around, especially for minimal PDF manipulation (rather than the level of PDF manipulation required to generate a report, for example).</p>
<p>At this point the only similarly licenced PDF library I know of is ICEPdf, which is under the <a href="http://www.icepdf.org/support/license-faq.html" rel="noreferrer">MPL 1.1 license</a>, but its business model is to have a more limited version and charge for more advanced features (such as more font support).</p> |
40,590,192 | Getting an error - AttributeError: 'module' object has no attribute 'run' while running subprocess.run(["ls", "-l"]) | <p>I am running on a AIX 6.1 and using Python 2.7. Want to execute following line but getting an error.</p>
<pre><code>subprocess.run(["ls", "-l"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'run'
</code></pre> | 40,590,445 | 2 | 5 | null | 2016-11-14 13:44:58.583 UTC | 2 | 2021-03-03 20:50:06.483 UTC | 2016-11-14 13:58:44.837 UTC | null | 100,297 | null | 5,816,183 | null | 1 | 39 | python|python-2.7|subprocess|aix | 85,965 | <p>The <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run()</code> function</a> only exists in Python 3.5 and newer.</p>
<p>It is easy enough to backport however:</p>
<pre><code>def run(*popenargs, **kwargs):
input = kwargs.pop("input", None)
check = kwargs.pop("handle", False)
if input is not None:
if 'stdin' in kwargs:
raise ValueError('stdin and input arguments may not both be used.')
kwargs['stdin'] = subprocess.PIPE
process = subprocess.Popen(*popenargs, **kwargs)
try:
stdout, stderr = process.communicate(input)
except:
process.kill()
process.wait()
raise
retcode = process.poll()
if check and retcode:
raise subprocess.CalledProcessError(
retcode, process.args, output=stdout, stderr=stderr)
return retcode, stdout, stderr
</code></pre>
<p>There is no support for timeouts, and no custom class for completed process info, so I'm only returning the <code>retcode</code>, <code>stdout</code> and <code>stderr</code> information. Otherwise it does the same thing as the original.</p> |
51,525,435 | What's the difference between Python pip's pip.conf and pypirc file? | <p>I'm having trouble reaching a nexus server that we're using to store custom python packages. I've been told to change the settings in both my <code>~/.pypirc</code> file and the <code>~/.pip/pip.conf</code> file. </p>
<p>What's the difference between those two files in how they're used? It seems like the <code>pip install -r requirements.txt</code> command refers to the <code>pip.conf</code> file, and then the fields within the <code>pip.conf</code> file requires looking up the pypirc file?</p>
<p>Example pip.conf file:</p>
<pre><code>[global]
index = https://user:[email protected]/somerepo/pypi-group/pypi
index-url = index = https://user:[email protected]/somerepo/pypi-group/simple
</code></pre>
<p>Example pypirc file:</p>
<pre><code>[distutils]
index-servers =
pypi
nexus
[pypi]
repository: https://pypi.org/pypi
username: abc
password: def
[nexus]
repository: https://someurl.com/somerepo/pypi-internal
username: someuser
password: somepassword
</code></pre>
<p>Also, what's the difference between index and index-url in the pip.conf file?</p> | 51,525,463 | 1 | 0 | null | 2018-07-25 18:24:11.68 UTC | 8 | 2018-07-25 20:15:32.777 UTC | null | null | null | null | 1,163,355 | null | 1 | 14 | python|pip|nexus|pypi | 9,911 | <p><code>.pypirc</code> is a file standard used by multiple tools, <em>but not by <code>pip</code></em>. For example, the <code>easy_install</code> tool <a href="https://pythonhosted.org/an_example_pypi_project/setuptools.html#intermezzo-pypirc-file-and-gpg" rel="noreferrer">reads that file</a>, as does <a href="https://github.com/pypa/twine" rel="noreferrer"><code>twine</code></a>. It contains configuration on how to access specific PyPI index servers <em>when publishing a package</em>.</p>
<p><code>pip.conf</code> on the other hand is <em>only</em> used by the <code>pip</code> tool, and <code>pip</code> never publishes packages, it downloads packages from them. As such, it never looks at the <code>.pypirc</code> file.</p>
<p>If you are not publishing packages, you don't need a <code>.pypirc</code> file. You can't use it to configure index servers for <code>pip</code>.</p>
<p>As for the <code>--index-url</code> and <code>--index</code> switches, these are used for different <code>pip</code> commands.</p>
<ul>
<li><p><code>--index-url</code> is a common switch among several pip commands that deal with installing packages (<code>pip install</code>, <code>pip download</code>, <code>pip list</code>, and <code>pip wheel</code>), where it is part of a group of switches (together with <code>--extra-index-url</code>, <code>--no-index</code>, <code>--find-links</code> and <code>--process-dependency-links</code> and a few deprecated switches) that all together configure how package discovery works. The URL must point to a <a href="https://www.python.org/dev/peps/pep-0503/" rel="noreferrer">PEP 503 Simple Repository API</a> location, the default is <code>https://pypi.org/simple</code>.</p></li>
<li><p><code>--index</code> is only used by <code>pip search</code>; it only needs this one piece of information. It is named separately because it should point to the public search web interface, not the simple repository! For <a href="https://pypi.org" rel="noreferrer">https://pypi.org</a>, that's <code>https://pypi.org/pypi</code>.</p></li>
</ul> |
856,706 | extract links (URLs), with nokogiri in ruby, from a href html tags? | <p>I want to extract from a webpage all URLs how can I do that with nokogiri?</p>
<p>example:</p>
<pre>
<div class="heat">
<a href='http://example.org/site/1/'>site 1</a>
<a href='http://example.org/site/2/'>site 2</a>
<a href='http://example.org/site/3/'>site 3</a>
</diV>
</pre>
<p>result should be an list:</p>
<p><pre><code>l = ['<a href="http://example.org/site/1/" rel="noreferrer">http://example.org/site/1/</a>', '<a href="http://example.org/site/2/" rel="noreferrer">http://example.org/site/2/</a>', '<a href="http://example.org/site/3/" rel="noreferrer">http://example.org/site/3/</a>'</pre></code> </p> | 856,878 | 2 | 1 | null | 2009-05-13 08:11:11.733 UTC | 20 | 2020-06-25 19:51:26.757 UTC | null | null | null | null | 106,072 | null | 1 | 42 | ruby|parsing|nokogiri | 47,324 | <p>You can do it like this:</p>
<pre><code>doc = Nokogiri::HTML.parse(<<-HTML_END)
<div class="heat">
<a href='http://example.org/site/1/'>site 1</a>
<a href='http://example.org/site/2/'>site 2</a>
<a href='http://example.org/site/3/'>site 3</a>
</div>
<div class="wave">
<a href='http://example.org/site/4/'>site 4</a>
<a href='http://example.org/site/5/'>site 5</a>
<a href='http://example.org/site/6/'>site 6</a>
</div>
HTML_END
l = doc.css('div.heat a').map { |link| link['href'] }
</code></pre>
<p>This solution finds all anchor elements using a css selector and collects their href attributes.</p> |
1,253,670 | Why do round() and ceil() not return an integer? | <p>Once in a while, I find myself rounding some numbers, and I always have to cast the result to an integer:</p>
<pre><code>int rounded = (int) floor(value);
</code></pre>
<p>Why do all rounding functions (<code>ceil()</code>, <code>floor()</code>) return a floating number, and not an integer? I find this pretty non-intuitive, and would love to have some explanations!</p> | 1,253,686 | 2 | 3 | null | 2009-08-10 08:16:09.34 UTC | 5 | 2013-04-21 22:32:11.5 UTC | 2013-04-21 22:32:11.5 UTC | null | 957,997 | null | 56,761 | null | 1 | 63 | c++|c|casting|rounding | 23,506 | <p>The integral value returned by these functions may be too large to store in an integer type (int, long, etc.). To avoid an overflow, which will produce undefined results, an application should perform a range check on the returned value before assigning it to an integer type.</p>
<p>from the ceil(3) Linux man page.</p> |
2,762,260 | Detecting a url using preg_match? without http:// in the string | <p>I was wondering how I could check a string broken into an array against a preg_match to see if it started with www. I already have one that check for <a href="http://www">http://www</a>. </p>
<pre><code>function isValidURL($url)
{
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
$stringToArray = explode(" ",$_POST['text']);
foreach($stringToArray as $key=>$val){
$urlvalid = isValidURL($val);
if($urlvalid){
$_SESSION["messages"][] = "NO URLS ALLOWED!";
header("Location: http://www.domain.com/post/id/".$_POST['postID']);
exit();
}
}
</code></pre>
<p>Thanks!
Stefan</p> | 2,762,412 | 5 | 2 | null | 2010-05-04 01:29:08.943 UTC | 6 | 2018-03-26 18:33:25.717 UTC | 2010-05-04 02:17:11.11 UTC | null | 153,995 | null | 234,631 | null | 1 | 13 | php|regex|url|preg-match | 67,697 | <p>You want something like:</p>
<pre><code>%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i
</code></pre>
<p>this is using the | to match either <code>http://</code> or <code>www</code> at the beginning. I changed the delimiter to <code>%</code> to avoid clashing with the <code>|</code></p> |
2,950,309 | viewWillAppear for subviews | <p>I have UIScrollView with multiple UIVIew subviews. I would like to update the data that is displayed by each UIView when they appear in the visible portion of the UIScrollView. </p>
<p>What is the callback that gets triggered? I tried viewWillAppear, but it does not seem to get called.</p>
<p>Thanks. :)</p> | 2,950,979 | 5 | 0 | null | 2010-06-01 13:51:37.623 UTC | 17 | 2020-03-30 19:04:27.947 UTC | null | null | null | null | 75,777 | null | 1 | 27 | iphone|uiview|uiscrollview | 17,129 | <p>You have to do the calculation yourself. Implement <code>scrollViewDidScroll:</code> in your scroll view delegate and calculate manually which views are visible (e.g. by checking if <code>CGRectIntersectsRect(scrollView.bounds, subview.frame)</code> returns true.</p> |
2,659,000 | Java - How to find the redirected url of a url? | <p>I am accessing web pages through java as follows:</p>
<pre><code>URLConnection con = url.openConnection();
</code></pre>
<p>But in some cases, a url redirects to another url. So I want to know the url to which the previous url redirected.</p>
<p>Below are the header fields that I got as a response:</p>
<pre><code>null-->[HTTP/1.1 200 OK]
Cache-control-->[public,max-age=3600]
last-modified-->[Sat, 17 Apr 2010 13:45:35 GMT]
Transfer-Encoding-->[chunked]
Date-->[Sat, 17 Apr 2010 13:45:35 GMT]
Vary-->[Accept-Encoding]
Expires-->[Sat, 17 Apr 2010 14:45:35 GMT]
Set-Cookie-->[cl_def_hp=copenhagen; domain=.craigslist.org; path=/; expires=Sun, 17 Apr 2011 13:45:35 GMT, cl_def_lang=en; domain=.craigslist.org; path=/; expires=Sun, 17 Apr 2011 13:45:35 GMT]
Connection-->[close]
Content-Type-->[text/html; charset=iso-8859-1;]
Server-->[Apache]
</code></pre>
<p>So at present, I am constructing the redirected url from the value of the <code>Set-Cookie</code> header field. In the above case, the redirected url is <code>copenhagen.craigslist.org</code></p>
<p>Is there any standard way through which I can determine which url the particular url is going to redirect.</p>
<p>I know that when a url redirects to other url, the server sends an intermediate response containing a <code>Location</code> header field that tells the redirected url but I am not receiving that intermediate response through the <code>url.openConnection();</code> method. </p> | 2,659,022 | 6 | 0 | null | 2010-04-17 15:56:26.537 UTC | 28 | 2017-11-29 11:16:45.063 UTC | 2010-04-17 16:08:11.503 UTC | null | 157,027 | null | 157,027 | null | 1 | 67 | java|url|http-headers | 112,641 | <p>You need to cast the <code>URLConnection</code> to <code>HttpURLConnection</code> and instruct it to <strong>not</strong> follow the redirects by setting <a href="http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html#setInstanceFollowRedirects%28boolean%29" rel="noreferrer"><code>HttpURLConnection#setInstanceFollowRedirects()</code></a> to <code>false</code>. You can also set it globally by <a href="http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html#setFollowRedirects%28boolean%29" rel="noreferrer"><code>HttpURLConnection#setFollowRedirects()</code></a>.</p>
<p>You only need to handle redirects yourself then. Check the response code by <a href="http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html#getResponseCode%28%29" rel="noreferrer"><code>HttpURLConnection#getResponseCode()</code></a>, grab the <code>Location</code> header by <a href="http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html#getHeaderField%28java.lang.String%29" rel="noreferrer"><code>URLConnection#getHeaderField()</code></a> and then fire a new HTTP request on it.</p> |
2,395,115 | Is there an algorithm to securely split a message into x parts requiring at least y parts to reassemble? | <p>Is there an algorithm to securely split a message into x parts requiring at least y parts to reassemble? Obviously, y <= x.</p>
<p>An example:</p>
<p>Say that I have a secret message that I only want to be read in the event of my death. As a way to ensure this, I give a fraction of the message to ten friends. Now, I can't guaranty that all my friends will be able to put their messages together to recover the original. So, I construct each message fraction in such a way so as to only require any 5 friends to put their parts together to reconstruct the whole. However, owning less than 5 parts will not give anything away about the message, except possibly the length.</p>
<p>My question is, is this possible? What algorithms might I look at to accomplish this?</p>
<p>Clarification edit: The important part of this is the cryptographic strength. An attacker should not be able to recover the message, either in whole or in part with less than y parts.</p> | 2,395,266 | 7 | 1 | null | 2010-03-07 03:54:33.31 UTC | 9 | 2010-03-08 03:04:11.33 UTC | 2010-03-07 04:17:23.217 UTC | null | 189,173 | null | 189,173 | null | 1 | 15 | algorithm|encryption | 2,763 | <p><a href="http://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing" rel="noreferrer">Shamir Secret Sharing</a> and <a href="http://en.wikipedia.org/wiki/Secret_sharing#Blakley.27s_scheme" rel="noreferrer">Blakley's scheme</a> are two well-established, provably secure means of sharing a secret so that it can be recovered only when a pre-determined number of "shares" are combined.</p> |
2,349,798 | In Haskell, how can I use the built in sortBy function to sort a list of pairs(tuple)? | <p>I am a beginner in Haskell so please bear with me. (Just started learning yesterday!) How can I sort a list of tuples primarily by their first components (highest to smallest) and secondarily by their second components (smallest to highest)? A sample input/output would be:</p>
<p><code>[(1, "b"), (1, "a"), (2, "b"), (2, "a")]</code> (input)</p>
<p><code>[(1, "a"), (2, "a"), (1, "b"), (2, "b")]</code> (middle step)</p>
<p><code>[(2, "a"), (2, "b"), (1, "a"), (1, "b")]</code> (output)</p>
<p>I tried using the following but it gave wrong output:</p>
<pre><code>sortGT a b = GT
sortBy sortGT lst
</code></pre>
<p>I am sure that I can do this by using <a href="http://haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Data-List.html#v:sortBy" rel="noreferrer"><code>sortBy</code></a> only, but I can't figure it out myself. Any help would be highly appreciated!</p> | 2,349,869 | 7 | 0 | null | 2010-02-28 02:15:40.453 UTC | 11 | 2017-01-17 14:23:54.91 UTC | 2012-05-03 18:52:42.113 UTC | null | 6,310 | null | 282,926 | null | 1 | 40 | sorting|haskell|tuples | 38,656 | <p>You need to construct your function <code>sortGT</code>, so that it compares pairs the way you want it:</p>
<pre><code>sortGT (a1, b1) (a2, b2)
| a1 < a2 = GT
| a1 > a2 = LT
| a1 == a2 = compare b1 b2
</code></pre>
<p><br/>
Using this you get the following results (I used ghci):</p>
<pre><code>*Main Data.List> sortBy sortGT [(1, "b"), (1, "a"), (2, "b"), (2, "a")]
[(2,"a"),(2,"b"),(1,"a"),(1,"b")]
</code></pre> |
2,455,750 | Replace duplicate spaces with a single space in T-SQL | <p>I need to ensure that a given field does not have more than one space (I am not concerned about all white space, just space) between characters.</p>
<p>So</p>
<pre><code>'single spaces only'
</code></pre>
<p>needs to be turned into </p>
<pre><code>'single spaces only'
</code></pre>
<p>The below will not work</p>
<pre><code>select replace('single spaces only',' ',' ')
</code></pre>
<p>as it would result in </p>
<pre><code>'single spaces only'
</code></pre>
<p>I would really prefer to stick with native T-SQL rather than a CLR based solution.</p>
<p>Thoughts?</p> | 2,455,869 | 15 | 1 | null | 2010-03-16 15:37:56.22 UTC | 50 | 2022-07-21 11:01:21.513 UTC | 2010-12-01 14:15:22.843 UTC | null | 63,550 | null | 98,795 | null | 1 | 125 | sql-server|tsql | 150,542 | <p>Even tidier:</p>
<pre><code>select string = replace(replace(replace(' select single spaces',' ','<>'),'><',''),'<>',' ')
</code></pre>
<p>Output:</p>
<blockquote>
<p>select single spaces</p>
</blockquote> |
3,102,819 | Disable same origin policy in Chrome | <p>Is there any way to disable the <a href="https://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">Same-origin policy</a> on Google's <a href="http://en.wikipedia.org/wiki/Google_Chrome" rel="noreferrer">Chrome</a> browser?</p> | 3,177,718 | 34 | 12 | null | 2010-06-23 15:00:21.823 UTC | 816 | 2022-08-24 03:56:39.053 UTC | 2019-05-15 16:11:44.643 UTC | null | 254,343 | null | 1,785 | null | 1 | 2,011 | javascript|ajax|google-chrome | 2,935,194 | <p>Close chrome (or chromium) and restart with the <code>--disable-web-security</code> argument. I just tested this and verified that I can access the contents of an iframe with src="http://google.com" embedded in a page served from "localhost" (tested under chromium 5 / ubuntu). For me the exact command was:</p>
<p><strong>Note : Kill all chrome instances before running command</strong></p>
<pre><code>chromium-browser --disable-web-security --user-data-dir="[some directory here]"
</code></pre>
<p>The browser will warn you that "you are using an unsupported command line" when it first opens, which you can ignore.</p>
<p>From the chromium source:</p>
<pre><code>// Don't enforce the same-origin policy. (Used by people testing their sites.)
const wchar_t kDisableWebSecurity[] = L"disable-web-security";
</code></pre>
<hr>
<p>Before Chrome 48, you could just use:</p>
<pre><code>chromium-browser --disable-web-security
</code></pre> |
2,686,855 | Is there a JavaScript function that can pad a string to get to a determined length? | <p>I am in need of a JavaScript function which can take a value and pad it to a given length (I need spaces, but anything would do). I found this, but I have no idea what the heck it is doing and it doesn't seem to work for me.</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>String.prototype.pad = function(l, s, t) {
return s || (s = " "),
(l -= this.length) > 0 ?
(s = new Array(Math.ceil(l / s.length) + 1).join(s))
.substr(0, t = !t ? l : t == 1 ?
0 :
Math.ceil(l / 2)) + this + s.substr(0, l - t) :
this;
};
var s = "Jonas";
document.write(
'<h2>S = '.bold(), s, "</h2>",
'S.pad(20, "[]", 0) = '.bold(), s.pad(20, "[]", 0), "<br />",
'S.pad(20, "[====]", 1) = '.bold(), s.pad(20, "[====]", 1), "<br />",
'S.pad(20, "~", 2) = '.bold(), s.pad(20, "~", 2)
);</code></pre>
</div>
</div>
</p> | 14,760,377 | 43 | 2 | null | 2010-04-21 21:59:57.86 UTC | 65 | 2022-02-02 09:14:47.163 UTC | 2021-09-24 10:46:24.277 UTC | null | 295,783 | null | 22,777 | null | 1 | 315 | javascript|string | 288,065 | <p>EcmaScript 2017 added <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart" rel="noreferrer"><code>String.padStart</code></a> (along with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd" rel="noreferrer"><code>String.padEnd</code></a>) for just this purpose:</p>
<pre><code>"Jonas".padStart(10); // Default pad string is a space
"42".padStart(6, "0"); // Pad with "0"
"*".padStart(8, "-/|\\"); // produces '-/|\\-/|*'
</code></pre>
<p>If not present in the JS host, <code>String.padStart</code> can be added as a polyfill.</p>
<h2>Pre ES-2017</h2>
<p>I found this solution <a href="http://dev.enekoalonso.com/2010/07/20/little-tricks-string-padding-in-javascript/" rel="noreferrer">here</a> and this is for me much much simpler:</p>
<pre><code>var n = 123
String("00000" + n).slice(-5); // returns 00123
("00000" + n).slice(-5); // returns 00123
(" " + n).slice(-5); // returns " 123" (with two spaces)
</code></pre>
<p>And here I made an extension to the string object:</p>
<pre><code>String.prototype.paddingLeft = function (paddingValue) {
return String(paddingValue + this).slice(-paddingValue.length);
};
</code></pre>
<p>An example to use it:</p>
<pre><code>function getFormattedTime(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
hours = hours.toString().paddingLeft("00");
minutes = minutes.toString().paddingLeft("00");
return "{0}:{1}".format(hours, minutes);
};
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
</code></pre>
<p>This will return a time in the format "15:30"</p> |
25,009,072 | How to write "good" Julia code when dealing with multiple types and arrays (multiple dispatch) | <p><strong>OP UPDATE:</strong> Note that in the latest version of Julia (v0.5), the idiomatic approach to answering this question is to just define <code>mysquare(x::Number) = x^2</code>. The vectorised case is covered using automatic broadcasting, i.e. <code>x = randn(5) ; mysquare.(x)</code>. See also the new answer explaining dot syntax in more detail.</p>
<p>I am new to Julia, and given my Matlab origins, I am having some difficulty determining how to write "good" Julia code that takes advantage of multiple dispatch and Julia's type system.</p>
<p>Consider the case where I have a function that provides the square of a <code>Float64</code>. I might write this as:</p>
<pre><code>function mysquare(x::Float64)
return(x^2);
end
</code></pre>
<p>Sometimes, I want to square all the <code>Float64</code>s in a one-dimentional array, but don't want to write out a loop over <code>mysquare</code> everytime, so I use multiple dispatch and add the following:</p>
<pre><code>function mysquare(x::Array{Float64, 1})
y = Array(Float64, length(x));
for k = 1:length(x)
y[k] = x[k]^2;
end
return(y);
end
</code></pre>
<p>But now I am sometimes working with <code>Int64</code>, so I write out two more functions that take advantage of multiple dispatch:</p>
<pre><code>function mysquare(x::Int64)
return(x^2);
end
function mysquare(x::Array{Int64, 1})
y = Array(Float64, length(x));
for k = 1:length(x)
y[k] = x[k]^2;
end
return(y);
end
</code></pre>
<p>Is this right? Or is there a more ideomatic way to deal with this situation? Should I use type parameters like this?</p>
<pre><code>function mysquare{T<:Number}(x::T)
return(x^2);
end
function mysquare{T<:Number}(x::Array{T, 1})
y = Array(Float64, length(x));
for k = 1:length(x)
y[k] = x[k]^2;
end
return(y);
end
</code></pre>
<p>This feels sensible, but will my code run as quickly as the case where I avoid parametric types?</p>
<p>In summary, there are two parts to my question:</p>
<ol>
<li><p>If fast code is important to me, should I use parametric types as described above, or should I write out multiple versions for different concrete types? Or should I do something else entirely?</p></li>
<li><p>When I want a function that operates on arrays as well as scalars, is it good practice to write two versions of the function, one for the scalar, and one for the array? Or should I be doing something else entirely?</p></li>
</ol>
<p>Finally, please point out any other issues you can think of in the code above as my ultimate goal here is to write good Julia code.</p> | 25,022,908 | 2 | 0 | null | 2014-07-29 06:02:14.517 UTC | 7 | 2021-06-08 18:42:14.077 UTC | 2020-02-23 23:29:48.953 UTC | null | 1,667,895 | null | 1,667,895 | null | 1 | 40 | arrays|types|julia|multiple-dispatch | 3,201 | <p>Julia compiles a specific version of your function for each set of inputs as required. Thus to answer part 1, there is no performance difference. The parametric way is the way to go.</p>
<p>As for part 2, it might be a good idea in some cases to write a separate version (sometimes for performance reasons, e.g., to avoid a copy). In your case however you can use the in-built macro <code>@vectorize_1arg</code> to automatically generate the array version, e.g.:</p>
<pre><code>function mysquare{T<:Number}(x::T)
return(x^2)
end
@vectorize_1arg Number mysquare
println(mysquare([1,2,3]))
</code></pre>
<p>As for general style, don't use semicolons, and <code>mysquare(x::Number) = x^2</code> is a lot shorter.</p>
<p>As for your vectorized <code>mysquare</code>, consider the case where <code>T</code> is a <code>BigFloat</code>. Your output array, however, is <code>Float64</code>. One way to handle this would be to change it to</p>
<pre><code>function mysquare{T<:Number}(x::Array{T,1})
n = length(x)
y = Array(T, n)
for k = 1:n
@inbounds y[k] = x[k]^2
end
return y
end
</code></pre>
<p>where I've added the <code>@inbounds</code> macro to boost speed because we don't need to check the bound violation every time — we know the lengths. This function could still have issues in the event that the type of <code>x[k]^2</code> isn't <code>T</code>. An even more defensive version would perhaps be</p>
<pre><code>function mysquare{T<:Number}(x::Array{T,1})
n = length(x)
y = Array(typeof(one(T)^2), n)
for k = 1:n
@inbounds y[k] = x[k]^2
end
return y
end
</code></pre>
<p>where <code>one(T)</code> would give <code>1</code> if <code>T</code> is an <code>Int</code>, and <code>1.0</code> if <code>T</code> is a <code>Float64</code>, and so on. These considerations only matter if you want to make hyper-robust library code. If you really only will be dealing with <code>Float64</code>s or things that can be promoted to <code>Float64</code>s, then it isn't an issue. It seems like hard work, but the power is amazing. You can always just settle for Python-like performance and disregard all type information.</p> |
23,670,260 | How to download a file from the jenkins job build folder | <p>I have a jenkins server running, and for a job I need to download a file which is in the <code>jobs/builds/buildname</code> folder.</p>
<p>How to download that file from jenkins job?</p> | 23,671,522 | 6 | 0 | null | 2014-05-15 05:52:10.197 UTC | 3 | 2018-10-09 11:26:01.04 UTC | 2017-09-26 16:50:08.913 UTC | null | 2,702,249 | null | 2,229,512 | null | 1 | 3 | jenkins | 48,277 | <p>If you would use the workspace as suggested by previous post, you can access it within a Pipeline:</p>
<pre><code>sh "wget http://<servername:port>/job/<jobname>/ws/index.txt"
</code></pre>
<p>Or inside a script:</p>
<pre><code>wget http://<servername:port>/job/<jobname>/ws/index.txt
</code></pre>
<p>Where <code>index.txt</code> is the file you want to download.</p> |
39,887,526 | Filter Spark DataFrame based on another DataFrame that specifies denylist criteria | <p>I have a <code>largeDataFrame</code> (multiple columns and billions of rows) and a <code>smallDataFrame</code> (single column and 10,000 rows).</p>
<p>I'd like to filter all the rows from the <code>largeDataFrame</code> whenever the <code>some_identifier</code> column in the <code>largeDataFrame</code> matches one of the rows in the <code>smallDataFrame</code>.</p>
<p>Here's an example:</p>
<p>largeDataFrame</p>
<pre><code>some_idenfitier,first_name
111,bob
123,phil
222,mary
456,sue
</code></pre>
<p>smallDataFrame</p>
<pre><code>some_identifier
123
456
</code></pre>
<p>desiredOutput</p>
<pre><code>111,bob
222,mary
</code></pre>
<p>Here is my ugly solution.</p>
<pre class="lang-scala prettyprint-override"><code>val smallDataFrame2 = smallDataFrame.withColumn("is_bad", lit("bad_row"))
val desiredOutput = largeDataFrame.join(broadcast(smallDataFrame2), Seq("some_identifier"), "left").filter($"is_bad".isNull).drop("is_bad")
</code></pre>
<p>Is there a cleaner solution?</p> | 39,889,263 | 2 | 0 | null | 2016-10-06 04:27:58.61 UTC | 18 | 2021-11-11 18:20:51.63 UTC | 2021-11-11 18:20:51.63 UTC | null | 1,386,551 | null | 1,125,159 | null | 1 | 45 | dataframe|apache-spark|pyspark|apache-spark-sql | 61,420 | <p>You'll need to use a <code>left_anti</code> join in this case. </p>
<p>The <em>left anti join</em> is the opposite of a <em>left semi join</em>. </p>
<p>It filters out data from the right table in the left table according to a given key :</p>
<pre><code>largeDataFrame
.join(smallDataFrame, Seq("some_identifier"),"left_anti")
.show
// +---------------+----------+
// |some_identifier|first_name|
// +---------------+----------+
// | 222| mary|
// | 111| bob|
// +---------------+----------+
</code></pre> |
10,748,253 | Idiomatic R code for partitioning a vector by an index and performing an operation on that partition | <p>I'm trying to find the idiomatic way in R to partition a numerical vector by some index vector, find the sum of all numbers in that partition and then divide each individual entry by that partition sum. In other words, if I start with this: </p>
<pre><code>df <- data.frame(x = c(1,2,3,4,5,6), index = c('a', 'a', 'b', 'b', 'c', 'c'))
</code></pre>
<p>I want the output to create a vector (let's call it z): </p>
<pre><code>c(1/(1+2), 2/(1+2), 3/(3+4), 3/(3+4), 5/(5+6), 6/(5+6))
</code></pre>
<p>If I were doing this is SQL and could use window functions, I would do this: </p>
<pre><code>select
x / sum(x) over (partition by index) as z
from df
</code></pre>
<p>and if I were using plyr, I would do something like this: </p>
<pre><code>ddply(df, .(index), transform, z = x / sum(x))
</code></pre>
<p>but I'd like to know how to do it using the standard R functional programming tools like mapply/aggregate etc. </p> | 10,748,470 | 3 | 0 | null | 2012-05-25 03:51:30.45 UTC | 13 | 2013-03-30 15:38:25.327 UTC | 2013-03-30 15:38:25.327 UTC | null | 559,784 | null | 271,844 | null | 1 | 19 | r|functional-programming|plyr | 2,888 | <p>Yet another option is <code>ave</code>. For good measure, I've collected the answers above, tried my best to make their output equivalent (a vector), and provided timings over 1000 runs using your example data as an input. First, my answer using <code>ave</code>: <code>ave(df$x, df$index, FUN = function(z) z/sum(z))</code>. I also show an example using <code>data.table</code> package since it is usually pretty quick, but I know you're looking for base solutions, so you can ignore that if you want.</p>
<p>And now a bunch of timings:</p>
<pre><code>library(data.table)
library(plyr)
dt <- data.table(df)
plyr <- function() ddply(df, .(index), transform, z = x / sum(x))
av <- function() ave(df$x, df$index, FUN = function(z) z/sum(z))
t.apply <- function() unlist(tapply(df$x, df$index, function(x) x/sum(x)))
l.apply <- function() unlist(lapply(split(df$x, df$index), function(x){x/sum(x)}))
b.y <- function() unlist(by(df$x, df$index, function(x){x/sum(x)}))
agg <- function() aggregate(df$x, list(df$index), function(x){x/sum(x)})
d.t <- function() dt[, x/sum(x), by = index]
library(rbenchmark)
benchmark(plyr(), av(), t.apply(), l.apply(), b.y(), agg(), d.t(),
replications = 1000,
columns = c("test", "elapsed", "relative"),
order = "elapsed")
#-----
test elapsed relative
4 l.apply() 0.052 1.000000
2 av() 0.168 3.230769
3 t.apply() 0.257 4.942308
5 b.y() 0.694 13.346154
6 agg() 1.020 19.615385
7 d.t() 2.380 45.769231
1 plyr() 5.119 98.442308
</code></pre>
<p>the <code>lapply()</code> solution seems to win in this case and <code>data.table()</code> is surprisingly slow. Let's see how this scales to a bigger aggregation problem:</p>
<pre><code>df <- data.frame(x = sample(1:100, 1e5, TRUE), index = gl(1000, 100))
dt <- data.table(df)
#Replication code omitted for brevity, used 100 replications and dropped plyr() since I know it
#will be slow by comparison:
test elapsed relative
6 d.t() 2.052 1.000000
1 av() 2.401 1.170078
3 l.apply() 4.660 2.270955
2 t.apply() 9.500 4.629630
4 b.y() 16.329 7.957602
5 agg() 20.541 10.010234
</code></pre>
<p>that seems more consistent with what I'd expect.</p>
<p>In summary, you've got plenty of good options. Find one or two methods that work with your mental model of how aggregation tasks should work and master that function. Many ways to skin a cat.</p>
<h1>Edit - and an example with 1e7 rows</h1>
<p>Probably not large enough for Matt, but as big as my laptop can handle without crashing:</p>
<pre><code>df <- data.frame(x = sample(1:100, 1e7, TRUE), index = gl(10000, 1000))
dt <- data.table(df)
#-----
test elapsed relative
6 d.t() 0.61 1.000000
1 av() 1.45 2.377049
3 l.apply() 4.61 7.557377
2 t.apply() 8.80 14.426230
4 b.y() 8.92 14.622951
5 agg() 18.20 29.83606
</code></pre> |
10,376,253 | Windows service - get current directory | <p>I have a Windows service that should look for a configuration file in its current directory.</p>
<p>So I use <code>directory.getcurrentdirectiry()</code> but instead of the service directory I get back </p>
<pre><code>c:\windows\system32
</code></pre>
<p>Any idea why and how should I get the service directory?</p> | 36,631,061 | 5 | 0 | null | 2012-04-29 21:41:40.43 UTC | 11 | 2021-06-22 05:26:31.653 UTC | 2012-04-30 05:04:06.077 UTC | null | 13,302 | null | 963,701 | null | 1 | 70 | c#|windows-services|working-directory | 71,830 | <p>Don't use <code>Directory.GetCurrentDirectory()</code>. I had the same exact problem with <em>C:\Windows\System32</em> being returned. Use this instead:</p>
<p><code>Path.GetDirectoryName(Application.ExecutablePath);</code></p> |
10,308,110 | Simplest way to download and unzip files in Node.js cross-platform? | <p>Just looking for a simple solution to downloading and unzipping <code>.zip</code> or <code>.tar.gz</code> files in Node.js on any operating system.</p>
<p>Not sure if this is built in or I have to use a separate library. Any ideas? Looking for just a couple lines of code so when the next zip file comes that I want to download in node, it's a no brainer. Feel like this should be easy and/or built in, but I can't find anything. Thanks!</p> | 10,314,258 | 12 | 0 | null | 2012-04-25 01:13:06.48 UTC | 26 | 2021-07-14 22:47:56.453 UTC | null | null | null | null | 169,992 | null | 1 | 102 | node.js|zip | 186,233 | <p>Node has builtin support for gzip and deflate via the <a href="http://nodejs.org/api/zlib.html">zlib module</a>:</p>
<pre><code>var zlib = require('zlib');
zlib.gunzip(gzipBuffer, function(err, result) {
if(err) return console.error(err);
console.log(result);
});
</code></pre>
<p><strong>Edit:</strong> You can even <code>pipe</code> the data directly through e.g. <code>Gunzip</code> (using <a href="https://github.com/mikeal/request">request</a>):</p>
<pre><code>var request = require('request'),
zlib = require('zlib'),
fs = require('fs'),
out = fs.createWriteStream('out');
// Fetch http://example.com/foo.gz, gunzip it and store the results in 'out'
request('http://example.com/foo.gz').pipe(zlib.createGunzip()).pipe(out);
</code></pre>
<p>For tar archives, there is Isaacs' <a href="https://github.com/isaacs/node-tar">tar module</a>, which is used by npm.</p>
<p><strong>Edit 2:</strong> Updated answer as <code>zlib</code> doesn't support the <code>zip</code> format. This will only work for <code>gzip</code>.</p> |
10,381,827 | handlerbars.js check if list is empty | <p>Is there a way in Handlebars.js templating to check if the collection or list is null or empty, before going and iterating through the list/collection?</p>
<pre><code>// if list is empty do some rendering ... otherwise do the normal
{{#list items}}
{{/list}}
{{#each items}}
{{/each}}
</code></pre> | 11,597,069 | 5 | 0 | null | 2012-04-30 10:06:07.973 UTC | 10 | 2018-06-05 07:14:45.56 UTC | null | null | null | null | 6,482 | null | 1 | 138 | handlebars.js | 78,506 | <p>The "each" tag can take an "else" section too. So the simplest form is:</p>
<pre><code>{{#each items}}
// render item
{{else}}
// render empty
{{/each}}
</code></pre> |
10,282,532 | Entity Framework - Start Over - Undo/Rollback All Migrations | <p>For some reason, my migrations appear to have been jumbled/corrupted/whatever. I'm at the point where I just want to start over, so is there a way to completely undo all migrations, erase the history, and delete the migration code, so I'm back to square one?</p>
<p>e.g.) <code>PM> Disable-Migrations</code> or <code>Rollback-Migrations</code></p>
<p>I don't want to "update" to an original migration step (i.e. something like an <code>InitialSchema</code> target) because I can't find it anymore.</p> | 10,282,630 | 5 | 0 | null | 2012-04-23 14:28:43.687 UTC | 56 | 2020-05-17 09:56:46.32 UTC | null | null | null | null | 1,037,948 | null | 1 | 173 | entity-framework|entity-framework-4.3|entity-framework-migrations | 90,059 | <p>You can rollback to any migration by using:</p>
<pre><code>Update-Database -TargetMigration:"MigrationName"
</code></pre>
<p>If you want to rollback all migrations you can use:</p>
<pre><code>Update-Database -TargetMigration:0
</code></pre>
<p>or equivalent:</p>
<pre><code>Update-Database -TargetMigration:$InitialDatabase
</code></pre>
<p>In some cases you can also delete database and all migration classes.</p> |
6,297,923 | Override SHIFT + CTRL + Z in Notepad++ | <p>Hello I use Notepad++ for a lot of my development.<br>
One of the things that I do not like about it is the way you perform a redo by pressing <kbd>CTRL</kbd> + <kbd>Y</kbd> and when you press <kbd>SHIFT</kbd> + <kbd>CTRL</kbd> + <kbd>Z</kbd> you get <code>sub</code></p>
<p>Is there a plugin or a way to override the <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>Z</kbd> hotkey in developing a plugin for notepad++ to make it perform the redo instead of the <kbd>CTRL</kbd> + <kbd>Y</kbd>?</p>
<p>Now I'm not trying to criticize the design choice for this, it's just that my fingers are short and fat and I have trouble pressing <kbd>CTRL</kbd> and <kbd>Y</kbd> at the same time.</p> | 6,297,954 | 2 | 6 | null | 2011-06-09 19:07:52.58 UTC | 4 | 2018-06-19 16:13:41.993 UTC | 2013-01-25 11:46:35.647 UTC | null | 729,489 | null | 102,526 | null | 1 | 57 | notepad++ | 14,954 | <p>You could try the 'shortcut mapper' under the Settings menu.</p>
<p>It seems that this key is not found in the normal Main menu commands, but it's the SCI_REDO command in the Scintalla tab. Whatever that may mean. ;) </p> |
19,694,503 | ajax, setRequestHeader(), Content-Type, application/x-www-form-urlencoded and charset | <p>I am having trouble understanding how to set the charset when the
content type is not text/html, text/plain, or text/xml, but is application/x-www-form-urlencoded content type instead.</p>
<p>Given this (simplified) javascript code:</p>
<pre><code>var xhr = new XMLHttpRequest();
</code></pre>
<p>If I <strong>do not</strong> explicitly set the encoding,</p>
<pre><code>xhr.open('POST', 'serv.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
</code></pre>
<p>firebug tells me that the content
type is "application/x-www-form-urlencoded; charset=<strong>UTF-8</strong>."</p>
<p>If I set the charset to ISO-8859-1 for instance,</p>
<pre><code>xhr.open('POST', 'serv.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
</code></pre>
<p>firebug <strong>still</strong> tells me "application/x-www-form-urlencoded; charset=<strong>UTF-8</strong>."</p>
<p>If I try something like</p>
<pre><code>xhr.setRequestHeader('Content-Type', 'text/plain; charset=ISO-8859-1');
</code></pre>
<p>then it respects the charset.</p>
<p>In all the cases the send() method goes like this:</p>
<pre><code>xhr.send('id=9&name=Yoda');
</code></pre>
<p>Why doesn't it honor the charset I specify if the Content-Type is x-www-form-urlencoded?</p>
<p>NOTE: I am using ISO-8859-1 just as an example. My goal is to understand what is going on.</p> | 24,415,321 | 2 | 0 | null | 2013-10-30 21:53:33.807 UTC | 5 | 2022-01-28 09:54:45.07 UTC | 2013-10-31 13:34:08.967 UTC | null | 2,855,955 | null | 2,855,955 | null | 1 | 10 | javascript|ajax|character-encoding | 63,977 | <p>The <code>application/x-www-form-urlencoded</code> mime type does not support parameters (such as <code>charset</code>). If you look at <a href="http://www.w3.org/TR/html5/forms.html#url-encoded-form-data" rel="noreferrer">this section</a> of the HTML5 spec, you will see how charset is determined (it's complicated). In particular, there is a note at the bottom of the section mentioning how charset cannot be specified as a parameter to the mime type.</p> |
41,040,702 | ASP.NET Identity (with IdentityServer4) get external resource oauth access token | <p>I have been through the docs of identityServer4 and I have set it up to use Microsoft Office 365 as a login provider. When the user has logged in I want to make a button where he can allow my app to subscribe to his calendar events using the webhooks api of graph.microsoft.com</p>
<p>The code in startup.cs</p>
<pre><code>app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions
{
AuthenticationScheme = "Microsoft",
DisplayName = "Microsoft",
SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
ClientId = "CLIENT ID",
ClientSecret = "CLIENT SECRET",
CallbackPath = new PathString("/signin-microsoft"),
Events = new OAuthEvents
{
OnCreatingTicket = context =>
{
redisCache.Set("AccessToken", context.AccessToken.GetBytes(), new DistributedCacheEntryOptions
{
AbsoluteExpiration = DateTimeOffset.UtcNow.AddDays(3)
});
return Task.FromResult(context);
}
}
Scope =
{
"Calendars.Read",
"Calendars.Read.Shared",
},
SaveTokens = true
});
</code></pre>
<p>But this is obviously not a viable path to go. I have only done this for testing purposes and to make a PoC of the subscriptions needed.</p>
<p>Now I would like to know if there is a smarter way to communicate with the identityServer that allows me to get this external access token, so that I can use the microsoft api on behalf of my logged in users?</p>
<p>Or is my only option to take the Microsoft AccessToken directly from this OAuthEvent and store it directly in a database, linked to the logged in user?</p>
<p>I really need this, since most of my functionality is based on data from third parties.</p> | 41,163,741 | 1 | 0 | null | 2016-12-08 13:29:40.977 UTC | 8 | 2019-09-20 03:04:28.763 UTC | 2016-12-15 11:56:34.657 UTC | null | 1,387,545 | null | 1,387,545 | null | 1 | 8 | c#|oauth|asp.net-identity|identityserver4|asp.net-identity-3 | 7,381 | <p>Ok, so I finally got this working. I have created a new project that is using <code>ASP.Net Identity</code> and <code>IdentityServer4</code> both build on top of <code>ASP.Net Core</code>.</p>
<p>The problem was that I wasn't completely aware of the flow that was used in the external login process.</p>
<p>If you use the boiler plates from both systems you will have an <code>AccountController</code> where the following method will be present:</p>
<pre><code>//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
</code></pre>
<p>The important part here is the: </p>
<p><code>await _signInManager.UpdateExternalAuthenticationTokensAsync(info);</code> </p>
<p>This will save your external credentials in the database table associated with your <code>ASP.Net identity</code>. In the table <code>AspNetUserTokens</code> you will now have 3 entries, called something like:
<code>access_token</code>, <code>expires_at</code> and <code>token_type</code>.</p>
<p>These are the tokens that we are interested in, that we can use to access the users credentials somewhere else in our application.</p>
<p>To fetch these tokens in the context of a logged in user:</p>
<p><code>var externalAccessToken = await _userManager.GetAuthenticationTokenAsync(User, "Microsoft", "access_token");</code></p>
<p>And to fetch them for a user we fetch from the DB we can use:</p>
<pre><code>var user = _userManager.Users.SingleOrDefault(x => x.Id == "myId");
if (user == null)
return;
var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
var externalAccessToken = await _userManager.GetAuthenticationTokenAsync(claimsPrincipal, "Microsoft", "access_token");
</code></pre> |
32,181,893 | Sql server update multiple columns from another table | <p>I have read lots of post about how to update multiple columns but still can't find right answer.</p>
<p>I have one table and I would like update this table from another table.</p>
<pre><code>Update table1
set (a,b,c,d,e,f,g,h,i,j,k)=(t2.a,t2.b,t2.c,t2.d,t2.e,t2.f,t2.g,t2.h,t2.i,t2.j,t2.k)
from
(
SELECT ..... with join ... where ....
) t2
where table1.id=table2.id
</code></pre>
<p>If I running only select statement (between brackets) then script return values but not working with update</p> | 32,181,923 | 4 | 0 | null | 2015-08-24 12:05:01.22 UTC | 2 | 2020-07-23 08:01:36.75 UTC | 2015-08-24 12:13:32.787 UTC | null | 4,560,953 | null | 3,747,585 | null | 1 | 15 | sql|sql-server|sql-server-2008 | 46,286 | <p>TSQL does not support <a href="https://connect.microsoft.com/SQLServer/feedback/details/299231/add-support-for-ansi-standard-row-value-constructors" rel="noreferrer">row-value constructor</a>. Use this instead:</p>
<pre><code>UPDATE table1
SET a = t2.a,
b = t2.b,
(...)
FROM
(
SELECT ..... with join ... WHERE ....
) t2
WHERE table1.id = table2.id
</code></pre> |
21,402,081 | Issue in Global.asax.cs page in MVC4 | <p>I my ASP.NET MVC 4 Project, my <code>Global.asax.cs</code> page shows the error on</p>
<pre><code> WebApiConfig.Register(GlobalConfiguration.Configuration);
</code></pre>
<blockquote>
<p><strong>The name 'GlobalConfiguration' does not exist in the current context</strong></p>
</blockquote>
<p>I have done many controllers and Views and all... How can I solve this issue and recover my project?</p>
<p>Here is the rest of my code for context</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace .....
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
</code></pre> | 21,402,541 | 7 | 1 | null | 2014-01-28 09:49:13.463 UTC | 3 | 2019-05-16 15:09:47.033 UTC | 2015-02-27 15:51:45.767 UTC | null | 2,319,844 | null | 2,677,745 | null | 1 | 46 | c#|asp.net|asp.net-mvc|asp.net-mvc-4 | 53,930 | <p>Make sure you have assembly <code>System.Web.Http.WebHost.dll</code> referenced. This is where GlobalConfiguration is.</p> |
19,278,515 | Use StringFormat to add a string to a WPF XAML binding | <p>I have a WPF 4 application that contains a TextBlock which has a one-way binding to an integer value (in this case, a temperature in degrees Celsius). The XAML looks like this:</p>
<pre><code><TextBlock x:Name="textBlockTemperature">
<Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock>
</code></pre>
<p>This works fine for displaying the actual temperature value but I'd like to format this value so it includes °C instead of just the number (30°C instead of just 30). I've been reading about StringFormat and I've seen several generic examples like this:</p>
<pre><code>// format the bound value as a currency
<TextBlock Text="{Binding Amount, StringFormat={}{0:C}}" />
</code></pre>
<p>and</p>
<pre><code>// preface the bound value with a string and format it as a currency
<TextBlock Text="{Binding Amount, StringFormat=Amount: {0:C}}"/>
</code></pre>
<p>Unfortunately, none of the examples I've seen have appended a string to the bound value as I'm trying to do. I'm sure it's got to be something simple but I'm not having any luck finding it. Can anyone explain to me how to do that?</p> | 19,278,672 | 4 | 0 | null | 2013-10-09 17:14:18.297 UTC | 26 | 2020-02-18 20:33:09.25 UTC | 2019-09-25 15:29:03.86 UTC | null | 285,795 | null | 685,869 | null | 1 | 144 | c#|wpf|xaml|data-binding|string-formatting | 227,010 | <p>Your first example is effectively what you need:</p>
<pre><code><TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />
</code></pre> |
30,145,812 | How to console.log an object definition and a text in same string? | <p>I have this JavaScript code:</p>
<pre><code>console.log(obj);// [query: "wordOfTheDay"]
console.log(note + " : " + obj ); // obj does not show up
</code></pre>
<p>I want to make "obj" display in the same string as "note" no matter the type it come in as.</p>
<p>For example:</p>
<pre><code>console.log("text sample : " + obj ); // text sample : [query: "wordOfTheDay"]
</code></pre>
<p>Thank you!</p> | 30,145,881 | 6 | 1 | null | 2015-05-09 22:45:43.973 UTC | 4 | 2022-04-13 05:34:52.45 UTC | null | null | null | null | 813,363 | null | 1 | 40 | javascript|object|concatenation|console.log | 30,363 | <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/log" rel="noreferrer"><code>console.log</code> accepts any number of parameters</a>, so just send each piece as its own param. That way you keep the formatting of the object in the console, and its all on one entry.</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>var obj = {
query: 'wordOfTheDay',
title: 'Frog',
url: '/img/picture.jpg'
};
console.log( "Text Here", obj);
// Text Here Object {query: "wordOfTheDay", title: "Frog", url: "/img/picture.jpg"}</code></pre>
</div>
</div>
</p> |
30,232,146 | Dynamically Populating Drop down list from selection of another drop down value | <p>My requirement is that for a selection in a 'meal' drop down list, a second drop down list 'category' should get dynamically populated with values related to the selection in first drop down list. Then depending on what is selected in the meal dropdown, the list should change in category. I have written the following Javascript function but the output I'm getting is not freshly populating the 2nd dropdown. On change of a selection, the new list is just getting appended to the old list. </p>
<pre><code>function changecat() {
var selectHTML = "";
var A = ["Soup", "Juice", "Tea", "Others"];
var B = ["Soup", "Juice", "Water", "Others"];
var C = ["Soup", "Juice", "Coffee", "Tea", "Others"];
if (document.getElementById("meal").value == "A") {
var select = document.getElementById('category').options.length;
for (var i = 0; i < select; i++) {
document.getElementById('category').options.remove(i);
}
for (var i = 0; i < A.length; i++) {
var newSelect = document.createElement('option');
selectHTML = "<option value='" + A[i] + "'>" + A[i] + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('category').add(newSelect);
}
}
else if (document.getElementById("meal").value == "B") {
var select = document.getElementById('category').options.length;
for (var i = 0; i < select; i++) {
document.getElementById('category').options.remove(i);
}
for (var i = 0; i < B.length; i++) {
var newSelect = document.createElement('option');
selectHTML = "<option value='" + B[i] + "'>" + B[i] + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('category').add(newSelect);
}
}
else if (document.getElementById("project").value == "C") {
var select = document.getElementById('category').options.length;
for (var i = 0; i < select; i++) {
document.getElementById('category').options.remove(i);
}
for (var i = 0; i < C.length; i++) {
var newSelect = document.createElement('option');
selectHTML = "<option value='" + C[i] + "'>" + C[i] + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('category').add(newSelect);
}
}
}
</code></pre>
<hr>
<pre><code>HTML-
<select name="meal" id="meal" onchange="changecat();">
<option value="">Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select name="category" id="category">
<option value="">Select</option>
</select>
</code></pre> | 30,232,604 | 3 | 2 | null | 2015-05-14 07:53:20.477 UTC | 15 | 2022-08-30 11:48:15.293 UTC | 2015-05-14 10:11:51.523 UTC | null | 449,429 | null | 2,514,121 | null | 1 | 18 | javascript|html | 102,464 | <p>Hope this might help you.</p>
<p><a href="http://jsfiddle.net/k148pk76/1/" rel="nofollow noreferrer">JSFiddle : DEMO</a></p>
<p><strong>HTML</strong></p>
<pre><code><select name="meal" id="meal" onChange="changecat(this.value);">
<option value="" disabled selected>Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select name="category" id="category">
<option value="" disabled selected>Select</option>
</select>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>var mealsByCategory = {
A: ["Soup", "Juice", "Tea", "Others"],
B: ["Soup", "Juice", "Water", "Others"],
C: ["Soup", "Juice", "Coffee", "Tea", "Others"]
}
function changecat(value) {
if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
else {
var catOptions = "";
for (categoryId in mealsByCategory[value]) {
catOptions += "<option>" + mealsByCategory[value][categoryId] + "</option>";
}
document.getElementById("category").innerHTML = catOptions;
}
}
</code></pre>
<p><strong>There is a loop (for...in loop) in JavaScript, which would help you in this case</strong></p>
<blockquote>
<p>A for...in loop only iterates over enumerable properties. Objects
created from built–in constructors like Array and Object have
inherited non–enumerable properties from Object.prototype and
String.prototype, such as String's indexOf() method or Object's
toString() method. The loop will iterate over all enumerable
properties of the object itself and those the object inherits from its
constructor's prototype (properties closer to the object in the
prototype chain override prototypes' properties).</p>
</blockquote>
<p>In each iteration one property from object is assigned to variable-name and this loop continues till all the properties of the object are exhausted.</p>
<p>For more <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in" rel="nofollow noreferrer">Link</a></p> |
8,916,107 | Data.Text vs Data.ByteString.Char8 | <p>Can anyone explain the pros and cons to using <code>Data.Text</code>and <code>Data.ByteString.Char8</code> data types? Does working with ASCII-only text change these pros and cons? Do their lazy variants change the story as well?</p> | 8,916,190 | 1 | 0 | null | 2012-01-18 19:28:21.747 UTC | 10 | 2012-01-18 19:39:30.2 UTC | null | null | null | null | 239,916 | null | 1 | 22 | haskell|text|bytestring | 2,915 | <p><code>Data.ByteString.Char8</code> provides functions to treat <code>ByteString</code> values as sequences of 8-bit ASCII characters, while <code>Data.Text</code> is an independent type supporting the entirety of Unicode.</p>
<p><code>ByteString</code> and <code>Text</code> are essentially the same, as far as representation goes — strict, unboxed arrays with lazy variants based on lists of strict chunks. The main difference is that <code>ByteString</code> stores octets (i.e. <code>Word8</code>s), while <code>Text</code> stores <code>Char</code>s, encoded in UTF-16.</p>
<p>If you're working with ASCII-only text, then using <code>Data.ByteString.Char8</code> will probably be faster than <code>Text</code>, and use less memory; however, you should ask yourself whether you're <em>really</em> sure that you're only ever going to work with ASCII. Basically, in 99% of cases, using <code>Data.ByteString.Char8</code> over <code>Text</code> is a speed hack — octets <em>aren't</em> characters, and any Haskeller can agree that using the <em>correct</em> type should be prioritised over raw, bare-metal speed. You should usually only consider it if you've profiled the program and it's a bottleneck. <code>Text</code> is well-optimised, and the difference will probably be negligible in most cases.</p>
<p>Of course, there are non-speed-related situations in which <code>Data.ByteString.Char8</code> is warranted. Consider a file containing data that is essentially binary, not text, but separated into lines; using <a href="http://hackage.haskell.org/packages/archive/bytestring/latest/doc/html/Data-ByteString-Char8.html#v:lines" rel="noreferrer"><code>lines</code></a> is completely reasonable. Additionally, it's entirely conceivable that an integer might be encoded in ASCII decimal in the context of a binary format; using <a href="http://hackage.haskell.org/packages/archive/bytestring/latest/doc/html/Data-ByteString-Char8.html#v:readInt" rel="noreferrer"><code>readInt</code></a> would make perfect sense in that case.</p>
<p>So, basically:</p>
<ol>
<li><code>Data.ByteString.Char8</code>: For pure ASCII situations where performance is paramount, and to handle "almost-binary" data that has some ASCII components.</li>
<li><code>Data.Text</code>: Text, including <em>any</em> situation where there's the slightest possibility of something other than ASCII being used.</li>
</ol> |
8,723,229 | How to generate unique object id in mongodb | <p>When I use Mongodb with Java, I want to generate Object id at clients. Before I insert a record, however, I have to query mongodb first to make sure that the id generated by ObjectId() method is unique. Is there any way that I can generate unique object id without accessing mongodb twice?</p> | 8,723,315 | 3 | 0 | null | 2012-01-04 07:07:03.25 UTC | 4 | 2017-03-18 18:00:35.647 UTC | 2012-01-04 07:09:35.207 UTC | null | 125,816 | null | 1,664,669 | null | 1 | 37 | java|mongodb | 111,982 | <p>Object IDs are not like sequential ids you use in a RDMS. If they are properly generated according to the <a href="http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-BSONObjectIDSpecification">Object ID specification</a> you will not need to worry about them being unique.</p>
<p>All you have to do is ensure you always create a new Object ID rather than reusing them.</p> |