input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: How to edit .csproj file <p>When I am compiling my .csproj file using .NET Framework 4.0 MSBUILD.EXE file, I am getting an error: &quot;lable01&quot; not found in the current context of &quot;website01.csproj&quot;.</p> <p>Actually, I need to add every ASP.NET page with its code-behind file's reference. I've done it, it's working fine, but the above error is pending.</p> <p>I hope it means that I need to add form name &quot;LABLE01&quot; in that .csproj file, but I do not know the syntax. Anybody please do provide me with the syntax to add form name in .csproj file.</p>
<p>The <code>CSPROJ</code> file, saved in XML format, stores all the references for your project including your compilation options. There is also an SLN file, which stores information about projects that make up your solution.</p> <p>If you are using Visual Studio and you have the need to view or edit your <code>CSPROJ</code> file, while in Visual Studio, you can do so by following these simple steps:</p> <ol> <li>Right-click on your project in solution explorer and select Unload Project</li> <li>Right-click on the project (tagged as unavailable in solution explorer) and click &quot;Edit yourproj.csproj&quot;. This will open up your CSPROJ file for editing.</li> <li>After making the changes you want, save, and close the file. Right-click again on the node and choose Reload Project when done.</li> </ol>
{ "question_id": 5129090, "question_date": "2011-02-26T19:04:34.987Z", "question_score": 237, "tags": "c#|asp.net|.net|csproj", "answer_id": 5129214, "answer_date": "2011-02-26T19:29:40.943Z", "answer_score": 494 }
Please answer the following Stack Overflow question: Title: Allow docker container to connect to a local/host postgres database <p>I've recently been playing around with Docker and QGIS and have installed a container following the instructions in <a href="http://kartoza.com/qgis-desktop-in-docker/" rel="noreferrer">this tutorial</a>.</p> <p>Everything works great, although I am unable to connect to a localhost postgres database that contains all my GIS data. I figure this is because my postgres database is not configured to accept remote connections and have been editing the postgres conf files to allow remote connections using the instructions in <a href="http://blog.jsinh.in/how-to-enable-remote-access-to-postgresql-database-server/#.VZqPgnXInK5" rel="noreferrer">this article</a>.</p> <p>I'm still getting an error message when I try and connect to my database running QGIS in Docker: could not connect to server: <code>Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections to port 5433?</code> The postgres server is running, and I've edited my <strong>pg_hba.conf</strong> file to allow connections from a range of IP addresses (172.17.0.0/32). I had previously queried the IP address of the docker container using <code>docker ps</code> and although the IP address changes, it has so far always been in the range 172.17.0.x</p> <p>Any ideas why I can't connect to this database? Probably something very simple I imagine!</p> <p>I'm running Ubuntu 14.04; Postgres 9.3</p>
<h3>TL;DR</h3> <ol> <li>Use <code>172.17.0.0/16</code> as IP address range, not <code>172.17.0.0/32</code>.</li> <li>Don't use <code>localhost</code> to connect to the PostgreSQL database on your host, but the host's IP instead. To keep the container portable, start the container with the <code>--add-host=database:&lt;host-ip&gt;</code> flag and use <code>database</code> as hostname for connecting to PostgreSQL.</li> <li>Make sure PostgreSQL is configured to listen for connections on all IP addresses, not just on <code>localhost</code>. Look for the setting <code>listen_addresses</code> in PostgreSQL's configuration file, typically found in <code>/etc/postgresql/9.3/main/postgresql.conf</code> (credits to @DazmoNorton).</li> </ol> <h3>Long version</h3> <p><code>172.17.0.0/32</code> is not a <em>range</em> of IP addresses, but a single address (namly <code>172.17.0.0</code>). No Docker container will ever get that address assigned, because it's the network address of the Docker bridge (<code>docker0</code>) interface.</p> <p>When Docker starts, it will create a new bridge network interface, that you can easily see when calling <code>ip a</code>:</p> <pre><code>$ ip a ... 3: docker0: &lt;NO-CARRIER,BROADCAST,MULTICAST,UP&gt; mtu 1500 qdisc noqueue state DOWN link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff inet 172.17.42.1/16 scope global docker0 valid_lft forever preferred_lft forever </code></pre> <p>As you can see, in my case, the <code>docker0</code> interface has the IP address <code>172.17.42.1</code> with a netmask of <code>/16</code> (or <code>255.255.0.0</code>). This means that the network address is <code>172.17.0.0/16</code>.</p> <p>The IP address is randomly assigned, but without any additional configuration, it will always be in the <code>172.17.0.0/16</code> network. For each Docker container, a random address from that range will be assigned.</p> <p>This means, if you want to grant access from all possible containers to your database, use <code>172.17.0.0/16</code>.</p>
{ "question_id": 31249112, "question_date": "2015-07-06T14:57:41.920Z", "question_score": 237, "tags": "ubuntu|docker|postgresql-9.3|qgis", "answer_id": 31249288, "answer_date": "2015-07-06T15:05:49.863Z", "answer_score": 225 }
Please answer the following Stack Overflow question: Title: How to render a DateTime object in a Twig template <p>One of my fields in one of my entities is a "datetime" variable.</p> <p>How can I convert this field into a string to render in a browser?</p> <p>Here is a code snippet:</p> <pre><code>{% for game in games %} ... &lt;td&gt; {{game.gameTeamIdOne.teamName}} &lt;/td&gt; &lt;td&gt; {{game.gameTeamIdTwo.teamName}} &lt;/td&gt; &lt;td&gt; {{game.gameDate}}&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre> <p>Here is the variable in my entity class:</p> <pre><code>/** * @var date $gameDate * * @ORM\Column(name="GAME_DATE", type="datetime", nullable=true) */ private $gameDate; </code></pre> <p>And here is the error message I am getting:</p> <blockquote> <p>An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class DateTime could not be converted to string in ...\app\cache\dev\twig\9b\ad\58fd3bb1517632badf1fdc7fa4a8.php line 33") in "BeerBundle:Games:gameTable.html.twig" at line 10.</p> </blockquote>
<p>Although you can use the</p> <pre><code>{{ game.gameDate|date('Y-m-d') }} </code></pre> <p>approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the <code>\DateTime</code> class, and adding a <code>__toString()</code> method to it that checks the locale and acts accordingly.</p> <p><strong>Edit</strong>:</p> <p>As pointed out by @Nic in a comment, if you use the <a href="http://twig-extensions.readthedocs.io/en/latest/intl.html" rel="noreferrer">Intl extension of Twig</a>, you will have a <code>localizeddate</code> filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending <code>\DateTime</code>.</p>
{ "question_id": 8318914, "question_date": "2011-11-29T22:54:33.430Z", "question_score": 237, "tags": "php|symfony|datetime|twig", "answer_id": 10196625, "answer_date": "2012-04-17T18:09:51.190Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: Using current time in UTC as default value in PostgreSQL <p>I have a column of the <code>TIMESTAMP WITHOUT TIME ZONE</code> type and would like to have that default to the current time in UTC. Getting the current time in UTC is easy:</p> <pre><code>postgres=# select now() at time zone 'utc'; timezone ---------------------------- 2013-05-17 12:52:51.337466 (1 row) </code></pre> <p>As is using the current timestamp for a column:</p> <pre><code>postgres=# create temporary table test(id int, ts timestamp without time zone default current_timestamp); CREATE TABLE postgres=# insert into test values (1) returning ts; ts ---------------------------- 2013-05-17 14:54:33.072725 (1 row) </code></pre> <p>But that uses local time. Trying to force that to UTC results in a syntax error:</p> <pre><code>postgres=# create temporary table test(id int, ts timestamp without time zone default now() at time zone 'utc'); ERROR: syntax error at or near "at" LINE 1: ...int, ts timestamp without time zone default now() at time zo... </code></pre>
<p>A function is not even needed. Just put parentheses around the default expression:</p> <pre><code>create temporary table test( id int, ts timestamp without time zone default (now() at time zone 'utc') ); </code></pre>
{ "question_id": 16609724, "question_date": "2013-05-17T13:00:50.147Z", "question_score": 237, "tags": "postgresql|timezone|timestamp", "answer_id": 16610360, "answer_date": "2013-05-17T13:30:51.697Z", "answer_score": 394 }
Please answer the following Stack Overflow question: Title: Remove insignificant trailing zeros from a number? <p>Have I missed a standard API call that removes trailing insignificant zeros from a number?</p> <pre><code>var x = 1.234000; // to become 1.234 var y = 1.234001; // stays 1.234001 </code></pre> <p><code>Number.toFixed()</code> and <code>Number.toPrecision()</code> are not quite what I'm looking for.</p>
<p>If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.</p> <pre><code>var n = 1.245000 var noZeroes = n.toString() // "1.245" </code></pre>
{ "question_id": 3612744, "question_date": "2010-08-31T20:00:59.797Z", "question_score": 237, "tags": "javascript|regex|math|numbers", "answer_id": 3613112, "answer_date": "2010-08-31T20:47:55.337Z", "answer_score": 174 }
Please answer the following Stack Overflow question: Title: What is "android.R.layout.simple_list_item_1"? <p>I've started learning Android development and am following a todolist example from a book:</p> <pre><code>// Create the array list of to do items final ArrayList&lt;String&gt; todoItems = new ArrayList&lt;String&gt;(); // Create the array adapter to bind the array to the listView final ArrayAdapter&lt;String&gt; aa; aa = new ArrayAdapter&lt;String&gt;( this, android.R.layout.simple_list_item_1, todoItems ); myListView.setAdapter(aa); </code></pre> <p>I can't understand exactly this code especially this line:</p> <pre><code>android.R.layout.simple_list_item_1 </code></pre>
<p>Zakaria, that is a reference to an built-in XML layout document that is part of the Android OS, rather than one of your own XML layouts.</p> <p>Here is a further list of layouts that you can use: <a href="http://developer.android.com/reference/android/R.layout.html" rel="noreferrer">http://developer.android.com/reference/android/R.layout.html</a><br> (Updated link thanks @Estel: <a href="https://github.com/android/platform_frameworks_base/tree/master/core/res/res/layout" rel="noreferrer">https://github.com/android/platform_frameworks_base/tree/master/core/res/res/layout</a> )</p> <p>You can actually view the code for the layouts.</p>
{ "question_id": 3663745, "question_date": "2010-09-08T00:31:56.537Z", "question_score": 237, "tags": "android|layout|android-arrayadapter", "answer_id": 3663829, "answer_date": "2010-09-08T00:48:42.243Z", "answer_score": 268 }
Please answer the following Stack Overflow question: Title: What is a wrapper class? <p>What is a wrapper class?<br> How are such classes useful?</p>
<p>In general, a wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. These are useful by providing a level of abstraction from the implementation of the underlying class or component; for example, wrapper classes that wrap COM components can manage the process of invoking the COM component without bothering the calling code with it. They can also simplify the use of the underlying object by reducing the number interface points involved; frequently, this makes for more secure use of underlying components.</p>
{ "question_id": 889160, "question_date": "2009-05-20T17:16:15.920Z", "question_score": 237, "tags": "design-patterns|wrapper", "answer_id": 889178, "answer_date": "2009-05-20T17:19:59.283Z", "answer_score": 181 }
Please answer the following Stack Overflow question: Title: WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance <p>I'm working to set up Panda on an Amazon EC2 instance. I set up my account and tools last night and had no problem using SSH to interact with my own personal instance, but right now I'm not being allowed permission into Panda's EC2 instance. <a href="http://pandastream.com/docs/getting_started" rel="noreferrer">Getting Started with Panda</a></p> <p>I'm getting the following error:</p> <pre><code>@ WARNING: UNPROTECTED PRIVATE KEY FILE! @ Permissions 0644 for '~/.ec2/id_rsa-gsg-keypair' are too open. It is recommended that your private key files are NOT accessible by others. This private key will be ignored. </code></pre> <p>I've chmoded my keypair to 600 in order to get into my personal instance last night, and experimented at length setting the permissions to 0 and even generating new key strings, but nothing seems to be working.</p> <p>Any help at all would be a great help!</p> <hr> <p>Hm, it seems as though unless permissions are set to 777 on the directory, the ec2-run-instances script is unable to find my keyfiles. I'm new to SSH so I might be overlooking something.</p>
<blockquote> <p>I've chmoded my keypair to 600 in order to get into my personal instance last night,</p> </blockquote> <p>And this is the way it is supposed to be. </p> <p>From the <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html" rel="noreferrer">EC2 documentation</a> we have <em>"If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you."</em> The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.</p> <p>The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.</p> <p>Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.</p> <p>Any problems you are having are client side, so be sure to include local OS information with any follow up questions! </p>
{ "question_id": 201893, "question_date": "2008-10-14T16:31:01.350Z", "question_score": 237, "tags": "ssh|amazon-web-services|amazon-ec2|chmod", "answer_id": 217729, "answer_date": "2008-10-20T07:41:32.883Z", "answer_score": 243 }
Please answer the following Stack Overflow question: Title: Django - makemigrations - No changes detected <p>I was trying to create migrations within an existing app using the makemigrations command but it outputs "No changes detected".</p> <p>Usually I create new apps using the <code>startapp</code> command but did not use it for this app when I created it.</p> <p>After debugging, I found that it is not creating migration because the <code>migrations</code> package/folder is missing from an app. </p> <p>Would it be better if it creates the folder if it is not there or am I missing something?</p>
<p>To create initial migrations for an app, run <code>makemigrations</code> and specify the app name. The migrations folder will be created.</p> <pre><code>./manage.py makemigrations &lt;myapp&gt; </code></pre> <p>Your app must be included in <code>INSTALLED_APPS</code> first (inside settings.py).</p>
{ "question_id": 36153748, "question_date": "2016-03-22T11:55:06.517Z", "question_score": 237, "tags": "python|django|django-migrations", "answer_id": 36154224, "answer_date": "2016-03-22T12:19:31.680Z", "answer_score": 463 }
Please answer the following Stack Overflow question: Title: How to know if docker is already logged in to a docker registry server <p>I'm not sure if I have already logged in to a docker registry in cmd line by using cmd: docker login. How can you test or see whether you are logged in or not, without trying to push?</p>
<p><strong>Edit 2020</strong></p> <p>Referring back to the (<em>closed</em>) <a href="https://github.com/moby/moby/issues/15466" rel="noreferrer">github</a> issue, where it is pointed out, there is no actual session or state; </p> <blockquote> <p>docker login actually isn't creating any sort of persistent session, it is only storing the user's credentials on disk so that when authentication is required it can read them to login</p> </blockquote> <p>As others have pointed out, an <code>auths</code> entry/node is added to the <code>~/.docker/config.json</code> file (this also works for <em>private</em> registries) after you succesfully login:</p> <pre><code>{ "auths": { "https://index.docker.io/v1/": {} }, ... </code></pre> <p>When logging out, this entry is then removed:</p> <pre><code>$ docker logout Removing login credentials for https://index.docker.io/v1/ </code></pre> <p>Content of docker <code>config.json</code> after:</p> <pre><code>{ "auths": {}, ... </code></pre> <p>This file can be parsed by your script or code to check your login status. </p> <h3>Alternative method (re-login)</h3> <p>You can login to docker with <code>docker login &lt;repository&gt;</code></p> <pre><code>$ docker login Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one. Username: </code></pre> <p>If you are already logged in, the prompt will look like:</p> <pre><code>$ docker login Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one. Username (myusername): # &lt;-- "myusername" </code></pre> <p>For the original explanation for the <code>~/.docker/config.json</code>, check <a href="https://stackoverflow.com/questions/36608467/how-can-i-tell-if-im-logged-in-to-a-private-docker-registry?noredirect=1#comment60864096_36608467">question: how can I tell if I'm logged into a private docker registry</a></p>
{ "question_id": 36022892, "question_date": "2016-03-15T21:50:07.423Z", "question_score": 237, "tags": "docker", "answer_id": 36023944, "answer_date": "2016-03-15T23:07:55.137Z", "answer_score": 153 }
Please answer the following Stack Overflow question: Title: Good Java graph algorithm library? <p>Has anyone had good experiences with any Java libraries for Graph algorithms. I've tried <a href="http://www.jgraph.com/jgraph.html" rel="noreferrer">JGraph</a> and found it ok, and there are a lot of different ones in google. Are there any that people are actually using successfully in production code or would recommend?</p> <p>To clarify, I'm not looking for a library that produces graphs/charts, I'm looking for one that helps with Graph algorithms, eg minimum spanning tree, Kruskal's algorithm Nodes, Edges, etc. Ideally one with some good algorithms/data structures in a nice Java OO API.</p>
<p>If you were using JGraph, you should give a try to <a href="http://jgrapht.org/" rel="noreferrer">JGraphT</a> which is designed for algorithms. One of its features is visualization using the JGraph library. It's still developed, but pretty stable. I analyzed the complexity of JGraphT algorithms some time ago. Some of them aren't the quickest, but if you're going to implement them on your own and need to display your graph, then it might be the best choice. I really liked using its API, when I quickly had to write an app that was working on graph and displaying it later.</p>
{ "question_id": 51574, "question_date": "2008-09-09T10:47:34.047Z", "question_score": 237, "tags": "java|algorithm|graph", "answer_id": 52691, "answer_date": "2008-09-09T19:28:21.427Z", "answer_score": 113 }
Please answer the following Stack Overflow question: Title: Does JavaScript have a built in stringbuilder class? <p>I see <a href="http://www.codeproject.com/KB/scripting/stringbuilder.aspx" rel="noreferrer">a few code project solutions</a>.</p> <p>But is there a regular implementation in JavaScript?</p>
<p>If you have to write code for Internet Explorer make sure you chose an implementation, which uses array joins. Concatenating strings with the <code>+</code> or <code>+=</code> operator are extremely slow on IE. This is especially true for IE6. On modern browsers <code>+=</code> is usually just as fast as array joins.</p> <p>When I have to do lots of string concatenations I usually fill an array and don't use a string builder class:</p> <pre><code>var html = []; html.push( "&lt;html&gt;", "&lt;body&gt;", "bla bla bla", "&lt;/body&gt;", "&lt;/html&gt;" ); return html.join(""); </code></pre> <p>Note that the <code>push</code> methods accepts multiple arguments.</p>
{ "question_id": 2087522, "question_date": "2010-01-18T16:29:48.743Z", "question_score": 237, "tags": "javascript|stringbuilder", "answer_id": 2087611, "answer_date": "2010-01-18T16:42:41.563Z", "answer_score": 374 }
Please answer the following Stack Overflow question: Title: Bring a window to the front in WPF <p>How can I bring my WPF application to the front of the desktop? So far I've tried:</p> <pre><code>SwitchToThisWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle, true); SetWindowPos(new WindowInteropHelper(Application.Current.MainWindow).Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); SetForegroundWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle); </code></pre> <p>None of which are doing the job (<code>Marshal.GetLastWin32Error()</code> is saying these operations completed successfully, and the P/Invoke attributes for each definition do have <code>SetLastError=true</code>).</p> <p>If I create a new blank WPF application, and call <code>SwitchToThisWindow</code> with a timer, it works exactly as expected, so I'm not sure why it's not working in my original case.</p> <p><strong>Edit</strong>: I'm doing this in conjunction with a global hotkey.</p>
<p>Well I figured out a work around. I'm making the call from a keyboard hook used to implement a hotkey. The call works as expected if I put it into a BackgroundWorker with a pause. It's a kludge, but I have no idea why it wasn't working originally.</p> <pre><code>void hotkey_execute() { IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle; BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += new DoWorkEventHandler(delegate { Thread.Sleep(10); SwitchToThisWindow(handle, true); }); bg.RunWorkerAsync(); } </code></pre>
{ "question_id": 257587, "question_date": "2008-11-02T23:42:59.667Z", "question_score": 237, "tags": "c#|.net|wpf|winapi|pinvoke", "answer_id": 257741, "answer_date": "2008-11-03T01:40:26.450Z", "answer_score": 3 }
Please answer the following Stack Overflow question: Title: SSL InsecurePlatform error when using Requests package <p>Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy.</p> <p>I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with <code>Requests</code> I get an <code>InsecurePlatform</code> exception.</p> <p>The error mentions <code>urllib3</code>, but I don't have that installed. I did install it to check if it resolved the error, but it didn't.</p> <pre><code>/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3 /util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest /security.html#insecureplatformwarning. </code></pre> <p>Any ideas as to why I'm getting this? I've checked the docs, as specified in the error message, but the docs are saying to import urllib3 and either disable the warning, or provide a certificate.</p>
<p>Use the somewhat hidden <strong>security</strong> feature:</p> <p><code>pip install requests[security]</code> or <code>pip install pyOpenSSL ndg-httpsclient pyasn1</code> </p> <p>Both commands install following extra packages:</p> <ul> <li>pyOpenSSL</li> <li>cryptography</li> <li>idna</li> </ul> <p>Please note that this is not required for <a href="https://requests.readthedocs.io/en/latest/community/faq/#what-are-hostname-doesn-t-match-errors" rel="noreferrer">python-2.7.9+</a>.</p> <p>If <code>pip install</code> fails with errors, check whether you have required development packages for <code>libffi</code>, <code>libssl</code> and <code>python</code> installed in your system <strong>using distribution's package manager</strong>:</p> <ul> <li><p><strong>Debian</strong>/<strong>Ubuntu</strong> - <code>python-dev</code> <code>libffi-dev</code> <code>libssl-dev</code> packages.</p></li> <li><p><strong>Fedora</strong> - <code>openssl-devel</code> <code>python-devel</code> <code>libffi-devel</code> packages.</p></li> </ul> <p><em>Distro list above is incomplete.</em></p> <p><strong>Workaround</strong> (<a href="https://stackoverflow.com/a/31946125/157176">see the original answer by @TomDotTom</a>)<strong>:</strong></p> <p>In case you cannot install some of the required development packages, there's also an option to disable that warning:</p> <pre><code>import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() </code></pre> <p>If your <code>pip</code> itself is affected by <code>InsecurePlatformWarning</code> and cannot install anything from PyPI, it can be fixed with <a href="https://stackoverflow.com/a/54582701/9575715">this step-by-step guide</a> to deploy extra python packages manually.</p>
{ "question_id": 29099404, "question_date": "2015-03-17T12:43:34.707Z", "question_score": 237, "tags": "python|ssl|python-requests", "answer_id": 29099439, "answer_date": "2015-03-17T12:45:11.877Z", "answer_score": 392 }
Please answer the following Stack Overflow question: Title: import module from string variable <p>I'm working on a documentation (personal) for nested matplotlib (MPL) library, which differs from MPL own provided, by interested submodule packages. I'm writing Python script which I hope will automate document generation from future MPL releases.<br> I selected interested submodules/packages and want to list their main classes from which I'll generate list and process it with <code>pydoc</code> </p> <p>Problem is that I can't find a way to instruct Python to load submodule from string. Here is example of what I tried:</p> <pre><code>import matplotlib.text as text x = dir(text) </code></pre> <p>. </p> <pre><code>i = __import__('matplotlib.text') y = dir(i) </code></pre> <p>.</p> <pre><code>j = __import__('matplotlib') z = dir(j) </code></pre> <p>And here is 3 way comparison of above lists through pprint:</p> <p><img src="https://i.stack.imgur.com/3n7pT.png" alt="enter image description here"></p> <p>I don't understand what's loaded in <code>y</code> object - it's base <code>matplotlib</code> plus something else, but it lack information that I wanted and that is main classes from <code>matplotlib.text</code> package. It's top blue coloured part on screenshot (<code>x</code> list)</p> <p>Please don't suggest Sphinx as different approach.</p>
<p>The <code>__import__</code> function can be a bit hard to understand.</p> <p>If you change </p> <pre><code>i = __import__('matplotlib.text') </code></pre> <p>to</p> <pre><code>i = __import__('matplotlib.text', fromlist=['']) </code></pre> <p>then <code>i</code> will refer to <code>matplotlib.text</code>.</p> <p>In Python 2.7 and Python 3.1 or later, you can use <code>importlib</code>:</p> <pre><code>import importlib i = importlib.import_module("matplotlib.text") </code></pre> <p>Some notes</p> <ul> <li><p>If you're trying to import something from a sub-folder e.g. <code>./feature/email.py</code>, the code will look like <code>importlib.import_module("feature.email")</code></p></li> <li><p>You can't import anything if there is no <code>__init__.py</code> in the folder with file you are trying to import</p></li> </ul>
{ "question_id": 8718885, "question_date": "2012-01-03T21:29:38.077Z", "question_score": 237, "tags": "python|matplotlib", "answer_id": 8719100, "answer_date": "2012-01-03T21:50:20.017Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: Insert a line break in mailto body <p>I would like to insert a line break into my mailto body. I tried %0A, %0D and %0D%0A. Nothing worked for me. I tested on Gmail, Yahoo, Apple Mail, Outlook 2010, Outlook.com and Thunderbird with Google Chrome on Mac OSX.</p> <p>Any help please ?</p> <p>Here's my code :</p> <pre><code>&lt;a href="mailto:[email protected]?subject=Subscribe&amp;body=Lastame%20%3A%0D%0A%20Firstname%20%3A"&gt;&lt;img alt="Subscribe" class="center" height="50" src="subscribe.png" style="width: 137px; height: 50px; color: #4da6f7; font-size: 20px; display: block;" width="137"&gt;&lt;/a&gt; </code></pre>
<p>I would suggest you try the html tag <code>&lt;br&gt;</code>, in case your marketing application will recognize it.</p> <p>I use <code>%0D%0A</code>. This should work as long as the email is HTML formatted.</p> <pre><code>&lt;a href="mailto:[email protected]?subject=Subscribe&amp;body=Lastame%20%3A%0D%0AFirstname%20%3A"&gt;&lt;img alt="Subscribe" class="center" height="50" src="subscribe.png" style="width: 137px; height: 50px; color: #4da6f7; font-size: 20px; display: block;" width="137"&gt;&lt;/a&gt; </code></pre> <p>You will likely want to take out the %20 before Firstname, otherwise you will have a space as the first character on the next line.</p> <p>A note, when I tested this with your code, it worked (along with some extra spacing). Are you using a mail client that doesn't allow HTML formatting?</p>
{ "question_id": 22765834, "question_date": "2014-03-31T15:33:31.930Z", "question_score": 237, "tags": "email|mailto", "answer_id": 22765878, "answer_date": "2014-03-31T15:35:32.297Z", "answer_score": 334 }
Please answer the following Stack Overflow question: Title: git stash -> merge stashed change with current changes <p>I made some changes to my branch and realized I forgot I had stashed some other necessary changes to said branch. What I want is a way to merge my stashed changes with the current changes. </p> <p>Is there a way to do this?</p> <p>Its more for convenience, I eventually gave up and committed first my current changes, then my stashed changes, but I would have preferred to get them in with one fell swoop.</p>
<h3>tl;dr</h3> <p>Run <code>git add</code> first.</p> <hr /> <p>I just discovered that if your uncommitted changes are added to the index (i.e. &quot;staged&quot;, using <code>git add ...</code>), then <code>git stash apply</code> (and, presumably, <code>git stash pop</code>) will actually do a proper merge. If there are no conflicts, you're golden. If not, resolve them as usual with <code>git mergetool</code>, or manually with an editor.</p> <p>To be clear, this is the process I'm talking about:</p> <pre><code>mkdir test-repo &amp;&amp; cd test-repo &amp;&amp; git init echo test &gt; test.txt git add test.txt &amp;&amp; git commit -m &quot;Initial version&quot; # here's the interesting part: # make a local change and stash it: echo test2 &gt; test.txt git stash # make a different local change: echo test3 &gt; test.txt # try to apply the previous changes: git stash apply # git complains &quot;Cannot apply to a dirty working tree, please stage your changes&quot; # add &quot;test3&quot; changes to the index, then re-try the stash: git add test.txt git stash apply # git says: &quot;Auto-merging test.txt&quot; # git says: &quot;CONFLICT (content): Merge conflict in test.txt&quot; </code></pre> <p>... which is probably what you're looking for.</p>
{ "question_id": 11675841, "question_date": "2012-07-26T18:35:50.307Z", "question_score": 237, "tags": "git|git-merge|git-stash", "answer_id": 16613814, "answer_date": "2013-05-17T16:25:02.120Z", "answer_score": 360 }
Please answer the following Stack Overflow question: Title: Angular 2: How to style host element of the component? <p>I have component in Angular 2 called my-comp:</p> <pre><code>&lt;my-comp&gt;&lt;/my-comp&gt; </code></pre> <p>How does one style the host element of this component in Angular 2?</p> <p>In Polymer, You would use ":host" selector. I tried it in Angular 2. But it doesn't work.</p> <pre><code>:host { display: block; width: 100%; height: 100%; } </code></pre> <p>I also tried using the component as selector:</p> <pre><code>my-comp { display: block; width: 100%; height: 100%; } </code></pre> <p>Both approaches don't seem to work.</p> <p>Thanks.</p>
<p>There was a bug, but it was fixed in the meantime. <code>:host { }</code> works fine now.</p> <p>Also supported are</p> <ul> <li><code>:host(selector) { ... }</code> for <code>selector</code> to match attributes, classes, ... on the host element</li> <li><p><code>:host-context(selector) { ... }</code> for <code>selector</code> to match elements, classes, ...on parent components</p></li> <li><p><em><code>selector /deep/ selector</code> (alias <code>selector &gt;&gt;&gt; selector</code> doesn't work with SASS) for styles to match across element boundaries</em></p> <ul> <li><p><strong>UPDATE:</strong> SASS is deprecating <code>/deep/</code>.<br> Angular (TS and Dart) added <code>::ng-deep</code> as a replacement that's also compatible with SASS.</p></li> <li><p><strong>UPDATE2:</strong> <code>::slotted</code> <code>::slotted</code> is now supported by all new browsers and can be used with `ViewEncapsulation.ShadowDom<br> <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted</a></p></li> </ul></li> </ul> <p>See also <a href="https://stackoverflow.com/questions/34542143/load-external-css-style-into-angular-2-component/34963135#34963135">Load external css style into Angular 2 Component</a></p> <p><code>/deep/</code> and <code>&gt;&gt;&gt;</code> are <strong>not affected</strong> by the same selector combinators that in Chrome which are deprecated.<br> Angular emulates (rewrites) them, and therefore doesn't depend on browsers supporting them.</p> <p>This is also why <code>/deep/</code> and <code>&gt;&gt;&gt;</code> don't work with <code>ViewEncapsulation.Native</code> which enables native shadow DOM and depends on browser support.</p>
{ "question_id": 32853924, "question_date": "2015-09-29T21:17:12.040Z", "question_score": 237, "tags": "css|angular|css-selectors|angular-components", "answer_id": 36175093, "answer_date": "2016-03-23T10:06:36.220Z", "answer_score": 327 }
Please answer the following Stack Overflow question: Title: Defining Z order of views of RelativeLayout in Android <p>I would like to define the z order of the views of a RelativeLayout in Android.</p> <p>I know one way of doing this is calling <code>bringToFront</code>.</p> <p>Is there are better way of doing this? It would be great if I could define the z order in the layout xml.</p>
<p>The easiest way is simply to pay attention to the order in which the Views are added to your XML file. Lower down in the file means higher up in the Z-axis.</p> <p>Edit: This is documented <a href="http://developer.android.com/reference/android/view/View.html#Drawing" rel="noreferrer">here</a> and <a href="http://developer.android.com/guide/topics/ui/how-android-draws.html" rel="noreferrer">here</a> on the Android developer site. (Thanks @flightplanner)</p>
{ "question_id": 2614393, "question_date": "2010-04-10T18:16:22.327Z", "question_score": 237, "tags": "android|android-relativelayout|z-order", "answer_id": 2614402, "answer_date": "2010-04-10T18:18:20.257Z", "answer_score": 326 }
Please answer the following Stack Overflow question: Title: ASP.NET MVC 3 Razor: Include JavaScript file in the head tag <p>I'm trying to figure out the proper Razor syntax to get a JavaScript file for a particular *.cshtml to be in the head tag along with all the other include files that are defined in _Layout.cshtml.</p>
<p>You can use <strong><a href="http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx" rel="noreferrer">Named Sections</a>.</strong></p> <p><strong>_Layout.cshtml</strong></p> <pre><code>&lt;head&gt; &lt;script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"&gt;&lt;/script&gt; @RenderSection("JavaScript", required: false) &lt;/head&gt; </code></pre> <p><strong>_SomeView.cshtml</strong></p> <pre><code>@section JavaScript { &lt;script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"&gt;&lt;/script&gt; } </code></pre>
{ "question_id": 4311783, "question_date": "2010-11-30T08:21:41.723Z", "question_score": 237, "tags": "javascript|asp.net-mvc|include|razor|asp.net-mvc-3", "answer_id": 4311876, "answer_date": "2010-11-30T08:39:28.023Z", "answer_score": 408 }
Please answer the following Stack Overflow question: Title: Dynamic tabs with user-click chosen components <p>I'm trying to setup a tab system that allows for components to register themselves (with a title). The first tab is like an inbox, there's plenty of actions/link items to choose from for the users, and each of these clicks should be able to instantiate a new component, on click. The actions / links comes in from JSON.</p> <p>The instantiated component will then register itself as a new tab.</p> <p>I'm not sure if this is the 'best' approach? So far, the only guides I've seen are for static tabs, which doesn't help.</p> <p>So far, I've only got the tabs service which is bootstrapped in main to persist throughout the app. It looks something like this:</p> <pre><code>export interface ITab { title: string; } @Injectable() export class TabsService { private tabs = new Set&lt;ITab&gt;(); addTab(title: string): ITab { let tab: ITab = { title }; this.tabs.add(tab); return tab; } removeTab(tab: ITab) { this.tabs.delete(tab); } } </code></pre> <p>Questions:</p> <ol> <li>How can I have a dynamic list in the inbox that creates new (different) tabs? I am sort of guessing the <code>DynamicComponentBuilder</code> would be used?</li> <li>How can the components be created from the inbox (on click) register themselves as tabs and also be shown? I'm guessing <code>ng-content</code>, but I can't find much info on how to use it</li> </ol> <p><strong>EDIT:</strong> An attempt to clarify.</p> <p>Think of the inbox as a mail inbox. Items are fetched as JSON and it displays several items. Once one of the items is clicked, a new tab is created with that items action 'type'. The type is then a component.</p> <p><strong>EDIT 2:</strong> <a href="https://i.imgur.com/yzfMOXJ.png" rel="noreferrer">Image</a>.</p>
<p> <strong>update</strong></p> <p><a href="https://stackblitz.com/edit/angular-ygz3jg" rel="noreferrer"><strong>Angular 5 StackBlitz example</strong></a></p> <p><strong>update</strong></p> <p><code>ngComponentOutlet</code> was added to 4.0.0-beta.3</p> <p><strong>update</strong></p> <p>There is a <code>NgComponentOutlet</code> work in progress that does something similar <a href="https://github.com/angular/angular/pull/11235" rel="noreferrer">https://github.com/angular/angular/pull/11235</a></p> <p><strong>RC.7</strong></p> <p><a href="http://plnkr.co/edit/UGzoPTCHlXKWrn4p8gd1?p=preview" rel="noreferrer"><strong>Plunker example RC.7</strong></a></p> <pre class="lang-ts prettyprint-override"><code>// Helper component to add dynamic components @Component({ selector: 'dcl-wrapper', template: `&lt;div #target&gt;&lt;/div&gt;` }) export class DclWrapper { @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef; @Input() type: Type&lt;Component&gt;; cmpRef: ComponentRef&lt;Component&gt;; private isViewInitialized:boolean = false; constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {} updateComponent() { if(!this.isViewInitialized) { return; } if(this.cmpRef) { // when the `type` input changes we destroy a previously // created component before creating the new one this.cmpRef.destroy(); } let factory = this.componentFactoryResolver.resolveComponentFactory(this.type); this.cmpRef = this.target.createComponent(factory) // to access the created instance use // this.compRef.instance.someProperty = 'someValue'; // this.compRef.instance.someOutput.subscribe(val =&gt; doSomething()); } ngOnChanges() { this.updateComponent(); } ngAfterViewInit() { this.isViewInitialized = true; this.updateComponent(); } ngOnDestroy() { if(this.cmpRef) { this.cmpRef.destroy(); } } } </code></pre> <p>Usage example</p> <pre class="lang-ts prettyprint-override"><code>// Use dcl-wrapper component @Component({ selector: 'my-tabs', template: ` &lt;h2&gt;Tabs&lt;/h2&gt; &lt;div *ngFor="let tab of tabs"&gt; &lt;dcl-wrapper [type]="tab"&gt;&lt;/dcl-wrapper&gt; &lt;/div&gt; ` }) export class Tabs { @Input() tabs; } </code></pre> <pre class="lang-ts prettyprint-override"><code>@Component({ selector: 'my-app', template: ` &lt;h2&gt;Hello {{name}}&lt;/h2&gt; &lt;my-tabs [tabs]="types"&gt;&lt;/my-tabs&gt; ` }) export class App { // The list of components to create tabs from types = [C3, C1, C2, C3, C3, C1, C1]; } </code></pre> <pre class="lang-ts prettyprint-override"><code>@NgModule({ imports: [ BrowserModule ], declarations: [ App, DclWrapper, Tabs, C1, C2, C3], entryComponents: [C1, C2, C3], bootstrap: [ App ] }) export class AppModule {} </code></pre> <hr> <p>See also <a href="https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html" rel="noreferrer">angular.io DYNAMIC COMPONENT LOADER</a></p> <p><strong>older versions</strong> <strong>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</strong></p> <p>This changed again in Angular2 RC.5</p> <p>I will update the example below but it's the last day before vacation.</p> <p>This <a href="http://plnkr.co/edit/3dzkMVXe4AGSRhk11TXG?p=preview" rel="noreferrer">Plunker example</a> demonstrates how to dynamically create components in RC.5</p> <p><strong>Update - use <a href="https://angular.io/docs/ts/latest/api/core/index/ViewContainerRef-class.html" rel="noreferrer">ViewContainerRef</a>.createComponent()</strong></p> <p>Because <code>DynamicComponentLoader</code> is deprecated, the approach needs to be update again.</p> <pre class="lang-ts prettyprint-override"><code>@Component({ selector: 'dcl-wrapper', template: `&lt;div #target&gt;&lt;/div&gt;` }) export class DclWrapper { @ViewChild('target', {read: ViewContainerRef}) target; @Input() type; cmpRef:ComponentRef; private isViewInitialized:boolean = false; constructor(private resolver: ComponentResolver) {} updateComponent() { if(!this.isViewInitialized) { return; } if(this.cmpRef) { this.cmpRef.destroy(); } this.resolver.resolveComponent(this.type).then((factory:ComponentFactory&lt;any&gt;) =&gt; { this.cmpRef = this.target.createComponent(factory) // to access the created instance use // this.compRef.instance.someProperty = 'someValue'; // this.compRef.instance.someOutput.subscribe(val =&gt; doSomething()); }); } ngOnChanges() { this.updateComponent(); } ngAfterViewInit() { this.isViewInitialized = true; this.updateComponent(); } ngOnDestroy() { if(this.cmpRef) { this.cmpRef.destroy(); } } } </code></pre> <p><a href="http://plnkr.co/edit/GJTLrnQdRDBvZenX59PZ?p=preview" rel="noreferrer"><strong>Plunker example RC.4</strong></a><br> <a href="https://plnkr.co/edit/PpgMvS?p=preview" rel="noreferrer"><strong>Plunker example beta.17</strong></a></p> <p><strong>Update - use loadNextToLocation</strong></p> <pre class="lang-ts prettyprint-override"><code>export class DclWrapper { @ViewChild('target', {read: ViewContainerRef}) target; @Input() type; cmpRef:ComponentRef; private isViewInitialized:boolean = false; constructor(private dcl:DynamicComponentLoader) {} updateComponent() { // should be executed every time `type` changes but not before `ngAfterViewInit()` was called // to have `target` initialized if(!this.isViewInitialized) { return; } if(this.cmpRef) { this.cmpRef.destroy(); } this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) =&gt; { this.cmpRef = cmpRef; }); } ngOnChanges() { this.updateComponent(); } ngAfterViewInit() { this.isViewInitialized = true; this.updateComponent(); } ngOnDestroy() { if(this.cmpRef) { this.cmpRef.destroy(); } } } </code></pre> <p><a href="https://plnkr.co/edit/kc2Bgg?p=preview" rel="noreferrer"><strong>Plunker example beta.17</strong></a></p> <p><strong>original</strong></p> <p>Not entirely sure from your question what your requirements are but I think this should do what you want.</p> <p>The <code>Tabs</code> component gets an array of types passed and it creates "tabs" for each item in the array.</p> <pre class="lang-ts prettyprint-override"><code>@Component({ selector: 'dcl-wrapper', template: `&lt;div #target&gt;&lt;/div&gt;` }) export class DclWrapper { constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {} @Input() type; ngOnChanges() { if(this.cmpRef) { this.cmpRef.dispose(); } this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) =&gt; { this.cmpRef = cmpRef; }); } } @Component({ selector: 'c1', template: `&lt;h2&gt;c1&lt;/h2&gt;` }) export class C1 { } @Component({ selector: 'c2', template: `&lt;h2&gt;c2&lt;/h2&gt;` }) export class C2 { } @Component({ selector: 'c3', template: `&lt;h2&gt;c3&lt;/h2&gt;` }) export class C3 { } @Component({ selector: 'my-tabs', directives: [DclWrapper], template: ` &lt;h2&gt;Tabs&lt;/h2&gt; &lt;div *ngFor="let tab of tabs"&gt; &lt;dcl-wrapper [type]="tab"&gt;&lt;/dcl-wrapper&gt; &lt;/div&gt; ` }) export class Tabs { @Input() tabs; } @Component({ selector: 'my-app', directives: [Tabs] template: ` &lt;h2&gt;Hello {{name}}&lt;/h2&gt; &lt;my-tabs [tabs]="types"&gt;&lt;/my-tabs&gt; ` }) export class App { types = [C3, C1, C2, C3, C3, C1, C1]; } </code></pre> <p><a href="https://plnkr.co/edit/kc2Bgg?p=preview" rel="noreferrer"><strong>Plunker example beta.15</strong></a> (not based on your Plunker)</p> <p>There is also a way to pass data along that can be passed to the dynamically created component like (<code>someData</code> would need to be passed like <code>type</code>)</p> <pre class="lang-ts prettyprint-override"><code> this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) =&gt; { cmpRef.instance.someProperty = someData; this.cmpRef = cmpRef; }); </code></pre> <p>There is also some support to use dependency injection with shared services.</p> <p>For more details see <a href="https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html" rel="noreferrer">https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html</a></p>
{ "question_id": 36325212, "question_date": "2016-03-31T05:53:43.723Z", "question_score": 237, "tags": "angular|angular-template", "answer_id": 36325468, "answer_date": "2016-03-31T06:10:17.820Z", "answer_score": 278 }
Please answer the following Stack Overflow question: Title: querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript <p>I would like to know what exactly is the difference between <code>querySelector</code> and <code>querySelectorAll</code> against <code>getElementsByClassName</code> and <code>getElementById</code>?</p> <p>From <a href="https://developer.mozilla.org/en-US/docs/DOM/Document.querySelector" rel="noreferrer">this link</a> I could gather that with <code>querySelector</code> I can write <code>document.querySelector(".myclass")</code> to get elements with class <code>myclass</code> and <code>document.querySelector("#myid")</code> to get element with ID <code>myid</code>. But I can already do that <code>getElementsByClassName</code> and <code>getElementById</code>. Which one should be preferred?</p> <p>Also I work in <a href="https://stackoverflow.com/tags/xpages/info">XPages</a> where the ID is dynamically generated with colon and looks like this <code>view:_id1:inputText1</code>. So when I write <code>document.querySelector("#view:_id1:inputText1")</code> it doesn't work. But writing <code>document.getElementById("view:_id1:inputText1")</code> works. Any ideas why?</p>
<blockquote> <p>I would like to know what exactly is the difference between querySelector and querySelectorAll against getElementsByClassName and getElementById?</p> </blockquote> <p>The syntax and the browser support. </p> <p><code>querySelector</code> is more useful when you want to use more complex selectors.</p> <p>e.g. All list items descended from an element that is a member of the foo class: <code>.foo li</code></p> <blockquote> <p>document.querySelector("#view:_id1:inputText1") it doesn't work. But writing document.getElementById("view:_id1:inputText1") works. Any ideas why?</p> </blockquote> <p>The <code>:</code> character has special meaning inside a selector. You have to escape it. (The selector escape character has special meaning in a JS string too, so you have to escape <em>that</em> too).</p> <pre><code>document.querySelector("#view\\:_id1\\:inputText1") </code></pre>
{ "question_id": 14377590, "question_date": "2013-01-17T11:00:20.310Z", "question_score": 237, "tags": "javascript", "answer_id": 14377614, "answer_date": "2013-01-17T11:01:43.593Z", "answer_score": 138 }
Please answer the following Stack Overflow question: Title: ResizeObserver - loop limit exceeded <p>About two months ago we started using Rollbar to notify us of various errors in our Web App. Ever since then we have been getting the occasional error:</p> <p><code>ResizeObserver loop limit exceeded</code></p> <p>The thing that confuses me about this is that we are not using <code>ResizeObserver</code> and I have investigated the only plugin which I thought could possibly be the culprit, namely:</p> <p><a href="https://www.npmjs.com/package/aurelia-resize" rel="noreferrer">Aurelia Resize</a></p> <p>But it doesn't appear to be using <code>ResizeObserver</code> either.</p> <p>What is also confusing is that these error messages have been occuring since January but <code>ResizeObserver</code> support has only recently been added to Chrome 65.</p> <p>The browser versions that have been giving us this error are:</p> <ul> <li>Chrome: 63.0.3239 (ResizeObserver loop limit exceeded)</li> <li>Chrome: 64.0.3282 (ResizeObserver loop limit exceeded)</li> <li>Edge: 14.14393 (SecurityError)</li> <li>Edge: 15.15063 (SecurityError)</li> </ul> <p>So I was wondering if this could possibly be a browser bug? Or perhaps an error that actually has nothing to do with <code>ResizeObserver</code>?</p>
<p>You can safely ignore this error.</p> <p>One of the specification authors wrote in a comment to your question but it is not an answer and it is not clear in the comment that the answer is really the most important one in this thread, and the one that made me comfortable to ignore it in our Sentry logs.</p> <blockquote> <p>This error means that ResizeObserver was not able to deliver all observations within a single animation frame. It is benign (your site will not break). – <a href="https://github.com/WICG/ResizeObserver/commits?author=atotic" rel="noreferrer">Aleksandar Totic</a> Apr 15 at 3:14</p> </blockquote> <p>There are also some <a href="https://github.com/WICG/ResizeObserver/issues/38" rel="noreferrer">related issues</a> to this in the specification repository.</p>
{ "question_id": 49384120, "question_date": "2018-03-20T12:22:04.060Z", "question_score": 237, "tags": "google-chrome|aurelia|microsoft-edge|rollbar", "answer_id": 50387233, "answer_date": "2018-05-17T08:53:07.403Z", "answer_score": 334 }
Please answer the following Stack Overflow question: Title: Can regular expressions be used to match nested patterns? <p>Is it possible to write a regular expression that matches a nested pattern that occurs an unknown number of times? For example, can a regular expression match an opening and closing brace when there are an unknown number of open/close braces nested within the outer braces?</p> <p>For example:</p> <pre><code>public MyMethod() { if (test) { // More { } } // More { } } // End </code></pre> <p>Should match:</p> <pre><code>{ if (test) { // More { } } // More { } } </code></pre>
<p>No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a <em>finite</em> automaton.</p> <p>You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input).</p> <p>There are many parser generators avialable, for instance <a href="http://www.antlr.org/" rel="noreferrer">ANTLR</a> for Java. Finding an existing grammar for Java (or C) is also not difficult.<br> For more background: <a href="http://en.wikipedia.org/wiki/Automata_theory" rel="noreferrer">Automata Theory</a> at Wikipedia</p>
{ "question_id": 133601, "question_date": "2008-09-25T14:17:40.873Z", "question_score": 237, "tags": "regex|nested|finite-automata", "answer_id": 133684, "answer_date": "2008-09-25T14:27:12.643Z", "answer_score": 277 }
Please answer the following Stack Overflow question: Title: What are some good ways to manage a changelog using Git? <p>I've been using Git for a while now, and I recently started using it to tag my releases so that I could more easily keep track of changes and be able to see which version each of our clients is running (unfortunately the code currently mandates that each client have their own copy of the PHP site; I'm changing this, but it's slow-going).</p> <p>In any case, we're starting to build some momentum, and I thought it would be really good to be able to show people what has changed since the last release. The problem is, I haven't been maintaining a changelog, because I don't have a good idea of how to go about it. For this particular time, I can run through the log and manually create one, but that will get tiring very quickly.</p> <p>I tried googling &quot;git changelog&quot; and &quot;git manage changelog&quot;, but I didn't find anything that really talked about the workflow of code changes and how that coincides with the changelog. We're currently following <a href="http://reinh.com/blog/2009/03/02/a-git-workflow-for-agile-teams.html" rel="noreferrer">Rein Henrichs' development workflow</a> and I would love something that went along with that.</p> <p>Is there a standard approach that I am missing, or is this an area where everybody does their own thing?</p>
<p>This was in 2015, but for the sake of future searchers, it's now possible to generate gorgeous logs with:</p> <pre><code>git log --oneline --decorate </code></pre> <p>Or, if you want it even prettier (with color for the terminal):</p> <pre><code>git log --oneline --decorate --color </code></pre> <p>Piping that output to <em>ChangeLog</em> is what I currently use in all my projects, and it's simply amazing.</p>
{ "question_id": 3523534, "question_date": "2010-08-19T15:43:51.723Z", "question_score": 237, "tags": "git|github|changelog", "answer_id": 22492425, "answer_date": "2014-03-18T22:30:40.637Z", "answer_score": 201 }
Please answer the following Stack Overflow question: Title: In log4j, does checking isDebugEnabled before logging improve performance? <p>I am using <strong><em>Log4J</em></strong> in my application for logging. Previously I was using debug call like:</p> <p><strong>Option 1:</strong></p> <pre><code>logger.debug("some debug text"); </code></pre> <p>but some links suggest that it is better to check <code>isDebugEnabled()</code> first, like: </p> <p><strong>Option 2:</strong></p> <pre><code>boolean debugEnabled = logger.isDebugEnabled(); if (debugEnabled) { logger.debug("some debug text"); } </code></pre> <p>So my question is "<strong>Does option 2 improve performance any way?</strong>".</p> <p>Because in any case Log4J framework have same check for debugEnabled. For option 2 it might be beneficial if we are using multiple debug statement in single method or class, where the framework does not need to call <code>isDebugEnabled()</code> method multiple times (on each call); in this case it calls <code>isDebugEnabled()</code> method only once, and if Log4J is configured to debug level then actually it calls <code>isDebugEnabled()</code> method twice:</p> <ol> <li>In case of assigning value to debugEnabled variable, and</li> <li>Actually called by logger.debug() method.</li> </ol> <p>I don't think that if we write multiple <code>logger.debug()</code> statement in method or class and calling <code>debug()</code> method according to option 1 then it is overhead for Log4J framework in comparison with option 2. Since <code>isDebugEnabled()</code> is a very small method (in terms of code), it might be good candidate for inlining.</p>
<p>In this particular case, Option 1 is better.</p> <p>The guard statement (checking <code>isDebugEnabled()</code>) is there to prevent potentially expensive computation of the log message when it involves invocation of the <code>toString()</code> methods of various objects and concatenating the results.</p> <p>In the given example, the log message is a constant string, so letting the logger discard it is just as efficient as checking whether the logger is enabled, and it lowers the complexity of the code because there are fewer branches.</p> <p>Better yet is to use a more up-to-date logging framework where the log statements take a format specification and a list of arguments to be substituted by the logger&mdash;but "lazily," only if the logger is enabled. This is the approach taken by <a href="http://www.slf4j.org/apidocs/org/slf4j/Logger.html#debug(java.lang.String,%20java.lang.Object[])" rel="noreferrer">slf4j</a>.</p> <p>See <a href="https://stackoverflow.com/questions/105852/conditional-logging-with-minimal-cyclomatic-complexity/105908#105908">my answer to a related question</a> for more information, and an example of doing something like this with log4j.</p>
{ "question_id": 963492, "question_date": "2009-06-08T05:13:54.777Z", "question_score": 237, "tags": "java|logging|log4j", "answer_id": 963681, "answer_date": "2009-06-08T06:44:48.930Z", "answer_score": 281 }
Please answer the following Stack Overflow question: Title: How can I run PowerShell with the .NET 4 runtime? <p>I am updating a PowerShell script that manages some .NET assemblies. The script was written for assemblies built against .NET 2 (the same version of the framework that PowerShell runs with), but now needs to work with .NET 4 assemblies as well as .NET 2 assemblies.</p> <p>Since .NET 4 supports running applications built against older versions of the framework, it seems like the simplest solution is to launch PowerShell with the .NET 4 runtime when I need to run it against .NET 4 assemblies.</p> <p>How can I run PowerShell with the .NET 4 runtime?</p>
<p>PowerShell (the engine) runs fine under .NET 4.0. PowerShell (the console host and the <a href="https://en.wikipedia.org/wiki/Windows_PowerShell#PowerShell_2.0" rel="noreferrer">ISE</a>) do not, simply because they were compiled against older versions of .NET. There's a registry setting that will <strong>change the .NET framework loaded systemwide</strong>, which will in turn allow PowerShell to use .NET 4.0 classes:</p> <pre><code>reg add hklm\software\microsoft\.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1 reg add hklm\software\wow6432node\microsoft\.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1 </code></pre> <p>To update just the ISE to use .NET 4.0, you can change the configuration ($psHome\powershell_ise.exe.config) file to have a chunk like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;startup&gt; &lt;supportedRuntime version="v4.0.30319" /&gt; &lt;/startup&gt; &lt;/configuration&gt; </code></pre> <p>You can build .NET 4.0 applications that call PowerShell using the PowerShell API (System.Management.Automation.PowerShell) just fine, but these steps will help get the in-the-box PowerShell hosts to work under .NET 4.0.</p> <hr> <p><strong>Remove the registry keys when you don't need them any more. These are machine-wide keys and forcibly migrate ALL applications to .NET 4.0, even applications using .net 2 and .net 3.5</strong></p> <hr>
{ "question_id": 2094694, "question_date": "2010-01-19T15:44:06.243Z", "question_score": 237, "tags": ".net|powershell|.net-4.0", "answer_id": 2096906, "answer_date": "2010-01-19T20:43:50.437Z", "answer_score": 147 }
Please answer the following Stack Overflow question: Title: Scoping in Python 'for' loops <p>I'm not asking about Python's scoping rules; I understand generally <em>how</em> scoping works in Python for loops. My question is <em>why</em> the design decisions were made in this way. For example (no pun intended):</p> <pre><code>for foo in xrange(10): bar = 2 print(foo, bar) </code></pre> <p>The above will print (9,2). </p> <p>This strikes me as weird: 'foo' is really just controlling the loop, and 'bar' was defined inside the loop. I can understand why it might be necessary for 'bar' to be accessible outside the loop (otherwise, for loops would have very limited functionality). What I don't understand is why it is necessary for the control variable to remain in scope after the loop exits. In my experience, it simply clutters the global namespace and makes it harder to track down errors that would be caught by interpreters in other languages.</p>
<p>The likeliest answer is that it just keeps the grammar simple, hasn't been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the location of assignment statements. The <a href="https://docs.python.org/3/reference/simple_stmts.html#global" rel="noreferrer"><code>global</code></a> keyword exists just for this reason (to signify that assignment is done at a global scope).</p> <p><strong>Update</strong></p> <p>Here's a good discussion on the topic: <a href="http://mail.python.org/pipermail/python-ideas/2008-October/002109.html" rel="noreferrer">http://mail.python.org/pipermail/python-ideas/2008-October/002109.html</a></p> <blockquote> <p>Previous proposals to make for-loop variables local to the loop have stumbled on the problem of existing code that relies on the loop variable keeping its value after exiting the loop, and it seems that this is regarded as a desirable feature.</p> </blockquote> <p>In short, you can probably blame it on the Python community :P</p>
{ "question_id": 3611760, "question_date": "2010-08-31T17:52:11.407Z", "question_score": 237, "tags": "python|scope", "answer_id": 3611987, "answer_date": "2010-08-31T18:22:03.953Z", "answer_score": 141 }
Please answer the following Stack Overflow question: Title: How can I inspect disappearing element in a browser? <p><strong>How can I inspect an element which disappears when my mouse moves away?</strong> <img src="https://i.stack.imgur.com/FVOVx.png" alt="Example dropdown which disappears"></p> <p>I don't know it's ID, class or anything but want to inspect it.</p> <p><strong>Solutions I have tried:</strong></p> <p>Run jQuery selector inside console <code>$('*:contains("some text")')</code> but didn't have any luck mainly because the element is not hidden but probably removed from the DOM tree.</p> <p>Manually inspecting DOM tree for changes gives me nothing as it seems to be just too fast to notice what have changed.</p> <p><strong>SUCCESS:</strong></p> <p>I have been successful with Event breakpoints. Specifically - mousedown in my case. Just go to <code>Sources-&gt; Event Listener Breakpoints-&gt; Mouse-&gt; mousedown</code> in Chrome. After that I clicked the element I wanted to inspect and inside <code>Scope Variables</code> I saw some useful directions.</p>
<p><s>(This answer only applies to Chrome Developer Tools.</s> See update below.)</p> <p>Find an element that contains the disappearing element. Right click on the element and apply &quot;Break on... &gt; Subtree Modifications.&quot; This will throw a debugger pause before the element disappears, which will allow you to interact with the element in a paused state.</p> <p><a href="https://i.stack.imgur.com/8OiFt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8OiFt.png" alt="enter image description here" /></a></p> <p><strong>Update Oct 22 2019:</strong> with the release of v. 70, it looks like FireFox finally supports this kind of debugging <a href="https://hacks.mozilla.org/2019/10/firefox-70-a-bountiful-release-for-all/" rel="noreferrer">2</a> <a href="https://wiki.developer.mozilla.org/en-US/docs/Tools/Debugger/Break_on_DOM_mutation" rel="noreferrer">3</a>:</p> <p><a href="https://i.stack.imgur.com/U4ll1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/U4ll1.png" alt="enter image description here" /></a></p> <p><strong>Update Sep 15 2020:</strong> Chrome has an &quot;Emulate a focused page&quot; option (you can get it from the [⌘]+[P] Command Menu, or Global Preferences) for this exact need. <a href="https://twitter.com/sulco/status/1305841873945272321" rel="noreferrer">5 - h/t @sulco on Twitter</a></p>
{ "question_id": 19422214, "question_date": "2013-10-17T08:57:42.483Z", "question_score": 237, "tags": "javascript|google-chrome|firefox|firebug|opera-dragonfly", "answer_id": 34095731, "answer_date": "2015-12-04T19:09:22.223Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: Can I get chrome-devtools to actually search all JS sources? <p>I'm having trouble with searching through JS files in chrome dev-tools, in the past the search activated by <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd> always found what I wanted, but recently (I'm not sure exactly which update triggered this) I'm finding the search does not catch</p> <ul> <li><p>JS in inline script tags</p></li> <li><p>JS inside iframes.</p></li> </ul> <p>I've also found the callstack messed up when inline scripts were involved, but when I try to google for these issues, I just get the dev-tools doc pages, has anyone else noticed these issues? Was I just imagining this worked before?</p>
<p>There is an option under <a href="https://developer.chrome.com/docs/devtools/customize/#settings" rel="noreferrer">Settings -&gt; Preferences -&gt; Sources</a> called &quot;Search in anonymous and content scripts&quot;.</p> <p>I'm not sure how/when I disabled this but enabling it and restarting chrome has fixed all of my problems.</p>
{ "question_id": 15944633, "question_date": "2013-04-11T09:00:07.817Z", "question_score": 237, "tags": "javascript|google-chrome-devtools", "answer_id": 15944975, "answer_date": "2013-04-11T09:16:23.680Z", "answer_score": 57 }
Please answer the following Stack Overflow question: Title: What is the difference between pyenv, virtualenv, anaconda? <p>I am a ruby programmer trying to learn python. I am pretty familiar with pyenv since it is like a copy and paste from rbenv. Pyenv helps allow to have more than one version of python in a system and also to isolate the python without touching sensitive parts of system.</p> <p>I suppose every python installation comes with pip package. What I still don't understand is, there are many good python libs out there that suggest to use this virtualenv and anaconda. I can even find a virtualenv plugin for pyenv.</p> <p>Now I am getting confused with the purpose of these two pyenv and virtualenv. worse inside pyenv there is a virtualenv plugin.</p> <p>My questions are:</p> <ul> <li>what is the difference between pyenv and virtualenv?</li> <li>Is there any difference in using pip command inside both pyenv and virtualenv?</li> <li>what does this pyenv virutalenv do?</li> </ul> <p>Your explanation with example will be highly appreciated.</p>
<p><em>Edit: It's worth mentioning <code>pip</code> here as well, as <code>conda</code> and <code>pip</code> have similarities and differences that are relevant to this topic</em>.</p> <p><strong>pip: the Python Package Manager.</strong></p> <ul> <li>You might think of <code>pip</code> as the python equivalent of the ruby <code>gem</code> command</li> <li><code>pip</code> is not included with python by default.</li> <li>You may install Python using <a href="https://github.com/Homebrew/brew/blob/master/docs/Homebrew-and-Python.md" rel="noreferrer">homebrew</a>, which will install pip automatically: <code>brew install python</code></li> <li>The final version of OSX did not include pip by default. To add pip to your mac system's version of python, you can <code>sudo easy_install pip</code></li> <li>You can find and publish python packages using <a href="https://pypi.python.org/pypi" rel="noreferrer">PyPI: The Python Package Index</a></li> <li>The requirements.txt file is comparable to the ruby <code>gemfile</code></li> <li>To create a requirements text file, <code>pip freeze &gt; requirements.txt</code></li> <li>Note, at this point, we have python installed on our system, and we have created a requirements.txt file that outlines all of the python packages that have been installed on your system.</li> </ul> <p><strong>pyenv: Python Version Manager</strong></p> <ul> <li><a href="https://github.com/yyuu/pyenv#simple-python-version-management-pyenv" rel="noreferrer">From the docs</a>: <em>pyenv lets you easily switch between multiple versions of Python. It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well. This project was forked from rbenv and ruby-build, and modified for Python.</em></li> <li>Many folks <a href="https://softwareengineering.stackexchange.com/questions/63859/why-do-people-hesitate-to-use-python-3">hesitate to use python3</a>.</li> <li>If you need to use different versions of python, <code>pyenv</code> lets you manage this easily.</li> </ul> <p><strong>virtualenv: Python Environment Manager.</strong></p> <ul> <li><a href="https://virtualenv.pypa.io/en/stable/" rel="noreferrer">From the docs</a>: <em>The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.</em></li> <li>To create a <code>virtualenv</code>, simply invoke <code>virtualenv ENV</code>, where <code>ENV</code> is is a directory to place the new virtual environment.</li> <li>To initialize the <code>virtualenv</code>, you need to <code>source ENV/bin/activate</code>. To stop using, simply call <code>deactivate</code>.</li> <li>Once you activate the <code>virtualenv</code>, you might install all of a workspace's package requirements by running <code>pip install -r</code> against the project's <code>requirements.txt</code> file.</li> </ul> <p><strong>Anaconda: Package Manager + Environment Manager + Additional Scientific Libraries.</strong></p> <ul> <li><a href="https://docs.continuum.io/anaconda/pkg-docs" rel="noreferrer">From the docs</a>: <em>Anaconda 4.2.0 includes an easy installation of Python (2.7.12, 3.4.5, and/or 3.5.2) and updates of over 100 pre-built and tested scientific and analytic Python packages that include NumPy, Pandas, SciPy, Matplotlib, and IPython, with over 620 more packages available via a simple <code>conda install &lt;packagename&gt;</code></em></li> <li>As a web developer, I haven't used Anaconda. It's ~3GB including all the packages.</li> <li>There is a slimmed down <code>miniconda</code> version, which seems like it could be a more simple option than using <code>pip</code> + <code>virtualenv</code>, although I don't have experience using it personally.</li> <li>While <code>conda</code> allows you to install packages, these packages are separate than PyPI packages, so you may still need to use pip additionally depending on the types of packages you need to install. </li> </ul> <p><em>See also:</em></p> <ul> <li><a href="https://docs.conda.io/projects/conda/en/latest/commands.html#conda-vs-pip-vs-virtualenv-commands" rel="noreferrer">conda vs pip vs virtualenv</a> (section in documentation from anaconda)</li> <li><a href="https://stackoverflow.com/questions/20994716/what-is-the-difference-between-pip-and-conda">the difference between pip and conda</a> (stackoverflow)</li> <li><a href="https://stackoverflow.com/questions/29950300/what-is-the-relationship-between-virtualenv-and-pyenv">the relationship between virtualenv and pyenv</a> (stackoverflow)</li> </ul>
{ "question_id": 38217545, "question_date": "2016-07-06T06:31:10.667Z", "question_score": 237, "tags": "python|pip|anaconda|virtualenv|pyenv", "answer_id": 39928067, "answer_date": "2016-10-08T02:22:57.550Z", "answer_score": 232 }
Please answer the following Stack Overflow question: Title: Linq list of lists to single list <p>Seems like this is the kind of thing that would have already been answered but I'm unable to find it.</p> <p>My question is pretty simple, how can I do this in one statement so that instead of having to new the empty list and then aggregate in the next line, that I can have a single linq statement that outputs my final list. details is a list of items that each contain a list of residences, I just want all of the residences in a flat list.</p> <pre><code>var residences = new List&lt;DAL.AppForm_Residences&gt;(); details.Select(d =&gt; d.AppForm_Residences).ToList().ForEach(d =&gt; residences.AddRange(d)); </code></pre>
<p>You want to use the <code>SelectMany</code> extension method.</p> <pre><code>var residences = details.SelectMany(d =&gt; d.AppForm_Residences).ToList(); </code></pre>
{ "question_id": 1145558, "question_date": "2009-07-17T20:34:54.523Z", "question_score": 237, "tags": "c#|linq", "answer_id": 1145583, "answer_date": "2009-07-17T20:40:03.013Z", "answer_score": 388 }
Please answer the following Stack Overflow question: Title: Use variable with TOP in select statement in SQL Server without making it dynamic <pre><code>declare @top int set @top = 5 select top @top * from tablename </code></pre> <p>Is it possible?</p> <p>Or any idea for such a logic (i don't want to use dynamic query)?</p>
<p>Yes, in SQL Server 2005 it's possible to use a variable in the <code>top</code> clause.</p> <pre><code>select top (@top) * from tablename </code></pre>
{ "question_id": 1927450, "question_date": "2009-12-18T10:35:18.260Z", "question_score": 237, "tags": "sql|sql-server|sql-server-2005|tsql", "answer_id": 1927460, "answer_date": "2009-12-18T10:38:25.590Z", "answer_score": 444 }
Please answer the following Stack Overflow question: Title: Install specific git commit with pip <p>I'm developing a django app and I'm using pip to manage my requirements. How can I do to install a specific git's commit?</p> <p>In my case I need to install this commit: <a href="https://github.com/aladagemre/django-notification/commit/2927346f4c513a217ac8ad076e494dd1adbf70e1">https://github.com/aladagemre/django-notification/commit/2927346f4c513a217ac8ad076e494dd1adbf70e1</a></p>
<p>You can specify commit hash, branch name, tag.</p> <p>For the branch name and the tag, you can also install a compressed distribution. This is faster and more efficient, as it does not require cloning the entire repository. GitHub creates those bundles automatically.</p> <p><strong>hash:</strong></p> <pre><code>$ pip install git+https://github.com/aladagemre/django-notification.git@2927346f4c513a217ac8ad076e494dd1adbf70e1 </code></pre> <p><strong>branch-name</strong></p> <p>With git</p> <pre><code>$ pip install git+https://github.com/aladagemre/django-notification.git@cool-feature-branch </code></pre> <p>or from source bundle</p> <pre><code>$ pip install https://github.com/aladagemre/django-notification/archive/cool-feature-branch.tar.gz </code></pre> <p><strong>tag</strong></p> <p>with git</p> <pre><code>$ pip install git+https://github.com/aladagemre/[email protected] </code></pre> <p>or from source bundle</p> <pre><code>$ pip install https://github.com/aladagemre/django-notification/archive/v2.1.0.tar.gz </code></pre> <p>It is a not well-documented feature, but you can find more information at <a href="https://pip.pypa.io/en/latest/topics/vcs-support/" rel="noreferrer">https://pip.pypa.io/en/latest/topics/vcs-support/</a></p>
{ "question_id": 13685920, "question_date": "2012-12-03T15:03:30.093Z", "question_score": 237, "tags": "git|installation|commit|pip", "answer_id": 13754517, "answer_date": "2012-12-06T23:29:31.927Z", "answer_score": 398 }
Please answer the following Stack Overflow question: Title: Tab not taking full width on Tablet device [Using android.support.design.widget.TabLayout] <p>I have setup tabs as <strong>UPDATE 29/05/2015</strong> <a href="https://stackoverflow.com/questions/26540078/use-tab-with-new-toolbar-appcompat-v7-21">this</a> post. Tabs take full width on my Nexus 4 mobile but on nexus 7 tablet it in center and not cover full screen width.</p> <p><strong>Nexus 7 screenshot</strong> <img src="https://i.stack.imgur.com/zZdVE.jpg" alt="Nexus7"> <strong>Nexus 4 screenshot</strong> <img src="https://i.stack.imgur.com/Zwv0O.jpg" alt="Nexus 4"></p>
<p>A "simpler" answer <a href="https://stackoverflow.com/a/31188097/1438339">borrowed from Kaizie</a> would just be adding <code>app:tabMaxWidth="0dp"</code> in your <code>TabLayout</code> xml:</p> <pre><code>&lt;android.support.design.widget.TabLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMaxWidth="0dp" app:tabGravity="fill" app:tabMode="fixed" /&gt; </code></pre>
{ "question_id": 30843775, "question_date": "2015-06-15T11:16:20.597Z", "question_score": 237, "tags": "android|tabs|width|android-appcompat|android-tablayout", "answer_id": 31620690, "answer_date": "2015-07-24T22:24:19.620Z", "answer_score": 665 }
Please answer the following Stack Overflow question: Title: How to exclude this / current / dot folder from find "type d" <pre><code>find . -type d </code></pre> <p>can be used to find all directories below some start point. But it returns the current directory (<code>.</code>) too, which may be undesired. How can it be excluded?</p>
<p><a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/find.html#tag_20_47" rel="noreferrer"><strong>POSIX 7 solution</strong></a>:</p> <pre><code>find . ! -path . -type d </code></pre> <p>For this particular case (<code>.</code>), golfs better than the <code>mindepth</code> solution (24 vs 26 chars), although this is probably slightly harder to type because of the <code>!</code>.</p> <p>To exclude other directories, this will golf less well and requires a variable for DRYness:</p> <pre><code>D="long_name" find "$D" ! -path "$D" -type d </code></pre> <p>My decision tree between <code>!</code> and <code>-mindepth</code>:</p> <ul> <li>script? Use <code>!</code> for portability.</li> <li>interactive session on GNU? <ul> <li>exclude <code>.</code>? Throw a coin.</li> <li>exclude <code>long_name</code>? Use <code>-mindepth</code>.</li> </ul></li> </ul>
{ "question_id": 13525004, "question_date": "2012-11-23T07:55:10.850Z", "question_score": 237, "tags": "shell|directory|find", "answer_id": 17389439, "answer_date": "2013-06-30T10:32:03.380Z", "answer_score": 231 }
Please answer the following Stack Overflow question: Title: git --git-dir not working as expected <p>I am trying to run git from a different directory than I am in. So for example if I am in:</p> <pre><code>cd /home/domain/ git status &lt;&lt; runs perfect ie # On branch master # Your branch is ahead of 'origin/master' by 6 commits. </code></pre> <p>So now I want to run this command from a different directory using the <code>--git-dir</code> option.</p> <p>So lets say I'm in <code>root/</code> and try this:</p> <pre><code>git --git-dir="/home/domain/" status ## Error fatal: Not a git repository: '/home/domain/' </code></pre> <p>I've also tried to include the <code>.git</code> folder i.e.</p> <pre><code>git --git-dir="/home/domain/.git/" status </code></pre> <p>But this looks like it's trying to run git from the root, i.e. deleting everything from my domain folder and adding everything in root.</p> <p>Hope someone can advise on what I'm doing wrong.</p>
<p>You have to define the working dir as well. Confusing I know but it's a flexibility thing.</p> <pre><code>git --git-dir=/mycode/.git --work-tree=/mycode status </code></pre> <p>You can read a little more <a href="http://marc.info/?l=git&amp;m=120956110207686&amp;w=2" rel="noreferrer">here</a></p>
{ "question_id": 1386291, "question_date": "2009-09-06T18:08:54.530Z", "question_score": 237, "tags": "git", "answer_id": 1386350, "answer_date": "2009-09-06T18:33:46.523Z", "answer_score": 345 }
Please answer the following Stack Overflow question: Title: How to delete Swift Package Dependency in Xcode 11? <p>I have a project in Xcode 11 that I added Swift Package Manager dependencies to. I now realized that I no longer need one of the package dependencies I previously added to my project.</p> <p>As you can see below, there are no options under <code>File &gt; Swift Packages</code> for deleting a packager from Swift Package Manager for this project.</p> <p><a href="https://i.stack.imgur.com/V8w13.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V8w13.png" alt="Swift Packages Menu Options"></a></p> <p>I have tried removing the package from the array in the <code>project.xcworkspace/xcshareddata/swiftpm/Package.resolved</code> file. But it still doesn't remove it from Xcode, and the next time I <code>Update to Latest Package Versions</code> it readds the entry to the <code>Package.resolved</code> file.</p> <p>How can I delete a Swift Package Manager dependency in my project?</p>
<ol> <li>Open Xcode</li> <li>Select your project</li> <li>Look at the top middle</li> <li>Select <strong>Swift Package Manager</strong> menu</li> </ol> <p>You'll be able to manage your packages (add / remove)</p> <p><a href="https://i.stack.imgur.com/LO08e.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LO08e.png" alt="enter image description here"></a></p>
{ "question_id": 56718121, "question_date": "2019-06-22T18:34:35.377Z", "question_score": 237, "tags": "xcode|swift-package-manager|xcode11", "answer_id": 56719712, "answer_date": "2019-06-22T22:44:13.017Z", "answer_score": 566 }
Please answer the following Stack Overflow question: Title: Calling shell functions with xargs <p>I am trying to use xargs to call a more complex function in parallel. </p> <pre><code>#!/bin/bash echo_var(){ echo $1 return 0 } seq -f "n%04g" 1 100 |xargs -n 1 -P 10 -i echo_var {} exit 0 </code></pre> <p>This returns the error</p> <pre><code>xargs: echo_var: No such file or directory </code></pre> <p>Any ideas on how I can use xargs to accomplish this, or any other solution(s) would be welcome.</p>
<p>Exporting the function should do it (untested):</p> <pre><code>export -f echo_var seq -f "n%04g" 1 100 | xargs -n 1 -P 10 -I {} bash -c 'echo_var "$@"' _ {} </code></pre> <p>You can use the builtin <code>printf</code> instead of the external <code>seq</code>:</p> <pre><code>printf "n%04g\n" {1..100} | xargs -n 1 -P 10 -I {} bash -c 'echo_var "$@"' _ {} </code></pre> <p>Also, using <code>return 0</code> and <code>exit 0</code> like that masks any error value that might be produced by the command preceding it. Also, if there's no error, it's the default and thus somewhat redundant.</p> <p>@phobic mentions that the Bash command <em><strong>could</strong></em> be simplified to</p> <pre><code>bash -c 'echo_var "{}"' </code></pre> <p>moving the <code>{}</code> directly inside it. <strong>But</strong> it's <strong>vulnerable to command injection</strong> as pointed out by @Sasha.</p> <p>Here is an example why you <strong>should not use</strong> the embedded format:</p> <pre><code>$ echo '$(date)' | xargs -I {} bash -c 'echo_var "{}"' Sun Aug 18 11:56:45 CDT 2019 </code></pre> <p>Another example of <strong>why not</strong>:</p> <pre><code>echo '\"; date\"' | xargs -I {} bash -c 'echo_var "{}"' </code></pre> <p>This is what is output <strong>using the safe format</strong>:</p> <pre><code>$ echo '$(date)' | xargs -I {} bash -c 'echo_var "$@"' _ {} $(date) </code></pre> <p>This is comparable to using <a href="https://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/" rel="noreferrer">parameterized</a> SQL <a href="https://en.wikipedia.org/wiki/Prepared_statement" rel="noreferrer">queries</a> to avoid <a href="https://rosettacode.org/wiki/Parametrized_SQL_statement" rel="noreferrer">injection</a>.</p> <p>I'm using <code>date</code> in a command substitution or in escaped quotes here instead of the <code>rm</code> command used in Sasha's comment since it's non-destructive.</p>
{ "question_id": 11003418, "question_date": "2012-06-12T19:23:12.483Z", "question_score": 237, "tags": "bash|sh|xargs", "answer_id": 11003457, "answer_date": "2012-06-12T19:26:02.587Z", "answer_score": 224 }
Please answer the following Stack Overflow question: Title: Is there a difference between foreach and map? <p>Ok this is more of a computer science question, than a question based on a particular language, but is there a difference between a map operation and a foreach operation? Or are they simply different names for the same thing?</p>
<p>Different.</p> <p>foreach iterates over a list and <strong>performs</strong> some operation with side effects to each list member (such as saving each one to the database for example)</p> <p>map iterates over a list, <strong>transforms</strong> each member of that list, and returns another list of the same size with the transformed members (such as converting a list of strings to uppercase)</p>
{ "question_id": 354909, "question_date": "2008-12-10T02:09:29.117Z", "question_score": 237, "tags": "foreach|language-agnostic|computer-science|map-function", "answer_id": 354915, "answer_date": "2008-12-10T02:14:53.393Z", "answer_score": 313 }
Please answer the following Stack Overflow question: Title: How to disable Diagnostic Tools? <p>When debugging a C# application in Visual Studio 2015, <strong>Diagnostic Tools</strong> starts automatically. I unchecked both checkboxes in <strong>Select Tools</strong>, but it doesn't seem to completely disable it.</p> <p>How do I turn it off (and on again later)?</p>
<p>If you want to disable the feature altogether you can currently do so from Tools &rarr; Options &rarr; Debugging &rarr; General &rarr; Enable Diagnostics Tools while debugging</p> <p><a href="https://i.stack.imgur.com/baZuP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/baZuP.png" alt="enter image description here"></a></p>
{ "question_id": 31904929, "question_date": "2015-08-09T13:48:27.650Z", "question_score": 237, "tags": "c#|visual-studio|visual-studio-2015|visual-studio-2022", "answer_id": 31904957, "answer_date": "2015-08-09T13:51:11.387Z", "answer_score": 411 }
Please answer the following Stack Overflow question: Title: Java "Virtual Machine" vs. Python "Interpreter" parlance? <p>It seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time.</p> <p>Both interpret byte codes; why call one a virtual machine and the other an interpreter?</p>
<p>A virtual machine is a virtual computing environment with a specific set of atomic well defined instructions that are supported independent of any specific language and it is generally thought of as a sandbox unto itself. The VM is analogous to an instruction set of a specific CPU and tends to work at a more fundamental level with very basic building blocks of such instructions (or byte codes) that are independent of the next. An instruction executes deterministically based only on the current state of the virtual machine and does not depend on information elsewhere in the instruction stream at that point in time.</p> <p>An interpreter on the other hand is more sophisticated in that it is tailored to parse a stream of some syntax that is of a specific language and of a specific grammer that must be decoded in the context of the surrounding tokens. You can't look at each byte or even each line in isolation and know exactly what to do next. The tokens in the language can't be taken in isolation like they can relative to the instructions (byte codes) of a VM.</p> <p>A Java compiler converts Java language into a byte-code stream no different than a C compiler converts C Language programs into assembly code. An interpreter on the other hand doesn't really convert the program into any well defined intermediate form, it just takes the program actions as a matter of the process of interpreting the source.</p> <p>Another test of the difference between a VM and an interpreter is whether you think of it as being language independent. What we know as the Java VM is not really Java specific. You could make a compiler from other languages that result in byte codes that can be run on the JVM. On the other hand, I don't think we would really think of "compiling" some other language other than Python into Python for interpretation by the Python interpreter.</p> <p>Because of the sophistication of the interpretation process, this can be a relatively slow process....specifically parsing and identifying the language tokens, etc. and understanding the context of the source to be able to undertake the execution process within the interpreter. To help accelerate such interpreted languages, this is where we can define intermediate forms of pre-parsed, pre-tokenized source code that is more readily directly interpreted. This sort of binary form is still interpreted at execution time, it is just starting from a much less human readable form to improve performance. However, the logic executing that form is not a virtual machine, because those codes still can't be taken in isolation - the context of the surrounding tokens still matter, they are just now in a different more computer efficient form.</p>
{ "question_id": 441824, "question_date": "2009-01-14T03:39:32.513Z", "question_score": 237, "tags": "java|python|jvm", "answer_id": 441973, "answer_date": "2009-01-14T05:06:47.097Z", "answer_score": 144 }
Please answer the following Stack Overflow question: Title: What framework for MVVM should I use? <p>I am developing an application with the MVVM model, but I have reached a point where I need to choose which framework to use.</p> <p>Among the possible options are:</p> <ul> <li>MVVM Toolkit </li> <li>MVVM Foundation </li> <li>WPF Application Framework (WAF) </li> <li>Light MVVM </li> <li>Caliburn </li> <li>Cinch </li> <li>Prism</li> <li>ReactiveUI</li> </ul> <p>In your experience, which is better?</p>
<p>It really depends on what you are trying to achieve, and how much infrastructure you want in place already, plus the ease with which you can find samples that help you out. I'm going to declare an interest here, because I've been actively involved in at least one MVVM framework, and I've had input into others through the WPF Disciples group, so I'm a little bit biased. Saying that, here goes:</p> <p>Microsofts <a href="http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=14962" rel="noreferrer">MVVM Toolkit</a> - this is still very much in the alpha stages. When it was originally released, it took a bit of a savaging from the Disciples because of what it didn't do. Saying that, MS is looking to beef this framework up so it's one to watch - it's just not ready yet.</p> <p><a href="http://mvvmfoundation.codeplex.com/" rel="noreferrer">MVVM Foundation</a> - ah Josh Smith's version of the framework. Josh is one of the daddies of MVVM, and has been a huge advocate and teacher of the pattern. As a result, a lot of what you'll find in other frameworks has Josh's fingerprints all over it. This framework is intended to provide the basics of MVVM, and not to address some of the more esoteric issues. Originally this was intended only for WPF, but people such as Laurent Bugnion and myself have added functionality/projects that mean this will be a Silverlight compatible framework as well.</p> <p><a href="http://waf.codeplex.com/" rel="noreferrer">WAF</a> - no experience of it, so I can't comment on it I'm afraid.</p> <p><a href="http://geekswithblogs.net/lbugnion/archive/2009/09/06/mvvm-light-toolkit-v1.1.1-whatrsquos-new.aspx" rel="noreferrer">MVVM Light</a> - Laurent Bugnion's take on it, and just updated to version 2. This is a very good framework, but again it's not intended to cover every single aspect of MVVM applications. Given Laurent's background, it has very strong Silverlight and Blendability support in it.</p> <p><em>Update</em> Laurent has just informed me that the .NET 3.5 and .NET 4.0 versions are feature compatible. Wau to go Laurent.</p> <p>Cinch - Sacha Barber's excellent WPF only MVVM framework. This covers more ground than the frameworks I've talked about above. It's an excellent framework, and takes advantage of concepts covered in Bill Kempf's excellent <a href="http://wpfonyx.codeplex.com/" rel="noreferrer">Onyx</a> project. Onyx is intended to complement MVVM frameworks, and adds in functionality that's typically been hard for people to do in MVVM/WPF. Again, originally intended to be WPF only, Onyx has progressed to include SL compatibility - work I am particularly proud to have been involved in.</p> <p><a href="http://www.codeplex.com/CompositeWPF" rel="noreferrer">Prism</a> - Again, I've never used it, but I've heard a lot of good things about it.</p> <p><a href="http://karlshifflett.wordpress.com/mvvm/wpf-line-of-business-demo-application-source/" rel="noreferrer">Ocean</a> - Karl Shifflett, Program Manager on the Cider team, recently released a fully featured WPF MVVM framework. Again, this is an excellent framework and has lots to recommend it.</p> <p>The bottom line is, download the different frameworks take a look at them and work out which one fits most intuitively with the way you think and with your requirements. If you think that you might want to support Silverlight from the same codebase then the WPF only frameworks should be discounted.</p>
{ "question_id": 1409553, "question_date": "2009-09-11T07:53:18.703Z", "question_score": 237, "tags": "wpf|mvvm|frameworks", "answer_id": 1409740, "answer_date": "2009-09-11T08:38:34.647Z", "answer_score": 195 }
Please answer the following Stack Overflow question: Title: AndroidViewModel vs ViewModel <p>With the introduction of the Android Architecture Components library, several new classes were introduced, including <code>AndroidViewModel</code> and <code>ViewModel</code>. However, I'm having trouble figuring out the difference between these two classes. The <a href="https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel.html" rel="noreferrer">documentation</a> succinctly describes <code>AndroidViewModel</code> as follows:</p> <blockquote> <p>Application context aware <code>ViewModel</code></p> </blockquote> <p>I appreciate the brevity, but what exactly does this imply? When should we choose to use <code>AndroidViewModel</code> over <code>ViewModel</code> and vice-versa?</p>
<h1>AndroidViewModel provides Application context</h1> <p>If you need to use context inside your Viewmodel you should use AndroidViewModel (AVM), because it contains the application context. To retrieve the context call <code>getApplication()</code>, otherwise use the regular ViewModel (VM).</p> <p>AndroidViewModel has <strong>application context</strong>. We all know <em>having static context instance is evil as it can cause memory leaks!!</em> However, <strong>having static Application instance is not as bad as you might think</strong> because there is only one Application instance in the running application.</p> <p>Therefore, using and having Application instance in a specific class is not a problem in general. But, if an Application instance references them, it is a problem because of the reference cycle problem.</p> <p><a href="https://www.philosophicalhacker.com/2015/07/14/why-static-references-to-application-contexts-are-probably-not-the-best-idea/" rel="noreferrer">See Also about Application Instance</a></p> <h1>AndroidViewModel Problematic for unit tests</h1> <p>AVM provides application context which is problematic for unit testing. Unit tests should not deal with any of the Android lifecycle, such as context.</p>
{ "question_id": 44148966, "question_date": "2017-05-24T04:24:20.153Z", "question_score": 237, "tags": "android|mvvm|viewmodel|android-architecture-components|android-viewmodel", "answer_id": 44155403, "answer_date": "2017-05-24T10:12:55.240Z", "answer_score": 304 }
Please answer the following Stack Overflow question: Title: Xcode iOS project only shows "My Mac 64-bit" but not simulator or device <p>This just started happening that my iOS project is only showing "My Mac 64-bit" rather than the Simulator or my iPhone to build to. I have no idea why this is happening. I do not think that I have changed anything.</p> <p><img src="https://i.stack.imgur.com/HAlhg.png" alt="enter image description here"></p> <p>I have my project set to iOS 5 as the base SDK, but no matter what I do it seems to never show my any other options to build for. I have restarted Xcode a few times, and still no luck.</p> <p>Why is the happening?</p> <p><strong>Xcode 4.2, Build 4D199</strong></p>
<p>I figured it out. I had to edit the scheme (Product->Scheme->Edit Scheme...), and for some reason no executable was selected. I chose my app, saved and now I have my simulator and device options back.</p>
{ "question_id": 8377970, "question_date": "2011-12-04T19:26:46.837Z", "question_score": 237, "tags": "ios|xcode|xcode4", "answer_id": 8378445, "answer_date": "2011-12-04T20:41:22.257Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: What's the '@' (at symbol) in the Redux @connect decorator? <p>I am learning Redux with React and stumbled upon this code. I am not sure if it is <a href="https://rackt.github.io/redux/index.html">Redux</a> specific or not, but I have seen the following code snippet in one of the examples.</p> <pre><code>@connect((state) =&gt; { return { key: state.a.b }; }) </code></pre> <p>While the functionality of <code>connect</code> is pretty straightforward, but I don't understand the <code>@</code> before <code>connect</code>. It isn't even a JavaScript operator if I am not wrong.</p> <p>Can someone explain please what is this and why is it used?</p> <p>Update: </p> <p>It is in fact a part of <a href="https://github.com/rackt/react-redux"><code>react-redux</code></a> which is used to connects a React component to a Redux store.</p>
<p>The <code>@</code> symbol is in fact a JavaScript expression <a href="https://github.com/wycats/javascript-decorators">currently proposed to signify <strong>decorators</strong></a>:</p> <blockquote> <p>Decorators make it possible to annotate and modify classes and properties at design time.</p> </blockquote> <p>Here's an example of setting up Redux without and with a decorator:</p> <p><strong>Without a decorator</strong></p> <pre><code>import React from 'react'; import * as actionCreators from './actionCreators'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; function mapStateToProps(state) { return { todos: state.todos }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actionCreators, dispatch) }; } class MyApp extends React.Component { // ...define your main app here } export default connect(mapStateToProps, mapDispatchToProps)(MyApp); </code></pre> <p><strong>Using a decorator</strong></p> <pre><code>import React from 'react'; import * as actionCreators from './actionCreators'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; function mapStateToProps(state) { return { todos: state.todos }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actionCreators, dispatch) }; } @connect(mapStateToProps, mapDispatchToProps) export default class MyApp extends React.Component { // ...define your main app here } </code></pre> <p>Both examples above are equivalent, it's just a matter of preference. Also, the decorator syntax isn't built into any Javascript runtimes yet, and is still experimental and subject to change. If you want to use it, it is available using <a href="https://babeljs.io/">Babel</a>.</p>
{ "question_id": 32646920, "question_date": "2015-09-18T08:07:08.780Z", "question_score": 237, "tags": "javascript|reactjs|decorator|redux", "answer_id": 32675956, "answer_date": "2015-09-20T04:56:50.433Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: Is it OK to leave a channel open? <p>Is it OK to leave a Go channel open forever (never close the channel) if I never check for its state? Will it lead to memory leaks? Is the following code OK?</p> <pre><code>func (requestCh chan&lt;- Request) GetResponse(data RequestData) Response { reply := make(chan Response) requestCh &lt;- Request{data: data, replyCh: reply} return &lt;-reply } </code></pre>
<p>It's OK to leave a Go channel open forever and never close it. When the channel is no longer used, it will be garbage collected.</p> <blockquote> <p>Note that it is only necessary to close a channel if the receiver is looking for a close. Closing the channel is a control signal on the channel indicating that no more data follows. </p> <p><a href="https://groups.google.com/d/msg/golang-nuts/pZwdYRGxCIk/qpbHxRRPJdUJ">Design Question: Channel Closing</a></p> </blockquote>
{ "question_id": 8593645, "question_date": "2011-12-21T17:12:38.727Z", "question_score": 237, "tags": "go|channel", "answer_id": 8593986, "answer_date": "2011-12-21T17:40:30.353Z", "answer_score": 362 }
Please answer the following Stack Overflow question: Title: Restart/undo conflict resolution in a single file <p>In a larger git merge with several conflicting files, I incorrectly marked a file as resolved (using <code>git add FILE</code> after some editing)</p> <p>Now I'd like to undo my conflict resolution attempt and start over resolving that file.</p> <p>How can I do that?</p>
<p>Found the solution here: <a href="http://gitster.livejournal.com/43665.html">http://gitster.livejournal.com/43665.html</a></p> <pre><code>git checkout -m FILE </code></pre> <p>This restores the unresolved state, including all information about parent and merge base, which allows restarting the resolution.</p>
{ "question_id": 14409420, "question_date": "2013-01-18T23:40:16.610Z", "question_score": 237, "tags": "git|git-merge", "answer_id": 14409744, "answer_date": "2013-01-19T00:18:05.313Z", "answer_score": 442 }
Please answer the following Stack Overflow question: Title: BindingFlags.IgnoreCase not working for Type.GetProperty()? <p>Imagine the following</p> <p>A type T has a field Company. When executing the following method it works perfectly:</p> <pre><code>Type t = typeof(T); t.GetProperty("Company") </code></pre> <p>Whith the following call I get null though</p> <pre><code>Type t = typeof(T); t.GetProperty("company", BindingFlags.IgnoreCase) </code></pre> <p>Anybody got an idea?</p>
<p>You've overwritten the default look-up flags, if you specify new flags you need to provide all the info so that the property can be found. For example: <code>BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance</code></p>
{ "question_id": 264745, "question_date": "2008-11-05T10:05:10.533Z", "question_score": 237, "tags": "c#|reflection|getproperty|bindingflags", "answer_id": 264752, "answer_date": "2008-11-05T10:09:35.827Z", "answer_score": 483 }
Please answer the following Stack Overflow question: Title: What kind of leaks does automatic reference counting in Objective-C not prevent or minimize? <p>In the Mac and iOS platforms, memory leaks are often caused by unreleased pointers. Traditionally, it has always been of utmost importance to check your allocs, copies and retains to make sure each has a corresponding release message.</p> <p>The toolchain that comes with Xcode 4.2 introduces automatic reference counting (ARC) with the latest version of the <a href="http://llvm.org">LLVM compiler</a>, that totally does away with this problem by getting the compiler to memory-manage your stuff for you. That's pretty cool, and it does cut lots of unnecessary, mundane development time and prevent a lot of careless memory leaks that are easy to fix with proper retain/release balance. Even autorelease pools need to be managed differently when you enable ARC for your Mac and iOS apps (as you shouldn't allocate your own <code>NSAutoreleasePool</code>s anymore).</p> <p>But what <em>other</em> memory leaks does it <em>not</em> prevent that I still have to watch out for?</p> <p>As a bonus, what are the differences between ARC on Mac OS X and iOS, and garbage collection on Mac OS X?</p>
<p>The primary memory-related problem you'll still need to be aware of is retain cycles. This occurs when one object has a strong pointer to another, but the target object has a strong pointer back to the original. Even when all other references to these objects are removed, they still will hold on to one another and will not be released. This can also happen indirectly, by a chain of objects that might have the last one in the chain referring back to an earlier object.</p> <p>It is for this reason that the <code>__unsafe_unretained</code> and <code>__weak</code> ownership qualifiers exist. The former will not retain any object it points to, but leaves open the possibility of that object going away and it pointing to bad memory, whereas the latter doesn't retain the object and automatically sets itself to nil when its target is deallocated. Of the two, <code>__weak</code> is generally preferred on platforms that support it.</p> <p>You would use these qualifiers for things like delegates, where you don't want the object to retain its delegate and potentially lead to a cycle.</p> <p>Another couple of significant memory-related concerns are the handling of Core Foundation objects and memory allocated using <code>malloc()</code> for types like <code>char*</code>. ARC does not manage these types, only Objective-C objects, so you'll still need to deal with them yourself. Core Foundation types can be particularly tricky, because sometimes they need to be bridged across to matching Objective-C objects, and vice versa. This means that control needs to be transferred back and forth from ARC when bridging between CF types and Objective-C. Some keywords related to this bridging have been added, and Mike Ash has a great description of various bridging cases in <a href="http://www.mikeash.com/pyblog/friday-qa-2011-09-30-automatic-reference-counting.html" rel="nofollow noreferrer">his lengthy ARC writeup</a>.</p> <p>In addition to this, there are several other less frequent, but still potentially problematic cases, which the <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html" rel="nofollow noreferrer">published specification</a> goes into in detail.</p> <p>Much of the new behavior, based on keeping objects around as long as there is a strong pointer to them, is very similar to garbage collection on the Mac. However, the technical underpinnings are very different. Rather than having a garbage collector process that runs at regular intervals to clean up objects no longer being pointed to, this style of memory management relies on the rigid retain / release rules we all need to obey in Objective-C. </p> <p>ARC simply takes the repetitive memory management tasks we've had to do for years and offloads them to the compiler so we never have to worry about them again. This way, you don't have the halting problems or sawtooth memory profiles experienced on garbage collected platforms. I've experienced both of these in my garbage collected Mac applications, and am eager to see how they behave under ARC.</p> <p>For more on garbage collection vs. ARC, see <a href="https://web.archive.org/web/20150713205910/http://lists.apple.com/archives/objc-language/2011/Jun/msg00013.html" rel="nofollow noreferrer">this very interesting response by Chris Lattner on the Objective-C mailing list</a>, where he lists many advantages of ARC over Objective-C 2.0 garbage collection. I've run into several of the GC issues he describes.</p>
{ "question_id": 6260256, "question_date": "2011-06-07T03:08:50.047Z", "question_score": 237, "tags": "ios|objective-c|macos|memory-leaks|automatic-ref-counting", "answer_id": 6388601, "answer_date": "2011-06-17T16:11:08.727Z", "answer_score": 263 }
Please answer the following Stack Overflow question: Title: Is there a vim command to relocate a tab? <p>How can I change the position / order of my current tab in <code>Vim</code>? For example, if I want to reposition my current tab to be the first tab?</p>
<p>You can relocate a tab with <code>:tabm</code> using either relative or zero-index absolute arguments.</p> <p>absolute:</p> <ul> <li>Move tab to position i: <code>:tabm i</code></li> </ul> <p>relative:</p> <ul> <li>Move tab i positions to the right: <code>:tabm +i</code></li> <li>Move tab i positions to the left: <code>:tabm -i</code></li> </ul> <p>It's a relatively new feature. So if it doesn't work try updating your vim.</p>
{ "question_id": 7961581, "question_date": "2011-11-01T01:23:15.170Z", "question_score": 237, "tags": "vim|tabs", "answer_id": 18147532, "answer_date": "2013-08-09T13:15:51.180Z", "answer_score": 324 }
Please answer the following Stack Overflow question: Title: Extracting hours from a DateTime (SQL Server 2005) <p>I can extract the month and day by using <code>Day(Date())</code>, <code>Month(Date())</code>. I can't extract hours, with <code>HOUR(Date())</code>. I get the following error.</p> <pre><code>'HOUR' is not a recognized built-in function name. </code></pre> <p>How can I extract hours?</p>
<pre><code>SELECT DATEPART(HOUR, GETDATE()); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms174420%28loband%29.aspx" rel="noreferrer"><code>DATEPART</code> documentation</a></p>
{ "question_id": 1114307, "question_date": "2009-07-11T18:09:35.433Z", "question_score": 236, "tags": "sql|tsql|datetime|sql-server-2005|hour", "answer_id": 1114314, "answer_date": "2009-07-11T18:12:51.947Z", "answer_score": 438 }
Please answer the following Stack Overflow question: Title: Function return value in PowerShell <p>I have developed a PowerShell function that performs a number of actions involving provisioning <a href="http://en.wikipedia.org/wiki/Microsoft_SharePoint" rel="noreferrer">SharePoint</a> Team sites. Ultimately, I want the function to return the URL of the provisioned site as a String so at the end of my function I have the following code:</p> <pre><code>$rs = $url.ToString(); return $rs; </code></pre> <p>The code that calls this function looks like:</p> <pre><code>$returnURL = MyFunction -param 1 ... </code></pre> <p>So I am expecting a String, however it's not. Instead, it is an object of type System.Management.Automation.PSMethod. Why is it returning that type instead of a String type?</p>
<p>PowerShell has really wacky return semantics - at least when viewed from a more traditional programming perspective. There are two main ideas to wrap your head around:</p> <ul> <li>All output is captured, and returned</li> <li>The return keyword really just indicates a logical exit point</li> </ul> <p>Thus, the following two script blocks will do effectively the exact same thing:</p> <pre><code>$a = "Hello, World" return $a </code></pre> <p> </p> <pre><code>$a = "Hello, World" $a return </code></pre> <p>The $a variable in the second example is left as output on the pipeline and, as mentioned, all output is returned. In fact, in the second example you could omit the return entirely and you would get the same behavior (the return would be implied as the function naturally completes and exits).</p> <p>Without more of your function definition I can't say why you are getting a PSMethod object. My guess is that you probably have something a few lines up that is not being captured and is being placed on the output pipeline.</p> <p>It is also worth noting that you <em>probably</em> don't need those semicolons - unless you are nesting multiple expressions on a single line. </p> <p>You can read more about the return semantics on the <a href="http://technet.microsoft.com/en-us/library/hh847760.aspx" rel="noreferrer">about_Return</a> page on TechNet, or by invoking the <code>help return</code> command from PowerShell itself.</p>
{ "question_id": 10286164, "question_date": "2012-04-23T18:28:39.173Z", "question_score": 236, "tags": "powershell", "answer_id": 10288256, "answer_date": "2012-04-23T21:01:56.683Z", "answer_score": 316 }
Please answer the following Stack Overflow question: Title: sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64') <p>I am using sklearn and having a problem with the affinity propagation. I have built an input matrix and I keep getting the following error. </p> <pre><code>ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). </code></pre> <p>I have run</p> <pre><code>np.isnan(mat.any()) #and gets False np.isfinite(mat.all()) #and gets True </code></pre> <p>I tried using</p> <pre><code>mat[np.isfinite(mat) == True] = 0 </code></pre> <p>to remove the infinite values but this did not work either. What can I do to get rid of the infinite values in my matrix, so that I can use the affinity propagation algorithm?</p> <p>I am using anaconda and python 2.7.9.</p>
<p>This might happen inside scikit, and it depends on what you're doing. I recommend reading the documentation for the functions you're using. You might be using one which depends e.g. on your matrix being positive definite and not fulfilling that criteria.</p> <p><strong>EDIT</strong>: How could I miss that:</p> <pre><code>np.isnan(mat.any()) #and gets False np.isfinite(mat.all()) #and gets True </code></pre> <p>is obviously wrong. Right would be:</p> <pre><code>np.any(np.isnan(mat)) </code></pre> <p>and</p> <pre><code>np.all(np.isfinite(mat)) </code></pre> <p>You want to check whether any of the elements are NaN, and not whether the return value of the <code>any</code> function is a number...</p>
{ "question_id": 31323499, "question_date": "2015-07-09T16:40:01.827Z", "question_score": 236, "tags": "python|python-2.7|scikit-learn|valueerror", "answer_id": 31323566, "answer_date": "2015-07-09T16:43:31.247Z", "answer_score": 155 }
Please answer the following Stack Overflow question: Title: jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points) <p>What is the best way to restrict "number"-only input for textboxes?</p> <p>I am looking for something that allows decimal points.</p> <p>I see a lot of examples. But have yet to decide which one to use.</p> <p><strong>Update from Praveen Jeganathan</strong></p> <p>No more plugins, jQuery has implemented its own <code>jQuery.isNumeric()</code> added in v1.7. See: <a href="https://stackoverflow.com/a/20186188/66767">https://stackoverflow.com/a/20186188/66767</a></p>
<h1>Update</h1> <p>There is a new and very simple solution for this:</p> <blockquote> <p>It allows you to use <strong>any</strong> kind of input filter on a text <code>&lt;input&gt;</code>, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.</p> </blockquote> <p>See <a href="https://stackoverflow.com/a/995193/1070129">this answer</a> or try it yourself <a href="https://jsfiddle.net/emkey08/tvx5e7q3" rel="noreferrer">on JSFiddle</a>.</p> <h1>jquery.numeric plugin</h1> <p>I've successfully implemented many forms with the <a href="https://github.com/SamWM/jQuery-Plugins/blob/master/numeric/jquery.numeric.js" rel="noreferrer">jquery.numeric</a> plugin.</p> <pre><code>$(document).ready(function(){ $(".numeric").numeric(); }); </code></pre> <p>Moreover this works with textareas also!</p> <p>However, note that Ctrl+A, Copy+Paste (via context menu) and Drag+Drop will <strong>not</strong> work as expected.</p> <h1>HTML 5</h1> <p>With wider support for the HTML 5 standard, we can use <code>pattern</code> attribute and <code>number</code> type for <code>input</code> elements to restrict number only input. In some browsers (notably Google Chrome), it works to restrict pasting non-numeric content as well. More information about <code>number</code> and other newer input types is available <a href="http://html5doctor.com/html5-forms-input-types/" rel="noreferrer">here</a>.</p>
{ "question_id": 891696, "question_date": "2009-05-21T07:04:48.677Z", "question_score": 236, "tags": "jquery|validation|isnumeric", "answer_id": 891749, "answer_date": "2009-05-21T07:20:01.110Z", "answer_score": 199 }
Please answer the following Stack Overflow question: Title: How do I apply the for-each loop to every character in a String? <p>So I want to iterate for each character in a string.</p> <p>So I thought:</p> <pre><code>for (char c : "xyz") </code></pre> <p>but I get a compiler error:</p> <pre><code>MyClass.java:20: foreach not applicable to expression type </code></pre> <p>How can I do this?</p>
<p>The easiest way to for-each every <code>char</code> in a <code>String</code> is to use <code>toCharArray()</code>:</p> <pre><code>for (char ch: "xyz".toCharArray()) { } </code></pre> <p>This gives you the conciseness of for-each construct, but unfortunately <code>String</code> (which is immutable) must perform a defensive copy to generate the <code>char[]</code> (which is mutable), so there is some cost penalty.</p> <p>From the <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#toCharArray%28%29" rel="noreferrer">documentation</a>:</p> <blockquote> <p>[<code>toCharArray()</code> returns] <em>a newly allocated character array</em> whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.</p> </blockquote> <p>There are more verbose ways of iterating over characters in an array (regular for loop, <code>CharacterIterator</code>, etc) but if you're willing to pay the cost <code>toCharArray()</code> for-each is the most concise.</p>
{ "question_id": 2451650, "question_date": "2010-03-16T01:53:56.443Z", "question_score": 236, "tags": "java|string|loops|foreach|char", "answer_id": 2451660, "answer_date": "2010-03-16T01:56:50.117Z", "answer_score": 411 }
Please answer the following Stack Overflow question: Title: Error: unable to verify the first certificate in nodejs <p>I'm trying to download a file from jira server using an URL but I'm getting an error. how to include certificate in the code to verify?</p> <p><strong>Error:</strong></p> <pre><code>Error: unable to verify the first certificate in nodejs at Error (native) at TLSSocket.&lt;anonymous&gt; (_tls_wrap.js:929:36) at TLSSocket.emit (events.js:104:17) at TLSSocket._finishInit (_tls_wrap.js:460:8) </code></pre> <p><strong>My Nodejs code:</strong></p> <pre><code>var https = require(&quot;https&quot;); var fs = require('fs'); var options = { host: 'jira.example.com', path: '/secure/attachment/206906/update.xlsx' }; https.get(options, function (http_res) { var data = &quot;&quot;; http_res.on(&quot;data&quot;, function (chunk) { data += chunk; }); http_res.on(&quot;end&quot;, function () { var file = fs.createWriteStream(&quot;file.xlsx&quot;); data.pipe(file); }); }); </code></pre>
<h3>Try adding the appropriate root certificate</h3> <p>This is always going to be a much safer option than just blindly accepting unauthorised end points, which should in turn only be used as a last resort.</p> <p>This can be as simple as adding</p> <pre><code>require('https').globalAgent.options.ca = require('ssl-root-cas/latest').create(); </code></pre> <p>to your application.</p> <p>The <a href="https://www.npmjs.com/package/ssl-root-cas" rel="noreferrer">SSL Root CAs npm package</a> (as used here) is a very useful package regarding this problem.</p>
{ "question_id": 31673587, "question_date": "2015-07-28T10:23:06.553Z", "question_score": 236, "tags": "node.js|ssl-certificate|jira", "answer_id": 32440021, "answer_date": "2015-09-07T13:35:00.530Z", "answer_score": 167 }
Please answer the following Stack Overflow question: Title: How to get child element by class name? <p>I'm trying to get the child span that has a class = 4. Here is an example element:</p> <pre><code>&lt;div id="test"&gt; &lt;span class="one"&gt;&lt;/span&gt; &lt;span class="two"&gt;&lt;/span&gt; &lt;span class="three"&gt;&lt;/span&gt; &lt;span class="four"&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>The tools I have available are JS and YUI2. I can do something like this:</p> <pre><code>doc = document.getElementById('test'); notes = doc.getElementsByClassName('four'); //or doc = YAHOO.util.Dom.get('#test'); notes = doc.getElementsByClassName('four'); </code></pre> <p>These do not work in IE. I get an error that the object (doc) doesn't support this method or property (getElementsByClassName). I've tried a few examples of cross browser implementations of getElementsByClassName but I could not get them to work and still got that error.</p> <p>I think what I need is a cross browser getElementsByClassName or I need to use doc.getElementsByTagName('span') and loop through until I find class 4. I'm not sure how to do that though. </p>
<p>Use <code>doc.childNodes</code> to iterate through each <code>span</code>, and then filter the one whose <code>className</code> equals <code>4</code>:</p> <pre><code>var doc = document.getElementById("test"); var notes = null; for (var i = 0; i &lt; doc.childNodes.length; i++) { if (doc.childNodes[i].className == "4") { notes = doc.childNodes[i]; break; } } </code></pre> <p>​</p>
{ "question_id": 12166753, "question_date": "2012-08-28T20:05:50.803Z", "question_score": 236, "tags": "javascript|yui", "answer_id": 12166811, "answer_date": "2012-08-28T20:10:26.357Z", "answer_score": 118 }
Please answer the following Stack Overflow question: Title: HTML encoding issues - "Â" character showing up instead of "&nbsp;" <p>I've got a legacy app just starting to misbehave, for whatever reason I'm not sure. It generates a bunch of HTML that gets turned into PDF reports by ActivePDF.</p> <p>The process works like this:</p> <ol> <li>Pull an HTML template from a DB with tokens in it to be replaced (e.g. "~CompanyName~", "~CustomerName~", etc.)</li> <li>Replace the tokens with real data</li> <li>Tidy the HTML with a simple regex function that property formats HTML tag attribute values (ensures quotation marks, etc, since ActivePDF's rendering engine hates anything but single quotes around attribute values)</li> <li>Send off the HTML to a web service that creates the PDF.</li> </ol> <p>Somewhere in that mess, the non-breaking spaces from the HTML template (the <code>&amp;nbsp;</code>s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character when viewing the document in a browser (FireFox). ActivePDF pukes on these non-UTF8 characters.</p> <p>My question: since I don't know where the problem stems from and don't have time to investigate it, is there an easy way to re-encode or find-and-replace the bad characters? I've tried sending it through this little function I threw together, but it <strike>turns it all into gobbledegook</strike> doesn't change anything.</p> <pre><code>Private Shared Function ConvertToUTF8(ByVal html As String) As String Dim isoEncoding As Encoding = Encoding.GetEncoding("iso-8859-1") Dim source As Byte() = isoEncoding.GetBytes(html) Return Encoding.UTF8.GetString(Encoding.Convert(isoEncoding, Encoding.UTF8, source)) End Function </code></pre> <p>Any ideas?</p> <p><strong>EDIT:</strong></p> <p>I'm getting by with this for now, though it hardly seems like a good solution:</p> <pre><code>Private Shared Function ReplaceNonASCIIChars(ByVal html As String) As String Return Regex.Replace(html, "[^\u0000-\u007F]", "&amp;nbsp;") End Function </code></pre>
<blockquote> <p>Somewhere in that mess, the non-breaking spaces from the HTML template (the &nbsp;s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character</p> </blockquote> <p>That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as <code>" "</code>. That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.</p> <p>What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your <code>&amp;nbsp;</code> strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.</p> <p>Well anyway, for now you can add one of the following to your document's <code>&lt;head&gt;</code> and see if that makes it look right in the browser:</p> <ul> <li>for HTML4: <code>&lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" /&gt;</code></li> <li>for HTML5: <code>&lt;meta charset="utf-8"&gt;</code></li> </ul> <p>If you've done that, then any remaining problem is ActivePDF's fault.</p>
{ "question_id": 1461907, "question_date": "2009-09-22T18:48:07.023Z", "question_score": 236, "tags": "html|vb.net|encoding|utf-8|iso-8859-1", "answer_id": 1462039, "answer_date": "2009-09-22T19:13:53.790Z", "answer_score": 372 }
Please answer the following Stack Overflow question: Title: Updates were rejected because the remote contains work that you do not have locally <p>I'm working on a team with a few developers using git on BitBucket. We are all working on a <code>dev</code> branch, not pushing to <code>master</code> until a release.</p> <p>One of the developers committed incorrect code that overwrote my own by accident, and now I am trying to push the correct code back to the repo. I have been reading about this error for a few days now, I can't push to the repo anymore because I am getting the following error:</p> <pre><code> ! [rejected] master -&gt; dev (fetch first) error: failed to push some refs to 'https://[email protected]/repo_user/repo_name.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. </code></pre> <p>I follow the instructions and <code>pull</code>, but then I receive a merge conflict. After entering a message for the merge conflict, my local code is now the incorrect code that the other developer uploaded by accident (as expected from the <code>pull</code>). So I replace the incorrect code with the backup I copied before committing, and when I try to push again, I get the same error.</p> <p>It is really frustrating, I really want to help out my team and contribute, but I can't because of this error. Does anyone know how to solve this issue? I would very much appreciate any help.</p> <p>These are the commands I run in order to commit if it helps anyone out:</p> <pre><code>git pull remotename master:dev git add --all git commit -m &quot;some message&quot; git pull remotename master:dev git push remotename master:dev </code></pre> <p>I would have thought that if I kept this order, I would not receive merge conflicts. I guess I was wrong. Thanks again</p> <p>Update: I should add that I have looked for a few hours on Google and StackOverflow, and followed different instructions, but I still can't <code>push</code> to the <code>dev</code> branch.</p>
<p><code>git pull &lt;remote&gt; master:dev</code> will fetch the <code>remote/master</code> branch and merge it into your <code>local/dev</code> branch.</p> <p><code>git pull &lt;remote&gt; dev</code> will fetch the <code>remote/dev</code> branch, and merge it into your current branch.</p> <p>I think you said the conflicting commit is on <code>remote/dev</code>, so that is the branch you probably intended to fetch and merge.</p> <p>In that case, you weren't actually merging the conflict into your local branch, which is sort of weird since you said you saw the incorrect code in your working copy. You might want to check what is going on in <code>remote/master</code>.</p>
{ "question_id": 24357108, "question_date": "2014-06-23T00:44:20.443Z", "question_score": 236, "tags": "git|version-control|merge|commit|bitbucket", "answer_id": 24357784, "answer_date": "2014-06-23T02:45:01.690Z", "answer_score": 77 }
Please answer the following Stack Overflow question: Title: SQL WHERE ID IN (id1, id2, ..., idn) <p>I need to write a query to retrieve a big list of ids.</p> <p>We do support many backends (MySQL, Firebird, SQLServer, Oracle, PostgreSQL ...) so I need to write a standard SQL.</p> <p>The size of the id set could be big, the query would be generated programmatically. So, what is the best approach?</p> <h3>1) Writing a query using IN</h3> <pre><code>SELECT * FROM TABLE WHERE ID IN (id1, id2, ..., idn) </code></pre> <p>My question here is. What happens if n is very big? Also, what about performance?</p> <h3>2) Writing a query using OR</h3> <pre><code>SELECT * FROM TABLE WHERE ID = id1 OR ID = id2 OR ... OR ID = idn </code></pre> <p>I think that this approach does not have n limit, but what about performance if n is very big?</p> <h3>3) Writing a programmatic solution:</h3> <pre><code> foreach (var id in myIdList) { var item = GetItemByQuery(&quot;SELECT * FROM TABLE WHERE ID = &quot; + id); myObjectList.Add(item); } </code></pre> <p>We experienced some problems with this approach when the database server is queried over the network. Normally is better to do one query that retrieve all results versus making a lot of small queries. Maybe I'm wrong.</p> <p>What would be a correct solution for this problem?</p>
<p>Option 1 is the only good solution.</p> <h3>Why?</h3> <ul> <li><p>Option 2 does the same but you repeat the column name lots of times; additionally the SQL engine doesn't immediately know that you want to check if the value is one of the values in a fixed list. However, a good SQL engine could optimize it to have equal performance like with <code>IN</code>. There's still the readability issue though...</p></li> <li><p>Option 3 is simply horrible performance-wise. It sends a query every loop and hammers the database with small queries. It also prevents it from using any optimizations for "value is one of those in a given list"</p></li> </ul>
{ "question_id": 5803472, "question_date": "2011-04-27T11:40:07.653Z", "question_score": 236, "tags": "sql|select", "answer_id": 5803519, "answer_date": "2011-04-27T11:44:39.063Z", "answer_score": 145 }
Please answer the following Stack Overflow question: Title: How to check if a folder exists? <p>I am playing a bit with the new Java 7 IO features. Actually I am trying to retrieve all the XML files in a folder. However this throws an exception when the folder does not exist. How can I check if the folder exists using the new IO?</p> <pre><code>public UpdateHandler(String release) { log.info(&quot;searching for configuration files in folder &quot; + release); Path releaseFolder = Paths.get(release); try(DirectoryStream&lt;Path&gt; stream = Files.newDirectoryStream(releaseFolder, &quot;*.xml&quot;)){ for (Path entry: stream){ log.info(&quot;working on file &quot; + entry.getFileName()); } } catch (IOException e){ log.error(&quot;error while retrieving update configuration files &quot; + e.getMessage()); } } </code></pre>
<p>Using <code>java.nio.file.Files</code>:</p> <pre><code>Path path = ...; if (Files.exists(path)) { // ... } </code></pre> <p>You can optionally pass this method <code>LinkOption</code> values:</p> <pre><code>if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) { </code></pre> <p>There's also a method <code>notExists</code>:</p> <pre><code>if (Files.notExists(path)) { </code></pre>
{ "question_id": 15571496, "question_date": "2013-03-22T13:25:36.680Z", "question_score": 236, "tags": "java", "answer_id": 15571626, "answer_date": "2013-03-22T13:30:57.900Z", "answer_score": 313 }
Please answer the following Stack Overflow question: Title: CSS selector based on element text? <p>Is there a way to select an element in css based on element text?</p> <p>ie:</p> <pre><code>li[text=*foo] &lt;li&gt;foo&lt;/li&gt; &lt;li&gt;bar&lt;/li&gt; </code></pre> <p>That probably doesn't work.</p> <p>Edit: Also only need to support Chrome.</p>
<p>Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.</p>
{ "question_id": 5441680, "question_date": "2011-03-26T10:25:11.200Z", "question_score": 236, "tags": "css|css-selectors", "answer_id": 5441705, "answer_date": "2011-03-26T10:29:32.343Z", "answer_score": 90 }
Please answer the following Stack Overflow question: Title: How to wait for 2 seconds? <p>How does one cause a delay in execution for a specified number of seconds?</p> <p>This doesn't do it:</p> <pre><code>WAITFOR DELAY '00:02'; </code></pre> <p>What is the correct format?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms187331.aspx">The documentation for <code>WAITFOR()</code></a> doesn't explicitly lay out the required string format. </p> <p>This will wait for 2 seconds:</p> <pre><code>WAITFOR DELAY '00:00:02'; </code></pre> <p>The format is <code>hh:mi:ss.mmm</code>.</p>
{ "question_id": 7676164, "question_date": "2011-10-06T14:52:55.327Z", "question_score": 236, "tags": "sql-server|sql-server-2008|tsql", "answer_id": 7676272, "answer_date": "2011-10-06T14:59:50.960Z", "answer_score": 457 }
Please answer the following Stack Overflow question: Title: How to capitalize the first letter of word in a string using Java? <p>Example strings</p> <pre><code>one thousand only two hundred twenty seven </code></pre> <p>How do I change the first character of a string in capital letter and not change the case of any of the other letters?</p> <p>After the change it should be:</p> <pre><code>One thousand only Two hundred Twenty Seven </code></pre> <p>Note: I don't want to use the apache.commons.lang.WordUtils to do this.</p>
<p>If you only want to capitalize the first letter of a string named <code>input</code> and leave the rest alone:</p> <pre><code>String output = input.substring(0, 1).toUpperCase() + input.substring(1); </code></pre> <p>Now <code>output</code> will have what you want. Check that your <code>input</code> is at least one character long before using this, otherwise you'll get an exception.</p>
{ "question_id": 5725892, "question_date": "2011-04-20T05:27:00.440Z", "question_score": 236, "tags": "java", "answer_id": 5725949, "answer_date": "2011-04-20T05:34:09.560Z", "answer_score": 557 }
Please answer the following Stack Overflow question: Title: How to initialize array to 0 in C? <p>I need a big null array in C as a global. Is there any way to do this besides typing out</p> <pre><code>char ZEROARRAY[1024] = {0, 0, 0, /* ... 1021 more times... */ }; </code></pre> <p>?</p>
<p>Global variables and static variables are automatically initialized to zero. If you have simply</p> <pre><code>char ZEROARRAY[1024]; </code></pre> <p>at global scope it will be all zeros at runtime. But actually there <em>is</em> a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:</p> <pre><code>char ZEROARRAY[1024] = {0}; </code></pre> <p>The compiler would fill the unwritten entries with zeros. Alternatively you could use <code>memset</code> to initialize the array at program startup:</p> <pre><code>memset(ZEROARRAY, 0, 1024); </code></pre> <p>That would be useful if you had changed it and wanted to reset it back to all zeros.</p>
{ "question_id": 2589749, "question_date": "2010-04-07T03:03:28.157Z", "question_score": 236, "tags": "c|arrays|initialization", "answer_id": 2589751, "answer_date": "2010-04-07T03:04:22.620Z", "answer_score": 381 }
Please answer the following Stack Overflow question: Title: How can I remove the extension of a filename in a shell script? <p>What's wrong with the following code?</p> <pre><code>name='$filename | cut -f1 -d'.'' </code></pre> <p>As is, I get the literal string <code>$filename | cut -f1 -d'.'</code>, but if I remove the quotes I don't get anything. Meanwhile, typing</p> <pre><code>"test.exe" | cut -f1 -d'.' </code></pre> <p>in a shell gives me the output I want, <code>test</code>. I already know <code>$filename</code> has been assigned the right value. What I want to do is assign to a variable the filename without the extension.</p>
<p>You should be using the <a href="https://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution" rel="noreferrer">command substitution</a> syntax <code>$(command)</code> when you want to execute a command in script/command.</p> <p>So your line would be </p> <pre><code>name=$(echo "$filename" | cut -f 1 -d '.') </code></pre> <p>Code explanation:</p> <ol> <li><code>echo</code> get the value of the variable <code>$filename</code> and send it to standard output</li> <li>We then grab the output and pipe it to the <code>cut</code> command</li> <li>The <code>cut</code> will use the . as delimiter (also known as separator) for cutting the string into segments and by <code>-f</code> we select which segment we want to have in output</li> <li>Then the <code>$()</code> command substitution will get the output and return its value</li> <li>The returned value will be assigned to the variable named <code>name</code></li> </ol> <p>Note that this gives the portion of the variable up to the first period <code>.</code>:</p> <pre><code>$ filename=hello.world $ echo "$filename" | cut -f 1 -d '.' hello $ filename=hello.hello.hello $ echo "$filename" | cut -f 1 -d '.' hello $ filename=hello $ echo "$filename" | cut -f 1 -d '.' hello </code></pre>
{ "question_id": 12152626, "question_date": "2012-08-28T04:06:05.333Z", "question_score": 236, "tags": "bash|shell|sh|cut|gnu-coreutils", "answer_id": 12152669, "answer_date": "2012-08-28T04:10:56.783Z", "answer_score": 174 }
Please answer the following Stack Overflow question: Title: Abort a Git Merge <p>I am working on a project using Git as the VCS. I got a branch <code>xyz</code> cut from the mainline branch of master. After working for a while, I committed my code and took a pull of the branch mainline.</p> <p>The pull was fine. I then merged the code with master. After the merge, there were problems in certain files. I have not committed the code after merging. Can someone please guide as to how I can abort this merge and bring my branch where I am working currently to the state where it was before I merged it?</p>
<p>as long as you did not commit you can type</p> <pre><code>git merge --abort </code></pre> <p>just as the command line suggested.</p>
{ "question_id": 44048982, "question_date": "2017-05-18T13:22:04.777Z", "question_score": 236, "tags": "git|git-merge", "answer_id": 44049103, "answer_date": "2017-05-18T13:27:35.007Z", "answer_score": 542 }
Please answer the following Stack Overflow question: Title: MySQL's now() +1 day <p>I'm using <code>now()</code> in MySQL query. </p> <pre><code>INSERT INTO table SET data = '$data', date = now() </code></pre> <p>But I want to add 1 day to this date (so that <code>date</code> should contain tomorrow).<br> Is it possible?</p>
<p>You can use:</p> <pre><code>NOW() + INTERVAL 1 DAY </code></pre> <p>If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:</p> <pre><code>CURDATE() + INTERVAL 1 DAY </code></pre>
{ "question_id": 3887509, "question_date": "2010-10-08T03:32:05.523Z", "question_score": 236, "tags": "sql|mysql|datetime", "answer_id": 3887517, "answer_date": "2010-10-08T03:34:13.450Z", "answer_score": 492 }
Please answer the following Stack Overflow question: Title: Email Address Validation in Android on EditText <p>How can we perform <code>Email Validation</code> on <code>edittext</code> in <code>android</code> ? I have gone through google &amp; SO but I didn't find out a simple way to validate it.</p>
<p>To perform Email Validation we have many ways,but simple &amp; easiest way are <strong>two methods</strong>.</p> <p><strong>1-</strong> Using <code>EditText(....).addTextChangedListener</code> which keeps triggering on every input in an <code>EditText box</code> i.e email_id is invalid or valid</p> <pre><code>/** * Email Validation ex:- [email protected] */ final EditText emailValidate = (EditText)findViewById(R.id.textMessage); final TextView textView = (TextView)findViewById(R.id.text); String email = emailValidate.getText().toString().trim(); String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; emailValidate .addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { if (email.matches(emailPattern) &amp;&amp; s.length() &gt; 0) { Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show(); // or textView.setText("valid email"); } else { Toast.makeText(getApplicationContext(),"Invalid email address",Toast.LENGTH_SHORT).show(); //or textView.setText("invalid email"); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // other stuffs } public void onTextChanged(CharSequence s, int start, int before, int count) { // other stuffs } }); </code></pre> <p><strong>2-</strong> Simplest method using <code>if-else</code> condition. Take the EditText box string using getText() and compare with pattern provided for email. If pattern doesn't match or macthes, onClick of button toast a message. It ll not trigger on every input of an character in EditText box . simple example shown below.</p> <pre><code>final EditText emailValidate = (EditText)findViewById(R.id.textMessage); final TextView textView = (TextView)findViewById(R.id.text); String email = emailValidate.getText().toString().trim(); String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; // onClick of button perform this simplest code. if (email.matches(emailPattern)) { Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show(); } </code></pre>
{ "question_id": 12947620, "question_date": "2012-10-18T05:20:26.347Z", "question_score": 236, "tags": "android|android-edittext|email-validation", "answer_id": 12947622, "answer_date": "2012-10-18T05:20:26.347Z", "answer_score": 85 }
Please answer the following Stack Overflow question: Title: How to get exit code when using Python subprocess communicate method? <p>How do I retrieve the exit code when using Python's <code>subprocess</code> module and the <code>communicate()</code> method?</p> <p>Relevant code:</p> <pre><code>import subprocess as sp data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0] </code></pre> <p>Should I be doing this another way?</p>
<p><code>Popen.communicate</code> will set the <code>returncode</code> attribute when it's done(*). Here's the relevant documentation section:</p> <pre><code>Popen.returncode The child return code, set by poll() and wait() (and indirectly by communicate()). A None value indicates that the process hasn’t terminated yet. A negative value -N indicates that the child was terminated by signal N (Unix only). </code></pre> <p>So you can just do (I didn't test it but it should work):</p> <pre><code>import subprocess as sp child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE) streamdata = child.communicate()[0] rc = child.returncode </code></pre> <hr> <p>(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls <code>wait</code>. </p>
{ "question_id": 5631624, "question_date": "2011-04-12T07:11:02.893Z", "question_score": 236, "tags": "python|subprocess", "answer_id": 5631819, "answer_date": "2011-04-12T07:29:23.573Z", "answer_score": 336 }
Please answer the following Stack Overflow question: Title: How to set ssh timeout? <p>I'm executing a script connecting via password-less SSH on a remote host. I want to set a timeout, so that if the remote host is taking an infinite time to run, I want to come out of that ssh session and continue other lines in my sh script.</p> <p>How can I set a timeout?</p>
<pre><code>ssh -o ConnectTimeout=10 &lt;hostName&gt; </code></pre> <p>Where 10 is time in seconds. This Timeout applies only to the creation of the connection.</p>
{ "question_id": 4936807, "question_date": "2011-02-08T18:25:37.860Z", "question_score": 236, "tags": "shell|ssh|timeout", "answer_id": 5255550, "answer_date": "2011-03-10T04:41:52.247Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: HTML entity for the middle dot <p>I'm looking for the html code for the dot. Not the dot that's at the end of sentences but the dot that's used to separate items horizontally.</p> <pre><code>Item 1 . Item 2 . Item 3 </code></pre> <p>The traditional dot is centered on the bottom of the line while the dot I'm looking for is centered on the middle.</p>
<p>It's called a <a href="http://www.fileformat.info/info/unicode/char/b7/index.htm" rel="noreferrer">middle dot</a>: &middot;</p> <p>HTML entities:</p> <ul> <li><code>&amp;middot;</code></li> <li><code>&amp;#183;</code></li> <li><code>&amp;#xb7;</code></li> </ul> <p>In CSS:</p> <ul> <li><code>\00B7</code></li> </ul>
{ "question_id": 7250381, "question_date": "2011-08-30T22:07:38.993Z", "question_score": 236, "tags": "html|html-entities", "answer_id": 7250398, "answer_date": "2011-08-30T22:10:21.830Z", "answer_score": 321 }
Please answer the following Stack Overflow question: Title: Git merge error "commit is not possible because you have unmerged files" <p>I forgot to <code>git pull</code> my code before editing it; when I committed the new code and tried to push, I got the error &quot;push is not possible&quot;.</p> <p>At that point I did a <code>git pull</code> which made some files with conflict highlighted. I removed the conflicts but I don't know what to do from here.</p> <p>I tried to <code>git commit</code> again but it says the &quot;commit is not possible because you have unmerged files&quot;:</p> <blockquote> <pre><code>error: Committing is not possible because you have unmerged files. </code></pre> </blockquote>
<p>If you have fixed the conflicts you need to add the files to the stage with <code>git add [filename]</code>, then commit as normal.</p>
{ "question_id": 12961752, "question_date": "2012-10-18T18:54:21.913Z", "question_score": 236, "tags": "git|git-merge", "answer_id": 12961804, "answer_date": "2012-10-18T18:57:36.230Z", "answer_score": 338 }
Please answer the following Stack Overflow question: Title: How to create a String with format? <p>I need to create a <code>String</code> with format which can convert <code>Int</code>, <code>Int64</code>, <code>Double</code>, etc types into <code>String</code>. Using Objective-C, I can do it by:</p> <pre><code>NSString *str = [NSString stringWithFormat:@&quot;%d , %f, %ld, %@&quot;, INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE]; </code></pre> <p>How to do same but in Swift?</p>
<p>I think this could help you:</p> <pre class="lang-swift prettyprint-override"><code>import Foundation let timeNow = time(nil) let aStr = String(format: &quot;%@%x&quot;, &quot;timeNow in hex: &quot;, timeNow) print(aStr) </code></pre> <p>Example result:</p> <pre class="lang-none prettyprint-override"><code>timeNow in hex: 5cdc9c8d </code></pre>
{ "question_id": 24074479, "question_date": "2014-06-06T05:00:59.533Z", "question_score": 236, "tags": "ios|swift|ios8|nsstring|string-formatting", "answer_id": 24097543, "answer_date": "2014-06-07T13:08:39.817Z", "answer_score": 452 }
Please answer the following Stack Overflow question: Title: Scale Image to fill ImageView width and keep aspect ratio <p>I have a <code>GridView</code>. The data of <code>GridView</code> is request from a server.</p> <p>Here is the item layout in <code>GridView</code>:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/analysis_micon_bg" android:gravity="center_horizontal" android:orientation="vertical" android:paddingBottom="@dimen/half_activity_vertical_margin" android:paddingLeft="@dimen/half_activity_horizontal_margin" android:paddingRight="@dimen/half_activity_horizontal_margin" android:paddingTop="@dimen/half_activity_vertical_margin" &gt; &lt;ImageView android:id="@+id/ranking_prod_pic" android:layout_width="fill_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:contentDescription="@string/app_name" android:scaleType="centerCrop" /&gt; &lt;TextView android:id="@+id/ranking_rank_num" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/ranking_prod_num" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/ranking_prod_name" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>I request data from server, get image url and load image to <code>Bitmap</code></p> <pre><code>public static Bitmap loadBitmapFromInputStream(InputStream is) { return BitmapFactory.decodeStream(is); } public static Bitmap loadBitmapFromHttpUrl(String url) { try { return loadBitmapFromInputStream((InputStream) (new URL(url).getContent())); } catch (Exception e) { Log.e(TAG, e.getMessage()); return null; } } </code></pre> <p>and there is the code of <code>getView(int position, View convertView, ViewGroup parent)</code> method in adapter</p> <pre><code>Bitmap bitmap = BitmapUtil.loadBitmapFromHttpUrl(product.getHttpUrl()); prodImg.setImageBitmap(bitmap); </code></pre> <p>The image size is <code>210*210</code>. I run my application on my Nexus 4. The image does fill <code>ImageView</code> width, but the <code>ImageView</code> height does not scale. <code>ImageView</code> does not show the whole image.</p> <p>How do I solve this problem?</p>
<p>Without using any custom classes or libraries:</p> <pre><code>&lt;ImageView android:id="@id/img" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:scaleType="fitCenter" /&gt; </code></pre> <p><code>scaleType="fitCenter"</code> (default when omitted)</p> <ul> <li>will make it as wide as the parent allows and up/down-scale as needed keeping aspect ratio.</li> </ul> <p><code>scaleType="centerInside"</code></p> <ul> <li>if the intrinsic width of <code>src</code> is smaller than parent width<br>will center the image horizontally </li> <li>if the intrinsic width of <code>src</code> is larger than parent width<br>will make it as wide as the parent allows and down-scale keeping aspect ratio.</li> </ul> <p>It doesn't matter if you use <code>android:src</code> or <code>ImageView.setImage*</code> methods and the key is probably the <code>adjustViewBounds</code>.</p>
{ "question_id": 18077325, "question_date": "2013-08-06T10:15:49.060Z", "question_score": 236, "tags": "android|imageview", "answer_id": 25069883, "answer_date": "2014-07-31T22:20:12.670Z", "answer_score": 626 }
Please answer the following Stack Overflow question: Title: Replacing Pandas or Numpy Nan with a None to use with MysqlDB <p>I am trying to write a Pandas dataframe (or can use a numpy array) to a mysql database using MysqlDB . MysqlDB doesn't seem understand 'nan' and my database throws out an error saying nan is not in the field list. I need to find a way to convert the 'nan' into a NoneType.</p> <p>Any ideas? </p>
<p>@bogatron has it right, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="noreferrer"><strong><code>where</code></strong></a>, it's worth noting that you can do this natively in pandas:</p> <pre><code>df1 = df.where(pd.notnull(df), None) </code></pre> <p>Note: this changes the dtype of <strong>all columns</strong> to <code>object</code>.</p> <p>Example:</p> <pre><code>In [1]: df = pd.DataFrame([1, np.nan]) In [2]: df Out[2]: 0 0 1 1 NaN In [3]: df1 = df.where(pd.notnull(df), None) In [4]: df1 Out[4]: 0 0 1 1 None </code></pre> <hr> <p>Note: what you cannot do recast the DataFrames <code>dtype</code> to allow all datatypes types, using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html" rel="noreferrer"><strong><code>astype</code></strong></a>, and then the DataFrame <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="noreferrer"><strong><code>fillna</code></strong></a> method:</p> <pre><code>df1 = df.astype(object).replace(np.nan, 'None') </code></pre> <p><em>Unfortunately neither this, nor using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="noreferrer"><strong><code>replace</code></strong></a>, works with <code>None</code> see <a href="https://github.com/pydata/pandas/issues/1972" rel="noreferrer">this (closed) issue</a>.</em></p> <hr> <p>As an aside, it's worth noting that for most use cases you don't need to replace NaN with None, see this question about <a href="https://stackoverflow.com/q/17534106/1240268"><strong>the difference between NaN and None in pandas</strong></a>.</p> <p>However, in this specific case it seems you do (at least at the time of this answer).</p>
{ "question_id": 14162723, "question_date": "2013-01-04T18:26:06.627Z", "question_score": 236, "tags": "python|pandas|numpy|mysql-python", "answer_id": 14163209, "answer_date": "2013-01-04T19:01:25.247Z", "answer_score": 304 }
Please answer the following Stack Overflow question: Title: ERROR: there is no unique constraint matching given keys for referenced table "bar" <p>Trying to create this example table structure in Postgres 9.1:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE foo ( name VARCHAR(256) PRIMARY KEY ); CREATE TABLE bar ( pkey SERIAL PRIMARY KEY, foo_fk VARCHAR(256) NOT NULL REFERENCES foo(name), name VARCHAR(256) NOT NULL, UNIQUE (foo_fk,name) ); CREATE TABLE baz( pkey SERIAL PRIMARY KEY, bar_fk VARCHAR(256) NOT NULL REFERENCES bar(name), name VARCHAR(256) ); </code></pre> <p>Running the above code produces an error, which does not make sense to me:</p> <blockquote> <pre><code>NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index &quot;foo_pkey&quot; for table &quot;foo&quot; NOTICE: CREATE TABLE will create implicit sequence &quot;bar_pkey_seq&quot; for serial column &quot;bar.pkey&quot; NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index &quot;bar_pkey&quot; for table &quot;bar&quot; NOTICE: CREATE TABLE / UNIQUE will create implicit index &quot;bar_foo_fk_name_key&quot; for table &quot;bar&quot; NOTICE: CREATE TABLE will create implicit sequence &quot;baz_pkey_seq&quot; for serial column &quot;baz.pkey&quot; NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index &quot;baz_pkey&quot; for table &quot;baz&quot; ERROR: there is no unique constraint matching given keys for referenced table &quot;bar&quot; </code></pre> </blockquote> <pre><code>********** Error ********** ERROR: there is no unique constraint matching given keys for referenced table &quot;bar&quot; SQL state: 42830 </code></pre> <p>Can anyone explain why this error arises?</p>
<p>It's because the <code>name</code> column on the <code>bar</code> table does not have the <em>UNIQUE</em> constraint.</p> <p>So imagine you have 2 rows on the <code>bar</code> table that contain the name <code>'ams'</code> and you insert a row on <code>baz</code> with <code>'ams'</code> on <code>bar_fk</code>, which row on <code>bar</code> would it be referring since there are two rows matching?</p>
{ "question_id": 11966420, "question_date": "2012-08-15T08:48:29.627Z", "question_score": 236, "tags": "sql|postgresql|foreign-keys|unique-constraint", "answer_id": 11966555, "answer_date": "2012-08-15T09:00:22.520Z", "answer_score": 291 }
Please answer the following Stack Overflow question: Title: Is there an exponent operator in C#? <p>For example, does an operator exist to handle this?</p> <pre><code>float Result, Number1, Number2; Number1 = 2; Number2 = 2; Result = Number1 (operator) Number2; </code></pre> <p>In the past the <code>^</code> operator has served as an exponential operator in other languages, but in C# it is a bit-wise operator.</p> <p>Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?</p>
<p>The C# language <a href="https://devblogs.microsoft.com/csharpfaq/why-doesnt-c-have-a-power-operator/" rel="noreferrer">doesn't have a power operator</a>. However, the .NET Framework offers the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.math.pow" rel="noreferrer"><code>Math.Pow</code></a> method:</p> <blockquote> <p>Returns a specified number raised to the specified power.</p> </blockquote> <p>So your example would look like this:</p> <pre><code>float Result, Number1, Number2; Number1 = 2; Number2 = 2; Result = Math.Pow(Number1, Number2); </code></pre>
{ "question_id": 3034604, "question_date": "2010-06-14T01:31:36.203Z", "question_score": 236, "tags": "c#|operators|arithmetic-expressions|exponent", "answer_id": 3034607, "answer_date": "2010-06-14T01:32:34.080Z", "answer_score": 281 }
Please answer the following Stack Overflow question: Title: Maven dependency for Servlet 3.0 API? <p>How can I tell Maven 2 to load the Servlet 3.0 API?</p> <p>I tried:</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;3.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>I use <a href="http://repository.jboss.com/maven2/" rel="noreferrer">http://repository.jboss.com/maven2/</a> but what repository would be correct?</p> <p><strong>Addendum:</strong></p> <p>It works with a dependency for the entire Java EE 6 API and the following settings:</p> <pre class="lang-xml prettyprint-override"><code>&lt;repository&gt; &lt;id&gt;java.net&lt;/id&gt; &lt;url&gt;http://download.java.net/maven/2&lt;/url&gt; &lt;/repository&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>I'd prefer to only add the Servlet API as dependency, but "Brabster" may be right that separate dependencies have been replaced by Java EE 6 Profiles. Is there a source that confirms this assumption?</p>
<blockquote> <p>I'd prefer to only add the Servlet API as dependency, </p> </blockquote> <p>To be honest, I'm not sure to understand why but never mind...</p> <blockquote> <p><a href="https://stackoverflow.com/users/2362/brabster">Brabster</a> separate dependencies have been replaced by Java EE 6 Profiles. Is there a source that confirms this assumption?</p> </blockquote> <p>The maven repository from Java.net indeed offers the following artifact for the WebProfile:</p> <pre class="lang-xml prettyprint-override"><code>&lt;repositories&gt; &lt;repository&gt; &lt;id&gt;java.net2&lt;/id&gt; &lt;name&gt;Repository hosting the jee6 artifacts&lt;/name&gt; &lt;url&gt;http://download.java.net/maven/2&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-web-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>This jar includes Servlet 3.0, EJB Lite 3.1, JPA 2.0, JSP 2.2, EL 1.2, JSTL 1.2, JSF 2.0, JTA 1.1, JSR-45, JSR-250.</p> <p>But to my knowledge, nothing allows to say that these APIs won't be distributed separately (in java.net repository or somewhere else). For example (ok, it may a particular case), the JSF 2.0 API is available separately (in the java.net repository):</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;com.sun.faces&lt;/groupId&gt; &lt;artifactId&gt;jsf-api&lt;/artifactId&gt; &lt;version&gt;2.0.0-b10&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>And actually, you could get <code>javax.servlet-3.0.jar</code> from <a href="http://download.java.net/maven/glassfish/org/glassfish/javax.servlet/3.0" rel="noreferrer">there</a> and install it in your own repository.</p>
{ "question_id": 1979957, "question_date": "2009-12-30T12:29:40.633Z", "question_score": 236, "tags": "java|maven-2|servlets|jakarta-ee", "answer_id": 1980718, "answer_date": "2009-12-30T15:24:02.327Z", "answer_score": 117 }
Please answer the following Stack Overflow question: Title: How do I create a Bash alias? <p>I'm on OSX and I need to put something like this, <code>alias blah="/usr/bin/blah"</code> in a config file but I don't know where the config file is. </p>
<p>You can add an <code>alias</code> or a <code>function</code> in your startup script file. Usually this is <code>.bashrc</code>, <code>.bash_login</code> or <code>.profile</code> file in your home directory. </p> <p>Since these files are hidden you will have to do an <code>ls -a</code> to list them. If you don't have one you can create one.</p> <hr> <p>If I remember correctly, when I had bought my Mac, the <code>.bash_login</code> file wasn't there. I had to create it for myself so that I could put <code>prompt info</code>, <code>alias</code>, <code>functions</code>, etc. in it. </p> <p>Here are the steps if you would like to create one:</p> <ol> <li>Start up Terminal</li> <li>Type <code>cd ~/</code> to go to your home folder</li> <li>Type <code>touch .bash_profile</code> to create your new file.</li> <li>Edit <code>.bash_profile</code> with your favorite editor (or you can just type <code>open -e .bash_profile</code> to open it in TextEdit.</li> <li>Type <code>. .bash_profile</code> to reload <code>.bash_profile</code> and update any alias you add.</li> </ol>
{ "question_id": 8967843, "question_date": "2012-01-23T06:15:33.497Z", "question_score": 236, "tags": "macos|bash|shell", "answer_id": 8967864, "answer_date": "2012-01-23T06:19:23.790Z", "answer_score": 314 }
Please answer the following Stack Overflow question: Title: Optional query string parameters in ASP.NET Web API <p>I need to implement the following WebAPI method:</p> <pre><code>/api/books?author=XXX&amp;title=XXX&amp;isbn=XXX&amp;somethingelse=XXX&amp;date=XXX </code></pre> <p>All of the query string parameters can be null. That is, the caller can specify from 0 to all of the 5 parameters.</p> <p>In <strong>MVC4 beta</strong> I used to do the following:</p> <pre><code>public class BooksController : ApiController { // GET /api/books?author=tolk&amp;title=lord&amp;isbn=91&amp;somethingelse=ABC&amp;date=1970-01-01 public string GetFindBooks(string author, string title, string isbn, string somethingelse, DateTime? date) { // ... } } </code></pre> <p>MVC4 RC doesn't behave like this anymore. If I specify fewer than 5 parameters, it replies with a <code>404</code> saying:</p> <blockquote> <p>No action was found on the controller 'Books' that matches the request.</p> </blockquote> <p>What is the correct method signature to make it behave like it used to, without having to specify the optional parameter in the URL routing?</p>
<p>This issue has been fixed in the regular release of MVC4. Now you can do:</p> <pre><code>public string GetFindBooks(string author="", string title="", string isbn="", string somethingelse="", DateTime? date= null) { // ... } </code></pre> <p>and everything will work out of the box.</p>
{ "question_id": 11862069, "question_date": "2012-08-08T09:58:42.207Z", "question_score": 236, "tags": "c#|url|asp.net-web-api|query-string", "answer_id": 12387327, "answer_date": "2012-09-12T11:39:07.843Z", "answer_score": 329 }
Please answer the following Stack Overflow question: Title: How do I use boolean variables in Perl? <p>I have tried:</p> <pre><code>$var = false; $var = FALSE; $var = False; </code></pre> <p>None of these work. I get the error message</p> <pre>Bareword "false" not allowed while "strict subs" is in use.</pre>
<p>In Perl, the following evaluate to false in conditionals:</p> <pre><code>0 '0' undef '' # Empty scalar () # Empty list ('') </code></pre> <p>The rest are true. There are no barewords for <code>true</code> or <code>false</code>.</p>
{ "question_id": 1036347, "question_date": "2009-06-24T04:08:11.387Z", "question_score": 236, "tags": "perl|boolean", "answer_id": 1036353, "answer_date": "2009-06-24T04:10:16.550Z", "answer_score": 298 }
Please answer the following Stack Overflow question: Title: How to concatenate strings with padding in sqlite <p>I have three columns in an sqlite table:</p> <pre><code> Column1 Column2 Column3 A 1 1 A 1 2 A 12 2 C 13 2 B 11 2 </code></pre> <p>I need to select <code>Column1-Column2-Column3</code> (e.g. <code>A-01-0001</code>). I want to pad each column with a <code>-</code></p> <p>I am a beginner with regards to SQLite, any help would be appreciated </p>
<blockquote> <p>The <code>||</code> operator is "concatenate" - it joins together the two strings of its operands.</p> </blockquote> <p>From <a href="http://www.sqlite.org/lang_expr.html" rel="noreferrer">http://www.sqlite.org/lang_expr.html</a></p> <p>For padding, the seemingly-cheater way I've used is to start with your target string, say '0000', concatenate '0000423', then substr(result, -4, 4) for '0423'.</p> <p><strong>Update:</strong> Looks like there is no native implementation of "lpad" or "rpad" in SQLite, but you can follow along (basically what I proposed) here: <a href="http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/" rel="noreferrer">http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/</a></p> <pre><code>-- the statement below is almost the same as -- select lpad(mycolumn,'0',10) from mytable select substr('0000000000' || mycolumn, -10, 10) from mytable -- the statement below is almost the same as -- select rpad(mycolumn,'0',10) from mytable select substr(mycolumn || '0000000000', 1, 10) from mytable </code></pre> <p>Here's how it looks:</p> <pre><code>SELECT col1 || '-' || substr('00'||col2, -2, 2) || '-' || substr('0000'||col3, -4, 4) </code></pre> <p>it yields</p> <pre><code>"A-01-0001" "A-01-0002" "A-12-0002" "C-13-0002" "B-11-0002" </code></pre>
{ "question_id": 6134415, "question_date": "2011-05-26T06:11:51.527Z", "question_score": 236, "tags": "string|sqlite|string-concatenation|leading-zero", "answer_id": 6134463, "answer_date": "2011-05-26T06:17:54.897Z", "answer_score": 416 }
Please answer the following Stack Overflow question: Title: How do you force a makefile to rebuild a target? <p>I have a makefile that builds and then calls another makefile. Since this makefile calls more makefiles that does the work it doesn't really change. Thus it keeps thinking the project is built and up to date.</p> <pre><code>dnetdev11 ~ # make make: `release' is up to date. </code></pre> <p>How do I force the makefile to rebuild the target?</p> <pre><code>clean = $(MAKE) -f ~/xxx/xxx_compile.workspace.mak clean build = svn up ~/xxx \ $(clean) \ ~/cbp2mak/cbp2mak -C ~/xxx ~/xxx/xxx_compile.workspace \ $(MAKE) -f ~/xxx/xxx_compile.workspace.mak $(1) \ release: $(build ) debug: $(build DEBUG=1) clean: $(clean) install: cp ~/xxx/source/xxx_utility/release/xxx_util /usr/local/bin cp ~/xxx/source/xxx_utility/release/xxxcore.so /usr/local/lib </code></pre> <p>Note: Names removed to protect the innocent</p> <p>Final Fixed version:</p> <pre><code>clean = $(MAKE) -f xxx_compile.workspace.mak clean; build = svn up; \ $(clean) \ ./cbp2mak/cbp2mak -C . xxx_compile.workspace; \ $(MAKE) -f xxx_compile.workspace.mak $(1); \ .PHONY: release debug clean install release: $(call build,) debug: $(call build,DEBUG=1) clean: $(clean) install: cp ./source/xxx_utillity/release/xxx_util /usr/bin cp ./dlls/Release/xxxcore.so /usr/lib </code></pre>
<p>You could declare one or more of your targets to be <a href="http://www.gnu.org/software/make/manual/html_node/Phony-Targets.html" rel="nofollow noreferrer">phony</a>.</p> <blockquote> <p>A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request. There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.</p> <p>...</p> <p>A phony target should not be a prerequisite of a real target file; if it is, its recipe will be run every time make goes to update that file. As long as a phony target is never a prerequisite of a real target, the phony target recipe will be executed only when the phony target is a specified goal</p> </blockquote>
{ "question_id": 816370, "question_date": "2009-05-03T05:00:49.047Z", "question_score": 236, "tags": "linux|makefile", "answer_id": 816373, "answer_date": "2009-05-03T05:03:26.620Z", "answer_score": 36 }
Please answer the following Stack Overflow question: Title: Does a `+` in a URL scheme/host/path represent a space? <p>I am aware that a <code>+</code> in the query string of a URL represents a space. Is this also the case outside of the query string region? That is to say, does the following URL:</p> <pre><code>http://a.com/a+b/c </code></pre> <p>actually represent:</p> <pre><code>http://a.com/a b/c </code></pre> <p>(and thus need to be encoded if it should actually be a <code>+</code>), or does it in fact actually represent <code>a+b/c</code>?</p>
<ul> <li>Percent encoding in the path section of a URL is expected to be decoded, but</li> <li>any <code>+</code> characters in the path component is expected to be treated literally.</li> </ul> <p>To be explicit: <code>+</code> is only a special character in the query component.</p> <p><a href="https://www.rfc-editor.org/rfc/rfc3986" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc3986</a></p>
{ "question_id": 1005676, "question_date": "2009-06-17T07:57:51.920Z", "question_score": 236, "tags": "url|encoding|query-string", "answer_id": 1006074, "answer_date": "2009-06-17T09:43:49.040Z", "answer_score": 178 }
Please answer the following Stack Overflow question: Title: How do I return clean JSON from a WCF Service? <p>I am trying to return some JSON from a WCF service. This service simply returns some content from my database. I can get the data. However, I am concerned about the format of my JSON. Currently, the JSON that gets returned is formatted like this:</p> <pre><code>{"d":"[{\"Age\":35,\"FirstName\":\"Peyton\",\"LastName\":\"Manning\"},{\"Age\":31,\"FirstName\":\"Drew\",\"LastName\":\"Brees\"},{\"Age\":29,\"FirstName\":\"Tony\",\"LastName\":\"Romo\"}]"} </code></pre> <p>In reality, I would like my JSON to be formatted as cleanly as possible. I believe (I may be incorrect), that the same collection of results, represented in clean JSON, should look like so:</p> <pre><code>[{ "Age": 35, "FirstName": "Peyton", "LastName": "Manning" }, { "Age": 31, "FirstName": "Drew", "LastName": "Brees" }, { "Age": 29, "FirstName": "Tony", "LastName": "Romo" }] </code></pre> <p>I have no idea where the “d” is coming from. I also have no clue why the escape characters are being inserted. My entity looks like the following:</p> <pre><code>[DataContract] public class Person { [DataMember] public string FirstName { get; set; } [DataMember] public string LastName { get; set; } [DataMember] public int Age { get; set; } public Person(string firstName, string lastName, int age) { this.FirstName = firstName; this.LastName = lastName; this.Age = age; } } </code></pre> <p>The service that is responsible for returning the content is defined as:</p> <pre><code>[ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class TestService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] public string GetResults() { List&lt;Person&gt; results = new List&lt;Person&gt;(); results.Add(new Person("Peyton", "Manning", 35)); results.Add(new Person("Drew", "Brees", 31)); results.Add(new Person("Tony", "Romo", 29)); // Serialize the results as JSON DataContractJsonSerializer serializer = new DataContractJsonSerializer(results.GetType()); MemoryStream memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, results); // Return the results serialized as JSON string json = Encoding.Default.GetString(memoryStream.ToArray()); return json; } } </code></pre> <p>How do I return “clean” JSON from a WCF service? Thank you!</p>
<p>Change the return type of your GetResults to be <code>List&lt;Person&gt;</code>.<br> Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically. </p> <p>Using your definition for the Person class, this code works for me: </p> <pre><code>public List&lt;Person&gt; GetPlayers() { List&lt;Person&gt; players = new List&lt;Person&gt;(); players.Add(new Person { FirstName="Peyton", LastName="Manning", Age=35 } ); players.Add(new Person { FirstName="Drew", LastName="Brees", Age=31 } ); players.Add(new Person { FirstName="Brett", LastName="Favre", Age=58 } ); return players; } </code></pre> <p>results:</p> <pre><code>[{"Age":35,"FirstName":"Peyton","LastName":"Manning"}, {"Age":31,"FirstName":"Drew","LastName":"Brees"}, {"Age":58,"FirstName":"Brett","LastName":"Favre"}] </code></pre> <p>(All on one line)</p> <p>I also used this attribute on the method: </p> <pre><code>[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "players")] </code></pre> <p>WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency. </p> <p>The UriTemplate sets the URL at which the method is available. So I can do a GET on <code>http://myserver/myvdir/JsonService.svc/players</code> and it just works. </p> <p>Also check out IIRF or another URL rewriter to get rid of the .svc in the URI. </p>
{ "question_id": 2086666, "question_date": "2010-01-18T14:33:25.823Z", "question_score": 236, "tags": "wcf|json", "answer_id": 2089974, "answer_date": "2010-01-18T23:26:33.780Z", "answer_score": 216 }
Please answer the following Stack Overflow question: Title: Load a WPF BitmapImage from a System.Drawing.Bitmap <p>I have an instance of a <code>System.Drawing.Bitmap</code> and would like to make it available to my WPF app in the form of a <code>System.Windows.Media.Imaging.BitmapImage</code>.</p> <p>What would be the best approach for this?</p>
<p>Thanks to Hallgrim, here is the code I ended up with:</p> <pre><code>ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmp.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(width, height)); </code></pre> <p>I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question</p>
{ "question_id": 94456, "question_date": "2008-09-18T16:58:32.490Z", "question_score": 236, "tags": "c#|wpf|bitmap", "answer_id": 96470, "answer_date": "2008-09-18T20:19:53.270Z", "answer_score": 88 }
Please answer the following Stack Overflow question: Title: How to style dt and dd so they are on the same line? <p>Using CSS, how can I style the following:</p> <pre><code>&lt;dl&gt; &lt;dt&gt;Mercury&lt;/dt&gt; &lt;dd&gt;Mercury (0.4 AU from the Sun) is the closest planet to the Sun and the smallest planet.&lt;/dd&gt; &lt;dt&gt;Venus&lt;/dt&gt; &lt;dd&gt;Venus (0.7 AU) is close in size to Earth, (0.815 Earth masses) and like Earth, has a thick silicate mantle around an iron core.&lt;/dd&gt; &lt;dt&gt;Earth&lt;/dt&gt; &lt;dd&gt;Earth (1 AU) is the largest and densest of the inner planets, the only one known to have current geological activity.&lt;/dd&gt; &lt;/dl&gt; </code></pre> <p>so the content of the <code>dt</code> show in one column and the content of the <code>dd</code> in another column, with each <code>dt</code> and the corresponding <code>dd</code> on the same line? I.e. producing something that looks like:</p> <p><a href="https://i.stack.imgur.com/WI4nf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WI4nf.png" alt="table format"></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>dl { width: 100%; overflow: hidden; background: #ff0; padding: 0; margin: 0 } dt { float: left; width: 50%; /* adjust the width; make sure the total of both is 100% */ background: #cc0; padding: 0; margin: 0 } dd { float: left; width: 50%; /* adjust the width; make sure the total of both is 100% */ background: #dd0; padding: 0; margin: 0 }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;dl&gt; &lt;dt&gt;Mercury&lt;/dt&gt; &lt;dd&gt;Mercury (0.4 AU from the Sun) is the closest planet to the Sun and the smallest planet.&lt;/dd&gt; &lt;dt&gt;Venus&lt;/dt&gt; &lt;dd&gt;Venus (0.7 AU) is close in size to Earth, (0.815 Earth masses) and like Earth, has a thick silicate mantle around an iron core.&lt;/dd&gt; &lt;dt&gt;Earth&lt;/dt&gt; &lt;dd&gt;Earth (1 AU) is the largest and densest of the inner planets, the only one known to have current geological activity.&lt;/dd&gt; &lt;/dl&gt;</code></pre> </div> </div> </p>
{ "question_id": 1713048, "question_date": "2009-11-11T04:39:22.590Z", "question_score": 236, "tags": "html|css", "answer_id": 1713060, "answer_date": "2009-11-11T04:44:03.523Z", "answer_score": 150 }
Please answer the following Stack Overflow question: Title: How do I parse a string into a number with Dart? <p>I would like to parse strings like <code>1</code> or <code>32.23</code> into integers and doubles. How can I do this with Dart?</p>
<p>You can parse a string into an integer with <code>int.parse()</code>. For example:</p> <pre class="lang-dart prettyprint-override"><code>var myInt = int.parse('12345'); assert(myInt is int); print(myInt); // 12345 </code></pre> <p>Note that <code>int.parse()</code> accepts <code>0x</code> prefixed strings. Otherwise the input is treated as base-10.</p> <p>You can parse a string into a double with <code>double.parse()</code>. For example:</p> <pre class="lang-dart prettyprint-override"><code>var myDouble = double.parse('123.45'); assert(myDouble is double); print(myDouble); // 123.45 </code></pre> <p><code>parse()</code> will throw FormatException if it cannot parse the input.</p>
{ "question_id": 13167496, "question_date": "2012-10-31T21:11:46.167Z", "question_score": 236, "tags": "string|parsing|dart", "answer_id": 13167498, "answer_date": "2012-10-31T21:11:46.167Z", "answer_score": 362 }
Please answer the following Stack Overflow question: Title: Unable to create Android Virtual Device <p><img src="https://i.stack.imgur.com/T5DP4.jpg" alt="Ok Button not clickable"></p> <p>For some reason, the OK button is not clickable when I try to create an AVD. Does anyone know what I'm doing wrong?</p>
<p>Simply because CPU/ABI says "No system images installed for this target". You need to install system images.</p> <p>In the Android SDK Manager check that you have installed "ARM EABI v7a System Image" (for each Android version from 4.0 and on you have to install a system image to be able to run a virtual device)</p> <p>In your case only ARM system image exsits (Android 4.2). If you were running an older version, Intel has provided System Images (Intel x86 ATOM). You can check on the internet to see the comparison in performance between both.</p> <p>In my case (see image below) I haven't installed a System Image for Android 4.2, whereas I have installed ARM and Intel System Images for 4.1.2</p> <p>As long as I don't install the 4.2 System Image I would have the same problem as you.</p> <p><strong>UPDATE</strong> : This recent article <a href="http://software.intel.com/en-us/articles/speeding-up-the-android-emulator-on-intel-architecture" rel="noreferrer">Speeding Up the Android Emaulator on Intel Architectures</a> explains how to use/install correctly the intel system images to speed up the emulator.</p> <p><strong>EDIT/FOLLOW UP</strong></p> <p>What I show in the picture is for Android 4.2, as it was the original question, but is true for every versions of Android.</p> <p>Of course (as @RedPlanet said), if you are developing for MIPS CPU devices you have to install the "MIPS System Image".</p> <p>Finally, as @SeanJA said, <strong>you have to restart eclipse</strong> to see the new installed images. But for me, I always restart a software which I updated to be sure it takes into account all the modifications, and I assume it is a good practice to do so. </p> <p><img src="https://i.stack.imgur.com/GQal9.jpg" alt="enter image description here"></p>
{ "question_id": 13488419, "question_date": "2012-11-21T07:38:19.900Z", "question_score": 236, "tags": "java|android", "answer_id": 13488547, "answer_date": "2012-11-21T07:48:17.597Z", "answer_score": 275 }
Please answer the following Stack Overflow question: Title: Get top most UIViewController <p>I can't seem to get the top most <code>UIViewController</code> without access to a <code>UINavigationController</code>. Here is what I have so far:</p> <pre><code>UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil) </code></pre> <p>However, it does not seem to do anything. The <code>keyWindow</code> and <code>rootViewController</code> seem to be non-nil values too, so the optional chaining shouldn't be an issue.</p> <p><strong>NOTE:</strong> <em>It is a bad idea to do something like this. It breaks the MVC pattern.</em></p>
<p><code>presentViewController</code> shows a view controller. It doesn't return a view controller. If you're not using a <code>UINavigationController</code>, you're probably looking for <code>presentedViewController</code> and you'll need to start at the root and iterate down through the presented views.</p> <pre><code>if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // topController should now be your topmost view controller } </code></pre> <p>For Swift 3+:</p> <pre><code>if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // topController should now be your topmost view controller } </code></pre> <p>For iOS 13+</p> <pre><code>let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first if var topController = keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // topController should now be your topmost view controller } </code></pre>
{ "question_id": 26667009, "question_date": "2014-10-31T03:14:00.210Z", "question_score": 236, "tags": "swift|uiviewcontroller", "answer_id": 26667122, "answer_date": "2014-10-31T03:29:14.947Z", "answer_score": 365 }
Please answer the following Stack Overflow question: Title: Namespace for [DataContract] <p>I can't find the namespace to use for <code>[DataContract]</code> and <code>[DataMember]</code> elements. According to what I've found, it seems that adding the following should be enough, but in my case it is not.</p> <pre><code>using System; using System.Runtime.Serialization; </code></pre> <p>Here is a snippet of my code:</p> <pre><code>using System; using System.Runtime.Serialization; namespace MyNamespace { [DataContract] public class Tuple&lt;T1, T2&gt; { // A custom implementation of a Tuple //... //... } } </code></pre> <p>And the error I get:</p> <blockquote> <p>The type or namespace name 'DataContract' could not be found (are you missing a using directive or an assembly reference?)</p> </blockquote> <p>Am I not using the right namespaces?</p>
<p><code>DataContractAttribute</code> Class is in the <code>System.Runtime.Serialization</code> namespace.</p> <p>You should add a reference to <code>System.Runtime.Serialization.dll</code>. That assembly isn't referenced by default though. To add the reference to your project you have to go to References -> Add Reference in the Solution Explorer and add an assembly reference manually.</p>
{ "question_id": 7401795, "question_date": "2011-09-13T12:23:31.820Z", "question_score": 236, "tags": "c#|wcf|datacontract", "answer_id": 7401828, "answer_date": "2011-09-13T12:25:38.327Z", "answer_score": 443 }
Please answer the following Stack Overflow question: Title: How is the default submit button on an HTML form determined? <p>If a form is submitted but not by any specific button, such as</p> <ul> <li>by pressing <kbd>Enter</kbd></li> <li>using <code>HTMLFormElement.submit()</code> in JS</li> </ul> <p>how is a browser supposed to determine which of multiple submit buttons, if any, to use as the one pressed?</p> <p>This is significant on two levels:</p> <ul> <li>calling an <code>onclick</code> event handler attached to a submit button</li> <li>the data sent back to the web server</li> </ul> <p>My experiments so far have shown that:</p> <ul> <li>when pressing <kbd>Enter</kbd>, Firefox, Opera and Safari use the first submit button in the form</li> <li>when pressing <kbd>Enter</kbd>, IE uses either the first submit button or none at all depending on conditions I haven't been able to figure out</li> <li>all these browsers use none at all for a JS submit</li> </ul> <p>What does the standard say?</p> <p>If it would help, here's my test code (the PHP is relevant only to my method of testing, not to my question itself)</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Get&lt;/h1&gt; &lt;dl&gt; &lt;?php foreach ($_GET as $k =&gt; $v) echo "&lt;dt&gt;$k&lt;/dt&gt;&lt;dd&gt;$v&lt;/dd&gt;"; ?&gt; &lt;/dl&gt; &lt;h1&gt;Post&lt;/h1&gt; &lt;dl&gt; &lt;?php foreach ($_POST as $k =&gt; $v) echo "&lt;dt&gt;$k&lt;/dt&gt;&lt;dd&gt;$v&lt;/dd&gt;"; ?&gt; &lt;/dl&gt; &lt;form name="theForm" method="&lt;?php echo isset($_GET['method']) ? $_GET['method'] : 'get'; ?&gt;" action="&lt;?php echo $_SERVER['SCRIPT_NAME']; ?&gt;"&gt; &lt;input type="text" name="method" /&gt; &lt;input type="submit" name="action" value="Button 1" onclick="alert('Button 1'); return true" /&gt; &lt;input type="text" name="stuff" /&gt; &lt;input type="submit" name="action" value="Button 2" onclick="alert('Button 2'); return true" /&gt; &lt;input type="button" value="submit" onclick="document.theForm.submit();" /&gt; &lt;/form&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
<p>If you submit the form via JavaScript (i.e., <code>formElement.submit()</code> or anything equivalent), then <em>none</em> of the submit buttons are considered successful and none of their values are included in the submitted data. (Note that if you submit the form by using <code>submitElement.click()</code> then the submit that you had a reference to is considered active; this doesn't really fall under the remit of your question since here the submit button is unambiguous but I thought I'd include it for people who read the first part and wonder how to make a submit button successful via JavaScript form submission. Of course, the form's onsubmit handlers will still fire this way whereas they wouldn't via <code>form.submit()</code> so that's another kettle of fish...)</p> <p>If the form is submitted by hitting Enter while in a non-textarea field, then it's actually down to the user agent to decide what it wants here. <a href="http://www.w3.org/TR/html401/interact/forms.html#submit-button" rel="nofollow noreferrer">The specifications</a> don't say anything about submitting a form using the <kbd>Enter</kbd> key while in a text entry field (if you tab to a button and activate it using space or whatever, then there's no problem as that specific submit button is unambiguously used). All it says is that a form must be submitted when a submit button is activated. It's not even a requirement that hitting <kbd>Enter</kbd> in e.g. a text input will submit the form.</p> <p>I believe that Internet Explorer chooses the submit button that appears first in the source; I have a feeling that Firefox and Opera choose the button with the lowest tabindex, falling back to the first defined if nothing else is defined. There's also some complications regarding whether the submits have a non-default value attribute IIRC.</p> <p>The point to take away is that there is no defined standard for what happens here and it's entirely at the whim of the browser - so as far as possible in whatever you're doing, try to avoid relying on any particular behaviour. If you really must know, you can probably find out the behaviour of the various browser versions, but when I investigated this a while back there were some quite convoluted conditions (which of course are subject to change with new browser versions) and I'd advise you to avoid it if possible!</p>
{ "question_id": 925334, "question_date": "2009-05-29T10:24:51.543Z", "question_score": 236, "tags": "javascript|html|cross-browser|standards", "answer_id": 925387, "answer_date": "2009-05-29T10:41:13.537Z", "answer_score": 123 }
Please answer the following Stack Overflow question: Title: Declaring abstract method in TypeScript <p>I am trying to figure out how to correctly define abstract methods in TypeScript:</p> <p>Using the original inheritance example:</p> <pre><code>class Animal { constructor(public name) { } makeSound(input : string) : string; move(meters) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name) { super(name); } makeSound(input : string) : string { return "sssss"+input; } move() { alert("Slithering..."); super.move(5); } } </code></pre> <p>I would like to know how to correctly define method makeSound, so it is typed and possible to overried.</p> <p>Also, I am not sure how to define correctly <code>protected</code> methods - it seems to be a keyword, but has no effect and the code won't compile.</p>
<p>The <code>name</code> property is marked as <code>protected</code>. This was added in TypeScript 1.3 and is now firmly established.</p> <p>The <code>makeSound</code> method is marked as <code>abstract</code>, as is the class. You cannot directly instantiate an <code>Animal</code> now, because it is abstract. <a href="https://github.com/Microsoft/TypeScript/issues/3578" rel="noreferrer">This is part of TypeScript 1.6</a>, which is now officially live.</p> <pre><code>abstract class Animal { constructor(protected name: string) { } abstract makeSound(input : string) : string; move(meters) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name: string) { super(name); } makeSound(input : string) : string { return "sssss"+input; } move() { alert("Slithering..."); super.move(5); } } </code></pre> <p>The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:</p> <pre><code>class Animal { constructor(public name) { } makeSound(input : string) : string { throw new Error('This method is abstract'); } move(meters) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name) { super(name); } makeSound(input : string) : string { return "sssss"+input; } move() { alert("Slithering..."); super.move(5); } } </code></pre>
{ "question_id": 13333489, "question_date": "2012-11-11T17:18:22.913Z", "question_score": 236, "tags": "typescript|abstract-class|abstract", "answer_id": 13335645, "answer_date": "2012-11-11T21:28:15.317Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: remove kernel on jupyter notebook <p>How can I remove a kernel from jupyter notebook? </p> <p>I have R kernel on my jupyter notebook. Recently kernel always dies right after I open a new notebook.</p>
<p>Run <code>jupyter kernelspec list</code> to get the paths of all your kernels. <br/> Then simply uninstall your unwanted-kernel</p> <pre><code>jupyter kernelspec uninstall unwanted-kernel </code></pre> <p><b>Old answer </b><br/> Delete the folder corresponding to the kernel you want to remove.</p> <p>The docs has a list of the common paths for kernels to be stored in: <a href="http://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs" rel="noreferrer">http://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs</a></p>
{ "question_id": 42635310, "question_date": "2017-03-06T20:51:15.247Z", "question_score": 236, "tags": "r|jupyter-notebook", "answer_id": 42647666, "answer_date": "2017-03-07T11:54:30.920Z", "answer_score": 435 }
Please answer the following Stack Overflow question: Title: How can I find out the current route in Rails? <p>I need to know the current route in a filter in Rails. How can I find out what it is?</p> <p>I'm doing REST resources, and see no named routes.</p>
<p>To find out URI: </p> <pre><code>current_uri = request.env['PATH_INFO'] # If you are browsing http://example.com/my/test/path, # then above line will yield current_uri as "/my/test/path" </code></pre> <p>To find out the route i.e. controller, action and params:</p> <pre><code>path = ActionController::Routing::Routes.recognize_path "/your/path/here/" # ...or newer Rails versions: # path = Rails.application.routes.recognize_path('/your/path/here') controller = path[:controller] action = path[:action] # You will most certainly know that params are available in 'params' hash </code></pre>
{ "question_id": 1203892, "question_date": "2009-07-30T00:50:58.997Z", "question_score": 236, "tags": "ruby-on-rails|ruby|routing", "answer_id": 1205824, "answer_date": "2009-07-30T10:48:19.773Z", "answer_score": 208 }
Please answer the following Stack Overflow question: Title: Textarea that can do syntax highlighting on the fly? <p>I am storing a number of HTML blocks inside a CMS for reasons of easier maintenance. They are represented by <code>&lt;textarea&gt;</code>s.</p> <p>Does anybody know a JavaScript Widget of some sort that can do syntax highlighting for HTML within a <code>textarea</code> or similar, while still staying a plain text editor (no WYSIWYG or advanced functions)?</p>
<p>It's not possible to achieve the required level of control over presentation in a regular <code>textarea</code>.</p> <p>If you're OK with that, try <a href="http://codemirror.net/" rel="noreferrer">CodeMirror</a> or <a href="https://ace.c9.io/" rel="noreferrer">Ace</a> or <a href="https://microsoft.github.io/monaco-editor/" rel="noreferrer">Monaco</a> (used in MS VSCode).</p> <p>From the duplicate thread - an obligatory wikipedia link: <a href="http://en.wikipedia.org/wiki/Comparison_of_JavaScript-based_source_code_editors" rel="noreferrer">Comparison of JavaScript-based source code editors</a></p>
{ "question_id": 1619167, "question_date": "2009-10-24T21:20:17.100Z", "question_score": 236, "tags": "javascript|html|richtextbox|widget|highlighting", "answer_id": 1619184, "answer_date": "2009-10-24T21:26:26.610Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: Is it possible to return empty in react render function? <p>I have a notification component, and I have a timeout setting for it. After timeout I call <code>this.setState({isTimeout:true})</code>.</p> <p>What I want to do is if already timeout, I want just render nothing:</p> <pre><code>render() { let finalClasses = &quot;&quot; + (this.state.classes || &quot;&quot;); if (isTimeout){ return (); // here has some syntax error } return (&lt;div&gt;{this.props.children}&lt;/div&gt;); } </code></pre> <p>The problem is:</p> <blockquote> <p>return (); // here has some syntax error</p> </blockquote>
<p>Yes you can, but instead of blank, simply return <code>null</code> if you don't want to <code>render</code> anything from component, like this:</p> <pre><code>return (null); </code></pre> <hr> <p>Another important point is, inside JSX if you are rendering element conditionally, then in case of <code>condition=false</code>, you can return any of these values <code>false, null, undefined, true</code>. As per <strong><a href="https://reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored" rel="noreferrer">DOC</a></strong>:</p> <blockquote> <p><code>booleans (true/false), null, and undefined</code> are <strong>valid children</strong>, they will be Ignored means they simply don’t render.</p> </blockquote> <p>All these <code>JSX</code> expressions will render to the same thing:</p> <pre><code>&lt;div /&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;{false}&lt;/div&gt; &lt;div&gt;{null}&lt;/div&gt; &lt;div&gt;{undefined}&lt;/div&gt; &lt;div&gt;{true}&lt;/div&gt; </code></pre> <p><strong>Example:</strong></p> <p>Only odd values will get rendered, because for even values we are returning <code>null</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const App = ({ number }) =&gt; { if(number%2) { return ( &lt;div&gt; Number: {number} &lt;/div&gt; ) } return (null); //===&gt; notice here, returning null for even values } const data = [1,2,3,4,5,6]; ReactDOM.render( &lt;div&gt; {data.map(el =&gt; &lt;App key={el} number={el} /&gt;)} &lt;/div&gt;, document.getElementById('app') )</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&gt;&lt;/script&gt; &lt;div id='app' /&gt;</code></pre> </div> </div> </p>
{ "question_id": 42083181, "question_date": "2017-02-07T06:29:58.577Z", "question_score": 236, "tags": "reactjs", "answer_id": 42083262, "answer_date": "2017-02-07T06:36:44.183Z", "answer_score": 395 }
Please answer the following Stack Overflow question: Title: MySQL: How to copy rows, but change a few fields? <p>I have a large number of rows that I would like to copy, but I need to change one field.</p> <p>I can select the rows that I want to copy:</p> <pre><code>select * from Table where Event_ID = "120" </code></pre> <p>Now I want to copy all those rows and create new rows while setting the <code>Event_ID</code> to <code>155</code>. How can I accomplish this?</p>
<pre><code>INSERT INTO Table ( Event_ID , col2 ... ) SELECT "155" , col2 ... FROM Table WHERE Event_ID = "120" </code></pre> <p>Here, the col2, ... represent the remaining columns (the ones <strong>other than</strong> Event_ID) in your table.</p>
{ "question_id": 2783150, "question_date": "2010-05-06T17:33:46.333Z", "question_score": 236, "tags": "sql|mysql", "answer_id": 2783162, "answer_date": "2010-05-06T17:35:50.287Z", "answer_score": 344 }