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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,128,444 | How does Git(Hub) handle possible collisions from short SHAs? | <p>Both Git and GitHub display short versions of SHAs -- just the first 7 characters instead of all 40 -- and both Git and GitHub support taking these short SHAs as arguments.</p>
<p>E.g. <code>git show 962a9e8</code></p>
<p>E.g. <a href="https://github.com/joyent/node/commit/962a9e8">https://github.com/joyent/node/commit/962a9e8</a></p>
<p>Given that the possibility space is now orders of magnitude lower, "just" <a href="http://www.google.com/search?q=16%5E7">268 million</a>, how do Git and GitHub protect against collisions here? And how do they handle them?</p> | 7,128,816 | 3 | 3 | null | 2011-08-19 23:32:21.093 UTC | 12 | 2018-04-25 07:45:49.513 UTC | null | null | null | null | 132,978 | null | 1 | 64 | git|cryptography|github|sha | 14,892 | <p>These short forms are just to simplify visual recognition and to make your life <a href="http://git-scm.com/book/en/Git-Tools-Revision-Selection">easier</a>. Git doesn't really truncate anything, internally everything will be handled with the complete value. You can use a partial SHA-1 at your convenience, though:</p>
<blockquote>
<p>Git is smart enough to figure out what commit you meant to type if you provide the first few characters, as long as your partial SHA-1 is at least four characters long and unambiguous — that is, only one object in the current repository begins with that partial SHA-1.</p>
</blockquote> |
7,541,767 | How can I show a Balloon Tip over a textbox? | <p>I have a C# WPF application using XAML and MVVM. My question is: How can I show a balloon tooltip above a text box for some invalid data entered by the user?</p>
<p>I want to use Microsoft's <a href="http://msdn.microsoft.com/en-us/library/aa511451.aspx" rel="noreferrer">native balloon control</a> for this. How would I implement this into my application?</p> | 7,649,590 | 4 | 2 | null | 2011-09-24 20:36:35.857 UTC | 9 | 2011-10-04 14:36:19.513 UTC | null | null | null | null | 334,053 | null | 1 | 13 | c#|wpf|mvvm|balloon-tip | 20,790 | <p>I've been searching for a better solution than the BalloonDecorator, and ran across the <a href="http://www.hardcodet.net/projects/wpf-notifyicon" rel="nofollow">http://www.hardcodet.net/projects/wpf-notifyicon</a> project. It is using the WinAPI at the lowest level, which might give you a head start on building your own solution. It appears that at first glance it could potentially solve it, but I haven't had enough time to verify that the BalloonTip can be made to behave as you've described.</p>
<p>Good luck on your project!</p> |
5,550,911 | Create array variable | <p>I wanted to create this kind of output</p>
<pre><code>var s1 = [['Sony',7],['Samsung',5],['LG',8]];
</code></pre>
<p>so that I could use it to pass on my graph as a variable</p>
<p>out from the result of my ajax</p>
<pre><code>success: function(data){
//code to extract the data value here
var s1= need to create the data here
$.jqplot('chart',[s1],{ blah blah blah
}
</code></pre>
<p>"data" in the success function returns this table layout</p>
<pre><code><table id="tblResult">
<tr class="tblRows">
<td class="clsPhone">Sony</td><td class="clsRating">7</td>
</tr>
<tr class="tblRows">
<td class="clsPhone">Samsung</td><td class="clsRating">5</td>
</tr>
<tr class="tblRows">
<td class="clsPhone">LG</td><td class="clsRating">8</td>
</tr>
</table>
</code></pre>
<p>can you please help me create the logic for this?</p>
<p>Thanks in advance</p>
<p><strong>EDIT:</strong>
I'm looking for a solution something like the following:</p>
<pre><code>var s1;
$(".tblRows").each(function(){
// here I don't know exactly on what to do
//s1.push($(".clsPhone").text(),$(".clsRating").text()));
});
// all I wanted is to make the resul s1=[['Sony',7],['Samsung',5],['LG',8]];
</code></pre>
<p>because jqplot requires this kind of parameter</p>
<pre><code>s1=[['Sony',7],['Samsung',5],['LG',8]];
$.jqplot('chart',[s1],{
renderer:$.jqplot.PieRenderer,
rendererOptions:{
showDataLabels:true,
dataLabelThreshold:1
}
}
});
</code></pre>
<p>so I'm looking for a way to create a the value for the variable s1 out from the data
could this be possible?</p> | 5,551,267 | 2 | 4 | null | 2011-04-05 11:14:43.787 UTC | 1 | 2020-07-28 16:40:53.01 UTC | 2020-07-28 16:40:53.01 UTC | null | 6,950,238 | null | 249,580 | null | 1 | 1 | jquery|variables|multidimensional-array|jqplot | 52,760 | <pre><code>var s1 = [];
$(".tblRows").each(function(){
// create a temp array for this row
var row = [];
// add the phone and rating as array elements
row.push($(this).find('.clsPhone').text());
row.push($(this).find('.clsRating').text());
// add the temp array to the main array
s1.push(row);
});
</code></pre> |
1,701,788 | How to convert string[] to ArrayList? | <p>I have an array of strings. How can I convert it to System.Collections.ArrayList?</p> | 1,701,807 | 4 | 2 | null | 2009-11-09 15:35:42.133 UTC | 5 | 2017-02-15 08:59:29.357 UTC | null | null | null | null | 187,644 | null | 1 | 21 | c#|.net | 62,533 | <pre><code>string[] myStringArray = new string[2];
myStringArray[0] = "G";
myStringArray[1] = "L";
ArrayList myArrayList = new ArrayList();
myArrayList.AddRange(myStringArray);
</code></pre> |
1,676,362 | JavaScript variable binding and loop | <p>Consider such loop:</p>
<pre><code>for(var it = 0; it < 2; it++)
{
setTimeout(function() {
alert(it);
}, 1);
}
</code></pre>
<p>The output is:</p>
<pre><code>=> 2
=> 2
</code></pre>
<p>I would like it to be: 0, 1. I see two ways to fix it:</p>
<p>Solution # 1.</p>
<p>This one based on the fact that we can pass data to setTimeout.</p>
<pre><code>for(var it = 0; it < 2; it++)
{
setTimeout(function(data) {
alert(data);
}, 1, it);
}
</code></pre>
<p>Solution # 2.</p>
<pre><code>function foo(data)
{
setTimeout(function() {
alert(data);
}, 1);
}
for(var it = 0; it < 2; it++)
{
foo(it);
}
</code></pre>
<p>Are there any other alternatives?</p> | 1,676,422 | 4 | 0 | null | 2009-11-04 20:20:46.257 UTC | 5 | 2017-09-10 17:13:45.993 UTC | 2009-11-04 23:14:56.117 UTC | null | 1,831 | null | 62,192 | null | 1 | 31 | javascript|loops|closures|scope | 15,729 | <p>Not really anything more than the two ways that you have proposed, but here's another</p>
<pre><code>for(var it = 0; it < 2; it++)
{
(function() {
var m = it;
setTimeout(function() {
alert(m);
}, 1);
})();
}
</code></pre>
<p>Essentially, you need to capture the variable value in a closure. This method uses an immediately invoked anonymous function to capture the outer variable value <code>it</code> in a local variable <code>m</code>.</p>
<p>Here's a <strong><a href="http://jsbin.com/esozo" rel="noreferrer">Working Demo</a></strong> to play with. add <strong>/edit</strong> to the URL to see the code</p> |
72,543,728 | Xcode 14 deprecates bitcode - but why? | <p><a href="https://developer.apple.com/documentation/Xcode-Release-Notes/xcode-14-release-notes" rel="noreferrer">Xcode 14 Beta release notes</a> are out, all thanks to the annual WWDC.</p>
<p>And alas, the Bitcode is now deprecated, and you'll get a warning message if you attempt to enable it.</p>
<p>And I was wondering, why has this happened? Was there any downside to using Bitcode? Was it somehow painful for Apple to maintain it? And how will per-iPhone-model compilation operate now?</p> | 73,219,854 | 4 | 2 | null | 2022-06-08 10:00:44.557 UTC | 11 | 2022-09-17 15:11:41.813 UTC | 2022-09-06 17:32:54.65 UTC | null | 819,340 | null | 9,353,387 | null | 1 | 41 | ios|xcode|bitcode|xcode14 | 6,883 | <p>Bitccode is actually just the LLVM intermediate language. When you compile source code using the LLVM toolchain, source code is translated into an intermediate language, named Bitcode. This Bitcode is then analyzed, optimized and finally translated to CPU instructions for the desired target CPU.</p>
<p>The advantage of doing it that way is that all LLVM based frontends (like clang) only need to translate source code to Bitcode, from there on it works the same regardless the source language as the LLVM toolchain doesn't care if the Bitcode was generated from C, C++, Obj-C, Rust, Swift or any other source language; once there is Bitcode, the rest of the workflow is always the same.</p>
<p>One benefit of Bitcode is that you can later on generate instructions for another CPU without having to re-compile the original source code. E.g. I may compile a C code to Bitcode and have LLVM generate a running binary for x86 CPUs in the end. If I save the Bitcode, however, I can later on tell LLVM to also create a running binary for an ARM CPU from that Bitcode, without having to compile anything and without access to the original C code. And the generated ARM code will be as good as if I had compiled to ARM from the very start.</p>
<p>Without the Bitcode, I would have to convert x86 code to ARM code and such a translation produces way worse code as the original intent of the code is often lost in the final compilation step to CPU code, which also involves CPU specific optimizations that make no sense for other CPUs, whereas Bitcode retains the original intent pretty well and only performs optimization that all CPUs will benefit from.</p>
<p>Having the Bitcode of all apps allowed Apple to re-compile that Bitcode for a specific CPU, either to make an App compatible with a different kind of CPU or an entirely different architecture or just to benefit from better optimizations of newer compiler versions. E.g. if Apple had tomorrow shiped an iPhone that uses a RISC-V instead of an ARM CPU, all apps with Bitcode could have been re-compiled to RISC-V and would natively support that new CPU architecture despite the author of the app having never even heard of RISC-V.</p>
<p>I think that was the idea why Apple wanted all Apps in Bitcode format. But that approach had issues to begin with. One issue is that Bitcode is not a frozen format, LLVM updates it with every release and they do not guarantee full backward compatibility. Bitcode has never been intended to be a stable representation for permanent storage or archival. Another problem is that you cannot use assembly code as no Bitcode is emitted for assembly code. Also you cannot use pre-built third party libraries that come without Bitcode.</p>
<p>And last but not least: AFAIK Apple has never used any of the Bitcode advantages so far. Despite requiring all apps to contain Bitcode in the past, the apps also had to contain pre-build fat binaries for all supported CPUs and Apple would always only just ship that pre-build code. E.g. for iPhones you used to once have a 32 Bit ARMv7 and a 64 Bit ARM64 version, as well as the Bitcode and during app thinning, Apple would remove either the 32 Bit or the 64 Bit version, as well as the Bitcode, and then ship whats left over. Fine, but they could have done so also if no Bitcode was there. Bitcode is not required to thin out architectures of a fat binary!</p>
<p>Bitcode would be required to re-build for a different architecture but Apple has never done that. No 32 Bit app magically became 64 bit by Apple re-compiling the Bitcode. And no 64 bit only app was magically available for 32 bit systems as Apple re-compiled the Bitcode on demand. As a developer, I can assure you, the iOS App Store always delivered exactly the binary code that you have built and signed yourself and never any code that Apple has themselves created from the Bitcode, so nothing was server side optimized. Even when Apple switched from Intel to M1, no macOS app magically got converted to native ARM, despite that would have been possible for all x86 apps in the app store for that Apple had the Bitcode. Instead Apple still shipped the x86 version and let it run in Rosetta 2.</p>
<p>So imposing various disadvantages onto developers by forcing all code to be available as Bitcode and then not using any of the advantages Bitcode would give you kinda makes the whole thing pointless. And now that all platforms migrated to ARM64 and in a couple of years there won't even be fat binaries anymore (once x86 support for Mac has been dropped), what's the point of continuing with that stuff? I guess Apple took the chance to bury that idea once and for all. Even if they one day add RISC-V to their platforms, developers can still ship fat binaries containing ARM64 and RISC-V code at the same time. This concept works well enough, is way simpler, and has no downsides other than "bigger binaries" and that's something server side app thinning can fix, as during download only the code for the current platform needs to be included.</p> |
10,426,501 | How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu | <p>I have been through lots of forums and checked various posts on similar topic but non seems to work out for me. </p>
<p>I have freshly installed XAMPP 1.7.7 on my Ubuntu 11.10 Operating system. Everything is running except for the phpMyAdmin. </p>
<p>Upon hitting: <a href="http://localhost/phpmyadmin" rel="noreferrer">http://localhost/phpmyadmin</a>, I am getting the following error: </p>
<blockquote>
<p>MySQL said: </p>
<pre><code>#2002 - The server is not responding
(or the local MySQL server's socket is not correctly configured)
Connection for controluser as defined in your configuration failed.
</code></pre>
</blockquote>
<p>When i am starting the services with: <strong>sudo /opt/lampp/lampp start</strong><br>
I am getting the following:</p>
<blockquote>
<p>XAMPP: Another web server daemon is already running.<br>
XAMPP: Another MySQL daemon is already running.<br>
XAMPP: Another FTP daemon is already running.<br>
XAMPP for Linux
started.</p>
</blockquote>
<p>Any suggestions would be greatly appreciated.</p> | 10,443,916 | 11 | 2 | null | 2012-05-03 06:52:20.053 UTC | 10 | 2018-11-17 17:59:07.557 UTC | 2012-05-04 06:28:35.523 UTC | null | 547,894 | null | 547,894 | null | 1 | 22 | mysql|ubuntu|phpmyadmin|xampp|mysql-error-2002 | 102,159 | <p>It turns out that the solution is to stop all the related services and solve the “Another daemon is already running” issue. </p>
<p>The commands i used to solve the issue are as follows: </p>
<pre><code>sudo /opt/lampp/lampp stop
sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop
</code></pre>
<p>Or, you can also type instead: </p>
<pre><code>sudo service apache2 stop
sudo service mysql stop
</code></pre>
<p>After that, we again start the lampp services:</p>
<pre><code>sudo /opt/lampp/lampp start
</code></pre>
<p>Now, there must be no problems while opening: </p>
<pre><code>http://localhost
http://localhost/phpmyadmin
</code></pre> |
10,451,482 | Can I refresh an XML comment in Visual Studio to reflect parameters that have changed? | <p>If I write the function:</p>
<pre><code> public static uint FindAUint(double firstParam)
{
}
</code></pre>
<p>I can generate the xml comments by typing '///', it gives :</p>
<pre><code> /// <summary>
/// *Here I type the summary of the method*
/// </summary>
/// <param name="firstParam">*Summary of param*</param>
/// <returns>*Summary of return*</returns>
public static uint FindAUint(double firstParam)
{
}
</code></pre>
<p>If I then decide I need to update my method to be:</p>
<pre><code> /// <summary>
/// *Here I type the summary of the method*
/// </summary>
/// <param name="firstParam">*Summary of param*</param>
/// <returns>*Summary of return*</returns>
public static uint FindAUint(double firstParam,double newParam, double newParam2)
{
}
</code></pre>
<p>Is there a way to get visual studio to add the new params into the xml without losing the descriptions of the previous ones?</p>
<p>(I should mention I am using Visual Studio Express; I wouldn't put it past Microsoft to disallow the feature in the Express version though)</p> | 10,451,511 | 3 | 2 | null | 2012-05-04 15:08:34.583 UTC | 4 | 2021-12-30 03:48:52.51 UTC | 2012-05-04 15:14:22.19 UTC | null | 334,053 | null | 1,029,916 | null | 1 | 33 | c#|visual-studio-2010|comments | 8,455 | <p>Check out <a href="http://submain.com/products/ghostdoc.aspx">GhostDoc</a>. It is a Visual Studio extension that will generate your XML comments for you.</p> |
7,420,780 | What is a constant reference? (not a reference to a constant) | <p>Why do constant references not behave the same way as constant pointers, so that I can actually change the object they are pointing to? They really seem like another plain variable declaration. Why would I ever use them?</p>
<p>This is a short example that I run which compiles and runs with no errors:</p>
<pre><code>int main (){
int i=0;
int y=1;
int&const icr=i;
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99; // Can assign another value but the value is not assigned to y...
int x=9;
icr=x;
cout<<"icr: "<<icr<<", y:"<<y<<endl;
}
</code></pre> | 7,432,351 | 7 | 5 | null | 2011-09-14 17:55:11.99 UTC | 30 | 2022-04-17 10:38:01.497 UTC | 2022-04-17 10:38:01.497 UTC | null | 3,924,118 | null | 840,997 | null | 1 | 72 | c++|reference|constants | 139,022 | <p>The clearest answer.
<strong><a href="https://isocpp.org/wiki/faq/const-correctness#const-ref-nonsense" rel="noreferrer">Does “X& const x” make any sense?</a></strong></p>
<blockquote>
<p><strong>No, it is nonsense</strong></p>
<p>To find out what the above declaration means, read it right-to-left:
“x is a const reference to a X”. But that is redundant — references
are always const, in the sense that you can never reseat a reference
to make it refer to a different object. Never. With or without the
const.</p>
<p>In other words, “X& const x” is functionally equivalent to “X& x”.
Since you’re gaining nothing by adding the const after the &, you
shouldn’t add it: it will confuse people — the const will make some
people think that the X is const, as if you had said “const X& x”.</p>
</blockquote> |
7,408,068 | tmux: hangs and do not load, and do not respond to any option command | <p>I have installed tmux from source on my localspace in Fedora. It was working nicely so far. But suddenly can not run it anymore, when run tmux, it just halts. Tried different command options like ls-sessions, none works. Killed all the processes of my user, deleted all the files of tmux and <code>libevnet</code>, and reinstalled them again from scratch. Still same, and tmux command in terminal just freezes without any actual error. </p> | 7,436,243 | 8 | 1 | null | 2011-09-13 20:29:10.807 UTC | 11 | 2019-02-22 15:49:44.907 UTC | 2015-10-01 15:59:47.18 UTC | null | 1,245,190 | null | 501,337 | null | 1 | 38 | linux|tmux | 37,521 | <p>Thanks.
I found the problem. The tmux process were in D state, and I had no choice but to reboot the system.
The problem came from kerberos ticket expiring after a while. And find a scripts that solves this problem:
<a href="https://iain.cx/src/ktmux/" rel="nofollow">https://iain.cx/src/ktmux/</a></p> |
7,348,150 | Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work | <p>I want my <code>DatePicker</code> and the button to be invisible in the begining. And when I press my magic button I want to setVisibility(View.Visible);</p>
<p>The problem here is when I <code>setVisibility(View.GONE)</code> or <code>setVisibility(View.INVISIBLE)</code> nothing changes and the component is still visible.</p>
<pre><code>final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
final Button btn2 = (Button) findViewById(R.id.btnDate2);
dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
TextView txt2 = (TextView) findViewById(R.id.txt2);
txt2.setText("You selected " + dp2.getDayOfMonth()
+ "/" + (dp2.getMonth() + 1) + "/" + dp2.getYear());
}
});
</code></pre> | 7,348,547 | 11 | 0 | null | 2011-09-08 12:39:27.29 UTC | 16 | 2020-11-13 11:19:25.327 UTC | 2017-10-20 06:24:35.23 UTC | null | 1,083,957 | null | 925,353 | null | 1 | 70 | java|android|android-layout|android-view|android-datepicker | 303,735 | <p>I see quite a few things wrong. For starters, you don't have your magic button defined and there is no event handler for it.</p>
<p>Also you shouldn't use:</p>
<pre><code>dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
</code></pre>
<p>Use only one of the two. From <a href="http://developer.android.com/reference/android/view/View.html" rel="noreferrer">Android documentation</a>:</p>
<blockquote>
<p>View.GONE This view is invisible, and it doesn't take any space for
layout purposes. </p>
<p>View.INVISIBLE This view is invisible, but it still
takes up space for layout purposes.</p>
</blockquote>
<p>In your example, you are overriding the <code>View.GONE</code> assignment with the <code>View.INVISIBLE</code> one.</p>
<hr>
<p>Try replacing:</p>
<pre><code>final DatePicker dp2 = new DatePicker(this)
</code></pre>
<p>with:</p>
<pre><code>DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
</code></pre>
<p>Similarly for other widgets:</p>
<pre><code> public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final DatePicker dp2 = new DatePicker(this);
final Button btn2 = new Button(this);
final Button magicButton = new Button(this);
final TextView txt2 = new TextView(TestActivity.this);
dp2.setVisibility(View.GONE);
btn2.setVisibility(View.GONE);
btn2.setText("set Date");
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
txt2.setText("You selected "
+ dp2.getDayOfMonth() + "/" + (dp2.getMonth() + 1)
+ "/" + dp2.getYear());
}
});
magicButton.setText("Magic Button");
magicButton.setOnClickListener(new View.OnClickListener()
public void onClick(View arg0) {
dp2.setVisibility(View.VISIBLE);
btn2.setVisibility(View.VISIBLE);
}
});
ll.addView(dp2);
ll.addView(btn2);
ll.addView(magicButton);
ll.addView(txt2);
setContentView(ll);
}
</code></pre> |
7,389,944 | $this vs $(this) in jQuery | <p>I've seen some discussions on SO regarding <code>$(this)</code> vs <code>$this</code> in jQuery, and they make sense to me. (See <a href="https://stackoverflow.com/questions/1051782/jquery-this-vs-this">discussion here</a> for an example.)</p>
<p>But what about the snippet below, from the jQuery website plugin tutorial showing how chainability works?</p>
<pre><code>(function ($) {
$.fn.lockDimensions = function (type) {
return this.each(function () {
var $this = $(this);
if (!type || type == 'width') {
$this.width($this.width());
}
if (!type || type == 'height') {
$this.height($this.height());
}
});
};
})(jQuery);
</code></pre>
<p>What does <code>$this</code> represent above? Just when I think I have it figured out ...</p> | 7,389,987 | 15 | 10 | null | 2011-09-12 15:03:40.507 UTC | 28 | 2015-06-24 08:48:06.38 UTC | 2017-05-23 11:46:19.453 UTC | null | -1 | null | 172,617 | null | 1 | 77 | javascript|jquery | 93,885 | <p><code>$this</code> is just an ordinary variable. The <code>$</code> character is a valid character in variable names, so <code>$this</code> acts the same as any other non-reserved variable name. It's functionally identical to calling a variable <code>JellyBean</code>.</p> |
14,059,429 | CSS: Full Size background image | <p>Trying to get full size background image with:</p>
<pre><code>html {
height: 100%;
background:url('../img/bg.jpg') no-repeat center center fixed;
background-size: cover;
}
</code></pre>
<p>It's showing the background image with correct width but height gets stretched.
I tried various options like</p>
<pre><code>html {
background:url('../img/bg.jpg') no-repeat center center fixed;
background-size: 100% auto;
-webkit-background-size: 100% auto;
-moz-background-size: 100% auto;
-o-background-size: 100% auto;
</code></pre>
<p>}</p>
<p>removing <code>height: 100%</code></p>
<p>but none of them worked.</p> | 14,059,876 | 6 | 4 | null | 2012-12-27 18:29:51.18 UTC | 5 | 2017-06-21 01:53:22.027 UTC | null | null | null | null | 1,101,083 | null | 1 | 18 | css | 50,473 | <p>Your screen is obviously a different shape to your image. This is not uncommon, and you should always cater to this case even if your screen is the same shape (aspect ratio), because other people's screens will not always be. To deal with this, you have only one of three options:</p>
<ul>
<li>You can choose to completely cover the screen with your image, but not distort the image. In this case, you will need to cope with the fact that edges of your image will be cut off. For this case, use: <code>background-size: cover</code></li>
<li>You can choose to make sure the entire image is visible, and not distorted. In this case, you'll need to cop with the fact that some of the background will not be covered by your image. The best way to deal with this is to give the page a solid background, and design your image to fade into the solid (although this is not always possible). For this case, use: <code>background-size: contain</code></li>
<li>You can choose to cover the entire screen with your background, and distort it to fit. For this case, use: <code>background-size: 100% 100%</code></li>
</ul> |
14,134,949 | jquery client side validation not working in MVC3 partial view | <p>I could not seem get client side validation work with the following partial view. This view is inside divTSettings div in the parent view. Tried lots of things from stackoverflow and other sites, nothing seems to work. Any ideas? </p>
<pre><code><script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
@using (Ajax.BeginForm("CreateT", "TAdmin", null,
new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "divTSettings"},
new { id = "CreateTForm" }))
{
<div>
<label>Name:</label>
<input type="text" name="tName" id="tName"/>
@Html.ValidationMessage("tName")
<input type="submit" value="Submit"/>
</div>
}
<script type="text/javascript">
$(function() {
$('#CreateTForm').validate({
rules: {
tName: {
required: true
}
},
messages: {
tName: {
required: 'Name required'
}
}
});
$("#CreateTForm").removeData("validator");
$("#CreateTForm").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#CreateTForm");
});
</script>
</code></pre> | 14,135,013 | 2 | 0 | null | 2013-01-03 07:52:04.67 UTC | 14 | 2018-03-09 13:40:52.933 UTC | 2013-01-04 19:15:40.493 UTC | null | 594,235 | null | 1,246,417 | null | 1 | 20 | jquery|asp.net-mvc-3|jquery-validate | 18,219 | <blockquote>
<p>Any ideas?</p>
</blockquote>
<p>Yes, the very first thing you should do is to get rid of all those <code><script></code> tags from your partial view. Partial views should not contain any scripts. Partial views should contain only markup. I have repeated this many times and still see people putting scripts in-there. Scripts should be registered either in your Layout or the main View in which you have rendered the partial, probably by overriding some scripts section registered in your Layout so that all scripts get inserted into the end of your HTML document, just before the closing <code></body></code> tag. That's where they belong.</p>
<p>OK, now to the actual problem: unobtrusive validation doesn't work out-of-the-box with dynamically added elements to the DOM - such as for example sending an AJAX request to the server which returns a partial view and this partial view is then injected into the DOM.</p>
<p>In order to make it work you need to register those newly added elements with the unobtrusive validation framework. To do this you need to call the <code>$.validator.unobtrusive.parse</code> on the newly added elements:</p>
<pre><code>$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</code></pre>
<p>You should put this code inside the AJAX success handler that is injecting the partial into your DOM. Once you have injected the new elements simply call this function.</p>
<p>And if you are not writing your AJAX requests manually with jQuery ($.ajax, $.post, ...) but are relying on some Ajax.BeginForm and Ajax.ActionLink helpers do the job for you, you will need to subscribe to the OnSuccess callback in the AjaxOptions and put this code in there.</p> |
13,905,407 | Append unit type to the result of a calculation in Sass | <p>I've been refactoring my CSS to a SASS style sheet recently. I'm using the <a href="http://visualstudiogallery.msdn.microsoft.com/2b96d16a-c986-4501-8f97-8008f9db141a" rel="noreferrer">Mindscape Web Workbench extension</a> for VS2012, which re-generates the CSS each time you save your SCSS. I started with code similar to this:</p>
<pre><code>/* Starting point: */
h1 { font-size: 1.5em; /* 24px ÷ 16px */ }
</code></pre>
<p>Then I tried to refactor it first to this:</p>
<pre><code>/* Recfator: */
h1 { font-size: (24px / 16px)em; }
</code></pre>
<p>But this unfortunately produces:</p>
<pre><code>/* Result: */
h1 { font-size: 1.5 em; } /* doesn't work, gives "1.5 em" */
</code></pre>
<p>Notice the <strong>extra space</strong>, which I don't want there. I've tried several alternatives, here are a few:</p>
<pre><code>h1 { font-size: (24/16)em; } /* doesn't work, gives "1.5 em" */
h2 { font-size: 24 / 16em; } /* doesn't work, gives "24/16em" */
h3 { font-size: (24px / 16px) * 1em; } /* works but "* 1 em" feels unnecessary */
h4 { font-size: (24em) / 16; } /* works, but without "px" it's not
really conveying what I mean to say */
</code></pre>
<p>I've also tried these variants with variables (because I want those anyways), but that didn't change the situation much. To keep the examples in this question sleek I've left out variables. However, I'd happily accept a solution that relies on using variables (in a clean way).</p>
<p>I've gone through the <a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#division-and-slash" rel="noreferrer">relevant SASS documenation on '/'</a>, and appreciate that this is a tough one for SASS because the '/' character already has a meaning in basic CSS. Either way, I was hoping for a clean solution. Am I missing something here?</p>
<p>PS. <a href="http://erskinelabs.com/calculating-ems-scss/" rel="noreferrer">This blogpost</a> does offer one solution, using a user defined function. That seems a bit heavy-weight though, so I'm interested if there's "cleaner" solutions in line with my attempts above. If someone can explain the "function approach" is the better (or even only) solution then I'll accept that as an answer too.</p>
<p>PS. <a href="https://stackoverflow.com/q/15513395/419956">This related question</a> seems to be about the same thing, though that one specically wants to do further calculations. <a href="https://stackoverflow.com/a/15514279/419956">The accepted answer there</a> is my third workaround (multiplying by <code>1em</code>), but I'd love to know if there's a different (cleaner) way if I'm willing to forego the ability to do further calculations. Perhaps the method mentioned in said question ("interpolation") is useful for me?</p>
<hr>
<p><strong><em>Bottom line:</strong> how can you cleanly append the unit type (e.g. <code>em</code>) to the result of a calculation in SASS?</em></p> | 13,905,609 | 5 | 12 | null | 2012-12-16 20:56:56.373 UTC | 14 | 2020-12-15 18:45:07.14 UTC | 2020-12-15 18:45:07.14 UTC | null | 2,803,565 | null | 419,956 | null | 1 | 70 | css|sass | 39,780 | <p><strong>The only way to add a unit to a number is via arithmetic</strong>.</p>
<p>To perform operations like concatenation (eg. <code>1 + px</code>) or interpolation (eg. <code>#{1}px</code>) will only create a <strong>string</strong> that <em>looks</em> like a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you <em>should not do this</em>.</p>
<p>More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:</p>
<pre><code>$foo: 1; // a number
$foo-percent: $foo + '%'; // a string
.bar {
color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}
</code></pre>
<blockquote>
<p>$amount: "1%" is not a number for `darken'</p>
</blockquote>
<p>There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:</p>
<pre><code>$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%
.bar {
color: darken(blue, $foo-percent); //works!
}
</code></pre>
<p>Output:</p>
<pre><code>.bar {
color: #0000fa;
}
</code></pre>
<p>Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the <code>box-flex</code> property. <code>flex: auto</code> or <code>flex: 30em</code> cannot be made compatible with the comparable <code>box-flex</code> property, so the mixin doesn't bother trying)</p>
<pre><code>@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
@if $legacy and unitless(nth($value, 1)) {
@include legacy-flex(nth($value, 1));
}
@include experimental(flex, $value, flex-support-common()...);
}
@mixin legacy-flex($value: 0) {
@include experimental(box-flex, $value, $box-support...);
}
</code></pre> |
29,987,969 | How to load a script only in IE | <p>I need a particular script to be triggered in Internet Explorer browsers Only!</p>
<p>I've tried this:</p>
<pre><code><!--[if IE]>
<script></script>
<![endif]-->
</code></pre>
<p>Unfortunately this actually stops the script from being loaded.</p>
<p>EDIT: For everyone asking why I need this: IE makes scrolling extremely jumpy when using some animations. In order to address this I need to implement a script that provides smooth scrolling to IE. I don't want to apply it to other browsers as they don't need it and this script although making the scrolling smoother also makes it a bit unnatural.</p> | 29,988,202 | 6 | 6 | null | 2015-05-01 13:42:13.82 UTC | 18 | 2022-05-28 07:46:14.693 UTC | 2015-05-01 16:15:35.587 UTC | null | 4,341,263 | null | 4,341,263 | null | 1 | 46 | javascript|internet-explorer|conditional-statements | 62,459 | <p>I'm curious why you specifically need to target IE browsers, but the following code should work if that really is what you need to do:</p>
<pre><code><script type="text/javascript">
if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))
document.write('<script src="somescript.js"><\/script>');
</script>
</code></pre>
<p>The first half of the Regex (<code>MSIE \d</code>) is for detecting Internet Explorer 10 and below. The second half is for detecting IE11 (<code>Trident.*rv:</code>).</p>
<p>If the browser's user agent string matches that pattern, it will append <code>somescript.js</code> to the page.</p> |
9,015,498 | Need Haar Casscades for Nose, Eyes & Lips(Mouth) | <p>I need Haar Cascades xml files for Mouth, Eyes & Nose. Do provide me useful links.</p>
<p>Any kind of help would be highly appreciated.</p> | 9,017,165 | 3 | 1 | null | 2012-01-26 08:31:57.43 UTC | 12 | 2017-09-23 07:30:08.14 UTC | null | null | null | null | 1,142,341 | null | 1 | 22 | opencv|face-detection|emgucv|emotion | 45,701 | <p>Look at this page: <a href="http://alereimondo.no-ip.org/OpenCV/34">http://alereimondo.no-ip.org/OpenCV/34</a></p>
<p>There are haar cascades for eyes, nose and mouth :)</p> |
44,492,197 | React Native ios build : Can't find node | <p>I have a prototype ready to go and the project is jammed with build:</p>
<blockquote>
<p>error: Can't find 'node' binary to build React Native bundle If you
have non-standard nodejs installation, select your project in Xcode,
find 'Build Phases' - 'Bundle React Native code and images' and change
NODE_BINARY to absolute path to your node executable (you can find it
by invoking 'which node' in the terminal)</p>
</blockquote>
<p>this feedback is helpless for me, i do have node with nvm. is this something related to bash?</p> | 44,494,828 | 12 | 3 | null | 2017-06-12 05:49:33.467 UTC | 25 | 2022-09-13 03:08:28.337 UTC | 2019-10-10 12:23:25.297 UTC | null | 5,660,517 | null | 6,263,936 | null | 1 | 68 | ios|node.js|react-native|build | 48,025 | <p>I found one
<a href="http://qiita.com/kztka/items/eca26d441461985d8397" rel="noreferrer">solution</a></p>
<p>First find your current node, in shell</p>
<pre><code>which node
</code></pre>
<p>then copy your node url to </p>
<pre><code>export NODE_BINARY=[your node path]
../node_modules/react-native/packager/react-native-xcode.sh to node_modules/react-native/scripts/react-native-xcode.sh
</code></pre>
<p><a href="https://i.stack.imgur.com/pwWA2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pwWA2.png" alt="enter image description here"></a></p> |
32,609,248 | setuptools: adding additional files outside package | <p>I have a <code>python</code> application that has a fixed layout which I cannot change. I would like to wrap it up using setuptools, e.g. write a <code>setup.py</code> script.</p>
<p>Using the official documentation, I was able to write a first template. However, the application in question uses a lot of additional data files that are not explicitly part of any package. Here's an example source tree:</p>
<pre><code>somepackage
__init__.py
something.py
data.txt
additionalstuff
moredata.txt
INFO.txt
</code></pre>
<p>Here's the trouble: The code in <code>something.py</code> reads the files <code>moredata.txt</code> and <code>INFO.txt</code>. For the former, I can monkeypatch the problem by adding an empty <code>additionalstuff/__init__.py</code> file to promote <code>additionalstuff</code> to a package and have it picked up by <code>setuptools</code>. But how could I possibly add <code>INFO.txt</code> to my <code>.egg</code>?</p>
<h1>Edit</h1>
<p>The proposed solutions using something along the lines of</p>
<pre><code>package_data = { '' : ['moredata.txt','INFO.txt']}
</code></pre>
<p>does not work for me because the files <code>moredata</code> and <code>INFO.txt</code> do not belong to a package, but are part of a separate folder that is only part of the module as a whole, not of any individual package.
As explained above, this could be fixed in the case of <code>moredata.txt</code> by adding a <code>__init__.py</code> file to <code>additionpythonalstuff</code>, thus promoting it to a package. However, this is not an elegant solution and does not work at all for <code>INFO.txt</code>, which lives in the top-level directory.</p>
<h1>Solution</h1>
<p>Based on the accepted answer, here's the solution</p>
<p>This is the <code>setup.py</code>:</p>
<pre><code>from setuptools import setup, find_packages
setup(
name='mytest',
version='1.0.0',
description='A sample Python project',
author='Test',
zip_safe=False,
author_email='[email protected]',
keywords='test',
packages=find_packages(),
package_data={'': ['INFO.txt', 'moredata.txt'],
'somepackage':['data.txt']},
data_files=[('.',['INFO.txt']),
('additionalstuff',['additionalstuff/moredata.txt'])],
include_package_data=True,
)
</code></pre>
<p>And this is the <code>MANIFEST.in</code>:</p>
<pre><code>include INFO.txt
graft additionalstuff
include somepackage/*.txt
</code></pre> | 32,610,786 | 2 | 4 | null | 2015-09-16 12:56:40.513 UTC | 6 | 2015-09-16 15:42:49.78 UTC | 2015-09-16 15:42:49.78 UTC | null | 2,657,641 | null | 2,657,641 | null | 1 | 34 | python|setuptools | 16,750 | <p>There is also <code>data_files</code></p>
<pre><code>data_files=[("yourdir",
["additionalstuff/moredata.txt", "INFO.txt"])],
</code></pre>
<p>Have a think about where you want to put those files. More info in the <a href="https://docs.python.org/3.3/distutils/setupscript.html#installing-additional-files" rel="noreferrer">docs</a>.</p> |
56,161,595 | How to use `async for` in Python? | <p>I mean what do I get from using <code>async for</code>. Here is the code I write with <code>async for</code>, <code>AIter(10)</code> could be replaced with <code>get_range()</code>.</p>
<p>But the code runs like sync not async.</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
async def get_range():
for i in range(10):
print(f"start {i}")
await asyncio.sleep(1)
print(f"end {i}")
yield i
class AIter:
def __init__(self, N):
self.i = 0
self.N = N
def __aiter__(self):
return self
async def __anext__(self):
i = self.i
print(f"start {i}")
await asyncio.sleep(1)
print(f"end {i}")
if i >= self.N:
raise StopAsyncIteration
self.i += 1
return i
async def main():
async for p in AIter(10):
print(f"finally {p}")
if __name__ == "__main__":
asyncio.run(main())
</code></pre>
<p>The result I excepted should be :</p>
<pre><code>start 1
start 2
start 3
...
end 1
end 2
...
finally 1
finally 2
...
</code></pre>
<p>However, the real result is:</p>
<pre><code>start 0
end 0
finally 0
start 1
end 1
finally 1
start 2
end 2
</code></pre>
<p>I know I could get the excepted result by using <code>asyncio.gather</code> or <code>asyncio.wait</code>. </p>
<p>But it is hard for me to understand what I got by use <code>async for</code> here instead of simple <code>for</code>.</p>
<p>What is the right way to use <code>async for</code> if I want to loop over several <code>Feature</code> object and use them as soon as one is finished. For example:</p>
<pre><code>async for f in feature_objects:
data = await f
with open("file", "w") as fi:
fi.write()
</code></pre> | 56,162,461 | 3 | 7 | null | 2019-05-16 05:49:59.927 UTC | 24 | 2022-06-27 14:07:45.597 UTC | null | null | null | null | 2,955,827 | null | 1 | 64 | python|asynchronous|python-asyncio | 53,055 | <blockquote>
<p>But it is hard for me to understand what I got by use <code>async for</code> here instead of simple <code>for</code>.</p>
</blockquote>
<p>The underlying misunderstanding is expecting <a href="https://docs.python.org/3/reference/compound_stmts.html#the-async-for-statement" rel="noreferrer"><code>async for</code></a> to automatically <em>parallelize</em> the iteration. It doesn't do that, it simply allows sequential iteration <em>over an async source</em>. For example, you can use <code>async for</code> to iterate over lines coming from a TCP stream, messages from a websocket, or database records from an async DB driver.</p>
<p>None of the above would work with an ordinary <code>for</code>, at least not without blocking the event loop. This is because <code>for</code> calls <a href="https://docs.python.org/3/library/stdtypes.html#iterator.__next__" rel="noreferrer"><code>__next__</code></a> as a blocking function and doesn't await its result. You cannot manually <code>await</code> elements obtained by <code>for</code> because <code>for</code> expects <code>__next__</code> to signal the end of iteration by raising <code>StopIteration</code>. If <code>__next__</code> is a coroutine, the <code>StopIteration</code> exception won't be visible before awaiting it. This is why <code>async for</code> was introduced, not just in Python, but also in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of" rel="noreferrer">other</a> <a href="https://boats.gitlab.io/blog/post/for-await-i/" rel="noreferrer">languages</a> with async/await and generalized <code>for</code>.</p>
<p>If you want to run the loop iterations in parallel, you need to start them as parallel coroutines and use <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.as_completed" rel="noreferrer"><code>asyncio.as_completed</code></a> or equivalent to retrieve their results as they come:</p>
<pre><code>async def x(i):
print(f"start {i}")
await asyncio.sleep(1)
print(f"end {i}")
return i
# run x(0)..x(10) concurrently and process results as they arrive
for f in asyncio.as_completed([x(i) for i in range(10)]):
result = await f
# ... do something with the result ...
</code></pre>
<p>If you don't care about reacting to results immediately as they arrive, but you need them all, you can make it even simpler by using <code>asyncio.gather</code>:</p>
<pre><code># run x(0)..x(10) concurrently and process results when all are done
results = await asyncio.gather(*[x(i) for i in range(10)])
</code></pre> |
24,911,238 | programmatically import .cer certificate into keystore | <p>How can I import a .p12 certificate from the classpath into the java keystore? First I used the InstallCert <a href="https://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java" rel="noreferrer">https://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java</a> and did some changes so the server certificate will be imported into the keystore in the java install directory. This works fine but now I want to load a certificate from my classpath.</p>
<p>EDIT: I just use a .cer certificate, see next answer</p> | 24,927,216 | 2 | 2 | null | 2014-07-23 13:03:11.583 UTC | 8 | 2020-08-05 03:45:51 UTC | 2014-07-24 07:11:08.413 UTC | null | 1,879,409 | null | 1,879,409 | null | 1 | 13 | java|keystore|pkcs#12|key-management | 19,858 | <p>The answer:</p>
<pre class="lang-java prettyprint-override"><code>InputStream certIn = ClassLoader.class.getResourceAsStream("/package/myCert.cer");
final char sep = File.separatorChar;
File dir = new File(System.getProperty("java.home") + sep + "lib" + sep + "security");
File file = new File(dir, "cacerts");
InputStream localCertIn = new FileInputStream(file);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(localCertIn, passphrase);
if (keystore.containsAlias("myAlias")) {
certIn.close();
localCertIn.close();
return;
}
localCertIn.close();
BufferedInputStream bis = new BufferedInputStream(certIn);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
Certificate cert = cf.generateCertificate(bis);
keystore.setCertificateEntry("myAlias", cert);
}
certIn.close();
OutputStream out = new FileOutputStream(file);
keystore.store(out, passphrase);
out.close();
</code></pre>
<p>For Java Web Start don't use the ClassLoader, use the Class itself:</p>
<pre class="lang-java prettyprint-override"><code>InputStream certIn = Certificates.class.getResourceAsStream("/package/myCert.cer");
</code></pre> |
379,977 | Online Assembly language resources | <p>does anyone have any resources for learning assembly language on x86? I'm trying to debug a program in MSVC++6 and frequently come across assembly (like stepping into memcpy).. Previously I just ignored these but memcpy keeps throwing exceptions and I need to find out why..</p>
<p>Any help would be appreciated :)</p>
<p>EDIT:Wow, lots of great resources.. I wish I could mark everything as accepted answer :P</p>
<p>HINT: combine anyone? :P</p>
<p>New edit: I just looked through the answers, and these seemed the best:</p>
<p>Aseraphim's post <a href="http://developer.intel.com/design/pentiumii/manuals/243191.htm" rel="noreferrer">specific to intel x86</a></p>
<p>jkchong's post <a href="http://www.drpaulcarter.com/pcasm/" rel="noreferrer">for a more introductory text</a></p> | 380,003 | 5 | 2 | null | 2008-12-19 02:42:28.627 UTC | 12 | 2012-03-01 00:29:46.377 UTC | 2009-01-08 02:21:21.31 UTC | Greg Hewgill | 893 | krebstar | 29,482 | null | 1 | 9 | visual-c++|assembly|x86 | 1,167 | <p>If you just need to understand what each instruction does, the reference manual for the IA-32 (x86) & IA64 instruction sets are located <a href="http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html" rel="nofollow noreferrer">here</a>.</p> |
162,149 | Avoid being blocked by web mail companies for mass/bulk emailing? | <p>Our company is sending out a lot of emails per day and planning to send even more in future. (thousands) Also there are mass mailouts as well in the ten thousands every now and then.</p>
<p>Anybody has experience with hotmail, yahoo (web.de, gmx.net) and similar webmail companies blocking your emails because "too many from the same source in a period of time" have been sent to them?</p>
<p>What can be done about it? Spreading email mailouts over a whole day/night? At what rate?</p>
<p>(we are talking about legal emailing just to make sure...)</p> | 162,320 | 6 | 1 | null | 2008-10-02 13:06:05.47 UTC | 18 | 2013-04-29 14:30:25.793 UTC | 2010-09-19 14:51:51.657 UTC | null | 63,051 | Johannes | 925 | null | 1 | 16 | email|bulk|webmail|massmail|sendgrid | 13,472 | <p>You want to look at the following:</p>
<ul>
<li>add a bulk-header to your outgoing email (<code>Precedence: bulk</code>)</li>
<li>look into <a href="http://en.wikipedia.org/wiki/Sender_Policy_Framework" rel="noreferrer">SPF</a></li>
<li>look into <a href="http://en.wikipedia.org/wiki/SenderID" rel="noreferrer">SenderID</a></li>
<li>look into <a href="http://antispam.yahoo.com/domainkeys" rel="noreferrer">DomainKeys</a> or <a href="http://www.dkim.org/" rel="noreferrer">DKIM</a></li>
<li>look into <a href="http://www.business.ftc.gov/documents/bus61-can-spam-act-compliance-guide-business" rel="noreferrer">CAN-SPAM act</a> </li>
<li>setup <strong>and handle</strong> email to abuse@</li>
<li>build relationships with the important providers</li>
<li>monitor the usual spam lists, work with them when you are on them</li>
</ul>
<p>Also, most providers have pages setup where they explain how they want "bulk" email to look like when you are sending it to their customers. That general includes requirements for double opt-in, etc..</p> |
1,936 | How to RedirectToAction in ASP.NET MVC without losing request data | <p>Using ASP.NET MVC there are situations (such as form submission) that may require a <code>RedirectToAction</code>. </p>
<p>One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to.</p>
<p>As I require the form to contain the originally <code>POST</code>ed data, for user convenience, as well as validation purposes, how can I pass the data through the <code>RedirectToAction()</code>? If I use the viewData parameter, my <code>POST</code> parameters will be changed to <code>GET</code> parameters.</p> | 1,940 | 6 | 2 | null | 2008-08-05 05:33:41.697 UTC | 49 | 2020-06-18 13:31:52.997 UTC | 2016-08-15 02:03:16.617 UTC | Dan | 316,469 | null | 364 | null | 1 | 124 | c#|asp.net-mvc | 91,666 | <p>The solution is to use the TempData property to store the desired Request components.</p>
<p>For instance:</p>
<pre><code>public ActionResult Send()
{
TempData["form"] = Request.Form;
return this.RedirectToAction(a => a.Form());
}
</code></pre>
<p>Then in your "Form" action you can go:</p>
<pre><code>public ActionResult Form()
{
/* Declare viewData etc. */
if (TempData["form"] != null)
{
/* Cast TempData["form"] to
System.Collections.Specialized.NameValueCollection
and use it */
}
return View("Form", viewData);
}
</code></pre> |
42,584,368 | How do you define custom `Error` types in Rust? | <p>I'm writing a function that could return several one of several different errors.</p>
<pre><code>fn foo(...) -> Result<..., MyError> {}
</code></pre>
<p>I'll probably need to define my own error type to represent such errors. I'm presuming it would be an <code>enum</code> of possible errors, with some of the <code>enum</code> variants having diagnostic data attached to them:</p>
<pre><code>enum MyError {
GizmoError,
WidgetNotFoundError(widget_name: String)
}
</code></pre>
<p>Is that the most idiomatic way to go about it? And how do I implement the <code>Error</code> trait?</p> | 42,584,607 | 3 | 3 | null | 2017-03-03 16:49:35.1 UTC | 16 | 2022-01-04 15:57:27.98 UTC | 2017-03-03 16:53:12.313 UTC | null | 155,423 | null | 525,872 | null | 1 | 68 | error-handling|rust | 36,765 | <p>You implement <a href="https://doc.rust-lang.org/std/error/trait.Error.html" rel="noreferrer"><code>Error</code></a> exactly like you would <a href="https://doc.rust-lang.org/stable/book/ch10-02-traits.html" rel="noreferrer">any other trait</a>; there's nothing extremely special about it:</p>
<pre><code>pub trait Error: Debug + Display {
fn description(&self) -> &str { /* ... */ }
fn cause(&self) -> Option<&Error> { /* ... */ }
fn source(&self) -> Option<&(Error + 'static)> { /* ... */ }
}
</code></pre>
<p><code>description</code>, <code>cause</code>, and <code>source</code> all have default implementations<sup>1</sup>, and your type must also implement <code>Debug</code> and <code>Display</code>, as they are supertraits.</p>
<pre><code>use std::{error::Error, fmt};
#[derive(Debug)]
struct Thing;
impl Error for Thing {}
impl fmt::Display for Thing {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Oh no, something bad went down")
}
}
</code></pre>
<p>Of course, what <code>Thing</code> contains, and thus the implementations of the methods, is highly dependent on what kind of errors you wish to have. Perhaps you want to include a filename in there, or maybe an integer of some kind. Perhaps you want to have an <code>enum</code> instead of a <code>struct</code> to represent multiple types of errors.</p>
<p>If you end up wrapping existing errors, then I'd recommend implementing <code>From</code> to convert between those errors and your error. That allows you to use <code>try!</code> and <code>?</code> and have a pretty ergonomic solution.</p>
<blockquote>
<p>Is that the most idiomatic way to go about it?</p>
</blockquote>
<p>Idiomatically, I'd say that a library will have a small (maybe 1-3) number of primary error types that are exposed. These are likely to be enumerations of other error types. This allows consumers of your crate to not deal with an explosion of types. Of course, this depends on your API and whether it makes sense to lump some errors together or not.</p>
<p>Another thing to note is that when you choose to embed data in the error, that can have wide-reaching consequences. For example, the standard library doesn't include a filename in file-related errors. Doing so would add overhead to every file error. The caller of the method usually has the relevant context and can decide if that context needs to be added to the error or not.</p>
<hr />
<p>I'd recommend doing this by hand a few times to see how all the pieces go together. Once you have that, you will grow tired of doing it manually. Then you can check out crates which provide macros to reduce the boilerplate:</p>
<ul>
<li><a href="https://crates.io/crates/error-chain" rel="noreferrer">error-chain</a></li>
<li><a href="https://crates.io/crates/failure" rel="noreferrer">failure</a></li>
<li><a href="https://crates.io/crates/quick-error" rel="noreferrer">quick-error</a></li>
<li><a href="https://crates.io/crates/anyhow" rel="noreferrer">Anyhow</a></li>
<li><a href="https://crates.io/crates/snafu" rel="noreferrer">SNAFU</a></li>
</ul>
<p>My preferred library is SNAFU (because I wrote it), so here's an example of using that with your original error type:</p>
<pre><code>use snafu::prelude::*; // 0.7.0
#[derive(Debug, Snafu)]
enum MyError {
#[snafu(display("Refrob the Gizmo"))]
Gizmo,
#[snafu(display("The widget '{widget_name}' could not be found"))]
WidgetNotFound { widget_name: String },
}
fn foo() -> Result<(), MyError> {
WidgetNotFoundSnafu {
widget_name: "Quux",
}
.fail()
}
fn main() {
if let Err(e) = foo() {
println!("{}", e);
// The widget 'Quux' could not be found
}
}
</code></pre>
<p>Note I've removed the redundant <code>Error</code> suffix on each enum variant. It's also common to just call the type <code>Error</code> and allow the consumer to prefix the type (<code>mycrate::Error</code>) or rename it on import (<code>use mycrate::Error as FooError</code>).</p>
<hr />
<p><sup>1</sup> Before <a href="https://github.com/rust-lang/rfcs/blob/master/text/2504-fix-error.md" rel="noreferrer">RFC 2504</a> was implemented, <code>description</code> was a required method.</p> |
21,164,365 | How to send image to PHP file using Ajax? | <p>my question is that is it possible to upload an image to a server using ajax(jquery)</p>
<p>below is my ajax script to send text without page reload</p>
<pre><code>$(function() {
//this submits a form
$('#post_submit').click(function(event) {
event.preventDefault();
var great_id = $("#post_container_supreme:first").attr("class");
var poster = $("#poster").val() ;
$.ajax({
type: "POST",
url: "my php file",
data: 'poster='+ poster + '&great_id=' + great_id,
beforeSend: function() {
$("#loader_ic").show();
$('#loader_ic').fadeIn(400).html('<img src="data_cardz_loader.gif" />').fadeIn("slow");
},
success: function(data) {
$("#loader_ic").hide();
$("#new_post").prepend(data);
$("#poster").val('');
}
})
})
})
</code></pre>
<hr>
<p>is it possible to modify it to send images?</p> | 21,164,512 | 5 | 4 | null | 2014-01-16 14:22:18.303 UTC | 8 | 2020-11-02 14:27:03.523 UTC | 2014-01-16 14:25:18.61 UTC | null | 913,707 | null | 2,757,519 | null | 1 | 18 | jquery|ajax|image|forms | 117,810 | <p>Use JavaScript's <a href="https://developer.mozilla.org/en/docs/Web/API/FormData" rel="nofollow noreferrer">formData API</a> and set <code>contentType</code> and <code>processData</code> to <code>false</code></p>
<pre><code>$("form[name='uploader']").on("submit", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var formData = new FormData(this);
$.ajax({
url: "page.php",
type: "POST",
data: formData,
success: function (msg) {
alert(msg)
},
cache: false,
contentType: false,
processData: false
});
});
</code></pre> |
61,204,259 | How can I resolve the "No Font Name" issue when importing fonts into R using extrafont? | <p>I have a folder on my Windows desktop (<code>C:\Users\me\Desktop\Fonts</code>) which contains fonts that I would like to import into R using <code>extrafont</code>.</p>
<p>When I try to import the fonts using</p>
<pre><code>library(extrafont)
font_import(paths = "C:/Users/me/Desktop/Fonts", prompt=FALSE)
</code></pre>
<p>I receive the error message</p>
<pre><code>Scanning ttf files in C:/Users/me/Desktop/Fonts ...
Extracting .afm files from .ttf files...
C:\Users\me\Desktop\Fonts\arista-light.ttf : No FontName. Skipping.
C:\Users\me\Desktop\Fonts\facebook-letter-faces.ttf : No FontName. Skipping.
C:\Users\me\Desktop\Fonts\Guardian-EgypTT-Text-Regular.ttf : No FontName. Skipping.
C:\Users\me\Desktop\Fonts\pico-black.ttf : No FontName. Skipping.
C:\Users\me\Desktop\Fonts\product-sans.ttf : No FontName. Skipping.
Found FontName for 0 fonts.
Scanning afm files in C:/Users/me/Documents/R/R-3.6.3/library/extrafontdb/metrics
Warning messages:
1: In system2(ttf2pt1, c(args, shQuote(ttfiles[i]), shQuote(tmpfiles[i])), :
running command '"C:/Users/me/Documents/R/R-3.6.3/library/Rttf2pt1/exec/ttf2pt1.exe" -a -G fAe "C:\Users\me\Desktop\Fonts\arista-light.ttf" "C:\Users\me\AppData\Local\Temp\RtmpOgbdTh/fonts/arista-light"' had status 1
2: In system2(ttf2pt1, c(args, shQuote(ttfiles[i]), shQuote(tmpfiles[i])), :
running command '"C:/Users/me/Documents/R/R-3.6.3/library/Rttf2pt1/exec/ttf2pt1.exe" -a -G fAe "C:\Users\me\Desktop\Fonts\facebook-letter-faces.ttf" "C:\Users\me\AppData\Local\Temp\RtmpOgbdTh/fonts/facebook-letter-faces"' had status 1
3: In system2(ttf2pt1, c(args, shQuote(ttfiles[i]), shQuote(tmpfiles[i])), :
running command '"C:/Users/me/Documents/R/R-3.6.3/library/Rttf2pt1/exec/ttf2pt1.exe" -a -G fAe "C:\Users\me\Desktop\Fonts\Guardian-EgypTT-Text-Regular.ttf" "C:\Users\me\AppData\Local\Temp\RtmpOgbdTh/fonts/Guardian-EgypTT-Text-Regular"' had status 1
4: In system2(ttf2pt1, c(args, shQuote(ttfiles[i]), shQuote(tmpfiles[i])), :
running command '"C:/Users/me/Documents/R/R-3.6.3/library/Rttf2pt1/exec/ttf2pt1.exe" -a -G fAe "C:\Users\me\Desktop\Fonts\pico-black.ttf" "C:\Users\me\AppData\Local\Temp\RtmpOgbdTh/fonts/pico-black"' had status 1
5: In system2(ttf2pt1, c(args, shQuote(ttfiles[i]), shQuote(tmpfiles[i])), :
running command '"C:/Users/me/Documents/R/R-3.6.3/library/Rttf2pt1/exec/ttf2pt1.exe" -a -G fAe "C:\Users\me\Desktop\Fonts\product-sans.ttf" "C:\Users\me\AppData\Local\Temp\RtmpOgbdTh/fonts/product-sans"' had status 1
</code></pre>
<p>Based on this I have two questions:</p>
<ol>
<li>How can I overcome the <code>No FontName. Skipping.</code> issue?</li>
<li>What are the warning messages trying to tell me and do I need to be concerned about this?</li>
</ol>
<p>I would appreciate any help, many thanks in advance!</p> | 68,642,855 | 3 | 2 | null | 2020-04-14 09:12:38.573 UTC | 14 | 2022-04-12 11:45:39.227 UTC | null | null | null | null | 10,561,781 | null | 1 | 41 | r|extrafont | 13,579 | <p>As it was mentioned by @Moritz Schwarz, the problem is <a href="https://github.com/wch/extrafont/issues/32" rel="noreferrer">traced to <code>Rttf2pt1</code></a>.</p>
<p>According to a solution proposed <a href="https://github.com/wch/extrafont/issues/88#issuecomment-890426514" rel="noreferrer">here</a>, downgrading it to 1.3.8 will fix the problem:</p>
<pre><code>library(extrafont)
library(remotes)
remotes::install_version("Rttf2pt1", version = "1.3.8")
extrafont::font_import()
</code></pre> |
65,342,769 | Install Node on M1 Mac | <p>Kind of a noob here on questions about binaries, processors and how that all works together:</p>
<p>I have a new Mac with an M1 chip, and want to install Node. I'm used to do this with Homebrew. Now, if I install Homebrew, I'm strongly recommended to use Rosetta, so I did. Next step: installing Node. So instead of <code>brew install node</code> I do <code>arch -x86_64 brew install node</code>.</p>
<p>This works fine, only I'm wondering, am I now using node in a sub-optimal way? Is Node also using Rosetta, instead of directly running on the M1 chip?</p> | 65,449,002 | 8 | 1 | null | 2020-12-17 14:39:04.557 UTC | 15 | 2022-03-02 10:54:53.76 UTC | null | null | null | null | 4,691,187 | null | 1 | 42 | node.js|homebrew|apple-silicon|rosetta | 84,565 | <p>I just got my M1 Mac mini. I did add an alias since I use oh-my-zsh to my <code>~/.zshrc</code> for <code>alias brew=arch -x86_64 brew</code> so I don't have to keep typing all that. I <code>brew install nvm</code> then <code>nvm ls-remote</code> and installed v15.5.0. It gets built <code>DV8_TARGET_ARCH_ARM64</code>.</p>
<p>Hope that helps. I also pulled the insiders VSCode for ARM64. Loads in a second.</p>
<p><code>> node -p "process.arch"</code>
<code> arm64</code></p>
<p>Don't forget you need <code>xcode-select --install</code> command line tools (~450MB).</p> |
2,211,915 | Library function for Permutation and Combination in C++ | <p>What's the most widely used existing library in C++ to give all the combination and permutation of k elements out of n elements?</p>
<p>I am not asking the algorithm but the existing library or methods.</p>
<p>Thanks.</p> | 2,212,063 | 5 | 1 | null | 2010-02-06 03:37:16.51 UTC | 29 | 2020-11-14 11:03:53.203 UTC | 2020-01-22 17:03:58.807 UTC | null | 10,251,345 | null | 233,254 | null | 1 | 35 | c++|c++-standard-library | 25,681 | <p>Combinations: from <a href="https://marknelson.us/posts/2002/03/01/next-permutation.html" rel="nofollow noreferrer">Mark Nelson's article</a> on the same topic we have <code>next_combination</code> Permutations: From STL we have <code>std::next_permutation</code></p>
<pre><code> template <typename Iterator>
inline bool next_combination(const Iterator first, Iterator k, const Iterator last)
{
if ((first == last) || (first == k) || (last == k))
return false;
Iterator itr1 = first;
Iterator itr2 = last;
++itr1;
if (last == itr1)
return false;
itr1 = last;
--itr1;
itr1 = k;
--itr2;
while (first != itr1)
{
if (*--itr1 < *itr2)
{
Iterator j = k;
while (!(*itr1 < *j)) ++j;
std::iter_swap(itr1,j);
++itr1;
++j;
itr2 = k;
std::rotate(itr1,j,last);
while (last != j)
{
++j;
++itr2;
}
std::rotate(k,itr2,last);
return true;
}
}
std::rotate(first,k,last);
return false;
}
</code></pre> |
1,952,404 | Linux bash: Multiple variable assignment | <p>Does exist in linux bash something similar to the following code in PHP:</p>
<pre><code>list($var1, $var2, $var3) = function_that_returns_a_three_element_array() ;
</code></pre>
<p>i.e. you assign in one sentence a corresponding value to 3 different variables.</p>
<p>Let's say I have the bash function <code>myBashFuntion</code> that writes to stdout the string "qwert asdfg zxcvb".
Is it possible to do something like:</p>
<pre><code>(var1 var2 var3) = ( `myBashFuntion param1 param2` )
</code></pre>
<p>The part at the left of the equal sign is not valid syntax of course. I'm just trying to explain what I'm asking for.</p>
<p>What does work, though, is the following:</p>
<pre><code>array = ( `myBashFuntion param1 param2` )
echo ${array[0]} ${array[1]} ${array[2]}
</code></pre>
<p>But an indexed array is not as descriptive as plain variable names.<br>
However, I could just do:</p>
<pre><code>var1 = ${array[0]} ; var2 = ${array[1]} ; var3 = ${array[2]}
</code></pre>
<p>But those are 3 more statements that I'd prefer to avoid.</p>
<p>I'm just looking for a shortcut syntax. Is it possible?</p> | 1,952,480 | 6 | 0 | null | 2009-12-23 12:03:49.197 UTC | 54 | 2022-07-05 12:36:48.127 UTC | null | null | null | null | 25,700 | null | 1 | 151 | linux|bash|shell|variable-assignment|multiple-variable-return | 167,109 | <p>First thing that comes into my mind:</p>
<pre><code>read -r a b c <<<$(echo 1 2 3) ; echo "$a|$b|$c"
</code></pre>
<p>output is, unsurprisingly</p>
<pre><code>1|2|3
</code></pre> |
2,157,458 | Using 'const' in class's functions | <p>I've seen a lot of uses of the const keyword put after functions in classes, so i wanted to know what was it about. I read up smth at here: <a href="http://duramecho.com/ComputerInformation/WhyHowCppConst.html" rel="noreferrer">http://duramecho.com/ComputerInformation/WhyHowCppConst.html</a> .</p>
<p>It says that const is used because the function "can attempt to alter any member variables in the object" . If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way. </p>
<pre><code>class Class2
{ void Method1() const;
int MemberVariable1;}
</code></pre>
<p>So, what is the real definition and use of const ?</p> | 2,157,477 | 7 | 5 | null | 2010-01-28 19:46:52.58 UTC | 14 | 2010-01-28 23:32:20.19 UTC | null | null | null | null | 242,343 | null | 1 | 29 | c++|oop|class|constants | 49,900 | <p>A const method can be called on a const object:</p>
<pre><code>class CL2
{
public:
void const_method() const;
void method();
private:
int x;
};
const CL2 co;
CL2 o;
co.const_method(); // legal
co.method(); // illegal, can't call regular method on const object
o.const_method(); // legal, can call const method on a regulard object
o.method(); // legal
</code></pre>
<p>Furthermore, it also tells the compiler that the const method should not be changing the state of the object and will catch those problems:</p>
<pre><code>void CL2::const_method() const
{
x = 3; // illegal, can't modify a member in a const object
}
</code></pre>
<p>There is an exception to the above rule by using the mutable modifier, but you should first get good at const correctness before you venture into that territory.</p> |
1,394,956 | How to do "hit any key" in python? | <p>How would I do a "hit any key" (or grab a menu option) in Python?</p>
<ul>
<li>raw_input requires you hit return.</li>
<li>Windows msvcrt has getch() and getche().</li>
</ul>
<p>Is there a portable way to do this using the standard libs?</p> | 1,394,994 | 7 | 3 | null | 2009-09-08 16:32:27.99 UTC | 8 | 2020-11-29 04:56:00.853 UTC | null | null | null | null | 3,233 | null | 1 | 34 | python | 40,506 | <pre><code>try:
# Win32
from msvcrt import getch
except ImportError:
# UNIX
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
</code></pre> |
2,251,622 | conditional execution (&& and ||) in powershell | <p>There's already question addressing my issue (<a href="https://stackoverflow.com/questions/563600/can-i-get-to-work-in-powershell">Can I get && to work in Powershell?</a>), but with one difference. I need an <strong>OUTPUT</strong> from both commands. See, if I just run:</p>
<pre><code>(command1 -arg1 -arg2) -and (command2 -arg1)
</code></pre>
<p>I won't see any output, but stderr messages. And, as expected, just typing:</p>
<pre><code>command1 -arg1 -arg2 -and command2 -arg1
</code></pre>
<p>Gives syntax error.</p> | 2,252,734 | 7 | 5 | null | 2010-02-12 12:05:46.55 UTC | 8 | 2020-11-27 12:48:35.407 UTC | 2017-05-23 12:32:05.06 UTC | null | -1 | null | 199,621 | null | 1 | 44 | syntax|powershell|command-execution | 36,490 | <p><strong>2019</strong>: the Powershell team are <a href="https://github.com/PowerShell/PowerShell/pull/9849" rel="noreferrer">considering adding support for <code>&&</code> to Powershell - weigh in at this GitHub PR</a></p>
<p>Try this:</p>
<pre><code>$(command -arg1 -arg2 | Out-Host;$?) -and $(command2 -arg1 | Out-Host;$?)
</code></pre>
<p>The <code>$()</code> is a subexpression allowing you to specify multiple statements within including a pipeline. Then execute the command and pipe to <code>Out-Host</code> so you can see it. The next statement (the actual output of the subexpression) should output <code>$?</code> i.e. the last command's success result. </p>
<hr>
<p>The <code>$?</code> works fine for native commands (console exe's) but for cmdlets it leaves something to be desired. That is, <code>$?</code> only seems to return <code>$false</code> when a cmdlet encounters a terminating error. Seems like <code>$?</code> needs at least three states (failed, succeeded and partially succeeded). So if you're using cmdlets, this works better:</p>
<pre><code>$(command -arg1 -arg2 -ev err | Out-Host;!$err) -and
$(command -arg1 -ev err | Out-Host;!$err)
</code></pre>
<p>This kind of blows still. Perhaps something like this would be better:</p>
<pre><code>function ExecuteUntilError([scriptblock[]]$Scriptblock)
{
foreach ($sb in $scriptblock)
{
$prevErr = $error[0]
. $sb
if ($error[0] -ne $prevErr) { break }
}
}
ExecuteUntilError {command -arg1 -arg2},{command2-arg1}
</code></pre> |
1,505,206 | Imitating the "IN" Operator | <p>How can one achieve:</p>
<pre><code>if X in (1,2,3) then
</code></pre>
<p>instead of:</p>
<pre><code>if x=1 or x=2 or x=3 then
</code></pre>
<p>In other words, how can one best imitate the <code>IN</code> operator in VBA for excel?</p> | 1,505,248 | 8 | 0 | null | 2009-10-01 17:02:18.323 UTC | 2 | 2022-06-25 22:16:34.657 UTC | 2018-07-09 19:34:03.733 UTC | null | -1 | null | 66,696 | null | 1 | 29 | excel|operators|in-operator|vba | 84,442 | <p>I don't think there is a very elegant solution.</p>
<p>However, you could try:</p>
<pre><code>If Not IsError(Application.Match(x, Array("Me", "You", "Dog", "Boo"), False)) Then
</code></pre>
<p>or you could write your own function:</p>
<pre><code>Function ISIN(x, StringSetElementsAsArray)
ISIN = InStr(1, Join(StringSetElementsAsArray, Chr(0)), _
x, vbTextCompare) > 0
End Function
Sub testIt()
Dim x As String
x = "Dog"
MsgBox ISIN(x, Array("Me", "You", "Dog", "Boo"))
End Sub
</code></pre> |
1,553,704 | Round a number to nearest .25 in JavaScript | <p>I want to convert all numbers to the nearest .25</p>
<p>So...</p>
<pre><code>5 becomes 5.00
2.25 becomes 2.25
4 becomes 4.00
3.5 becomes 3.50
</code></pre> | 1,553,728 | 8 | 1 | null | 2009-10-12 09:59:56.817 UTC | 9 | 2022-08-15 07:21:02.86 UTC | 2022-08-15 07:12:37.967 UTC | null | 479,156 | null | 164,230 | null | 1 | 30 | javascript|rounding | 26,106 | <p>Here’s an implementation of what rslite said:</p>
<pre><code>var number = 5.12345;
number = (Math.round(number * 4) / 4).toFixed(2);
</code></pre> |
1,905,446 | How to debug compiled Java code in Eclipse | <p>I wonder if there are any solutions for Eclipse IDE to debug Java code for which I have no source, i.e. to debug dynamically decompiled code, step through it, etc.? I tried to use <a href="http://java.decompiler.free.fr/?q=jdeclipse" rel="noreferrer">JD-Eclipse</a>, <a href="http://jadclipse.sourceforge.net/wiki/index.php/Main_Page" rel="noreferrer">JadClipse</a>, and these plug-ins work great if I want to look at some class files, but as I debug, I get "Source not found." - how can I "attach" these plug-ins to "provide" source?</p>
<p>My environment:</p>
<ul>
<li>Eclipse 3.5</li>
<li>Windows XP (but I look for a cross platform solution, if possible)</li>
</ul>
<p>Thank you.</p> | 1,906,302 | 8 | 3 | null | 2009-12-15 06:02:27.76 UTC | 13 | 2013-01-16 15:22:53.367 UTC | 2009-12-15 08:35:46.407 UTC | null | 82,804 | null | 102,917 | null | 1 | 37 | java|eclipse|debugging|decompiler | 45,497 | <p>I have good experience with Jadclipse - <a href="http://jadclipse.sourceforge.net/wiki/index.php/Main_Page" rel="noreferrer">http://jadclipse.sourceforge.net/wiki/index.php/Main_Page</a> - there is an update site at <a href="http://jadclipse.sf.net/update" rel="noreferrer">http://jadclipse.sf.net/update</a></p>
<p>For best results, use jad and configure it to list line numbers as comments which will enable the output where the code is on the correct line. This is best for debugging sessions.</p>
<p>Then set it to be the default view for classes. See the documentation for details. This works well for me.</p> |
1,573,593 | What's the fastest way to iterate over an object's properties in Javascript? | <p>I know that I can iterate over an object's properties like this:</p>
<pre><code>for (property in object)
{
// do stuff
}
</code></pre>
<p>I also know that the fastest way to iterate over an array in Javascript is to use a decreasing while loop:</p>
<pre><code>var i = myArray.length;
while (i--)
{
// do stuff fast
}
</code></pre>
<p>I'm wondering if there is something similar to a decreasing while loop for iterating over an object's properties.</p>
<p><strong>Edit:</strong> just a word about the answers concerned with enumerability - I'm not. </p> | 1,574,813 | 8 | 8 | null | 2009-10-15 16:40:34.687 UTC | 16 | 2021-08-26 09:25:33.53 UTC | 2009-10-16 06:23:19.93 UTC | null | 1,026 | null | 139,010 | null | 1 | 48 | javascript|performance|optimization | 42,799 | <p>1) There are many different ways to enumerate properties:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in" rel="noreferrer"><code>for..in</code></a> (iterates over enumerable properties of the object and its prototype chain)</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer"><code>Object.keys(obj)</code></a> returns the array of the enumerable properties, found directly on the object (not in its prototype chain)</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames" rel="noreferrer"><code>Object.getOwnPropertyNames(obj)</code></a> returns an array of all properties (enumerable or not) found directly on the object.</li>
<li>If you're dealing with multiple objects of the same "shape" (set of properties), it might make sense to "pre-compile" the iteration code (see <a href="https://stackoverflow.com/a/25700742/1026">the other answer here</a>).</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of" rel="noreferrer"><code>for..of</code></a> can't be used to iterate an arbitrary object, but can be used with a <code>Map</code> or a <code>Set</code>, which are both suitable replacements for ordinary Objects for certain use-cases.</li>
<li>...</li>
</ul>
<p>Perhaps if you stated your original problem, someone could suggest a way to optimize.</p>
<p>2) I find it hard to believe that the actual enumeration is taking more than whatever you do with the properties in the loop body.</p>
<p>3) You didn't specify what platform you're developing for. The answer would probably depend on it, and the available language features depend on it too. E.g. in SpiderMonkey (Firefox JS interpreter) circa 2009 you could use <code>for each(var x in arr)</code> (<a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in" rel="noreferrer">docs</a>) if you actually needed the values, not the keys. It was faster than <code>for (var i in arr) { var x = arr[i]; ... }</code>.</p>
<p>V8 at some point <a href="http://benediktmeurer.de/2017/09/07/restoring-for-in-peak-performance/" rel="noreferrer">regressed the performance of <code>for..in</code> and subsequently fixed it</a>. Here's a post on the internals of <code>for..in</code> in V8 in 2017: <a href="https://v8project.blogspot.com/2017/03/fast-for-in-in-v8.html" rel="noreferrer">https://v8project.blogspot.com/2017/03/fast-for-in-in-v8.html</a></p>
<p>4) You probably just didn't include it in your snippet, but a faster way to do a <code>for..in</code> iteration is to make sure the variables you use in the loop are declared inside the function containing the loop, i.e.:</p>
<pre><code>//slower
for (property in object) { /* do stuff */ }
//faster
for (var property in object) { /* do stuff */ }
</code></pre>
<p>5) Related to (4): while trying to optimize a Firefox extension I once noticed that extracting a tight loop into a separate function improved its performance (<a href="https://www.mozdev.org/bugs/show_bug.cgi?id=20412#c1" rel="noreferrer">link</a>). (Obviously, it doesn't mean you should always do that!)</p> |
1,903,252 | Extract Integer Part in String | <p>What is the best way to extract the integer part of a string like</p>
<pre><code>Hello123
</code></pre>
<p>How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?</p> | 1,903,279 | 9 | 1 | null | 2009-12-14 20:23:21.51 UTC | 8 | 2022-06-20 02:14:43.653 UTC | 2011-05-15 12:55:02.673 UTC | null | 21,234 | null | 84,399 | null | 1 | 25 | java|string|parsing|integer|java.util.scanner | 110,831 | <p>Why don't you just use a Regular Expression to match the part of the string that you want?</p>
<pre><code>[0-9]
</code></pre>
<p>That's all you need, plus whatever surrounding chars it requires.</p>
<p>Look at <a href="http://www.regular-expressions.info/tutorial.html" rel="noreferrer">http://www.regular-expressions.info/tutorial.html</a> to understand how Regular expressions work.</p>
<p>Edit: I'd like to say that Regex may be a little overboard for this example, if indeed the code that the other submitter posted works... but I'd still recommend learning Regex's in general, for they are very powerful, and will come in handy more than I'd like to admit (after waiting several years before giving them a shot).</p> |
1,835,756 | Using 'try' vs. 'if' in Python | <p>Is there a rationale to decide which one of <code>try</code> or <code>if</code> constructs to use, when testing variable to have a value?</p>
<p>For example, there is a function that returns either a list or doesn't return a value. I want to check result before processing it. Which of the following would be more preferable and why?</p>
<pre><code>result = function();
if (result):
for r in result:
#process items
</code></pre>
<p>or</p>
<pre><code>result = function();
try:
for r in result:
# Process items
except TypeError:
pass;
</code></pre>
<h3>Related discussion:</h3>
<p><em><a href="https://stackoverflow.com/questions/204308/">Checking for member existence in Python</a></em></p> | 1,835,844 | 9 | 1 | null | 2009-12-02 20:58:37.69 UTC | 90 | 2022-02-02 17:45:47.89 UTC | 2022-02-02 17:45:47.89 UTC | null | 63,550 | null | 214,178 | null | 1 | 195 | python | 88,767 | <p>You often hear that Python encourages <a href="https://docs.python.org/3.6/glossary.html#term-eafp" rel="noreferrer">EAFP</a> style ("it's easier to ask for forgiveness than permission") over <a href="https://docs.python.org/3.6/glossary.html#term-lbyl" rel="noreferrer">LBYL</a> style ("look before you leap"). To me, it's a matter of efficiency and readability.</p>
<p>In your example (say that instead of returning a list or an empty string, the function were to return a list or <code>None</code>), if you expect that 99 % of the time <code>result</code> will actually contain something iterable, I'd use the <code>try/except</code> approach. It will be faster if exceptions really are exceptional. If <code>result</code> is <code>None</code> more than 50 % of the time, then using <code>if</code> is probably better.</p>
<p>To support this with a few measurements:</p>
<pre><code>>>> import timeit
>>> timeit.timeit(setup="a=1;b=1", stmt="a/b") # no error checking
0.06379691968322732
>>> timeit.timeit(setup="a=1;b=1", stmt="try:\n a/b\nexcept ZeroDivisionError:\n pass")
0.0829463709378615
>>> timeit.timeit(setup="a=1;b=0", stmt="try:\n a/b\nexcept ZeroDivisionError:\n pass")
0.5070195056614466
>>> timeit.timeit(setup="a=1;b=1", stmt="if b!=0:\n a/b")
0.11940114974277094
>>> timeit.timeit(setup="a=1;b=0", stmt="if b!=0:\n a/b")
0.051202772912802175
</code></pre>
<p>So, whereas an <code>if</code> statement <em>always</em> costs you, it's nearly free to set up a <code>try/except</code> block. But when an <code>Exception</code> actually occurs, the cost is much higher.</p>
<p><strong>Moral:</strong></p>
<ul>
<li>It's perfectly OK (and "pythonic") to use <code>try/except</code> for flow control,</li>
<li>but it makes sense most when <code>Exception</code>s are actually exceptional. </li>
</ul>
<p>From the Python docs:</p>
<blockquote>
<p><strong>EAFP</strong></p>
<p>Easier to ask for forgiveness than
permission. This common Python coding
style assumes the existence of valid
keys or attributes and catches
exceptions if the assumption proves
false. This clean and fast style is
characterized by the presence of many
<code>try</code> and <code>except</code> statements. The
technique contrasts with the <a href="https://docs.python.org/3.6/glossary.html#term-lbyl" rel="noreferrer">LBYL</a>
style common to many other languages
such as C.</p>
</blockquote> |
1,690,400 | Getting an instance name inside class __init__() | <p>While building a new class object in python, I want to be able to create a default value based on the instance name of the class without passing in an extra argument. How can I accomplish this? Here's the basic pseudo-code I'm trying for:</p>
<pre><code>class SomeObject():
defined_name = u""
def __init__(self, def_name=None):
if def_name == None:
def_name = u"%s" % (<INSTANCE NAME>)
self.defined_name = def_name
ThisObject = SomeObject()
print ThisObject.defined_name # Should print "ThisObject"
</code></pre> | 1,690,433 | 10 | 3 | null | 2009-11-06 20:58:57.747 UTC | 15 | 2019-08-15 18:08:27.99 UTC | 2009-11-06 21:03:10.557 UTC | null | 143,938 | null | 143,078 | null | 1 | 24 | python|class|variables|object|instance | 61,676 | <p>Instances don't have names. By the time the global name <code>ThisObject</code> gets <strong>bound</strong> to the instance created by evaluating the <code>SomeObject</code> constructor, the constructor has finished running.</p>
<p>If you want an object to have a name, just pass the name along in the constructor.</p>
<pre><code>def __init__(self, name):
self.name = name
</code></pre> |
2,016,249 | How to programmatically set style attribute in a view | <p>I'm getting a view from the XML with the code below: </p>
<pre><code>Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
</code></pre>
<p>I would like to set a "style" for the button how can I do that in java since a want to use several style for each button I will use.</p> | 2,016,344 | 11 | 0 | null | 2010-01-06 21:08:13.42 UTC | 26 | 2021-11-22 03:14:31.357 UTC | 2018-02-13 15:08:12.48 UTC | null | 2,837,443 | null | 221,204 | null | 1 | 116 | android|styles | 257,172 | <p>Generally you can't change styles programmatically; you can set the look of a screen, or part of a layout, or individual button in your XML layout using <a href="http://developer.android.com/guide/topics/ui/themes.html" rel="noreferrer">themes or styles</a>. Themes can, however, <a href="http://developer.android.com/guide/topics/ui/themes.html#fromTheApp" rel="noreferrer">be applied programmatically</a>.</p>
<p>There is also such a thing as a <a href="http://developer.android.com/reference/android/graphics/drawable/StateListDrawable.html" rel="noreferrer"><code>StateListDrawable</code></a> which lets you define different drawables for each state the your <code>Button</code> can be in, whether focused, selected, pressed, disabled and so on.</p>
<p>For example, to get your button to change colour when it's pressed, you could define an XML file called <code>res/drawable/my_button.xml</code> directory like this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@drawable/btn_pressed" />
<item
android:state_pressed="false"
android:drawable="@drawable/btn_normal" />
</selector>
</code></pre>
<p>You can then apply this selector to a <code>Button</code> by setting the property <code>android:background="@drawable/my_button"</code>.</p> |
2,032,149 | Optional Parameters in Go? | <p>Can Go have optional parameters? Or can I just define two different functions with the same name and a different number of arguments?</p> | 2,032,160 | 15 | 8 | null | 2010-01-09 02:38:57.707 UTC | 88 | 2022-09-13 15:06:12.293 UTC | 2022-06-02 22:17:31.063 UTC | null | 3,739,391 | null | 371,407 | null | 1 | 679 | go|overloading | 417,716 | <p>Go does not have optional parameters <a href="http://golang.org/doc/faq#overloading" rel="noreferrer">nor does it support method overloading</a>:</p>
<blockquote>
<p>Method dispatch is simplified if it
doesn't need to do type matching as
well. Experience with other languages
told us that having a variety of
methods with the same name but
different signatures was occasionally
useful but that it could also be
confusing and fragile in practice.
Matching only by name and requiring
consistency in the types was a major
simplifying decision in Go's type
system.</p>
</blockquote> |
1,715,697 | What is the best IDE to develop Android apps in? | <p>I am about to start developing an android app and need to get an IDE. Eclipse and the android eclipse plugin appears to be the natural choice. However I am familiar with intelliJ and re-sharper so I would prefer use intelliJ. </p>
<p>Has anyone used <a href="https://code.google.com/archive/p/idea-android/" rel="noreferrer">https://code.google.com/archive/p/idea-android/</a>? Is this any good?</p>
<p>Should I just bite the bullet and learn Eclipse?</p> | 1,715,759 | 20 | 3 | null | 2009-11-11 14:56:09.893 UTC | 81 | 2017-09-10 14:31:21.027 UTC | 2017-09-10 14:31:21.027 UTC | null | 1,033,581 | null | 30,099 | null | 1 | 251 | android|eclipse|intellij-idea | 266,674 | <p><strong>LATEST NEWS</strong></p>
<p>Android Studio has officially come out of beta and been released. It is now the official IDE for Android Development - Eclipse won't be supported anymore. It is definitely the IDE of choice for Android Development. Link to download page: <a href="http://developer.android.com/sdk/index.html" rel="noreferrer">http://developer.android.com/sdk/index.html</a></p>
<hr>
<p><strong>NEWS</strong></p>
<p>As of Google I/O 2013, the Android team has moved to IntelliJ Idea with the new Android Studio IDE: <a href="http://developer.android.com/sdk/installing/studio.html" rel="noreferrer">http://developer.android.com/sdk/installing/studio.html</a> </p>
<p>Great to see Google endorse Idea. It is safe to say that Android Studio, and thus Idea, will from now on be the definitive IDE for Android development! :D</p>
<hr>
<p><strong>ORIGINAL ANSWER</strong></p>
<p>IntelliJ now has support for Android. See <a href="http://www.jetbrains.com/idea/webhelp/enabling-android-support.html" rel="noreferrer">Enabling Android Support</a> from the JetBrains help page and the <a href="http://code.google.com/p/idea-android/" rel="noreferrer">Google Code project page</a> for the plugin. The <a href="http://code.google.com/p/idea-android/wiki/GettingStarted" rel="noreferrer">Getting Started</a> wiki page is pretty helpful.</p>
<p>If you are used to IntelliJ, I don't think it would be beneficial to switch IDEs just for Android tools. You can work on Android with any text editor (I use Vim). If you're more productive with a specific environment I don't see why you'd have to learn a new one. Not worth it in my opinion. Plus I'm a big IntelliJ fan. The IntelliJ plugin lets you make apk files and push the app to the emulator, that's all you need for Android app development. I'd say you're safe sticking with IntelliJ.</p>
<p>Update: there is now an official free IDE for IntelliJ android dev! <a href="http://blogs.jetbrains.com/idea/2010/10/intellij-idea-10-free-ide-for-android-development/" rel="noreferrer">http://blogs.jetbrains.com/idea/2010/10/intellij-idea-10-free-ide-for-android-development/</a></p> |
33,668,668 | CoordinatorLayout not drawing behind status bar even with windowTranslucentStatus and fitsSystemWindows | <p>I am trying to draw views behind the status bar like this:
<a href="https://i.stack.imgur.com/C56Qd.png"><img src="https://i.stack.imgur.com/C56Qd.png" alt="Desired result"></a></p>
<p>I tried to produce this effect with the recommended techniques, but I get this:</p>
<p><a href="https://i.stack.imgur.com/Y2IT4.png"><img src="https://i.stack.imgur.com/Y2IT4.png" alt="Actual result"></a></p>
<p>It's clear from the screenshot that none of my app content is being drawn behind the status bar.</p>
<p>What's interesting is that somehow, the Nav Drawer manages to draw behind the status bar:</p>
<p><a href="https://i.stack.imgur.com/pAEGL.jpg"><img src="https://i.stack.imgur.com/pAEGL.jpg" alt="enter image description here"></a></p>
<p>Stuff I did:</p>
<ul>
<li>Use support library widgets - <code>CoordinatorLayout</code>, <code>AppBarLayout</code>, <code>Toolbar</code>, <code>DrawerLayout</code></li>
<li><code>windowTranslucentStatus</code> set to <code>true</code> in my app theme</li>
<li><code>fitsSystemWindows</code> set to <code>true</code> on my <code>CoordinatorLayout</code></li>
</ul>
<p>This is my app theme:</p>
<pre class="lang-html prettyprint-override"><code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@android:color/transparent</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
</code></pre>
<p>This is my activity layout:</p>
<pre class="lang-html prettyprint-override"><code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout android:id="@+id/page_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"/>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>The FrameLayout in my activity layout is replaced with this fragment layout:</p>
<pre class="lang-html prettyprint-override"><code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="@android:color/holo_blue_bright"
tools:context=".MainActivity">
<TextView android:text="@string/lorem_ipsum"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:elevation="0dp"
android:theme="@style/AppTheme.TransparentAppBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/transparent"
app:title="@string/hello_blank_fragment"
app:popupTheme="@style/AppTheme.OverflowMenu" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
</code></pre> | 33,669,264 | 4 | 4 | null | 2015-11-12 09:57:28.657 UTC | 15 | 2020-08-01 19:28:27.13 UTC | null | null | null | null | 1,057,393 | null | 1 | 27 | android|material-design|android-support-library|statusbar|android-coordinatorlayout | 27,004 | <p><strong>edit for future readers:</strong> there's a lot of good information on the subject and the issue on the comments too, make sure to read through them.</p>
<p><strong>original answer:</strong>
Your theme is wrong, that's why.
Unfortunately, there're differences on how to activate in in Kitkat or Lollipop. On my code I did it in Java, but you can also achieve it in XML if you want to play with the <code>V21</code> folders on your resources tree. The name of the parameters will be very similar to the Java counterparts.</p>
<p>Delete the <code>android:windowTranslucentStatus</code> from your XML and in Java use like that:</p>
<pre><code> public static void setTranslucentStatusBar(Window window) {
if (window == null) return;
int sdkInt = Build.VERSION.SDK_INT;
if (sdkInt >= Build.VERSION_CODES.LOLLIPOP) {
setTranslucentStatusBarLollipop(window);
} else if (sdkInt >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatusBarKiKat(window);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void setTranslucentStatusBarLollipop(Window window) {
window.setStatusBarColor(
window.getContext()
.getResources()
.getColor(R.color. / add here your translucent color code /));
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private static void setTranslucentStatusBarKiKat(Window window) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
</code></pre>
<p>then you can call from your activity <code>setTranslucentStatusBar(getWindow());</code></p>
<p><strong>edit:</strong></p>
<p>making the status bar translucent and drawing behind it (for some reason I cannot understand) are two separate tasks in Android.</p>
<p>I've looked more on my code and I'm for sure have A LOT more <code>android:fitsSystemWindows="true"</code> on my layout than just the <code>CoordinatorLayout</code>.</p>
<p>below are all the Views on my layout with <code>android:fitsSystemWindows="true"</code> on them:</p>
<ul>
<li>CoordinatorLayout</li>
<li>AppBarLayout</li>
<li>CollapsingToolbarLayout</li>
<li>ImageView (with the background image)</li>
<li>FrameLayout (with the content of the header)</li>
</ul>
<p>so my suggestion is to just test/try filling up <code>android:fitsSystemWindows="true"</code> on your XML.</p> |
18,148,884 | Difference between no-cache and must-revalidate for Cache-Control? | <p>From the RFC 2616</p>
<p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1" rel="noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1</a></p>
<blockquote>
<p>no-cache</p>
<p>If the no-cache directive does not specify a field-name, then a cache
MUST NOT use the response to satisfy a subsequent request without
successful revalidation with the origin server. This allows an origin
server to prevent caching even by caches that have been configured to
return stale responses to client requests.</p>
</blockquote>
<p>So it directs agents to revalidate <em>all</em> responses.</p>
<p>Compared this to</p>
<blockquote>
<p>must-revalidate</p>
<p>When the must-revalidate directive is present in a response received
by a cache, that cache MUST NOT use the entry after it becomes stale
to respond to a subsequent request without first revalidating it with
the origin server</p>
</blockquote>
<p>So it directs agents to revalidate <em>stale</em> responses.</p>
<p>Particularly with regard to <code>no-cache</code>, is this how user agents actually, empirically treat this directive?</p>
<p>What's the point of <code>no-cache</code> if there's <code>must-revalidate</code> and <code>max-age</code>?</p>
<p>See this comment:</p>
<p><a href="http://palpapers.plynt.com/issues/2008Jul/cache-control-attributes/" rel="noreferrer">http://palpapers.plynt.com/issues/2008Jul/cache-control-attributes/</a></p>
<blockquote>
<p>no-cache</p>
<p>Though this directive sounds like it is instructing the browser not to
cache the page, there’s a subtle difference. The “no-cache” directive,
according to the RFC, tells the browser that it should revalidate with
the server before serving the page from the cache. Revalidation is a
neat technique that lets the application conserve band-width. If the
page the browser has cached has not changed, the server just signals
that to the browser and the page is displayed from the cache. Hence,
the browser (in theory, at least), stores the page in its cache, but
displays it only after revalidating with the server. In practice, IE
and Firefox have started treating the no-cache directive as if it
instructs the browser not to even cache the page. We started observing
this behavior about a year ago. We suspect that this change was
prompted by the widespread (and incorrect) use of this directive to
prevent caching.</p>
</blockquote>
<p>Has anyone got anything more official on this?</p>
<p><em>Update</em></p>
<blockquote>
<p>The must-revalidate directive ought to be used by servers if and only if failure to validate a request on the representation could result in incorrect operation, such as a silently unexecuted financial transaction.</p>
</blockquote>
<p>That's something I've never taken to heart until now. The RFC is saying not to use must-revalidate lightly. The thing is, with web services, you have to take a negative view and assume the worst for your unknown client apps. Any stale resource has the potential to cause a problem.</p>
<p>And something else I've just considered, without Last-Modified or ETags, the browser can only fetch the whole resource again. However with ETags, I've observed that Chrome at least seems to revalidate on every request. Which makes both these directives moot or at least poorly named since they can't properly revalidate unless the request also includes other headers that then cause 'always revalidate' anyway.</p>
<p>I just want to make that last point clearer. By just setting <code>must-revalidate</code> but not including either an ETag or Last-Modified, the agent can only get the content again since it has nothing to send to the server to compare.</p>
<p>However, my empirical testing has shown that when ETag or modified header data is included in responses, the agents always revalidate anyway, regardless of the presence of the <code>must-revalidate</code> header.</p>
<p>So the point of <code>must-revalidate</code> is to force a 'bypass cache' when it goes stale, which can only happen when you have set a lifetime/age, thus if <code>must-revalidate</code> is set on a response with no age or other headers, it effectively becomes equivalent to <code>no-cache</code> since the response will be considered immediately stale.</p>
<p>-- So I'm going to finally mark Gili's answer!</p> | 19,938,619 | 6 | 4 | null | 2013-08-09 14:19:30.463 UTC | 58 | 2022-09-14 02:45:56.703 UTC | 2022-09-14 02:45:56.703 UTC | null | 1,718,491 | null | 107,783 | null | 1 | 217 | caching|http-headers|browser-cache|cache-control | 156,620 | <p>I believe that <code>must-revalidate</code> means :</p>
<blockquote>
<p>Once the cache expires, refuse to return stale responses to the user
even if they say that stale responses are acceptable.</p>
</blockquote>
<p>Whereas <code>no-cache</code> implies :</p>
<blockquote>
<p><code>must-revalidate</code> plus the fact the response becomes stale right away.</p>
</blockquote>
<p>If a response is cacheable for 10 seconds, then <code>must-revalidate</code> kicks in after 10 seconds, whereas <code>no-cache</code> implies <code>must-revalidate</code> after 0 seconds.</p>
<p>At least, that's my interpretation.</p> |
17,727,386 | DropDownList in MVC 4 with Razor | <p>I'm trying to create a <code>DropDownList</code> on a razor view.</p>
<p>Would someone help me with this?</p>
<p><strong>Normal HTML5 code:</strong></p>
<pre><code><select id="dropdowntipo">
<option value="Exemplo1">Exemplo1</option>
<option value="Exemplo2">Exemplo2</option>
<option value="Exemplo3">Exemplo3</option>
</select>
</code></pre>
<p>I tried this:</p>
<pre><code>@{
var listItems = new List<ListItem> {
new ListItem { Text = "Exemplo1", Value = "Exemplo1" },
new ListItem { Text = "Exemplo2", Value = "Exemplo2" },
new ListItem { Text = "Exemplo3", Value = "Exemplo3" }
};
}
@Html.DropDownListFor(model =>
model.tipo,
new SelectList(listItems),
"-- Select Status --"
)
</code></pre> | 17,727,558 | 13 | 10 | null | 2013-07-18 15:13:37.693 UTC | 47 | 2022-09-16 12:47:15.813 UTC | 2017-12-29 16:35:06.9 UTC | null | 5,622,941 | null | 2,232,273 | null | 1 | 148 | c#|asp.net-mvc|razor | 563,883 | <pre><code>@{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Exemplo1",
Value = "Exemplo1"
});
listItems.Add(new SelectListItem
{
Text = "Exemplo2",
Value = "Exemplo2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Exemplo3",
Value = "Exemplo3"
});
}
@Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")
</code></pre> |
6,953,528 | Best way to internationalize simple PHP website | <p>I have to develop a pretty simple php website so I don't need framework.
But it's must support multi language (EN/FR/CHINESE).
I have looked for php built in system and I found two ways :</p>
<ul>
<li>intl module from php5.3 (<a href="http://php.net/manual/fr/book.intl.php" rel="noreferrer">http://php.net/manual/fr/book.intl.php</a>)</li>
<li>gettext (<a href="http://php.net/manual/fr/book.gettext.php" rel="noreferrer">http://php.net/manual/fr/book.gettext.php</a>)</li>
</ul>
<p>I have no experience in i18n without framework, so any advices about what's the <strong>simplest way</strong> to support multi language ?</p>
<p>At end I just need a function that search translation into file (one file by language).
EQ :
<code>trans('hello');</code></p>
<p>=> en.yaml (yaml or not, it's an example)</p>
<pre><code>hello: "Hello world!"
</code></pre>
<p>=> fr.yaml</p>
<pre><code>hello: "Bonjour tout le monde !"
</code></pre>
<p>And if possible I prefer Pure PHP implementations</p> | 6,954,120 | 4 | 2 | null | 2011-08-05 08:34:55.527 UTC | 11 | 2016-10-14 12:11:07.423 UTC | 2011-08-05 09:40:05.537 UTC | null | 636,472 | null | 636,472 | null | 1 | 17 | php|internationalization|multilingual | 29,591 | <p>Although <code>ext/gettext</code> and <code>ext/intl</code> are both related to i18 (internationalization), <code>gettext</code> deals with translation while <code>intl</code> deals with internationalizing things like number and date display, sorting orders and transliteration. So you'd actually need both for a complete i18-solution. Depending on your needs you may come up with an home-brew solution relying on the extensions mentioned above or your use components provided by some framework:</p>
<ul>
<li><strong>Translation</strong>
<ul>
<li><a href="http://symfony.com/doc/current/book/translation.html" rel="noreferrer">Symfony 2 Translation component</a>: <a href="https://github.com/symfony/Translation" rel="noreferrer">https://github.com/symfony/Translation</a></li>
<li>Zend Framework <a href="http://framework.zend.com/manual/en/zend.translate.html" rel="noreferrer"><code>Zend_Translate</code></a></li>
</ul></li>
<li><strong>Internationalization</strong>
<ul>
<li>Zend Framework <a href="http://framework.zend.com/manual/en/zend.locale.html" rel="noreferrer"><code>Zend_Locale</code></a></li>
</ul></li>
</ul>
<p>If you only need translation and the site is simple enough, perhaps your simple solution (reading a translation configuration file into an PHP array, using a simple function to retrieve a token) might be the easiest.</p>
<p>The most simple solution I can think of is:</p>
<pre><code>$translation = array(
'Hello world!' => array(
'fr' => 'Bonjour tout le monde!',
'de' => 'Hallo Welt!'
)
);
if (!function_exists('gettext')) {
function _($token, $lang = null) {
global $translation;
if ( empty($lang)
|| !array_key_exists($token, $translation)
|| !array_key_exists($lang, $translation[$token])
) {
return $token;
} else {
return $translation[$token][$lang];
}
}
}
echo _('Hello World!');
</code></pre> |
16,009,608 | Combine columns from multiple columns into one in Hive | <p>Is there any way to do kind of reverse thing for explode() function in Apache Hive.
Let's say I have a table in this form <code>id int, description string, url string, ...</code></p>
<p>And from this table I would like to create table which looks like <code>id int, json string</code> where in <code>json</code> column stored all other columns as json. <code>"description":"blah blah", "url":"http:", ...</code></p> | 16,020,378 | 2 | 0 | null | 2013-04-15 07:15:03.797 UTC | 1 | 2017-07-16 07:49:50.77 UTC | null | null | null | null | 1,831,986 | null | 1 | 5 | hadoop|hive | 46,263 | <p>Hive has access to some <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-StringFunctions" rel="noreferrer">string operations</a> which can be used to combine multiple columns into one column</p>
<pre><code>SELECT id, CONCAT(CONCAT("(", CONCAT_WS(", ", description, url)), ")") as descriptionAndUrl
FROM originalTable
</code></pre>
<p>This is obviously going to get complicated fast for combining many columns into valid JSON. If this is one-of and you know that all of the JSON strings will have the same properties you might get away with just CONCAT for your purposes.</p>
<p>The "right" way to do it would be to write a <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF" rel="noreferrer">User Defined Function</a> which takes a list of columns and spits out a JSON string. This will be much more maintainable if you ever need to add columns or do the same thing to other tables. </p>
<p>It's likely someone has already written one you can use, so you should look around. Unfortunately the [JSON related UDFs provided by Hive]<a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-get_json_object" rel="noreferrer">https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-get_json_object</a>) work from JSON strings, they don't make them.</p> |
19,284,193 | 'Invalid value' when setting default value in HTML5 datetime-local input | <p>Can someone explain why when I set the default value of a datetime-local input with seconds other than :00, the browser gives me an error of "Invalid value."?</p>
<p>This may be a bug in Chrome's implementation of datetime-local since this bug does not appear in the latest Firefox and Safari.</p>
<p><strong>Error in Chrome: 30.0.1599.69</strong></p>
<p><img src="https://i.stack.imgur.com/EI9br.png" alt="enter image description here"></p>
<p><strong>Chrome Canary: 32.0.1665.2 canary</strong></p>
<p><img src="https://i.stack.imgur.com/v3CZa.png" alt="enter image description here"></p>
<p><strong>This works:</strong></p>
<pre><code><input type="datetime-local" name="pub_date" value="2013-10-09T15:38:00">
</code></pre>
<p><strong>But this does not:</strong></p>
<pre><code><input type="datetime-local" name="pub_date" value="2013-10-09T15:38:15">
</code></pre>
<p><a href="http://jsfiddle.net/YNdee/1/" rel="noreferrer">Link to fiddle.</a></p>
<p>Per the <a href="http://www.w3.org/TR/html-markup/input.datetime-local.html" rel="noreferrer">W3 Spec for the datetime-local input element</a>, the value attribute should contain "A string representing a local date and time."</p>
<pre><code>Example:
1985-04-12T23:20:50.52
1996-12-19T16:39:57
</code></pre>
<p>I tried both of the above examples and they don't work either.</p>
<p><strong>Update: Confirmed Bug & Solution</strong></p>
<p>This behavior is a <a href="https://code.google.com/p/chromium/issues/detail?id=257369&q=datetime-local&colspec=ID%20Pri%20M%20Iteration%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified" rel="noreferrer">known bug</a>.</p>
<p>As of today, the quick fix is to add the step attribute like so for non-zero seconds:</p>
<pre><code><input type="datetime-local"
name="pub_date"
value="2013-10-09T15:38:15"
step="1">
</code></pre> | 39,536,563 | 3 | 2 | null | 2013-10-09 22:54:58.747 UTC | 6 | 2016-09-22 19:49:20.69 UTC | 2016-06-25 23:24:47.937 UTC | null | 6,510,354 | null | 361,833 | null | 1 | 30 | html|google-chrome | 16,507 | <p>This works in Chrome Version 52.0.2743.116 m</p>
<pre><code><input type="datetime-local" name="pub_date" value="2013-10-09T15:38:15" />
</code></pre> |
40,148,442 | Mainline parent number when cherry picking merge commits | <p>Suppose this is my git history</p>
<pre>
Z
/
A -- C -- D
\ /
B
</pre>
<p>My HEAD is currently at <code>Z</code>. I want to cherry-pick <code>B</code> and <code>C</code>. If my understanding is correct, I should do this:</p>
<pre><code>git cherry-pick B
git cherry-pick C -m 1
git commit --allow-empty
</code></pre>
<p>It worked in my case because <code>C</code> is a no-op (hence the empty commit afterwards, I needed the commit for other reasons), but I am wondering what the parameter after <code>-m</code> does. Here is what I read from <a href="https://git-scm.com/docs/git-cherry-pick" rel="noreferrer">the docs</a>:</p>
<blockquote>
<p><strong>-m parent-number</strong></p>
<p><strong>--mainline parent-number</strong></p>
<p>Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.</p>
</blockquote>
<p>In my case, <code>C</code> has two parents but how do I know which one is 1 and 2, and more importantly when does it matter when I pick 1 or 2?</p> | 40,166,605 | 2 | 4 | null | 2016-10-20 07:47:48.42 UTC | 20 | 2016-10-21 01:24:46.13 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 404,623 | null | 1 | 50 | git|cherry-pick|git-cherry-pick | 43,979 | <p>My understanding based off <a href="//stackoverflow.com/a/12628579/2747593">this answer</a> is that parent 1 is the branch being merged into, and parent 2 is the branch being merged from. So in your case, parent 1 is <code>A</code>, and parent 2 is <code>B</code>. Since a cherry-pick is really applying the diff between two commits, you use <code>-m 1</code> to apply only the changes from <code>B</code> (because the diff between <code>A</code> and <code>C</code> contains the changes from <code>B</code>). In your case, it probably doesn't matter, since you have no commits between <code>A</code> and <code>C</code>.</p>
<p>So yes, <code>-m 1</code> is what you want, and that is true even if there were extra commits between <code>A</code> and <code>C</code>.</p>
<p>If you want to make the new history look a little more like the original history, there's another way to do this:</p>
<pre><code>git cherry-pick B
git checkout Z
git merge --no-ff --no-commit B
git commit --author="Some Dev <[email protected]>" --date="<commit C author date>"
</code></pre>
<p>(If needed, you can create a new branch for <code>B</code> before cherry-picking.)</p>
<p>This will retain the author information, should give you a history that looks like this:</p>
<pre><code> B'
/ \
Z -- C'
/
A -- C -- D
\ /
B
</code></pre> |
4,966,592 | Hadoop safemode recovery - taking too long! | <p>I have a Hadoop cluster with 18 data nodes.
I restarted the name node over two hours ago and the name node is still in safe mode.</p>
<p>I have been searching for why this might be taking too long and I cannot find a good answer.
The posting here:
<a href="https://stackoverflow.com/questions/2792020/hadoop-safemode-recovery-taking-lot-of-time">Hadoop safemode recovery - taking lot of time</a>
is relevant but I'm not sure if I want/need to restart the name node after making a change to this setting as that article mentions:</p>
<pre><code><property>
<name>dfs.namenode.handler.count</name>
<value>3</value>
<final>true</final>
</property>
</code></pre>
<p>In any case, this is what I've been getting in 'hadoop-hadoop-namenode-hadoop-name-node.log':</p>
<pre><code>2011-02-11 01:39:55,226 INFO org.apache.hadoop.ipc.Server: IPC Server handler 0 on 8020, call delete(/tmp/hadoop-hadoop/mapred/system, true) from 10.1.206.27:54864: error: org.apache.hadoop.hdfs.server.namenode.SafeModeException: Cannot delete /tmp/hadoop-hadoop/mapred/system. Name node is in safe mode.
The reported blocks 319128 needs additional 7183 blocks to reach the threshold 0.9990 of total blocks 326638. Safe mode will be turned off automatically.
org.apache.hadoop.hdfs.server.namenode.SafeModeException: Cannot delete /tmp/hadoop-hadoop/mapred/system. Name node is in safe mode.
The reported blocks 319128 needs additional 7183 blocks to reach the threshold 0.9990 of total blocks 326638. Safe mode will be turned off automatically.
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.deleteInternal(FSNamesystem.java:1711)
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.delete(FSNamesystem.java:1691)
at org.apache.hadoop.hdfs.server.namenode.NameNode.delete(NameNode.java:565)
at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:508)
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:966)
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:962)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:416)
at org.apache.hadoop.ipc.Server$Handler.run(Server.java:960)
</code></pre>
<p>Any advice is appreciated.
Thanks!</p> | 5,020,881 | 2 | 3 | null | 2011-02-11 07:28:07.597 UTC | 11 | 2019-08-15 06:50:30.547 UTC | 2017-05-23 12:26:19.87 UTC | null | -1 | null | 612,644 | null | 1 | 28 | hadoop|safe-mode | 35,194 | <p>I had it once, where some blocks were never reported in. I had to forcefully let the namenode leave safemode (<code>hadoop dfsadmin -safemode leave</code>) and then run an fsck to delete missing files.</p> |
1,180,606 | Using subprocess.Popen for Process with Large Output | <p>I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like:</p>
<pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
errcode = p.wait()
retval = p.stdout.read()
errmess = p.stderr.read()
if errcode:
log.error('cmd failed <%s>: %s' % (errcode,errmess))
</code></pre>
<p>There are comments in the docs that seem to indicate the potential issue. Under wait, there is:</p>
<blockquote>
<p>Warning: This will deadlock if the child process generates enough output to a <code>stdout</code> or <code>stderr</code> pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use <code>communicate()</code> to avoid that.</p>
</blockquote>
<p>though under communicate, I see:</p>
<p>Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.</p>
<p>So it is unclear to me that I should use either of these if I have a large amount of data. They don't indicate what method I should use in that case.</p>
<p>I do need the return value from the exec and do parse and use both the <code>stdout</code> and <code>stderr</code>.</p>
<p>So what is an equivalent method in Python to exec an external app that is going to have large output?</p> | 1,180,641 | 7 | 1 | null | 2009-07-24 23:08:07.763 UTC | 12 | 2018-03-29 05:41:11.857 UTC | 2009-07-25 19:40:14.307 UTC | null | 12,855 | null | 5,284 | null | 1 | 39 | python|subprocess | 26,844 | <p>You're doing blocking reads to two files; the first needs to complete before the second starts. If the application writes a lot to <code>stderr</code>, and nothing to <code>stdout</code>, then your process will sit waiting for data on <code>stdout</code> that isn't coming, while the program you're running sits there waiting for the stuff it wrote to <code>stderr</code> to be read (which it never will be--since you're waiting for <code>stdout</code>).</p>
<p>There are a few ways you can fix this.</p>
<p>The simplest is to not intercept <code>stderr</code>; leave <code>stderr=None</code>. Errors will be output to <code>stderr</code> directly. You can't intercept them and display them as part of your own message. For commandline tools, this is often OK. For other apps, it can be a problem.</p>
<p>Another simple approach is to redirect <code>stderr</code> to <code>stdout</code>, so you only have one incoming file: set <code>stderr=STDOUT</code>. This means you can't distinguish regular output from error output. This may or may not be acceptable, depending on how the application writes output.</p>
<p>The complete and complicated way of handling this is <code>select</code> (<a href="http://docs.python.org/library/select.html" rel="nofollow noreferrer">http://docs.python.org/library/select.html</a>). This lets you read in a non-blocking way: you get data whenever data appears on either <code>stdout</code> or <code>stderr</code>. I'd only recommend this if it's really necessary. This probably doesn't work in Windows.</p> |
36,350 | How to pass a single object[] to a params object[] | <p>I have a method which takes params object[] such as:</p>
<pre><code>void Foo(params object[] items)
{
Console.WriteLine(items[0]);
}
</code></pre>
<p>When I pass two object arrays to this method, it works fine:</p>
<pre><code>Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } );
// Output: System.Object[]
</code></pre>
<p>But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:</p>
<pre><code>Foo(new object[]{ (object)"1", (object)"2" });
// Output: 1, expected: System.Object[]
</code></pre>
<p>How do I pass a single object[] as a first argument to a params array?</p> | 36,367 | 7 | 0 | null | 2008-08-30 21:22:06.433 UTC | 15 | 2022-06-26 10:17:37.633 UTC | 2008-08-31 06:35:08.897 UTC | Rob Cooper | 832 | buyutec | 31,505 | null | 1 | 128 | c#|arrays | 131,263 | <p>A simple typecast will ensure the compiler knows what you mean in this case.</p>
<pre><code>Foo((object)new object[]{ (object)"1", (object)"2" }));
</code></pre>
<p>As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree.</p> |
32,034 | In C#, isn't the observer pattern already implemented using Events? | <p>After reading the Head First Design Patterns book and using a number of other design patterns, I'm trying to understand the Observer pattern. Isn't this already implemented using Events in the .NET Framework?</p> | 32,036 | 8 | 0 | null | 2008-08-28 11:36:52.297 UTC | 9 | 2016-02-24 10:50:19.637 UTC | 2016-02-24 10:50:19.637 UTC | null | 4,454,567 | Sean Chambers | 2,993 | null | 1 | 33 | c#|.net|design-patterns | 13,730 | <p>Yes, it is. The observer pattern is also called the publish/subscribe pattern, which is exactly what events allow you to do.</p> |
76,327 | How can I prevent Java from creating hsperfdata files? | <p>I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating <code>/tmp/hsperfdata_username</code> directories, which I would like to prevent. Is there any way to stop java from creating these files?</p> | 76,423 | 8 | 0 | null | 2008-09-16 20:03:08.087 UTC | 11 | 2018-10-03 15:12:48.857 UTC | 2016-01-13 20:56:51.623 UTC | user719662 | null | null | 13,582 | null | 1 | 50 | java|performance|report | 76,136 | <p>Try JVM option <strong>-XX:-UsePerfData</strong></p>
<p><a href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html" rel="noreferrer">more info</a></p>
<p>The following might be helpful that is from link <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html" rel="noreferrer">https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html</a></p>
<pre><code>-XX:+UsePerfData
Enables the perfdata feature. This option is enabled by default
to allow JVM monitoring and performance testing. Disabling it
suppresses the creation of the hsperfdata_userid directories.
To disable the perfdata feature, specify -XX:-UsePerfData.
</code></pre> |
936,969 | Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds | <p>I basically need to get current date and time separately, formatted as:</p>
<pre>
2009-04-26
11:06:54
</pre>
<p>The code below, from another question on the same topic, generates</p>
<pre>
now: |2009-06-01 23:18:23 +0100|
dateString: |Jun 01, 2009 23:18|
parsed: |2009-06-01 23:18:00 +0100|
</pre>
<p>This is almost what I'm looking for, but I want to separate the day and time.</p>
<pre><code>NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy"];
NSDate *parsed = [inFormat dateFromString:dateString];
NSLog(@"\n"
"now: |%@| \n"
"dateString: |%@| \n"
"parsed: |%@|", now, dateString, parsed);
</code></pre> | 937,143 | 8 | 1 | null | 2009-06-01 21:48:28.35 UTC | 62 | 2017-05-09 15:50:50.39 UTC | 2016-03-03 21:25:39.67 UTC | null | 603,977 | null | 112,313 | null | 1 | 132 | cocoa|cocoa-touch|nsdate|nsdateformatter|date-formatting | 295,901 | <p>iPhone format strings are in <a href="http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns" rel="noreferrer">Unicode format</a>. Behind the link is a table explaining what all the letters above mean so you can build your own.</p>
<p>And of course don't forget to release your date formatters when you're done with them. The above code leaks <code>format</code>, <code>now</code>, and <code>inFormat</code>.</p> |
74,620 | Date.getTime() not including time? | <p>Can't understand why the following takes place:</p>
<pre><code>String date = "06-04-2007 07:05";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm");
Date myDate = fmt.parse(date);
System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007
long timestamp = myDate.getTime();
System.out.println(timestamp); //1180955100000 -- where are the milliseconds?
// on the other hand...
myDate = new Date();
System.out.println(myDate); //Tue Sep 16 13:02:44 EDT 2008
timestamp = myDate.getTime();
System.out.println(timestamp); //1221584564703 -- why, oh, why?
</code></pre> | 74,652 | 9 | 2 | null | 2008-09-16 17:08:16.943 UTC | 1 | 2020-05-02 22:43:01.38 UTC | 2015-01-18 01:08:34.317 UTC | Hank Gay | 1,264,804 | Jake | 10,675 | null | 1 | 7 | java|date|timestamp|gettime | 47,396 | <p>What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for?</p>
<pre><code>String date = "06-04-2007 07:05:00.999";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S");
Date myDate = fmt.parse(date);
System.out.println(myDate);
long timestamp = myDate.getTime();
System.out.println(timestamp);
</code></pre> |
1,001,290 | Console based progress in Java | <p>Is there are easy way to implement a rolling percentage for a process in Java, to be displayed in the console? I have a percentage data type (double) I generated during a particular process, but can I force it to the console window and have it refresh, instead of just printing a new line for each new update to the percentage? I was thinking about pushing a cls and updating, because I'm working in a Windows environment, but I was hoping Java had some sort of built-in capability. All suggestions welcomed! Thanks!</p> | 1,001,340 | 9 | 1 | null | 2009-06-16 12:51:48.15 UTC | 20 | 2018-02-27 18:13:02.697 UTC | 2015-01-06 08:45:25.243 UTC | null | 258,400 | null | 107,092 | null | 1 | 36 | java|console|progress-bar|refresh | 40,079 | <p>You can print a carriage return <code>\r</code> to put the cursor back to the beginning of line.</p>
<p>Example:</p>
<pre><code>public class ProgressDemo {
static void updateProgress(double progressPercentage) {
final int width = 50; // progress bar width in chars
System.out.print("\r[");
int i = 0;
for (; i <= (int)(progressPercentage*width); i++) {
System.out.print(".");
}
for (; i < width; i++) {
System.out.print(" ");
}
System.out.print("]");
}
public static void main(String[] args) {
try {
for (double progressPercentage = 0.0; progressPercentage < 1.0; progressPercentage += 0.01) {
updateProgress(progressPercentage);
Thread.sleep(20);
}
} catch (InterruptedException e) {}
}
}
</code></pre> |
592,931 | Why doesn't Python have static variables? | <p>There is a <a href="https://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p> | 593,046 | 9 | 2 | null | 2009-02-26 23:28:09.013 UTC | 18 | 2012-11-15 14:31:16.087 UTC | 2017-05-23 12:25:23.57 UTC | gs | -1 | gs | 24,587 | null | 1 | 47 | python | 31,994 | <p>The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator.</p>
<p>If you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonetheless:</p>
<pre><code>def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
do_stuff(my_bar)
foo(bar)
foo()
# -- becomes ->
class Foo(object):
def __init__(self, bar):
self.bar = bar
def __call__(self):
do_stuff(self.bar)
foo = Foo(bar)
foo()
foo()
</code></pre>
<p>If you want your function's behavior to change each time it's called, what you need is a generator:</p>
<pre><code>def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
my_bar = my_bar * 3 % 5
return my_bar
foo(bar)
foo()
# -- becomes ->
def foogen(bar):
my_bar = bar
while True:
my_bar = my_bar * 3 % 5
yield my_bar
foo = foogen(bar)
foo.next()
foo.next()
</code></pre>
<p>Of course, static variables <em>are</em> useful for quick-and-dirty scripts where you don't want to deal with the hassle of big structures for little tasks. But there, you don't really need anything more than <code>global</code> — it may seem a but kludgy, but that's okay for small, one-off scripts:</p>
<pre><code>def foo():
global bar
do_stuff(bar)
foo()
foo()
</code></pre> |
1,069,621 | Are members of a C++ struct initialized to 0 by default? | <p>I have this <code>struct</code>:</p>
<pre><code>struct Snapshot
{
double x;
int y;
};
</code></pre>
<p>I want <code>x</code> and <code>y</code> to be 0. Will they be 0 by default or do I have to do:</p>
<pre><code>Snapshot s = {0,0};
</code></pre>
<p>What are the other ways to zero out the structure?</p> | 1,069,634 | 9 | 2 | null | 2009-07-01 14:58:39.757 UTC | 80 | 2021-10-28 16:13:31.81 UTC | 2018-03-29 10:01:02.46 UTC | null | 72,178 | Sasha | null | null | 1 | 231 | c++ | 186,694 | <p>They are not null if you don't initialize the struct. </p>
<pre><code>Snapshot s; // receives no initialization
Snapshot s = {}; // value initializes all members
</code></pre>
<p>The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive:</p>
<pre><code>struct Parent { Snapshot s; };
Parent p; // receives no initialization
Parent p = {}; // value initializes all members
</code></pre>
<p>The second will make <code>p.s.{x,y}</code> zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors</p>
<pre><code>struct Snapshot {
int x;
double y;
Snapshot():x(0),y(0) { }
// other ctors / functions...
};
</code></pre>
<p>Will initialize both x and y to 0. Note that you can use <code>x(), y()</code> to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template. </p> |
370,518 | How do I start with working Sub-Version + Delphi? | <p>I'm new to this SCM, but since SVN is gaining popularity I was going to give it a try.</p>
<p>Things I noticed:</p>
<ol>
<li>SVN is only the backbone of the SCM, no front-end?</li>
<li>Why is there several versions of Windows Binaries? Tigris? SlikSVN? VisualSVN?</li>
<li>Do I need a Web Server like Apache in order to use SVN?</li>
<li>There's dozens of front-end, Tortoise, WinSVN, etc... Which one is recommended?</li>
</ol>
<p>The whole thing is rather confusing and I got no idea where to start. I'm using Delphi and would like to use it to store my source files.</p>
<p>Update 1:
Seems I got it working using the "file:///" protocol, thanks. Now, how do I configure it as a server with client PCs.</p> | 370,528 | 10 | 3 | null | 2008-12-16 05:18:06.287 UTC | 18 | 2019-04-30 19:41:43.553 UTC | 2008-12-16 07:02:01.647 UTC | Atlas | 30,787 | Atlas | 30,787 | null | 1 | 16 | svn|delphi | 7,577 | <p><a href="http://blog.excastle.com/2007/04/09/subversion-in-delphis-tools-menu/" rel="nofollow noreferrer">Here's a great guide</a> for integrating TortoiseSVN with Delphi's "Tools" menu.</p>
<p>This site shows how to add the following into the IDE:</p>
<ol>
<li><p><code>svn Commit</code>: Opens the TortoiseSVN commit window.</p></li>
<li><p><code>svn Diff</code>: Shows diffs for the file currently being edited. (If you've configured an external diff viewer like Beyond Compare, this will use it.)</p></li>
<li><p><code>svn Modifications</code>: Opens the TortoiseSVN modifications window, which shows a list of all modified files.</p></li>
<li><code>svn Update</code>: Updates your working copy with the latest changes from the repository.</li>
</ol>
<p><a href="http://hallvards.blogspot.com/2007/04/subversion-in-delphis-tools-menu.html" rel="nofollow noreferrer">If you don't have Ruby installed (as the guide suggests using), simply replace it with
a simple online batch file instead</a>:</p>
<pre><code>"c:/program files/tortoisesvn/bin/tortoiseproc.exe" /command:%1 /path:%2 /notempfile
</code></pre>
<p>Then create the Tools items with:</p>
<p>Program: <code>c:\windows\system32\cmd.exe</code></p>
<p>Parameters: <code>/C C:\SvnPas\Utils\Batch\SvnCmd.Bat diff $EDNAME $SAVEALL</code></p> |
231,211 | Using Git how do I find changes between local and remote | <p>Here are two different questions but I think they are related.</p>
<ol>
<li><p>When using Git, how do I find which changes I have committed locally, but haven't yet pushed to a remote branch? I'm looking for something similar to the Mercurial command <code>hg outgoing</code>.</p></li>
<li><p>When using Git, how do I find what changes a remote branch has prior to doing a pull? I'm looking for something similar to the Mercurial command <code>hg incoming</code>.</p></li>
</ol>
<p>For the second: is there a way to see what is available and then cherry-pick the changes I want to pull?</p> | 231,379 | 11 | 1 | null | 2008-10-23 19:52:30.02 UTC | 64 | 2020-10-08 12:51:48.697 UTC | 2013-02-19 23:47:24.827 UTC | null | 2,354 | ejunker | 796 | null | 1 | 155 | git|mercurial | 104,157 | <p>Git can't send that kind of information over the network, like Hg can. But you can run <code>git fetch</code> (which is more like <code>hg pull</code> than <code>hg fetch</code>) to fetch new commits from your remote servers.</p>
<p>So, if you have a branch called <code>master</code> and a remote called <code>origin</code>, after running <code>git fetch</code>, you should also have a branch called <code>origin/master</code>. You can then get the <code>git log</code> of all commits that <code>master</code> needs to be a superset of <code>origin/master</code> by doing <code>git log master..origin/master</code>. Invert those two to get the opposite.</p>
<p>A friend of mine, David Dollar, has created a couple of git shell scripts to simulate <code>hg incoming/outgoing</code>. You can find them at <a href="http://github.com/ddollar/git-utils" rel="noreferrer">http://github.com/ddollar/git-utils</a>.</p> |
598,913 | Most important things about C++ templates… lesson learned | <p>What are most important things you know about templates: hidden features, common mistakes, best and most useful practices, tips...<strong>common mistakes/oversight/assumptions</strong></p>
<p>I am starting to implement most of my library/API using templates and would like to collect most common patterns, tips, etc., found in practice.</p>
<p>Let me formalize the question: What is the most important thing you've learned about templates?</p>
<p>Please try to provide examples -- it would be easier to understand, as opposed to convoluted and overly dry descriptions</p>
<p>Thanks</p> | 599,050 | 12 | 2 | null | 2009-02-28 23:47:18.92 UTC | 14 | 2022-07-29 13:21:07.17 UTC | 2009-03-01 01:30:55.817 UTC | strager | 39,992 | Sasha | null | null | 1 | 13 | c++|templates | 6,085 | <p>From <strong>"Exceptional C++ style", Item 7:</strong> function overload resolution happens <em>before</em> templates specialization. Do not mix overloaded function and specializations of template functions, or you are in for a nasty surprise at which function actually gets called.</p>
<pre><code>template<class T> void f(T t) { ... } // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f<int*>(int *t) { ... } // (c)
...
int *pi; f(pi); // (b) is called, not (c)!
</code></pre>
<p>On top of <strong>Item 7</strong>:</p>
<p>Worse yet, if you omit the type in template specialization, a <em>different</em> function template might get specialized depending on the order of definition and as a result a specialized function may or may not be called.</p>
<p>Case 1:</p>
<pre><code>template<class T> void f(T t) { ... } // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f(int *t) { ... } // (c) - specializes (b)
...
int *pi; f(pi); // (c) is called
</code></pre>
<p>Case 2:</p>
<pre><code>template<class T> void f(T t) { ... } // (a)
template<> void f(int *t) { ... } // (c) - specializes (a)
template<class T> void f(T *t) { ... } // (b)
...
int *pi; f(pi); // (b) is called
</code></pre> |
335,293 | Human factors design (meeting psychological needs in UI design) | <p>Reading about the <a href="http://en.wikipedia.org/wiki/G.729" rel="nofollow noreferrer">G.729 codec</a>, I found this interesting tidbit about "<a href="http://en.wikipedia.org/wiki/Comfort_noise" rel="nofollow noreferrer">Comfort Noise</a>":</p>
<blockquote>
<p>A comfort noise generator (CNG) is
also set up because in a communication
channel, if transmission is stopped,
and the link goes quiet because of no
speech, then the receiving side may
assume that the link has been cut. By
inserting comfort noise the old analog
hiss is played during silence to
assure the receiver that the link is
active and operational.</p>
</blockquote>
<p>This is the kind of thing a good programmer needs to know about before they design VOIP software, for instance.</p>
<p>Earlier today I also learned about <a href="http://scienceweek.com/2004/sc040709-4.htm" rel="nofollow noreferrer">Saccadic Suppression</a>:</p>
<blockquote>
<p>Humans avoid retinal blurring during eye
movement by
temporarily attenuating the data
flowing from the retina into the
brain. An amusing way to demonstrate
this phenomenon is to look at your
face in a mirror. Holding your head
steady, look at one eye and then the
other, rapidly shifting your gaze
between the two. The image is stable
and you do not see your own eye
movement, but another person watching
you will clearly see your eyes move.</p>
</blockquote>
<p>This has application in video game and other visual and graphics development.</p>
<p>There are many books on user interface design, but I have yet to see a single reference which enumerates <em>most</em> of the human design factors we <em>should</em> understand when designing software. I expect a lot of software engineers learn this by the seat of their pants - they design it, find that something is odd and/or annoying, and play with it until it feels comfortable. Yet the answers already exist, the studies have been done, and <em>someone</em> knows not only how to fix our issue, but why it's an issue.</p>
<ul>
<li><strong>Without getting a BS/BA in a dozen different professions, where would I look for this sort of information?</strong></li>
<li><strong>Am I doomed to stumbling across it in daily internet surfing</strong> (which many companies/managers frown on)<strong>?</strong></li>
<li><strong>What other human factors impact programming</strong> (please link a reference, resource, or at least give a googleable technical name - alternately post a new question about it with the tag "human-factors")<strong>?</strong></li>
</ul> | 488,259 | 12 | 0 | null | 2008-12-02 20:22:53.11 UTC | 26 | 2018-07-01 09:19:00.01 UTC | 2018-07-01 09:19:00.01 UTC | Rich B | 4,099,593 | Adam Davis | 2,915 | null | 1 | 29 | user-interface | 2,518 | <p>I think what you need to know varies depending upon the type of application you are trying to develop and the user environment it will be in.</p>
<p>From the enormous company/product perspective - it's wise to have an HMI/UI Style Guide that spells out the basic precepts developers should be using their interface designs for the specific goals of their software. In many cases, it's as important to be consistent as it is to be correct, so having a single guide for a big product, or suite of products gets really important. It also keeps the software experts from also having to be user experts. If there is just one source, I would say that the internal style guide would be it. Ideally, they should be written (and updated) to do exactly what you ask - be a reference point of all the things to consider when making a design.</p>
<p>I'm not sure you will ever find a single guide for <em>all</em> aspects of user interface design that is a one size fits all source. Different types of technology require different techniques - for example the two design ideas above are useful for two very different types of applications (voice transmissions and video games). And neither one is particularly helpful for web applications. Worse yet, user needs change as a given technology becomes more widely adopted - for example, Web 2.0 GUIs use some layouts and design concepts that violate older early web UI design practices. </p>
<p>General principles that I find useful for my work in the web app world:</p>
<ul>
<li>Always consider what the user is trying to do as the first priority</li>
<li>Consider other systems the user is already familiar with and copy them when possible*</li>
<li>Focus attention on the most important decision/information (see first bullet) - attention can be focused in many ways, depending on technology - size, movement, position, color, sound, or any other sensory input.</li>
<li>Consider the user - age, disablity/ability, prior experience with this technology, and almost anything else you can think of. Then design with the key aspects of the user in mind.</li>
<li>Consider the user's environment - hardware, network, physical surroundings </li>
<li>Make the user do as little activity as possible to accomplish their goals - ie, mouse clicks, key strokes, voice commands</li>
</ul>
<p>Sadly, mileage may vary - I have always worked in the world of applications that people must use, but would never willingly use if they didn't need to do their jobs - hopefully the tool makes work easier, but it's still work. Things like video games - which people willingly pay money for just for the fun of using them - are a whole different ball game. In those cases, you may not be trying to make everything <em>easy</em> - but you are trying to add challenge in a way that is enjoyable.</p>
<p>*(Edit - Added) - when possible <em>and</em> when it makes sense. Don't be afraid to reinvent the wheel when you have a better idea so long as you have a good case for it really being better.</p> |
683,462 | Best way to integrate Python and JavaScript? | <p>Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if <strong>anyone has done it within a "serious" project or product</strong>.</p>
<p>I'm guessing it would be possible using <a href="http://www.jython.org/Project/" rel="noreferrer">Jython</a> and <a href="http://www.mozilla.org/rhino/" rel="noreferrer">Rhino</a>, for one example, but I'm curious whether or not anyone's ever actually done this, and if there are solutions for other platforms (especially <a href="http://en.wikipedia.org/wiki/CPython" rel="noreferrer">CPython</a>).</p> | 683,481 | 13 | 4 | null | 2009-03-25 21:08:11.837 UTC | 36 | 2021-07-23 10:15:05.01 UTC | 2017-01-29 19:35:58.41 UTC | null | 1,577,341 | Jacob Gabrielson | 68,127 | null | 1 | 71 | javascript|python|brython|transcrypt|rapydscript | 131,739 | <p>Here's something, a Python wrapper around the SeaMonkey Javascript interpreter... <a href="http://pypi.python.org/pypi/python-spidermonkey" rel="noreferrer">http://pypi.python.org/pypi/python-spidermonkey</a></p> |
192,957 | Efficiently querying one string against multiple regexes | <p>Lets say that I have 10,000 regexes and one string and I want to find out if the string matches any of them and get all the matches.
The trivial way to do it would be to just query the string one by one against all regexes. Is there a faster,more efficient way to do it? </p>
<p>EDIT:
I have tried substituting it with DFA's (lex)
The problem here is that it would only give you one single pattern. If I have a string "hello" and patterns "[H|h]ello" and ".{0,20}ello", DFA will only match one of them, but I want both of them to hit.</p> | 1,346,398 | 18 | 2 | null | 2008-10-10 20:42:16.683 UTC | 22 | 2019-09-02 15:34:27.287 UTC | 2008-10-10 21:41:15.503 UTC | Sridhar Iyer | 13,820 | Sridhar Iyer | 13,820 | null | 1 | 54 | regex|algorithm|pcre | 13,186 | <p><a href="http://sulzmann.blogspot.com/" rel="noreferrer">Martin Sulzmann</a> Has done quite a bit of work in this field.
He has <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/regexpr-symbolic" rel="noreferrer">a HackageDB project</a> explained breifly <a href="http://sulzmann.blogspot.com/2008/12/equality-containment-and-intersection.html" rel="noreferrer">here</a> which use <a href="http://sulzmann.blogspot.com/2008/11/playing-with-regular-expressions.html" rel="noreferrer">partial derivatives</a> seems to be tailor made for this.</p>
<p>The language used is Haskell and thus will be very hard to translate to a non functional language if that is the desire (I would think translation to many other FP languages would still be quite hard).</p>
<p>The code is not based on converting to a series of automata and then combining them, instead it is based on symbolic manipulation of the regexes themselves.</p>
<p>Also the code is very much experimental and Martin is no longer a professor but is in 'gainful employment'(1) so may be uninterested/unable to supply any help or input.</p>
<hr>
<ol>
<li>this is a joke - I like professors, the less the smart ones try to work the more chance I have of getting paid!</li>
</ol> |
129,628 | What is declarative programming? | <p>I keep hearing this term tossed around in several different contexts. What is it?</p> | 129,639 | 18 | 4 | null | 2008-09-24 20:15:26.857 UTC | 75 | 2018-04-17 06:48:11.387 UTC | 2008-09-29 11:25:20.603 UTC | Sam Hasler | 2,541 | Brian | 3,208 | null | 1 | 193 | programming-languages|declarative|glossary | 127,961 | <p>Declarative programming is when you write your code in such a way that it describes what you want to do, and not how you want to do it. It is left up to the compiler to figure out the how. </p>
<p>Examples of declarative programming languages are SQL and Prolog.</p> |
374,644 | How do I capture response of form.submit | <p>I have the following code:</p>
<pre><code><script type="text/javascript">
function SubmitForm()
{
form1.submit();
}
function ShowResponse()
{
}
</script>
.
.
.
<div>
<a href="#" onclick="SubmitForm();">Click</a>
</div>
</code></pre>
<p>I want to capture the html response of <code>form1.submit</code>? How do I do this? Can I register any callback function to form1.submit method?</p> | 374,677 | 20 | 0 | null | 2008-12-17 14:15:01.85 UTC | 43 | 2020-09-25 20:58:30.71 UTC | 2019-10-17 10:06:49.843 UTC | sblundy | 4,370,109 | Ngm | 46,279 | null | 1 | 158 | javascript|forms|dom-events|form-submit | 424,425 | <p>You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the <code>submit()</code> function doesn't actually return anything, it just sends the form data to the server.</p>
<p>If you really wanted to get the response in Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll <em>need</em> to use a library. <a href="http://www.jquery.com" rel="noreferrer">jQuery</a> is by far the most popular, and my personal favourite. There's a great plugin for jQuery called <a href="http://malsup.com/jquery/form/" rel="noreferrer">Form</a> which will do exactly what it sounds like you want.</p>
<p>Here's how you'd use jQuery and that plugin:</p>
<pre><code>$('#myForm')
.ajaxForm({
url : 'myscript.php', // or whatever
dataType : 'json',
success : function (response) {
alert("The server says: " + response);
}
})
;
</code></pre> |
511,761 | js function to get filename from url | <p>I have a url like <a href="http://www.example.com/blah/th.html" rel="noreferrer">http://www.example.com/blah/th.html</a></p>
<p>I need a javascript function to give me the 'th' value from that.</p>
<p>All my urls have the same format (2 letter filenames, with .html extension).</p>
<p>I want it to be a safe function, so if someone passes in an empty url it doesn't break.</p>
<p>I know how to check for length, but I should be checking for null to right?</p> | 17,143,667 | 23 | 2 | null | 2009-02-04 15:11:45.09 UTC | 12 | 2022-08-13 01:35:11.267 UTC | null | null | null | Blankman | 39,677 | null | 1 | 76 | javascript|function | 93,178 | <pre><code>var filename = url.split('/').pop()
</code></pre> |
6,934,752 | Combining multiple commits before pushing in Git | <p>I have a bunch of commits on my local repository which are thematically similar. I'd like to combine them into a single commit before pushing up to a remote. How do I do it? I think <code>rebase</code> does this, but I can't make sense of the docs.</p> | 6,934,882 | 8 | 4 | null | 2011-08-04 00:04:00.567 UTC | 183 | 2022-05-21 03:34:51.97 UTC | 2014-06-06 08:09:07.86 UTC | user456814 | null | null | 288,843 | null | 1 | 465 | git|git-squash | 322,720 | <p>What you want to do is referred to as "squashing" in git. There are lots of options when you're doing this (too many?) but if you just want to merge all of your unpushed commits into a single commit, do this:</p>
<pre><code>git rebase -i origin/master
</code></pre>
<p>This will bring up your text editor (<code>-i</code> is for "interactive") with a file that looks like this:</p>
<pre><code>pick 16b5fcc Code in, tests not passing
pick c964dea Getting closer
pick 06cf8ee Something changed
pick 396b4a3 Tests pass
pick 9be7fdb Better comments
pick 7dba9cb All done
</code></pre>
<p>Change all the <code>pick</code> to <code>squash</code> (or <code>s</code>) except the first one:</p>
<pre><code>pick 16b5fcc Code in, tests not passing
squash c964dea Getting closer
squash 06cf8ee Something changed
squash 396b4a3 Tests pass
squash 9be7fdb Better comments
squash 7dba9cb All done
</code></pre>
<p>Save your file and exit your editor. Then another text editor will open to let you combine the commit messages from all of the commits into one big commit message.</p>
<p>Voila! Googling "git squashing" will give you explanations of all the other options available.</p> |
6,563,091 | Can Excel interpret the URLs in my CSV as hyperlinks? | <p>Can Excel interpret the URLs in my CSV as hyperlinks? If so, how?</p> | 8,027,013 | 9 | 1 | null | 2011-07-03 13:13:26.97 UTC | 7 | 2022-05-25 19:15:35.887 UTC | 2011-07-03 13:54:37.56 UTC | null | 343,238 | null | 618,355 | null | 1 | 76 | excel|csv|hyperlink | 52,306 | <p>You can actually do this and have Excel show a clickable link. Use this format in the CSV file:</p>
<pre><code>=HYPERLINK("URL")
</code></pre>
<p>So the CSV would look like:</p>
<pre><code>1,23.4,=HYPERLINK("http://www.google.com")
</code></pre>
<p>However, I'm trying to get some links with commas in them to work properly and it doesn't look like there's a way to escape them and still have Excel make the link clickable.</p>
<p>Does anyone know how?</p> |
15,987,014 | How to remove jQuery Mobile styling? | <p>I chose jQuery Mobile over other frameworks for its animation capabilities and dynamic pages support.</p>
<p>However, I'm running into troubles with styling. I'd like to keep the basic page style in order to perform page transitions. But I also need to fully customize the look'n feel of headers, listviews, buttons, searchboxes... Dealing with colors only is not enough. I need to handle dimensions, positions, margins, paddings, and so on.</p>
<p>Therefore I struggle with extra divs and classes added by jQuery Mobile in order to override them with CSS. But it is so time-consuming, and it would be way faster to rewrite css from scratch...</p>
<p>Is there a way to load a minimal jQuery Mobile css file ?</p>
<p>Or should I look towards an other mobile framework ? I need to handle page transitions, ajax calls, Cordova compatibility, and of course a fully customizable html/css...</p> | 15,997,162 | 5 | 3 | null | 2013-04-13 10:50:37.643 UTC | 12 | 2015-06-12 09:57:50.167 UTC | 2015-06-12 09:57:50.167 UTC | null | 1,848,600 | null | 79,445 | null | 1 | 31 | javascript|html|css|jquery-mobile | 36,691 | <h2>Methods of markup enhancement prevention:</h2>
<p>This can be done in few ways, sometimes you will need to combine them to achieve a desired result.</p>
<ul>
<li><p>Method 1:</p>
<p>It can do it by adding this attribute:</p>
<pre><code>data-enhance="false"
</code></pre>
<p>to the header, content, footer container.</p>
<p>This also needs to be turned in the app loading phase:</p>
<pre><code>$(document).on("mobileinit", function () {
$.mobile.ignoreContentEnabled=true;
});
</code></pre>
<p><strong><em>Initialize it before jquery-mobile.js is initialized (look at the example below).</em></strong></p>
<p>More about this can be found here:</p>
<p><a href="http://jquerymobile.com/test/docs/pages/page-scripting.html">http://jquerymobile.com/test/docs/pages/page-scripting.html</a></p>
<p>Example: <a href="http://jsfiddle.net/Gajotres/UZwpj/">http://jsfiddle.net/Gajotres/UZwpj/</a></p>
<p>To recreate a page again use this:</p>
<pre><code>$('#index').live('pagebeforeshow', function (event) {
$.mobile.ignoreContentEnabled = false;
$(this).attr('data-enhance','true');
$(this).trigger("pagecreate")
});
</code></pre></li>
<li><p>Method 2:</p>
<p>Second option is to do it manually with this line:</p>
<pre><code>data-role="none"
</code></pre>
<p>Example: <a href="http://jsfiddle.net/Gajotres/LqDke/">http://jsfiddle.net/Gajotres/LqDke/</a></p></li>
<li><p>Method 3:</p>
<p>Certain HTML elements can be prevented from markup enhancement:</p>
<pre><code> $(document).bind('mobileinit',function(){
$.mobile.keepNative = "select,input"; /* jQuery Mobile 1.4 and higher */
//$.mobile.page.prototype.options.keepNative = "select, input"; /* jQuery Mobile 1.4 and lower */
});
</code></pre>
<p>Example: <a href="http://jsfiddle.net/Gajotres/gAGtS/">http://jsfiddle.net/Gajotres/gAGtS/</a></p>
<p><strong><em>Again initialize it before jquery-mobile.js is initialized (look at the example below).</em></strong></p></li>
</ul>
<p>Read more about it in my other tutorial: <strong><a href="http://www.gajotres.net/how-to-remove-jquery-mobile-styling/">jQuery Mobile: Markup Enhancement of dynamically added content</a></strong></p> |
15,873,153 | Explanation of Algorithm for finding articulation points or cut vertices of a graph | <p>I have searched the net and could not find any explanation of a DFS algorithm for finding all articulation vertices of a graph. There is not even a wiki page.</p>
<p>From reading around, I got to know the basic facts from here. <a href="https://web.archive.org/web/20130718095926/http://sydney.edu.au/engineering/it/~mestre/class/2012s2/material/DFS.pdf" rel="noreferrer">PDF</a></p>
<p>There is a variable at each node which is actually looking at back edges and finding the closest and upmost node towards the root node. After processing all edges it would be found.</p>
<p>But I do not understand how to find this down & up variable at each node during the execution of DFS. What is this variable doing exactly?</p>
<p>Please explain the algorithm.</p>
<p>Thanks.</p> | 16,203,988 | 4 | 5 | null | 2013-04-08 07:04:42.64 UTC | 15 | 2021-07-23 01:29:05.157 UTC | 2021-07-23 01:29:05.157 UTC | null | 553,073 | null | 728,407 | null | 1 | 34 | algorithm|graph|complexity-theory|graph-algorithm|depth-first-search | 51,279 | <p>Finding articulation vertices is an application of DFS.</p>
<p>In a nutshell,</p>
<ol>
<li>Apply DFS on a graph. Get the DFS tree.</li>
<li>A node which is visited earlier is a "parent" of those nodes which are reached by it and visited later.</li>
<li>If any child of a node does not have a path to any of the ancestors of its parent, it means that removing this node would make this child disjoint from the graph. </li>
<li>There is an exception: the root of the tree. If it has more than one child, then it is an articulation point, otherwise not.</li>
</ol>
<p>Point 3 essentially means that this node is an articulation point.</p>
<p>Now for a child, this path to the ancestors of the node would be through a back-edge from it or from any of its children. </p>
<p>All this is explained beautifully in this <a href="http://www.eecs.wsu.edu/~holder/courses/CptS223/spr08/slides/graphapps.pdf" rel="noreferrer">PDF</a>.</p> |
15,882,326 | Angular, onLoad function on an iFrame | <p>I have this iframe working with basic JavaScript:</p>
<pre><code><iframe id="upload_iframe" name="upload_iframe" onLoad="uploadDone();"></iframe>
</code></pre>
<p>Which triggers the method <code>uploadDone();</code> when the content of the iframe has been loaded.</p>
<p>How do I do the same thing in Angular?. I want to call a function on the controller when the iframe loads, but I haven't seen a <code>ng-onload</code> so far.</p> | 15,882,735 | 5 | 0 | null | 2013-04-08 14:53:44.39 UTC | 15 | 2021-03-14 21:43:46.167 UTC | 2014-11-26 21:27:06.637 UTC | null | 303,914 | null | 1,180,686 | null | 1 | 56 | iframe|angularjs | 81,284 | <p>try defining the function within controller as:</p>
<pre><code>window.uploadDone=function(){
/* have access to $scope here*/
}
</code></pre> |
15,607,873 | What does the * * CSS selector do? | <p>Recently I came across <code>* *</code> in <a href="http://en.wikipedia.org/wiki/Cascading_Style_Sheets" rel="noreferrer">CSS</a>.</p>
<p>Site reference - <a href="http://semlabs.co.uk/journal/how-to-stop-your-wordpress-blog-getting-hacked" rel="noreferrer">Site Link</a>.</p>
<p>For a single <code>*</code> usage in CSS style sheet, Internet and Stack Overflow is flooded with examples, but I am not sure about using two <code>* *</code> symbol in CSS.</p>
<p>I googled it, but unable to find any relevant information about this, as a single <code>*</code> selects all elements, but I am not sure why the site used it twice. What is the missing part for this, and why is this hack used (if it is a hack)?</p> | 15,607,906 | 5 | 0 | null | 2013-03-25 04:52:52.253 UTC | 27 | 2014-12-18 08:09:25.197 UTC | 2013-07-04 18:58:53.373 UTC | null | 639,406 | null | 639,406 | null | 1 | 97 | html|css|css-selectors | 3,272 | <p>Just like any other time you put two selectors one after another (for example <code>li a</code>), you get the descendant combinator. So <code>* *</code> is any element that is a descendant of any other element — in other words, any element that <em>isn't</em> the root element of the whole document.</p> |
10,537,294 | Multiple string matches with indexOf() | <p>Im pretty sure my syntax this wrong because the script only works if the string matches "Video", if the string has the "word "Audio" it is ignored. Also since the href tags have a value of "#" the redirect for "../../../index.html" doesnt work.</p>
<p>js</p>
<pre><code>var ua = navigator.userAgent.toLowerCase();
var isIE8 = /MSIE 8.0/i.test(ua);
if (isIE8) {
$('a').click(function () {
var srcTag = $(this).find('img').attr('src');
if (srcTag.indexOf('Video' || 'Audio') > -1) {
if (confirm('Download Safari? \n\n http://apple.com/safari/download/')) {
window.location = 'http://apple.com/safari/download/';
} else { window.location = '../../../index.html';}
} else {
alert('no match');
}
});
}
</code></pre>
<p>html</p>
<pre><code><a href="#"><img src="Video/000_Movies/assets/005_CCC_Jesus_Story_80x60.jpg" />test1</a>
<a href="#"><img src="Audio/000_Movies/assets/006_GSP_Gods_Story_80x60.jpg" />test2</a>
<a href="#"><img src="Media/000_Movies/assets/002_God_Man_80x60.jpg" />test3</a>
</code></pre> | 10,537,354 | 9 | 5 | null | 2012-05-10 15:25:47.103 UTC | 13 | 2020-10-16 09:22:55.317 UTC | 2012-05-10 15:47:56.547 UTC | null | 54,680 | null | 1,159,429 | null | 1 | 24 | javascript|jquery|html | 69,426 | <p>It's far shorter to turn this into a regular expression.</p>
<pre><code>if ( srcTag.match( /(video|audio)/ ) ) {
/* Found */
} else {
/* Not Found */
}
</code></pre>
<p>On a side note, please don't do what you're attempting to do. Asking users to download Safari when they're using Internet Explorer 8 is doing a disservice to the Internet, as well as to that user.</p>
<p>As for redirecting the domain to another location, you should use <code>.preventDefault()</code> to keep the browser from following the link:</p>
<pre><code>$("a.videoDownload").on("click", function(e){
e.preventDefault();
if ( this.getElementsByTagName("img")[0].src.match( /(video|audo)/ ) ) {
window.location = confirm( 'Download Safari?' )
? "http://apple.com/safari/download"
: "../../../index.html" ;
} else {
/* No match */
}
});
</code></pre>
<p>Again, please don't <em>actually</em> do this. Nobody wants to be <em>that guy</em>, and when you tell users to download another browser, you're being <em>that guy</em>.</p> |
10,299,901 | How do sites like goo.gl or jsfiddle generate their URL codes? | <p>I would like to generate a code like <a href="http://goo.gl/UEhtg" rel="noreferrer">goo.gl</a> and <a href="http://jsfiddle.net/XzKvP/" rel="noreferrer">jsfiddle</a> websites (<code>http://jsfiddle.net/XzKvP/</code>). </p>
<p>I tried different things that give me too large of a guid, a repeating alphanumeric code, etc. </p>
<p>I'm thinking I should be able to generate an alphanumeric code based on the Primary Key in my database table. This way it will be non-repeating? The PK is an auto-incremented integer by 1. But not sure that's how it should be done.</p>
<p>I want the code to <strong><em>look</em></strong> random, but it does <strong><em>NOT</em></strong> have to be.
For example, I do <strong><em>NOT</em></strong> want item <code>1234</code> in my database to be <code>BCDE</code> and the <code>1235</code> item to be <code>BCDF</code>.</p>
<p><strong>Examples:</strong> </p>
<p>Notice how the url <code>http://jsfiddle.net/XzKvP/</code> has a unique 5 character code <code>XzKvP</code> associated to the page. I want to be able to generate the same type of code. </p>
<p>goo.gl does it too: <a href="http://goo.gl/UEhtg" rel="noreferrer">http://goo.gl/UEhtg</a> has <code>UEhtg</code></p>
<p><strong>How is this done?</strong></p> | 17,592,413 | 3 | 7 | null | 2012-04-24 14:21:07.443 UTC | 17 | 2013-07-11 14:09:44.13 UTC | null | null | null | null | 442,580 | null | 1 | 26 | c#|algorithm | 3,321 | <p>The solutions based on a random substring are no good because the outputs will collide. It may happen prematurely (with bad luck), and it will eventually happen when the list of generated values grows large. It doesn't even have to be that large for the probability of collisions to become high (see <a href="http://en.wikipedia.org/wiki/Birthday_attack" rel="noreferrer">birthday attack</a>).</p>
<p>What's good for this problem is a <a href="http://en.wikipedia.org/wiki/Pseudorandom_permutation" rel="noreferrer">pseudo random permutation</a> between the incrementing ID and its counterpart that will be shown in the URL. This technique guarantees that a collision is impossible, while still generating into an output space that is as small as the input space.</p>
<p><strong>Implementation</strong></p>
<p>I suggest this C# version of a <a href="http://en.wikipedia.org/wiki/Feistel_cipher" rel="noreferrer">Feistel cipher</a> with 32 bits blocks, 3 rounds and a <strong>round function</strong> that is inspired by pseudo-random generators.</p>
<pre><code>private static double RoundFunction(uint input)
{
// Must be a function in the mathematical sense (x=y implies f(x)=f(y))
// but it doesn't have to be reversible.
// Must return a value between 0 and 1
return ((1369 * input + 150889) % 714025) / 714025.0;
}
private static uint PermuteId(uint id)
{
uint l1=(id>>16)&65535;
uint r1=id&65535;
uint l2, r2;
for (int i = 0; i < 3; i++)
{
l2 = r1;
r2 = l1 ^ (uint)(RoundFunction(r1) * 65535);
l1 = l2;
r1 = r2;
}
return ((r1 << 16) + l1);
}
</code></pre>
<p>To express the permuted ID in a base62 string:</p>
<pre><code>private static string GenerateCode(uint id)
{
return ToBase62(PermuteId(id));
}
</code></pre>
<p>The <code>Base62</code> function is the same as <a href="https://stackoverflow.com/a/10302978/238814">the previous answer</a> except that is takes <code>uint</code> instead of <code>int</code> (otherwise these functions would have to be rewritten to deal with negative values).</p>
<p><strong>Customizing the algorithm</strong></p>
<p><code>RoundFunction</code> is the secret sauce of the algorithm. You may change it to a non-public version, possibly including a secret key. The Feistel network has two very nice properties:</p>
<ul>
<li><p>even if the supplied <code>RoundFunction</code> is not reversible, the algorithm guarantees that <code>PermuteId()</code> will be a permutation in the mathematical sense (wich implies zero collision).</p></li>
<li><p>changing the expression inside the round function even lightly will change drastically the list of final output values.</p></li>
</ul>
<p>Beware that putting something too trivial in the round expression would ruin the pseudo-random effect, although it would still work in terms of uniqueness of each <code>PermuteId</code> output. Also, an expression that wouldn't be a function in the mathematical sense would be incompatible with the algorithm, so for instance anything involving <code>random()</code> is not allowed.</p>
<p><strong>Reversability</strong></p>
<p>In its current form, the <code>PermuteId</code> function is its own inverse, which means that:</p>
<pre><code>PermuteId(PermuteId(id))==id
</code></pre>
<p>So given a short string produced by the program, if you convert it back to <code>uint</code> with a <code>FromBase62</code> function, and give that as input to <code>PermuteId()</code>, that will return the corresponding initial ID. That's pretty cool if you don't have a database to store the [internal-ID / shortstring] relationships: they don't actually need to be stored!</p>
<p><strong>Producing even shorter strings</strong></p>
<p>The range of the above function is 32 bits, that is about 4 billion values from 0 to <code>2^32-1</code>. To express that range in base62, 6 characters are needed.</p>
<p>With only 5 characters, we could hope to represent at most <code>62^5</code> values, which is a bit under 1 billion. Should the output string be limited to 5 characters, the code should be tweaked as follows:</p>
<ul>
<li><p>find <code>N</code> such that <code>N</code> is even and <code>2^N</code> is as high as possible but lower than <code>62^5</code>. That's 28, so our real output range that fits in <code>62^5</code> is going to be <code>2^28</code> or about 268 million values.</p></li>
<li><p>in <code>PermuteId</code>, use <code>28/2=14</code> bits values for <code>l1</code> and <code>r1</code> instead of 16 bits, while being careful to not ignore a single bit of the input (which must be less than 2^28).</p></li>
<li><p>multiply the result of <code>RoundFunction</code> by 16383 instead of 65535, to stay within the 14 bits range.</p></li>
<li><p>at the end of <code>PermuteId</code>, recombine <code>r1</code> and <code>l1</code> to form a <code>14+14=28</code> bits value instead of 32.</p></li>
</ul>
<p>The same method could be applied for 4 characters, with an output range of <code>2^22</code>, or about 4 million values.</p>
<p><strong>What does it look like</strong></p>
<p>In the version above, the first 10 produced strings starting with id=1 are:</p>
<pre>
cZ6ahF
3t5mM
xGNPN
dxwUdS
ej9SyV
cmbVG3
cOlRkc
bfCPOX
JDr8Q
eg7iuA
</pre>
<p>If I make a trivial change in the round function, that becomes:</p>
<pre>
ey0LlY
ddy0ak
dDw3wm
bVuNbg
bKGX22
c0s5GZ
dfNMSp
ZySqE
cxKH4b
dNqMDA
</pre> |
13,696,906 | Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension | <p>I have tried many ways( all documented procedures)to inject script into a specific page upon checking URL at onUpdated.addListener. Finally the below code with 'executescript' seems to work, but not perfectly. I could able to get alerts but can not able to find document elements of the page through getElementById/getElementsByName.</p>
<p>When I inspected the page, script is injected. But in error console I get:</p>
<blockquote>
<p>Denying load of chrome-extension://jfeiadiicafjpmaefageabnpamkapdhe/js/Leoscript.js. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.</p>
</blockquote>
<p>Manifest.json:</p>
<pre class="lang-json prettyprint-override"><code>{
"name": "Leo Extension for Job Boards",
"version": "1.6",
"manifest_version": 2,
"content_security_policy": "script-src 'self'; object-src 'self'",
"description": "Leo Extension",
"background": {
"scripts": ["js/Leojshelper.js"],
"persistent": true
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["js/eventPage.js"],
"run_at" : "document_start"
}
],
"icons":{"48":"images/bob48.png", "128":"images/bob128.png"}, //Define any icon sizes and the files that you want to use with them. 48/128 etc.
"browser_action": {
"default_icon": "images/bob.png", // What icon do you want to display on the chrome toolbar
"default_popup": "LeoExtwatch.html" // The page to popup when button clicked.
},
"permissions": [
"tabs", "<all_urls>" // "http://*/*","https://*/*" // Cross Site Access Requests
],
"web_accessible_resources": ["js/LeoScript.js"]
}
</code></pre>
<p>I have also given 'web_accessible_resources' permission to the script, but still no success. Code in background script:</p>
<pre class="lang-js prettyprint-override"><code>chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
if (tab.url.indexOf("in.yahoo") !== -1) {
chrome.tabs.update(tabId, { url: "https://login.yahoo.com/config/mail?.intl=us" });
chrome.tabs.executeScript(tabId, {
code: "document.body.appendChild(document.createElement('script')).src='" +
chrome.extension.getURL("js/LeoScript.js") + "';"
}, null);
</code></pre>
<p>Code in LeoScript.js, which will be injected into specific page. </p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
alert('injected');
document.getElementById('username').value='aaaaaaa';
});
</code></pre>
<p>Content Script :eventPage.js which I used to inject script.</p>
<pre class="lang-js prettyprint-override"><code>var script = document.createElement('script');
script.src = chrome.extension.getURL("js/Leoscript.js");
(document.body || document.head || document.documentElement).appendChild(script);
</code></pre>
<p>Please point me at any changes in the above code that will solve the permission issues. Thanks in advance.</p> | 13,696,976 | 3 | 0 | null | 2012-12-04 05:52:17.497 UTC | 9 | 2017-08-11 12:55:36.623 UTC | 2017-08-11 12:55:36.623 UTC | null | 2,724,961 | null | 1,865,673 | null | 1 | 32 | google-chrome|google-chrome-extension | 70,499 | <p><strong>UPDATE:</strong> Finally figured out your problem. In eventPage.js, you tried to inject js/Leoscript.js, which is NOT whitelisted, instead of js/LeoScript.js (with a capital 'S'), which is whitelisted. Note that URLs are <em>case-sensitive</em>!</p>
<pre><code>chrome.tabs.executeScript(tabId, {file: 'js/LeoScript.js'});
</code></pre>
<p>LeoScript.js: </p>
<pre><code>alert('injected');
document.getElementById('username').value='aaaaaaa';
</code></pre> |
13,678,993 | How should I test a Future in Dart? | <p>How can one test a method that returns <code>Future</code> before the test runner completes? I have a problem where my unit test runner completes before the asynchronous methods are completed. </p> | 13,678,996 | 6 | 0 | null | 2012-12-03 07:36:20.083 UTC | 3 | 2020-12-04 04:38:40.613 UTC | 2013-02-07 00:45:17.763 UTC | null | 123,471 | null | 1,127,340 | null | 1 | 33 | unit-testing|dart | 14,470 | <p>Full example of how to test with the <code>completion</code> matcher is as follows.</p>
<pre class="lang-java prettyprint-override"><code>import 'package:unittest/unittest.dart';
class Compute {
Future<Map> sumIt(List<int> data) {
Completer completer = new Completer();
int sum = 0;
data.forEach((i) => sum += i);
completer.complete({"value" : sum});
return completer.future;
}
}
void main() {
test("testing a future", () {
Compute compute = new Compute();
Future<Map> future = compute.sumIt([1, 2, 3]);
expect(future, completion(equals({"value" : 6})));
});
}
</code></pre>
<p>The unit test runner might not complete before this code completes. So it would seem that the unit test executed correctly. With <code>Future</code>s that might take longer periods of time to complete the proper way is to utilize <code>completion</code> matcher available in unittest package. </p>
<pre class="lang-java prettyprint-override"><code>/**
* Matches a [Future] that completes succesfully with a value that matches
* [matcher]. Note that this creates an asynchronous expectation. The call to
* `expect()` that includes this will return immediately and execution will
* continue. Later, when the future completes, the actual expectation will run.
*
* To test that a Future completes with an exception, you can use [throws] and
* [throwsA].
*/
Matcher completion(matcher) => new _Completes(wrapMatcher(matcher));
</code></pre>
<p>One would be tempted to do the following which would be incorrect way of unit testing a returned Future in dart. WARNING: below is an incorrect way to test Futures. </p>
<pre class="lang-java prettyprint-override"><code>import 'package:unittest/unittest.dart';
class Compute {
Future<Map> sumIt(List<int> data) {
Completer completer = new Completer();
int sum = 0;
data.forEach((i) => sum+=i);
completer.complete({"value":sum});
return completer.future;
}
}
void main() {
test("testing a future", () {
Compute compute = new Compute();
compute.sumIt([1, 2, 3]).then((Map m) {
Expect.equals(true, m.containsKey("value"));
Expect.equals(6, m["value"]);
});
});
}
</code></pre> |
13,590,139 | Remove numbers from alphanumeric characters | <p>I have a list of alphanumeric characters that looks like: </p>
<pre><code>x <-c('ACO2', 'BCKDHB456', 'CD444')
</code></pre>
<p>I would like the following output: </p>
<pre><code>x <-c('ACO', 'BCKDHB', 'CD')
</code></pre>
<p>Any suggestions?</p>
<pre><code># dput(tmp2)
structure(c(432L, 326L, 217L, 371L, 179L, 182L, 188L, 268L, 255L,...,
), class = "factor")
</code></pre> | 13,590,204 | 4 | 0 | null | 2012-11-27 17:52:16.663 UTC | 14 | 2021-09-01 20:40:26.003 UTC | 2016-02-29 22:25:07.363 UTC | null | 680,068 | null | 1,791,307 | null | 1 | 56 | regex|r | 93,695 | <p>You can use <code>gsub</code> for this:</p>
<pre><code>gsub('[[:digit:]]+', '', x)
</code></pre>
<p>or</p>
<pre><code>gsub('[0-9]+', '', x)
# [1] "ACO" "BCKDHB" "CD"
</code></pre> |
13,366,730 | Proper REST response for empty table? | <p>Let's say you want to get list of users by calling <code>GET</code> to <code>api/users</code>, but currently the table was truncated so there are no users. What is the proper response for this scenario: <code>404</code> or <code>204</code>?</p> | 13,367,198 | 5 | 5 | null | 2012-11-13 18:43:33.267 UTC | 26 | 2021-03-26 10:57:28.317 UTC | 2021-03-26 10:57:28.317 UTC | null | 9,213,345 | null | 748,789 | null | 1 | 141 | http|rest | 54,630 | <p>I'd say, neither.</p>
<h2>Why not 404 (Not Found) ?</h2>
<p>The 404 status code should be reserved for situations, in which a resource is not found. In this case, your resource is <em>a collection of users</em>. This collection exists but it's currently empty. Personally, I'd be very confused as an author of a client for your application if I got a <code>200</code> one day and a <code>404</code> the next day just because someone happened to remove a couple of users. What am I supposed to do? Is my URL wrong? Did someone change the API and neglect to leave a redirection.</p>
<h2>Why not 204 (No Content) ?</h2>
<p>Here's an excerpt from <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noreferrer">the description of the 204 status code by w3c</a></p>
<blockquote>
<p>The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.</p>
</blockquote>
<p>While this may seem reasonable in this case, I think it would also confuse clients. A <code>204</code> is supposed to indicate that some operation was executed successfully and no data needs to be returned. This is perfect as a response to a <code>DELETE</code> request or perhaps firing some script that does not need to return data. In case of <code>api/users</code>, you usually expect to receive a representation of your collection of users. Sending a response body one time and not sending it the other time is inconsistent and potentially misleading.</p>
<h2>Why I'd use a 200 (OK)</h2>
<p>For reasons mentioned above (consistency), I would return a representation of an empty collection. Let's assume you're using XML. A normal response body for a non-empty collection of users could look like this:</p>
<pre><code><users>
<user>
<id>1</id>
<name>Tom</name>
</user>
<user>
<id>2</id>
<name>IMB</name>
</user>
</users>
</code></pre>
<p>and if the list is empty, you could just respond with something like this (while still using a <code>200</code>):</p>
<pre><code><users/>
</code></pre>
<p>Either way, a client receives a response body that follows a certain, well-known format. There's no unnecessary confusion and status code checking. Also, no status code definition is violated. Everybody's happy.</p>
<p>You can do the same with JSON or HTML or whatever format you're using.</p> |
20,581,920 | Static IP Address with Heroku (not Proximo) | <p>Is there a way to get one Static IP address for a Heroku Server? I'm trying to integrate various API's which ask for an IP address. Because of Heroku's server setup, you never have one server with a static IP - instead your IP is dynamic.</p>
<p>I've looked into add-ons like Proximo, however this appears to be a paid-for solution. Is there a solution where you have a static IP that you don't have to pay for?</p> | 20,777,622 | 3 | 2 | null | 2013-12-14 10:03:20.373 UTC | 13 | 2019-05-13 06:05:46.093 UTC | null | null | null | null | 1,775,598 | null | 1 | 34 | heroku|ip|static-ip-address | 27,353 | <p>You can use <a href="https://addons.heroku.com/quotaguardstatic" rel="noreferrer">QuotaGuard Static</a> Heroku add-on.</p>
<p>QuotaGuard can be attached to a Heroku application via the command line:</p>
<pre><code>$ heroku addons:add quotaguardstatic
</code></pre>
<p>After installing, the application should be configured to fully integrate with the add-on.
When you sign up you will be provided with a unique username and password that you can use when configuring your proxy service in your application</p>
<p>A QUOTAGUARDSTATIC_URL setting will be available in the app configuration and will contain the full URL you should use to proxy your API requests.
This can be confirmed using the next command:</p>
<pre><code>$ heroku config:get QUOTAGUARDSTATIC_URL
http://user:[email protected]:9293
</code></pre>
<p>All requests that you make via this proxy will appear to the destination server to originate from one of the two static IPs you will be assigned when you sign up.</p>
<p>You can use A simple HTTP and REST client for Ruby for detecting your IP:</p>
<pre><code>$ gem install rest-client
</code></pre>
<p>Next, you can run the below example in an IRB session and verify that the final IP returned is one of your two static IPs.</p>
<pre><code>$ irb
>require "rest-client"
>RestClient.proxy = 'http://user:[email protected]:9293'
>res = RestClient.get("http://ip.jsontest.com")
</code></pre>
<p>That's it:)</p> |
24,071,525 | What is the equivalent for java interfaces or objective c protocols in swift? | <p>I've been looking in to the new Swift language trying to find what's the equivalent for an interface(in java) or a protocol(in objective-c) in Swift, after surfing on the internet and searching in the book provided by Apple, I still can't seem to find it.</p>
<p>Does any one know what's the name of this component in swift and what's its syntax?</p> | 24,071,596 | 2 | 2 | null | 2014-06-05 22:54:38.68 UTC | 7 | 2017-11-06 20:27:46.307 UTC | 2017-06-30 15:42:40.713 UTC | null | 1,033,581 | null | 1,965,099 | null | 1 | 32 | ios|macos|interface|protocols|swift | 37,528 | <p><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html" rel="noreferrer">Protocols in Swift</a> are very similar to Objc, except you may use them not only on classes, but also on structs and enums.</p>
<pre><code>protocol SomeProtocol {
var fullName: String { get } // You can require iVars
class func someTypeMethod() // ...or class methods
}
</code></pre>
<p>Conforming to a protocol is a bit different:</p>
<pre><code>class myClass: NSObject, SomeProtocol // Specify protocol(s) after the class type
</code></pre>
<p>You can also extend a protocol with a default (overridable) function implementation:</p>
<pre><code>extension SomeProtocol {
// Provide a default implementation:
class func someTypeMethod() {
print("This implementation will be added to objects that adhere to SomeProtocol, at compile time")
print("...unless the object overrides this default implementation.")
}
}
</code></pre>
<p><em>Note: default implementations must be added via extension, and not in the protocol definition itself - a protocol is not a concrete object, so it can't actually have method bodies attached. Think of a default implementation as a C-style template; essentially the compiler copies the declaration and pastes it into each object which adheres to the protocol.</em></p> |
3,837,394 | MongoDB map/reduce over multiple collections? | <p>First, the background. I used to have a collection <code>logs</code> and used map/reduce to generate various reports. Most of these reports were based on data from within a single day, so I always had a condition <code>d: SOME_DATE</code>. When the <code>logs</code> collection grew extremely big, inserting became extremely slow (slower than the app we were monitoring was generating logs), even after dropping lots of indexes. So we decided to have each day's data in a separate collection - <code>logs_YYYY-mm-dd</code> - that way indexes are smaller, and we don't even need an index on date. This is cool since most reports (thus map/reduce) are on daily data. However, we have a report where we need to cover multiple days.</p>
<p>And now the question. Is there a way to run a map/reduce (or more precisely, the map) over multiple collections as if it were only one?</p> | 3,837,773 | 2 | 0 | null | 2010-10-01 08:01:10.8 UTC | 13 | 2017-12-01 21:26:25.897 UTC | 2010-10-01 08:27:39.803 UTC | null | 5,475 | null | 5,475 | null | 1 | 16 | mongodb|mapreduce | 17,600 | <p>A reduce function may be called once, with a key and <strong>all corresponding values</strong> (but only if there are multiple values for the key - it won't be called at all if there's only 1 value for the key).</p>
<p>It may also be called multiple times, each time with a key and only a <strong>subset of the corresponding values</strong>, and the previous reduce results for that key. This scenario is called a <strong>re-reduce</strong>. In order to support re-reduces, your reduce function should be <a href="http://en.wikipedia.org/wiki/Idempotent" rel="noreferrer">idempotent</a>.</p>
<p>There are two key features in a idempotent reduce function:</p>
<ul>
<li>The <strong>return value</strong> of the reduce function should be in the <strong>same format as the values</strong> it takes in. So, if your reduce function accepts an array of strings, the function should return a string. If it accepts objects with several properties, it should return an object containing those same properties. This ensures that the function doesn't break when it is called with the result of a previous reduce.</li>
<li><strong>Don't make assumptions based on the number of values</strong> it takes in. It isn't guaranteed that the <code>values</code> parameter contains <em>all</em> the values for the given key. So using <code>values.length</code> in calculations is very risky and should be avoided.</li>
</ul>
<p><strong>Update:</strong> The two steps below aren't required (or even possible, I haven't checked) on the more recent MongoDB releases. It can now handle these steps for you, if you specify an output collection in the map-reduce <a href="http://docs.mongodb.org/manual/reference/method/db.collection.mapReduce/#out-options" rel="noreferrer">options</a>:</p>
<pre><code>{ out: { reduce: "tempResult" } }
</code></pre>
<hr>
<p>If your reduce function is idempotent, you shouldn't have any problems map-reducing multiple collections. Just re-reduce the results of each collection:</p>
<h3>Step 1</h3>
<p>Run the map-reduce on each required collection and save the results in a single, temporary collection. You can store the results using a <a href="http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-FinalizeFunction" rel="noreferrer">finalize function</a>:</p>
<pre><code>finalize = function (key, value) {
db.tempResult.save({ _id: key, value: value });
}
db.someCollection.mapReduce(map, reduce, { finalize: finalize })
db.anotherCollection.mapReduce(map, reduce, { finalize: finalize })
</code></pre>
<h3>Step 2</h3>
<p>Run another map-reduce on the temporary collection, <strong>using the same reduce function</strong>. The map function is a simple function that selects the keys and values from the temporary collection:</p>
<pre><code>map = function () {
emit(this._id, this.value);
}
db.tempResult.mapReduce(map, reduce)
</code></pre>
<p>This second map-reduce is basically a re-reduce and should give you the results you need.</p> |
3,922,461 | Extract Column from data.frame as a Vector | <p>I'm new to R.</p>
<p>I have a a Data.frame with a column called "Symbol".</p>
<pre><code> Symbol
1 "IDEA"
2 "PFC"
3 "RPL"
4 "SOBHA"
</code></pre>
<p>I need to store its values as a vector(<code>x = c("IDEA","PFC","RPL","SOBHA")</code>). Which is the most concise way of doing this?</p> | 3,922,499 | 2 | 0 | null | 2010-10-13 09:53:36.003 UTC | 7 | 2020-12-05 07:03:03.207 UTC | 2016-12-01 15:44:05.697 UTC | null | 2,040,375 | null | 216,517 | null | 1 | 27 | r|vector|dataframe | 80,500 | <pre><code>your.data <- data.frame(Symbol = c("IDEA","PFC","RPL","SOBHA"))
new.variable <- as.vector(your.data$Symbol) # this will create a character vector
</code></pre>
<p>VitoshKa suggested to use the following code.</p>
<pre><code>new.variable.v <- your.data$Symbol # this will retain the factor nature of the vector
</code></pre>
<p>What you want depends on what you need. If you are using this vector for further analysis or plotting, retaining the factor nature of the vector is a sensible solution.</p>
<p>How these two methods differ:</p>
<pre><code>cat(new.variable.v)
#1 2 3 4
cat(new.variable)
#IDEA PFC RPL SOBHA
</code></pre> |
3,463,256 | What are some great Quartz 2D drawing tutorials? | <p>I'm searching for some great Quartz 2D drawing tutorials aimed at the iPhone. I'm new to Quartz and want to start off with something easy and then progress to more difficult stuff.</p>
<p>Does anyone know of any Quartz 2D drawing tutorials that they would recommend?</p> | 3,464,136 | 2 | 0 | null | 2010-08-11 22:10:57.12 UTC | 24 | 2019-06-08 09:57:27.99 UTC | 2010-08-12 01:38:38.38 UTC | null | 19,679 | null | 414,336 | null | 1 | 30 | iphone|core-graphics|quartz-graphics | 16,847 | <p>I devoted an entire class to Quartz 2D drawing last semester in my advanced iPhone development course. The video for that is available <a href="https://podcasts.apple.com/us/podcast/advanced-iphone-development-spring-2010/id407243032" rel="nofollow noreferrer">on iTunes U</a>, along with the rest of the class. The course notes for that session can be found <a href="http://www.sunsetlakesoftware.com/sites/default/files/Spring2010CourseNotes/quartz%202d%20drawing.html" rel="nofollow noreferrer">here</a>, and I created a <a href="http://www.sunsetlakesoftware.com/sites/default/files/QuartzExamples.zip" rel="nofollow noreferrer">sample application</a> to show off some more advanced Quartz drawing concepts.</p>
<p>Beyond that, I highly recommend reading the <a href="https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/Introduction/Introduction.html" rel="nofollow noreferrer">Quartz 2D Programming Guide</a>.</p> |
3,369,791 | Java VM tuning - Xbatch and -Xcomp | <p>I am looking at the JVM configuration options for running Alfresco, mainly <a href="http://wiki.alfresco.com/wiki/JVM_Tuning" rel="noreferrer">this</a> document on the <a href="http://wiki.alfresco.com/wiki/Main_Page" rel="noreferrer">Alfresco Wiki</a>. One of the recommendations is to use the JVM flags <code>-Xcomp</code> and <code>-Xbatch</code>. The justification of this is:</p>
<blockquote>
<p>If you wish to have Hotspot precompile the classes, you can add [-Xcomp and -Xbatch]. This will, however, significantly increase the server startup time, but will highlight missing dependencies that can be hit later.</p>
</blockquote>
<p>From what I have <a href="http://blogs.oracle.com/watt/resource/jvm-options-list.html" rel="noreferrer">read elsewhere</a> about the <code>-Xcomp</code> and <code>-Xbatch</code> flags, I am wondering whether they really provide any benefit.</p>
<ul>
<li><code>-Xcomp</code> gets HotSpot to compile all code beforehand with maximum optimization, thus foregoing any profiling that the VM will get through the standard running of the system.</li>
<li><code>-Xbatch</code> stops background compiling, meaning the thread which caused the code to be compiled blocks until the compile is complete. However, after the compile is finished, the previously-blocked thread <em>will not run the compiled code</em>, <a href="http://blogs.oracle.com/fatcatair/entry/more_tiered_compilation" rel="noreferrer">it will still run the interpreted code</a>. This was a change in Java 6 (Mustang) – before Mustang, threads blocked for compiling by the presence of the <code>-Xbatch</code> flag were guaranteed to run in the compiled code as soon as the compile was completed. Therefore, I am guessing that the recommendation of the <code>-Xbatch</code> flag is a relic of running Alfresco on older VMs.</li>
</ul>
<p>Does anyone have any thoughts? My inclination is to get rid of these two flags and rely on the VM to get things right.</p>
<p>I would like to add two things, first of all that I don't yet have access to an Alfresco instance to test this on and secondly I don't really know what spec of machine is hosting Alfresco other than that by looking at the other configuration options it must be a 64 bit VM. Despite this, I hope the community will have some useful input, perhaps from a general HotSpot-tuning point of view.</p> | 3,439,450 | 2 | 2 | null | 2010-07-30 08:27:13.297 UTC | 10 | 2012-07-29 14:48:35.013 UTC | 2012-07-27 23:01:11.587 UTC | null | 1,288 | null | 68,283 | null | 1 | 34 | java|jvm|jvm-hotspot|jvm-arguments | 11,353 | <p>Generally speaking, it's always preferable to let HotSpot compiler tune itself. Even using Server VM (-server) is default for 64bits and some 'server-class' machines.</p>
<p>-Xbatch was intended mostly for debugging as described in <a href="http://blogs.oracle.com/fatcatair/entry/more_tiered_compilation" rel="noreferrer">Steve Goldman's blog</a> you pointed:</p>
<blockquote>
<p>So the -Xbatch switch is not a particularly useful switch even in the pre-mustang days. It is somewhat useful for jvm developers since it tends to make a run more predictable and reproducible.</p>
</blockquote>
<p>-Xcomp removes the ability to gather information for efficient compilation. From an <a href="http://nerds-central.blogspot.com/2009/09/tuning-jvm-for-unusual-uses-have-some.html" rel="noreferrer">Alex Turner's post</a>:</p>
<blockquote>
<p>One might think that -Xcomp would be a good idea from a performance point of view. However, it is not! The JIT compiler uses those 1000 iterations before compilation to gather information on how the method should be compiled for optimal efficiency. -Xcomp removes its ability to do so and thus we can actually see performance slip.</p>
</blockquote>
<p>Without performance in mind, I've never seen using those flags to detect missing dependencies (<a href="http://markmail.org/message/7vfjptdu5bi32mkm" rel="noreferrer">and it may not work if some code is still interpreted</a>) so IMHO, I would get rid of both.</p> |
3,684,421 | What is WCF RIA services? | <p>I hate MSDN's site for WCF RIA services. It does not say what it is, it only says what it does. It says what it can achieve but does not say why I need it. </p>
<p>For example:</p>
<blockquote>
<p>"A common problem when developing an
n-tier RIA solution is coordinating
application logic between the middle
tier and the presentation tier".</p>
</blockquote>
<p>Well, it does not mean much to me.</p>
<blockquote>
<p>"RIA Services solves this problem by
providing framework components, tools,
and services that make the application
logic on the server available to the
RIA client without requiring you to
manually duplicate that programming
logic. You can create a RIA client
that is aware of business rules and
know that the client is automatically
updated with latest middle tier logic
every time that the solution is
re-compiled."</p>
</blockquote>
<p>So does it download DLLs from server? Is it a metadata describing the rules for the data?</p>
<p>So what is it? Is it just a VS 2010 add-on for RAD? Or is it a technology on top of WCF or underneath it or what? Where does it live? With data, with server, what?</p>
<p>I appreciate if you can summarise this for me please.</p> | 3,684,710 | 2 | 4 | null | 2010-09-10 12:00:28.477 UTC | 25 | 2016-03-28 06:58:40.677 UTC | 2011-03-05 16:46:07.907 UTC | null | 440,502 | null | 440,502 | null | 1 | 103 | c#|.net|wcf|ria | 63,447 | <p>RIA services is a server-side technology that automatically generates client-side (Silverlight) objects that take care of the communication with the server for you and provide client-side validation.</p>
<p>The main object inside a RIA service is a <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.domainservices.server.domainservice(VS.91).aspx" rel="noreferrer"><code>DomainService</code></a>, usually a <a href="http://msdn.microsoft.com/en-us/library/ff423019(VS.91).aspx" rel="noreferrer"><code>LinqToEntitiesDomainService</code></a> that is connected to a LinqToEntities model.</p>
<p>The key thing to remember in RIA services is that it's mainly a sophisticated build trick. When you create a domain service and compile your solution, a client-side representation of your domain service is generated. This client-side representation has the same interface. Suppose you create a server-side domain service <code>CustomerService</code> with a method <code>IQueryable<Customer> GetCustomersByCountry</code>. When you build your solution, a class is generated inside your Silverlight project called <code>CustomerContext</code> that has a method <code>GetCustomersByCountryQuery</code>. You can now use this method on the client as if you were calling it on the server.</p>
<p>Updates, inserts and deletes follow a different pattern. When you create a domain service, you can indicate whether you want to enable editing. The corresponding methods for update/insert/delete are then generated in the server-side domain service. However, the client-side part doesn't have these methods. What you have on your <code>CustomerContext</code> is a method called <code>SubmitChanges</code>. So how does this work:</p>
<ul>
<li>For updates, you simply update properties of existing customers (that you retrieved via <code>GetCustomersByCountryQuery</code>).</li>
<li>For inserts, you use <code>CustomerContext.Customers.Add(new Customer(...) {...})</code>.</li>
<li>For deletes, you use <code>CustomerContext.Customers.Remove(someCustomer)</code>.</li>
</ul>
<p>When you're done editing, you call <code>CustomerContext.SubmitChanges()</code>.</p>
<p>As for validation, you can decorate your server-side objects with validation attributes from the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx" rel="noreferrer"><code>System.ComponentModel.DataAnnotations</code></a> namespace. Again, when you build your project, validation code is now automatically generated for the corresponding client-side objects.</p>
<p>I hope this explanation helps you a little further.</p> |
28,644,616 | Android - EditText gives IndexOutOfBounds Exception while using textAllCaps | <p>I'm trying to create a very simple registration page using a relative layout. This registration page is linked to a fragment called RegistrationFragment.</p>
<p>I have five EditText fields for this layout: name, phone number, email, password, and confirm password. For some reason, I can enter text into password and confirm password, but whenever I try to enter any text into the other fields, they immediately crash the application with an IndexOutOfBounds Exception.</p>
<p>Here's the full stack trace:</p>
<pre><code>java.lang.IndexOutOfBoundsException
at android.graphics.Paint.getTextRunAdvances(Paint.java:1879)
at android.text.TextLine.handleText(TextLine.java:747)
at android.text.TextLine.handleRun(TextLine.java:898)
at android.text.TextLine.measureRun(TextLine.java:414)
at android.text.TextLine.measure(TextLine.java:293)
at android.text.TextLine.metrics(TextLine.java:267)
at android.text.Layout.getLineExtent(Layout.java:998)
at android.text.Layout.drawText(Layout.java:329)
at android.widget.Editor.drawHardwareAccelerated(Editor.java:1380)
at android.widget.Editor.onDraw(Editor.java:1303)
at android.widget.TextView.onDraw(TextView.java:5163)
at android.view.View.draw(View.java:14465)
at android.view.View.getDisplayList(View.java:13362)
at android.view.View.getDisplayList(View.java:13404)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3077)
at android.view.View.getDisplayList(View.java:13300)
at android.view.View.getDisplayList(View.java:13404)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3077)
at android.view.View.getDisplayList(View.java:13300)
at android.view.View.getDisplayList(View.java:13404)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3077)
at android.view.View.getDisplayList(View.java:13300)
at android.view.View.getDisplayList(View.java:13404)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3077)
at android.view.View.getDisplayList(View.java:13300)
at android.view.View.getDisplayList(View.java:13404)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3077)
at android.view.View.getDisplayList(View.java:13300)
at android.view.View.getDisplayList(View.java:13404)
at android.view.HardwareRenderer$GlRenderer.buildDisplayList(HardwareRenderer.java:1570)
at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1449)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2377)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2249)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1879)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>My xml layout file:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e5e5e5">
<TextView
android:id="@+id/fragment_registration_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/activity_vertical_margin"
android:layout_marginTop="@dimen/activity_vertical_margin"
android:layout_marginRight="@dimen/activity_horizontal_margin"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:text="@string/registration_title"
android:textAllCaps="true"
android:textSize="35sp"
android:layout_centerHorizontal="true"
android:textColor="@color/blue"
/>
<RelativeLayout
android:id="@+id/fragment_registration_edit_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_below="@id/fragment_registration_title"
android:layout_centerHorizontal="true">
<EditText
android:id="@+id/fragment_registration_legal_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:hint="@string/full_name_prompt"
android:maxLines="1"
android:textAllCaps="true"
android:background="@drawable/edit_text_top_rounded"
/>
<EditText
android:id="@+id/fragment_registration_cell_phone"
android:layout_below="@id/fragment_registration_legal_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:hint="@string/cell_phone_prompt"
android:maxLines="1"
android:textAllCaps="true"
android:background="@drawable/edit_text_white"
/>
<EditText
android:id="@+id/fragment_registration_email"
android:layout_below="@id/fragment_registration_cell_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:hint="@string/email_prompt"
android:maxLines="1"
android:textAllCaps="true"
android:background="@drawable/edit_text_white"
/>
<EditText
android:id="@+id/fragment_registration_password"
android:layout_below="@id/fragment_registration_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:hint="@string/confirm_password_prompt"
android:maxLines="1"
android:background="@drawable/edit_text_bottom_rounded"
/>
</RelativeLayout>
<Button
android:id="@+id/fragment_registration_button"
android:background="@drawable/button_registration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/registration_button"
android:textColor="#ffffff"
android:layout_below="@+id/fragment_registration_edit_text_layout"
android:layout_marginTop="5dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
</code></pre>
<p>If relevant, I'm "looking" at my Fragment code using the below, which is at the end of the onCreate() method of my main activity for testing purposes. I got the same errors when I tried testing Registration as an activity though.</p>
<pre><code>RegistrationFragment test = new RegistrationFragment();
setContentView(R.layout.fragment_registration);
</code></pre> | 28,803,492 | 4 | 4 | null | 2015-02-21 10:17:24.083 UTC | 7 | 2021-07-18 13:30:12.363 UTC | 2015-04-04 10:42:28.367 UTC | null | 3,535,925 | null | 3,866,448 | null | 1 | 47 | android|android-fragments|android-edittext | 12,224 | <p>I had the same problem with <code>textAllCaps</code> for <code>EditText</code> in my application.</p>
<blockquote>
<p>I have found that <code>textAllCaps</code> is a property for <code>TextView</code> only. You can not use this property for <code>EditText</code>.</p>
</blockquote>
<p>So, I did R&D for it and found a better solution for this issue.</p>
<blockquote>
<p>Rather than using <code>textAllCaps</code> we can use <code>android:inputType="textCapCharacters"</code>.</p>
</blockquote>
<p>E.g.</p>
<pre><code> <EditText
android:id="@+id/edittext1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textCapCharacters"
android:hint="@string/first_name"
android:padding="10dp" >
</EditText>
</code></pre>
<p>If we use <strong><code>android:inputType="textCapCharacters"</code></strong> it will convert all characters into UPPER CASE, like we want in <code>textAllCaps</code>.</p>
<blockquote>
<p><strong>P.S.</strong> If you use the shift key and type text it may convert the text in lowercase. You can always use <code>toUpper()</code> method in string object to convert it back to uppercase.
It may help...</p>
</blockquote>
<p>You can read these details from this blog post: <a href="https://androidacademic.blogspot.com/2018/05/indexoutofbounds-exception-while-using.html" rel="nofollow noreferrer">https://androidacademic.blogspot.com/2018/05/indexoutofbounds-exception-while-using.html</a></p> |
9,189,575 | git submodule tracking latest | <p>We are moving our (huge) project to git and we are thinking about using submodules. Our plan is to have three different heads in the superproject:</p>
<blockquote>
<p>release, stable, latest</p>
</blockquote>
<p>The project leads will handle the release and stable branches. They will move the submodules as required.</p>
<p>The issue is the "latest" head. We would like the superproject "latest" head to track the master branches of all the submodules (automatically). And also it would be great if it would show the history of all commits to the submodule.</p>
<p>I have looked at gitslave, but it is not quite what we want. Any suggestions?</p> | 9,189,815 | 1 | 2 | null | 2012-02-08 08:00:41.6 UTC | 76 | 2021-08-21 11:50:40.28 UTC | 2021-05-30 08:29:27.457 UTC | null | 12,632,699 | null | 226,889 | null | 1 | 172 | git|git-submodules|git-track | 131,072 | <p>Edit (2020.12.28): GitHub change default <strong>master</strong> branch to <strong>main</strong> branch since October 2020. See <a href="https://github.com/github/renaming" rel="noreferrer">https://github.com/github/renaming</a><br />
This answer below still reflect the old naming convention.</p>
<hr />
<p>Update March 2013</p>
<p><a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.8.2.txt" rel="noreferrer">Git 1.8.2</a> added the possibility to track branches.</p>
<blockquote>
<p>"<code>git submodule</code>" started learning a new mode to <strong>integrate with the tip of the remote branch</strong> (as opposed to integrating with the commit recorded in the superproject's gitlink).</p>
</blockquote>
<pre><code># add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
</code></pre>
<p>If you had a submodule <em>already present</em> you now wish would track a branch, see "<strong><a href="https://stackoverflow.com/a/18799234/6309">how to make an existing submodule track a branch</a></strong>".</p>
<p>Also see <a href="http://www.vogella.com/tutorials/GitSubmodules/article.html" rel="noreferrer">Vogella's tutorial on submodules</a> for general information on submodules.</p>
<p>Note:</p>
<pre><code>git submodule add -b . [URL to Git repo];
^^^
</code></pre>
<p>See <a href="https://github.com/git/git/blob/7425fe100fc90b492549f51aa60ac1e70e7f4c9a/Documentation/git-submodule.txt#L258-L264" rel="noreferrer"><code>git submodule</code> man page</a>:</p>
<blockquote>
<p>A special value of <code>.</code> is used to indicate that <strong>the name of the branch in the submodule should be the same name as the current branch in the current repository</strong>.</p>
</blockquote>
<hr />
<p>See <a href="https://github.com/git/git/commit/b928922727d6691a3bdc28160f93f25712c565f6" rel="noreferrer">commit b928922727d6691a3bdc28160f93f25712c565f6</a>:</p>
<blockquote>
<h2><code>submodule add</code>: If <code>--branch</code> is given, record it in <code>.gitmodules</code></h2>
<p><sup>Signed-off-by: W. Trevor King</sup></p>
<p>This allows you to easily record a <strong><code>submodule.<name>.branch</code></strong> option in <strong><code>.gitmodules</code></strong> when you add a new submodule. With this patch,</p>
<pre><code>$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>
</code></pre>
<p>reduces to</p>
<pre><code>$ git submodule add -b <branch> <repository> [<path>]
</code></pre>
<p>This means that future calls to</p>
<pre><code>$ git submodule update --remote ...
</code></pre>
<p>will get updates from the same branch that you used to initialize the submodule, which is usually what you want.</p>
</blockquote>
<hr />
<p>Original answer (February 2012):</p>
<p>A submodule is a single commit referenced by a parent repo.<br />
Since it is a Git repo on its own, the "history of all commits" is accessible through a <code>git log</code> within that submodule.</p>
<p>So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:</p>
<ul>
<li>cd in the submodule</li>
<li>git fetch/pull to make sure it has the latest commits on the right branch</li>
<li>cd back in the parent repo</li>
<li>add and commit in order to record the new commit of the submodule.</li>
</ul>
<p><a href="http://gitslave.sourceforge.net/" rel="noreferrer">gitslave</a> (that you already looked at) seems to be the best fit, <a href="https://stackoverflow.com/questions/6108828/what-are-the-options-when-working-with-git-submodules-from-which-commits-are-mad">including for the commit operation</a>.</p>
<blockquote>
<p>It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).</p>
</blockquote>
<p>Other alternatives are <a href="https://stackoverflow.com/questions/6500524/git-subtree-or-gitslave-if-switch-away-from-git-submodules">detailed here</a>.</p> |
16,086,870 | Assert.That vs Assert.True | <p>What to prefer:</p>
<pre><code>Assert.That(obj.Foo, Is.EqualTo(true))
</code></pre>
<p>or</p>
<pre><code>Assert.True(obj.Foo)
</code></pre>
<p>For me, both asserts are equivalent, so which one should be prefered?</p> | 16,086,949 | 4 | 5 | null | 2013-04-18 15:19:50.103 UTC | 2 | 2018-05-10 14:54:31.947 UTC | 2018-05-10 14:54:31.947 UTC | null | 23,512 | null | 967,164 | null | 1 | 43 | c#|unit-testing|nunit | 57,861 | <p>In this particular case, there is no difference: you will see the output of roughly the same level of detail (i.e. it tells you that something that was expected to evaluate to <code>true</code> has evaluated to <code>false</code>). Same goes for</p>
<pre><code>Assert.IsTrue(obj.Foo);
</code></pre>
<p>and</p>
<pre><code>Assert.That(obj.Foo, Is.True);
</code></pre>
<p>Your team should pick one style of assertions, and stick with it throughout all your tests. If your team prefers the <code>Assert.That</code> style, then you should use <code>Assert.That(obj.Foo, Is.True)</code>.</p> |
16,156,594 | How to change border color of textarea on :focus | <p>I want to change border color of TEXTAREA on focus. But my code doesn't seem to working properly.</p>
<p>The code is on <a href="http://fiddle.jshell.net/ffS4S/" rel="noreferrer">fiddle</a>.</p>
<pre class="lang-html prettyprint-override"><code><form name = "myform" method = "post" action="insert.php" onsubmit="return validateform()" style="width:40%">
<input type="text" placeholder="Enter Name." name="name" maxlength="300" class="input">
<input type="email" placeholder="Enter E-mail." name="address" maxlength="300" class="input">
<textarea placeholder="Enter Message." name="descrip" class="input" ></textarea>
<br>
<input class="button secondary" type=submit name="submit" value="Submit" >
</form>
</code></pre>
<p>Here is the CSS</p>
<pre class="lang-css prettyprint-override"><code>.input {
border:0;
padding:10px;
font-size:1.3em;
font-family:"Ubuntu Light","Ubuntu","Ubuntu Mono","Segoe Print","Segoe UI";
color:#ccc;
border:solid 1px #ccc;
margin:0 0 20px;
width:300px;
-moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
box-shadow: inner 0 0 4px rgba(0, 0, 0, 0.2);
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
input:focus {
outline: none !important;
border-color: #719ECE;
box-shadow: 0 0 10px #719ECE;
}
</code></pre> | 16,156,683 | 9 | 1 | null | 2013-04-22 20:58:47.88 UTC | 33 | 2022-04-22 19:26:09.11 UTC | 2022-04-21 08:38:27.103 UTC | null | 5,446,749 | null | 2,207,792 | null | 1 | 191 | html|css | 499,075 | <pre class="lang-css prettyprint-override"><code>.input:focus {
outline: none !important;
border:1px solid red;
box-shadow: 0 0 10px #719ECE;
}
</code></pre> |
29,130,208 | How to redirect to an external URL | <p>When trying to redirect to an external page using <code>$window.location.href</code>, the page is just refreshing and not redirecting to the expected URL.</p> | 29,130,767 | 2 | 8 | null | 2015-03-18 18:42:40.84 UTC | null | 2018-03-19 17:54:36.1 UTC | 2015-10-08 16:18:26.693 UTC | null | 1,486,275 | null | 4,686,777 | null | 1 | 16 | angularjs | 48,990 | <pre><code><html ng-app="myApp">
<head>
</head>
<body ng-controller="myCtrl">
<p> <a href="https://www.google.co.in/"><button>Click me to redirect from template</button></a></p>
<p ng-click="myFunction()"> <button>Click me to redirect from controller</button></p>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($window,$scope){
$scope.myFunction = function(){
$window.location.href = 'http://www.google.com'; //You should have http here.
}
});
</script>
</body>
</html>
</code></pre>
<p>This works for me.</p> |
14,964,649 | Loop through all the records of datablock in Oracle forms | <p>I am trying to learn Oracle forms (v6.0). In a when-button-pressed trigger I am trying to loop through all of the records from a datablock. So far I have following code:</p>
<pre><code>BEGIN
GO_BLOCK('MY_BLOCK');
FIRST_RECORD;
LOOP
MESSAGE(:MY_BLOCK.DSP_NAME);
EXIT WHEN :SYSTEM.LAST_RECORD = 'TRUE';
NEXT_RECORD;
END LOOP;
END;
</code></pre>
<p>When I run the code all the DSP_NAME values are displayed except the last one. If I add :</p>
<pre><code>MESSAGE(:MY_BLOCK.DSP_NAME);
</code></pre>
<p>after the loop, then the DSP_NAME value of the last record is displayed. Why it is like that - the message is displayed before the last record check? and what would be the right way to loop through the records? </p> | 14,965,634 | 2 | 0 | null | 2013-02-19 18:22:35.4 UTC | null | 2014-03-25 08:54:50.037 UTC | null | null | null | null | 303,605 | null | 1 | 8 | forms|oracle | 65,928 | <p>Your loop is correct. I suspect the last message is showing up in the status bar at the bottom of the form instead of as a popup window.</p> |
17,464,515 | How do I clear the text in Android TextView? | <p>So I have an Android program like so: </p>
<pre><code>package com.example.androiddemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class AndroidDemo extends Activity {
String[] messages = {"Short Text",
"I want to show some really long text" +
"on the display of the phone. " +
"Having run out of ideas on what to type, " +
"I am adding this text which makes absolutely " +
"no sense."};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button add = (Button) findViewById(R.id.addBtn);
final Button clear = (Button) findViewById(R.id.clrBtn);
final EditText text = (EditText) findViewById(R.id.display);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v == add){
text.setText(messages[new java.util.Random().nextInt(messages.length)]);
}else if(v == clear){
text.setText("");
}
}
});
}
}
</code></pre>
<p>The button to add text to the <code>TextView</code> works perfectly fine however the text never clears.<br>
My belief was that the operation of <code>TextView</code> would be analogous to <code>JTextField</code> or <code>JTextArea</code> where setting the text to <code>""</code> clears it. </p>
<p><strong>How do I clear the text?</strong></p> | 17,464,568 | 5 | 2 | null | 2013-07-04 07:41:53.013 UTC | null | 2019-10-07 06:31:52.887 UTC | 2013-07-04 08:29:11.48 UTC | null | 494,879 | null | 1,894,684 | null | 1 | 6 | android|android-edittext|onclicklistener | 43,036 | <p>Try this,</p>
<pre><code>public class AndroidDemo extends Activity implements OnClickListener{
Button add, clear;
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add = (Button) findViewById(R.id.addBtn);
clear = (Button) findViewById(R.id.clrBtn);
text = (EditText) findViewById(R.id.display);
add.setOnClickListener(this);
clear.setOnClickListener(this);
}
@Override
public void onClick(View v){
if(v == add){
text.setText(messages[new java.util.Random().nextInt(messages.length)]);
}else if(v == clear){
text.setText("");
}
}
}
</code></pre> |
24,625,687 | Swift - UIImagePickerController - how to use it? | <p>I am trying hard to understand how this works, but it's pretty hard for me. =)
I have 1 view, there is one button and one small ImageView area for preview.
The button triggers imagepickercontroller, and the UIView will display picked image.
There is no error but the image doesn't show in the UIImageView area. </p>
<pre><code>var imagePicker = UIImagePickerController()
@IBOutlet var imagePreview : UIImageView
@IBAction func AddImageButton(sender : AnyObject) {
imagePicker.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
imagePicker.delegate = self
self.presentModalViewController(imagePicker, animated: true)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary!) {
var tempImage:UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
imagePreview.image = tempImage
self.dismissModalViewControllerAnimated(true)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController!) {
self.dismissModalViewControllerAnimated(true)
}
</code></pre> | 24,626,808 | 6 | 4 | null | 2014-07-08 07:07:54.523 UTC | 11 | 2021-11-08 07:46:23.827 UTC | 2021-11-08 07:46:23.827 UTC | null | 8,090,893 | null | 3,806,731 | null | 1 | 50 | ios|swift|xcode|cocoa-touch|uiimagepickercontroller | 95,195 | <p>You're grabbing a <code>UIImage</code> named <code>UIImagePickerControllerOriginalImage</code> and there exists no such image. You're meant to grab the <code>UIImage</code> with the key <code>UIImagePickerControllerOriginalImage</code> from the <code>editingInfo</code> dictionary:</p>
<pre><code>let tempImage = editingInfo[UIImagePickerControllerOriginalImage] as! UIImage
</code></pre> |
24,661,857 | Ruby: colon before vs after | <p>When using Ruby, I keep getting mixed up with the <code>:</code>.</p>
<p>Can someone please explain when I'm supposed to use it before the variable name, like <code>:name</code>, and when I'm supposed to use it after the variable like <code>name:</code>?</p>
<p>An example would be sublime.</p> | 24,661,893 | 4 | 5 | null | 2014-07-09 19:06:15.62 UTC | 19 | 2017-08-13 16:58:10.64 UTC | 2017-08-13 16:58:10.64 UTC | null | 3,924,118 | null | 2,022,751 | null | 1 | 95 | ruby | 40,142 | <p>You are welcome for both, while creating <code>Hash</code> :</p>
<pre><code>{:name => "foo"}
#or
{name: 'foo'} # This is allowed since Ruby 1.9
</code></pre>
<p>But basically <code>:name</code> is a <a href="http://www.ruby-doc.org/core-2.1.2/Symbol.html"><code>Symbol</code></a> object in Ruby.</p>
<p>From <a href="http://www.ruby-doc.org/core-2.1.0/Hash.html">docs</a></p>
<blockquote>
<p>Hashes allow an alternate syntax form when your keys are always symbols. Instead of</p>
</blockquote>
<pre><code>options = { :font_size => 10, :font_family => "Arial" }
</code></pre>
<p>You could write it as:</p>
<pre><code>options = { font_size: 10, font_family: "Arial" }
</code></pre> |
22,264,502 | In Rust, what is the difference between clone() and to_owned()? | <p>In Rust, <code>Clone</code> is a trait that specifies the <code>clone</code> method (and <code>clone_from</code>). Some traits, like <code>StrSlice</code> and <code>CloneableVector</code> specify a <code>to_owned</code> fn. Why would an implementation need both? What is the difference?</p>
<p>I did an experiment with Rust strings, which have both methods, and it demonstrates that there is a difference, but I don't understand it:</p>
<pre class="lang-rust prettyprint-override"><code>fn main() {
test_clone();
test_to_owned();
}
// compiles and runs fine
fn test_clone() {
let s1: &'static str = "I am static";
let s2 = "I am boxed and owned".to_string();
let c1 = s1.clone();
let c2 = s2.clone();
println!("{:?}", c1);
println!("{:?}", c2);
println!("{:?}", c1 == s1); // prints true
println!("{:?}", c2 == s2); // prints true
}
fn test_to_owned() {
let s1: &'static str = "I am static";
let s2 = "I am boxed and owned".to_string();
let c1 = s1.to_owned();
let c2 = s2.to_owned();
println!("{:?}", c1);
println!("{:?}", c2);
println!("{:?}", c1 == s1); // compile-time error here (see below)
println!("{:?}", c2 == s2);
}
</code></pre>
<p>The compile time error for the <code>to_owned</code> example is:</p>
<pre><code>error: mismatched types: expected `~str` but found `&'static str`
(str storage differs: expected `~` but found `&'static `)
clone.rs:30 println!("{:?}", c1 == s1);
</code></pre>
<p>Why would the first example work but not the second? </p> | 22,265,792 | 1 | 3 | null | 2014-03-08 03:09:52.33 UTC | 12 | 2022-08-05 18:40:48.353 UTC | 2016-09-24 15:32:31.153 UTC | null | 871,012 | null | 871,012 | null | 1 | 92 | rust | 35,105 | <p><code>.clone()</code> returns its receiver. <code>clone()</code> on a <code>&str</code> returns a <code>&str</code>. If you want a <code>String</code>, you need a different method, which in this case is <code>.to_owned()</code>.</p>
<p>For most types, <code>clone()</code> is sufficient because it's only defined on the underlying type and not on the reference type. But for <code>str</code> and <code>[T]</code>, <code>clone()</code> is implemented on the reference type (<code>&str</code> and <code>&[T]</code>), and therefore it has the wrong type. It's also implemented on the owned types (<code>String</code> and <code>Vec<T></code>), and in that case <code>clone()</code> will return another owned value.</p>
<p>Your first example works because <code>c1</code> and <code>s1</code> (and <code>c2</code> and <code>s2</code>) have the same types. Your second example fails because they don't (<code>c1</code> is <code>String</code> whereas <code>s1</code> is <code>&str</code>). That's a perfect example of why the separate methods are necessary.</p>
<hr />
<p>As of current Rust, both now compile, but in <code>test_clone()</code> <code>c1</code> is a <code>&str</code> and in <code>test_to_owned()</code> it's a <code>String</code>. I'm pretty sure it compiles as Rust is now more lenient about automatically referencing and dereferencing values. In this particular example I believe the <code>c1 == s1</code> line is compiled as though it said <code>&*c1 == s1</code>. If you wish to prove the types involved you can add a deliberate type error, such as <code>let _: i32 = c1;</code> and the error message will show the type.</p> |
37,429,519 | Font Awesome error: downloadable font: rejected by sanitizer | <blockquote>
<p>downloadable font: rejected by sanitizer (font-family: "FontAwesome"
style:normal weight:normal stretch:normal src index:1) source:
<a href="http://192.168.1.254/theme/font-awesome/fonts/fontawesome-webfont.woff2?v=4.6.3" rel="noreferrer">http://192.168.1.254/theme/font-awesome/fonts/fontawesome-webfont.woff2?v=4.6.3</a> <a href="http://192.168.1.254/theme/font-awesome/css/font-awesome.min.css" rel="noreferrer">http://192.168.1.254/theme/font-awesome/css/font-awesome.min.css</a> Line
4</p>
</blockquote>
<p>I was keep getting above error. and i tried lots of stuff found on the internet. (hosting the fonts on own server)</p>
<ul>
<li>CORS issue</li>
<li>MIME-type header config in web server</li>
</ul>
<p>Other combinations of HTTP headers and MIME-types everything that can resolve the issue but nothing solved it.</p> | 37,429,520 | 5 | 2 | null | 2016-05-25 06:37:55.6 UTC | 2 | 2022-09-13 07:24:51.973 UTC | 2019-09-19 13:27:56.857 UTC | null | 2,088,053 | null | 5,463,169 | null | 1 | 14 | html|css|firefox|fonts|font-awesome | 40,410 | <p>Remove the <code>?v=4.6.3</code> and remaining tail from this block (<code>font-awesome.css</code> / <code>font-awesome.min.css</code>).</p>
<pre class="lang-css prettyprint-override"><code>@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot?v=4.6.3');
src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.6.3') format('embedded-opentype'),
url('../fonts/fontawesome-webfont.woff2?v=4.6.3') format('woff2'),
url('../fonts/fontawesome-webfont.woff?v=4.6.3') format('woff'),
url('../fonts/fontawesome-webfont.ttf?v=4.6.3') format('truetype'),
url('../fonts/fontawesome-webfont.svg?v=4.6.3#fontawesomeregular') format('svg');
font-weight: normal;
</code></pre>
<p>Updated to:</p>
<pre class="lang-css prettyprint-override"><code>@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot');
src: url('../fonts/fontawesome-webfont.eot') format('embedded-opentype'),
url('../fonts/fontawesome-webfont.woff2') format('woff2'),
url('../fonts/fontawesome-webfont.woff') format('woff'),
url('../fonts/fontawesome-webfont.ttf') format('truetype'),
url('../fonts/fontawesome-webfont.svg') format('svg');
font-weight: normal;
font-style: normal;
}
</code></pre> |
27,078,285 | Simple throttle in JavaScript | <p>I am looking for a simple throttle in JavaScript. I know libraries like lodash and underscore have it, but only for one function it will be overkill to include any of those libraries.</p>
<p>I was also checking if jQuery has a similar function - could not find.</p>
<p><a href="https://remysharp.com/2010/07/21/throttling-function-calls" rel="noreferrer">I have found one working throttle</a>, and here is the code:</p>
<pre><code>function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}
</code></pre>
<p>The problem with this is: it fires the function once more after the throttle time is complete. So let's assume I made a throttle that fires every 10 seconds on keypress - if I do keypress 2 times, it will still fire the second keypress when 10 seconds are completed. I do not want this behavior.</p> | 27,078,401 | 24 | 5 | null | 2014-11-22 14:09:06.727 UTC | 35 | 2022-09-24 06:34:31.973 UTC | 2021-09-23 07:56:41.037 UTC | null | 1,480,391 | null | 1,806,399 | null | 1 | 118 | javascript|jquery|throttling | 130,378 | <p>I would use the <a href="https://github.com/jashkenas/underscore/blob/master/underscore.js" rel="noreferrer" title="underscore.js">underscore.js</a> or <a href="https://lodash.com" rel="noreferrer">lodash</a> source code to find a well tested version of this function.</p>
<p>Here is the slightly modified version of the underscore code to remove all references to underscore.js itself:</p>
<pre><code>// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
function throttle(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
</code></pre>
<p>Please note that this code can be simplified if you don't need all the options that underscore support.</p>
<p>Please find below a very simple and non-configurable version of this function:</p>
<pre><code>function throttle (callback, limit) {
var waiting = false; // Initially, we're not waiting
return function () { // We return a throttled function
if (!waiting) { // If we're not waiting
callback.apply(this, arguments); // Execute users function
waiting = true; // Prevent future invocations
setTimeout(function () { // After a period of time
waiting = false; // And allow future invocations
}, limit);
}
}
}
</code></pre>
<p>Edit 1: Removed another reference to underscore, thx to @Zettam 's comment</p>
<p>Edit 2: Added suggestion about lodash and possible code simplification, thx to @lolzery @wowzery 's comment</p>
<p>Edit 3: Due to popular requests, I added a very simple, non-configurable version of the function, adapted from @vsync 's comment</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.