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
5,403,636
Cause CMAKE to generate an error
<p>How can I get CMAKE to generate an error on a particular condition. That is, I want something like this:</p> <pre><code>if( SOME_COND ) error( "You can't do that" ) endif() </code></pre>
5,403,778
1
0
null
2011-03-23 10:14:24.373 UTC
18
2022-09-19 05:46:45.407 UTC
null
null
null
null
229,686
null
1
165
cmake
103,215
<p>The <a href="https://cmake.org/cmake/help/latest/command/message.html" rel="nofollow noreferrer"><code>message()</code></a> method has an optional argument for the mode, allowing <code>STATUS</code>, <code>WARNING</code>, <code>AUTHOR_WARNING</code>, <code>SEND_ERROR</code>, and <code>FATAL_ERROR</code>. <code>STATUS</code> messages go to stdout. Every other mode of message, including none, goes to stderr.</p> <p>You want <code>SEND_ERROR</code> if you want to output an error, but continue processing. You want <code>FATAL_ERROR</code> if you want to exit CMake processing.</p> <p>Something like:</p> <pre><code>if( SOME_COND ) message( SEND_ERROR &quot;You can't do that&quot; ) elseif( SOME_CRITICAL_COND ) message( FATAL_ERROR &quot;You can not do this at all, CMake will exit.&quot; ) endif() </code></pre>
25,201,438
Python: How to get values of an array at certain index positions?
<p>I have a numpy array like this:</p> <pre><code>a = [0,88,26,3,48,85,65,16,97,83,91] </code></pre> <p>How can I get the values at certain index positions in ONE step? For example:</p> <pre><code>ind_pos = [1,5,7] </code></pre> <p>The result should be:</p> <pre><code>[88,85,16] </code></pre>
25,201,473
5
1
null
2014-08-08 10:31:08.963 UTC
3
2020-12-18 15:08:53.607 UTC
null
null
null
null
2,952,871
null
1
28
python|arrays|numpy|indexing
181,837
<p>Just index using you <code>ind_pos</code> </p> <pre><code>ind_pos = [1,5,7] print (a[ind_pos]) [88 85 16] In [55]: a = [0,88,26,3,48,85,65,16,97,83,91] In [56]: import numpy as np In [57]: arr = np.array(a) In [58]: ind_pos = [1,5,7] In [59]: arr[ind_pos] Out[59]: array([88, 85, 16]) </code></pre>
27,614,936
Laravel rule validation for numbers
<p>I have the following rules :</p> <pre><code>'Fno' =&gt; 'digits:10' 'Lno' =&gt; 'min:2|max5' // this seems invalid </code></pre> <p>But how to have the rule that</p> <p>Fno should be a digit with minimum 2 digits to maximum 5 digits and</p> <p>Lno should be a digit only with min 2 digits</p>
27,615,084
6
1
null
2014-12-23 06:02:24.347 UTC
16
2022-08-20 11:23:10.88 UTC
2022-08-20 11:23:10.88 UTC
null
9,521,512
null
3,492,495
null
1
75
php|laravel|laravel-4
263,905
<p>If I correctly got what you want:</p> <pre><code>$rules = ['Fno' =&gt; 'digits_between:2,5', 'Lno' =&gt; 'numeric|min:2']; </code></pre> <p>or</p> <pre><code>$rules = ['Fno' =&gt; 'numeric|min:2|max:5', 'Lno' =&gt; 'numeric|min:2']; </code></pre> <p>For all the available rules: <a href="http://laravel.com/docs/4.2/validation#available-validation-rules">http://laravel.com/docs/4.2/validation#available-validation-rules</a></p> <blockquote> <p><strong>digits_between</strong> <em>:min,max</em></p> <p>The field under validation must have a length between the given min and max.</p> <p><strong>numeric</strong></p> <p>The field under validation must have a numeric value.</p> <p><strong>max</strong>:<em>value</em></p> <p>The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.</p> <p><strong>min</strong>:<em>value</em></p> <p>The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.</p> </blockquote>
44,618,542
How to change the color of an AlertDialog message?
<p>I have an <code>AlertDialog</code> and it's message is displayed, but the color of the text is white. It blends in with the background. I've tried changing the theme but it doesn't work. How do I change the color of the message?</p> <p>The relevant code:</p> <pre><code>AlertDialog.Builder builder; builder = new AlertDialog.Builder(MainActivityGame.this); builder.setTitle("Name"); builder.setMessage("Are you "); builder.setCancelable(false); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Submit default name, go home boolean isInserted = myDb.insertData(defaultName, triesTaken, difficultyText); if (isInserted) { Toast.makeText(MainActivityGame.this, "Your name was submitted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivityGame.this, "Error, your name wasn't submitted\n Have you entered a default name?\n Go to Settings/Default Name to set it up", Toast.LENGTH_SHORT).show(); } Intent intent = new Intent(MainActivityGame.this, MainActivity.class); startActivity(intent); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { userName.setVisibility(View.VISIBLE); submitName.setVisibility(View.VISIBLE); submitName.setEnabled(true); dialogInterface.dismiss(); } }); builder.create(); builder.show(); </code></pre>
44,618,722
4
1
null
2017-06-18 19:09:35.757 UTC
9
2021-04-27 07:02:13.977 UTC
2017-06-19 06:04:47.953 UTC
null
5,869,325
null
7,656,601
null
1
26
java|android|android-alertdialog
26,296
<p>you can give style to your alert dialog like this:</p> <pre><code>AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogStyle); </code></pre> <p>and the style is like always:</p> <pre><code>&lt;style name="AlertDialogStyle" parent="Theme.AppCompat.Light.Dialog"&gt; &lt;item name="android:colorAccent"&gt;#f3f3f3&lt;/item&gt; &lt;item name="android:textColor"&gt;#f3f3f3&lt;/item&gt; &lt;item name="android:textColorPrimary"&gt;#f3f3f3&lt;/item&gt; &lt;/style&gt; </code></pre>
21,732,123
Convert True/False value read from file to boolean
<p>I'm reading a <code>True - False</code> value from a file and I need to convert it to boolean. Currently it always converts it to <code>True</code> even if the value is set to <code>False</code>.</p> <p>Here's a <code>MWE</code> of what I'm trying to do:</p> <pre><code>with open('file.dat', mode="r") as f: for line in f: reader = line.split() # Convert to boolean &lt;-- Not working? flag = bool(reader[0]) if flag: print 'flag == True' else: print 'flag == False' </code></pre> <p>The <code>file.dat</code> file basically consists of a single string with the value <code>True</code> or <code>False</code> written inside. The arrangement looks very convoluted because this is a minimal example from a much larger code and this is how I read parameters into it.</p> <p>Why is <code>flag</code> always converting to <code>True</code>?</p>
21,732,183
17
1
null
2014-02-12 15:26:16.07 UTC
17
2022-08-12 10:44:03.757 UTC
2017-04-27 15:47:22.797 UTC
null
1,391,441
null
1,391,441
null
1
94
python|string|boolean
170,289
<p><code>bool('True')</code> and <code>bool('False')</code> always return <code>True</code> because strings 'True' and 'False' are not empty.</p> <p>To quote a great man (and Python <a href="http://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="noreferrer">documentation</a>):</p> <blockquote> <h3><a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="noreferrer">5.1. Truth Value Testing</a></h3> <p>Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:</p> <ul> <li>&hellip;</li> <li>zero of any numeric type, for example, <code>0</code>, <code>0L</code>, <code>0.0</code>, <code>0j</code>.</li> <li>any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.</li> <li>&hellip;</li> </ul> <p>All other values are considered true &mdash; so objects of many types are always true.</p> </blockquote> <p>The built-in <a href="http://docs.python.org/2/library/functions.html#bool" rel="noreferrer"><code>bool</code></a> function uses the standard truth testing procedure. That's why you're always getting <code>True</code>.</p> <p>To convert a string to boolean you need to do something like this:</p> <pre><code>def str_to_bool(s): if s == 'True': return True elif s == 'False': return False else: raise ValueError # evil ValueError that doesn't tell you what the wrong value was </code></pre>
51,476,234
Subclass a class that extends StatelessWidget or StatefulWidget class
<p>Is it possible to create a class that extends a class extending StatelessWidget or StatefulWidget.</p> <p>For example:</p> <pre><code>class MyButton extends StatelessWidget { final String label; Button({this.label}); @override Widget build(BuildContext context) { return ButtonExample("label");} } </code></pre> <p>then</p> <pre><code>class SubmitButton extends MyButton { String label; SubmitButton({Key key, this.label}) : super(label: label); // then somehow extend the parent build and change only the color // or in case of StatefulWidget change a functionality } </code></pre> <p>I tried to search for examples online but I had not success.</p>
51,477,727
5
3
null
2018-07-23 10:06:11.957 UTC
8
2021-11-15 09:39:19.07 UTC
2018-07-23 10:24:09.257 UTC
null
5,482,015
null
5,482,015
null
1
33
flutter
26,132
<p>In Flutter composition is preferred over inheritance.<br> Widgets are not supposed to be extended, this is why there are no examples or tutorials how to do it.</p> <p>Flutter has a strong focus on composition and the included widget library contains a lot of smaller widgets that do one thing well, that allow to compose them into custom widgets in many different ways. </p>
32,614,752
F12 - Go to Implementation of Interface
<p>When not running an application, pressing F12 (Go To Definition) on a method on an interface type will take you to the interface itself. </p> <p>Is there any key combo that exists (or one that I can make) that will allow me to provide a default implementation to jump to, or allow me to quickly pick an implementation to go to? </p> <p>We have several layers in our application, and it would save a lot of time to be able to jump straight to the <code>Mock</code> or <code>Real</code> implementations rather than navigating to them in source control.</p>
32,614,836
6
2
null
2015-09-16 17:12:22.21 UTC
1
2021-09-24 17:50:06.637 UTC
2015-09-16 17:19:12.66 UTC
null
2,642,204
null
1,786,428
null
1
32
visual-studio|interface|keyboard-shortcuts
18,970
<p><strong>If using VS 2015 and above:</strong> <br/><br/> <a href="https://stackoverflow.com/a/37794970/970191">See answer below</a>:</p> <blockquote> <p>Visual Studio 2015 Update 1 added Edit.GoToImplementation which appeared in the context menu, but there was no keyboard shortcut associated with it by default.</p> <p>In Visual Studio Update 2, we added a default shortcut of Ctrl+F12.</p> </blockquote> <hr /> <p><strong>If using VS 2013 and below:</strong></p> <p>We had the same problem and started using <a href="https://www.jetbrains.com/resharper/" rel="noreferrer">Resharper</a>. It has a nice <em>Goto Implementation</em> feature, which was working very well, as I remember.</p> <p>The problem is that this tool is not free though (which is of course justified, as it offers much, much more than the mentioned feature).</p> <p>Without this, I use <em>Find All References</em> and identify the implementation quickly by looking at the path (we have interfaces, implementations and mocks nicely segregated). But you've probably identified this possibility by yourself.</p> <p>Also, you may consider an option mentioned in <a href="https://stackoverflow.com/a/8260069/2642204">this answer</a> (although it's for interface methods, not implementations):</p> <ul> <li>move the cursor over the method</li> <li>type <strong>CTRL+K</strong> <strong>CTRL+T</strong> to open the <em>Call Hierarchy window</em></li> <li>move down to <em>Implements</em> node</li> <li>type <strong>Return</strong> to go to the selected implementation</li> </ul>
33,432,983
Docker apps logging with Filebeat and Logstash
<p>I have a set of dockerized applications scattered across multiple servers and trying to setup production-level centralized logging with ELK. I'm ok with the ELK part itself, but I'm a little confused about how to forward the logs to my logstashes. I'm trying to use Filebeat, because of its loadbalance feature. I'd also like to avoid packing Filebeat (or anything else) into all my dockers, and keep it separated, dockerized or not.</p> <p>How can I proceed?</p> <p>I've been trying the following. My Dockers log on stdout so with a non-dockerized Filebeat configured to read from stdin I do:</p> <blockquote> <p>docker logs -f mycontainer | ./filebeat -e -c filebeat.yml</p> </blockquote> <p>That appears to work at the beginning. The first logs are forwarded to my logstash. The cached one I guess. But at some point it gets stuck and keep sending the same event </p> <p>Is that just a bug or am I headed in the wrong direction? What solution have you setup?</p>
33,433,254
6
2
null
2015-10-30 09:47:46.97 UTC
18
2017-09-13 22:14:56.57 UTC
null
null
null
null
311,151
null
1
22
docker|logstash|elastic-stack|logstash-forwarder
25,682
<p>Docker allows you to specify the <a href="https://docs.docker.com/reference/logging/overview/" rel="noreferrer">logDriver</a> in use. This answer does not care about Filebeat or load balancing.</p> <p>In a presentation I used syslog to forward the logs to a Logstash (ELK) instance listening on port 5000. The following command constantly sends messages through syslog to Logstash:</p> <pre><code>docker run -t -d --log-driver=syslog --log-opt syslog-address=tcp://127.0.0.1:5000 ubuntu /bin/bash -c 'while true; do echo "Hello $(date)"; sleep 1; done' </code></pre>
9,037,605
How I can clear the value of TextView?
<p>The value of the TextView is inserted by selecting the Item on List (ArrayList). When I close and open the app again the value in the TextView is still there. There is some way to clear the value of TextView?</p>
9,037,643
3
0
null
2012-01-27 17:40:26.83 UTC
1
2020-07-04 13:18:14.427 UTC
2020-07-04 13:18:14.427 UTC
null
8,422,953
null
1,112,535
null
1
9
android|textview
44,256
<pre><code>TextView myTextView = (TextView) findViewById(R.id.myTextView); myTextView.setText(""); </code></pre>
9,193,769
disabling view with in action in ZF2
<p>I am struggling with disabling view in ZF2 <code>$this-&gt;_helper-&gt;viewRenderer-&gt;setNoRender(); or (true)</code> with no luck as it always says there </p> <pre><code>PHP Fatal error: Call to a member function setNoRender() on a non-object in ../module/Location/src/Location/Controller/LocationController.php on line 190 </code></pre>
9,870,758
9
0
null
2012-02-08 12:59:16.26 UTC
11
2016-03-12 04:45:12 UTC
2014-04-17 09:44:39.597 UTC
null
3,351,765
null
1,197,203
null
1
20
zend-framework2
20,265
<p>To disable the view completely, from within a controller action, you should return a Response object:</p> <pre><code>&lt;?php namespace SomeModule\Controller; use Zend\Mvc\Controller\ActionController, Zend\View\Model\ViewModel; class SomeController extends ActionController { public function someAction() { $response = $this-&gt;getResponse(); $response-&gt;setStatusCode(200); $response-&gt;setContent("Hello World"); return $response; } } </code></pre> <p>To disable the layout and just render this action's view model template you would do this:</p> <pre><code>public function anotherAction() { $result = new ViewModel(); $result-&gt;setTerminal(true); return $result; } </code></pre>
9,486,498
How to properly set JSESSIONID cookie path behind reverse proxy
<p>My web app is running in Tomcat at <code>http://localhost:8080/example.com/</code> but it is being reverse proxied from Apache that is serving up <code>http://example.com/</code> on port 80. My web app looks at the <code>request.getHeader("x-forwarded-host")</code> header to know that it is behind a reverse proxy. When it detects this (dynamically) it builds URLs without the servlet path on them. </p> <p>This works fine for everything except for the JSESSIONID cookie. It gets set with a path of <code>/example.com</code> instead of <code>/</code> when it is accessed through the reverse proxy. I can't figure out how I can have my code tell Tomcat to override the path for that cookie when there is a <code>x-forwarded-host</code> header on the request.</p> <p>I've tried setting the JSESSIONID cookie from the web app myself, but that just results in two Set-Cookie headers, only one of which is correct.</p>
9,487,204
3
0
null
2012-02-28 17:12:04.2 UTC
15
2015-01-20 20:59:50.17 UTC
2015-01-20 20:59:50.17 UTC
null
1,145,388
null
1,145,388
null
1
24
tomcat|reverse-proxy|jsessionid
48,956
<p>Tomcat6 uses the Servlet 2.3 spec. It does not support changing the cookie path either through code or Tomcat configuration.</p> <p>I got it to work from the Apache side with some <code>mod_proxy</code> directives. The <code>ProxyPassReverseCookiePath</code> directive does exactly what I want. It takes the cookie from Tomcat with the incorrect path and rewrites it to the correct path.</p> <pre><code>&lt;VirtualHost *:*&gt; Servername example.com ProxyRequests Off ProxyPass / http://localhost:8080/example.com/ ProxyPassReverseCookiePath /example.com / ProxyPassReverseCookieDomain localhost example.com &lt;/VirtualHost&gt; </code></pre>
9,013,916
Do arrays stored in MongoDB keep their order?
<p>Simple question, do arrays keep their order when stored in MongoDB?</p>
9,013,993
3
0
null
2012-01-26 04:23:05.833 UTC
3
2019-10-03 09:58:55.753 UTC
null
null
null
null
255,344
null
1
79
mongodb
18,869
<p>yep MongoDB keeps the order of the array.. just like Javascript engines..</p>
29,972,404
Xamarin Forms Swipe Left/Swipe Right Gestures
<p>I want to preface this by saying I'm completely new to mobile development, Xamarin, C#, .Net.</p> <p>I'm working on creating a mobile app using Xamarain Forms and have run into the problem of not having the swipe gesture available to me, at least according to the documentation I've seen. </p> <p>I found this site: <a href="http://arteksoftware.com/gesture-recognizers-with-xamarin-forms/" rel="noreferrer">http://arteksoftware.com/gesture-recognizers-with-xamarin-forms/</a></p> <p>This describes how to add some additional gestures for IOS/Android to be accessible in the context of the form. Before I try to follow this, I wanted to see if anyone else has implemented swipe in a Xamarin Forms app and how they went about it.</p> <p>My goals are that there has to be a horizontal stack layout. This layout contains 7 buttons, each button reflects a day in the current week. Swiping left on the stack layout will change the button's text to the previous week. Swiping right will change the button's text to the next week.</p> <p>So I'm also trying to use MVVM for this and XAML. So is it possible for me to separate the swipe left and the swipe right action? I want to use ICommand to pass a certain parameter to a function based on the direction of the swipe.</p> <p>Any examples of this or any advice would be greatly appreciated.</p>
53,971,252
6
4
null
2015-04-30 15:54:47.57 UTC
9
2020-01-31 19:06:36.963 UTC
2017-08-26 13:05:05.48 UTC
null
6,761,181
null
4,738,177
null
1
34
c#|xaml|xamarin|xamarin.forms
52,381
<p>Xamarin.Forms has introduced SwipeGestureRecognizer :</p> <pre><code>&lt;BoxView Color="Teal" ...&gt; &lt;BoxView.GestureRecognizers&gt; &lt;SwipeGestureRecognizer Direction="Left" Swiped="OnSwiped"/&gt; &lt;/BoxView.GestureRecognizers&gt; &lt;/BoxView&gt; </code></pre>
30,909,492
mongoError: Topology was destroyed
<p>I have a REST service built in node.js with Restify and Mongoose and a mongoDB with a collection with about 30.000 regular sized documents. I have my node service running through pmx and pm2.</p> <p>Yesterday, suddenly, node started crapping out errors with the message "MongoError: Topology was destroyed", nothing more. I have no idea what is meant by this and what could have possibly triggered this. there is also not much to be found when google-searching this. So I thought I'd ask here.</p> <p>After restarting the node service today, the errors stopped coming in. I also have one of these running in production and it scares me that this could happen at any given time to a pretty crucial part of the setup running there...</p> <p>I'm using the following versions of the mentioned packages:</p> <ul> <li>mongoose: 4.0.3</li> <li>restify: 3.0.3</li> <li>node: 0.10.25</li> </ul>
31,950,062
17
2
null
2015-06-18 07:50:32.317 UTC
29
2020-11-13 03:50:53.1 UTC
2015-06-29 09:08:49.127 UTC
null
940,833
null
940,833
null
1
174
node.js|mongodb|mongoose|restify|pm2
163,679
<p>It seems to mean your node server's connection to your MongoDB instance was interrupted while it was trying to write to it.</p> <p>Take a look at the <a href="https://github.com/christkv/mongodb-core/blob/V2.2.1/lib/topologies/mongos.js#L664" rel="noreferrer">Mongo source code that generates that error</a></p> <pre><code>Mongos.prototype.insert = function(ns, ops, options, callback) { if(typeof options == 'function') callback = options, options = {}; if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if(!this.isConnected() &amp;&amp; this.s.disconnectHandler != null) { callback = bindToCurrentDomain(callback); return this.s.disconnectHandler.add('insert', ns, ops, options, callback); } executeWriteOperation(this.s, 'insert', ns, ops, options, callback); } </code></pre> <p>This does not appear to be related to the Sails issue cited in the comments, as no upgrades were installed to precipitate the crash or the "fix"</p>
34,305,351
What does [::] mean in my nginx config file
<p>I was looking at my nginx config file I noticed two this.</p> <pre><code>server { listen 80 default_server; listen [::]:80 default_server; index index.html; } </code></pre> <p>I understand this part <code>listen 80 default_server;</code> it tells nginx to listen on port 80 and set that as the "default_server" but I do not understand the second line.</p> <p><code>listen [::]:80 default_server;</code></p> <p>It appears I am setting the default server again on port 80 but I do not really understand the <code>[::]</code> part of it at all.</p> <p>Can someone explain to me what this configuration does?</p>
34,305,428
1
1
null
2015-12-16 06:33:25.403 UTC
8
2018-10-22 14:27:47.783 UTC
null
null
null
null
1,914,652
null
1
59
nginx
19,798
<p>It is for the IPv6 configs</p> <p>from the nginx <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#listen" rel="noreferrer">docs</a> </p> <pre><code>IPv6 addresses (0.7.36) are specified in square brackets: listen [::]:8000; listen [::1]; </code></pre>
34,294,054
How to implement single-line ellipsis with CSS
<p>I want to be able to add three dots and maintain a text in a single line in a responsive design.</p> <p>So for example:</p> <p>I have a link with a link inside a container element (e.g. <code>&lt;span&gt;</code>). If the text is long, it will shown in two lines one a small screen:</p> <pre><code>This is a very long text and it wraps because it's very long </code></pre> <p>I want that text to be shown like this:</p> <pre><code>This is a very long text... </code></pre> <p><code>text-overflow: ellipsis;</code> works if you have set a width to the container, but in responsive design and on my web app it's not specified obviously.</p> <p>Here's the HTML:</p> <pre><code>&lt;div class="itm-title"&gt; &lt;a href="/friendly-url-sample/"&gt;This is a very long sentence and I don't want it to wrap, I want three dots&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Is there a solution in <strong>CSS or jQuery</strong> that can solve this? thanks.</p>
34,294,113
1
1
null
2015-12-15 16:12:23.853 UTC
3
2015-12-15 16:36:37.7 UTC
2015-12-15 16:36:37.7 UTC
null
4,768,433
null
865,939
null
1
39
css
28,884
<p>You actually don't need <code>width</code> to be "set" here. All the elements in the responsive design have their width. You can just do it around with the following rules:</p> <pre><code>white-space: nowrap; overflow: hidden; text-overflow: ellipsis; </code></pre> <p><strong>Comment:</strong> This doesn't work with anchor:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>a { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a href="#"&gt;Pages you view in incognito tabs won’t stick around in your browser’s history, cookie store, or search history after you’ve closed all of your incognito tabs. Any files you download or bookmarks you create will be kept. Learn more about incognito browsing.&lt;/a&gt;</code></pre> </div> </div> </p> <p><strong>It works! <code>:)</code></strong></p> <ul> <li>No <code>width</code> set.</li> <li>Using <code>&lt;a&gt;</code> tag.</li> </ul> <p><strong>Updated with OP's Code</strong></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.itm-title { width: 150px; } a { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="itm-title"&gt; &lt;a href="/friendly-url-sample/"&gt;This is a very long sentence and I don't want it to wrap, I want three dots&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Result: Works!</strong></p>
22,514,803
Maximum size of size_t
<p>I know in <code>C</code> return type of <code>sizeof</code> operator is <code>size_t</code> being unsigned integer type defined in <code>&lt;stdint.h&gt;</code>. Which means max size of it should be <code>65535</code> as stated in <code>C99</code> standard <a href="http://port70.net/~nsz/c/c99/n1256.html#7.18.3" rel="noreferrer">7.18.3</a>:</p> <pre><code>limit of size_t SIZE_MAX 65535 </code></pre> <p>However in <code>gcc-4.8.2</code> header file <code>stdint.h</code> has defined its size much greater than <code>65535</code> contradicting to which is stated in <code>C99</code> standard as below shown, </p> <pre><code>/* Limit of `size_t' type. */ # if __WORDSIZE == 64 # define SIZE_MAX (18446744073709551615UL) # else # define SIZE_MAX (4294967295U) # endif </code></pre> <p>Kindly help me in understanding why there is a difference or reason behind my misinterpretation.</p>
22,514,848
1
1
null
2014-03-19 18:20:17.533 UTC
6
2020-07-01 20:34:09.287 UTC
2015-02-16 07:06:46.997 UTC
null
1,079,907
null
1,079,907
null
1
49
c|gcc|sizeof|c99|size-t
79,544
<p>The standard says that <code>SIZE_MAX</code> must be <em>at least</em> 65535.</p> <p>It specifies no upper bound, and gcc's implementation is perfectly valid.</p> <p>Quoting the reference you cited (emphasis added):</p> <blockquote> <p>Its implementation-defined value shall be <strong>equal to or greater</strong> in magnitude (absolute value) than the corresponding value given below, with the same sign.</p> </blockquote>
7,219,431
Why connection to localhost is refused?
<p>I have a server, to which a client machine connects. Recently I decided to encrypt the connection with stunnel, so now client program connects not directly to the server, but to localhost:8045 (I checked, and this port is not occupied).</p> <p>Java code:</p> <pre><code>URL url = new URL("http://localhost:8045/malibu/GetProviders"); InputStream stream = url.openStream(); </code></pre> <p>And I get the following:</p> <pre><code>java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:519) at java.net.Socket.connect(Socket.java:469) at java.net.Socket.&lt;init&gt;(Socket.java:366) at java.net.Socket.&lt;init&gt;(Socket.java:180) . . . </code></pre> <p>If I try to request the same page using <code>curl</code>, everything is fine.</p> <p>What can cause such behavior?</p> <p><strong>EDIT:</strong> Yes, there is a listening socket - running <code>netstat -avn | grep 8045</code> gives:</p> <pre><code>tcp6 0 0 ::1:8045 :::* LISTEN </code></pre>
7,219,513
2
5
null
2011-08-28 06:42:10.113 UTC
2
2017-10-07 05:50:26.317 UTC
2011-08-28 07:00:23.567 UTC
null
486,057
null
486,057
null
1
8
java|url|networking|localhost|stunnel
79,242
<p>The listening socket is bound to the IPv6 loopback address (::1). I recall some issues with Java not supporting dual-stack IPv4/IPv6 systems correctly; this is probably such a case. It is connecting to 127.0.0.1 only (IPv4).</p> <p>Everything else you have tried (curl, telnet...) will try the IPv6 address first, and then fall back on the IPv4 address if that fails. That's why they work, while the Java application does not.</p> <p>Try forcing stunnel to bind to 127.0.0.1. You might also try having Java connect to <code>http://[::1]:8045/malibu/GetProviders</code>, though I can't recall if it supports IPv6 addresses in HTTP URLs.</p>
23,408,756
Create a general class for custom Dialog in java Android
<p>My app shows many custom dialog like Yes/No or Accept/Cancel decissions and, while I was coding, I realized that there are so much code repeated, following the same schema. </p> <p>I want to build a general class but I don't know how to do it or, more exactly, the correct way that I have to do it(interfaces, abstract classes, inheritance, static classes, ...)</p> <p>This is my current class:</p> <pre><code>public class DialogTwoOptions extends Dialog { TextView title_tv; // Button yes_btn, no_btn; public DialogTwoOptions(Context context) { super(context); setContentView(R.layout.dialogo_sino); // a simple layout with a TextView and Two Buttons title_tv = (TextView) findViewById(R.id.dialogo_titulo_sino); // yes_btn = (Button) findViewById(R.id.dialogo_aceptar); // no_btn = (Button) findViewById(R.id.dialogo_cancelar); View v = getWindow().getDecorView(); v.setBackgroundResource(android.R.color.transparent); } public void quitDialog(View v) { if (isShowing()) dismiss(); } public void setTitle(String title) { title_tv.setText(title); } </code></pre> <p>}</p> <p>And this is what I am doing when I need to use this class:</p> <pre><code>final DialogTwoOptions dialog = new DialogTwoOptions(this); Button yes = (Button) dialog.findViewById(R.id.dialog_yes_btn); Button no = (Button) dialog.findViewById(R.id.dialog_no_btn); yes.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { dialog.dismiss(); // Do something } }); no.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { dialog.dismiss(); // Do something } }); dialog.show(); </code></pre> <p>I am sure that it is improvable, but how could you do this?</p> <p>Thanks</p>
23,408,864
6
1
null
2014-05-01 13:31:54.873 UTC
13
2018-08-23 07:08:15.1 UTC
null
null
null
null
1,196,978
null
1
27
java|android|generics|dialog
47,310
<p>First create an Base <code>DialogFragment</code> to keep hold of the instance of the <code>Activity</code>. So when the Dialog is attached to the <code>Activity</code> , you will know the instance of the <code>Activity</code> which created it.</p> <pre><code>public abstract class BaseDialogFragment&lt;T&gt; extends DialogFragment { private T mActivityInstance; public final T getActivityInstance() { return mActivityInstance; } @Override public void onAttach(Activity activity) { mActivityInstance = (T) activity; super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); mActivityInstance = null; } } </code></pre> <p>Then, create a <code>GeneralDialogFragment</code> which extends the <code>BaseDialogFragment</code></p> <pre><code>public class GeneralDialogFragment extends BaseDialogFragment&lt;GeneralDialogFragment.OnDialogFragmentClickListener&gt; { // interface to handle the dialog click back to the Activity public interface OnDialogFragmentClickListener { public void onOkClicked(GeneralDialogFragment dialog); public void onCancelClicked(GeneralDialogFragment dialog); } // Create an instance of the Dialog with the input public static GeneralDialogFragment newInstance(String title, String message) { GeneralDialogFragment frag = new GeneralDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); args.putString("msg", message); frag.setArguments(args); return frag; } // Create a Dialog using default AlertDialog builder , if not inflate custom view in onCreateView @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setTitle(getArguments().getString("title")) .setMessage(getArguments().getString("message")) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Positive button clicked getActivityInstance().onOkClicked(GeneralDialogFragment.this); } } ) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // negative button clicked getActivityInstance().onCancelClicked(GeneralDialogFragment.this); } } ) .create(); } } </code></pre> <p>If you need to use your own custom layout for dialog,then inflate a layout in <code>onCreateView</code> and remove <code>onCreateDialog</code> . But Add the click listeners in <code>onCreateView</code> like i explained in <code>onCreateDialog</code> </p> <pre><code> @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_dialog, container, false); return view; } </code></pre> <p>Then , In your <code>Activity</code> need to implement an <code>interface</code> to handle the action in <code>dialog</code></p> <pre><code>public class TryMeActivity extends FragmentActivity implements GeneralDialogFragment.OnDialogFragmentClickListener { @Override public void onOkClicked(GeneralDialogFragment dialog) { // do your stuff } @Override public void onCancelClicked(GeneralDialogFragment dialog) { // do your stuff } } </code></pre> <p>Finally, Show the <code>Dialog</code> from your <code>Activity</code> when required, like this</p> <pre><code> GeneralDialogFragment generalDialogFragment = GeneralDialogFragment.newInstance("title", "message"); generalDialogFragment.show(getSupportFragmentManager(),"dialog"); </code></pre> <p>Hope this helps. I am sure this approach is one of the optimized way, but there could be also different approaches . </p>
31,309,034
In release mode, code behavior is not as expected
<p>The following code generates different results under debug mode and release mode (using Visual Studio 2008):</p> <pre><code>int _tmain(int argc, _TCHAR* argv[]) { for( int i = 0; i &lt; 17; i++ ) { int result = i * 16; if( result &gt; 255 ) { result = 255; } printf("i:%2d, result = %3d\n", i, result) ; } return 0; } </code></pre> <p>The output of debug mode, which is as expected:</p> <pre><code>i: 0, result = 0 i: 1, result = 16 (...) i:14, result = 224 i:15, result = 240 i:16, result = 255 </code></pre> <p>The output of release mode, where i:15 result is not correct:</p> <pre><code>i: 0, result = 0 i: 1, result = 16 (...) i:14, result = 224 i:15, result = 255 i:16, result = 255 </code></pre> <p>By choosing "Optimization -> Not to optimize" in Visual Studio under release mode, the output result will be correct. However I would like to know why the optimization process could lead to erroneous output.</p> <hr> <p><strong>Update:</strong></p> <p>As suggested by Mohit JainBy, prints by:</p> <pre><code>printf("i:%2d, result = %3d, i*16=%d\n", i, result, i*16) ; </code></pre> <p>The release mode output is correct:</p> <pre><code>i: 0, result = 0, i*16=0 i: 1, result = 16, i*16=16 (...) i:14, result = 224, i*16=224 i:15, result = 240, i*16=240 i:16, result = 255, i*16=256 </code></pre>
31,310,432
2
4
null
2015-07-09 05:41:21.05 UTC
18
2015-07-09 11:02:27.667 UTC
2015-07-09 11:02:27.667 UTC
null
2,659,313
null
5,078,289
null
1
132
c++|c|optimization|visual-studio-2008|compiler-bug
10,470
<p>This is interesting, at least from a historical perspective. I can reproduce the problem with VC 2008 (15.00.30729.01) <strong><em>and</em></strong> VC 2010 (16.00.40219.01) (targeting either 32-bit x86 or 64-bit x64). The problem doesn't occur with any of the compilers I have tried starting with VC 2012 (17.00.61030).</p> <p>The command I used to compile: <code>cl /Ox vc15-bug.cpp /FAsc</code></p> <p>Since VC 2008 (and 2010) is rather old and the fix has been in for several years now, I don't think you can expect any action from Microsoft except to use a newer compiler (though maybe someone can suggest a workaround). </p> <p>The problem is that the test to determine if the value should be forced to <code>255</code> is done based on the loop count rather than the actual result of the <code>i * 16</code> expression. And the compiler simply gets the count wrong for when it should start forcing the value to <code>255</code>. I have no idea why that happens - it's just the effect that I see:</p> <pre><code>; 6 : for( int i = 0; i &lt; 17; i++ ) 00001 33 f6 xor esi, esi $LL4@main: 00003 8b c6 mov eax, esi 00005 c1 e0 04 shl eax, 4 ; 7 : { ; 8 : int result = i * 16; ; 9 : ; 10 : if( result &gt; 255 ) // the value `esi` is compared with in the following line should be 15! 00008 83 fe 0e cmp esi, 14 ; 0000000eH 0000b 7e 05 jle SHORT $LN1@main ; 11 : { ; 12 : result = 255; 0000d b8 ff 00 00 00 mov eax, 255 ; 000000ffH $LN1@main: ; 13 : } </code></pre> <p><strong>Update</strong>: All versions of VC I have installed earlier than VC 2008 have the same bug, except VC6 - compiling the program crashes the VC6 compiler:</p> <pre><code>vc15-bug.cpp(10) : fatal error C1001: INTERNAL COMPILER ERROR </code></pre> <p>So this is a bug that lasted in MSVC in one form or another for more than 10 years!</p>
19,147,280
How do you pipe "echo" into "openssl"?
<p>I am simply trying to submit the "OPTIONS / HTTP/1.0" request to SSL-enabled web servers; however, when running this, I am just simply getting "DONE" At the end of the connection. </p> <p>Here's the exact command that I'm using:</p> <pre><code>echo -e "OPTIONS / HTTP/1.0\r\n\r\n" | openssl s_client -connect site.com:443 </code></pre> <p>Any suggestions? I'm sure I'm missing something very simple.</p>
19,148,270
3
1
null
2013-10-02 21:38:33.083 UTC
5
2016-11-17 14:37:30.55 UTC
null
null
null
null
1,493,116
null
1
32
openssl
32,531
<p>the problem is discussed in this thread (the linked email has the only simple answer, which i'll repeat below): <a href="http://www.mail-archive.com/openssl-users@openssl.org/msg02937.html">http://www.mail-archive.com/openssl-users@openssl.org/msg02937.html</a></p> <pre><code>(echo "GET /"; sleep 10) | openssl s_client -connect news.ycombinator.com:443 </code></pre> <p>the problem being that s_client shuts down as soon as stdin closes. so your code works fine, but s_client is exiting after receiving the OPTIONS and before receiving the server response.</p>
3,901,101
Python+Celery: Chaining jobs?
<p>The <a href="http://celery.readthedocs.org/en/latest/userguide/tasks.html#avoid-launching-synchronous-subtasks" rel="noreferrer">Celery documentation</a> suggests that it's a bad idea to have tasks wait on the results of other tasks… But the suggested solution (see “good” heading) leaves a something to be desired. Specifically, there's no clear way of getting the subtask's result back to the caller (also, it's kind of ugly).</p> <p>So, is there any way of “chaining” jobs, so the caller gets the result of the final job? Eg, to use the <code>add</code> example:</p> <pre><code>&gt;&gt;&gt; add3 = add.subtask(args=(3, )) &gt;&gt;&gt; add.delay(1, 2, callback=add3).get() 6 </code></pre> <p>Alternately, is it OK to return instances of Result? For example:</p> <pre><code>@task def add(x, y, callback=None): result = x + y if callback: return subtask(callback).delay(result) return result </code></pre> <p>This would let the result of the “final” job in the chain could be retrived with a simple:</p> <pre><code>result = add(1, 2, callback=add3).delay() while isinstance(result, Result): result = result.get() print "result:", result </code></pre>
12,034,239
1
2
null
2010-10-10 16:24:24.12 UTC
19
2016-12-22 21:19:52.643 UTC
2016-12-22 21:19:52.643 UTC
null
71,522
null
71,522
null
1
40
python|celery
34,751
<p>You can do it with a celery chain. See <a href="https://celery.readthedocs.org/en/latest/userguide/canvas.html#chains">https://celery.readthedocs.org/en/latest/userguide/canvas.html#chains</a></p> <pre><code>@task() def add(a, b): time.sleep(5) # simulate long time processing return a + b </code></pre> <p>Chaining job:</p> <pre><code># import chain from celery import chain # the result of the first add job will be # the first argument of the second add job ret = chain(add.s(1, 2), add.s(3)).apply_async() # another way to express a chain using pipes ret2 = (add.s(1, 2) | add.s(3)).apply_async() ... # check ret status to get result if ret.status == u'SUCCESS': print "result:", ret.get() </code></pre>
1,558,481
self-taught compiler courses / good introductory compiler books?
<p>Does anyone know of online course / university lectures that comprise a typical compiler course? I've had theory of computing but unfortunately my school didn't offer a course in compiler construction. </p> <p>I know there are lectures out there; I was hoping for recommendations for particularly good offerings.</p> <p>Also, are there books for newbies to the field? Something besides the dragon book, at least. Beginners level is fine, I know there are a lot of intermediate-advanced texts on the market.</p> <p>Thanks!</p>
1,558,560
3
4
null
2009-10-13 06:28:21.267 UTC
14
2019-03-11 21:22:15.197 UTC
null
null
null
null
172,617
null
1
9
compiler-construction|context-free-grammar|dfa
6,096
<p><strong>Edit</strong>: in case this SO questions doesn't get closed, do check this <a href="https://stackoverflow.com/questions/1669/learning-to-write-a-compiler">duplicate SO posting</a> which answers the question in a much more exhaustive fashion.</p> <p>A couple of ressources on MIT's OpenCourseWare site:</p> <p><a href="http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-035-computer-language-engineering-sma-5502-fall-2005/" rel="nofollow noreferrer"><strong>6.035 Computer Language Engineering</strong></a><br> <a href="http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-827Multithreaded-Parallelism--Languages-and-CompilersFall2002/CourseHome/index.htm" rel="nofollow noreferrer"><strong>6.827 Multithreaded Parallelism: Languages and Compilers</strong></a></p> <p>The former probably along the lines of what you had in mind. It also includes some of the lectures' videos.<br> The latter... positively a graduate level course. Also focus is more on multi-threading than the traditional compiling chain. (But then again to to chunk code threads efficiently one must have a decent grasp of the semantics expressed in the original program...)</p>
1,826,008
UpdatePanel Exception Handling
<p>Where exceptions occur in the UpdatePanels I've implemented in the ASP.NET web app I'm building, they cause a JavaScript error on the page with some high level error output available in the alert. This is OKish for development, but as soon as the system is in Production, it's obviously no good for multiple reasons. I can surround troublesome activities with Try Catch etc to control the Javascript error but in some cases, I want to take actions on the main page etc to support the user experience.</p> <p>How do I go about handling errors that occur in UpdatePanels gracefully to provide a seamless and Javascript error free implementation?</p>
1,827,097
3
0
null
2009-12-01 12:51:27.027 UTC
9
2018-06-08 19:50:04.79 UTC
2011-06-09 13:14:41.593 UTC
user1228
null
null
202,055
null
1
17
asp.net|exception|asp.net-ajax|error-handling|updatepanel
14,607
<p>You can use a combination of the AsyncPostBackError event on the ScriptManager (server-side) and the EndRequest event on the PageRequestManager (client-side) to fully handle server-side errors when using the UpdatePanel.</p> <p>Here are a couple resources that should help you:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb398934.aspx" rel="noreferrer">Customizing Error Handling for ASP.NET UpdatePanel Controls</a></p> <p><a href="http://www.codeproject.com/KB/webforms/asp_error_handling.aspx" rel="noreferrer">Error Handling Customization for ASP.NET UpdatePanel</a></p> <p>Here's a simple example:</p> <pre><code>// Server-side protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) { ScriptManager1.AsyncPostBackErrorMessage = "An error occurred during the request: " + e.Exception.Message; } // Client-side &lt;script type="text/javascript"&gt; function pageLoad() { Sys.WebForms.PageRequestManager.getInstance(). add_endRequest(onEndRequest); } function onEndRequest(sender, args) { var lbl = document.getElementById("Label1"); lbl.innerHTML = args.get_error().message; args.set_errorHandled(true); } &lt;/script&gt; </code></pre>
2,075,836
Read contents of a URL in Android
<p>I'm new to android and I'm trying to figure out how to get the contents of a URL as a String. For example if my URL is <a href="http://www.google.com/" rel="noreferrer">http://www.google.com/</a> I want to get the HTML for the page as a String. Could anyone help me with this?</p>
2,075,847
3
0
null
2010-01-16 01:25:54.257 UTC
4
2018-06-07 22:55:31.033 UTC
null
null
null
null
200,565
null
1
23
android
61,380
<p>From the Java Docs : <a href="http://java.sun.com/docs/books/tutorial/networking/urls/readingURL.html" rel="noreferrer">readingURL</a></p> <pre><code>URL yahoo = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); </code></pre> <p>Instead of writing each line to <code>System.out</code> just append it to a string.</p>
1,753,186
Dynamic Scoping - Deep Binding vs Shallow Binding
<p>I've been trying to get my head around shallow binding and deep binding, wikipedia doesn't do a good job of explaining it properly. Say I have the following code, what would the output be if the language uses dynamic scoping with</p> <p>a) deep binding</p> <p>b) shallow binding?</p> <pre><code>x: integer := 1 y: integer := 2 procedure add x := x + y procedure second(P:procedure) x:integer := 2 P() procedure first y:integer := 3 second(add) ----main starts here--- first() write_integer(x) </code></pre>
1,753,505
3
1
null
2009-11-18 02:12:18.65 UTC
9
2020-10-03 12:18:41.52 UTC
2011-04-02 15:53:03.343 UTC
null
94,687
null
100,758
null
1
30
language-agnostic|binding|scoping|dynamic-scope
34,225
<p>Deep binding binds the environment at the time the procedure is passed as an argument</p> <p>Shallow binding binds the environment at the time the procedure is actually called</p> <p>So for dynamic scoping with deep binding when add is passed into a second the environment is x = 1, y = 3 and the x is the global x so it writes 4 into the global x, which is the one picked up by the write_integer.</p> <p>Shallow binding just traverses up until it finds the nearest variable that corresponds to the name so the answer would be 1.</p>
8,964,191
Test type of elements python tuple/list
<p>How do you verify that the type of all elements in a list or a tuple are the same and of a certain type? </p> <p>for example:</p> <pre><code>(1, 2, 3) # test for all int = True (1, 3, 'a') # test for all int = False </code></pre>
8,964,208
5
1
null
2012-01-22 19:59:00.71 UTC
9
2021-09-30 18:51:23.943 UTC
2016-07-19 13:31:16.027 UTC
null
100,297
null
801,820
null
1
34
python
58,823
<pre><code>all(isinstance(n, int) for n in lst) </code></pre> <p>Demo:</p> <pre><code>In [3]: lst = (1,2,3) In [4]: all(isinstance(n, int) for n in lst) Out[4]: True In [5]: lst = (1,2,'3') In [6]: all(isinstance(n, int) for n in lst) Out[6]: False </code></pre> <p>Instead of <code>isinstance(n, int)</code> you could also use <code>type(n) is int</code></p>
8,963,400
The correct way to read a data file into an array
<p>I have a data file, with each line having one number, like</p> <pre><code>10 20 30 40 </code></pre> <p>How do I read this file and store the data into an array? </p> <p>So that I can conduct some operations on this array.</p>
8,963,627
5
1
null
2012-01-22 18:18:49.953 UTC
16
2022-02-07 03:41:20.883 UTC
2014-02-02 18:39:19.38 UTC
null
63,550
null
297,850
null
1
38
perl
148,233
<p>Just reading the file into an array, one line per element, is trivial:</p> <pre><code>open my $handle, '&lt;', $path_to_file; chomp(my @lines = &lt;$handle&gt;); close $handle; </code></pre> <p>Now the lines of the file are in the array <code>@lines</code>.</p> <p>If you want to make sure there is error handling for <code>open</code> and <code>close</code>, do something like this (in the snipped below, we <a href="https://perldoc.perl.org/Encode.html#Encoding-via-PerlIO" rel="noreferrer">open the file in UTF-8 mode</a>, too):</p> <pre><code>my $handle; unless (open $handle, "&lt;:encoding(utf8)", $path_to_file) { print STDERR "Could not open file '$path_to_file': $!\n"; # we return 'undefined', we could also 'die' or 'croak' return undef } chomp(my @lines = &lt;$handle&gt;); unless (close $handle) { # what does it mean if close yields an error and you are just reading? print STDERR "Don't care error while closing '$path_to_file': $!\n"; } </code></pre>
19,468,209
Spring Security configuration: HTTP 403 error
<p>I'm trying to secure my website using Spring Security following the guides on the web.</p> <p>So on my server side I have the following classes.</p> <p>My <code>WebSecurityConfigurerAdapter</code>:</p> <pre><code>@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements ApplicationContextAware { @Override protected void registerAuthentication(AuthenticationManagerBuilde rauthManagerBuilder) throws Exception { authManagerBuilder.inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;ADMIN&quot;); } } </code></pre> <p>My controller:</p> <pre><code>@Controller //@RequestMapping(&quot;/course&quot;) public class CourseController implements ApplicationContextAware { @RequestMapping(value=&quot;/course&quot;, method = RequestMethod.GET, produces=&quot;application/json&quot;) public @ResponseBody List&lt;Course&gt; get( // The criterion used to find. @RequestParam(value = &quot;what&quot;, required = true) String what, @RequestParam(value = &quot;value&quot;, required = true) String value) { //..... } @RequestMapping(value = &quot;/course&quot;, method = RequestMethod.POST, produces = &quot;application/json&quot;) public List&lt;Course&gt; upload(@RequestBody Course[] cs) { } } </code></pre> <p>What confused me very much is the server does not respond to the <code>POST</code>/<code>DELETE</code> method, while the <code>GET</code> method works fine. BTW, I'm using <code>RestTemplate</code> on the client side.</p> <p>Exceptions are:</p> <pre><code>Exception in thread &quot;main&quot; org.springframework.web.client.HttpClientErrorException: 403 Forbidden at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:574) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:530) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:487) at org.springframework.web.client.RestTemplate.delete(RestTemplate.java:385) at hello.Application.createRestTemplate(Application.java:149) at hello.Application.main(Application.java:99) </code></pre> <p>I've searched the internet for days. Still don't have a clue. Please help. Thanks so much</p>
19,496,356
6
1
null
2013-10-19 16:18:58.42 UTC
23
2022-06-15 17:37:15.897 UTC
2022-06-15 17:37:15.897 UTC
null
814,702
null
2,531,174
null
1
94
spring|spring-mvc|spring-security
152,591
<p>The issue is likely due to <a href="https://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/" rel="noreferrer">CSRF protection</a>. If users will not be using your application in a web browser, <a href="https://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/" rel="noreferrer">then it is safe to disable CSRF</a> protection. Otherwise you should ensure to <a href="https://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/" rel="noreferrer">include the CSRF token in the request</a>. </p> <p>To <a href="https://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/" rel="noreferrer">disable CSRF protection</a> you can use the following:</p> <pre><code>@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements ApplicationContextAware { @Override protected void configure(HttpSecurity http) throws Exception { http // ... .csrf().disable(); } @Override protected void registerAuthentication(AuthenticationManagerBuilder authManagerBuilder) throws Exception { authManagerBuilder .inMemoryAuthentication() .withUser("user").password("password").roles("ADMIN"); } } </code></pre>
62,345,581
Node.js + Puppeteer on Docker, No usable sandbox
<p>i'm building a node.js LTS application. I followed puppeteer documentation, so my Dockerfile has this content:</p> <pre><code>FROM node:12.18.0 WORKDIR /home/node/app ADD package*.json ./ # Install latest chrome dev package and fonts to support major charsets (Chinese, Japanese, Arabic, Hebrew, Thai and a few others) # Note: this installs the necessary libs to make the bundled version of Chromium that Puppeteer # installs, work. RUN apt-get update \ &amp;&amp; apt-get install -y wget gnupg \ &amp;&amp; wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \ &amp;&amp; sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" &gt;&gt; /etc/apt/sources.list.d/google.list' \ &amp;&amp; apt-get update \ &amp;&amp; apt-get install -y google-chrome-unstable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf \ --no-install-recommends \ &amp;&amp; rm -rf /var/lib/apt/lists/* # Install node modules RUN npm i # Add user so we don't need --no-sandbox. RUN groupadd -r -f audio \ &amp;&amp; groupadd -r -f video \ &amp;&amp; usermod -a -G audio,video node \ &amp;&amp; mkdir -p /home/node/Downloads \ &amp;&amp; chown -R node:node /home/node USER node CMD ["google-chrome-unstable"] </code></pre> <p>Application builds and runs well, but as soon as i try to start browser with <code>await puppeteer.launch();</code> i get this error:</p> <pre><code>pdf | Error: Failed to launch the browser process! pdf | [0612/133635.958777:FATAL:zygote_host_impl_linux.cc(116)] No usable sandbox! Update your kernel or see https://chromium.googlesource.com/chromium/src/+/master/docs/linux/suid_sandbox_development.md for more information on developing with the SUID sandbox. If you want to live dangerously and need an immediate workaround, you can try using --no-sandbox. pdf | #0 0x5638d5faa399 base::debug::CollectStackTrace() pdf | #1 0x5638d5f0b2a3 base::debug::StackTrace::StackTrace() pdf | #2 0x5638d5f1cc95 logging::LogMessage::~LogMessage() pdf | #3 0x5638d77f940e service_manager::ZygoteHostImpl::Init() pdf | #4 0x5638d5ad5060 content::ContentMainRunnerImpl::Initialize() pdf | #5 0x5638d5b365e7 service_manager::Main() pdf | #6 0x5638d5ad3631 content::ContentMain() pdf | #7 0x5638d5b3580d headless::(anonymous namespace)::RunContentMain() pdf | #8 0x5638d5b3550c headless::HeadlessShellMain() pdf | #9 0x5638d35295a7 ChromeMain pdf | #10 0x7fc01f0492e1 __libc_start_main pdf | #11 0x5638d35293ea _start pdf | pdf | Received signal 6 pdf | #0 0x5638d5faa399 base::debug::CollectStackTrace() pdf | #1 0x5638d5f0b2a3 base::debug::StackTrace::StackTrace() pdf | #2 0x5638d5fa9f35 base::debug::(anonymous namespace)::StackDumpSignalHandler() pdf | #3 0x7fc0255f30e0 (/lib/x86_64-linux-gnu/libpthread-2.24.so+0x110df) pdf | #4 0x7fc01f05bfff gsignal pdf | #5 0x7fc01f05d42a abort pdf | #6 0x5638d5fa8e95 base::debug::BreakDebugger() pdf | #7 0x5638d5f1d132 logging::LogMessage::~LogMessage() pdf | #8 0x5638d77f940e service_manager::ZygoteHostImpl::Init() pdf | #9 0x5638d5ad5060 content::ContentMainRunnerImpl::Initialize() pdf | #10 0x5638d5b365e7 service_manager::Main() pdf | #11 0x5638d5ad3631 content::ContentMain() pdf | #12 0x5638d5b3580d headless::(anonymous namespace)::RunContentMain() pdf | #13 0x5638d5b3550c headless::HeadlessShellMain() pdf | #14 0x5638d35295a7 ChromeMain pdf | #15 0x7fc01f0492e1 __libc_start_main pdf | #16 0x5638d35293ea _start pdf | r8: 0000000000000000 r9: 00007ffcd14664d0 r10: 0000000000000008 r11: 0000000000000246 pdf | r12: 00007ffcd1467788 r13: 00007ffcd1466760 r14: 00007ffcd1467790 r15: aaaaaaaaaaaaaaaa pdf | di: 0000000000000002 si: 00007ffcd14664d0 bp: 00007ffcd1466710 bx: 0000000000000006 pdf | dx: 0000000000000000 ax: 0000000000000000 cx: 00007fc01f05bfff sp: 00007ffcd1466548 pdf | ip: 00007fc01f05bfff efl: 0000000000000246 cgf: 002b000000000033 erf: 0000000000000000 pdf | trp: 0000000000000000 msk: 0000000000000000 cr2: 0000000000000000 pdf | [end of stack trace] pdf | Calling _exit(1). Core file will not be generated. pdf | pdf | pdf | TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md pdf | pdf | at onClose (/home/node/app/node_modules/puppeteer/lib/launcher/BrowserRunner.js:159:20) pdf | at Interface.&lt;anonymous&gt; (/home/node/app/node_modules/puppeteer/lib/launcher/BrowserRunner.js:149:65) pdf | at Interface.emit (events.js:327:22) pdf | at Interface.close (readline.js:416:8) pdf | at Socket.onend (readline.js:194:10) pdf | at Socket.emit (events.js:327:22) pdf | at endReadableNT (_stream_readable.js:1221:12) pdf | at processTicksAndRejections (internal/process/task_queues.js:84:21) </code></pre> <p>oh yeah, container name is <code>pdf</code></p> <p>I tried looking at puppeteer troubleshooting page as suggested, but i didn't found any solution.</p> <p>Any suggestions?</p>
62,383,642
4
1
null
2020-06-12 13:47:42.65 UTC
11
2022-07-29 08:20:33.647 UTC
2020-06-12 14:27:02.027 UTC
null
12,048,220
null
12,048,220
null
1
15
node.js|docker|google-chrome|docker-compose|puppeteer
28,909
<p>I found a way that allows the use of chrome sandbox, thanks to usethe4ce's answer in <a href="https://stackoverflow.com/questions/50662388/running-headless-chrome-puppeteer-with-no-sandbox">here</a></p> <p>Initially i needed to install chrome separately from puppeteer, i edited my Dockerfile as following:</p> <pre><code>FROM node:12.18.0 WORKDIR /home/runner/app ADD package*.json ./ # Install latest chrome dev package and fonts to support major charsets (Chinese, Japanese, Arabic, Hebrew, Thai and a few others) # Note: this installs the necessary libs to make the bundled version of Chromium that Puppeteer # installs, work. RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \ &amp;&amp; sh -c 'echo &quot;deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main&quot; &gt;&gt; /etc/apt/sources.list.d/google.list' \ &amp;&amp; apt-get update \ &amp;&amp; apt-get install -y google-chrome-unstable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst ttf-freefont \ --no-install-recommends \ &amp;&amp; rm -rf /var/lib/apt/lists/* # Uncomment to skip the chromium download when installing puppeteer. If you do, # you'll need to launch puppeteer with: # browser.launch({executablePath: 'google-chrome-unstable'}) ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true # Install node modules RUN npm i\ # Add user so we don't need --no-sandbox. # same layer as npm install to keep re-chowned files from using up several hundred MBs more space &amp;&amp; groupadd -r runner &amp;&amp; useradd -r -g runner -G audio,video runner \ &amp;&amp; mkdir -p /home/runner/Downloads \ &amp;&amp; chown -R runner:runner /home/runner \ &amp;&amp; chown -R runner:runner /home/runner/app/node_modules USER runner CMD [&quot;google-chrome-unstable&quot;] </code></pre> <p>Doing that, error changed from <code>No usable sandbox</code> to:</p> <pre><code>Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted </code></pre> <p>Then i followed usethe4ce's answer advices. Docker by default blocks accessibility to some kernel level operations, Seccomp options allow to &quot;unlock&quot; some of those operations that chrome needs to create his own sandbox. So i added this <a href="https://github.com/jessfraz/dotfiles/blob/master/etc/docker/seccomp/chrome.json" rel="noreferrer">chrome.json</a> file to my repo, and i edited my docker-compose file as following:</p> <pre><code>version: &quot;3.8&quot; services: &lt;service name&gt;: build: &lt;build options&gt; init: true security_opt: - seccomp=&lt;path to chrome.json file&gt; [...] </code></pre> <p>If you are not using a docker-compose file you can run your container using the option <code>--security-opt seccomp=path/to/chrome.json</code> as suggested in the linked answer.</p> <p>Finally launch the browser using:</p> <pre><code>await puppeteer.launch({ executablePath: 'google-chrome-unstable' }); </code></pre> <hr /> <p>Edit:</p> <p>It is not suitable to use a custom installation of chrome, as its version could not be fully supported by puppeteer. The only version guarantied to work with a specific puppeteer version is the one bundled.</p> <p>So i suggest using security_opt as above, just ignore the custom installation part.</p>
390,534
Aggregate functions in WHERE clause in SQLite
<p>Simply put, I have a table with, among other things, a column for timestamps. I want to get the row with the most recent (i.e. greatest value) timestamp. Currently I'm doing this:</p> <pre><code>SELECT * FROM table ORDER BY timestamp DESC LIMIT 1 </code></pre> <p>But I'd much rather do something like this:</p> <pre><code>SELECT * FROM table WHERE timestamp=max(timestamp) </code></pre> <p>However, SQLite rejects this query:</p> <pre><code>SQL error: misuse of aggregate function max() </code></pre> <p>The <a href="http://www.sqlite.org/lang_expr.html" rel="noreferrer">documentation</a> confirms this behavior (bottom of page):</p> <blockquote> <p>Aggregate functions may only be used in a SELECT statement.</p> </blockquote> <p>My question is: is it possible to write a query to get the row with the greatest timestamp without ordering the select and limiting the number of returned rows to 1? This seems like it should be possible, but I guess my SQL-fu isn't up to snuff.</p>
390,542
4
0
null
2008-12-24 00:57:33.743 UTC
4
2012-10-18 13:18:47.95 UTC
null
null
null
nobody
658
null
1
13
sql|sqlite|where-clause|aggregate-functions
41,439
<pre><code>SELECT * from foo where timestamp = (select max(timestamp) from foo) </code></pre> <p>or, if SQLite insists on treating subselects as sets, </p> <pre><code>SELECT * from foo where timestamp in (select max(timestamp) from foo) </code></pre>
671,694
Passing Credentials to Sql Report Server 2008
<p>I am pretty new in C# and my English is not so good - sorry in advance if I miss a point.</p> <p>I tried to build an ASP.NET web site with a <code>ReportService</code> control. As you might already know, SSRS 2008 does not allow anonymous login. So, I tried to pass Credentials to SSRS which will be stored inside my web page so that users will be able to see the report without logging in.</p> <p>I found the code below and put it on my <code>WebForm</code>, but I'm having a problem with the report parameters. </p> <ul> <li><p>If there are default values for the report parameters, the below code works okay. </p></li> <li><p>But, if I try to change the value of a parameter, the whole page is<br> refreshed and before I click the "View Report" button, all<br> parameters are reset to default or null values.</p></li> </ul> <p>Any suggestion on how to avoid refreshing the whole page, or another way to pass the login info to SSRS? Thanks a lot in advance.</p> <pre><code>using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Net; using Microsoft.Reporting.WebForms; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ReportViewer1.Width = 800; ReportViewer1.Height = 600; ReportViewer1.ProcessingMode = ProcessingMode.Remote; IReportServerCredentials irsc =new CustomReportCredentials("administrator", "MYpassworw", "domena"); ReportViewer1.ServerReport.ReportServerCredentials = irsc; ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://192.168.0.1/ReportServer/"); ReportViewer1.ServerReport.ReportPath = "/autonarudzba/listanarudzbi"; ReportViewer1.ServerReport.Refresh(); } } public class CustomReportCredentials : IReportServerCredentials { private string _UserName; private string _PassWord; private string _DomainName; public CustomReportCredentials(string UserName, string PassWord, string DomainName) { _UserName = UserName; _PassWord = PassWord; _DomainName = DomainName; } public System.Security.Principal.WindowsIdentity ImpersonationUser { get { return null; } } public ICredentials NetworkCredentials { get { return new NetworkCredential(_UserName, _PassWord, _DomainName); } } public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority) { authCookie = null; user = password = authority = null; return false; } } </code></pre>
671,761
4
2
null
2009-03-22 22:16:48.063 UTC
5
2017-10-09 06:26:26.123 UTC
2016-06-23 09:55:35.743 UTC
Mark Brackett
1,698,143
adopilot
69,433
null
1
21
c#|asp.net|reporting-services|ssrs-2008
52,856
<p>I really haven't messed with SSRS - but my ASP.NET hat tells me you may want to wrap that stuff in an <code>if (!IsPostBack)</code> block to keep it from running on the page refresh. My guess is that <code>ReportViewer1.ServerReport.Refresh()</code> pulls the default values again.</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { ReportViewer1.Width = 800; ReportViewer1.Height = 600; ReportViewer1.ProcessingMode = ProcessingMode.Remote; IReportServerCredentials irsc =new CustomReportCredentials("administrator", "MYpassworw", "domena"); ReportViewer1.ServerReport.ReportServerCredentials = irsc; ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://192.168.0.1/ReportServer/"); ReportViewer1.ServerReport.ReportPath = "/autonarudzba/listanarudzbi"; ReportViewer1.ServerReport.Refresh(); } } </code></pre>
1,096,899
Back to revision in Subversion
<p>suppose you update your code to revision 10 which is broken. You want to go back to revision 9, work on the code and wait until someone will fix the build:</p> <pre><code>svn merge -rHEAD:9 . </code></pre> <p>But it won't work, why?</p>
1,096,921
4
0
null
2009-07-08 08:48:32.237 UTC
5
2018-04-02 19:37:37.413 UTC
2018-04-02 19:37:37.413 UTC
null
59,087
null
61,628
null
1
56
svn|version-control
65,884
<p>If you simply want to go back to an other revision, <code>update</code> is what you are looking for:</p> <pre><code>svn update -r 9 </code></pre> <p>You can work on the code but you can't commit changes. Well, if revision 10 didn't change the same file you changed, you could commit but it's better if you wait for revision 10 to be fixed.</p> <p>Instead, if you want to go ahead and work on the code, you might consider to create a branch from revision 9, go ahead in the branch and reintegrate the branch into trunk when revision 10 is fixed.</p>
54,419,027
How to reset a spy in Jasmine?
<p>I have an issue where I've set up a mock service as a spy.</p> <pre><code> mockSelectionsService = jasmine.createSpyObj(['updateSelections']); </code></pre> <p>I then call that stub method twice, each time in a different test. The problem is that when i <code>expect()</code> the spy with <code>.toHaveBeenCalledWith()</code> the toHaveBeenCalledWith method also contains the arguments it was passed from the first test which produces a false positive on my second test.</p> <p>How do I wipe/clear/reset the spyObject for my next test so that it no longer believes it as been called at all?</p> <p>Initialisation of services/components</p> <pre><code> beforeEach(() =&gt; { mockSelectionsService = jasmine.createSpyObj(['updateSelections']); TestBed.configureTestingModule({ declarations: [QuickSearchComponent, LoaderComponent, SearchComponent, SearchPipe, OrderByPipe], providers: [OrderByPipe, SearchPipe, SlicePipe, {provide: SelectionsService, useValue: mockSelectionsService}], imports: [FormsModule, HttpClientModule] }); fixture = TestBed.createComponent(QuickSearchComponent); component = fixture.componentInstance; fixture.detectChanges(); fixture.componentInstance.templates = mockTemplates; fixture.componentInstance.manufacturers = mockManufacturers; }); </code></pre>
54,419,453
5
2
null
2019-01-29 10:32:48.613 UTC
4
2022-09-23 19:27:18.387 UTC
2020-05-29 09:54:57.77 UTC
null
542,251
null
2,066,039
null
1
53
javascript|angular|jasmine
39,919
<p><code>const spy = spyOn(somethingService, "doSomething");</code></p> <p><code>spy.calls.reset();</code></p> <p>This resets the already made calls to the spy. This way you can reuse the spy between tests. The other way would be to nest the tests in another <code>describe()</code> and put a <code>beforeEach()</code> in it too.</p>
873,828
Inserting a row into DB2 from a sub-select - NULL error
<p>I am trying to insert a row into a table, using a value that is derived from another table. Here is the SQL statement that I am trying to use:</p> <pre><code>INSERT INTO NextKeyValue(KeyName, KeyValue) SELECT 'DisplayWorkItemId' AS KeyName, (MAX(work_item_display_id) + 1) AS KeyValue FROM work_item; </code></pre> <p>So, I am trying to create a row in <code>NextKeyValue</code> that has 'KeyName' of 'DisplayWorkItemId' and 'KeyValue' of one more than the maximum value in <code>work_item.work_item_display_id</code>.</p> <p>The SELECT statement in the above query returns the expected result, when I run it on its own.</p> <p>The whole SQL query is giving me the following error, though:</p> <blockquote> <p>Error: DB2 SQL Error: SQLCODE=-407, SQLSTATE=23502, SQLERRMC=TBSPACEID=2, TABLEID=75, COLNO=2, DRIVER=3.50.152 SQLState: 23502 ErrorCode: -407</p> </blockquote> <p>What does this mean, and what is wrong with my query?</p>
873,945
1
1
null
2009-05-17 03:13:47.63 UTC
null
2009-05-17 17:29:27.033 UTC
2009-05-17 17:29:27.033 UTC
null
4,257
null
4,257
null
1
7
sql|db2
80,232
<p>The most probable explanation is that you have additional columns in NextKeyValue table that can't accept NULL values, and this INSERT statement is "trying" to put NULL in them. </p> <p>Is that the case by any chance?</p>
57,453,141
Using React Hooks To Update w/ Scroll
<p>I'm trying to control the visibility of a React Component based on whether an individual is scrolling down on the component. The visibility is passed into the <code>Fade</code> element as the "in" property.</p> <p>I've set up a listener using the UseEffect Hook, which adds the listener onMount. The actual onScroll function is supposed to update the scrollTop state (which is the current value of the height to the top of the page) and then the scrolling state (which compares the event's scroll to the top of the page with the previous state, and if the first is greater than the second, returns true).</p> <p>However, for some reason the setScrollTop hook isn't working, and the scrolling state continues to stay at 0.</p> <p>What am I doing wrong? Here's the full component:</p> <pre><code>export const Header = (props) =&gt; { const classes = useStyles(); const [scrolling, setScrolling] = useState(false); const [scrollTop, setScrollTop] = useState(0); const onScroll = (e) =&gt; { setScrollTop(e.target.documentElement.scrollTop); setScrolling(e.target.documentElement.scrollTop &gt; scrollTop); } useEffect(() =&gt; { window.addEventListener('scroll', onScroll); },[]); useEffect(() =&gt; { console.log(scrollTop); }, [scrollTop]) return ( &lt;Fade in={!scrolling}&gt; &lt;AppBar className={classes.header} position="fixed"&gt; .... </code></pre>
57,453,199
2
0
null
2019-08-11 19:53:33.547 UTC
9
2021-01-07 09:11:08.07 UTC
2019-08-11 23:05:47.547 UTC
null
7,860,026
null
7,860,026
null
1
29
javascript|reactjs|react-hooks
52,269
<p>You're missing the dependencies in your hook. Try this: </p> <pre><code> useEffect(() =&gt; { const onScroll = e =&gt; { setScrollTop(e.target.documentElement.scrollTop); setScrolling(e.target.documentElement.scrollTop &gt; scrollTop); }; window.addEventListener("scroll", onScroll); return () =&gt; window.removeEventListener("scroll", onScroll); }, [scrollTop]); </code></pre> <p>By moving <code>onScroll</code> inside the <code>useEffect</code>, you don't need to track it on the hook's dependencies, however since it uses <code>scrollTop</code> from the component's scope, you'll need to add it. </p> <p>Alternatively, if for some reason you don't want to move <code>onScroll</code> definition inside the <code>useEffect</code>, you'll need to wrap <code>onScroll</code> in <code>useCallback</code> and track it in <code>useEffect</code>'s dependency array.</p> <p>In general I'd recommend adding <code>react-hooks/exhaustive-deps</code> to your ESlint rules</p> <p>Also it's a good idea to remove the event listener in cleanup function.</p>
29,855,098
Is there a built-in javascript function similar to os.path.join?
<p>Is there a built-in javascript (client-side) function that functions similarly to Node's <code>path.join</code>? I know I can join strings in the following manner:</p> <pre><code>['a', 'b'].join('/') </code></pre> <p>The problem is that if the strings already contain a leading/trailing &quot;/&quot;, then they will not be joined correctly, e.g.:</p> <pre><code>['a/','b'].join('/') </code></pre>
29,855,282
10
1
null
2015-04-24 18:39:10.527 UTC
1
2022-06-10 18:29:35.147 UTC
2022-02-08 14:04:29.443 UTC
null
2,059,996
null
1,459,601
null
1
43
javascript|node.js
36,899
<p>There isn't currently a built-in that will perform a join while preventing duplicate separators. If you want concise, I'd just write your own:</p> <pre><code>function pathJoin(parts, sep){ var separator = sep || '/'; var replace = new RegExp(separator+'{1,}', 'g'); return parts.join(separator).replace(replace, separator); } var path = pathJoin(['a/', 'b', 'c//']) </code></pre>
40,025,762
angular2-cli gives @multi styles error
<p>I started using angular2-cli recently and created a new project. I wanted to use bootstrap in my project hence I installed bootstrap and then wanted to import the bootstrap css file like it is shown in the the angular2-cli guide here. <a href="https://github.com/angular/angular-cli#global-library-installation" rel="noreferrer">https://github.com/angular/angular-cli#global-library-installation</a> After running ng serve I get the following error.</p> <blockquote> <p>ERROR in multi styles Module not found: Error: Can't resolve '/home/krishna/angular2_migrate/webui/node_modules/bootstrap/dist/css/bootstrap.min.css' in '/home/krishna/angular2_migrate/webui/node_modules/angular-cli/models' @ multi styles</p> </blockquote> <p>What am I doing wrong ?</p> <p>Information about angular2-cli version</p> <pre><code>krishna@Krishna:~/angular2_migrate/webui$ ng version Could not start watchman; falling back to NodeWatcher for file system events. Visit http://ember-cli.com/user-guide/#watchman for more info. angular-cli: 1.0.0-beta.17 node: 4.4.3 os: linux x64 </code></pre>
42,698,103
16
0
null
2016-10-13 15:58:13.207 UTC
3
2021-03-22 12:24:28.397 UTC
null
null
null
null
3,979,221
null
1
18
css|angular|styles|angular2-cli
44,096
<p>Add ../ before path.</p> <p>In angular-cli.json,</p> <pre><code>"styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", "styles.scss" ] </code></pre> <p><strong>Update</strong></p> <p>In angular7, there is angular.json file and you do not need to add ../ before path</p>
39,882,618
paste text with a newline/return in formatted text
<p>I want to do a column that is formatted to use for a mailing address and I can not get the newline/return carriage or <code>&lt;br/&gt;</code> to work when making a new column.</p> <pre><code>name = c("John Smith", "Patty Smith", "Sam Smith") address = c("111 Main St.", "222 Main St.", "555 C Street") cityState = c("Portland, OR 97212", "Portland, OR 95212", "Portland, OR 99212") df &lt;- data.frame(name, address, cityState) </code></pre> <p>I want to create a column that formats the data in an address label: John Smith 111 Main st. Portland, OR 97212</p> <p>Each new column: will have a return after each line: so it is always 3 lines. One line for each of the other 3 columns. </p> <pre><code># example of what I am trying to do... paste0(name, "return", address, "return", cityState). Everything I have tried does not work for making a newline. </code></pre>
39,882,657
2
1
null
2016-10-05 19:55:58.433 UTC
3
2016-10-14 19:40:54.48 UTC
2016-10-14 19:40:54.48 UTC
null
1,016,716
null
5,151,945
null
1
25
r|text|text-processing
67,754
<p>To get a new line (or return) we use <code>\n</code>. So</p> <pre><code>addr = paste(name, address, cityState, sep="\n") </code></pre> <p>To view the result just use <code>cat</code></p> <pre><code>&gt; cat(addr[1]) #John Smith #111 Main St. #Portland, OR 97212 </code></pre> <p>The function <code>cat</code> just prints to the screen.</p> <hr> <p>The other standard character is <code>\t</code> for a tab-space.</p>
23,757,345
Android does not correctly scroll on input focus if not body element
<p>When a mobile browser brings up a keyboard it tries to move the scrollbars so that the input is still in view.</p> <p>On iOS Safari it seems to do this properly by finding the <strong>nearest</strong> scrolling parent.</p> <p>On Android native or Chrome mobile browser it seems to just try the body element and then gives up, so the focused input is hidden beneath the keyboard.</p> <h3> How to break it</h3> <p>Set <code>overflow-y: hidden</code> on the body element. Create a scrollable container and put a form in there.</p> <p>When you select an element near the bottom of your screen it will be obscured by the keyboard.</p> <h3>Demo</h3> <p><a href="http://dominictobias.com/android-scroll-bug/" rel="noreferrer">http://dominictobias.com/android-scroll-bug/</a></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no&quot;/&gt; &lt;title&gt;Android scroll/focus bug&lt;/title&gt; &lt;style&gt; html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; } .scroll { position: absolute; top: 0; right: 0; bottom: 0; left: 0; overflow-y: scroll; } input { margin-bottom: 20px; width: 100%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;scroll&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 1&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 2&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 3&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 4&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 5&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 6&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 7&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 8&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 9&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 10&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 11&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 12&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 13&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 14&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 15&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 16&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 17&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 18&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 19&quot;&gt; &lt;input type=&quot;text&quot; value=&quot;Input 20&quot;&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Any ideas how to fix this? Will it require some browser detection and messy hacks?</p>
25,032,766
4
1
null
2014-05-20 10:30:41.32 UTC
10
2017-08-22 13:41:38.04 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
414,062
null
1
21
android|google-chrome|input|scroll|focus
32,229
<p>This is a bug in the Android native browser. By the way, the input scrolls into the view after a character is typed on the soft keyboard.</p> <p>The following code snippet placed somewhere in the page should help:</p> <pre><code>if(/Android 4\.[0-3]/.test(navigator.appVersion)){ window.addEventListener("resize", function(){ if(document.activeElement.tagName=="INPUT"){ window.setTimeout(function(){ document.activeElement.scrollIntoViewIfNeeded(); },0); } }) } </code></pre>
42,720,421
Could not load file or assembly System.Net.Http version 4.1.1.0
<p>I'm porting a Net Framework 4 dll to Net Core. When porting my unit tests project I get an exception running some specific tests (not all).</p> <blockquote> <p>System.IO.FileLoadException: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p> </blockquote> <p>This is the project.json for my dll</p> <pre><code> { "version": "1.0.0-*", "dependencies": { "log4net": "2.0.7", "NETStandard.Library": "1.6.1", "Newtonsoft.Json": "9.0.1", "StackExchange.Redis": "1.2.1" }, "frameworks": { "netstandard1.6": { "imports": "dnxcore50" } } } </code></pre> <p>And this is Packages.config for the unit tests project</p> <pre><code>&lt;packages&gt; &lt;package id="Castle.Core" version="4.0.0" targetFramework="net462" /&gt; &lt;package id="log4net" version="2.0.7" targetFramework="net462" /&gt; &lt;package id="Microsoft.Win32.Primitives" version="4.0.1" targetFramework="net462" /&gt; &lt;package id="Moq" version="4.7.1" targetFramework="net462" /&gt; &lt;package id="Newtonsoft.Json" version="9.0.1" targetFramework="net462" /&gt; &lt;package id="StackExchange.Redis" version="1.2.1" targetFramework="net462" /&gt; &lt;package id="System.Diagnostics.DiagnosticSource" version="4.0.0" targetFramework="net462" /&gt; &lt;package id="System.IO" version="4.1.0" targetFramework="net462" /&gt; &lt;package id="System.IO.FileSystem" version="4.0.1" targetFramework="net462" /&gt; &lt;package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net462" /&gt; &lt;package id="System.IO.FileSystem.Watcher" version="4.0.0" targetFramework="net462" /&gt; &lt;package id="System.Linq" version="4.1.0" targetFramework="net462" /&gt; &lt;package id="System.Net.Http" version="4.1.1" targetFramework="net462" /&gt; &lt;package id="System.Net.NameResolution" version="4.0.0" targetFramework="net462" /&gt; &lt;package id="System.Runtime" version="4.1.0" targetFramework="net462" /&gt; &lt;package id="System.Runtime.Extensions" version="4.1.0" targetFramework="net462" /&gt; &lt;package id="System.Security.Cryptography.Algorithms" version="4.2.0" targetFramework="net462" /&gt; &lt;package id="System.Security.Cryptography.Encoding" version="4.0.0" targetFramework="net462" /&gt; &lt;package id="System.Security.Cryptography.Primitives" version="4.0.0" targetFramework="net462" /&gt; &lt;package id="System.Security.Cryptography.X509Certificates" version="4.1.0" targetFramework="net462" /&gt; &lt;package id="System.Text.RegularExpressions" version="4.1.0" targetFramework="net462" /&gt; &lt;package id="System.Threading.Thread" version="4.0.0" targetFramework="net462" /&gt; &lt;/packages&gt; </code></pre>
42,721,262
10
3
null
2017-03-10 14:13:05.803 UTC
4
2022-01-26 20:30:14.15 UTC
2019-01-18 15:22:39.08 UTC
null
1,448,943
null
1,535,132
null
1
42
c#|.net|.net-core|porting|.net-framework-version
47,165
<p>Fixed it by updating System.Net.Http to 4.3.1</p>
37,333,339
How to install latest JMeter in Ubuntu 15.10?
<p>When I try to install Apache JMeter in Ubuntu 15.10 using apt-get install JMeter it installs the older version 2.11. However, I tried to download the latest JMeter 3.0 version and when tried to run <code>jmeter.jar</code> file it won't open.</p> <p>I am trying to install this on a Ubuntu 15.10 server. I can't upgrade to the latest version. </p> <p>Could anyone guide me how to install or open the latest release of JMeter in Ubuntu 15.10?</p>
37,342,086
4
1
null
2016-05-19 20:24:21.36 UTC
2
2019-09-11 18:24:27.533 UTC
2018-09-07 08:20:59.697 UTC
null
5,180,017
null
3,584,034
null
1
18
ubuntu|jmeter
54,076
<p>Looking into <a href="http://packages.ubuntu.com/search?keywords=jmeter" rel="noreferrer">jmeter package details</a> you won't be able to get latest JMeter via apt.</p> <p>Follow the next simple installation steps:</p> <ol> <li><code>sudo apt-get update</code> - to refresh packages metadata</li> <li><code>sudo apt-get install openjdk-7-jre-headless</code> - Java 7 is pre-requisite for JMeter 3.0</li> <li><code>wget -c http://ftp.ps.pl/pub/apache//jmeter/binaries/apache-jmeter-3.0.tgz</code> - download JMeter 3.0</li> <li><code>tar -xf apache-jmeter-3.0.tgz</code> - unpack JMeter</li> <li><code>apache-jmeter-3.0/bin/./jmeter -n -t apache-jmeter-3.0/extras/Test.jmx</code> - run a sample test</li> </ol> <p>If anything goes wrong check <code>java -version</code> command output, it should print something like:</p> <blockquote> <p>ubuntu@ip-172-31-57-21:~$ java -version</p> <p>java version &quot;<strong>1.7</strong>.0_101&quot;</p> <p>OpenJDK Runtime Environment (IcedTea 2.6.6) (7u101-2.6.6-0ubuntu0.14.04.1)</p> <p>OpenJDK 64-Bit Server VM (build 24.95-b01, mixed mode)</p> </blockquote> <p>Make sure you have <strong>1.7</strong> or higher.</p> <p>Just in case see <a href="https://www.blazemeter.com/blog/how-get-started-jmeter-part-1-installation-test-plans" rel="noreferrer">How to Get Started With JMeter: Part 1 - Installation &amp; Test Plans</a> article for more detailed installation details</p>
37,268,572
How to use data binding for Switch onCheckedChageListener event?
<p>As question indicates, how to bind checked change listener to Switch button in xml ? </p> <p>I am not using recycler view. Just a simple layout.</p> <p>Any help appreciated.</p>
37,288,929
4
2
null
2016-05-17 06:21:28.067 UTC
7
2020-06-24 19:18:09.32 UTC
2018-09-21 04:56:37.813 UTC
null
6,891,563
null
5,907,852
null
1
42
android|data-binding|android-switch
30,570
<p>You can do it with a method reference:</p> <pre><code>&lt;CheckBox android:onCheckedChanged="@{callback::checkedChangedListener}".../&gt; </code></pre> <p>or with a lambda expression if you want to pass different parameters:</p> <pre><code>&lt;CheckBox android:onCheckedChanged="@{() -&gt; callback.checked()}".../&gt; </code></pre>
30,305,217
Is it possible to use Mockito in Kotlin?
<p>The problem I'm facing is that <code>Matchers.anyObject()</code> returns <code>null</code>. When used to mock method that only accepts non-nullable types it causes a "Should not be null" exception to be thrown. </p> <pre><code>`when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -&gt; someResponse } </code></pre> <p>Mocked method:</p> <pre><code>public open fun login(userCredentials: UserCredentials): Response </code></pre>
30,308,199
6
2
null
2015-05-18 13:58:34.37 UTC
23
2020-09-03 17:17:50.65 UTC
null
null
null
null
1,356,130
null
1
92
java|mocking|mockito|kotlin
47,214
<p>There are two possible workarounds:</p> <pre><code>private fun &lt;T&gt; anyObject(): T { Mockito.anyObject&lt;T&gt;() return uninitialized() } private fun &lt;T&gt; uninitialized(): T = null as T @Test fun myTest() { `when`(mockedBackend).login(anyObject())).thenAnswer { ... } } </code></pre> <p>The other workaround is </p> <pre><code>private fun &lt;T&gt; anyObject(): T { return Mockito.anyObject&lt;T&gt;() } @Test fun myTest() { `when`(mockedBackend).login(anyObject())).thenAnswer { ... } } </code></pre> <p>Here is <a href="https://discuss.kotlinlang.org/t/how-to-use-mockito-with-kotlin/324" rel="noreferrer">some more discussion</a> on this topic, where the workaround is first suggested.</p>
20,793,306
How to append content to querySelectorAll element with innerHTML/innerText?
<p>I currently have my class element:</p> <pre><code>var frame_2 = document.querySelectorAll(".name"); </code></pre> <p>Currently this div is empty. I now want to "append/add" some content to that div - I had a go with <code>innerHTML</code> + <code>innerText</code> but for some reason nothing seems to be added.</p> <p><strong>Example:</strong></p> <pre><code>frame_2.innerHTML = '&lt;img src="image.gif" /&gt;'; </code></pre> <p>and</p> <pre><code>frame_2.innerText = 'some text'; </code></pre> <p>Any suggestions? Im not sure if there are ways of doing the same - or performance'wise something better?</p>
20,793,362
2
1
null
2013-12-27 01:01:49.287 UTC
5
2021-11-11 13:54:00.017 UTC
null
null
null
null
1,231,561
null
1
9
javascript|append|innerhtml|innertext
51,304
<p>this gives you a list of elements that contain the class name</p> <pre><code>var name=document.querySelectorAll(".name"); </code></pre> <p>you want the first element?</p> <pre><code>name[0].textContent='some text'; </code></pre> <p>This gives you one single element, the first one.</p> <pre><code>var name=document.querySelector(".name"); name.textContent='some text'; </code></pre> <p>To <em>append</em> stuff</p> <pre><code>name.appendChild(document.createTextNode('pizza')); name.appendChild(document.createElement('div')).textContent='spaghetti'; name.appendChild(document.createElement('img')).src='cookie.jpg'; </code></pre> <p><strong>EDIT</strong></p> <p>To get the elements by classname, then retrieve the id :</p> <pre><code>var names=document.querySelectorAll(".name"),l; while(l--){ console.log(names[l].id); } </code></pre> <p>or if i didn't understand correctly</p> <p>html</p> <pre><code>&lt;div class="spaghetti" id="pizza"&gt;&lt;/div&gt; </code></pre> <p>js</p> <pre><code>document.querySelector(".spaghetti#pizza") </code></pre> <p><strong>EDIT2</strong></p> <p>html </p> <pre><code>&lt;div id="container1"&gt;&lt;div class="my-class"&gt;&lt;/div&gt;&lt;/div&gt; </code></pre> <p>js</p> <pre><code>document.querySelector("#container1&gt;.my-class") </code></pre>
47,062,532
Multiple Lines for Text per Legend Label in ggplot2
<p>I'm trying to deal with very long labels for a legend in a bar plot (see picture included and the code i used to produce it. I need to break them down in multiple (rows of) lines (2 or 3), other wise the whole picture will be to wide. Some help would be very helpful. Actually I also suspect that my code is not as concise as it should be, but at least it works (but feel free to change)</p> <p><a href="https://i.stack.imgur.com/CinYu.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/CinYu.jpg" alt="enter image description here"></a></p> <pre><code>glimpse(df) Observations: 301 Variables: 3 $ V12n &lt;int&gt; 1, 4, 4, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1... $ V12 &lt;fctr&gt; De verwijzer neemt contact op om na te gaa... $ METING.f &lt;fctr&gt; Meting 0, Meting 0, Meting 0, Meting 0, Me... p = ggplot(df, aes(x = V12n, fill = V12)) + geom_bar(aes(y = (..count..)/tapply(..count..,..PANEL..,sum) [..PANEL..])) + scale_y_continuous(labels = scales::percent) + geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..])), stat = "count", vjust = -0.25) + facet_grid(.~ METING.f) + labs(title = " ", x = "Vraag 12", y = "Percentage") + theme(axis.text.x = element_blank(), axis.ticks.x=element_blank()) + scale_fill_manual(values = c("greenyellow", "green4", "darkorange1", "red"), name = "Zijn er afspraken gemaakt over het overdragen van de verantwoordelijkheid naar de volgende zorgverlener?\n") p </code></pre>
47,064,251
1
3
null
2017-11-01 19:45:12.733 UTC
14
2017-11-01 21:49:12.563 UTC
null
null
null
null
5,235,404
null
1
27
r|ggplot2|legend
38,405
<p>You can use <code>str_wrap</code> for automated wrapping of long strings or you can hard code breaks by adding <code>\n</code> (the line break character) to a string. To add space between the legend keys, you can use the <code>legend.key.height</code> theme element. Here's an example with the built-in <code>iris</code> data frame:</p> <pre><code>library(stringr) library(tidyverse) # Create long labels to be wrapped iris$Species = paste(iris$Species, "random text to make the labels much much longer than the original labels") ggplot(iris, aes(Sepal.Length, Sepal.Width, colour=str_wrap(Species,20))) + geom_point() + labs(colour="Long title shortened\nwith wrapping") + theme(legend.key.height=unit(2, "cm")) </code></pre> <p><a href="https://i.stack.imgur.com/6DcfF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6DcfF.png" alt="enter image description here"></a></p>
32,448,414
What does colon at assignment for list[:] = [...] do in Python
<p>I came accross the following code:</p> <pre><code># O(n) space def rotate(self, nums, k): deque = collections.deque(nums) k %= len(nums) for _ in xrange(k): deque.appendleft(deque.pop()) nums[:] = list(deque) # &lt;- Code in question </code></pre> <p>What does <code>nums[:] =</code> do that <code>nums =</code> does not? For that matter, what does <code>nums[:]</code> do that <code>nums</code> does not?</p>
32,448,477
2
3
null
2015-09-08 02:36:27.893 UTC
22
2022-08-03 15:26:31.773 UTC
2017-12-06 22:20:27.337 UTC
null
2,202,071
null
1,218,699
null
1
28
python|python-3.x
37,048
<p>This syntax is a slice assignment. A slice of <code>[:]</code> means the entire list. The difference between <code>nums[:] =</code> and <code>nums =</code> is that the latter doesn't replace elements in the original list. This is observable when there are two references to the list</p> <pre><code>&gt;&gt;&gt; original = [1, 2, 3] &gt;&gt;&gt; other = original &gt;&gt;&gt; original[:] = [0, 0] # changes the contents of the list that both # original and other refer to &gt;&gt;&gt; other # see below, now you can see the change through other [0, 0] </code></pre> <p>To see the difference just remove the <code>[:]</code> from the assignment above.</p> <pre><code>&gt;&gt;&gt; original = [1, 2, 3] &gt;&gt;&gt; other = original &gt;&gt;&gt; original = [0, 0] # original now refers to a different list than other &gt;&gt;&gt; other # other remains the same [1, 2, 3] </code></pre> <hr /> <p>To take the title of your question literally, if <code>list</code> is a variable name and not the builtin, it will replace the length of the sequence with an ellipsis</p> <pre><code>&gt;&gt;&gt; list = [1,2,3,4] &gt;&gt;&gt; list[:] = [...] &gt;&gt;&gt; list [Ellipsis] </code></pre> <hr /> <p>Note: vincent thorpe's comments below are either incorrect or irrelevant to the question. This is not a matter of value vs reference semantics.</p>
34,764,796
Why does declaring main as an array compile?
<p>I saw <a href="https://codegolf.stackexchange.com/a/69193/13441">a snippet of code on CodeGolf</a> that's intended as a compiler bomb, where <code>main</code> is declared as a huge array. I tried the following (non-bomb) version:</p> <pre><code>int main[1] = { 0 }; </code></pre> <p>It seems to compile fine under Clang and with only a warning under GCC:</p> <blockquote> <p>warning: 'main' is usually a function [-Wmain]</p> </blockquote> <p>The resulting binary is, of course, garbage.</p> <p>But why does it compile at all? Is it even allowed by the C specification? The section that I think is relevant says:</p> <blockquote> <p>5.1.2.2.1 Program startup</p> <p>The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters [...] or with two parameters [...] or in some other implementation-defined manner.</p> </blockquote> <p>Does "some other implementation-defined manner" include a global array? (It seems to me that the spec still refers to a <em>function</em>.)</p> <p>If not, is it a compiler extension? Or a feature of the toolchains, that serves some other purpose and they decided to make it available through the frontend?</p>
34,764,930
6
4
null
2016-01-13 10:55:04.573 UTC
12
2018-04-25 07:56:21.013 UTC
2017-04-13 12:38:59.36 UTC
null
-1
null
1,892,179
null
1
62
c|gcc|clang|program-entry-point
11,756
<p>It's because C allows for "non-hosted" or freestanding environment which doesn't require the <code>main</code> function. This means that the name <code>main</code> is freed for other uses. This is why the language as such allows for such declarations. Most compilers are designed to support both (the difference is mostly how linking is done) and therefore they don't disallow constructs that would be illegal in hosted environment.</p> <p>The section you refers to in the standard refers to hosted environment, the corresponding for freestanding is:</p> <blockquote> <p>in a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. Any library facilities available to a freestanding program, other than the minimal set required by clause 4, are implementation-defined.</p> </blockquote> <p>If you then link it as usual it will go bad since the linker normally has little knowledge about the nature of the symbols (what type it has or even if it's a function or variable). In this case the linker will happily resolve calls to <code>main</code> to the variable named <code>main</code>. If the symbol is not found it will result in link error. </p> <p>If you're linking it as usual you're basically trying to use the compiler in hosted operation and then not defining <code>main</code> as you're supposed to means undefined behavior as per appendix J.2:</p> <blockquote> <p>the behavior is undefined in the following circumstances:</p> <ul> <li>...</li> <li>program in a hosted environment does not define a function named main using one of the specified forms (5.1.2.2.1)</li> </ul> </blockquote> <p>The purpose of the freestanding possibility is to be able to use C in environments where (for example) standard libraries or CRT initialization is not given. This means that the code that is run before <code>main</code> is called (that's the CRT initialization that initializes the C runtime) might not provided and you would be expected to provide that yourself (and you may decide to have a <code>main</code> or may decide not to).</p>
25,297,705
mean( ,na.rm=TRUE) still returns NA
<p>I'm very new to R (moving over from SPSS). I'm using RStudio on a Mac running Mavericks. Please answer my question in words of 2 syllables as this is my first real attempt at anything like this. I've worked through some basic tutorials and can make things work on all the sample data.</p> <p>I have a data set with 64,000-ish rows and about 20 columns. I want to get the mean of the variable "hold_time", but whatever I try I get either NA or NA and a warning message</p> <p>I have tried all of the following:</p> <pre><code>&gt; summary(data_Apr_Jun$hold_time,na.rm=TRUE) 5 6 7 4 8 2 1 3 10 9596 9191 3192 1346 1145 977 940 655 534 11 9 12 0 13 15 14 16 17 490 444 249 128 106 86 73 68 40 98 118 121 128 125 97 101 188 86 31 29 28 28 27 27 26 26 26 102 105 113 81 119 139 127 134 152 25 25 25 25 24 24 23 23 23 18 69 96 106 110 111 120 190 76 23 23 23 22 22 22 22 22 22 82 132 135 156 166 94 115 116 117 22 21 21 21 21 21 20 20 20 142 153 165 19 93 100 104 112 126 20 20 20 20 20 19 19 19 19 131 138 143 157 177 189 61 87 103 19 19 19 19 19 19 19 19 18 108 148 176 212 54 56 64 74 79 18 18 18 18 18 18 18 18 18 99 107 129 163 168 171 178 226 236 18 17 17 17 17 17 17 17 17 59 71 78 95 114 122 123 130 (Other) 17 17 17 17 16 16 16 16 2739 NA's 29807 &gt; mean(as.numeric(data_Apr_Jun$hold_time,NA.rm=TRUE)) [1] NA &gt; data_Apr_Jun$hold_time[data_Apr_Jun$hold_time=="NA"]&lt;-0 &gt; mean(as.numeric(data_Apr_Jun$hold_time)) [1] NA &gt; mean(data_Apr_Jun$hold_time) [1] NA Warning message: In mean.default(data_Apr_Jun$hold_time) : argument is not numeric or logical: returning NA &gt; mean(as.numeric(data_Apr_Jun$hold_time,na.rm=TRUE)) [1] NA &gt; colMeans(data_Apr_Jun$hold_time) Error in colMeans(data_Apr_Jun$hold_time) : 'x' must be an array of at least two dimensions &gt; colMeans(data_Apr_Jun) Error in colMeans(data_Apr_Jun) : 'x' must be numeric &gt; mean(data_Apr_Jun$hold_time,na.omit) [1] NA Warning message: In mean.default(data_Apr_Jun$hold_time, na.omit) : argument is not numeric or logical: returning NA </code></pre> <p>So even though I am removing the NAs they don't seem to be being removed. I am flummoxed.</p>
25,297,762
2
4
null
2014-08-13 23:13:42.023 UTC
4
2017-05-29 23:58:01.373 UTC
null
null
null
null
3,939,345
null
1
9
r|mean|na
46,418
<p>Hello Rnovice unfortunatly there are several errors... Lets resolve them one by one:</p> <pre><code>&gt; mean(as.numeric(data_Apr_Jun$hold_time,NA.rm=TRUE)) [1] NA </code></pre> <p>This is because you use <code>na.rm</code> in a wrong manner: it should be </p> <pre><code>mean(as.numeric(data_Apr_Jun$hold_time),na.rm=TRUE) </code></pre> <ol> <li><code>na.rm</code> is an argument of <code>mean</code>, not of <code>as.numeric</code> (caution with the brackets)</li> <li>is <code>na.rm</code> <code>R</code> is case sensitive</li> </ol> <p>==================================================================================</p> <pre><code>&gt; data_Apr_Jun$hold_time[data_Apr_Jun$hold_time=="NA"]&lt;-0 </code></pre> <p><code>R</code> does not allow comparison with <code>NA</code> as i pointed our here: <a href="https://stackoverflow.com/questions/25274518/something-weird-about-returning-nas/25274690#25274690">Something weird about returning NAs</a><br> What you mean is</p> <pre><code>data_Apr_Jun$hold_time[which(is.na(data_Apr_Jun$hold_time))] &lt;- 0 </code></pre> <p>One more remark <code>=="NA"</code> is comparing with a string <code>"NA"</code>. Try <code>is.na("NA")</code> and <code>is.na(NA)</code> to see the difference. </p> <p>==================================================================================</p> <pre><code>colMeans(data_Apr_Jun$hold_time) Error in colMeans(data_Apr_Jun$hold_time) : 'x' must be an array of at least two dimensions </code></pre> <p>try <code>data_Apr_Jun$hold_time</code> and you will see, that it returns a vector. This is why a colwise mean (computed by <code>colMeans</code>) makes no sence.</p> <p>Hope the rest is understandable/solveable with these hints. One very importent thing that you already realized:<br> <strong>Use R!</strong> you are on the right track!</p>
39,072,001
Dependency injection resolving by name
<p>How can I inject different implementation of object for a specific class?</p> <p>For example, in Unity, I can define two implementations of <code>IRepository</code></p> <pre><code>container.RegisterType&lt;IRepository, TestSuiteRepositor(&quot;TestSuiteRepository&quot;); container.RegisterType&lt;IRepository, BaseRepository&gt;(); </code></pre> <p>and call the needed implementation</p> <pre><code>public BaselineManager([Dependency(&quot;TestSuiteRepository&quot;)]IRepository repository) </code></pre>
39,072,950
5
4
null
2016-08-22 05:37:02.05 UTC
13
2020-11-12 01:11:17.833 UTC
2020-11-12 01:07:14.643 UTC
null
1,402,846
null
2,924,700
null
1
35
c#|dependency-injection|asp.net-core
39,518
<p>As @Tseng pointed, there is no built-in solution for named binding. However using factory method may be helpful for your case. Example should be something like below:</p> <p>Create a repository resolver:</p> <pre><code>public interface IRepositoryResolver { IRepository GetRepositoryByName(string name); } public class RepositoryResolver : IRepositoryResolver { private readonly IServiceProvider _serviceProvider; public RepositoryResolver(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IRepository GetRepositoryByName(string name) { if(name == "TestSuiteRepository") return _serviceProvider.GetService&lt;TestSuiteRepositor&gt;(); //... other condition else return _serviceProvider.GetService&lt;BaseRepositor&gt;(); } } </code></pre> <p>Register needed services in <code>ConfigureServices.cs</code></p> <pre><code>services.AddSingleton&lt;IRepositoryResolver, RepositoryResolver&gt;(); services.AddTransient&lt;TestSuiteRepository&gt;(); services.AddTransient&lt;BaseRepository&gt;(); </code></pre> <p>Finally use it in any class:</p> <pre><code>public class BaselineManager { private readonly IRepository _repository; public BaselineManager(IRepositoryResolver repositoryResolver) { _repository = repositoryResolver.GetRepositoryByName("TestSuiteRepository"); } } </code></pre>
6,929,180
REST and SOAP webservice in android
<p>I found tutorial to use kSOAP api to use SOAP webservice. Can anyone provide me sample programs (tutorial) on getting REST webservice and SOAP webservice in android. I have googled lot but didn't find such type of tutorial.</p>
6,978,711
2
1
null
2011-08-03 15:38:20.39 UTC
15
2012-10-28 10:06:13.523 UTC
2012-04-03 08:45:21.817 UTC
user831722
948,041
user831722
null
null
1
10
android|web-services|rest|soap
22,977
<p><strong>SOAP</strong></p> <p>Pros:</p> <blockquote> <ul> <li>Langauge, platform, and transport agnostic</li> <li>Designed to handle distributed computing environments</li> <li>Is the prevailing standard for web services, and hence has better support from other standards (WSDL, WS-*) and tooling from vendors</li> <li>Built-in error handling (faults)</li> <li>Extensibility</li> </ul> </blockquote> <p>Cons:</p> <blockquote> <ul> <li>Conceptually more difficult, more "heavy-weight" than REST</li> <li>More verbose</li> <li>Harder to develop, requires tools</li> </ul> </blockquote> <p><strong>REST</strong></p> <p>Pros:</p> <blockquote> <ul> <li>Language and platform agnostic</li> <li>Much simpler to develop than SOAP</li> <li>Small learning curve, less reliance on tools</li> <li>Concise, no need for additional messaging layer</li> <li>Closer in design and philosophy to the Web</li> </ul> </blockquote> <p>Cons:</p> <blockquote> <ul> <li>Assumes a point-to-point communication model--not usable for distributed computing environment where message may go through one or more intermediaries</li> <li>Lack of standards support for security, policy, reliable messaging, etc., so services that have more sophisticated requirements are harder to develop ("roll your own")</li> <li>Tied to the HTTP transport model</li> </ul> </blockquote> <h2>Example of REST</h2> <p>Use apache http jar</p> <pre><code>public void callRestWebService(){ System.out.println(".....REST.........."); HttpClient httpclient = new DefaultHttpClient(); HttpGet request = new HttpGet(wsdlURL); request.addHeader("company name", "abc"); request.addHeader("getAccessNumbers","http://service.xyz.com/"); ResponseHandler&lt;String&gt; handler = new BasicResponseHandler(); try { result = httpclient.execute(request, handler); System.out.println("..result..."+result); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } httpclient.getConnectionManager().shutdown(); } // end callWebService() } </code></pre> <h2>Example of SOAP</h2> <p>You can use either ksoap or create soap xml by yourself and send to url </p> <pre><code>private boolean callSOAPWebService() { OutputStream out = null; int respCode = -1; boolean isSuccess = false; URL url = null; HttpsURLConnection httpURLConnection = null; try { url = new URL(wsdlURL); httpURLConnection = (HttpsURLConnection) url.openConnection(); do { // httpURLConnection.setHostnameVerifier(DO_NOT_VERIFY); httpURLConnection.setRequestMethod("POST"); httpURLConnection .setRequestProperty("Connection", "keep-alive"); httpURLConnection .setRequestProperty("Content-Type", "text/xml"); httpURLConnection.setRequestProperty("SendChunked", "True"); httpURLConnection.setRequestProperty("UseCookieContainer", "True"); HttpURLConnection.setFollowRedirects(false); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(true); httpURLConnection.setRequestProperty("Content-length", getReqData().length + ""); httpURLConnection.setReadTimeout(10 * 1000); // httpURLConnection.setConnectTimeout(10 * 1000); httpURLConnection.connect(); out = httpURLConnection.getOutputStream(); if (out != null) { out.write(getReqData()); out.flush(); } if (httpURLConnection != null) { respCode = httpURLConnection.getResponseCode(); Log.e("respCode", ":" + respCode); } } while (respCode == -1); // If it works fine if (respCode == 200) { try { InputStream responce = httpURLConnection.getInputStream(); String str = convertStreamToString(responce); System.out.println(".....data....." + new String(str)); // String str // =Environment.getExternalStorageDirectory().getAbsolutePath()+"/sunilwebservice.txt"; // File f = new File(str); // // try{ // f.createNewFile(); // FileOutputStream fo = new FileOutputStream(f); // fo.write(b); // fo.close(); // }catch(Exception ex){ // ex.printStackTrace(); // } } catch (Exception e1) { e1.printStackTrace(); } } else { isSuccess = false; } } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out = null; } if (httpURLConnection != null) { httpURLConnection.disconnect(); httpURLConnection = null; } } return isSuccess; } public static String createSoapHeader() { String soapHeader = null; soapHeader = "&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;" + "&lt;soap:Envelope " + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + "&gt;"; return soapHeader; } public static byte[] getReqData() { StringBuilder requestData = new StringBuilder(); requestData.append(createSoapHeader()); requestData .append("&lt;soap:Body&gt;" + "&lt;getAccessNumbers" + " xmlns=\"http://service.xyz.com.com/\"" + "&lt;/getAccessNumbers&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt;"); return requestData.toString().trim().getBytes(); } private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } </code></pre>
6,545,741
Django catch-all URL without breaking APPEND_SLASH
<p>I have an entry in my urls.py that acts as a catch-all which loads a simple view if it finds an appropriate page in the database. The problem with this approach is that the URL solver will then never fail, meaning that the APPEND_SLASH functionality won't kick in - which I need.</p> <p>I'd rather not have to resort to adding a prefix to the static page URLs to stop it being a catch-all. I do know about flatpages, which uses a 404 hook rather than an entry in urls.py, and I had kinda hoped to avoid having to use it, but I guess this problem might be exactly the kind of reason why one would use it.</p> <p>Any way round this problem or should I just give in and use flatpages?</p>
10,199,446
2
0
null
2011-07-01 08:59:39.27 UTC
7
2012-04-17 21:28:14.023 UTC
2011-07-01 09:38:46.447 UTC
null
77,533
null
77,533
null
1
32
django
18,387
<p>Make sure that your catch-all URL pattern has a slash at the end, and that the pattern is the last in your URLconf. If the catch-all pattern doesn't end with a slash, then it will match stray URLs before the middleware tries appending a slash.</p> <p>For example, use <code>r'^.*/$'</code> instead of <code>r'^.*'</code> as your last pattern.</p> <p>To do the same, but pass the url to the view as a named argument, use <code>r'^(?P&lt;url&gt;.*)/$'</code>.</p>
7,613,359
Why Can't I access src/test/resources in Junit test run with Maven?
<p>I am having a problems running the following code:</p> <pre><code>configService.setMainConfig("src/test/resources/MainConfig.xml"); </code></pre> <p>From within a Junit @Before method.</p> <p>Is this the way Maven builds out its target folder?</p>
7,613,426
3
0
null
2011-09-30 16:29:37.82 UTC
14
2019-08-02 19:44:29.433 UTC
null
null
null
null
1,399,539
null
1
48
java|junit4|mockito
85,231
<p>Access <code>MainConfig.xml</code> directly. The <code>src/test/resources</code> directory contents are placed in the root of your CLASSPATH.</p> <p>More precisely: contents of <code>src/test/resources</code> are copied into <code>target/test-classes</code>, so if you have the following project structure:</p> <pre><code>. └── src └── test ├── java │   └── foo │   └── C.java └── resources ├── a.xml └── foo └── b.xml </code></pre> <p>It will result with the following test CLASSPATH contents:</p> <ul> <li><code>/foo/C.class</code></li> <li><code>/a.xml</code></li> <li><code>/foo/b.xml</code></li> </ul> <p>To actually access the files from Java source, use <code>getClass().getResource("/MainConfig.xml").getFile()</code>.</p>
7,500,081
Scala: what is the best way to append an element to an Array?
<p>Say I have an <code>Array[Int]</code> like</p> <pre><code>val array = Array( 1, 2, 3 ) </code></pre> <p>Now I would like to append an element to the array, say the value <code>4</code>, as in the following example: </p> <pre><code>val array2 = array + 4 // will not compile </code></pre> <p>I can of course use <code>System.arraycopy()</code> and do this on my own, but there must be a Scala library function for this, which I simply could not find. Thanks for any pointers!</p> <p>Notes:</p> <ol> <li><p>I am aware that I can append another Array of elements, like in the following line, but that seems too round-about:</p> <pre><code>val array2b = array ++ Array( 4 ) // this works </code></pre></li> <li><p>I am aware of the advantages and drawbacks of List vs Array and here I am for various reasons specifically interested in extending an Array. </p></li> </ol> <h3>Edit 1</h3> <p>Thanks for the answers pointing to the <code>:+</code> operator method. This is what I was looking for. Unfortunately, it is rather slower than a custom append() method implementation using <code>arraycopy</code> -- about two to three times slower. Looking at the implementation in <code>SeqLike[]</code>, a builder is created, then the array is added to it, then the append is done via the builder, then the builder is rendered. Not a good implementation for arrays. I did a quick benchmark comparing the two methods, looking at the fastest time out of ten cycles. Doing 10 million repetitions of a single-item append to an 8-element array instance of some class <code>Foo</code> takes 3.1 sec with <code>:+</code> and 1.7 sec with a simple <code>append()</code> method that uses <code>System.arraycopy();</code> doing 10 million single-item append repetitions on 8-element arrays of Long takes 2.1 sec with <code>:+</code> and 0.78 sec with the simple <code>append()</code> method. Wonder if this couldn't be fixed in the library with a custom implementation for <code>Array</code>?</p> <h3>Edit 2</h3> <p>For what it's worth, I filed a ticket: <a href="https://issues.scala-lang.org/browse/SI-5017">https://issues.scala-lang.org/browse/SI-5017</a></p>
7,500,143
3
6
null
2011-09-21 12:53:10.943 UTC
32
2017-11-24 11:47:29.183 UTC
2014-12-19 08:07:42.29 UTC
null
402,884
null
820,380
null
1
121
arrays|scala|append
185,266
<p>You can use <code>:+</code> to append element to array and <code>+:</code> to prepend it:</p> <pre><code>0 +: array :+ 4 </code></pre> <p>should produce:</p> <pre><code>res3: Array[Int] = Array(0, 1, 2, 3, 4) </code></pre> <p>It's the same as with any other implementation of <code>Seq</code>. </p>
7,575,589
How does JavaScript handle AJAX responses in the background?
<p>Since JavaScript runs in a single thread, after an AJAX request is made, what actually happens in the background? I would like to get a deeper insight into this, can anyone shed some light? </p>
7,575,649
3
4
null
2011-09-27 20:58:11.563 UTC
104
2020-05-03 07:46:18.157 UTC
2016-06-29 00:23:41.13 UTC
null
914,272
null
914,272
null
1
145
javascript|xmlhttprequest
24,667
<p>Below the covers, javascript has an event queue. Each time a javascript thread of execution finishes, it checks to see if there is another event in the queue to process. If there is, it pulls it off the queue and triggers that event (like a mouse click, for example).</p> <p>The native code networking that lies under the ajax call will know when the ajax response is done and an event will get added to the javascript event queue. How the native code knows when the ajax call is done depends upon the implementation. It may be implemented with threads or it may also be event driven itself (it doesn't really matter). The point of the implementation is that when the ajax response is done, some native code will know it's done and put an event into the JS queue. </p> <p>If no Javascript is running at the time, the event will be immediately triggered which will run the ajax response handler. If something is running at the time, then the event will get processed when the current javascript thread of execution finishes. There doesn't need to be any polling by the javascript engine. When a piece of Javascript finishes executing, the JS engine just checks the event queue to see if there is anything else that needs to run. If so, it pops the next event off the queue and executes it (calling one or more callback functions that are registered for that event). If nothing is in the event queue, then the JS interpreter has free time (garbage collection or idle) until some external agent puts something else in the event queue and wakes it up again.</p> <p>Because all outside events go through the event queue and no event is ever triggered while javascript is actually running something else, it stays single threaded.</p> <p>Here are some articles on the details:</p> <ul> <li><a href="http://ejohn.org/blog/how-javascript-timers-work/" rel="noreferrer">How Javascript Timers Work - written by John Resig</a> </li> <li><a href="http://javascript.info/tutorial/events-and-timing-depth" rel="noreferrer">Events and Timing in Depth</a> </li> <li><a href="http://www.w3.org/TR/html5/webappapis.html#event-loops" rel="noreferrer">W3 spec: HTML5 event loops</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop" rel="noreferrer">MDN article on Event Loop</a></li> <li><a href="http://thomashunter.name/blog/the-javascript-event-loop-presentation/" rel="noreferrer">Presentation on JS event queue</a></li> <li><a href="http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/" rel="noreferrer">The JavaScript Event Loop: Explained</a></li> <li><a href="https://sking7.github.io/articles/389411742.html" rel="noreferrer">Five Patterns to Help Tame Asynchronous Javascript</a></li> <li><a href="https://thomashunter.name/blog/the-javascript-event-loop-presentation/" rel="noreferrer">Javascript Event Loop Presentation</a></li> <li><a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ" rel="noreferrer">Video Discussing How Javascript Works (including event loop at 10:27)</a></li> </ul>
24,282,121
Why use tanh for activation function of MLP?
<p>Im personally studying theories of neural network and got some questions. </p> <p>In many books and references, for activation function of hidden layer, hyper-tangent functions were used. </p> <p>Books came up with really simple reason that linear combinations of tanh functions can describe nearly all shape of functions with given error. </p> <p>But, there came a question. </p> <ol> <li>Is this a real reason why tanh function is used?</li> <li>If then, is it the only reason why tanh function is used?</li> <li>if then, is tanh function the only function that can do that?</li> <li>if not, what is the real reason?..</li> </ol> <p>I stock here keep thinking... please help me out of this mental(?...) trap!</p>
24,282,337
7
1
null
2014-06-18 09:38:06.29 UTC
18
2020-03-05 20:27:08.177 UTC
null
null
null
null
3,709,740
null
1
20
machine-learning|neural-network|hyperbolic-function
28,220
<p>In truth both tanh and logistic functions can be used. The idea is that you can map any real number ( [-Inf, Inf] ) to a number between [-1 1] or [0 1] for the tanh and logistic respectively. In this way, it can be shown that a combination of such functions can approximate any non-linear function. Now regarding the preference for the tanh over the logistic function is that the first is symmetric regarding the 0 while the second is not. This makes the second one more prone to saturation of the later layers, making training more difficult.</p>
24,222,088
Capture program stdout and stderr to separate variables
<p>Is it possible to redirect stdout from an external program to a variable and stderr from external programs to another variable in one run?</p> <p>For example:</p> <pre><code>$global:ERRORS = @(); $global:PROGERR = @(); function test() { # Can we redirect errors to $PROGERR here, leaving stdout for $OUTPUT? $OUTPUT = (&amp; myprogram.exe 'argv[0]', 'argv[1]'); if ( $OUTPUT | select-string -Pattern "foo" ) { # do stuff } else { $global:ERRORS += "test(): oh noes! 'foo' missing!"; } } test; if ( @($global:ERRORS).length -gt 0 ) { Write-Host "Script specific error occurred"; foreach ( $err in $global:ERRORS ) { $host.ui.WriteErrorLine("err: $err"); } } else { Write-Host "Script ran fine!"; } if ( @($global:PROGERR).length -gt 0 ) { # do stuff } else { Write-Host "External program ran fine!"; } </code></pre> <p>A dull example however I am wondering if that is possible?</p>
24,223,482
7
1
null
2014-06-14 16:44:00.87 UTC
8
2021-05-03 23:36:30.417 UTC
2018-12-09 13:23:10.25 UTC
null
1,630,171
null
2,245,659
null
1
48
windows|powershell|command-line|stdout|stderr
52,321
<p>The easiest way to do this is to use a file for the stderr output, e.g.:</p> <pre><code>$output = &amp; myprogram.exe 'argv[0]', 'argv[1]' 2&gt;stderr.txt $err = get-content stderr.txt if ($LastExitCode -ne 0) { ... handle error ... } </code></pre> <p>I would also use $LastExitCode to check for errors from native console EXE files.</p>
24,390,005
Checking for empty or null List<string>
<p>I have a List where sometimes it is empty or null. I want to be able to check if it contains any List-item and if not then add an object to the List.</p> <pre><code> // I have a list, sometimes it doesn't have any data added to it var myList = new List&lt;object&gt;(); // Expression is always false if (myList == null) Console.WriteLine("List is never null"); if (myList[0] == null) myList.Add("new item"); //Errors encountered: Index was out of range. Must be non-negative and less than the size of the collection. // Inner Exception says "null" </code></pre>
24,390,071
25
1
null
2014-06-24 15:00:51.427 UTC
22
2022-03-22 11:24:20.82 UTC
2018-10-13 19:33:32.967 UTC
null
2,768,516
null
3,131,062
null
1
97
c#|list
416,385
<p>Try the following code:</p> <pre><code> if ( (myList!= null) &amp;&amp; (!myList.Any()) ) { // Add new item myList.Add(&quot;new item&quot;); } </code></pre> <p>A late EDIT because for these checks I now like to use the following solution. First, add a small reusable extension method called Safe():</p> <pre><code>public static class IEnumerableExtension { public static IEnumerable&lt;T&gt; Safe&lt;T&gt;(this IEnumerable&lt;T&gt; source) { if (source == null) { yield break; } foreach (var item in source) { yield return item; } } } </code></pre> <p>And then, you can do the same like:</p> <pre><code> if (!myList.Safe().Any()) { // Add new item myList.Add(&quot;new item&quot;); } </code></pre> <p>I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.</p> <p>And another EDIT, which doesn't require an extension method, but uses the ? (Null-conditional) operator (C# 6.0):</p> <pre><code>if (!(myList?.Any() ?? false)) { // Add new item myList.Add(&quot;new item&quot;); } </code></pre>
1,850,732
How to position a div dynamically below another?
<p>I'm trying to use jQuery to detect the position of a div (<code>#olddiv</code>), so I can use that position to place another div (<code>#newdiv</code>) exactly below it. The right borders of the 2 divs are aligned (right border). </p> <p>I'm trying to get the <code>#olddiv</code> bottom and right locations to use them as the <code>#newdiv</code> top and right borders. I've used this code, but it's not working. Any idea what I'm doing wrong? </p> <pre><code>var right = $('#olddiv').position().right; var top = $('#olddiv').position().bottom; $('#newdiv').css('top', right); $('#newdiv').css('right', top); </code></pre> <p>Also, I'm not sure if <code>position</code> is what I need. I think this can be done with <code>position</code> or <code>offset</code>, but I'm not sure:</p> <pre><code>$('#ID').position().left $('#ID').offset().left </code></pre> <p>Thanks</p>
1,850,766
4
0
null
2009-12-05 01:21:17.717 UTC
4
2016-04-29 09:15:36.11 UTC
2013-07-22 14:34:47.013 UTC
null
448,144
null
225,215
null
1
11
jquery|dom
39,404
<p>I've used offset() to position elements dynamically. Try this:</p> <pre><code>var offset = $('#olddiv').offset(); var height = $('#olddiv').height(); var width = $('#olddiv').width(); var top = offset.top + height + "px"; var right = offset.left + width + "px"; $('#ID').css( { 'position': 'absolute', 'right': right, 'top': top }); </code></pre> <p>also don't forget to bind this to the <code>window.onresize</code> event if you need it to scale when the user resizes the window.</p> <p><strong>UPDATE:</strong> another thought - does this have to be positioned absolutely? Why not just insert the div after the other in the DOM?</p> <pre><code>$('#olddiv').after($('#ID').html()); </code></pre> <p>then just make sure they are the same width.</p>
2,231,460
gdb: howto list open files
<p>I am wondering if it might be possible to get a list of files/directories that the debugged application has opened but not closed from GDB itself ?</p> <p>Currently I set a breakpoint and then I use an external program like <code>lsof</code> to check for opened files.</p> <p>But this approach is really annoying.</p> <p>Environment: Debian-Lenny with gdb v6.8</p> <p><strong>EDIT</strong>: I am asking because my application is leaking file handles in some situations</p>
2,232,734
4
0
null
2010-02-09 18:28:36.657 UTC
11
2017-07-21 15:29:38.117 UTC
2010-02-09 18:37:25.65 UTC
anon
null
anon
null
null
1
22
gdb
26,050
<p>due to the help of Nicholas I was able to fully automate the task by defining a macro.</p> <p><code>.gdbinit</code>:</p> <pre><code>define lsof shell rm -f pidfile set logging file pidfile set logging on info proc set logging off shell lsof -p `cat pidfile | perl -n -e 'print $1 if /process (.+)/'` end document lsof List open files end </code></pre> <p>here is a session using the new macro (the program opens a file in the /tmp directory):</p> <pre><code>file hello break main run next lsof </code></pre> <p>output:</p> <pre><code>... hello 2683 voku 5r REG 8,1 37357 11110 /home/voku/hello hello 2683 voku 6w REG 8,1 0 3358 /tmp/testfile.txt ... </code></pre>
52,724,312
Webpack: TypeError: Cannot read property 'properties' of undefined
<p>Here is the branch and repo in question: <a href="https://github.com/Futuratum/moon.holdings/tree/dev" rel="noreferrer">https://github.com/Futuratum/moon.holdings/tree/dev</a></p> <blockquote> <p>/Users/leongaban/projects/Futuratum/moon.holdings/node_modules/webpack-cli/bin/config-yargs.js:89 describe: optionsSchema.definitions.output.properties.path.description,</p> </blockquote> <p>Not sure why I'm getting this error, but I upgraded from Webpack 3 to 4.</p> <p><strong>webpack</strong></p> <pre><code>/* eslint-disable no-console */ import webpack from 'webpack'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import CopyWebpackPlugin from 'copy-webpack-plugin'; import path from 'path'; const moonholdings = path.resolve(__dirname, 'moonholdings'); const app = path.resolve(__dirname, 'app'); const nodeModules = path.resolve(__dirname, 'node_modules'); const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: path.join(__dirname, '/app/index.html'), inject: 'body' }); const ExtractTextPluginConfig = new ExtractTextPlugin({ filename: 'moonholdings.css', disable: false, allChunks: true }); const CopyWebpackPluginConfigOptions = [{ from: 'app/static', to: 'static/' }]; const CopyWebpackPluginConfig = new CopyWebpackPlugin(CopyWebpackPluginConfigOptions); const PATHS = { app, build: moonholdings }; const LAUNCH_COMMAND = process.env.npm_lifecycle_event; const isProduction = LAUNCH_COMMAND === 'production'; process.env.BABEL_ENV = LAUNCH_COMMAND; const productionPlugin = new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }); const base = { entry: ['babel-polyfill', PATHS.app], performance: { hints: false, maxAssetSize: 1000000 }, output: { path: PATHS.build, publicPath: '/', filename: 'index_bundle.js' }, resolve: { modules: [app, nodeModules] }, module: { rules: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.s?css/, use: [ 'style-loader', 'css-loader', 'sass-loader' ] }, { test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)/, loader: 'file-loader?name=[path][name].[ext]' } ] } }; const developmentConfig = { devtool: 'inline-source-map', devServer: { contentBase: moonholdings }, plugins: [ CopyWebpackPluginConfig, ExtractTextPluginConfig, HtmlWebpackPluginConfig ] }; const productionConfig = { devtool: false, plugins: [ CopyWebpackPluginConfig, ExtractTextPluginConfig, HtmlWebpackPluginConfig, productionPlugin ] }; export default Object.assign( {}, base, isProduction === true ? productionConfig : developmentConfig ); </code></pre> <p><strong>package.json</strong></p> <pre><code>{ "name": "moon.holdings", "version": "1.0.0", "description": "Cryptocurrency asset portfolio", "main": "index.js", "repository": "https://github.com/Futuratum/moon.holdings.git", "author": "Leon Gaban &lt;leongaban@gmail.com&gt;", "license": "MIT", "scripts": { "start": "webpack &amp;&amp; webpack-dev-server", "webpack": "webpack-dev-server", "dev": "webpack-dev-server", "build": "webpack -p", "production": "webpack -p", "test": "yarn run test-eslint; yarn run test-jest:update", "test-eslint": "eslint app", "test-eslint:fix": "eslint --fix app", "test-sasslint": "./node_modules/.bin/sass-lint 'app/**/*.scss' -v -q", "test-jest": "jest", "test-jest:watch": "jest --watch", "test-jest:coverage": "jest --coverage", "test-jest:update": "jest --updateSnapshot" }, "setupFiles": [ "&lt;rootDir&gt;/config/polyfills.js", "&lt;rootDir&gt;/src/setupTests.js" ], "now": { "name": "moonholdings", "alias": "moon.holdings" }, "jest": { "moduleNameMapper": {}, "moduleFileExtensions": [ "js", "jsx" ], "moduleDirectories": [ "node_modules", "app" ], "setupTestFrameworkScriptFile": "./app/utils/testConfigure.js" }, "dependencies": { "axios": "^0.18.0", "babel-cli": "^6.26.0", "babel-core": "^6.26.0", "babel-eslint": "^8.2.2", "babel-loader": "^7.1.4", "babel-plugin-transform-async-to-generator": "^6.24.1", "babel-plugin-transform-es2015-destructuring": "^6.23.0", "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0", "babel-plugin-transform-object-rest-spread": "^6.26.0", "babel-plugin-transform-runtime": "^6.23.0", "babel-polyfill": "^6.26.0", "babel-preset-env": "^1.6.1", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "babel-preset-react-hmre": "^1.1.1", "babel-preset-stage-0": "^6.24.1", "babel-register": "^6.26.0", "copy-webpack-plugin": "^4.5.0", "css-loader": "^0.28.10", "enzyme": "^3.3.0", "enzyme-adapter-react-16": "^1.1.1", "enzyme-to-json": "^3.3.1", "eslint": "^4.18.2", "eslint-config-airbnb": "^16.1.0", "eslint-import-resolver-node": "^0.3.2", "eslint-plugin-dependencies": "^2.4.0", "eslint-plugin-import": "^2.9.0", "eslint-plugin-jsx-a11y": "^6.0.3", "eslint-plugin-react": "^7.7.0", "extract-text-webpack-plugin": "^3.0.2", "file-loader": "^1.1.11", "flexboxgrid": "^6.3.1", "git-hooks": "^1.1.10", "history": "^4.7.2", "html-webpack-plugin": "^3.0.6", "jest": "^22.4.2", "lodash": "^4.17.10", "node-sass": "^4.7.2", "path-to-regexp": "^2.2.0", "ramda": "^0.25.0", "react": "^16.2.0", "react-dom": "^16.2.0", "react-hot-loader": "^4.0.0", "react-redux": "^5.0.7", "react-router": "^4.2.0", "react-router-dom": "^4.2.2", "react-router-redux": "^4.0.8", "react-sortable-hoc": "^0.6.8", "react-test-renderer": "^16.3.2", "redux": "^3.7.2", "redux-mock-store": "^1.5.1", "redux-thunk": "^2.2.0", "rest": "^2.0.0", "sass-lint": "^1.12.1", "sass-loader": "^6.0.7", "style-loader": "^0.20.2", "svg-inline-loader": "^0.8.0", "svg-loader": "^0.0.2", "url-loader": "^1.0.1", "webpack": "^4.20.2", "webpack-cli": "^2.0.10", "webpack-dev-server": "2.11.1" } } </code></pre>
52,841,778
6
5
null
2018-10-09 15:14:02.74 UTC
null
2022-09-22 20:50:57.333 UTC
null
null
null
null
168,738
null
1
24
javascript|webpack
45,682
<p>Try to install latest LTS version of Node and test again. Works perfectly fine for me with latest LTS node and npm.</p>
10,723,088
401 response for CORS request in IIS with Windows Auth enabled
<p>I'm trying to enable CORS support in my WebAPI project, and if I enable Anonymous Authentication then everything works fine, but with Windows Auth + disabled anonymous authentication, the OPTIONS request sent always returns a 401 unauthorized response. The site requesting it is on the DOMAIN so should be able to make the call, is there any way to get around the issue without disabling Windows Authentication?</p>
10,820,339
14
2
null
2012-05-23 15:25:16.157 UTC
22
2021-11-07 08:24:57.077 UTC
null
null
null
null
88,170
null
1
51
iis-7.5|windows-authentication|asp.net-web-api|ntlm|cors
53,696
<p>From MS:</p> <p>If you disable anonymous authentication, it’s by design that IIS would return a 401 to any request. If they have enabled Windows auth, the 401 response in that case would have a WWW-Authenticate header to allow the client to start an authentication handshake. The question then becomes whether the client that the customer is using can do Windows authentication or not.</p> <p>Finally, it seems like there might be an underlying question about whether it’s possible or not to configure a URL such that anonymous access is allowed for one verb (OPTIONS, in this case), but require Windows authentication for other verbs. IIS does not support this through simple configuration. It might be possible to get this behavior by enabling both Anonymous and Windows authentication, setting ACLs on the content that deny access to the anonymous user, and then configuring the handler mapping for the URL in question so that it does not verify the existence of the file associated with the URL. But it would take some playing with it to confirm this.</p>
7,372,268
how to convert hex to base64
<p>how to convert hex string into base64 ? I found this page <a href="http://home2.paulschou.net/tools/xlate/" rel="noreferrer">http://home2.paulschou.net/tools/xlate/</a> but I need some function in java: <code>String base64 = ...decoder(String hex);</code> I found something in the Internet but they are to difficult and use byte array. I am looking for something simplier thx a lot</p>
7,372,374
6
1
null
2011-09-10 14:09:45.34 UTC
5
2022-01-22 11:40:53.527 UTC
null
null
null
null
431,769
null
1
17
java|base64
38,939
<p>Have a look at <a href="http://commons.apache.org/codec/" rel="noreferrer">Commons Codec</a> :</p> <pre><code> import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; byte[] decodedHex = Hex.decodeHex(hex); byte[] encodedHexB64 = Base64.encodeBase64(decodedHex); </code></pre>
7,694,843
using array_search for multi dimensional array
<p>using array_search in a 1 dimensional array is simple</p> <pre><code>$array = array("apple", "banana", "cherry"); $searchValue = "cherry"; $key = array_search($searchValue, $array); echo $key; </code></pre> <p>but how about an multi dimensional array?</p> <pre><code> #RaceRecord [CarID] [ColorID] [Position] [0] 1 1 3 [1] 2 1 1 [2] 3 2 4 [3] 4 2 2 [4] 5 3 5 </code></pre> <p>for example i want to get the index of the car whose position is 1. How do i do this?</p>
7,694,864
6
2
null
2011-10-08 04:34:50.233 UTC
8
2019-04-15 05:39:49.513 UTC
2017-07-11 08:52:50.733 UTC
null
4,474,165
null
946,159
null
1
35
php|arrays|multidimensional-array
104,137
<pre><code>function find_car_with_position($cars, $position) { foreach($cars as $index =&gt; $car) { if($car['Position'] == $position) return $index; } return FALSE; } </code></pre>
7,331,425
Twitter bootstrap CSS + jQuery
<p>I just discover twitter-boostrap </p> <p><a href="https://github.com/twbs/bootstrap" rel="nofollow">https://github.com/twbs/bootstrap</a></p> <p>and I'm wondering if there is a jquery library to use with it.</p> <p>For popovers, modals, tool tips, alerts messages, tabs...</p> <p>or for example, use this as jquery-ui theme!</p> <p>anyone know ?</p>
9,113,210
7
1
null
2011-09-07 09:17:07.42 UTC
10
2015-08-15 20:44:12.6 UTC
2013-09-09 17:22:10.73 UTC
null
1,430,996
null
210,456
null
1
26
jquery|jquery-ui|twitter-bootstrap
36,484
<p>There is Jquery UI Bootstrap: <a href="https://github.com/jquery-ui-bootstrap/jquery-ui-bootstrap" rel="nofollow noreferrer">https://github.com/jquery-ui-bootstrap/jquery-ui-bootstrap</a></p> <p>It's a Bootstrap port on jQuery UI.</p>
7,090,883
How can I get package name in android?
<p>I need to write some util class by myself and I need the packagename of android app. While I found the packageManager which only can be used in Activity and so on that has context. I only want to get packagename in my class which will be used in android app. So how can I do this? Thank you!</p>
7,090,983
9
1
null
2011-08-17 09:53:04.853 UTC
2
2018-01-18 15:55:27.79 UTC
2011-08-17 10:33:03.44 UTC
null
811,854
null
898,366
null
1
9
java|android
50,310
<p>Use : <code>getPackageManager().getPackageInfo(getPackageName(), 0).packageName</code> Or just <code>MyContext.getPackageName()</code></p> <p>You can also create a function:</p> <pre><code>public String getPackageName(Context context) { return context.getPackageName(); } </code></pre>
7,186,648
How to remove first 10 characters from a string?
<p>How to ignore the first 10 characters of a string?</p> <p>Input:</p> <pre><code>str = "hello world!"; </code></pre> <p>Output:</p> <pre><code>d! </code></pre>
7,186,711
12
4
null
2011-08-25 07:35:04.053 UTC
16
2020-06-01 08:31:35.27 UTC
2015-08-17 10:58:25.937 UTC
null
1,080,354
null
898,129
null
1
113
c#|asp.net|.net|string|substring
281,670
<pre><code>str = "hello world!"; str.Substring(10, str.Length-10) </code></pre> <p>you will need to perform the length checks else this would throw an error</p>
14,089,342
Refresh ComboBox Items, easiest way
<p>I've googled a lot. Found a lot as well. Unfortunately nothing is straight, easy and most importantly, simple. I want some guy write a <code>method</code> that takes a <code>List&lt;string&gt;</code> and removes previous <code>Items</code>, then set this <code>List&lt;string&gt;</code>.</p> <p>Currently I have a method but it's not error free.</p> <pre><code>public void refreshList(List&lt;string&gt; list){ albumList.Items.Clear(); albumList.DataSource = list; } </code></pre>
14,089,398
5
1
null
2012-12-30 08:25:54.09 UTC
3
2018-06-08 12:22:33.95 UTC
2015-07-15 12:04:41.273 UTC
null
2,723,943
null
1,928,378
null
1
11
c#|winforms|c#-4.0|combobox
70,049
<p>You don't need albumList.Items.Clear();</p> <p>This code works just fine</p> <pre><code>public void refreshList(List&lt;string&gt; list){ albumList.DataSource = list; } </code></pre>
14,018,394
Android SQLite Query - Getting latest 10 records
<p>I have a database saved in my Android application and want to retrieve the last 10 messages inserted into the DB.</p> <p>When I use:</p> <pre><code>Select * from tblmessage DESC limit 10; </code></pre> <p>it gives me the 10 messages but from the <strong>TOP</strong>. But I want the <strong>LAST</strong> 10 messages. Is it possible?</p> <p>Suppose the whole table data is -</p> <pre><code>1,2,3,4,5....30 </code></pre> <p>I wrote query <code>select * from tblmessage where timestamp desc limit 10</code></p> <p>It shows <code>30,29,28...21</code></p> <p>But I want the sequence as - <code>21,22,23...30</code></p>
14,018,868
9
3
null
2012-12-24 07:25:22.977 UTC
9
2020-11-16 00:55:03.147 UTC
2017-05-20 15:46:00.743 UTC
null
165,071
null
1,114,329
null
1
26
android|sql|sqlite|android-sqlite
41,518
<p>Change the DESC to ASC and you will get the records that you want, but if you need them ordered, then you will need to reverse the order that they come in. You can either do that in your own code or simply extend your query like so:</p> <pre><code>select * from ( select * from tblmessage order by sortfield ASC limit 10 ) order by sortfield DESC; </code></pre> <p>You really should always specify an order by clause, not just ASC or DESC.</p>
13,887,365
Circular Heatmap that looks like a donut
<p>I'm trying to create circular heatmap with ggplot2 so I can use a larger number of labels around the circumference of a circle. I'd like to have it look more like a donut with an empty hole in the middle but at the same time not losing any rows (they would need to be compressed).</p> <p>Code for what I have is below.</p> <pre><code>library(reshape) library(ggplot2) nba &lt;- read.csv("http://datasets.flowingdata.com/ppg2008.csv") nba$Name &lt;- with(nba, reorder(Name, PTS)) nba.m &lt;- melt(nba) nba.m &lt;- ddply(nba.m, .(variable), transform, value = scale(value)) p = ggplot(nba.m, aes(Name,variable)) + geom_tile(aes(fill = value), colour = "white") + scale_fill_gradient(low = "white", high = "steelblue") p&lt;-p+opts( panel.background=theme_blank(), axis.title.x=theme_blank(), axis.title.y=theme_blank(), panel.grid.major=theme_blank(), panel.grid.minor=theme_blank(), axis.text.x=theme_blank(), axis.ticks=theme_blank() ) p = p + coord_polar() plot(p) </code></pre>
13,888,860
2
0
null
2012-12-14 22:51:21.347 UTC
20
2021-04-27 21:52:05.527 UTC
2018-12-21 13:23:57.493 UTC
null
4,076,315
null
1,905,004
null
1
33
r|ggplot2|heatmap|donut-chart
8,172
<p>Here is a solution accomplished by (1) converting factor to numeric and adding an offset, (2) manually specifying y-limits and (3) manually setting y-axis breaks and labels:</p> <pre><code>library(reshape) library(ggplot2) # Using ggplot2 0.9.2.1 nba &lt;- read.csv("http://datasets.flowingdata.com/ppg2008.csv") nba$Name &lt;- with(nba, reorder(Name, PTS)) nba.m &lt;- melt(nba) nba.m &lt;- ddply(nba.m, .(variable), transform, value = scale(value)) # Convert the factor levels to numeric + quanity to determine size of hole. nba.m$var2 = as.numeric(nba.m$variable) + 15 # Labels and breaks need to be added with scale_y_discrete. y_labels = levels(nba.m$variable) y_breaks = seq_along(y_labels) + 15 p2 = ggplot(nba.m, aes(x=Name, y=var2, fill=value)) + geom_tile(colour="white") + scale_fill_gradient(low = "white", high = "steelblue") + ylim(c(0, max(nba.m$var2) + 0.5)) + scale_y_discrete(breaks=y_breaks, labels=y_labels) + coord_polar(theta="x") + theme(panel.background=element_blank(), axis.title=element_blank(), panel.grid=element_blank(), axis.text.x=element_blank(), axis.ticks=element_blank(), axis.text.y=element_text(size=5)) ggsave(filename="plot_2.png", plot=p2, height=7, width=7) </code></pre> <p><img src="https://i.stack.imgur.com/49FHZ.png" alt="enter image description here"></p>
43,040,685
How can I change php-cli version on Ubuntu 14.04?
<p>I am new to using Linux and I broke some php settings while tampering. </p> <p>If I execute a php script containing: <code>phpinfo();</code> it shows the php versions as 5.6, but via the command line, if I run <code>php -v</code> it returns a version of 7.0.</p> <p>I want to have both versions match.<br> How can i fix my command line PATH to also use php 5.6?</p>
43,168,301
7
2
null
2017-03-27 07:49:32.743 UTC
30
2020-04-27 16:16:11 UTC
2017-03-29 17:41:39.72 UTC
null
1,590,950
null
6,197,481
null
1
99
php|linux|ubuntu
90,177
<pre><code>sudo update-alternatives --set php /usr/bin/php5.6 </code></pre> <p>Please see: <a href="https://tecadmin.net/switch-between-multiple-php-version-on-ubuntu/" rel="noreferrer">Source</a></p>
44,463,987
Homestead installation
<p>I could not figure out where I made a mistake here. My command <code>vagrant up</code> replies with the following lines</p> <pre><code>$ vagrant up Check your Homestead.yaml file, the path to your private key does not exist. Check your Homestead.yaml file, the path to your private key does not exist. </code></pre> <p><a href="https://i.stack.imgur.com/AlJuQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AlJuQ.png" alt="enter image description here"></a></p>
44,466,436
4
5
null
2017-06-09 17:50:44.467 UTC
37
2021-01-31 17:31:22.497 UTC
2017-06-09 18:30:46.027 UTC
null
345,812
null
3,775,790
null
1
110
laravel|homestead
83,484
<p>You want to follow these steps from terminal</p> <p>Generate a ssh key <code>ssh-keygen -t rsa -b 4096 -C "your_email@example.com"</code></p> <p>Start ssh agent <code>eval "$(ssh-agent -s)"</code></p> <p>Add your SSH private key to the ssh-agent <code>ssh-add -k ~/.ssh/id_rsa</code></p> <p>Then run <code>vagrant up</code></p>
19,739,371
Dismiss Ongoing Android Notification Via Action Button Without Opening App
<p>I have an app that has an ongoing notification to help with memorization. I want to be able to dismiss this notification with one of the action button, but I don't want to open the app when the button is hit. I would prefer to use the built-in notification action buttons and not create a RemoteViews object to populate the notification. I saw one post mention using a BroadcastReceiver on this button which is received in my app, and though his tutorial was quite unhelpful, it sounds like this is headed in the right direction.</p> <pre><code>Intent resultIntent = new Intent(getBaseContext(), Dashboard.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(getBaseContext()); stackBuilder.addParentStack(Dashboard.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); Intent cancel = new Intent(getBaseContext(), CancelNotification.class); stackBuilder.addParentStack(Dashboard.class); stackBuilder.addNextIntent(cancel); PendingIntent pendingCancel = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext()); mb.setSmallIcon(R.drawable.cross_icon); mb.setContentTitle(ref); mb.setContentText(ver); mb.setPriority(NotificationCompat.PRIORITY_LOW); mb.setOngoing(true); mb.setStyle(new NotificationCompat.BigTextStyle().bigText(ver)); mb.setContentIntent(resultPendingIntent); mb.addAction(R.drawable.ic_cancel_dark, "Dismiss", pendingCancel); manager.notify(1, mb.build()); </code></pre>
19,745,745
3
2
null
2013-11-02 05:54:38.263 UTC
10
2022-06-25 18:16:50.827 UTC
null
null
null
null
2,469,169
null
1
23
android|notifications|broadcastreceiver
31,440
<p>Start with this:</p> <pre><code>int final NOTIFICATION_ID = 1; //Create an Intent for the BroadcastReceiver Intent buttonIntent = new Intent(context, ButtonReceiver.class); buttonIntent.putExtra("notificationId",NOTIFICATION_ID); //Create the PendingIntent PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, buttonIntent,0); //Pass this PendingIntent to addAction method of Intent Builder NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext()); ..... ..... ..... mb.addAction(R.drawable.ic_Action, "My Action", btPendingIntent); manager.notify(NOTIFICATION_ID, mb.build()); </code></pre> <p>Create the BroadcastReceiver:</p> <pre><code>public class ButtonReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int notificationId = intent.getIntExtra("notificationId", 0); // Do what you want were. .............. .............. // if you want cancel notification NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(notificationId); } } </code></pre> <p>If you don´t want show any activity when user click on notification, define the intent passed in <code>setContentIntent</code> in this way: </p> <pre><code>PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, new Intent(), 0); ...... ...... mb.setContentIntent(resultPendingIntent); </code></pre> <p>To close notification tray when clicked, call <code>setAutoCancel()</code> with true when building the notification: <code>mb.setAutoCancel(true);</code> </p>
56,227,419
Why does Python's hash of infinity have the digits of π?
<p>The hash of infinity in Python has digits matching <a href="https://en.wikipedia.org/wiki/Pi" rel="noreferrer">pi</a>:</p> <pre><code>&gt;&gt;&gt; inf = float('inf') &gt;&gt;&gt; hash(inf) 314159 &gt;&gt;&gt; int(math.pi*1e5) 314159 </code></pre> <p>Is that just a coincidence or is it intentional?</p>
56,227,651
3
6
null
2019-05-20 20:00:20.537 UTC
22
2021-03-15 22:45:56.6 UTC
2019-05-24 01:24:26.663 UTC
null
8,454
null
674,039
null
1
243
python|math|hash|floating-point|pi
29,093
<p><code>_PyHASH_INF</code> is <a href="https://github.com/python/cpython/blob/35d5068928ab5485e5f28b60b1e33062bc2c46cc/Include/pyhash.h#L31" rel="nofollow noreferrer">defined as a constant</a> equal to <code>314159</code>.</p> <p>I can't find any discussion about this, or comments giving a reason. I think it was chosen more or less arbitrarily. I imagine that as long as they don't use the same meaningful value for other hashes, it shouldn't matter.</p>
34,984,552
What is the difference between quote and list?
<p>I know that you can use <code>'</code> (aka <code>quote</code>) to create a list, and I use this all the time, like this:</p> <pre><code>&gt; (car '(1 2 3)) 1 </code></pre> <p>But it doesn’t always work like I’d expect. For example, I tried to create a list of functions, like this, but it didn’t work:</p> <pre><code>&gt; (define math-fns '(+ - * /)) &gt; (map (lambda (fn) (fn 1)) math-fns) application: not a procedure; expected a procedure that can be applied to arguments given: '+ </code></pre> <p>When I use <code>list</code>, it works:</p> <pre><code>&gt; (define math-fns (list + - * /)) &gt; (map (lambda (fn) (fn 1)) math-fns) '(1 -1 1 1) </code></pre> <p>Why? I thought <code>'</code> was just a convenient shorthand, so why is the behavior different?</p>
34,984,553
2
3
null
2016-01-25 03:18:35.543 UTC
35
2021-03-23 04:18:12.873 UTC
2016-09-04 10:23:43.02 UTC
null
849,891
null
465,378
null
1
60
scheme|racket|evaluation|quote
15,836
<h1>TL;DR: They are different; use <code>list</code> when in doubt.</h1> <p>A rule of thumb: use <code>list</code> whenever you want the arguments to be evaluated; <code>quote</code> “distributes” over its arguments, so <code>'(+ 1 2)</code> is like <code>(list '+ '1 '2)</code>. You’ll end up with a symbol in your list, not a function.</p> <hr> <h1>An in-depth look at <code>list</code> and <code>quote</code></h1> <p>In Scheme and Racket, <code>quote</code> and <code>list</code> are <em>entirely different things</em>, but since both of them can be used to produce lists, confusion is common and understandable. There is an incredibly important difference between them: <code>list</code> is a plain old <strong>function</strong>, while <code>quote</code> (even without the special <code>'</code> syntax) is a <strong>special form</strong>. That is, <code>list</code> can be implemented in plain Scheme, but <code>quote</code> cannot be.</p> <h2>The <code>list</code> function</h2> <p>The <code>list</code> function is actually by far the simpler of the two, so let’s start there. It is a function that takes any number of arguments, and it collects the arguments into a list.</p> <pre><code>&gt; (list 1 2 3) (1 2 3) </code></pre> <p>This above example can be confusing because the result is printed as a <code>quote</code>able s-expression, and it’s true, in this case, the two syntaxes are equivalent. But if we get slightly more complicated, you’ll see that it is different:</p> <pre><code>&gt; (list 1 (+ 1 1) (+ 1 1 1)) (1 2 3) &gt; '(1 (+ 1 1) (+ 1 1 1)) (1 (+ 1 1) (+ 1 1 1)) </code></pre> <p>What’s going on in the <code>quote</code> example? Well, we’ll discuss that in a moment, but first, take a look at <code>list</code>. It’s just an ordinary function, so it follows standard Scheme evaluation semantics: it evaluates each of its arguments <em>before</em> they get passed to the function. This means that expressions like <code>(+ 1 1)</code> will be reduced to <code>2</code> before they get collected into the list.</p> <p>This behavior is also visible when supplying variables to the list function:</p> <pre><code>&gt; (define x 42) &gt; (list x) (42) &gt; '(x) (x) </code></pre> <p>With <code>list</code>, the <code>x</code> gets evaluated before getting passed to <code>list</code>. With <code>quote</code>, things are more complicated.</p> <p>Finally, because <code>list</code> is just a function, it can be used just like any other function, including in higher-order ways. For example, it can be passed to the <code>map</code> function, and it will work appropriately:</p> <pre><code>&gt; (map list '(1 2 3) '(4 5 6)) ((1 4) (2 5) (3 6)) </code></pre> <h2>The <code>quote</code> form</h2> <p>Quotation, unlike <code>list</code>, is a special part of Lisps. The <code>quote</code> form is special in part because it gets a special reader abbreviation, <code>'</code>, but it’s <em>also</em> special even without that. Unlike <code>list</code>, <code>quote</code> is <em>not</em> a function, and therefore it does not need to behave like one—it has rules of its own.</p> <h3>A brief discussion of Lisp source code</h3> <p>In Lisp, of which Scheme and Racket are derivatives, all code is actually made up of ordinary data structures. For example, consider the following expression:</p> <pre><code>(+ 1 2) </code></pre> <p>That expression is actually <em>a list</em>, and it has three elements:</p> <ul> <li>the <code>+</code> symbol</li> <li>the number <code>1</code></li> <li>the number <code>2</code></li> </ul> <p>All of these values are normal values that can be created by the programmer. It’s really easy to create the <code>1</code> value because it evaluates to itself: you just type <code>1</code>. But symbols and lists are harder: by default, a symbol in the source code does a variable lookup! That is, symbols are not <em>self-evaluating</em>:</p> <pre><code>&gt; 1 1 &gt; a a: undefined cannot reference undefined identifier </code></pre> <p>As it turns out, though, symbols are basically just strings, and in fact we can convert between them:</p> <pre><code>&gt; (string-&gt;symbol "a") a </code></pre> <p>Lists do even more than symbols, because by default, a list in the source code <em>calls a function!</em> Doing <code>(+ 1 2)</code> looks at the first element in the list, the <code>+</code> symbol, looks up the function associated with it, and invokes it with the rest of the elements in the list.</p> <p>Sometimes, though, you might want to disable this “special” behavior. You might want to just get the list or get the symbol without it being evaluated. To do this, you can use <code>quote</code>.</p> <h3>The meaning of quotation</h3> <p>With all this in mind, it’s pretty obvious what <code>quote</code> does: it just “turns off” the special evaluation behavior for the expression that it wraps. For example, consider <code>quote</code>ing a symbol:</p> <pre><code>&gt; (quote a) a </code></pre> <p>Similarly, consider <code>quote</code>ing a list:</p> <pre><code>&gt; (quote (a b c)) (a b c) </code></pre> <p>No matter what you give <code>quote</code>, it will always, <strong><em>always</em></strong> spit it back out at you. No more, no less. That means if you give it a list, none of the subexpressions will be evaluated—do not expect them to be! If you need evaluation of any kind, use <code>list</code>.</p> <p>Now, one might ask: what happens if you <code>quote</code> something other than a symbol or a list? Well, the answer is... nothing! You just get it back.</p> <pre><code>&gt; (quote 1) 1 &gt; (quote "abcd") "abcd" </code></pre> <p>This makes sense, since <code>quote</code> still just spits out exactly what you give it. This is why “literals” like numbers and strings are sometimes called “self-quoting” in Lisp parlance.</p> <p>One more thing: what happens if you <code>quote</code> an expression containing <code>quote</code>? That is, what if you “double <code>quote</code>”?</p> <pre><code>&gt; (quote (quote 3)) '3 </code></pre> <p>What happened there? Well, remember that <code>'</code> is actually just a direct abbreviation for <code>quote</code>, so nothing special happened at all! In fact, if your Scheme has a way to disable the abbreviations when printing, it will look like this:</p> <pre><code>&gt; (quote (quote 3)) (quote 3) </code></pre> <p>Don’t be fooled by <code>quote</code> being special: just like <code>(quote (+ 1))</code>, the result here is just a plain old list. In fact, we can get the first element out of the list: can you guess what it will be?</p> <pre><code>&gt; (car (quote (quote 3))) quote </code></pre> <p>If you guessed <code>3</code>, you are wrong. Remember, <code>quote</code> disables <em>all evaluation</em>, and an expression containing a <code>quote</code> symbol is still just a plain list. Play with this in the REPL until you are comfortable with it.</p> <pre><code>&gt; (quote (quote (quote 3))) ''3 (quote (1 2 (quote 3))) (1 2 '3) </code></pre> <p>Quotation is incredibly simple, but it can come off as very complex because of how it tends to defy our understanding of the traditional evaluation model. In fact, it is confusing <em>because</em> of how simple it is: there are no special cases, there are no rules. It just returns exactly what you give it, precisely as stated (hence the name “quotation”).</p> <hr> <h1>Appendix A: Quasiquotation</h1> <p>So if quotation completely disables evaluation, what is it good for? Well, aside from making lists of strings, symbols, or numbers that are all known ahead of time, not much. Fortunately, the concept of <em>quasiquotation</em> provides a way to break out of the quotation and go back into ordinary evaluation.</p> <p>The basics are super simple: instead of using <code>quote</code>, use <code>quasiquote</code>. Normally, this works exactly like <code>quote</code> in every way:</p> <pre><code>&gt; (quasiquote 3) 3 &gt; (quasiquote x) x &gt; (quasiquote ((a b) (c d))) ((a b) (c d)) </code></pre> <p>What makes <code>quasiquote</code> special is that is recognizes a special symbol, <code>unquote</code>. Wherever <code>unquote</code> appears in the list, then it is replaced by the arbitrary expression it contains:</p> <pre><code>&gt; (quasiquote (1 2 (+ 1 2))) (1 2 (+ 1 2)) &gt; (quasiquote (1 2 (unquote (+ 1 2)))) (1 2 3) </code></pre> <p>This lets you use <code>quasiquote</code> to construct templates of sorts that have “holes” to be filled in with <code>unquote</code>. This means it’s possible to actually include the values of variables inside of quoted lists:</p> <pre><code>&gt; (define x 42) &gt; (quasiquote (x is: (unquote x))) (x is: 42) </code></pre> <p>Of course, using <code>quasiquote</code> and <code>unquote</code> is rather verbose, so they have abbreviations of their own, just like <code>'</code>. Specifically, <code>quasiquote</code> is <code>`</code> (backtick) and <code>unquote</code> is <code>,</code> (comma). With those abbreviations, the above example is much more palatable.</p> <pre><code>&gt; `(x is: ,x) (x is: 42) </code></pre> <p>One final point: quasiquote actually <em>can</em> be implemented in Racket using a rather hairy macro, and it is. It expands to usages of <code>list</code>, <code>cons</code>, and of course, <code>quote</code>.</p> <hr> <h1>Appendix B: Implementing <code>list</code> and <code>quote</code> in Scheme</h1> <p>Implementing <code>list</code> is super simple because of how “rest argument” syntax works. This is all you need:</p> <pre><code>(define (list . args) args) </code></pre> <p>That’s it!</p> <p>In contrast, <code>quote</code> is a lot harder—in fact, it’s impossible! It would seem totally feasible, since the idea of disabling evaluation sounds a lot like macros. Yet a naïve attempt reveals the trouble:</p> <pre><code>(define fake-quote (syntax-rules () ((_ arg) arg))) </code></pre> <p>We just take <code>arg</code> and spit it back out... but this doesn’t work. Why not? Well, the result of our macro will be evaluated, so all is for naught. We might be able to expand to something sort of like <code>quote</code> by expanding to <code>(list ...)</code> and recursively quoting the elements, like this:</p> <pre><code>(define impostor-quote (syntax-rules () ((_ (a . b)) (cons (impostor-quote a) (impostor-quote b))) ((_ (e ...)) (list (impostor-quote e) ...)) ((_ x) x))) </code></pre> <p>Unfortunately, though, without procedural macros, we can’t handle symbols without <code>quote</code>. We could get closer using <code>syntax-case</code>, but even then, we would only be emulating <code>quote</code>’s behavior, not replicating it.</p> <hr> <h1>Appendix C: Racket printing conventions</h1> <p>When trying the examples in this answer in Racket, you may find that they do not print as one would expect. Often, they may print with a leading <code>'</code>, such as in this example:</p> <pre><code>&gt; (list 1 2 3) '(1 2 3) </code></pre> <p>This is because Racket, by default, prints results as expressions when possible. That is, you should be able to type the result into the REPL and get the same value back. I personally find this behavior nice, but it can be confusing when trying to understand quotation, so if you want to turn it off, call <code>(print-as-expression #f)</code>, or change the printing style to “write” in the DrRacket language menu.</p>
429,478
Do I need to dispose a web service reference in ASP.NET?
<p>Does the garbage collector clean up web service references or do I need to call dispose on the service reference after I'm finished calling whatever method I call?</p>
429,499
5
0
null
2009-01-09 19:58:14.1 UTC
10
2021-07-03 04:22:40.84 UTC
null
null
null
BeaverProj
32,908
null
1
10
c#|asp.net|web-services|dispose
16,014
<p>Instead of worrying about disposing your web services, you could keep only a single instance of each web service, using a <a href="http://csharpindepth.com/Articles/General/Singleton.aspx" rel="nofollow noreferrer">singleton pattern</a>. Web services are stateless, so they can safely be shared between connections and threads on a web server.</p> <p>Here is an example of a Web Service class you can use to hold references to your web service instances. This singleton is lazy and thread-safe. It is advised that if you make your singletons lazy, they are also kept thread safe by following the same logic. To learn more about how to do this, read the C# In Depth article on <a href="http://csharpindepth.com/Articles/General/Singleton.aspx" rel="nofollow noreferrer">Implementing Singletons</a>.</p> <p>Also keep in mind that you may run into issues with WCF web services. I'd recommend reading up on <a href="http://msdn.microsoft.com/en-us/magazine/cc163590.aspx" rel="nofollow noreferrer">WCF's instance management techniques article</a>, specifically the singleton section, for more details.</p> <pre><code>public static class WS { private static object sync = new object(); private static MyWebService _MyWebServiceInstance; public static MyWebService MyWebServiceInstance { get { if (_MyWebServiceInstance == null) { lock (sync) { if (_MyWebServiceInstance == null) { _MyWebServiceInstance= new MyWebService(); } } } return _MyWebServiceInstance; } } } </code></pre> <p>And then when you need to access your web service, you can do this:</p> <pre><code>WS.MyWebServiceInstance.MyMethod(...) </code></pre> <p>or</p> <pre><code>var ws = WS.MyWebServiceInstance; ws.MyMethod(...) </code></pre> <p>I've successfully used this pattern on several projects and it has worked well, but as tvanfosson mentions in the comments below, an even better strategy would be to use a DI framework to manage your web service instances.</p>
1,320,621
Throw a NullReferenceException while calling the set_item method of a Dictionary object in a multi-threading scenario
<p>Our website has a configuration page such as "config.aspx", when the page initializing will load some information from a configuration file. To cache the loaded information we provided a factory class and we call a public method of the factory to get the configuration instance when the page loaded. But sometimes when the Application Pool is restarted, we found some error message in the Event Log such as below:</p> <pre> Message: Object reference not set to an instance of an object. Stack: at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value) at ObjectFactory.GetInstance(string key) at config.Page_Load(Object sender, EventArgs e) at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) </pre> <p>The factory class implements like below:</p> <pre> <code> public static class ObjectFactory { private static object _InternalSyncObject; private static Dictionary _Instances; private static object InternalSyncObject { get { if (_InternalSyncObject == null) { var @object = new object(); Interlocked.CompareExchange(ref _InternalSyncObject, @object, null); } return _InternalSyncObject; } } private static Dictionary Instances { get { if (_Instances == null) { lock (InternalSyncObject) { if (_Instances == null) { _Instances = new Dictionary(); } } } return _Instances; } } private static object LoadInstance(string key) { object obj = null; // some statements to load an specific instance from a configuration file. return obj; } public static object GetInstance(string key) { object instance; if (false == Instances.TryGetValue(key, out instance)) { instance = LoadInstance(key); Instances[key] = instance; } return instance; } } </code> </pre> <p>I guess the exception was thrown by the line "Instances[key] = instance;", because its the only code that could call <code>set_Item</code> method of a dictionary. But if the "Instances" value is null, it will thrown a <code>NullReferenceException</code> when calling the <code>TryGetValue</code> method and the top frame of the stacktrace should be the <code>GetInstance</code> not the <code>Insert</code>. Does anyone know how the dictionary could throw a <code>NullReferenceException</code> when call the <code>set_Item</code> method in multi-threading scenario?</p>
1,320,701
5
0
null
2009-08-24 05:32:47.663 UTC
4
2015-10-19 14:52:40.717 UTC
2015-10-19 14:52:40.717 UTC
null
70,345
null
161,849
null
1
53
c#|multithreading|dictionary|locking
18,593
<p>As the exception occurs internally in the <code>Dictionary</code> code, it means that you are accessing the same <code>Dictionary</code> instance from more than one thread at the same time.</p> <p>You need to synchronise the code in the <code>GetInstance</code> method so that only one thread at a time accesses the <code>Dictionary</code>.</p> <p>Edit:<br> Lock around the accesses separately, so that you aren't inside a lock while doing the (supposedly) time consuming loading:</p> <pre><code>private static object _sync = new object(); public static object GetInstance(string key) { object instance = null; bool found; lock (_sync) { found = Instances.TryGetValue(key, out instance); } if (!found) { instance = LoadInstance(key); lock (_sync) { object current; if (Instances.TryGetValue(key, out current)) { // some other thread already loaded the object, so we use that instead instance = current; } else { Instances[key] = instance; } } } return instance; } </code></pre>
354,224
Combining UNION ALL and ORDER BY in Firebird
<p>This is my first attempt at answering my own question, since someone may well run into this and so it might be of help. Using Firebird, I want to combine the results of two queries using UNION ALL, then sort the resulting output on a given column. Something like:</p> <pre><code>(select C1, C2, C3 from T1) union all (select C1, C2, C3 from T2) order by C3 </code></pre> <p>The parentheses came from valid syntax for other databases, and are needed to make sure the arguments to UNION ALL (an operation that's defined to work on tables - i.e. an <i>unordered</i> set of records) don't try to be ordered individually. However I couldn't get this syntax to work in Firebird - how can it be done?</p>
354,242
6
0
null
2008-12-09 21:00:58.94 UTC
3
2021-10-26 15:45:31.5 UTC
null
null
null
Chris
8,415
null
1
16
sql|database|database-design|firebird
46,304
<pre><code>SELECT C1, C2, C3 FROM ( select C1, C2, C3 from T1 union all select C1, C2, C3 from T2 ) order by C3 </code></pre>
373,126
How to design a database schema to support tagging with categories?
<p>I am trying to so something like <a href="https://stackoverflow.com/questions/48475/database-design-for-tagging">Database Design for Tagging</a>, except each of my tags are grouped into categories.</p> <p>For example, let's say I have a database about vehicles. Let's say we actually don't know very much about vehicles, so we can't specify the columns all vehicles will have. Therefore we shall "tag" vehicles with information.</p> <pre><code>1. manufacture: Mercedes model: SLK32 AMG convertible: hardtop 2. manufacture: Ford model: GT90 production phase: prototype 3. manufacture: Mazda model: MX-5 convertible: softtop </code></pre> <p>Now as you can see all cars are tagged with their manufacture and model, but the other categories don't all match. Note that a car can only have one of each category. IE. A car can only have one manufacturer.</p> <p>I want to design a database to support a search for all Mercedes, or to be able to list all manufactures.</p> <p>My current design is something like this:</p> <pre><code>vehicles int vid String vin vehicleTags int vid int tid tags int tid String tag int cid categories int cid String category </code></pre> <p>I have all the right primary and foreign keys in place, except I can't handle the case where each car can only have one manufacturer. Or can I?</p> <p>Can I add a foreign key constraint to the composite primary key in vehicleTags? IE. Could I add a constraint such that the composite primary key (vid, tid) can only be added to vehicleTags only if there isn't already a row in vehicleTags such that for the same vid, there isn't already a tid in the with the same cid?</p> <p>My guess is no. I think the solution to this problem is add a cid column to vehicleTags, and make the new composite primary key (vid, cid). It would look like:</p> <pre><code>vehicleTags int vid int cid int tid </code></pre> <p>This would prevent a car from having two manufacturers, but now I have duplicated the information that tid is in cid.</p> <p>What should my schema be?</p> <p>Tom noticed this problem in my database schema in my previous question, <a href="https://stackoverflow.com/questions/372399/how-do-you-do-many-to-many-table-outer-joins">How do you do many to many table outer joins?</a></p> <p><strong>EDIT</strong><br/> I know that in the example manufacture should really be a column in the vehicle table, but let's say you can't do that. The example is just an example.</p>
373,291
6
1
null
2008-12-16 23:18:40.737 UTC
30
2021-01-11 18:53:56.357 UTC
2017-05-23 12:16:25.973 UTC
Bill Karwin
-1
Pyrolistical
21,838
null
1
16
sql|schema|tags|foreign-keys|entity-attribute-value
13,102
<p>This is yet another variation on the <a href="http://en.wikipedia.org/wiki/Entity-attribute-value_model" rel="nofollow noreferrer">Entity-Attribute-Value</a> design.</p> <p>A more recognizable EAV table looks like the following:</p> <pre><code>CREATE TABLE vehicleEAV ( vid INTEGER, attr_name VARCHAR(20), attr_value VARCHAR(100), PRIMARY KEY (vid, attr_name), FOREIGN KEY (vid) REFERENCES vehicles (vid) ); </code></pre> <p>Some people force <code>attr_name</code> to reference a lookup table of predefined attribute names, to limit the chaos.</p> <p>What you've done is simply spread an EAV table over three tables, but without improving the order of your metadata:</p> <pre><code>CREATE TABLE vehicleTag ( vid INTEGER, cid INTEGER, tid INTEGER, PRIMARY KEY (vid, cid), FOREIGN KEY (vid) REFERENCES vehicles(vid), FOREIGN KEY (cid) REFERENCES categories(cid), FOREIGN KEY (tid) REFERENCES tags(tid) ); CREATE TABLE categories ( cid INTEGER PRIMARY KEY, category VARCHAR(20) -- "attr_name" ); CREATE TABLE tags ( tid INTEGER PRIMARY KEY, tag VARCHAR(100) -- "attr_value" ); </code></pre> <p>If you're going to use the EAV design, you only need the <code>vehicleTags</code> and <code>categories</code> tables. </p> <pre><code>CREATE TABLE vehicleTag ( vid INTEGER, cid INTEGER, -- reference to "attr_name" lookup table tag VARCHAR(100, -- "attr_value" PRIMARY KEY (vid, cid), FOREIGN KEY (vid) REFERENCES vehicles(vid), FOREIGN KEY (cid) REFERENCES categories(cid) ); </code></pre> <p>But keep in mind that you're <em>mixing data with metadata</em>. You lose the ability to apply certain constraints to your data model. </p> <ul> <li>How can you make one of the categories mandatory (a conventional column uses a <code>NOT NULL</code> constraint)? </li> <li>How can you use SQL data types to validate some of your tag values? You can't, because you're using a long string for every tag value. Is this string long enough for every tag you'll need in the future? You can't tell.</li> <li>How can you constrain some of your tags to a set of permitted values (a conventional table uses a foreign key to a lookup table)? This is your "softtop" vs. "soft top" example. But you can't make a constraint on the <code>tag</code> column because that constraint would apply to all other tag values for other categories. You'd effectively restrict engine size and paint color to "soft top" as well.</li> </ul> <p>SQL databases don't work well with this model. It's extremely difficult to get right, and querying it becomes very complex. If you do continue to use SQL, you will be better off modeling the tables conventionally, with one column per attribute. If you have need to have "subtypes" then define a subordinate table per subtype (<a href="http://www.martinfowler.com/eaaCatalog/classTableInheritance.html" rel="nofollow noreferrer">Class-Table Inheritance</a>), or else use <a href="http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html" rel="nofollow noreferrer">Single-Table Inheritance</a>. If you have an unlimited variation in the attributes per entity, then use <a href="http://www.martinfowler.com/eaaCatalog/serializedLOB.html" rel="nofollow noreferrer">Serialized LOB</a>. </p> <p>Another technology that is designed for these kinds of fluid, non-relational data models is a Semantic Database, storing data in <a href="http://en.wikipedia.org/wiki/Resource_Description_Framework" rel="nofollow noreferrer">RDF</a> and queried with <a href="http://en.wikipedia.org/wiki/SPARQL" rel="nofollow noreferrer">SPARQL</a>. One free solution is <a href="https://rdf4j.org" rel="nofollow noreferrer">RDF4J</a> (formerly Sesame).</p>
950,928
How to specify Windows credentials in WCF client configuration file
<p>I have a WCF service using BasicHttpBinding with Windows authentication. Most clients are domain accounts and connect to the service using their default credentials.</p> <p>Now I want to connect to the service from an ASP.NET client that is running under a local account. I want to connect to the WCF service using windows credentials (domain\user and password) that are available to the ASP.NET application.</p> <p>I know I can do this in code using ClientBase&lt;T>.ClientCredentials.</p> <p>Is there a way to specify the credentials (domain\user and password) in the client's web.config file so I don't have to change the code?</p> <p><strong>EDIT</strong></p> <p>If it can't be done in the configuration file, is there a way of using System.Net.ICredentials or System.Net.NetworkCredential as a credential for a WCF service?</p> <p>The .NET Framework provides these as a homogenous way to provide network credentials, but with WCF this seems to have been thrown out in favour of a new incompatible system based on the unrelated System.ServiceModel.Description.ClientCredentials class.</p> <p><strong>EDIT 2</strong></p> <p>Accepting Marc's answer to the original question - it seems there is no way to do this in the client configuration file :(</p> <p>I would see this as a deficiency in WCF - I don't accept that Microsoft should be deliberately discouraging us from putting credentials in the configuration file - after all they have to be stored somewhere, and the Framework includes facilities for encrypting the config file. I guess I could create a custom BehaviorExtensionElement for this, but it ought to be available out of the box.</p> <p>It's also a bit inconsistent: the system.net/mailSettings/smtp/network configuration element allows credentials to be specified, so why not WCF?</p> <p>Regarding the second question about using System.Net.NetworkCredential, it seems from <a href="http://devdump.wordpress.com/tag/wcf/" rel="noreferrer">this blog</a> that it is possible, at least when using Windows authentication, with the following code:</p> <pre><code>factory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(name, password, domain); </code></pre>
950,966
6
0
null
2009-06-04 14:23:39.73 UTC
6
2016-06-01 01:57:50.07 UTC
2012-03-01 18:41:41.147 UTC
null
13,087
null
13,087
null
1
25
wcf|credentials
65,938
<p>You can't specify your credentials in the config file, unfortunately - you have to do this in code (most likely because otherwise you might end up with credentials in your config file, in plain text - not a good thing....).</p>
468,993
Is there a way to enable the JavaScript Error/Debug Console for Safari within Android?
<p>I'm developing a JavaScript application that needs to run on the Google Android Phone OS. Is there a way to enable the JavaScript Error/Debug console within Safari on either the Android Emulator or an actual device? If so any instructions on how to do so would be appreciated.</p>
487,622
6
0
null
2009-01-22 12:52:33.457 UTC
16
2018-01-10 05:34:29.047 UTC
2009-01-27 05:56:26.313 UTC
Soviut
46,914
Kevin
2,723
null
1
43
javascript|android|safari
27,718
<p>A quick Google turns up this <a href="https://web.archive.org/web/20120413212614/http://www.nanaze.com/2009/01/debugging-javascript-on-android.html" rel="noreferrer">blog post</a> (posted after you asked your question), that should at least let you see any Javascript errors via the Android Debug Bridge using the command:</p> <pre><code>adb logcat WebCore:V *:S </code></pre> <p>Not quite the same as a full debug console though.</p>
17,733,509
$ is not defined - asp.net MVC 4
<p>With this code below, I get an error: <code>$ is not defined</code>. My question is: How it is possible? </p> <pre><code>... &lt;script type="text/javascript"&gt; $(document).ready(function () { $(function () { $('#cb').click(function () { if (this.checked) { $('div#div').slideDown(); } else { $('div#div').slideUp(); } }); }) }); &lt;/script&gt; @section Scripts { @Scripts.Render("~/bundles/jqueryval") } @Scripts.Render("~/Scripts/jquery-1.7.1.min.js") @Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js") </code></pre> <p>As we can see, it load properly all of scripts:</p> <pre><code>&lt;script src="/Scripts/jquery-1.7.1.min.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/jquery-ui-1.8.20.min.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/jquery-1.7.1.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/jquery.unobtrusive-ajax.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/jquery.validate.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/jquery.validate.unobtrusive.js"&gt;&lt;/script&gt; </code></pre> <p>How to resolve it?</p>
17,733,652
3
0
null
2013-07-18 20:42:41.197 UTC
3
2017-01-13 14:17:29.14 UTC
null
null
null
null
1,503,095
null
1
29
jquery|asp.net-mvc
62,313
<p>You've placed your script in the view body and not inside the <code>Scripts</code> section which is where it belongs and <strong>after</strong> referencing jQuery:</p> <pre><code>@section Scripts { @Scripts.Render("~/Scripts/jquery-1.7.1.min.js") @Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js") @Scripts.Render("~/bundles/jqueryval") &lt;script type="text/javascript"&gt; $(function () { $('#cb').click(function () { if (this.checked) { $('div#div').slideDown(); } else { $('div#div').slideUp(); } }); }); &lt;/script&gt; } </code></pre> <p>Also to avoid having referenced jQuery twice (as in your case) double check if you haven't included it already as a bundle in your <code>_Layout</code>.</p> <p>And one last remark: since by default scripts are included at the end of the DOM, just before the closing body tag, you don't need to be wrapping your script in a <code>$(document).ready</code> simply because by the time it executes the DOM will already be loaded. Your code is even worse because you had it twice. Bear in mind that <code>$(function() { ... });</code> is equivalent to <code>$(document).ready(function() { ... });</code> and in your case you've nested 2 of those things when you actually don't need any of them.</p> <p>So:</p> <pre><code>@section Scripts { @Scripts.Render("~/Scripts/jquery-1.7.1.min.js") @Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js") @Scripts.Render("~/bundles/jqueryval") &lt;script type="text/javascript"&gt; $('#cb').click(function () { if (this.checked) { $('div#div').slideDown(); } else { $('div#div').slideUp(); } }); &lt;/script&gt; } </code></pre>
46,990,995
On Android 8.1 API 27 notification does not display
<p>I get Toast on Android 8.1 API 27: </p> <blockquote> <p>Developer warning for package "my_package_name"<br> Failed to post notification on ...</p> </blockquote> <p>Logcat includes next strings:</p> <blockquote> <p>Notification: Use of stream types is deprecated for operations other than volume control </p> <p>W/Notification: See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case</p> <p>E/NotificationService: No Channel found for pkg=my_package_name</p> </blockquote> <p>The full information in the Toast and in Logcat can help in the localization this problem.</p>
46,991,229
4
3
null
2017-10-28 14:50:49.387 UTC
16
2018-12-29 08:35:35.107 UTC
2017-12-15 06:04:13.413 UTC
null
6,829,540
null
6,829,540
null
1
41
android|notifications|android-notifications|android-8.0-oreo
50,094
<p>If you get this error should be paid attention to 2 items and them order:</p> <ol> <li><code>NotificationChannel mChannel = new NotificationChannel(id, name, importance);</code></li> <li><code>builder = new NotificationCompat.Builder(context, id);</code></li> </ol> <p>Also NotificationManager notifManager and NotificationChannel mChannel are created only once.</p> <p>There are required setters for Notification:</p> <ul> <li>builder.setContentTitle() // required</li> <li>.setSmallIcon() // required</li> <li>.setContentText() // required</li> </ul> <p>See example: </p> <pre><code>private NotificationManager notifManager; public void createNotification(String aMessage, Context context) { final int NOTIFY_ID = 0; // ID of notification String id = context.getString(R.string.default_notification_channel_id); // default_channel_id String title = context.getString(R.string.default_notification_channel_title); // Default Channel Intent intent; PendingIntent pendingIntent; NotificationCompat.Builder builder; if (notifManager == null) { notifManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); } if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) { int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel mChannel = notifManager.getNotificationChannel(id); if (mChannel == null) { mChannel = new NotificationChannel(id, title, importance); mChannel.enableVibration(true); mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); notifManager.createNotificationChannel(mChannel); } builder = new NotificationCompat.Builder(context, id); intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); builder.setContentTitle(aMessage) // required .setSmallIcon(android.R.drawable.ic_popup_reminder) // required .setContentText(context.getString(R.string.app_name)) // required .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true) .setContentIntent(pendingIntent) .setTicker(aMessage) .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); } else { builder = new NotificationCompat.Builder(context, id); intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); builder.setContentTitle(aMessage) // required .setSmallIcon(android.R.drawable.ic_popup_reminder) // required .setContentText(context.getString(R.string.app_name)) // required .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true) .setContentIntent(pendingIntent) .setTicker(aMessage) .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}) .setPriority(Notification.PRIORITY_HIGH); } Notification notification = builder.build(); notifManager.notify(NOTIFY_ID, notification); } </code></pre>
46,914,025
Node exits without error and doesn't await promise (Event callback)
<p>I've got a really weird issue whereby awaiting a Promise that has passed its <code>resolve</code> to an event-emitter callback just exits the process without error. </p> <pre><code>const {EventEmitter} = require('events'); async function main() { console.log("entry"); let ev = new EventEmitter(); let task = new Promise(resolve=&gt;{ ev.once("next", function(){resolve()}); console.log("added listener"); }); await task; console.log("exit"); } main() .then(()=&gt;console.log("exit")) .catch(console.log); process.on("uncaughtException", (e)=&gt;console.log(e)); </code></pre> <p>I'm expecting the process to halt when I run this because clearly "next" is currently never emitted. but the output I get is: </p> <blockquote> <p>entry <br> added listener</p> </blockquote> <p>and then the nodejs process terminates gracefully. </p> <p>I thought it was something to do with the Garbage Collector, but <code>ev</code> and <code>task</code> are clearly still in scope on <code>main</code>. So I'm really at a loss as to why the process exits entirely without error. </p> <p>Obviously I <em>would</em> eventually emit the event, but I've simplified my code to the above to reproduce. I'm on <code>node v8.7.0</code>. Is there something wrong with my code or is this a node bug?</p>
46,916,601
3
5
null
2017-10-24 15:07:45.67 UTC
10
2021-05-11 20:35:46.863 UTC
2019-01-24 10:44:12.783 UTC
null
1,657,476
null
1,657,476
null
1
35
javascript|node.js|promise
8,684
<p>This question is basically: how does node decide whether to exit the event loop or go around again?</p> <p>Basically node keeps a reference count of scheduled async requests — <code>setTimeouts</code>, network requests, etc.. Each time one is scheduled, that count increases, and each time one is finished, the count decreases. If you arrive at the end of an event loop cycle and that reference count is zero node exits.</p> <p>Simply creating a promise or event emitter does <em>not</em> increase the reference count — creating these objects isn't actually an async operation. For example, this promise's state will always be pending but the process exits right away:</p> <pre><code>const p = new Promise( resolve =&gt; { if(false) resolve() }) p.then(console.log) </code></pre> <p>In the same vein this also exits after creating the emitter and registering a listener:</p> <pre><code>const ev = new EventEmitter() ev.on("event", (e) =&gt; console.log("event:", e)) </code></pre> <p>If you expect Node to wait on an event that is never scheduled, then you may be working under the idea that Node doesn't know whether there are future events possible, but it does because it keeps a count every time one is scheduled.</p> <p>So consider this small alteration:</p> <pre><code>const ev = new EventEmitter() ev.on("event", (e) =&gt; console.log("event:", e)) const timer = setTimeout(() =&gt; ev.emit("event", "fired!"), 1000) // ref count is not zero, event loop will go again. // after timer fires ref count goes back to zero and node exits </code></pre> <p>As a side note, you can remove the reference to the timer with: <code>timeout.unref()</code>. This, unlike the previous example, will exit immediately:</p> <pre><code>const ev = new EventEmitter() ev.on("event", (e) =&gt; console.log("event:", e)) const timer = setTimeout(() =&gt; ev.emit("event", "fired!"), 1000) timer.unref() </code></pre> <p>There's a good talk about the event loop by Bert Belder here that clears up a lot of misconceptions: <a href="https://www.youtube.com/watch?v=PNa9OMajw9w" rel="noreferrer">https://www.youtube.com/watch?v=PNa9OMajw9w</a></p>
1,846,077
Size of empty UDP and TCP packet?
<p>What is the size of an empty UDP datagram? And that of an empty TCP packet?</p> <p>I can only find info about the MTU, but I want to know what is the "base" size of these, in order to estimate bandwidth consumption for protocols on top of them.</p>
1,846,139
5
5
null
2009-12-04 10:21:01.857 UTC
14
2022-06-20 06:11:18.05 UTC
2018-06-04 20:04:23.397 UTC
null
212,378
null
134,763
null
1
34
tcp|udp|size
93,962
<p><strong>TCP:</strong></p> <p>Size of Ethernet frame - 24 Bytes<br> Size of IPv4 Header (without any options) - 20 bytes<br> Size of TCP Header (without any options) - 20 Bytes </p> <p>Total size of an Ethernet Frame carrying an IP Packet with an empty TCP Segment - 24 + 20 + 20 = 64 bytes</p> <p><strong>UDP:</strong></p> <p>Size of Ethernet frame - 24 Bytes<br> Size of IPv4 Header (without any options) - 20 bytes<br> Size of UDP header - 8 bytes </p> <p>Total size of an Ethernet Frame carrying an IP Packet with an empty UDP Datagram - 24 + 20 + 8 = 52 bytes</p>
1,645,230
Rails Migrations: Check Existence and Keep Going?
<p>I was doing this kind of thing in my migrations:</p> <pre><code>add_column :statuses, :hold_reason, :string rescue puts "column already added" </code></pre> <p>but it turns out that, <strong>while this works for SQLite, it does not work for PostgreSQL</strong>. It seems like if the add_column blows up, <strong>even if the Exception is caught,</strong> the transaction is dead and so the Migration can't do any additional work.</p> <p>Is there any <strong>non-DB sepecific</strong> ways to check if a column or table already exist? Failing that, is there any way to get my rescue block to really work?</p>
5,958,436
5
2
null
2009-10-29 17:12:12.537 UTC
14
2021-01-21 07:48:00.437 UTC
null
null
null
null
8,047
null
1
88
ruby-on-rails|migration
36,453
<p>As of Rails 3.0 and later, you can use <a href="http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/column_exists%3F" rel="noreferrer"><code>column_exists?</code></a> to check for the existance of a column.</p> <pre><code>unless column_exists? :statuses, :hold_reason add_column :statuses, :hold_reason, :string end </code></pre> <p>There's also a <a href="http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/table_exists%3F" rel="noreferrer"><code>table_exists?</code></a> function, which goes as far back as Rails 2.1.</p>
2,183,503
Substitute values in a string with placeholders in Scala
<p>I have just started using Scala and wish to better understand the functional approach to problem solving. I have pairs of strings the first has placeholders for parameter and it's pair has the values to substitute. e.g. "select col1 from tab1 where id > $1 and name like $2" "parameters: $1 = '250', $2 = 'some%'"</p> <p>There may be many more than 2 parameters.</p> <p>I can build the correct string by stepping through and using regex.findAllIn(line) on each line and then going through the iterators to construct the substitution but this seems fairly inelegant and procedurally driven.</p> <p>Could anyone point me towards a functional approach that will be neater and less error prone?</p>
2,185,067
6
1
null
2010-02-02 11:12:26.72 UTC
11
2022-08-11 10:41:36.43 UTC
null
null
null
null
264,264
null
1
17
scala|functional-programming
16,901
<p>Speaking strictly to the replacement problem, my preferred solution is one enabled by a feature that should probably be available in the upcoming Scala 2.8, which is the ability to replace regex patterns using a function. Using it, the problem can be reduced to this:</p> <pre><code>def replaceRegex(input: String, values: IndexedSeq[String]) = """\$(\d+)""".r.replaceAllMatchesIn(input, { case Regex.Groups(index) =&gt; values(index.toInt) }) </code></pre> <p>Which reduces the problem to what you actually intend to do: replace all <em>$N</em> patterns by the corresponding <em>Nth</em> value of a list.</p> <p>Or, if you can actually set the standards for your input string, you could do it like this:</p> <pre><code>"select col1 from tab1 where id &gt; %1$s and name like %2$s" format ("one", "two") </code></pre> <p>If that's all you want, you can stop here. If, however, you are interested in how to go about solving such problems in a functional way, absent clever library functions, please do continue reading.</p> <p>Thinking functionally about it means thinking of the function. You have a string, some values, and you want a string back. In a statically typed functional language, that means you want something like this:</p> <pre><code>(String, List[String]) =&gt; String </code></pre> <p>If one considers that those values may be used in any order, we may ask for a type better suited for that:</p> <pre><code>(String, IndexedSeq[String]) =&gt; String </code></pre> <p>That should be good enough for our function. Now, how do we break down the work? There are a few standard ways of doing it: recursion, comprehension, folding.</p> <p><strong>RECURSION</strong></p> <p>Let's start with recursion. Recursion means to divide the problem into a first step, and then repeating it over the remaining data. To me, the most obvious division here would be the following:</p> <ol> <li>Replace the first placeholder</li> <li>Repeat with the remaining placeholders</li> </ol> <p>That is actually pretty straight-forward to do, so let's get into further details. How do I replace the first placeholder? One thing that can't be avoided is that I need to know what that placeholder is, because I need to get the index into my values from it. So I need to find it:</p> <pre><code>(String, Pattern) =&gt; String </code></pre> <p>Once found, I can replace it on the string and repeat:</p> <pre><code>val stringPattern = "\\$(\\d+)" val regexPattern = stringPattern.r def replaceRecursive(input: String, values: IndexedSeq[String]): String = regexPattern findFirstIn input match { case regexPattern(index) =&gt; replaceRecursive(input replaceFirst (stringPattern, values(index.toInt))) case _ =&gt; input // no placeholder found, finished } </code></pre> <p>That is inefficient, because it repeatedly produces new strings, instead of just concatenating each part. Let's try to be more clever about it.</p> <p>To efficiently build a string through concatenation, we need to use <code>StringBuilder</code>. We also want to avoid creating new strings. <code>StringBuilder</code> can accepts <code>CharSequence</code>, which we can get from <code>String</code>. I'm not sure if a new string is actually created or not -- if it is, we could roll our own <code>CharSequence</code> in a way that acts as a view into <code>String</code>, instead of creating a new <code>String</code>. Assured that we can easily change this if required, I'll proceed on the assumption it is not.</p> <p>So, let's consider what functions we need. Naturally, we'll want a function that returns the index into the first placeholder:</p> <pre><code>String =&gt; Int </code></pre> <p>But we also want to skip any part of the string we have already looked at. That means we also want a starting index:</p> <pre><code>(String, Int) =&gt; Int </code></pre> <p>There's one small detail, though. What if there's on further placeholder? Then there wouldn't be any index to return. Java reuses the index to return that exception. When doing functional programming however, it is always best to return what you mean. And what we mean is that we <em>may</em> return an index, or we may not. The signature for that is this:</p> <pre><code>(String, Int) =&gt; Option[Int] </code></pre> <p>Let's build this function:</p> <pre><code>def indexOfPlaceholder(input: String, start: Int): Option[Int] = if (start &lt; input.lengt) { input indexOf ("$", start) match { case -1 =&gt; None case index =&gt; if (index + 1 &lt; input.length &amp;&amp; input(index + 1).isDigit) Some(index) else indexOfPlaceholder(input, index + 1) } } else { None } </code></pre> <p>That's rather complex, mostly to deal with boundary conditions, such as index being out of range, or false positives when looking for placeholders.</p> <p>To skip the placeholder, we'll also need to know it's length, signature <code>(String, Int) =&gt; Int</code>:</p> <pre><code>def placeholderLength(input: String, start: Int): Int = { def recurse(pos: Int): Int = if (pos &lt; input.length &amp;&amp; input(pos).isDigit) recurse(pos + 1) else pos recurse(start + 1) - start // start + 1 skips the "$" sign } </code></pre> <p>Next, we also want to know what, exactly, the index of the value the placeholder is standing for. The signature for this is a bit ambiguous:</p> <pre><code>(String, Int) =&gt; Int </code></pre> <p>The first <code>Int</code> is an index into the input, while the second is an index into the values. We could do something about that, but not that easily or efficiently, so let's ignore it. Here's an implementation for it:</p> <pre><code>def indexOfValue(input: String, start: Int): Int = { def recurse(pos: Int, acc: Int): Int = if (pos &lt; input.length &amp;&amp; input(pos).isDigit) recurse(pos + 1, acc * 10 + input(pos).asDigit) else acc recurse(start + 1, 0) // start + 1 skips "$" } </code></pre> <p>We could have used the length too, and achieve a simpler implementation:</p> <pre><code>def indexOfValue2(input: String, start: Int, length: Int): Int = if (length &gt; 0) { input(start + length - 1).asDigit + 10 * indexOfValue2(input, start, length - 1) } else { 0 } </code></pre> <p>As a note, using curly brackets around simple expressions, such as above, is frowned upon by conventional Scala style, but I use it here so it can be easily pasted on REPL.</p> <p>So, we can get the index to the next placeholder, its length, and the index of the value. That's pretty much everything needed for a more efficient version of <code>replaceRecursive</code>:</p> <pre><code>def replaceRecursive2(input: String, values: IndexedSeq[String]): String = { val sb = new StringBuilder(input.length) def recurse(start: Int): String = if (start &lt; input.length) { indexOfPlaceholder(input, start) match { case Some(placeholderIndex) =&gt; val placeholderLength = placeholderLength(input, placeholderIndex) sb.append(input subSequence (start, placeholderIndex)) sb.append(values(indexOfValue(input, placeholderIndex))) recurse(start + placeholderIndex + placeholderLength) case None =&gt; sb.toString } } else { sb.toString } recurse(0) } </code></pre> <p>Much more efficient, and as functional as one can be using <code>StringBuilder</code>.</p> <p><strong>COMPREHENSION</strong></p> <p>Scala Comprehensions, at their most basic level, means transforming <code>T[A]</code> into <code>T[B]</code> given a function <code>A =&gt; B</code>, something known as a functor. It can be easily understood when it comes to collections. For instance, I may transform a <code>List[String]</code> of names into a <code>List[Int]</code> of name lengths through a function <code>String =&gt; Int</code> which returns the length of a string. That's a list comprehension.</p> <p>There are other operations that can be done through comprehensions, given functions with signatures <code>A =&gt; T[B]</code>, which is related to monads, or <code>A =&gt; Boolean</code>.</p> <p>That means we need to see the input string as a <code>T[A]</code>. We can't use <code>Array[Char]</code> as input because we want to replace the whole placeholder, which is larger than a single char. Let's propose, therefore, this type signature:</p> <pre><code>(List[String], String =&gt; String) =&gt; String </code></pre> <p>Since we the input we receive is <code>String</code>, we need a function <code>String =&gt; List[String]</code> first, which will divide our input into placeholders and non-placeholders. I propose this:</p> <pre><code>val regexPattern2 = """((?:[^$]+|\$(?!\d))+)|(\$\d+)""".r def tokenize(input: String): List[String] = regexPattern2.findAllIn(input).toList </code></pre> <p>Another problem we have is that we got an <code>IndexedSeq[String]</code>, but we need a <code>String =&gt; String</code>. There are many ways around that, but let's settle with this:</p> <pre><code>def valuesMatcher(values: IndexedSeq[String]): String =&gt; String = (input: String) =&gt; values(input.substring(1).toInt - 1) </code></pre> <p>We also need a function <code>List[String] =&gt; String</code>, but <code>List</code>'s <code>mkString</code> does that already. So there's little left to do aside composing all this stuff:</p> <pre><code>def comprehension(input: List[String], matcher: String =&gt; String) = for (token &lt;- input) yield (token: @unchecked) match { case regexPattern2(_, placeholder: String) =&gt; matcher(placeholder) case regexPattern2(other: String, _) =&gt; other } </code></pre> <p>I use <code>@unchecked</code> because there <em>shouldn't</em> be any pattern other than these two above, if my regex pattern was built correctly. The compiler doesn't know that, however, so I use that annotation to silent the warning it would produce. If an exception is thrown, there's a bug in the regex pattern.</p> <p>The final function, then, unifies all that:</p> <pre><code>def replaceComprehension(input: String, values: IndexedSeq[String]) = comprehension(tokenize(input), valuesMatcher(values)).mkString </code></pre> <p>One problem with this solution is that I apply the regex pattern twice: once to break up the string, and the other to identify the placeholders. Another problem is that the <code>List</code> of tokens is an unnecessary intermediate result. We can solve that with these changes:</p> <pre><code>def tokenize2(input: String): Iterator[List[String]] = regexPattern2.findAllIn(input).matchData.map(_.subgroups) def comprehension2(input: Iterator[List[String]], matcher: String =&gt; String) = for (token &lt;- input) yield (token: @unchecked) match { case List(_, placeholder: String) =&gt; matcher(placeholder) case List(other: String, _) =&gt; other } def replaceComprehension2(input: String, values: IndexedSeq[String]) = comprehension2(tokenize2(input), valuesMatcher(values)).mkString </code></pre> <p><strong>FOLDING</strong></p> <p>Folding is a bit similar to both recursion and comprehension. With folding, we take a <code>T[A]</code> input that can be comprehended, a <code>B</code> "seed", and a function <code>(B, A) =&gt; B</code>. We comprehend the list using the function, always taking the <code>B</code> that resulted from the last element processed (the first element takes the seed). Finally, we return the result of the last comprehended element.</p> <p>I'll admit I could hardly explained it in a less-obscure way. That's what happens when you try to keep abstract. I explained it that way so that the type signatures involved become clear. But let's just see a trivial example of folding to understand its usage:</p> <pre><code>def factorial(n: Int) = { val input = 2 to n val seed = 1 val function = (b: Int, a: Int) =&gt; b * a input.foldLeft(seed)(function) } </code></pre> <p>Or, as a one-liner:</p> <pre><code>def factorial2(n: Int) = (2 to n).foldLeft(1)(_ * _) </code></pre> <p>Ok, so how would we go about solving the problem with folding? The result, of course, should be the string we want to produce. Therefore, the seed should be an empty string. Let's use the result from <code>tokenize2</code> as the comprehensible input, and do this:</p> <pre><code>def replaceFolding(input: String, values: IndexedSeq[String]) = { val seed = new StringBuilder(input.length) val matcher = valuesMatcher(values) val foldingFunction = (sb: StringBuilder, token: List[String]) =&gt; { token match { case List(_, placeholder: String) =&gt; sb.append(matcher(placeholder)) case List(other: String, _) =&gt; sb.append(other) } sb } tokenize2(input).foldLeft(seed)(foldingFunction).toString } </code></pre> <p>And, with that, I finish showing the most usual ways one would go about this in a functional manner. I have resorted to <code>StringBuilder</code> because concatenation of <code>String</code> is slow. If that wasn't the case, I could easily replace <code>StringBuilder</code> in functions above by <code>String</code>. I could also convert <code>Iterator</code> into a <code>Stream</code>, and completely do away with mutability.</p> <p>This is Scala, though and Scala is about balancing needs and means, not of purist solutions. Though, of course, you are free to go purist. :-)</p>
2,195,568
How do I add slashes to a string in Javascript?
<p>Just a string. Add \' to it every time there is a single quote.</p>
2,195,580
8
3
null
2010-02-03 21:24:31.7 UTC
6
2016-09-15 08:03:18.81 UTC
2016-09-15 08:03:18.81 UTC
null
1,045,444
null
179,736
null
1
41
javascript|jquery|formatting|string-formatting|backslash
141,049
<p><code>replace</code> works for the first quote, so you need a tiny regular expression:</p> <pre><code>str = str.replace(/'/g, "\\'"); </code></pre>
2,161,634
How to check if element has any children in Javascript?
<p>Simple question, I have an element which I am grabbing via <code>.getElementById ()</code>. How do I check if it has any children?</p>
2,161,646
8
0
null
2010-01-29 11:43:30.72 UTC
35
2021-02-09 16:11:17.767 UTC
2015-10-12 19:19:12.96 UTC
null
2,619,939
null
175,562
null
1
145
javascript|dom
220,379
<p>A couple of ways:</p> <pre><code>if (element.firstChild) { // It has at least one } </code></pre> <p>or the <code>hasChildNodes()</code> function:</p> <pre><code>if (element.hasChildNodes()) { // It has at least one } </code></pre> <p>or the <code>length</code> property of <code>childNodes</code>:</p> <pre><code>if (element.childNodes.length &gt; 0) { // Or just `if (element.childNodes.length)` // It has at least one } </code></pre> <p>If you only want to know about child <em>elements</em> (as opposed to text nodes, attribute nodes, etc.) on all modern browsers (and IE8 — in fact, even IE6) you can do this: <em>(thank you <a href="https://stackoverflow.com/users/851498/florian-margaine">Florian</a>!)</em></p> <pre><code>if (element.children.length &gt; 0) { // Or just `if (element.children.length)` // It has at least one element as a child } </code></pre> <p>That relies on the <a href="http://dom.spec.whatwg.org/#dom-element-children" rel="noreferrer"><code>children</code></a> property, which wasn't defined in <a href="http://www.w3.org/TR/REC-DOM-Level-1/" rel="noreferrer">DOM1</a>, <a href="http://www.w3.org/TR/DOM-Level-2-Core/" rel="noreferrer">DOM2</a>, <em>or</em> <a href="http://www.w3.org/TR/DOM-Level-3-Core/" rel="noreferrer">DOM3</a>, but which has near-universal support. (It works in IE6 and up and Chrome, Firefox, and Opera at <em>least</em> as far back as November 2012, when this was originally written.) If supporting older mobile devices, be sure to check for support.</p> <p>If you don't need IE8 and earlier support, you can also do this:</p> <pre><code>if (element.firstElementChild) { // It has at least one element as a child } </code></pre> <p>That relies on <a href="https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild" rel="noreferrer"><code>firstElementChild</code></a>. Like <code>children</code>, it wasn't defined in DOM1-3 either, but unlike <code>children</code> it wasn't added to IE until IE9. The same applies to <a href="https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/childElementCount" rel="noreferrer"><code>childElementCount</code></a>:</p> <pre><code>if (element.childElementCount !== 0) { // It has at least one element as a child } </code></pre> <p>If you want to stick to something defined in DOM1 (maybe you have to support really obscure browsers), you have to do more work:</p> <pre><code>var hasChildElements, child; hasChildElements = false; for (child = element.firstChild; child; child = child.nextSibling) { if (child.nodeType == 1) { // 1 == Element hasChildElements = true; break; } } </code></pre> <p>All of that is part of <a href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-1451460987" rel="noreferrer">DOM1</a>, and nearly universally supported.</p> <p>It would be easy to wrap this up in a function, e.g.:</p> <pre><code>function hasChildElement(elm) { var child, rv; if (elm.children) { // Supports `children` rv = elm.children.length !== 0; } else { // The hard way... rv = false; for (child = element.firstChild; !rv &amp;&amp; child; child = child.nextSibling) { if (child.nodeType == 1) { // 1 == Element rv = true; } } } return rv; } </code></pre>
1,470,768
How to escape apostrophe or quotes on a JSP (used by JavaScript)
<p>I have a user form. If the user types in a string with <code>'</code> or <code>"</code> as part of it I have no problem. The form is submitted and saved correctly to the database. My problem is when I reload the page (all entries can be modified and are loaded into a list in the JSP before being displayed). On loading the page I get an error saying:</p> <pre><code>missing ) after argument list 'Caroline's message', \n </code></pre> <p>What do I need to do to escape this string for displaying it on the frontend?</p> <p>Here is the code I am using on the frontend to read in the data and store it in a JavaScript object. I am not fully sure where I need to escape. The field causing the problem is c.getComName:</p> <pre><code>communications[&lt;%=i%&gt;][1] = new CommObject('&lt;%=c.getComId()%&gt;', '&lt;%=c.getComName()%&gt;'); </code></pre> <p><strong>UPDATED WITH HTML GENERATED:</strong></p> <pre><code>communications[0][1] = new CommObject('101', 'Caroline's Message'); </code></pre>
1,473,192
9
4
null
2009-09-24 10:01:52.923 UTC
13
2021-12-20 02:05:49.937 UTC
2015-05-04 16:35:50.147 UTC
null
63,550
null
174,292
null
1
36
java|javascript|forms|jsp|escaping
86,710
<p>Use the Apache <a href="https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#escapeJavaScript(java.lang.String)" rel="noreferrer">StringEscapeUtils.escapeJavaScript</a> function.</p> <blockquote> <pre><code>Escapes the characters in a String using JavaScript String rules. Escapes any values it finds into their JavaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) So a tab becomes the characters '\\' and 't'. </code></pre> </blockquote>
1,396,718
Generic Key/Value pair collection in that preserves insertion order?
<p>I'm looking for something like a Dictionary&lt;K,V&gt; however with a guarantee that it preserves insertion order. Since Dictionary is a hashtable, I do not think it does.</p> <p>Is there a generic collection for this, or do I need to use one of the old .NET 1.1 collections?</p>
1,396,743
9
0
null
2009-09-08 22:42:41.89 UTC
7
2018-11-21 00:25:23.29 UTC
null
null
null
null
1,965
null
1
44
c#|.net|data-structures
35,453
<p>There is not. However, <a href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx" rel="noreferrer">System.Collections.Specialized.OrderedDictionary</a> should solve most need for it.</p> <p>EDIT: Another option is to turn this into a Generic. I haven't tested it but it compiles (C# 6) and should work. However, it will still have the same limitations that Ondrej Petrzilka mentions in comments below.</p> <pre><code> public class OrderdDictionary&lt;T, K&gt; { public OrderedDictionary UnderlyingCollection { get; } = new OrderedDictionary(); public K this[T key] { get { return (K)UnderlyingCollection[key]; } set { UnderlyingCollection[key] = value; } } public K this[int index] { get { return (K)UnderlyingCollection[index]; } set { UnderlyingCollection[index] = value; } } public ICollection&lt;T&gt; Keys =&gt; UnderlyingCollection.Keys.OfType&lt;T&gt;().ToList(); public ICollection&lt;K&gt; Values =&gt; UnderlyingCollection.Values.OfType&lt;K&gt;().ToList(); public bool IsReadOnly =&gt; UnderlyingCollection.IsReadOnly; public int Count =&gt; UnderlyingCollection.Count; public IDictionaryEnumerator GetEnumerator() =&gt; UnderlyingCollection.GetEnumerator(); public void Insert(int index, T key, K value) =&gt; UnderlyingCollection.Insert(index, key, value); public void RemoveAt(int index) =&gt; UnderlyingCollection.RemoveAt(index); public bool Contains(T key) =&gt; UnderlyingCollection.Contains(key); public void Add(T key, K value) =&gt; UnderlyingCollection.Add(key, value); public void Clear() =&gt; UnderlyingCollection.Clear(); public void Remove(T key) =&gt; UnderlyingCollection.Remove(key); public void CopyTo(Array array, int index) =&gt; UnderlyingCollection.CopyTo(array, index); } </code></pre>
1,793,119
Could not find a base address that matches scheme net.tcp
<p>I have moved my file transfer service from basicHttpBinding to netTcpBinding as I am trying to set up a duplex mode channel. I have also started my net.tcp port sharing service.</p> <p>I am currently in dev and am self hosting on an xp box until we move the app to a dev server. so, for now, I do not have access to IIS. </p> <p>After configuring my service as such:</p> <pre><code>&lt;service behaviorConfiguration="transferServiceBehavior" name="API.FileTransfer.FileTransferService"&gt; &lt;endpoint name="MyFileTransferEP" address = "" binding = "netTcpBinding" bindingConfiguration="MyFileTransferNetTcpEP" behaviorConfiguration="NetTcpEPBehavior" contract="API.FileTransfer.IFileTransferService" /&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:8001/project/filetransfer.svc" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; </code></pre> <p>And, my binding as such:</p> <pre><code>&lt;netTcpBinding&gt; &lt;binding name="MyFileTransferNetTcpEP" hostNameComparisonMode="StrongWildcard" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" maxReceivedMessageSize="2147483647" transferMode="Streamed" portSharingEnabled="true"&gt; &lt;security mode="None"&gt; &lt;transport clientCredentialType="None" /&gt; &lt;message clientCredentialType="None" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/netTcpBinding&gt; </code></pre> <p>I get the folloing error when I right and browser to the SVC file: </p> <blockquote> <p>Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding. Registered base address schemes are [http].</p> </blockquote> <p>The reading online suggests that, in order to fix this problem, i needed to add the net.tcp binding to the binding of the application in IIS. But, what do I do if I am self hosting and do not have access to IIS?? By the way, if you are reading this and "do" have IIS, do the following: Right click the virtual directory/application in IIS -> Manage application -> Advanced settings. And, in the Enabled Protocols part, add net.tcp. </p> <p>Any ideas? </p> <hr> <p>UPDATE: I thought I had it working but it's still not working. Here is what I have now: I am still getting the "could not find base address that matches scheme net.tcp" error. I have changed all my base addresses to reflect your suggestion. Here is what I have now:</p> <pre><code>&lt;service behaviorConfiguration="transferServiceBehavior" name="API.FileTransfer.FileTransferService"&gt; &lt;endpoint name="MyJSONFileTransferEP" address="json" binding="webHttpBinding" bindingConfiguration="jsonWeb" behaviorConfiguration="WebHttpEPBehavior" contract="API.FileTransfer.IJSONFileTransferService" /&gt; &lt;endpoint name="MyPOXFileTransferEP" address="pox" behaviorConfiguration="WebHttpEPBehavior" binding="webHttpBinding" bindingConfiguration="poxWeb" contract="API.FileTransfer.IPOXFileTransferService" /&gt; &lt;endpoint name="MySOAPFileTransferEP" address="filetransfer" binding="netTcpBinding" bindingConfiguration="netTcpWeb" behaviorConfiguration="NetTcpEPBehavior" contract="API.FileTransfer.ISOAPFileTransferService" /&gt; &lt;endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:2544/filetransfer/" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; </code></pre> <p>I have tried this with both "net.tcp://localhost:2544" &amp; "net.tcp://localhost:8001". Do I need to add (allow) something in my firewall settings? Any other suggestions? </p> <p>Here is my filetransferservice's mexTcpBinding in my App.config file:</p> <pre><code>&lt;endpoint address="net.tcp://localhost:2544/filetransfer/mex" binding="mexTcpBinding" bindingConfiguration="" contract="IMetadataExchange" name="filetransfermex"&gt; &lt;identity&gt; &lt;certificateReference storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectDistinguishedName" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; </code></pre> <p>I am still unable to reference my FileTransferServiceClient in my web app. </p> <p>Thanks again. </p>
1,793,146
10
2
null
2009-11-24 21:43:32.05 UTC
6
2021-03-08 08:40:20.25 UTC
2009-11-25 11:46:54.527 UTC
null
150,510
null
150,510
null
1
34
c#|wcf|duplex|net.tcp
75,011
<p>You need to define just the <strong>base address</strong> (not the <strong>whole</strong> address) for your service, and then the rest in the service endpoint. The address you have with the <code>filetransfer.svc</code> file at the end is not a valid base address (it's a file address, really)</p> <pre><code>&lt;service behaviorConfiguration="transferServiceBehavior" name="API.FileTransfer.FileTransferService"&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:8001/project/" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;endpoint name="MyFileTransferEP" address = "filetransfer" binding = "netTcpBinding" bindingConfiguration="MyFileTransferNetTcpEP" behaviorConfiguration="NetTcpEPBehavior" contract="API.FileTransfer.IFileTransferService" /&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/&gt; &lt;/service&gt; </code></pre> <p>With this, and using self-hosting, your service would be available at the complete address:</p> <pre><code>net.tcp://localhost:8001/project/filetransfer </code></pre> <p>Since this is net.tcp and you're self-hosting, there's no need for a svc file at all.</p> <p><strong>UPDATE:</strong> if you want to be able to get metadata on your net.TCP base address, you'll need to expose a net.Tcp MEX endpoint like this inside your <code>&lt;service&gt;</code> section:</p> <pre><code> &lt;endpoint name="NetTcpMEX" address="netTcpMex" binding="mexTcpBinding" contract="IMetadataExchange" /&gt; </code></pre>
1,935,918
PHP substring extraction. Get the string before the first '/' or the whole string
<p>I am trying to extract a substring. I need some help with doing it in PHP.</p> <p>Here are some sample strings I am working with and the results I need: </p> <pre><code>home/cat1/subcat2 =&gt; home test/cat2 =&gt; test startpage =&gt; startpage </code></pre> <p>I want to get the string till the first <code>/</code>, but if no <code>/</code> is present, get the whole string.</p> <p>I tried,</p> <pre><code>substr($mystring, 0, strpos($mystring, '/')) </code></pre> <p>I think it says - get the position of <code>/</code> and then get the substring from position 0 to <em>that</em> position.</p> <p>I don't know how to handle the case where there is no <code>/</code>, without making the statement too big.</p> <p>Is there a way to handle that case also without making the PHP statement too complex?</p>
1,935,929
13
1
null
2009-12-20 14:07:02.017 UTC
38
2020-10-03 12:43:17.84 UTC
2010-09-02 08:21:05.047 UTC
anon355079
null
anon355079
null
null
1
207
php|string|substring
361,287
<p>Use <a href="http://php.net/explode"><code>explode()</code></a></p> <pre><code>$arr = explode("/", $string, 2); $first = $arr[0]; </code></pre> <p>In this case, I'm using the <code>limit</code> parameter to <code>explode</code> so that php won't scan the string any more than what's needed.</p>
1,594,917
What features should Java 7 onwards have to encourage switching from C#?
<p>C# has a good momentum at the moment. What are the features that you would <em>need</em> to have in order to switch (or return) to Java?</p> <p>It would also be quite useful if people posted workarounds for these for the current Java versions, e.g. Nullables being wrapped around custom classes, to make this a much more interesting wiki.</p>
1,595,050
24
8
null
2009-10-20 14:15:33.327 UTC
11
2010-09-10 21:32:26.947 UTC
null
null
null
null
182,094
null
1
24
c#|java|programming-languages|language-features
3,065
<p>As a .NET/C# developer here are the missing features that annoy me. This list in no particular order - just as thoughts come to mind:</p> <ol> <li>The Java library is too small. For common things I have to choose between 5 competing open source products because the base library is lacking in so many ways.</li> <li>This is an Object Oriented programming language right? Why in the heck do primitive types not inherit from "object"?</li> <li>Pointers</li> <li>Lambdas</li> <li>Closures</li> <li>Partial Classes and to a lesser extent partial Methods</li> <li>Real support for Generics</li> <li>Using statements and Dispose - this was a real WTF for me. You really have to explicitly close connections in try/catch blocks. Poor Java guys!</li> <li><a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0%28VS.80%29.aspx" rel="nofollow noreferrer">Yield return</a> would be nice</li> <li>Unsigned integers - again WTF? I have to use number types larger than I need for what purpose again?</li> <li>In Java you can return from final blocks of try/catch. A co-worker confused the hell out of me for hours by introducing a bug this way. This behavior should be prohibited as in C#.</li> </ol> <p>I rarely have to use Java and when I do, I have all sorts of WTF moments.</p> <p>Edit: I Removed for-each comment based on the fact it is no longer a missing Java feature since 1.5.</p>
33,687,496
Get fullUrl in laravel 5.1
<p>i have multiple bootstrap tabs where each one do different action from others tabs for exmaple </p> <p><code>app-url/users#creat-admin-users-tab</code> <code>app-url/users#creat-regular-users-tab</code> </p> <p><strong>Is there any way in Laravel to get full url including the #tab-name</strong></p> <p>Thanks for your time.</p>
33,902,542
3
2
null
2015-11-13 07:07:48.71 UTC
8
2016-10-24 15:43:17.833 UTC
2015-11-13 07:46:29.573 UTC
null
3,516,962
null
3,144,496
null
1
31
php|laravel|laravel-5|laravel-routing
45,819
<p>Check the following</p> <p><code>$_SERVER['HTTP_HOST'] =&gt; Host name from the current request.</code> </p> <p><code>$_SERVER['HTTP'] =&gt; Set to a non-empty value if the protocol is HTTP</code></p> <p><code>$_SERVER['HTTPS'] =&gt; Set to a non-empty value if the protocol is HTTPS</code></p> <p><code>$_SERVER["SERVER_PORT"] =&gt; Server port. Default is: 80</code></p> <p><code>$_SERVER['REQUEST_URI'] =&gt; The URI to access this page;</code></p>
18,090,672
Convert dictionary entries into variables
<p>Is there a Pythonic way to assign the values of a dictionary to its keys, in order to convert the dictionary entries into variables? I tried this out:</p> <pre><code>&gt;&gt;&gt; d = {'a':1, 'b':2} &gt;&gt;&gt; for key,val in d.items(): exec('exec(key)=val') exec(key)=val ^ SyntaxError: invalid syntax </code></pre> <p>I am certain that the key-value pairs are correct because they were previously defined as variables by me before. I then stored these variables in a dictionary (as key-value pairs) and would like to reuse them in a different function. I could just define them all over again in the new function, but because I may have a dictionary with about 20 entries, I thought there may be a more efficient way of doing this.</p>
18,647,701
7
6
null
2013-08-06 21:17:42.243 UTC
42
2021-11-29 05:49:39.157 UTC
2021-11-28 22:07:08.837 UTC
null
6,243,352
null
2,635,863
null
1
89
python|dictionary
98,674
<p>This was what I was looking for:</p> <pre><code>&gt;&gt;&gt; d = {'a':1, 'b':2} &gt;&gt;&gt; for key,val in d.items(): exec(key + '=val') </code></pre>
18,135,551
How to call python script on excel vba?
<p>Trying to call a python script on Vba and I am a newb. I tried converting the main script to an exe using py2exe and then calling it from VBA (shell) but the main script calls other scripts therefore it becomes complicated and I messed it up (my exe is not functional). Besides, the the main script is a large file and I do not want to revise it a lot.</p> <p>Bottomline, is there a way to call the main script from excel vba, without converting the script to an exe file.</p> <p>So far, I tried:</p> <pre><code>RetVal = Shell(&quot;C:\python27\python.exe &quot; &amp; &quot;import &quot; &amp; &quot;C:\\&quot; &amp; &quot;MainScriptFile&quot;) </code></pre> <p>It starts python.exe but does nothing else. Then I tried:</p> <pre><code>RetVal = Shell(&quot;C:\Windows\System32\cmd.exe &quot; &amp; &quot;python &quot; &amp; &quot;C:\\Python27\\hello.py&quot;) </code></pre> <p>It starts command prompt but does not even start python.</p> <p>P.S. I checked all the related questions in the forum, they do not solve my prob.</p>
18,135,876
11
2
null
2013-08-08 20:31:35.767 UTC
37
2022-06-23 13:51:55.68 UTC
2021-08-27 20:32:42.157 UTC
null
3,739,391
null
2,665,094
null
1
40
python|excel|vba|shell|py2exe
161,655
<p>Try this:</p> <pre><code>RetVal = Shell("&lt;full path to python.exe&gt; " &amp; "&lt;full path to your python script&gt;") </code></pre> <p>Or if the python script is in the same folder as the workbook, then you can try :</p> <pre><code>RetVal = Shell("&lt;full path to python.exe&gt; " &amp; ActiveWorkBook.Path &amp; "\&lt;python script name&gt;") </code></pre> <p>All details within <code>&lt;&gt;</code> are to be given. <code>&lt;&gt;</code> - indicates changeable fields</p> <p>I guess this should work. But then again, if your script is going to call other files which are in different folders, it can cause errors unless your script has properly handled it. Hope it helps.</p>
6,934,477
How can i get DataGridView row values and store in variables?
<p>How can i loop through a DataGridView's rows at a time (I have 2 columns) then store those 2 columns in a variable which I will be using as a parameter for an sql query?</p> <pre><code> foreach (DataGridViewRow Datarow in contentTable_grd.Rows) { contentValue1 = Datarow.Cells[0].Value.ToString(); contentValue2 = Datarow.Cells[1].Value.ToString(); SqlParameter param4 = new SqlParameter("@contentTableValue1", contentValue1); SqlParameter param5 = new SqlParameter("@contentTableValue2", contentValue2); } </code></pre> <p>I'm getting this error when using the above code -</p> <blockquote> <p>Object reference not set to an instance of an object.</p> </blockquote>
6,934,705
3
6
null
2011-08-03 23:20:38.527 UTC
1
2011-08-03 23:56:45.18 UTC
2011-08-03 23:47:48.03 UTC
null
52,249
null
541,408
null
1
7
c#|datagridview
53,516
<p>Found the problem I needed an if statement to prevent empty cells from going through</p> <pre><code> foreach (DataGridViewRow Datarow in contentTable_grd.Rows) { if (Datarow.Cells[0].Value != null &amp;&amp; Datarow.Cells[1].Value != null) { contentValue1 = Datarow.Cells[0].Value.ToString(); contentValue2 = Datarow.Cells[1].Value.ToString(); MessageBox.Show(contentValue1); MessageBox.Show(contentValue2); } } </code></pre>
6,671,232
Youtube api - stop video
<p>I need some help with Youtube API and embeded videos. I want to stop video when clicked on some element (div,link,td etc.). I am trying to get it work just for 1 video now, but the final function of this script should be to stop all videos loaded on current page. I have read thru the YT API documentation but Im really beginner in JS so its still quite hard to understand for me.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="swfobject.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="javascript:ytplayer.stopVideo()"&gt;Play&lt;/a&gt; &lt;br/&gt; &lt;iframe id="ytplayer" src="http://www.youtube.com/embed/8Ax-dAR3ABs?rel=0&amp;iv_load_policy=3&amp;showinfo=0&amp;enablejsapi=1&amp;version=3&amp;playerapiid=ytplayer" type="application/x-shockwave-flash" frameborder="0" allowscriptaccess="always"&gt;&lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>thanks in advance for any advices</p>
6,671,815
3
2
null
2011-07-12 21:15:05.54 UTC
1
2012-07-25 09:01:47.773 UTC
null
null
null
null
841,585
null
1
9
javascript|api|video|youtube
60,752
<p>You can't control it if you embed it with an iframe. You have to use object embedding, like this:</p> <pre><code>&lt;object id="ytplayer" style="height: 390px; width: 640px"&gt; &lt;param name="movie" value="http://www.youtube.com/v/8Ax-dAR3ABs?version=3&amp;enablejsapi=1"&gt; &lt;param name="allowScriptAccess" value="always"&gt; &lt;embed id="ytplayer" src="http://www.youtube.com/v/8Ax-dAR3ABs?version=3&amp;enablejsapi=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="390"&gt; &lt;/object&gt; </code></pre> <p>The rest of your code should generally work after that, although it may need to be updated to say:</p> <pre><code>&lt;a href="javascript:document.getElementById('ytplayer').stopVideo()"&gt;Play&lt;/a&gt; </code></pre> <p>Also, have you seen the demo site? <a href="http://code.google.com/apis/youtube/youtube_player_demo.html">http://code.google.com/apis/youtube/youtube_player_demo.html</a></p>
15,568,159
How to get FB User ID using Facebook Login Button in android application
<p>I'm developing an application in which I'm using <code>Facebook</code> log in button from SDK. I'm able to get <code>access_token</code> of the user but I want <code>userID</code> too. I have tried almost everything but was not successful. I have used facebook tutorial for achieving that. Here is the link: <a href="https://developers.facebook.com/docs/howtos/androidsdk/3.0/login-with-facebook/" rel="noreferrer">Facebook Login Button</a></p> <p>Please help me in getting <code>userID</code> from the same login button.</p> <p>Any kind of help will be appreciated.</p>
15,570,742
8
0
null
2013-03-22 10:32:09.92 UTC
5
2017-10-04 03:31:16.413 UTC
2013-07-01 04:36:16.31 UTC
null
964,741
null
1,321,290
null
1
11
android|facebook|facebook-android-sdk
41,818
<p>After successful login, you need to call following code. You can get the logged-in user details with id in response.</p> <pre><code>Session session = Session.getActiveSession(); Request request = Request.newGraphPathRequest(session, "me", null); com.facebook.Response response = Request.executeAndWait(request) </code></pre>