id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,405,343 | Does the .NET CLR Really Optimize for the Current Processor | <p>When I read about the performance of JITted languages like C# or Java, authors usually say that they should/could theoretically outperform many native-compiled applications. The theory being that native applications are usually just compiled for a processor family (like x86), so the compiler cannot make certain optimizations as they may not truly be optimizations on all processors. On the other hand, the CLR can make processor-specific optimizations during the JIT process.</p>
<p>Does anyone know if Microsoft's (or Mono's) CLR actually performs processor-specific optimizations during the JIT process? If so, what kind of optimizations?</p> | 2,405,530 | 7 | 4 | null | 2010-03-08 22:39:18.31 UTC | 16 | 2010-03-09 15:02:54.17 UTC | 2010-03-08 22:42:50.04 UTC | null | 14,048 | null | 100,398 | null | 1 | 45 | c#|.net|optimization|clr|jit | 3,206 | <p>From back in 2005, David Notario listed several specific targeted optimizations is his blog entry "<a href="http://blogs.msdn.com/davidnotario/archive/2005/08/15/451845.aspx" rel="noreferrer">Does the JIT take advantage of my CPU?</a>". I can't find anything about the new CLR 4, but I imagine several new items are included.</p> |
3,016,683 | The difference between traditional DLL and COM DLL | <p>I am currently studying COM. I found that COM DLL is kind of built upon the traditional DLL infrastructure. When we build COM DLLs, we still rely on the traditional DLL export methods to lead us to the internal COM co-classes. </p>
<p>If COM is for component reusing at the binary level, I think the traditional DLL can achieve the same thing. They both expose functions, they are both binary, so what's the point of turning to COM approach?</p>
<p>Currently, I have the feeling that the traditional DLL expose methods in a "<strong>flat</strong>" manner, while the COM DLL expose methods in an "<strong>OOP</strong>" hierarchy manner. And the OOP manner seems to be a better approach. Could this be the reason why COM prevails?</p>
<p>Many thanks.</p> | 3,017,368 | 8 | 2 | null | 2010-06-10 17:07:05.477 UTC | 23 | 2020-05-21 12:52:35.1 UTC | 2010-06-10 17:12:25.12 UTC | null | 264,052 | null | 264,052 | null | 1 | 32 | c++|com | 32,075 | <p>No, there's a Big difference. COM has a well defined protocols for creating objects, exposing methods, managing memory, publishing type information, managing threading. There is practically no language left that doesn't support using a COM server, no matter what language it was written in.</p>
<p>You will not get that from exposing your own functions directly. That will likely be only usable from a program written in C/C++ (so it can read your header files), compiled with the exact same version of the C++ compiler and no lack of all kinds of interop problems. Something as simple as exposing a C++ class object like std::string is not safe. Neither the memory layout is guaranteed to be compatible, nor is there any kind of memory ownership protocol. </p>
<p>It could well be more OOPy, COM doesn't support inheritance because OOP is so hard to get compatible at the binary level. That problem requires runtime support that all code buys into, VMs like .NET and Java.</p> |
2,533,972 | android include tag - invalid layout reference | <p>I'm having a problem including a different layout through the include tag in the android layout xml file. When specifing the layout reference ( @layout/... ), i'm getting a InflateException in the Eclipse ADT with the following error:
<strong>InflateException: You must specifiy a valid layout reference. The layout ID @layout/func_edit_simple_calculator_toolbox is not valid.</strong></p>
<p>the reference should be valid, as I've selected it from the the list of my other layouts and didnt type it in. I'm using android sdk v2.1</p>
<p>these are the layout files</p>
<p>func_edit_simple_calculator_toolbox.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:layout_width="wrap_content">
<TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content"android:layout_height="wrap_content">
<Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1"></Button>
<Button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2"></Button>
<Button android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="3"></Button>
<Button android:id="@+id/Button04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+"></Button>
</TableRow>
<TableRow android:id="@+id/TableRow02" android:layout_width="wrap_content" android:layout_height="wrap_content">
<Button android:id="@+id/Button05" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="4"></Button>
<Button android:id="@+id/Button06" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="5"></Button>
<Button android:id="@+id/Button07" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="6"></Button>
<Button android:id="@+id/Button08" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-"></Button>
</TableRow>
</TableLayout>
</code></pre>
<p>function_editor_layout.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.calculoid.FunctionView android:id="@+id/function_view" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
<include android:id="@+id/include01" android:layout_width="wrap_content" android:layout_height="wrap_content" layout="@layout/func_edit_simple_calculator_toolbox"></include>
</LinearLayout>
</code></pre>
<p>Does any one know what could be the problem?</p>
<p>thanks in advance</p> | 3,203,327 | 8 | 1 | null | 2010-03-28 18:19:41.8 UTC | 8 | 2014-11-14 21:04:59.55 UTC | 2012-02-29 14:24:35.347 UTC | null | 303,704 | null | 303,704 | null | 1 | 43 | xml|android|layout | 29,815 | <p>I think i should mention how i solved the same problem. Tried cleaning the project and didn't work. I have quite large names for the layout (chrono_first_small_field), and that wasn't the cause either. </p>
<p><strong>Closed Eclipse, and just opened it again, and that worked.</strong></p>
<p>That makes more sense than having to implement the onMeasure method :-)</p> |
2,596,862 | How do you make an html page fade out while another fades in? | <p>I have a client with an event planning site asking his pages to fade into one another. I have no idea how I can accomplish this. Any ideas? Is there anyway to do this without flash?</p> | 2,596,933 | 9 | 3 | null | 2010-04-08 00:47:31.953 UTC | 2 | 2010-07-24 23:56:14.537 UTC | null | null | null | null | 270,589 | null | 1 | 11 | html|css | 39,525 | <p>Definitely get hold of a javascript framework. jQuery is popular (because it's ace), but there's Mootools, Prototype, and Dojo to name a few.</p>
<p>I'm not sure if crosssfading can be done reliably across all the browsers without popping / jumping artifacts. Even the example Dancrumb points to is a bit ropey (no insult intended Dan).</p>
<p>Process-wise, you could have 3 layers (top to bottom)</p>
<ul>
<li>screen (initially invisible)</li>
<li>page (one)</li>
<li>container (initially empty)</li>
</ul>
<p>when the user tries to navigate to the second page, load it into the container using ajax. Once the page has loaded, start fading up the screen. Once the screen is at 100% opacity, manipulate the DOM to move the loaded content out of the hidden container and into what is now page two, then start fading the screen back out again.</p>
<p><strong>EDIT</strong> on a sidenote - I would summon up all my webdev mojo and try to convince the client what I bad idea it is to have complete page fades on an site designed to communicate information. Obviously I know sweet FA about this project so feel free to slap me down; but I've never seen a case where fancy effects and transitions has improved the usability of a site when used at the page level. I know it'd irritate me if I had to wait for a fancy transition to finish before I could continue navigating... </p> |
2,758,415 | Swap values for two rows in the same table in SQL Server | <p>I want to swap the values from two rows in a table. I have the rows IDs of the two rows. Is there any query to do that? Here is an example. Before the query I have this:</p>
<pre>
row1 : 1,2,3
row2 : 5,6,7
</pre>
<p>After the swap I want this:</p>
<pre>
row1 : 5,6,7
row2 : 1,2,3
</pre> | 2,758,631 | 9 | 3 | null | 2010-05-03 13:39:11.79 UTC | 3 | 2022-08-01 19:37:25.263 UTC | 2019-02-13 21:11:32.537 UTC | null | 5,405,967 | null | 437,176 | null | 1 | 19 | sql|sql-server | 58,778 | <p>If you want to swap values from one row to the other for two known IDs try something like this:</p>
<pre><code>--need to store the original values
SELECT
*,CASE WHEN id=123 then 987 ELSE 123 END AS JoinId
INTO #Temp
FROM YourTable
WHERE ID in (123,987)
--swap values
UPDATE y
SET col1=t.col1
,col2=t.col2
FROM YourTable y
INNER JOIN #Temp t ON y.id =t.JoinId
WHERE ID in (123,987)
</code></pre> |
3,139,879 | How do I get currency exchange rates via an API such as Google Finance? | <p>Now, I did find the <a href="http://code.google.com/apis/finance/" rel="noreferrer">Google Finance API</a> and started looking through that but I found a lot of info about portfolios, transactions, positions & other stuff I know nothing about. </p>
<p>Am I looking at the wrong docs? What do I need to do to get a feed of exchange rates from GF? Is this even possible?</p>
<p><strong>EDIT</strong></p>
<p>To make things a little clearer. I'm not interested in technical stuff nor do I want any code. </p> | 8,391,430 | 9 | 6 | null | 2010-06-29 10:42:06.227 UTC | 410 | 2021-11-30 19:06:54.91 UTC | 2014-02-27 20:12:26.5 UTC | null | 16,587 | null | 350,722 | null | 1 | 137 | api|google-finance-api | 676,439 | <p>Thanks for all your answers.</p>
<p><strong>Free currencyconverterapi:</strong></p>
<ul>
<li>Rates updated every 30 min</li>
<li>API key is now required for the free server.</li>
</ul>
<p>A sample conversion URL is: <a href="http://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y" rel="noreferrer">http://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y</a></p>
<hr />
<p>For posterity here they are along with other possible answers:</p>
<ol>
<li><h3><del>Yahoo finance API</del> Discontinued 2017-11-06###</h3>
</li>
</ol>
<p>Discontinued as of 2017-11-06 with message</p>
<blockquote>
<p>It has come to our attention that this service is being used in
violation of the Yahoo Terms of Service. As such, the service is being
discontinued. For all future markets and equities data research,
please refer to finance.yahoo.com.</p>
</blockquote>
<p>Request: <a href="http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDINR=X" rel="noreferrer">http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDINR=X</a><br>
This CSV was being used by a jQuery plugin called <a href="http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29" rel="noreferrer">Curry</a>. Curry has since (2017-08-29) moved to use fixer.io instead due to stability issues.
Might be useful if you need more than just a CSV.</p>
<ol start="2">
<li>(<a href="https://stackoverflow.com/a/16408368/1269037">thanks to Keyo</a>) <strong>Yahoo Query Language</strong> lets you get a whole bunch of currencies at once in XML or JSON. The data updates by the second (whereas the European Central Bank has day old data), and stops in the weekend. Doesn't require any kind of sign up.</li>
</ol>
<p><a href="http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29" rel="noreferrer">http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys</a></p>
<p>Here is the <del>YQL query builder</del>, where you can test a query and copy the url: (NO LONGER AVAILABLE)</p>
<p><del><a href="http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29" rel="noreferrer">http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29</a></del></p>
<p><img src="https://i.stack.imgur.com/6Yd49.png" alt="yql console no longer available" /></p>
<ol start="3">
<li><h3>Open Source Exchange Rates API</h3>
</li>
</ol>
<p><a href="https://openexchangerates.org/signup/free" rel="noreferrer">Free for personal use</a> (1000 hits per month)<br>
Changing "base" (from "USD") is not allowed in Free account<br>
Requires registration.<br>
Request: <a href="http://openexchangerates.org/latest.json" rel="noreferrer">http://openexchangerates.org/latest.json</a><br>
Response:</p>
<pre><code> <!-- language: lang-js -->
{
"disclaimer": "This data is collected from various providers ...",
"license": "all code open-source under GPL v3 ...",
"timestamp": 1323115901,
"base": "USD",
"rates": {
"AED": 3.66999725,
"ALL": 102.09382091,
"ANG": 1.78992886,
// 115 more currency rates here ...
}
}
</code></pre>
<ol start="4">
<li><h3>currencylayer API</h3>
</li>
</ol>
<p><a href="https://currencylayer.com/product" rel="noreferrer">Free Plan</a> for 250 monthly hits<br>
Changing "source" (from "USD") is not allowed in Free account<br>
Requires registration.<br>
Documentation: <a href="http://currencylayer.com/documentation" rel="noreferrer">currencylayer.com/documentation</a><br><br>
JSON Response:</p>
<pre><code> <!-- language: lang-js -->
{
[...]
"timestamp": 1436284516,
"source": "USD",
"quotes": {
"USDAUD": 1.345352401,
"USDCAD": 1.27373397,
"USDCHF": 0.947845302,
"USDEUR": 0.91313905,
"USDGBP": 0.647603397,
// 168 world currencies
}
}
</code></pre>
<ol start="5">
<li><h3>CurrencyFreaks API</h3>
</li>
</ol>
<p><a href="https://currencyfreaks.com/pricing.html" rel="noreferrer">Free Plan</a> (1000 hits per month)<br>
Changing 'Base' (From 'USD') is not allowed in free account<br>
Requires registration<br>
Data updated every 60 sec.<br>
179 currencies worldwide including currencies, metals, and cryptocurrencies<br>
Support (Even on the free plan) Shell,Node.js, Java, Python, PHP, Ruby, JS, C#, C, Go, Swift.<br>
Documentation: <a href="https://currencyfreaks.com/documentation.html" rel="noreferrer">https://currencyfreaks.com/documentation.html</a><br><br>
Endpoint:</p>
<pre><code>$ curl 'https://api.currencyfreaks.com/latest?apikey=YOUR_APIKEY'
</code></pre>
<p>JSON Response:</p>
<pre><code>{
"date": "2020-10-08 12:29:00+00",
"base": "USD",
"rates": {
"FJD": "2.139",
"MXN": "21.36942",
"STD": "21031.906016",
"LVL": "0.656261",
"SCR": "18.106031",
"CDF": "1962.53482",
"BBD": "2.0",
"GTQ": "7.783265",
"CLP": "793.0",
"HNL": "24.625383",
"UGX": "3704.50271",
"ZAR": "16.577611",
"TND": "2.762",
"CUC": "1.000396",
"BSD": "1.0",
"SLL": "9809.999914",
"SDG": 55.325,
"IQD": "1194.293591",
.
.
.
[179 currencies]
}
}
</code></pre>
<ol start="6">
<li><h3>Fixer.io API (European Central Bank data)</h3>
</li>
</ol>
<p>Free Plan for 1,000 monthly hits<br>
Changing "source" (from "USD") is not allowed in Free account
Requires registration.<br></p>
<p>This API endpoint is deprecated and will stop working on June 1st, 2018. For more information please visit: https://github.com/fixerAPI/fixer#readme)
</p>
<br>
Website : http://fixer.io/
<br>
Example request :
[http://api.fixer.io/latest?base=USD][7]
<br>
Only collects one value per each day
<ol start="7">
<li><h3>European Central Bank Feed</h3>
</li>
</ol>
<p>Docs:
<a href="http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html#dev" rel="noreferrer">http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html#dev</a><br>
Request: <a href="http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml" rel="noreferrer">http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml</a><br><br>
XML Response:</p>
<pre><code> <!-- language: lang-xml -->
<Cube>
<Cube time="2015-07-07">
<Cube currency="USD" rate="1.0931"/>
<Cube currency="JPY" rate="133.88"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="27.100"/>
</Cube>
</code></pre>
<ol start="8">
<li><h3>exchangeratesapi.io</h3>
</li>
</ol>
<p>According to the website:<blockquote> Exchange rates API is a free service for current and historical foreign exchange rates published by the European Central Bank</blockquote>
This service is compatible with fixer.io and is really easy to use: <del> no API key needed </del> - UPDATE: API key is now needed, free tier is 250 requests/mo.<br />
For example (this uses CURL, but you can use your favorite requesting tool):</p>
<pre><code> > curl https://api.exchangeratesapi.io/latest?base=GBP&symbols=USD&apikey=YOUR_KEY
{"base":"GBP","rates":{"USD":1.264494191},"date":"2019-05-29"}
</code></pre>
<ol start="9">
<li><h3>CurrencyApi.net</h3>
</li>
</ol>
<p><a href="https://currencyapi.net" rel="noreferrer">Free Plan</a> for 1250 monthly hits<br>
150 Crypto and physical currencies - live updates<br>
Base currency is set as USD on free account<br>
Requires registration.<br>
Documentation: <a href="https://currencyapi.net/documentation" rel="noreferrer">currencyapi.net/documentation</a><br><br>
JSON Response:</p>
<pre><code> {
"valid": true,
"updated": 1567957373,
"base": "USD",
"rates": {
"AED": 3.673042,
"AFN": 77.529504,
"ALL": 109.410403,
// 165 currencies + some cryptos
}
}
</code></pre>
<ol start="10">
<li><h3>Currency from LabStack</h3>
</li>
</ol>
<p>Website: <a href="https://labstack.com/currency" rel="noreferrer">https://labstack.com/currency</a><br>
Documentation: <a href="https://labstack.com/docs/api/currency/convert" rel="noreferrer">https://labstack.com/docs/api/currency/convert</a><br>
Pricing: <a href="https://labstack.com/pricing" rel="noreferrer">https://labstack.com/pricing</a><br>
Request: <a href="https://currency.labstack.com/api/v1/convert/1/USD/INR" rel="noreferrer">https://currency.labstack.com/api/v1/convert/1/USD/INR</a><br>
Response:<br></p>
<pre><code>```js
{
"time": "2019-10-09T21:15:00Z",
"amount": 71.1488
}
```
</code></pre>
<p><a href="http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29" rel="noreferrer">1</a>: <a href="http://query.yahooapis.com/v1/public/yql?q=select" rel="noreferrer">http://query.yahooapis.com/v1/public/yql?q=select</a> * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys</p>
<ol start="11">
<li><h3>currency-api</h3>
</li>
</ol>
<ul>
<li>Free & Blazing Fast response using CDN</li>
<li>No Rate limits</li>
<li>150+ Currencies, Including Common Cryptocurrencies</li>
<li>Daily Updated</li>
</ul>
<p>Documentation: <a href="https://github.com/fawazahmed0/currency-api#readme" rel="noreferrer">Link</a> <br>
Request: <a href="https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/eur/jpy.json" rel="noreferrer">https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/eur/jpy.json</a> <br>
Request(Fallback): <a href="https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/eur/jpy.min.json" rel="noreferrer">https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/eur/jpy.min.json</a> <br>
Response:</p>
<pre class="lang-json prettyprint-override"><code>{
"date": "2021-10-03",
"jpy": 128.798673
}
</code></pre> |
2,719,270 | Video/audio streaming does not stop even if UIWebView is closed - iPad | <p>I see this issue only on the iPad. The same things works as expected on the iPhone.</p>
<p>I am opening the URL from my application in a UIWebView. If the URL is a normal web page, it works fine as expected. But if the URL is that of a remote video/audio file, the UIWebView opens the default player which is again good.</p>
<p>Now when I dismiss the UIWebView (by clicking on the Done button on the player), the streaming doesn't stop and the audio/video keeps playing in the background (I cannot see it but it does keep playing in the background, can hear it). The UIViewController in which the webview was created is also dealloced (I put in a log statement in the dealloc method) but the streaming doesn't stop.</p>
<p>Can someone please help me out on why this could be happening? And how can I stop the audio/video streaming when the UIWebView is closed?</p>
<p>Thanks.</p> | 2,746,967 | 11 | 0 | null | 2010-04-27 06:53:00.483 UTC | 16 | 2019-01-29 08:41:31.373 UTC | null | null | null | null | 46,297 | null | 1 | 33 | uiwebview|video-streaming|ipad | 27,811 | <p>I have the same issue as stated but in this case the video that won't stop playing is a Youtube video embeded using the object/embed method. </p>
<p>I spent a long time trying to figure out how to get the video to stop playing and the only solution I found was to tell the UIWebView to load a blank page before dismissing the view:</p>
<pre><code> [self.webContent loadRequest:NSURLRequestFromString(@"about:blank")];
</code></pre>
<p>Edit(2015-05-12): As mentioned by @chibimai below, <a href="https://stackoverflow.com/a/7038152/281437">this answer by alloc_iNit works along the same lines</a> but since my answer is from 5 years ago -- and his only 4 -- the linked answer may be more applicable. I no longer do iPhone dev work so I cannot determine which is better either way.</p> |
2,787,679 | How to reload page every 5 seconds? | <p>I am converting one layout to html; once I make the changes in code/html/css, every time I have to hit F5. Is there any simple javascript/jQuery solution for this? I.e. after I add the script, reload the whole page every 5 seconds (or some other specific time).</p> | 2,787,691 | 11 | 0 | null | 2010-05-07 10:00:34.79 UTC | 63 | 2022-02-15 14:53:03.627 UTC | 2019-04-03 17:52:34.72 UTC | null | 8,112,776 | null | 88,493 | null | 1 | 210 | javascript|jquery | 643,542 | <pre><code> <meta http-equiv="refresh" content="5; URL=http://www.yourdomain.com/yoursite.html">
</code></pre>
<p>If it has to be in the script use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout" rel="noreferrer">setTimeout</a> like:</p>
<pre><code>setTimeout(function(){
window.location.reload(1);
}, 5000);
</code></pre> |
25,102,593 | Failed to load resource: the server responded with a status of 404 (Not Found) angular js + ionic | <p><img src="https://i.stack.imgur.com/rGa81.jpg" alt="enter image description here"></p>
<p>This is the error im having from Google Devt Tools. Anyone knows the problem? I tried to change in many times including the file structure and the stateProvider (no controllers for that) in app.js file but it does not seem to be the issue. (script is included in app.js with correct file name and directory)</p>
<p>In addition, my logout and submitPost buttons arent working as well. </p>
<p><br>
<strong>newpost.html</strong> </p>
<pre><code><div class="modal slide-in-up" ng-controller="NavCtrl">
<!-- Modal header bar -->
<header class="bar bar-header bar-secondary">
<button class="button button-clear button-primary" ng-click="close()">Cancel</button>
<h1 class="title">New Shout</h1>
<button class="button button-positive" ng-click="submitPost()">Done</button>
</header>
<!-- Modal content area -->
<ion-content class="padding has-header">
<form class ng-submit="submitPost()" ng-show="signedIn()">
<div class="form-group">
<input type="text" class="form-control" placeholder="Title" ng-model="post.title">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Link" ng-model="post.url">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</ion-content>
</div>
</code></pre>
<p><br>
<strong>controller.js file</strong> </p>
<pre><code>app.controller('NavCtrl', function ($scope, $firebase, $location, Post, Auth, $ionicModal) {
$scope.post = {url: 'http://', title: ''};
// Create and load the Modal
$ionicModal.fromTemplateUrl('newpost.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope,
animation: 'slide-in-up'
});
// Open our new task modal
$scope.submitPost = function () {
Post.create($scope.post).then(function (postId) {
$scope.post = {url: 'http://', title: ''};
$location.path('/posts/' + postId);
$scope.taskModal.show();
});
};
$scope.close = function() {
$scope.taskModal.hide();
};
$scope.logout = function () {
Auth.logout();
};
});
</code></pre>
<p><br>
<strong>List of items page, post.html</strong> </p>
<pre><code><ion-header-bar class="bar-positive" ng-controller="NavCtrl">
<button class="button button-clear" ng-click="submitPost()">New</button>
<h1 class="title"><b><a class="navbar-brand" href="#/posts">MyApp</a></b></h1>
<button class="button button-clear" ng-click="logout()">Logout</button>
</ion-header-bar>
</code></pre> | 25,102,721 | 3 | 0 | null | 2014-08-03 07:32:03.697 UTC | 3 | 2019-09-13 10:54:14.473 UTC | null | null | null | null | 3,395,829 | null | 1 | 6 | javascript|html|angularjs|angular-ui-router|ionic-framework | 98,757 | <p><strong>404</strong> literally means that file was not found. <strong>It's simple as that</strong>. Check if the URL is right, and there are no rediretions being done(use fiddler). Perhaps the protocol should be https:// istead of http://? Perhaps you need "<strong>www</strong>" in url? </p>
<p>Click the url given in Chrome and see if the file exists.</p> |
50,907,600 | Vue.js - Vuetify how to get rounded corners on cards? | <p>I am trying to get rounded corners on a v-card as I can get on a btn, but it does not seems to be possible ? </p>
<p>I used </p>
<pre><code><v-card round class="elevation-0">
</code></pre>
<p>Here is my template</p>
<pre><code> <template>
<section id="section2">
<v-parallax :src="require('../../assets/images/members.jpeg')" height="380">
<v-layout column align-center justify-center>
<v-flex xs12 sm12 md8>
<v-card round class="elevation-0">
<v-card-title primary-title class="layout justify-center">
<h3 v-html="$t('lang.views.home.section4.thank_you')" ></h3>
</v-card-title>
<v-card-text>
</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-parallax>
</section>
</template>
</code></pre> | 50,907,816 | 5 | 0 | null | 2018-06-18 10:36:42.477 UTC | 2 | 2021-09-10 10:01:00.87 UTC | null | null | null | user762579 | null | null | 1 | 15 | vue.js|vuetify.js | 38,585 | <p><code>v-card</code> has rounded corners by default. It does not provide a prop named <code>round</code> to make it have more rounded corners.</p>
<p>If you want to have more rounded corners as compared to the default then add a custom css class to <code>v-card</code></p>
<pre><code><v-card class="rounded-card">
</code></pre>
<h3>css</h3>
<pre><code>.rounded-card{
border-radius:50px;
}
</code></pre>
<p>Here is a <a href="https://codepen.io/anon/pen/gKXEdb?editors=1100" rel="noreferrer">codepen</a></p> |
42,379,899 | Use custom setter in Lombok's builder | <p>I have a custom setter in my Lombok-based POJO:</p>
<pre><code>@Data
@Builder
public class User {
private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
private String password = null;
public void setPassword(String password) {
Assert.notNull(password);
this.password = ENCODER.encode(password);
}
</code></pre>
<p>but when I use the Lombok generated builder:</p>
<pre><code>User user = User.builder()
.password(password)
.build();
</code></pre>
<p>my custom setter is not invoked, and so the password is not encoded. This makes me sad. </p>
<p>My custom setter is, of course, invoked when I use it directly:</p>
<pre><code>public void changePassword(String password, User user) {
user.setPassword(password);
}
</code></pre>
<p>What can I do to have Lombok's builder use my custom setter?</p> | 42,380,017 | 5 | 0 | null | 2017-02-21 23:23:11.347 UTC | 7 | 2021-05-19 19:53:21.793 UTC | 2017-02-22 14:07:30.483 UTC | null | 3,342,253 | null | 3,342,253 | null | 1 | 61 | java|lombok | 52,381 | <p>Per <a href="https://projectlombok.org/features/Builder.html" rel="noreferrer">the documentation for <code>@Builder</code></a>: Just define enough skeleton yourself. In particular, Lombok will generate a class <code>UserBuilder</code>, fields mirroring the <code>User</code> fields, and builder methods, and you can provide any or all of this yourself.</p>
<pre><code>@Builder
public class User {
private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
private String username;
private String password;
public static class UserBuilder {
public UserBuilder password(String password) {
this.password = ENCODER.encode(password);
return this;
}
}
}
</code></pre> |
6,097,301 | CallContext.LogicalGetData Vs. CallContext.GetData | <p>The <code>CallContext</code> API has <code>LogicalGetData</code> & <code>GetData</code>, but the MSDN Documentation doesn't do much to explain the difference between the two, and when they differ.</p>
<p>Any ideas?</p> | 6,098,134 | 2 | 0 | null | 2011-05-23 12:38:58.263 UTC | 10 | 2017-03-16 11:17:20.873 UTC | 2017-03-16 11:17:20.873 UTC | null | 4,275,342 | null | 766,006 | null | 1 | 47 | c#|.net | 16,549 | <p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.callcontext.aspx#remarksToggle" rel="noreferrer">It appears that this is a subtle difference related to method calls made remotely to another <code>AppDomain</code></a>. In this instance a <code>LogicalCallContext</code> is created and the data is stored in a manner accessible to <code>LogicalGetData</code>. While in normal, non-remoted method calls the data is stored in a manner accessible to <code>GetData</code>.</p>
<blockquote>
<p>When a remote method call is made to an object in another AppDomain, the CallContext class generates a LogicalCallContext instance that travels along with the remote call. Only objects that expose the ILogicalThreadAffinative interface and are stored in the CallContext are propagated outside the AppDomain in a LogicalCallContext. Objects that do not support this interface are not transmitted in LogicalCallContext instances with remote method calls.</p>
</blockquote>
<p><code>GetData</code>:</p>
<blockquote>
<p>Retrieves an object with the specified name from the <code>CallContext</code>.</p>
</blockquote>
<p><code>LogicalGetData</code>:</p>
<blockquote>
<p>Retrieves an object with the specified name from the logical call context.</p>
</blockquote> |
31,655,085 | Database on a personal github page | <p>Is it possible to have some data stored somewhere on your personal github page?</p>
<p>For example a button that triggers a counter. When you click on the button , counter increments by 1. When other user visits that page and clicks the button , counter gets incremented by 1 once again.</p>
<p>So it would be a sum of all click across all visitors that would be displayed on the page.</p> | 31,655,819 | 4 | 1 | null | 2015-07-27 13:55:51.74 UTC | 32 | 2021-08-18 21:40:46.377 UTC | 2017-02-09 09:03:52.98 UTC | null | 4,403,497 | null | 4,403,497 | null | 1 | 61 | database|github | 76,739 | <p>Github pages only allow for static content, so you'd have to use something like <a href="https://firebase.google.com/" rel="noreferrer">firebase</a> in order to get a database.</p> |
41,213,215 | Webpack dev server not auto-reloading | <p>So I've setup webpack and <code>webpack-dev-server</code>, but <code>webpack-dev-server</code> does not auto-reload. If i modify a file and save it there is no change in the browser until I manually refresh.</p>
<p>Here is my webpack config and my script file that runs <code>webpack-dev-server</code>. Does anyone see anything that could be preventing auto-reload from working?</p>
<p><em>I put these together by reading through multiple tutorials, the docs, and by reading through the <code>react-create-app</code> generated files.</em></p>
<hr>
<p><strong>config/webpack.config.dev.js</strong></p>
<pre><code>'use strict';
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const extractSass = new ExtractTextPlugin('style.css');
module.exports = {
entry : './src/index.jsx',
eslint: {configFile: './src/.eslintrc.json'},
module: {
loaders: [
{
exclude: /node_modules/,
include: ['src'],
loader: 'babel',
test : /(\.js|\.jsx)$/
},
{
exclude: /node_modules/,
include: ['src']
loader : extractSass.extract([ 'css', 'postcss', 'sass' ]),
test : /\.scss$/
}
],
preLoaders: [
{
exclude: /node_modules/,
loader : 'eslint',
query : {presets: [ 'react', 'latest' ]},
test : /(\.js|\.jsx)$/
}
]
},
output: {
filename : 'bundle.js',
path : 'dist',
publicPath: '/'
},
plugins: [
extractSass,
new HtmlWebpackPlugin({
inject : true,
template: paths.appHtml
}),
new webpack.HotModuleReplacementPlugin({multistep: true})
],
postcss: () => [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9'
]
})
]
};
</code></pre>
<hr>
<p><strong>scripts/dev.js</strong></p>
<p><em>run with <code>$ yarn run dev</code></em></p>
<pre><code>'use strict';
const WebpackDevServer = require('webpack-dev-server');
const config = require('../config/webpack.config.dev.js');
const webpack = require('webpack');
const compiler = webpack(config);
const server = new WebpackDevServer(compiler, {
clientLogLevel : 'warn',
compress : true,
contentBase : 'public',
filename : config.output.filename,
historyApiFallback: true,
hot : true,
inline : true,
lazy : false,
noInfo : true,
publicPath : '/',
quiet : true,
stats : 'errors-only',
watchOptions : {
aggregateTimeout: 300,
poll : 1000
}
});
server.listen(8080, 'localhost', () => {
console.log('Listening on port 8080');
});
</code></pre> | 41,223,040 | 9 | 0 | null | 2016-12-18 21:45:17.587 UTC | 2 | 2021-08-04 04:08:47.513 UTC | 2016-12-18 21:52:00.14 UTC | null | 2,525,699 | null | 2,525,699 | null | 1 | 20 | javascript|webpack|webpack-dev-server | 40,343 | <p>According to the <a href="https://webpack.github.io/docs/webpack-dev-server.html#inline-mode-with-node-js-api" rel="noreferrer">webpack dev server documentation</a> you should add this entry point to the webpack configuration to support automatic refresh.</p>
<pre><code>config.entry.unshift("webpack-dev-server/client?http://localhost:8080/");
</code></pre> |
20,954,944 | Stop LastPass filling out a form | <p>Is there a way to prevent the LastPass browser extension from filling out a HTML-based form with an input field with the name "username"?</p>
<p>This is an hidden field, so I don't want any software to use this field for their purposes:</p>
<pre><code><input type="text" name="username" id="checkusername" maxlength="9" value="1999" class="longinput" style="display:none">
</code></pre>
<p>The solution should not be like "rename the input field".</p> | 44,984,917 | 16 | 2 | null | 2014-01-06 16:49:41.397 UTC | 28 | 2021-12-16 14:33:45.03 UTC | 2021-12-16 14:33:45.03 UTC | null | 74,089 | null | 2,969,320 | null | 1 | 180 | html|forms|lastpass | 63,507 | <p>Adding</p>
<pre><code>data-lpignore="true"
</code></pre>
<p>to an input field disabled the grey LastPass [...] box for me.</p>
<p>Sourced from <a href="https://support.logmeininc.com/lastpass/help/manage-your-form-fills-lp040002" rel="noreferrer">LastPass.com</a></p> |
35,424,982 | How can I enable the MySQLi extension in PHP 7? | <p>I have installed PHP 7 and MySQL 5.5.47 on Ubuntu 14.04 (Trusty Tahr).</p>
<p>I have checked installed extension using:</p>
<pre><code>sudo apt-cache search php7-*
</code></pre>
<p>It outputs:</p>
<pre><code>php7.0-common - Common files for packages built from the PHP source
libapache2-mod-php7.0 - server-side, HTML-embedded scripting language (Apache 2 module)
php7.0-cgi - server-side, HTML-embedded scripting language (CGI binary)
php7.0-cli - command-line interpreter for the PHP scripting language
php7.0-phpdbg - server-side, HTML-embedded scripting language (PHPDBG binary)
php7.0-fpm - server-side, HTML-embedded scripting language (FPM-CGI binary)
libphp7.0-embed - HTML-embedded scripting language (Embedded SAPI library)
php7.0-dev - Files for PHP7.0 module development
php7.0-dbg - Debug symbols for PHP7.0
php7.0-curl - CURL module for PHP
php7.0-enchant - Enchant module for PHP
php7.0-gd - GD module for PHP
php7.0-gmp - GMP module for PHP
php7.0-imap - IMAP module for PHP
php7.0-interbase - Interbase module for PHP
php7.0-intl - Internationalisation module for PHP
php7.0-ldap - LDAP module for PHP
php7.0-mcrypt - libmcrypt module for PHP
php7.0-readline - readline module for PHP
php7.0-odbc - ODBC module for PHP
php7.0-pgsql - PostgreSQL module for PHP
php7.0-pspell - pspell module for PHP
php7.0-recode - recode module for PHP
php7.0-snmp - SNMP module for PHP
php7.0-tidy - tidy module for PHP
php7.0-xmlrpc - XMLRPC-EPI module for PHP
php7.0-xsl - XSL module for PHP
php7.0 - server-side, HTML-embedded scripting language (metapackage)
php7.0-json - JSON module for PHP
php-all-dev - package depending on all supported PHP development packages
php7.0-sybase - Sybase module for PHP
php7.0-sqlite3 - SQLite3 module for PHP
php7.0-mysql - MySQL module for PHP
php7.0-opcache - Zend OpCache module for PHP
php7.0-bz2 - bzip2 module for PHP
</code></pre>
<p>I am not able to see the MySQLi extension using phpinfo() either. How can I enable/install MySQLi extension in PHP 7?</p>
<p>That's why I cannot use phpMyAdmin. It says "The mysqli extension is missing."</p> | 35,425,511 | 8 | 0 | null | 2016-02-16 06:06:52.473 UTC | 30 | 2021-03-25 12:23:37.413 UTC | 2019-12-30 12:25:48.247 UTC | null | 3,238,278 | null | 3,238,278 | null | 1 | 86 | php|mysql|mysqli|php-7 | 421,583 | <p>I got the solution. I am able to enable MySQLi extension in php.ini. I just uncommented this line in php.ini:</p>
<pre><code>extension=php_mysqli.dll
</code></pre>
<p>Now MySQLi is working well. Here is the <code>php.ini</code> file path in an Apache 2, PHP 7, and Ubuntu 14.04 environment:</p>
<pre><code>/etc/php/7.0/apache2/php.ini
</code></pre>
<p>By default, the MySQLi extension is disabled in PHP 7.</p> |
18,930,436 | iOS 7 UIImagePickerController Camera No Image | <p>For some reason the first time I open the <code>UIImagePickerController</code> in camera mode on my app it comes up blank. I have to close and reopen that view to get the camera feed to start working. I'm using the standard code that works in iOS 6 perfectly for camera capture. From the sample below I'm firing the <code>capturePhoto:</code> method. Anyone else running into this jenkiness with the iOS 7 camera? I checked the Apple dev forums but its near impossible to find answers there.</p>
<pre><code>- (IBAction)capturePhoto:(id)sender {
[self doImagePickerForType:UIImagePickerControllerSourceTypeCamera];
}
- (void)doImagePickerForType:(UIImagePickerControllerSourceType)type {
if (!_imagePicker) {
_imagePicker = [[UIImagePickerController alloc] init];
_imagePicker.mediaTypes = @[(NSString*)kUTTypeImage];
_imagePicker.delegate = self;
}
_imagePicker.sourceType = type;
[self presentViewController:_imagePicker animated:YES completion:nil];
}
</code></pre>
<p><img src="https://i.stack.imgur.com/FGpMW.png" alt="why so empty?"></p> | 19,073,930 | 4 | 0 | null | 2013-09-21 08:15:07.84 UTC | 11 | 2014-09-14 11:36:56.567 UTC | 2013-09-22 07:29:57.197 UTC | null | 246,589 | null | 246,589 | null | 1 | 8 | ios|ios7 | 12,677 | <p>I'm also using UIImagePickerController and ran into the same issue with a blank screen. I'd like to expand a little on what klaudz mentioned regarding iOS 7 authorization for the camera.</p>
<p>Reference:
<a href="https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVCaptureDevice_Class/Reference/Reference.html" rel="noreferrer">https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVCaptureDevice_Class/Reference/Reference.html</a></p>
<p>"Recording audio always requires explicit permission from the user; recording video also requires user permission on devices sold in certain regions."</p>
<p>Here is some code fragments you can start with to check to see if you have permission for the camera and request it if your app hadn't previously requested it. If you are denied due to an earlier request, your app may need to put up a notice to the user to go into settings to manually enable access as klaudz pointed out.</p>
<p><strong>iOS 7 example</strong></p>
<pre><code>NSString *mediaType = AVMediaTypeVideo; // Or AVMediaTypeAudio
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
// This status is normally not visible—the AVCaptureDevice class methods for discovering devices do not return devices the user is restricted from accessing.
if(authStatus == AVAuthorizationStatusRestricted){
NSLog(@"Restricted");
}
// The user has explicitly denied permission for media capture.
else if(authStatus == AVAuthorizationStatusDenied){
NSLog(@"Denied");
}
// The user has explicitly granted permission for media capture, or explicit user permission is not necessary for the media type in question.
else if(authStatus == AVAuthorizationStatusAuthorized){
NSLog(@"Authorized");
}
// Explicit user permission is required for media capture, but the user has not yet granted or denied such permission.
else if(authStatus == AVAuthorizationStatusNotDetermined){
[AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
// Make sure we execute our code on the main thread so we can update the UI immediately.
//
// See documentation for ABAddressBookRequestAccessWithCompletion where it says
// "The completion handler is called on an arbitrary queue."
//
// Though there is no similar mention for requestAccessForMediaType, it appears it does
// the same thing.
//
dispatch_async(dispatch_get_main_queue(), ^{
if(granted){
// UI updates as needed
NSLog(@"Granted access to %@", mediaType);
}
else {
// UI updates as needed
NSLog(@"Not granted access to %@", mediaType);
}
});
}];
}
else {
NSLog(@"Unknown authorization status");
}
</code></pre> |
18,900,249 | google.maps.places and its Autocomplete method are undefined | <p>I'm loading the <a href="https://developers.google.com/maps/documentation/javascript/" rel="noreferrer">Google Maps API</a>, <a href="http://jquery.com/" rel="noreferrer">jQuery</a> and this <a href="http://ubilabs.github.io/geocomplete/" rel="noreferrer">Geocomplete</a> plugin.
Please note that I'm also specifying the libraries (<em>libraries=places</em>) and eventually my <em>API key</em>:</p>
<pre><code><script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script src='http://maps.googleapis.com/maps/api/js?v=3&sensor=false&amp;libraries=places&key=xxx'></script>
<script src='js/vendor/jquery.geocomplete.js'></script>
</code></pre>
<p>I'm triggering the Geocomplete plugin on the page load</p>
<pre><code>$(window).load(function () {
$('#my-input').geocomplete();
});
</code></pre>
<p>but I always get an error:</p>
<p><em>Uncaught TypeError: Cannot read property 'Autocomplete' of undefined [jquery.geocomplete.js:153]</em>.</p>
<p>Inside the plugin...</p>
<pre><code>this.autocomplete = new google.maps.places.Autocomplete(
this.input, options
);
</code></pre>
<p>I tried to <em>google.maps</em> and it returns a regular object, but places is <em>undefined</em>!</p> | 18,905,094 | 1 | 0 | null | 2013-09-19 16:30:02.39 UTC | 5 | 2018-11-19 17:30:30.47 UTC | 2018-02-21 10:58:47.387 UTC | null | 1,905,949 | null | 334,210 | null | 1 | 24 | javascript|jquery|google-maps | 50,072 | <blockquote>
<p>I tried to google.maps and it returns a regular object, but places is undefined!</p>
</blockquote>
<p>That means the google.maps.places library is not loading (the line of code that you posted, shown below is either not correct or is not actually on your page):</p>
<pre><code><script src='http://maps.googleapis.com/maps/api/js?v=3&sensor=false&amp;libraries=places&key=xxx'></script>
</code></pre>
<p>This is the example from the documentation:</p>
<pre><code><script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
</code></pre>
<p>The only obvious difference is the <code>&amp;</code> in yours, that should work, but you should probably use it consistently. </p>
<p><strong>TL;DR</strong></p>
<p>Use <code>&libraries</code> not <code>&amp;libraries</code> and it will work.</p> |
51,791,618 | SQL "with" clause - Error Code: 1046. No database selected Select the default DB to be used by double-clicking its name in the SCHEMAS | <p>I have the following query which works fine:</p>
<pre><code>select a.dataId, a.my_no, b.my_attribute from myDB.table_a a left join myDB.table_b b
on a.my_no = b.my_no order by dataId
</code></pre>
<p>However, if I include the <code>with</code> clause like below:</p>
<pre><code>with my_table as (
select a.dataId, a.my_no, b.my_attribute from myDB.table_a a left join myDB.table_b b
on a.my_no = b.my_no order by dataId
)
select * from my_table
</code></pre>
<p>I got the following error:</p>
<pre><code>Error Code: 1046. No database selected Select the default DB to be used by double-clicking its name in the SCHEMAS list in the sidebar.
</code></pre>
<p>This is confusing ... shouldn't these two queries be identical? What did I do wrong here? (I am using MariaDB server) Thanks!</p> | 51,791,751 | 6 | 0 | null | 2018-08-10 17:45:23.29 UTC | 3 | 2022-04-22 12:06:58.29 UTC | null | null | null | null | 3,993,270 | null | 1 | 7 | mysql|mariadb | 50,323 | <p>Before a <code>WITH</code> clause, you should specify the database you're using with</p>
<pre><code>USE db_name;
</code></pre>
<p>That should solve the problem.</p> |
8,441,708 | WCF : How to disable WCF Test Client | <p>I created a new WCF Application. It has a svc file & a code behind, When I try to debug (F5) then I see the following.</p>
<ol>
<li>If svc file is open & press F5 then it opens the web browser</li>
<li>If code behind file is currently open & press F5 then WCF Test client opens.</li>
</ol>
<p>Why there are different behavior? I do not want to use Test Client, how to disable it in the app so that it would not come again.</p>
<p>Atul Sureka</p> | 8,441,887 | 8 | 0 | null | 2011-12-09 06:06:33.2 UTC | 11 | 2019-04-01 14:09:14.55 UTC | null | null | null | null | 883,766 | null | 1 | 24 | wcf|wcftestclient | 28,647 | <p>Open your project properties, go to the Debug tab, under <em>start options</em> you will see something like
/client:"WcfTestClient.exe"</p>
<p>delete that line.</p>
<p>For a WCF Service Application and WCF Workflow Service Application you need to modify the .csproj.user file. A full write up <a href="http://blogs.msdn.com/b/wcftoolsteamblog/archive/2010/01/04/tips-for-launching-wcf-test-client.aspx">can be found here</a>.</p>
<p>The key part is </p>
<pre><code> <WebProjectProperties>
<EnableWcfTestClientForSVC>False</EnableWcfTestClientForSVC>
</WebProjectProperties>
</code></pre> |
8,626,018 | How to check if file exists in a Windows Store App? | <p>Is there any other way of checking whether a file exists in a Windows Store app?</p>
<pre><code>try
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("Test.xml");
//no exception means file exists
}
catch (FileNotFoundException ex)
{
//find out through exception
}
</code></pre> | 8,626,046 | 10 | 0 | null | 2011-12-24 17:51:53.27 UTC | 6 | 2015-08-11 18:00:06.98 UTC | 2014-01-14 08:22:19.14 UTC | null | 53,236 | null | 421,611 | null | 1 | 48 | c#|windows-8|windows-runtime|microsoft-metro|filenotfoundexception | 34,206 | <p>According to the accepted answer in <a href="http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/1eb71a80-c59c-4146-aeb6-fefd69f4b4bb/">this post</a>, there is no other way at the moment. However, the File IO team is considering changing the the api so that it returns null instead of throwing an exception. </p>
<p>Quote from the linked post:</p>
<blockquote>
<p>Currently the only way to check if a file exists is to catch the
FileNotFoundException. As has been pointed out having an explicit
check and the opening is a race condition and as such I don't expect
there to be any file exists API's added. I believe the File IO team
(I'm not on that team so I don't know for sure but this is what I've
heard) is considering having this API return null instead of throwing
if the file doesn't exist.</p>
</blockquote> |
27,085,219 | How Can I Disable Authentication in Django REST Framework | <p>I'm working on a store site, where every user is going to be anonymous (well, until it's time to pay at least), and I'm trying to use Django REST Framework to serve the product API, but it keeps complaining about:</p>
<pre><code>"detail": "Authentication credentials were not provided."
</code></pre>
<p>I found some settings related to authentication, but I couldn't find anything like <code>ENABLE_AUTHENTICATION = True</code>. How do I simply disable authentication, and let any visitor to the site access the API?</p> | 27,086,121 | 8 | 1 | null | 2014-11-23 03:15:31.25 UTC | 13 | 2022-09-19 11:42:36.063 UTC | 2022-04-03 19:02:17.81 UTC | null | 6,562,458 | null | 5,921 | null | 1 | 76 | django|authentication|django-rest-framework | 64,776 | <p>You can give empty defaults for the <a href="http://www.django-rest-framework.org/api-guide/permissions#setting-the-permission-policy">permission</a> and <a href="http://www.django-rest-framework.org/api-guide/authentication#setting-the-authentication-scheme">authentication</a> classes in your settings.</p>
<pre><code>REST_FRAMEWORK = {
# other settings...
'DEFAULT_AUTHENTICATION_CLASSES': [],
'DEFAULT_PERMISSION_CLASSES': [],
}
</code></pre> |
27,324,020 | No valid 'aps-environment' entitlement string found for application on app store | <p>So I have this app called Dripper that I put out about a month ago and then an update a couple days ago. The update added push notifications and a few little tweaks. I tested it with the sandbox-apn using the development profile and things worked great. Then I switched things to the production-apn and pushed it to test-flight, again things worked perfectly. Once I put update on the market and ran it I noticed I wasn’t getting any new push registrations on the server. I looked at the console logs for the device and found this:</p>
<blockquote>
<p>Dec 4 17:55:15 Ina-touch-it coffco[1210] : Registering for remote notifications<br/>
Dec 4 17:55:15 Ina-touch-it SpringBoard[52] : No valid 'aps-environment' entitlement string found for application 'Dripper': (null). Notifications will not be delivered.<br/>
Dec 4 17:55:15 Ina-touch-it coffco[1210] <code><Warning>: Failed to register with error : Error Domain=NSCocoaErrorDomain Code=3000 "no valid 'aps-environment' entitlement string found for application" UserInfo=0x174270900 {NSLocalizedDescription=no valid 'aps-environment' entitlement string found for application}</code></p>
</blockquote>
<p>I am a bit confused because I thought that the production-apn would function the same between ad-hoc and app store builds.</p>
<p>Here is my app id and its entitlements:</p>
<p><a href="https://i.stack.imgur.com/uf4pB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uf4pB.png" alt="enter image description here" /></a></p>
<p>Here is the provisioning profile for the apps store:</p>
<p><a href="https://i.stack.imgur.com/AYOV5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AYOV5.png" alt="enter image description here" /></a></p> | 33,015,254 | 10 | 1 | null | 2014-12-05 20:18:42.953 UTC | 17 | 2021-01-10 12:35:08.967 UTC | 2021-01-10 12:35:08.967 UTC | null | 5,175,709 | null | 2,162,648 | null | 1 | 126 | ios|xcode|apple-push-notifications|app-store|entitlements | 103,324 | <p>I fix this problem by enabling push notification capability.</p>
<p>Click on .xcodeproj -> Capabilities -> Enable Push Notification</p>
<p><a href="https://i.stack.imgur.com/jvRFy.png"><img src="https://i.stack.imgur.com/jvRFy.png" alt=""></a></p> |
26,675,490 | Unexpectedly found nil while unwrapping optional value | <p>In my app I am checking to see whether a post has a picture or not.</p>
<p>For this I am using:</p>
<pre><code>if pictures[string]? != nil {
if var image: NSData? = pictures[string]? {
imageView.image = UIImage(data: image!)
}
}
</code></pre>
<p>However, it still comes up with the error:</p>
<blockquote>
<p>fatal error: unexpectedly found nil while unwrapping an Optional value.</p>
</blockquote>
<p>I'm sure it is something easy to fix but I am quite new to this - what am I doing wrong?</p> | 26,675,638 | 4 | 0 | null | 2014-10-31 13:08:55.367 UTC | 4 | 2019-02-19 20:50:21.72 UTC | 2016-01-25 22:00:36.94 UTC | null | 1,677,912 | null | 3,941,176 | null | 1 | 8 | ios|iphone|xcode|swift | 41,360 | <p>Try doing it this way:</p>
<pre><code>if let imageData = pictures[string] {
if let image = UIImage(data: imageData) {
imageView.image = image
}
}
</code></pre>
<p>Assuming that <code>string</code> is a valid key.</p>
<p>You are dealing with optionals, so conditionally unwrap each return object before using it.</p>
<p>Forced unwrapping is dangerous and should only be used when you are <strong>absolutely</strong> sure that an optional contains a value. Your imageData may not be in the correct format to create an image, but you are forcibly unwrapping it anyway. This is okay to do in Objective-C as it just means <code>nil</code> objects get passed around. Swift is not so tolerant.</p> |
255,714 | Syntax for putting a block on a single line | <p>So I've got a Ruby method like this:</p>
<pre><code>def something(variable, &block)
....
end
</code></pre>
<p>And I want to call it like this:</p>
<pre><code>something 'hello' { do_it }
</code></pre>
<p>Except that isn't working for me, I'm getting a syntax error. If I do this instead, it works:</p>
<pre><code>something 'hello' do
do_it
end
</code></pre>
<p>Except there I'm kind of missing the nice look of it being on one line.</p>
<p>I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. Is there?</p> | 255,791 | 3 | 0 | null | 2008-11-01 16:04:21.37 UTC | 2 | 2008-11-02 19:36:33.92 UTC | 2008-11-02 19:36:33.937 UTC | Romulo A. Ceccon | 23,193 | Cameron Booth | 14,873 | null | 1 | 30 | ruby|syntax | 13,464 | <p>You need to parenthesize your argument:</p>
<pre><code>something('hello') { do_it }
</code></pre>
<p>That should work.</p> |
973,146 | How to include header files in GCC search path? | <p>I have the following code in a sample file:</p>
<pre><code>#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkGLCanvas.h"
#include "SkGraphics.h"
#include "SkImageEncoder.h"
#include "SkPaint.h"
#include "SkPicture.h"
#include "SkStream.h"
#include "SkWindow.h"
</code></pre>
<p>However, this code is located in various folders within /home/me/development/skia (which includes core/ animator/ images/ ports/ svg/ and a lot more.)</p>
<p>How can I make GCC recognize this path?</p> | 973,158 | 3 | 2 | null | 2009-06-10 00:20:38.347 UTC | 17 | 2020-11-20 10:10:09.787 UTC | 2011-11-08 12:40:04.42 UTC | null | 11,343 | null | 120,172 | null | 1 | 72 | c++|gcc|header | 186,814 | <p>Try <code>gcc -c -I/home/me/development/skia sample.c</code>.</p> |
39,506,619 | angular2: how to copy object into another object | <p>Please help me in order to copy the object into another object using angular 2?</p>
<p>In angular, I used angular.copy() to copy objects to the loose reference of the old objects. But, when I used the same in angular 2 getting below error:</p>
<blockquote>
<p>Error: angular is not defined.</p>
</blockquote> | 39,506,676 | 10 | 1 | null | 2016-09-15 08:42:31.733 UTC | 16 | 2022-09-08 07:21:46.043 UTC | 2020-08-10 13:22:25.677 UTC | null | 706,020 | null | 6,747,259 | null | 1 | 83 | angular|typescript | 154,420 | <p><strong>Solution</strong></p>
<p>Angular2 developed on the ground of modern technologies like TypeScript and ES6.</p>
<p>So you can just do <code>let copy = Object.assign({}, myObject)</code>.</p>
<p><a href="https://angular-training-guide.rangle.io/immutable/javascript-solutions/object_assign" rel="nofollow noreferrer">Object assign</a> - nice examples.</p>
<p><strong>For nested objects</strong> :
<code>let copy = JSON.parse(JSON.stringify(myObject))</code></p> |
56,284,370 | Remove self element onclick | <p>I have an element that is added using javascript to my HTML document. I am trying to remove it when I click on that same element. I do not know the id of the element yet, I have just included a sample id for now.</p>
<p>I have already tried looking at this answer here (<a href="https://stackoverflow.com/questions/15650131/creating-an-element-that-can-remove-it-self">Creating an element that can remove it self?</a>) and tried using the method provided here (<a href="https://stackoverflow.com/questions/619514/javascript-how-to-make-a-control-send-itself-in-a-method">Javascript: How to make a Control send itself in a method</a>) as well to reference the element but have had no luck.</p>
<p>Here is what I have so far.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function remove() {
var element = this.id;
//I have also tried using document.getElementByID(this.id)
element.remove();
//I have also tried using element.parentNode.removeChild(element); to remove the element.
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="i" onclick="remove(this)">Sample text</div></code></pre>
</div>
</div>
</p>
<p>I am not sure what I am doing wrong but this is the error I keep getting.</p>
<blockquote>
<p>"Uncaught TypeError: Cannot read property 'remove' of undefined"</p>
</blockquote> | 56,284,459 | 9 | 1 | null | 2019-05-24 00:15:11.82 UTC | 3 | 2021-02-03 18:10:03.75 UTC | null | null | null | null | 9,253,840 | null | 1 | 12 | javascript|html | 53,166 | <p>You have to pass <code>this</code> through the function call in html <code>onclick</code> so it could refer to the element then you have to use it as parameter in the function definition, otherwise, if you use <code>this</code> in the function definition, it will just refer to the window object.</p>
<p>This will work fine
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function remove(el) {
var element = el;
element.remove();
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="i" onclick="remove(this)">Sample text</div></code></pre>
</div>
</div>
</p> |
6,158,907 | What does Python treat as reference types? | <p>I assumed sequence types in Python were value types. It turns out they're reference types (Meaning that the value of a variable won't be copied when assigned to a new variable, but referenced). So now I'm wondering, what are the value types in Python? That is, what types in Python can I assign to new variables without worrying that the variable was referenced?</p> | 6,158,918 | 3 | 0 | null | 2011-05-28 00:36:43.683 UTC | 13 | 2021-07-05 03:29:09.767 UTC | null | null | null | null | 388,916 | null | 1 | 29 | python|sequences|value-type|reference-type | 19,040 | <p><em>All</em> values in Python are references. What you need to worry about is if a type is <strong>mutable</strong>. The basic numeric and string types, as well as <code>tuple</code> and <code>frozenset</code> are immutable; names that are bound to an object of one of those types can only be rebound, not mutated.</p>
<pre><code>>>> t = 1, 2, 3
>>> t[1] = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
</code></pre> |
6,270,354 | How to open warning/information/error dialog in Swing? | <p>How to open warning/information/error dialog in Swing?</p>
<p>I need standard error dialog with "Ok" button and "red cross" image.
I.e. analog of <code>org.eclipse.jface.dialogs.MessageDialog.openError()</code></p> | 6,270,381 | 4 | 0 | null | 2011-06-07 19:10:38.873 UTC | 7 | 2022-07-25 05:51:45.123 UTC | 2021-01-02 08:50:51.823 UTC | null | 213,269 | null | 93,647 | null | 1 | 48 | java|swing | 136,792 | <p>See <a href="http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html" rel="noreferrer">How to Make Dialogs</a>.</p>
<p>You can use:</p>
<pre><code>JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
</code></pre>
<p>And you can also change the symbol to an error message or an warning. E.g see <a href="http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html#features" rel="noreferrer">JOptionPane Features</a>.</p> |
52,484,812 | ReactJS: Material ui breakpoints | <p>What is the difference between <code>breakpoints.up</code>, <code>breakpoints.down</code>, <code>breakpoints.between</code> and <code>breakpoints.value</code> ?
And what is meant by this code, how breakpoints value is working here? Is <code>theme.spacing.unit*2*2 = theme.spacing.unit*4</code> or it has some other meaning?</p>
<pre><code>[theme.breakpoints.up(600 + theme.spacing.unit * 2 * 2)]: {
width: 600,
marginLeft: 'auto',
marginRight: 'auto',
},
</code></pre> | 52,490,042 | 1 | 2 | null | 2018-09-24 17:51:55.99 UTC | 13 | 2019-10-02 08:19:18.773 UTC | 2018-09-26 07:49:34.13 UTC | null | 8,255,883 | null | 10,379,605 | null | 1 | 29 | reactjs|responsive-design|media-queries|material-ui|breakpoints | 51,997 | <p>Material uses the following set of breakpoints. You can customize the <em>values</em> of this breakpoint in the theme. </p>
<p><a href="https://material-ui.com/customization/breakpoints/" rel="noreferrer">Breakpoint documentation</a></p>
<blockquote>
<p>A breakpoint is the range of predetermined screen sizes that have specific layout requirements.</p>
<ul>
<li><strong>xs</strong> (extra-small): 0px or larger</li>
<li><strong>sm</strong> (small): 600px or larger</li>
<li><strong>md</strong> (medium): 960px or larger</li>
<li><strong>lg</strong> (large): 1280px or larger</li>
<li><strong>xl</strong> (extra-large): 1920px or larger</li>
</ul>
</blockquote>
<p>The functions you asked about (<code>up</code>, <code>down</code>, <code>between</code>) are helpers for creating media queries using the breakpoints defined in the theme. </p>
<p>Note: <code>breakpoints.up()</code> and <code>breakpoints.down()</code> also accept a number, which will be converted to pixels. This is not true of the other methods. </p>
<h3>breakpoints.up(breakpoint | number)</h3>
<p>Creates a <strong>min-width</strong> media query that targets screen sizes greater than or equal to the given breakpoint. </p>
<pre class="lang-js prettyprint-override"><code>// Styles will be applies to screen sizes from "sm" and up
[theme.breakpoints.up('sm')]: {
// styles
}
</code></pre>
<h3>breakpoints.down(breakpoint | number)</h3>
<p>Takes a breakpoint name and creates a <strong>max-width</strong> media query that targets screen sizes up to <em>and including</em> the given breakpoint. </p>
<p>Because this is inclusive, the max-width will be the value of the next breakpoint up.</p>
<pre class="lang-js prettyprint-override"><code>// Styles will be applies to screen sizes from 0 up to and including "md"
[theme.breakpoints.down('md')]: {
// styles
}
</code></pre>
<h3>breakpoints.between(start, end)</h3>
<p>Takes two breakpoint names, and creates a media query that targets screen sizes from the first breakpoint, up to <em>and including</em> the second breakpoint. </p>
<pre class="lang-js prettyprint-override"><code>// Styles will be applies to screen sizes from "sm" up to
// and including "lg"
[theme.breakpoints.between('sm', 'lg')]: {
// styles
}
</code></pre>
<hr>
<h3>breakpoints.values</h3>
<p>An object containing the breakpoint values defined in the theme</p>
<pre class="lang-js prettyprint-override"><code>{xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920}
</code></pre>
<h3>breakpoints.width(breakpoint)</h3>
<p>This function is used to get the value of a specific breakpoint. </p>
<pre class="lang-js prettyprint-override"><code>theme.breakpoints.width('sm') // => 600
</code></pre> |
5,810,635 | Is there a quick way to convert a JavaScript object to valid JSON in the text editor? | <p>I have a big old config object. Something like:</p>
<pre><code>var object = {
item1: 'value1',
item2: 1000,
item3: ['a', 'b', 'c'],
item4: [1, 2, 3],
item5: {
foo: 'bar'
}
};
</code></pre>
<p>... and so on. I want to rewrite it as valid JSON so it can travel through the intertubes, but I don't want to go through every line in my file manually adding double quotes all over the place. Of course, I don't mind manually wrapping the whole thing in brackets and changing the initial assignment to be the first property, but beyond that I was hoping there's some resource that will do the grunt work.</p>
<p>Anyway, please help me out if know of a TextMate command, regex trick, online converter, friendly robot, or anything else that will make this less tedious. </p> | 5,810,716 | 5 | 2 | null | 2011-04-27 21:10:53.67 UTC | 12 | 2019-02-15 17:38:02.45 UTC | 2011-04-27 21:12:53.07 UTC | null | 68,587 | null | 174,676 | null | 1 | 36 | javascript|json|text-editor | 33,451 | <ol>
<li>Launch Firefox/Chrome/Safari</li>
<li>Open Firebug/developer tools</li>
<li>Copy/paste your code into the console.</li>
<li><p>Then type <code>console.log(JSON.stringify(object))</code> and voila!</p>
<pre><code>{"item1":"value1","item2":1000,"item3":["a","b","c"],
"item4":[1,2,3],"item5":{"foo":"bar"}}
</code></pre></li>
<li>Copy/paste back into your text editor.</li>
</ol>
<hr>
<p>For more control over the formatting, I have a free online webpage:</p>
<h3><a href="http://phrogz.net/JS/NeatJSON" rel="noreferrer">http://phrogz.net/JS/NeatJSON</a></h3>
<p>that lets you paste JSON or JS values in one box and see JSON at the bottom, with lots of knobs and sliders to adjust how it looks. For example, the JS value <code>["foo","bar",{dogs:42,piggies:0,cats:7},{jimmy:[1,2,3,4,5],jammy:3.14159265358979,hot:"pajammy"}]</code> can be formatted like any of the following (and more):</p>
<pre class="lang-json prettyprint-override"><code>[
"foo", <- adjustable indentation
"bar",
{"dogs":42,"piggies":0,"cats":7}, <- small objects on one line!
{
"jimmy":[1,2,3,4,5], <- small arrays on one line!
"jammy":3.142, <- decimal precision!
"hot":"pajammy"
}
]
</code></pre>
<pre class="lang-json prettyprint-override"><code>[
"foo",
"bar",
{ "cats":7, "dogs":42, "piggies":0 }, <- spaces inside braces!
{
"hot":"pajammy", <- sort object keys!
"jammy":3.14159265358979,
"jimmy":[ 1, 2, 3, 4, 5 ] <- spaces after commas!
}
]
</code></pre>
<pre class="lang-json prettyprint-override"><code>[ "foo", <- 'short' format puts first value
"bar", <- on same line as opening bracket...
{ "dogs" : 42,
"piggies" : 0,
"cats" : 7 }, <- ...and close bracket with last value!
{ "jimmy" : [ 1, 2, 3, 4, 5 ],
"jammy" : 3.14159265358979, <- spaces around colons!
"hot" : "pajammy" } ] <- align object values!
</code></pre>
<p><a href="http://phrogz.net/JS/NeatJSON/" rel="noreferrer"><img src="https://i.stack.imgur.com/RoLm0.png" alt="Screenshot of NeatJSON webpage"></a></p> |
6,310,620 | How to get relative path in Javascript? | <p>In my ASP.net web project, I've written the following Javascript code in a .js file:</p>
<pre><code>function getDeviceTypes() {
var deviceTypes;
$.ajax({
async: false,
type: "POST",
url: "Controls/ModelSelectorWebMethods.aspx/getDeviceTypes",
data: '{ }',
contentType: "application/json;",
dataType: "json",
success: function(response) {
deviceTypes = response.d;
},
error: function(xhr, status) {
debugger;
alert('Error getting device types.');
}
}); // end - $.ajax
return deviceTypes;
}
</code></pre>
<p>It was working great until I tried to load this .js file into a page in a subdirectory.</p>
<p>Let's suppose that the name of my project is <code>widget</code>.</p>
<p>When I use this code in the main virtual directory, Javascript interprets <code>Controls/ModelSelectorWebMethods.aspx/getDeviceTypes</code> to mean <code>https://mysite.com/widget/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes</code> and all is well. However, from the page in a subdirectory, Javascript interprets it to mean <code>https://mysite.com/widget/subdirectory/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes</code> and it doesn't work.</p>
<p>How can I write my Javascript code so that the AJAX web method can be called from pages in any directory in my application?</p> | 6,310,991 | 6 | 3 | null | 2011-06-10 18:34:30.907 UTC | 4 | 2014-08-20 21:03:14.31 UTC | null | null | null | null | 238,260 | null | 1 | 13 | javascript|jquery|asp.net|ajax | 53,224 | <p>You've got two options:</p>
<ol>
<li><p>Build a configuration/ preferences object in JavaScript which contains all your environment specific settings:</p>
<pre><code> var config = {
base: <% /* however the hell you output stuff in ASPX */ %>,
someOtherPref: 4
};
</code></pre>
<p>and then prefix the AJAX url with <code>config.base</code> (and change the value for <code>config.base</code> whether you're on a dev/ testing/ deployment server.)</p></li>
<li><p>Use the <a href="https://developer.mozilla.org/en/HTML/Element/base" rel="noreferrer"><code><base /></code></a> HTML tag to set the URL prefix for all relative URL's. This affects <strong>all</strong> relative URL's: image's, links etc.</p></li>
</ol>
<p>Personally, I'd go for option 1. You'll most likely find that config object coming in handy elsewhere.</p>
<p>Obviously the config object will have to be included in a part of your site where server-side-code is evaluated; a <code>.js</code> file won't cut it without configuring your server. I always include the config object in the HTML <code><head></code>; its a small config object, whose contents can change on each page, so it's perfectly warrented to stick it in there.</p> |
6,131,323 | How to select the top n from a union of two queries where the resulting order needs to be ranked by individual query? | <p>Let's say I have a table with usernames:</p>
<pre><code>Id | Name
-----------
1 | Bobby
20 | Bob
90 | Bob
100 | Joe-Bob
630 | Bobberino
820 | Bob Junior
</code></pre>
<p>I want to return a list of <code>n</code> matches on name for 'Bob' where the resulting set first contains exact matches followed by similar matches. </p>
<p>I thought something like this might work</p>
<pre><code>SELECT TOP 4 a.* FROM
(
SELECT * from Usernames WHERE Name = 'Bob'
UNION
SELECT * from Usernames WHERE Name LIKE '%Bob%'
) AS a
</code></pre>
<p>but there are two problems:</p>
<ol>
<li>It's an inefficient query since the sub-select could return many rows (looking at the execution plan shows a join happening before top)</li>
<li>(Almost) more importantly, the exact match(es) will not appear first in the results since the resulting set appears to be ordered by primary key.</li>
</ol>
<p>I am looking for a query that will return (for TOP 4)</p>
<pre><code>Id | Name
---------
20 | Bob
90 | Bob
(and then 2 results from the LIKE query, e.g. 1 Bobby and 100 Joe-Bob)
</code></pre>
<p>Is this possible in a single query?</p> | 6,131,353 | 6 | 1 | null | 2011-05-25 21:42:37.68 UTC | 1 | 2014-09-03 03:19:52.427 UTC | null | null | null | null | 9,913 | null | 1 | 14 | sql|tsql|sql-server-2008|sql-server-2008-r2 | 41,136 | <p>You could use a <code>case</code> to place the exact matches on top:</p>
<pre><code>select top 4 *
from Usernames
where Name like '%Bob%'
order by
case when Name = 'Bob' then 1 else 2 end
</code></pre>
<p>Or, if you're worried about performance and have an index on <code>(Name)</code>:</p>
<pre><code>select top 4 *
from (
select 1 as SortOrder
, *
from Usernames
where Name = 'Bob'
union all
select 2
, *
from Usernames
where Name like '%Bob%'
and Name <> 'Bob'
and 4 >
(
select count(*)
from Usernames
where Name = 'Bob'
)
) as SubqueryAlias
order by
SortOrder
</code></pre> |
5,734,678 | Custom filtering of intent chooser based on installed Android package name | <p>I'd like to leverage the built-in intent chooser to display a custom filtered list of apps for user to select from and launch. </p>
<p>I know how to get a list of installed packages:</p>
<pre><code>final Intent myIntent = new Intent(android.content.Intent.ACTION_MAIN);
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(myIntent, 0);
</code></pre>
<p>At this point I want to filter the list based on a specific string (or variation of strings) contained within the package name, which I can figure out how to do as well. </p>
<p>But here's where I get stuck. As far as I know, <code>Intent.createChooser()</code> takes only a single target Intent as a parameter. I was hoping there was an overload that took a list of intents based on package and class names or something. But I don't see anything like that. Did I miss that somewhere? </p>
<p>So the question is, is this possible to do with a built-in chooser, or do I have to construct my own with AlertDialog Builder? I'm hoping to avoid the later. </p>
<p>Thanks in advance.</p> | 5,735,419 | 6 | 0 | null | 2011-04-20 18:06:39.31 UTC | 49 | 2020-05-26 19:06:19.583 UTC | 2011-04-20 18:17:07.86 UTC | null | 22,303 | null | 22,303 | null | 1 | 59 | android|android-intent | 53,109 | <p>The only one additional parameter for the chooser is <code>Intent.EXTRA_INITIAL_INTENTS</code>. Its description is:</p>
<blockquote>
<p>A <code>Parcelable[]</code> of Intent or <code>LabeledIntent</code> objects as set with <code>putExtra(String, Parcelable[])</code> of additional activities to place a the front of the list of choices, when shown to the user with a <code>ACTION_CHOOSER</code>.</p>
</blockquote>
<p>I haven't found any way in Android sources to exclude other activities from the list, so it seems there's no way to do what you want to do using the chooser.</p>
<p><strong>EDIT</strong>: That's really easy to find out. Just check <a href="https://github.com/android/platform_frameworks_base/blob/8d21bdb90573ec48491c44eca312c162e262298d/core/java/com/android/internal/app/ChooserActivity.java" rel="nofollow noreferrer">ChooserActivity</a> and <a href="https://github.com/android/platform_frameworks_base/blob/8d21bdb90573ec48491c44eca312c162e262298d/core/java/com/android/internal/app/ResolverActivity.java" rel="nofollow noreferrer">ResolverActivity</a> source code. These classes are rather small.</p> |
5,610,822 | Convert Enumeration to a Set/List | <p>Is there some one-liner bridge method to dump a given <em>Enumeration</em> to <code>java.util.List</code> or <code>java.util.Set</code>?</p>
<p>Something built-in like <code>Arrays.asList()</code> or <code>Collection.toArray()</code> should exist somewhere, but I'm unable to find that in my IntelliJ debugger's evaluator window (and Google/SO results, too).</p> | 5,610,838 | 6 | 0 | null | 2011-04-10 09:17:52.397 UTC | 10 | 2022-01-17 14:18:36.6 UTC | 2022-01-17 14:18:36.6 UTC | null | 4,294,399 | null | 148,926 | null | 1 | 211 | java|collections|conventions | 130,036 | <p>You can use <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#list%28java.util.Enumeration%29"><code>Collections.list()</code></a> to convert an <code>Enumeration</code> to a <code>List</code> in one line:</p>
<pre><code>List<T> list = Collections.list(enumeration);
</code></pre>
<p>There's no similar method to get a <code>Set</code>, however you can still do it one line:</p>
<pre><code>Set<T> set = new HashSet<T>(Collections.list(enumeration));
</code></pre> |
5,903,597 | Add new items to top of list view on Android? | <p>Android has the <a href="http://developer.android.com/reference/android/widget/AbsListView.html#setTranscriptMode%28int%29" rel="noreferrer">transcript mode</a> to allow to automatically scroll a list view to the bottom when new data is added to the adapter.</p>
<p>Can this be somehow reversed so that new items are automatically added at the top of the list ("inverse transcript mode")</p>
<p>Method <a href="http://developer.android.com/reference/android/widget/AbsListView.html#setStackFromBottom%28boolean%29" rel="noreferrer">stackFromBottom</a> seems about right, but does not do the auto-scrolling on input change. </p>
<p>Does anyone have some example code where a list is constantly adding stuff that gets always inserted at the top? Am I on the right track here?</p>
<p><strong>Update</strong></p>
<p>Thanks for the answers, that made me think more. Actually. I want to have new entries to appear at the top, but the screen still show the item the user is looking at. The user should actively scroll to the top to view the new items. So I guess that transcript mode is not what I want.</p> | 5,903,875 | 7 | 2 | null | 2011-05-05 20:19:47.823 UTC | 11 | 2017-04-22 18:01:05.353 UTC | 2011-05-06 07:24:50.13 UTC | null | 100,957 | null | 100,957 | null | 1 | 33 | android|listview | 62,545 | <p>Hmm, well, if I was going to try this, I'd do something like the following:</p>
<pre><code>List items = new ArrayList();
//some fictitious objectList where we're populating data
for(Object obj : objectList) {
items.add(0, obj);
listAdapter.notifyDataSetChanged();
}
listView.post(new Runnable() {
@Override
public void run() {
listView.smoothScrollToPosition(0);
}
}
</code></pre>
<p>I don't know for certain that this will work, but it seems logical. Basically, just make sure to add the item at the beginning of the list (position 0), refresh the list adapter, and scroll to position (0, 0).</p> |
44,242,068 | What part of Spark SQL parse SQL statements and create execution plan? | <p>Assuming the following query:</p>
<pre><code>select * from my_table
</code></pre>
<p>what part of Spark parses the sql and create the execution plan?</p>
<p>Does Spark SQL execution engine have its own sql parser that translates it to his own execution model? how it works?</p>
<p>I got exception for some functions that spark does not support them yet, does it means spark parse the sql query ? does each other execution engine does it too?</p> | 44,242,242 | 1 | 0 | null | 2017-05-29 12:04:34.883 UTC | 10 | 2017-05-29 12:20:54.717 UTC | 2017-05-29 12:16:13.933 UTC | null | 1,305,344 | null | 2,220,509 | null | 1 | 4 | apache-spark|apache-spark-sql | 5,028 | <p>In Spark SQL it's <a href="https://github.com/apache/spark/blob/master/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala#L45-L46" rel="noreferrer">AstBuilder</a> that builds a abstract syntax tree of logical operators and expressions.</p>
<blockquote>
<p>The AstBuilder converts an ANTLR4 ParseTree into a catalyst <code>Expression</code>, <code>LogicalPlan</code> or <code>TableIdentifier</code>.</p>
</blockquote>
<p><code>AstBuilder</code> is a ANTLR-based SQL parser that uses the SQL grammar described in <a href="https://github.com/apache/spark/blob/master/sql/catalyst/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBase.g4" rel="noreferrer">SqlBase.g4</a> (that was incidentally borrowed from Facebook's Presto with additional support for Hive and PostgreSQL statements).</p>
<p>You can play with supported queries using <a href="http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.SparkSession@sql(sqlText:String):org.apache.spark.sql.DataFrame" rel="noreferrer">SparkSession.sql</a>:</p>
<blockquote>
<p><strong>sql(sqlText: String): DataFrame</strong> Executes a SQL query using Spark, returning the result as a DataFrame. The dialect that is used for SQL parsing can be configured with 'spark.sql.dialect'.</p>
</blockquote>
<p>You could go low-level and use the parser directly:</p>
<pre><code>import spark.sessionState.sqlParser
scala> :type sqlParser
org.apache.spark.sql.catalyst.parser.ParserInterface
</code></pre>
<p>Use <code>parsePlan</code> method (among the other parsing methods) that accepts a SQL text.</p>
<pre><code>scala> sqlParser.parsePlan("select * from myTable")
res1: org.apache.spark.sql.catalyst.plans.logical.LogicalPlan =
'Project [*]
+- 'UnresolvedRelation `myTable`
</code></pre>
<p>With a logical plan (for SQL) Spark SQL uses something I call a <strong>structured query execution pipeline</strong> (aka <a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/QueryExecution.scala#L36-L40" rel="noreferrer">QueryExecution</a>):</p>
<blockquote>
<p><strong>QueryExecution</strong> The primary workflow for executing relational queries using Spark. Designed to allow easy access to the intermediate phases of query execution for developers.</p>
</blockquote>
<p>Every <code>Dataset</code> has its own <code>QueryExecution</code> that you can access using <code>queryExecution</code> property:</p>
<pre><code>val q = spark.range(5)
val qe = q.queryExecution
</code></pre>
<p>You can access the phases of a query execution using <code>analyzed</code>, <code>withCachedData</code>, <code>optimizedPlan</code>, <code>sparkPlan</code>, <code>executedPlan</code>, <code>toRdd</code> lazy values that are all together displayed using <code>explain</code> operator.</p>
<pre><code>scala> q.explain(extended = true)
== Parsed Logical Plan ==
Range (0, 5, step=1, splits=Some(8))
== Analyzed Logical Plan ==
id: bigint
Range (0, 5, step=1, splits=Some(8))
== Optimized Logical Plan ==
Range (0, 5, step=1, splits=Some(8))
== Physical Plan ==
*Range (0, 5, step=1, splits=8)
</code></pre> |
4,973,454 | Session management : How to generate Authentication token for REST service ? (Jersey) | <p>I am trying to implement session management in my REST service. I came to know these guidelines while surfing :</p>
<ol>
<li><p>Not using server side sessions - it violates the RESTful principle.</p></li>
<li><p>Using HTTP Basic authentication - Not possible right now, as I am asked not to use SSL/TLS (which is no doubt needed for Basic auth.)</p></li>
<li><p>Using Http digest - I heard this increases network traffic. This sounds costly, especially when my client is a mobile device.</p></li>
<li><p>Using cookies - I am told I should never rely on cookie for securing my important resources, they can be spoofed easily. Plus, I read about cross-site scripting attacks through cookies.</p></li>
<li><p>I am left with an option of generating authentication token ,which the user has to send everytime - which I admit is not "entirely" RESTful. </p></li>
</ol>
<p>Now I need to know, how should I generate these unique authentication tokens, which are secure enough at a business level ? Is there some library for Jersey ? Should I go for OAuth..I have just read a little about them, are they useful in my case ? Please keep in mind that my target clients are mobile devices - can they access an OAuth service ??</p> | 4,973,576 | 1 | 0 | null | 2011-02-11 20:00:43.933 UTC | 35 | 2013-03-22 22:13:42.75 UTC | null | null | null | null | 430,720 | null | 1 | 44 | security|session|rest|oauth|jersey | 30,990 | <p>For simplicity sake, I generate my own authentication token using <a href="http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html" rel="noreferrer"><code>UUID</code></a> before encrypting the entire token with <a href="http://www.jasypt.org/" rel="noreferrer">Jasypt</a>:-</p>
<pre class="lang-java prettyprint-override"><code>String key = UUID.randomUUID().toString().toUpperCase() +
"|" + someImportantProjectToken +
"|" + userName +
"|" + creationDateTime;
StandardPBEStringEncryptor jasypt = new StandardPBEStringEncryptor();
...
// this is the authentication token user will send in order to use the web service
String authenticationToken = jasypt.encrypt(key);
</code></pre>
<p>The key contains the <code>creationDateTime</code> so that I can use it to verify the time-to-live. This way, if the user uses the same authentication token after X minutes, it will not work anymore, and I'll send back a 403 forbidden code.</p> |
24,981,333 | iOS check if application has access to microphone | <p>With the introduction of iOS 7, applications have to request microphone access when they want to record audio. </p>
<p>How do I check if the application has access to the microphone?<br>
In the iOS 8 SDK I can use the <code>AVAudioSessionRecordPermission</code> enum, but how do I check this in iOS 7?</p>
<p>Info:<br>
I don't want to request permission, I just want to check if the app has access to the microphone. (Like Location access):</p>
<pre><code>if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
// Do something
}
</code></pre> | 24,981,502 | 8 | 1 | null | 2014-07-27 13:16:15.557 UTC | 10 | 2021-10-28 16:18:17.18 UTC | 2018-08-03 13:02:36.673 UTC | null | 4,253,437 | null | 2,513,803 | null | 1 | 36 | ios|objective-c|swift|microphone|avaudiosession | 59,441 | <p>In <code>iOS7</code> there is no way to get the current status of <code>microphone authorization</code>.They have given the enum in <code>iOS8</code> as <a href="https://developer.apple.com/library/prerelease/ios/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/index.html#//apple_ref/c/tdef/AVAudioSessionRecordPermission" rel="noreferrer">AVAudioSessionRecordPermission</a></p>
<p>In <code>iOS7</code> you have to request permission every time with</p>
<pre><code>[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
if (granted) {
NSLog(@"Permission granted");
}
else {
NSLog(@"Permission denied");
}
}];
</code></pre>
<p>The same question has been asked before but there is no such api with which you know current status as in <code>iOS8</code></p>
<p>You can refer <a href="https://stackoverflow.com/questions/19615105/check-for-mic-permission-on-ios-7-without-showing-prompt?rq=1">Check for mic permission on iOS 7 without showing prompt</a></p>
<p><strong>Solution:</strong></p>
<p>Another option is you can show the <code>popup</code> or ask for permission <strong>first time</strong> and save the states of user option selected in <code>NSUserDefaults</code> and than onwards do not ask for permission.
From docs you explicitly do not need to call this if each you do not need to get the permission of user.It will automatically called by <code>AVAudioSession</code> first time when you try to record</p>
<blockquote>
<p>Recording audio requires explicit permission from the user. The first
time your app’s audio session attempts to use an audio input route
while using a category that enables recording (see “Audio Session
Categories”), the system automatically prompts the user for
permission; alternatively, you can call requestRecordPermission: to
prompt the user at a time of your choosing</p>
</blockquote> |
25,057,182 | How to change panel-body background-color in bootstrap? | <p>I am creating a webpage using twitter bootstrap, here i wanna change panel-body background-color form white to light-pink, but i haven't any idea that how it will be done? So ..... help me
Thank You</p> | 25,133,586 | 1 | 1 | null | 2014-07-31 10:58:47.1 UTC | 3 | 2014-08-05 08:24:48.76 UTC | 2014-08-05 08:24:48.76 UTC | null | 15,541 | null | 3,811,454 | null | 1 | 12 | twitter-bootstrap|panel | 53,638 | <p>The CSS being as follows (as an example) should work fine. If not then you'll need to show your code.</p>
<pre><code>.panel-body {
background:#FFCCFF;}
</code></pre> |
27,796,203 | How to set a driver path of firefoxdriver in selenium | <p>Hi I am very new to selenium . So pardon me for any technical mistakes.
I have a project which works fine for IE. But I need to test using firefox too. Does the project require a pointer towards the driver like IEDriver in case of execution in IE?</p> | 27,802,941 | 7 | 1 | null | 2015-01-06 10:01:07.55 UTC | 1 | 2020-08-04 08:42:46.2 UTC | null | null | null | null | 1,700,354 | null | 1 | 4 | java|firefox|selenium | 54,477 | <p>You don't need to set the driver path for FirefoxDriver.<br>You can directly use <strong><code>WebDriver driver = new FirefoxDriver();</code></strong>.</p>
<p>However, there are other ways to run selenium in Firefox also, as below:</p>
<p>1- <a href="http://www.toolsqa.com/selenium-webdriver/custom-firefox-profile/" rel="nofollow noreferrer">Using Firefox Profile</a>; <br>
Used to run selenium in a new user-defined profile with a set of preferences as necessary.</p>
<p>2- <a href="https://stackoverflow.com/a/24891650/4193730">Using Firefox Binary</a>; <br> [PS:- Not much Idea on how it works, But this link might help you out]</p> |
21,842,274 | Cross-browser custom styling for file upload button | <p>I'm trying to style a file upload button to my personal preferences, but I couldn't find any really solid ways to do this without JS. I did find <a href="https://stackoverflow.com/q/3226167/1256925">two</a> <a href="https://stackoverflow.com/q/3606876/1256925">other</a> questions about this subject, but the answers there either involved JavaScript, or suggested <a href="http://www.quirksmode.org/dom/inputfile.html" rel="noreferrer">Quirksmode's approach</a>.</p>
<p>My major issue with this Quirksmode's approach is that the file button will still have the browser-defined dimensions, so it won't automatically adjust to whatever's used as button that's placed below it. I've made some code, based on it, but it will just take up the space the file button would normally take up, so it won't at all fill the parent div like I want it to.</p>
<p><strong>HTML:</strong></p>
<pre><code><div class="myLabel">
<input type="file"/>
<span>My Label</span>
</div>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>.myLabel {
position: relative;
}
.myLabel input {
position: absolute;
z-index: 2;
opacity: 0;
width: 100%;
height: 100%;
}
</code></pre>
<p><a href="http://jsfiddle.net/KY42f/1/" rel="noreferrer"><strong>This fiddle</strong></a> demonstrates how this approach is quite flawed. In Chrome, clicking the <code>!!</code> below the second demo button will open the file dialog anyway, but also in all other browsers, the file button doesn't take up the correct areas of the button.</p>
<p>Is there any more solid way to style the file upload button, without any JavaScript, and preferably using as little 'hacky' coding as possible (since hacking usually brings other problems along with it, such as the ones in the fiddle)?</p> | 21,842,275 | 7 | 2 | null | 2014-02-18 00:52:16.607 UTC | 69 | 2018-04-22 21:07:53.927 UTC | 2017-05-23 12:18:20.277 UTC | null | -1 | null | 1,256,925 | null | 1 | 117 | html|css|cross-browser|file-io | 174,639 | <p><em>I'm posting this because (to my surprise) there was no other place I could find that recommended this.</em></p>
<p>There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <code><label></code> tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via <a href="http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/" rel="noreferrer">webkit's built-in styling</a><sup>[1]</sup>.</p>
<p>The label tag was made for the exact purpose of directing any click events on it to the child inputs<sup>[2]</sup>, so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:</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>label.myLabel input[type="file"] {
position:absolute;
top: -1000px;
}
/***** Example custom styling *****/
.myLabel {
border: 2px solid #AAA;
border-radius: 4px;
padding: 2px 5px;
margin: 2px;
background: #DDD;
display: inline-block;
}
.myLabel:hover {
background: #CCC;
}
.myLabel:active {
background: #CCF;
}
.myLabel :invalid + span {
color: #A44;
}
.myLabel :valid + span {
color: #4A4;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="myLabel">
<input type="file" required/>
<span>My Label</span>
</label></code></pre>
</div>
</div>
</p>
<p>I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a <code>visibility:hidden</code> or <code>display:none</code> file-input). I've tested in emulated IE7 and up, and it worked perfectly.</p>
<hr>
<ol>
<li>You can't use <code><button></code>s inside <code><label></code> tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.</li>
<li>If the <code>for</code> attribute is defined, its value is used to trigger the input with the same <code>id</code> as the <code>for</code> attribute on the <code><label></code>.</li>
</ol> |
33,340,659 | How to auto start an application in openwrt? | <p>I have created a shell with necessary functions such as
start()
stop()
restart()</p>
<p>But my file is not getting started at boot time.</p>
<p>I have used <strong>update-rc.d</strong> command in "ubuntu" to add this file to the list of autostart applications. And it was successfully started at boot time.</p>
<p>But in "openwrt" I have seen an <strong>enable</strong> function. Anyone aware of how to use this enable function or is there any similar command like <strong>update-rc.d</strong> in "openwrt"</p>
<p>I had some reference here : <a href="http://wiki.openwrt.org/doc/techref/initscripts" rel="noreferrer">http://wiki.openwrt.org/doc/techref/initscripts</a></p> | 33,341,189 | 3 | 2 | null | 2015-10-26 07:37:28.783 UTC | 9 | 2020-04-03 05:40:29.58 UTC | 2015-10-26 07:49:39.147 UTC | null | 4,456,198 | null | 4,456,198 | null | 1 | 12 | shell|openwrt|autostart | 36,796 | <p>/etc/init.d/ - directory will by automaticly readed and searching for boot function or START STOP.
Starts at boot time.</p>
<pre><code>boot() {
echo boot
# commands to run on boot
}
</code></pre>
<p>START-Position then to start</p>
<p>STOP-Position then to stop</p>
<pre><code>START=10
STOP=15
start() {
echo start
# commands to launch application
}
stop() {
echo stop
# commands to kill application
}
</code></pre>
<p><strong>EDITED:</strong></p>
<p>In /etc/rc.common directory files are compiled whoes going to start on boot.</p>
<p>Enable your function: /etc/init.d/your_script.sh enable</p>
<p>Here you will find more information about booting <a href="http://wiki.openwrt.org/doc/techref/process.boot" rel="noreferrer">http://wiki.openwrt.org/doc/techref/process.boot</a></p> |
9,193,112 | Secure and HttpOnly flags for session cookie Websphere 7 | <p>In Servlet 3.0 complaint application servers I can set the HttpOnly and secure flags for the session cookie (JSESSIONID) by adding the following to the web.xml:</p>
<pre><code><session-config>
<cookie-config>
<secure>true</secure>
<http-only>true</http-only>
</cookie-config>
</session-config>
</code></pre>
<p>However, the application I'm working on is to be deployed in Websphere 7, which is Servlet 2.5 complaint and it fails to start if I add the above to the web.xml</p>
<p>Is there any other declarative way or setting in Websphere 7 configuration to turn on the HttpOnly and secure flags for the session cookie?</p>
<p>If not, what would be the best approach to accomplish that programmatically? </p> | 9,193,319 | 3 | 0 | null | 2012-02-08 12:14:42.527 UTC | 4 | 2016-01-27 12:04:45.09 UTC | 2016-01-27 12:04:45.09 UTC | null | 157,882 | null | 26,699 | null | 1 | 10 | servlets|cookies|websphere-7|httponly | 47,965 | <p>I think in WebSphere 7 you may have to delve into the administrative console. As ever the WebSphere documentation seems poor but seems to suggest setting the <a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/topic/com.ibm.websphere.express.doc/info/exp/ae/usec_seccustomprop.html" rel="noreferrer">com.ibm.ws.security.addHttpOnlyAttributeToCookies</a> property:</p>
<blockquote>
<p>Both the Secure flag and the HTTPOnly flag are enabled by setting the WebSphere Application Server property:
<code>com.ibm.ws.security.addHttpOnlyAttributeToCookies</code>.</p>
</blockquote>
<p>I found <a href="http://www-01.ibm.com/support/docview.wss?uid=swg21422185" rel="noreferrer">this</a>, which I hope is applicable to WAS7. Can you try please (I only have WAS 8 at the moment on my system):</p>
<blockquote>
<p><strong><em>JSESSIONID cookie:</em></strong></p>
<p><strong>Secure Flag:</strong></p>
<p>The Secure flag can be set within the WebSphere Application Server
administrative interface by selecting AppServer->[Server Name]->Web
Container Settings->Session Management. Check the checkbox for
“Restrict cookies to HTTPS Sessions”. </p>
<p><strong>HTTPOnly Flag:</strong></p>
<p>The HTTPOnly attribute cannot currently be set on this cookie. This
is registered on the IBM site as APAR PK98436. The fix for this APAR
is currently targeted for inclusion in Fix Packs 6.1.0.31 and 7.0.0.9,
which are not yet available. With this APAR in place, the HTTPOnly
flag can be set on the JSESSIONID cookie by way of the property name:
com.ibm.ws.webcontainer.httpOnlyCookies. Refer to the following
technote for instructions on enabling WebContainer custom properties.</p>
</blockquote>
<p>The <a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/rweb_custom_props.html" rel="noreferrer">com.ibm.ws.webcontainer.httpOnlyCookies</a> property is documented on the WAS 7 help site.</p> |
9,033,166 | Multiplayer JavaScript game built with Node.JS - Separating players | <p>I have a question which I cannot find an answer to.</p>
<p>I'm experimenting with building a multiplayer game with Node.JS and Socket.IO. I have built a chat room as my first experiment, so I have broadcasts working etc. Now I'm at the point where I want to get something working with Canvas.</p>
<p>The problem I'm having is getting my head around multiple and independent players. I know that each player will send their x,y cords to the server and the server will broadcast those, but how does the client know how many players to display, I'm guessing they have to be stored in an array somewhere.</p> | 9,035,404 | 3 | 0 | null | 2012-01-27 12:19:46.633 UTC | 26 | 2017-05-23 11:08:40.627 UTC | 2012-01-27 12:21:17.067 UTC | null | 1,044,146 | null | 300,329 | null | 1 | 13 | javascript|node.js|canvas|socket.io | 14,292 | <p>My implementation will be very naive and simplified, no lag compensation, extrapolation and such, but it should point out a general conception of "multiplayering" with node.</p>
<p>I think the simplest approach is to have an associative array containing players(entities) on both client and server. Then from client side you send commands like <code>{action: "move", target:[32, 100]}</code> and process this command with server logic (where the real game is running). To each socket <code>on connection</code> you should assign a player object or id so you can access it like:</p>
<pre><code>var lastPlayerID = 0;
var players = {};
server.on("connection", function(socket) {
var newcommer = new Player({id: lastPlayerID});
players[lastPlayerID] = newcommer;
socket.player = newcommer; // or lastPlayerID
lastPlayerID++;
socket.onMessage = function(message) {
this.player.doSomething();
}
});
</code></pre>
<p>Then each let's say 100ms you could send snapshots to all connected players:</p>
<pre><code>{
timestamp: game.delta,
players: {
1: {x: 32, y: 100},
2: {x: 14, y: 11}
}
}
</code></pre>
<p>And then at client side receive data and interpolate from old to new values.</p>
<pre><code>// duration in this simplified example is snapshot sending interval in [ms]
Player.prototype.interpolateTo = function(data, duration) {
if(typeof data.x != "undefined") {
// step needed to get `destination x` within `duration` miliseconds
this.stepValues.x = Math.abs(data.x - this.x) / duration;
this.target.x = data.x;
}
// ...
}
// step you call for each game loop iteration
Player.prototype.step = function(delta) {
if(this.x < this.target.x) {
this.x += delta * this.stepValues.x
}
}
</code></pre>
<p>This is a sufficient algorithm for a semi-arcade game with 20 objects at maximum. Decreasing snapshot's interval makes it almost suitable for strategy game with more objects. Your main enemy is bandwidth usage which you can decrease minimizing packet's size. For instance read about BiSON, LZW and don't send data which haven't changed since last snapshot.</p>
<p><strike>My reputation doesn't allow me to post all the links, so I have attached them here:
<a href="http://pastebin.com/Kh3wvF1D">http://pastebin.com/Kh3wvF1D</a></strike></p>
<p>General introduction to multiplayer conceptions by Glenn Fiedler:</p>
<blockquote>
<p><a href="http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/">http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/</a></p>
</blockquote>
<p>Some multiplayer techniques from Quake:
This will give u a clue about interpolation and extrapolation(prediction)</p>
<blockquote>
<p><a href="http://fabiensanglard.net/quakeSource/quakeSourcePrediction.php">http://fabiensanglard.net/quakeSource/quakeSourcePrediction.php</a></p>
</blockquote>
<p>Valve's article about latency compensation and general optimisations:</p>
<blockquote>
<p><a href="https://developer.valvesoftware.com/wiki/Latency_Compensating_Methods_in_Client/Server_In-game_Protocol_Design_and_Optimization">https://developer.valvesoftware.com/wiki/Latency_Compensating_Methods_in_Client/Server_In-game_Protocol_Design_and_Optimization</a></p>
</blockquote>
<p>Multiplayer techniques in Age of Empires:</p>
<blockquote>
<p><a href="http://zoo.cs.yale.edu/classes/cs538/readings/papers/terrano_1500arch.pdf#search=%22Real%20time%20strategy%20networking%20lockstep%22">http://zoo.cs.yale.edu/classes/cs538/readings/papers/terrano_1500arch.pdf#search=%22Real%20time%20strategy%20networking%20lockstep%22</a></p>
</blockquote>
<p>You can also read my article about optimizing bandwidth usage</p>
<blockquote>
<p><a href="http://rezoner.net/minimizing-bandwidth-usage-in-html5-games-using-websocket,299">http://rezoner.net/minimizing-bandwidth-usage-in-html5-games-using-websocket,299</a></p>
</blockquote>
<p>+1 for Ivo's Wetzel Mapple.js it's a big pile of knowledge.</p>
<blockquote>
<p><a href="https://github.com/BonsaiDen/Maple.js">https://github.com/BonsaiDen/Maple.js</a></p>
</blockquote> |
9,019,512 | How can I change the touch effect color of the ActionBar in Android 3.0 and higher | <p>I am trying to change the color of the rollover effect when you touch an ActionBar Item.
On my Galaxy Nexus with 4.0.2 it's kind of a turquoise color shading which I want to be in a different color.</p>
<p>To be clear, I am talking about ActionBar items here, not navigation tabs.</p>
<p>I got it working under the compatibility library, but for Android 3.0 and higher, i.e. the "real" ActionBar, I just can't figure out how to do this.</p>
<p>Does anyone knows if and how this can be achieved?</p> | 9,019,730 | 1 | 0 | null | 2012-01-26 14:23:39.9 UTC | 15 | 2013-11-19 21:41:28.847 UTC | 2013-11-19 21:41:28.847 UTC | null | 321,731 | null | 709,835 | null | 1 | 23 | android|colors|touch|android-actionbar | 19,580 | <p>The native action bar uses the theme attribute <code>selectableItemBackground</code> for action item background drawing. This should be a state-list drawable.</p>
<p>Here's the declaration in <code>Theme.Holo</code>:</p>
<pre><code><style name="Theme.Holo">
<!-- bunch of things -->
<item name="android:selectableItemBackground">@android:drawable/item_background_holo_dark</item>
<!-- bunch of things -->
</style>
</code></pre>
<p>And its drawable XML:</p>
<pre><code><selector xmlns:android="http://schemas.android.com/apk/res/android"
android:exitFadeDuration="@android:integer/config_mediumAnimTime">
<!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. -->
<item android:state_focused="true" android:state_enabled="false" android:state_pressed="true" android:drawable="@drawable/list_selector_disabled_holo_dark" />
<item android:state_focused="true" android:state_enabled="false" android:drawable="@drawable/list_selector_disabled_holo_dark" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/list_selector_background_transition_holo_dark" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/list_selector_background_transition_holo_dark" />
<item android:state_focused="true" android:drawable="@drawable/list_focused_holo" />
<item android:drawable="@color/transparent" />
</selector>
</code></pre> |
9,419,207 | Does Tomcat require Apache httpd? | <p>If I am given a war file that contains a Java web application, and I want to run that war locally, then do I just need Tomcat, or do I need Tomcat <strong>and</strong> Apache httpd (or any other web server)? Thanks in advance!</p> | 9,419,248 | 4 | 0 | null | 2012-02-23 18:45:46.86 UTC | 13 | 2016-08-10 03:54:20.97 UTC | null | null | null | null | 892,029 | null | 1 | 39 | java|tomcat|webserver|war|apache | 21,597 | <p>Tomcat is a web server of its own, so a separate web server like Apache is not required. You probably will want to change Tomcat's port though, since it defaults to 8080 and web sites are usually on port 80.</p>
<p>I think people generally put Apache in front of Tomcat so they can do things like:</p>
<ul>
<li>Have one website have several Tomcat instances behind it.</li>
<li>Serve static files from Apache to take load off of Tomcat.</li>
<li>Use other Apache features you may need (modules).</li>
<li>As @TacticalCoder mentions in the comments, you need to be root to listen on port 80, so some people may be using Apache as an easy way to proxy port 80 to port 8080.</li>
</ul>
<p>I'd recommend the <a href="http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it" rel="noreferrer">YAGNI</a> approach and just go with Tomcat until/unless you find a reason you want Apache in front of it.</p> |
10,725,705 | How To Create Table with Identity Column | <p>I have an existing table that I am about to blow away because I did not create it with the <code>ID</code> column set to be the table's Identity column.</p>
<p>Using <strong>SQL Server Management Studio</strong>, I scripted a <em>"Create To..."</em> of the existing table and got this:</p>
<pre><code>CREATE TABLE [dbo].[History](
[ID] [int] NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code></pre>
<p>My question is, how would I modify this <code>SQL</code> so that my resulting table has the <code>ID</code> column set as the <strong>Identity</strong>?</p> | 10,725,745 | 4 | 1 | null | 2012-05-23 18:24:54.24 UTC | 12 | 2018-03-22 10:46:33.833 UTC | 2018-03-22 10:46:33.833 UTC | null | 153,923 | null | 153,923 | null | 1 | 120 | sql|sql-server|tsql | 386,970 | <pre><code>CREATE TABLE [dbo].[History](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON [PRIMARY]
</code></pre> |
10,591,086 | shell-script headers (#!/bin/sh vs #!/bin/csh) | <p>Why do all script files start with </p>
<pre><code>#!/bin/sh
</code></pre>
<p>or with </p>
<pre><code>#!/bin/csh
</code></pre>
<p>Is that required? What's the purpose of this? And what's the difference between the two?</p> | 10,591,174 | 3 | 1 | null | 2012-05-14 21:08:22.403 UTC | 19 | 2021-06-06 21:09:44.423 UTC | 2014-11-24 10:08:32.32 UTC | null | 1,600,108 | null | 1,293,653 | null | 1 | 124 | shell|unix | 228,632 | <p>This is known as a <code>Shebang</code>:</p>
<p><a href="http://en.wikipedia.org/wiki/Shebang_%28Unix%29">http://en.wikipedia.org/wiki/Shebang_(Unix)</a></p>
<blockquote>
<p>#!interpreter [optional-arg]</p>
</blockquote>
<p>A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).</p>
<p>When a shell executes the script it will use the specified interpreter.</p>
<p>Example:</p>
<pre><code>#!/bin/bash
# file: foo.sh
echo 1
$ chmod u+x foo.sh
$ ./foo.sh
1
</code></pre> |
7,069,176 | How do I setup a private git repository in Ubuntu? | <p>I use a git repository at work on GitHub. I know the basic commands for navigating and editing a repository but I don't know how to set one up from scratch.</p>
<p>I would like to setup my own server for the git repo so my buddies can come help me with the game I'm developing for Android. But I don't know how!</p>
<p>Would Gitosis be the best choice for this?</p> | 7,070,048 | 2 | 3 | null | 2011-08-15 18:44:16.603 UTC | 9 | 2014-02-10 05:59:28.68 UTC | 2011-08-15 18:54:02.06 UTC | null | 635,608 | null | 625,740 | null | 1 | 9 | git|ubuntu | 16,488 | <p>First, You need to create the repo (easy as <code>git init</code>)<br>
Second, You need to give your buddies access to the repo.</p>
<p>You may use few options which git handles:</p>
<ul>
<li>via <code>file://</code> (direct access on LAN)</li>
<li>via ftp</li>
<li>via git protocol (ssh access)</li>
</ul>
<p>Third, manage the access, permissions etc.</p>
<p>For this, the best option is <a href="https://github.com/sitaramc/gitolite" rel="noreferrer">gitolite</a>, better than <code>gitosis</code>. There is a good installation guide in the repo. The most tricky part is setting up passwordless access to the server (but this this is not actually git related). Using Ubuntu and Github you probably know what for are public ssh keys.</p>
<p>Gitolite is the best option so far, but a bit complex. However, if you don't want to use gitolite, you may still only to init the repo, and make the machine accessible, which is the simplest solution.</p>
<p>See also <a href="http://progit.org/book/ch4-4.html" rel="noreferrer">Setting Up the Server</a> from the free <a href="http://progit.org/" rel="noreferrer">Pro Git</a> book. There are chapters about <em>gitolite</em> and <em>gitosis</em> as well.</p> |
7,208,773 | MySQL "Row 30153 was cut by GROUP_CONCAT()" error | <p>I have a function listed below. When I call it with the LIMIT set at 0,60 as seen below, it works fine. However, whenever I increase that LIMIT to 70 or higher, or even remove the LIMIT, MySQL errors when I call the function with the error: "Row 30153 was cut by GROUP_CONCAT()".</p>
<p>I have tried increasing the varchar values to 10 000 but that does not help.
As far as I can understand from the error, their doesn't seem to be enough space i nthe variable for the contents. But like I mentioned, I have tried increasing the size but it doesn't help. Any ideas?? Thanks</p>
<pre><code>DELIMITER $$
DROP FUNCTION IF EXISTS `fnAlbumGetPhotoList` $$
CREATE DEFINER=`root`@`%` FUNCTION `fnAlbumGetPhotoList`(_albumId int) RETURNS varchar(2048) CHARSET utf8
BEGIN
DECLARE _outPhotoList VARCHAR(2048);
SET _outPhotoList = (
SELECT (CAST(GROUP_CONCAT(CONCAT(photoId, '|', photoFileName) separator '~') AS CHAR(10000) CHARACTER SET utf8)) AS recentPhotoList
FROM
(
SELECT photoId, photoFileName
FROM photo
WHERE photoAlbumId = _albumId
AND photoIsDisabled = 0
AND photoIsActive = 1
ORDER BY photoId DESC
LIMIT 0,60
) as subQuery
);
RETURN _outPhotoList;
END $$
DELIMITER ;
</code></pre> | 7,208,835 | 2 | 1 | null | 2011-08-26 18:00:41.37 UTC | 12 | 2019-07-31 07:59:18.51 UTC | null | null | null | null | 453,495 | null | 1 | 59 | mysql | 66,626 | <p>You could set the <a href="http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_group_concat_max_len">group_concat_max_len</a> variable to bigger value. Or perhaps use <a href="http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat"><code>GROUP_CONCAT(DISTINCT ...)</code></a> to shorthen the result.</p> |
23,243,277 | Thymeleaf - How to compare string with request parameter in html in Thymeleaf tag "th:if"? | <p>How to compare string with request parameter in html in Thymeleaf tag "th:if" ?
right now i am using this</p>
<pre><code><div class="error" th:if="${param.error == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}">
<p class="errorMsg"><span th:text="${errorMsg}"></span></p>
</div>
</code></pre>
<p>But no luck, it is not working.</p> | 23,291,183 | 3 | 1 | null | 2014-04-23 11:43:34.563 UTC | 9 | 2021-08-07 10:13:14.027 UTC | null | null | null | null | 3,515,080 | null | 1 | 14 | html|spring-mvc|thymeleaf | 64,885 | <p>It's not working because <code>param.error</code> is array of strings. You must retrieve first element of array (<code>param.error[0]</code>) to get first value of parameter (see <a href="http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html#web-context-namespaces-for-requestsession-attributes-etc." rel="noreferrer">documentation</a>). Besides that you can access request parameter via Web context object method <code>#httpServletRequest.getParameter</code> that returns first value when parameter is multivalued (see <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29" rel="noreferrer">documentation</a>).</p>
<ol>
<li><p>Usage of Web context namespaces for request attributes</p>
<pre><code><div class="error" th:if="${param.error[0] == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}">
<p class="errorMsg"><span th:text="${errorMsg}"></span></p>
</div>
</code></pre></li>
<li><p>Usage of Web context object</p>
<pre><code><div class="error" th:if="${#httpServletRequest.getParameter('error') == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}">
<p class="errorMsg"><span th:text="${errorMsg}"></span></p>
</div>
</code></pre></li>
</ol> |
31,615,057 | Refactor menu missing from Visual Studio 2015 | <p>I am having trouble finding the right-click context menu in Visual Studio 2015. I know that nothing is wrong with my project or the file I am working. I can find the right-click context refactor menu in Visual Studio 2013. However, in Visual Studio 2015 there isn't a refactor context menu in the right-click context menu.</p>
<p>Where did it go? How do I get it back?</p>
<p>Your suggestion cannot include menu <em>Edit</em> → <em>Refactor</em>.</p>
<p>I have tried to reset my Visual Studio settings back to default using menu <em>Tools</em> → <em>Import and Export Settings</em> and that didn't bring the menu back either.</p> | 31,615,254 | 5 | 4 | null | 2015-07-24 16:04:19 UTC | 8 | 2019-03-18 23:46:24.593 UTC | 2019-02-25 07:57:55.54 UTC | null | 63,550 | null | 682,849 | null | 1 | 89 | visual-studio|refactoring|visual-studio-2015 | 48,520 | <p>Some of the refactoring tools have been relocated or are at least accessible in a different manner than they were previously.</p>
<p>Using the extract method refactor as an example, you can still use this function; it is just not done the same as before:</p>
<p><a href="https://i.stack.imgur.com/02w4A.png" rel="noreferrer"><img src="https://i.stack.imgur.com/02w4Am.png" alt="Select parts to extract"></a></p>
<p>Right click</p>
<p><a href="https://i.stack.imgur.com/vKwpQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vKwpQm.png" alt="Right click"></a></p>
<p>Quick actions</p>
<p><a href="https://i.stack.imgur.com/m1UVr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/m1UVrm.png" alt="Quick actions"></a></p>
<p>Click extract Method</p>
<p><a href="https://i.stack.imgur.com/Ds7ag.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ds7agm.png" alt="Click extract method"></a></p>
<p>I think they've changed it to feel more "ReSharper"ey. All of the functionality should still be there however.</p>
<p>Here's more information on refactoring in Visual Studio 2015 - hopefully this helps! <em><a href="https://msdn.microsoft.com/en-us/library/719exd8s.aspx" rel="noreferrer">Refactoring (C#)</a></em></p> |
19,036,033 | Month is not printed from a date - Java DateFormat | <p>How to get month from a date in java : </p>
<pre><code> DateFormat inputDF = new SimpleDateFormat("mm/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
</code></pre>
<p>This code return day and year but not month.</p>
<p>output : </p>
<pre><code>0 - 30 - 2011
</code></pre> | 19,036,073 | 7 | 1 | null | 2013-09-26 18:35:10.98 UTC | 1 | 2018-01-10 11:29:41.25 UTC | 2017-11-28 19:29:33.703 UTC | null | 770,467 | null | 2,536,373 | null | 1 | 10 | java|date|calendar|date-format | 48,207 | <p>This is because your format is incorrect: you need <code>"MM/dd/yy"</code> for the month, because <code>"mm"</code> is for minutes:</p>
<pre><code>DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
</code></pre>
<p>Prints <code>8 - 30 - 2011</code> (because months are zero-based; <a href="http://ideone.com/bPi3gH" rel="noreferrer">demo</a>)</p> |
37,814,508 | Order columns through Bootstrap4 | <p>I have 3 columns which I want to order in different ways on desktop and mobile.</p>
<p>Currently, my grid looks like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
<div class="col-xs-3 col-md-6">
1
</div>
<div class="col-xs-3 col-md-6">
2
</div>
<div class="col-xs-6 col-md-12">
3
</div>
</div></code></pre>
</div>
</div>
</p>
<p>In the mobile view I want to have the following output:</p>
<pre><code>1-3-2
</code></pre>
<p>Unfortunately I don't get how to solve this with the <code>.col-md-push-*</code> and <code>.col-md-pull-*</code> classes in Bootstrap 4.</p> | 43,069,703 | 6 | 2 | null | 2016-06-14 14:12:12.29 UTC | 24 | 2022-09-20 19:20:36.173 UTC | 2022-09-20 19:20:36.173 UTC | null | 1,264,804 | null | 1,788,961 | null | 1 | 90 | css|twitter-bootstrap|bootstrap-4|grid | 179,228 | <p><strong>2021 - Bootstrap 5</strong></p>
<p>The responsive ordering classes are now <code>order-first</code>, <code>order-last</code> and <code>order-0</code> - <code>order-5</code></p>
<p><a href="https://codeply.com/p/XLuC2eGQND" rel="noreferrer">Demo</a></p>
<p><strong>2018 - Bootstrap 4</strong></p>
<p>The responsive <a href="https://getbootstrap.com/docs/4.0/layout/grid/#order-classes" rel="noreferrer">ordering classes</a> are now <code>order-first</code>, <code>order-last</code> and <code>order-0</code> - <code>order-12</code></p>
<strike>
The Bootstrap 4 **push** **pull** classes are now `push-{viewport}-{units}` and `pull-{viewport}-{units}` and the `xs-` infix has been removed. To get the desired 1-3-2 layout on mobile/xs would be: [Bootstrap 4 push pull demo](http://www.codeply.com/go/OmrcmepbUp)</strike> (This only works pre 4.0 beta)
<hr>
<p><strong>Bootstrap 4.1+</strong></p>
<p>Since Bootstrap 4 is flexbox, it's easy to change the order of columns. The cols can be ordered from <code>order-1</code> to <code>order-12</code>, responsively such as <code>order-md-12 order-2</code> (last on <code>md</code>, 2nd on <code>xs</code>) relative to the parent <code>.row</code>.</p>
<pre><code><div class="container">
<div class="row">
<div class="col-3 col-md-6">
<div class="card card-body">1</div>
</div>
<div class="col-6 col-md-12 order-2 order-md-12">
<div class="card card-body">3</div>
</div>
<div class="col-3 col-md-6 order-3">
<div class="card card-body">2</div>
</div>
</div>
</div>
</code></pre>
<p>Demo: <a href="https://www.codeply.com/go/Lmy5dG7C33" rel="noreferrer">Change order using <code>order-*</code> classes</a><br></p>
<p>Desktop (larger screens):
<a href="https://i.stack.imgur.com/M53x9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M53x9.png" alt="enter image description here" /></a></p>
<p>Mobile (smaller screens):
<a href="https://i.stack.imgur.com/q0A5m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/q0A5m.png" alt="enter image description here" /></a></p>
<p>It's also possible to change column order using the <a href="http://getbootstrap.com/docs/4.1/utilities/flex/#direction" rel="noreferrer">flexbox direction utils</a>...</p>
<pre><code><div class="container">
<div class="row flex-column-reverse flex-md-row">
<div class="col-md-8">
2
</div>
<div class="col-md-4">
1st on mobile
</div>
</div>
</div>
</code></pre>
<p>Demo: <a href="https://www.codeply.com/go/6vWQN2ocxe" rel="noreferrer">Bootstrap 4.1 Change Order with Flexbox Direction</a></p>
<hr/>
<p><em>Older version demos</em><br>
<a href="https://www.codeply.com/go/zIpTgyHfJh" rel="noreferrer">demo - alpha 6</a><br>
<a href="https://www.codeply.com/go/dNtWO26nQv" rel="noreferrer">demo - beta (3)</a></p>
<p><a href="https://www.codeply.com/go/SXtwk690Lx" rel="noreferrer"><strong>See more Bootstrap 4.1+ ordering demos</strong></a></p>
<hr />
<p><strong>Related</strong><br>
<a href="https://stackoverflow.com/questions/38247873/column-ordering-in-bootstrap-4-with-push-pull-and-col-md-12">Column ordering in Bootstrap 4 with push/pull and col-md-12</a><br>
<a href="https://stackoverflow.com/questions/45292170/bootstrap-4-change-order-of-columns/45302093#45302093">Bootstrap 4 change order of columns</a></p>
<p>A-C-B A-B-C</p> |
18,050,836 | Getting return value from Task.Run | <p>I have the following code:</p>
<pre><code>public static async Task<string> Start(IProgress<ProcessTaskAsyncExProgress> progress)
{
const int total = 10;
for (var i = 0; i <= total; i++)
{
await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));
if (progress != null)
{
var args = new ProcessTaskAsyncExProgress
{
ProgressPercentage = (int)(i / (double)total * 100.0),
Text = "processing " + i
};
progress.Report(args);
}
}
return "Done";
}
private static string RunLongTask(string taskName)
{
Task.Delay(300);
return taskName + "Completed!";
}
</code></pre>
<p>How do I get back the string value of <code>RunLongTask</code> from this line: <code>await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));</code>?</p>
<p>I've tried:</p>
<pre><code>var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture))).Result;
</code></pre>
<p>But I get an error saying "string is not awaitable".</p> | 18,050,858 | 2 | 0 | null | 2013-08-05 04:58:23.5 UTC | 8 | 2019-11-20 02:44:12.307 UTC | 2019-11-20 02:44:12.307 UTC | null | 4,404,544 | null | 1,177,278 | null | 1 | 71 | c#|.net|task-parallel-library|async-await | 122,242 | <p>Remove the <code>Result</code> from the end. When you <code>await</code> you will get the <code>Result</code> back from the await-able method.</p>
<pre><code>var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));
</code></pre> |
1,867,170 | purpose of webAppRootKey? | <p>Can somebody explain this entry in web.xml ? When it has to be used and why ?</p>
<pre><code><context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapp.root</param-value>
</context-param>
</code></pre>
<p>Is this something related to Spring or general one?</p> | 1,867,197 | 3 | 0 | null | 2009-12-08 14:04:00.93 UTC | 2 | 2017-12-24 05:06:02.75 UTC | null | null | null | null | 136,913 | null | 1 | 29 | spring-mvc|web.xml|servlets | 29,132 | <p>It is both general and Spring Specific. <code>context-param</code> allows you to specify context parameters (that is general) but what you specify is specific to your application, and your application will look for the parameter and use it.</p>
<p>In this case it is the key of the system property that should specify the root directory of this web app. Applied by <a href="http://static.springsource.org/spring/docs/2.0.8/api/org/springframework/web/util/WebAppRootListener.html" rel="noreferrer">WebAppRootListener</a> or <a href="http://www.jarvana.com/jarvana/view/org/springframework/spring/1.2.9/spring-1.2.9-javadoc.jar!/org/springframework/web/util/Log4jConfigListener.html" rel="noreferrer">Log4jConfigListener</a>.</p> |
1,537,673 | How do I forward parameters to other command in bash script? | <p>Inside my bash script, I would like to parse zero, one or two parameters (the script can recognize them), then forward the remaining parameters to a command invoked in the script. How can I do that?</p> | 1,537,695 | 3 | 0 | null | 2009-10-08 13:05:15.363 UTC | 35 | 2020-04-07 18:08:26.333 UTC | 2017-03-15 14:41:33.897 UTC | null | 1,486,275 | null | 61,342 | null | 1 | 224 | bash|command-line | 98,071 | <p>Use the <a href="http://www.gnu.org/software/bash/manual/bashref.html#index-shift" rel="noreferrer"><code>shift</code></a> built-in command to "eat" the arguments. Then call the child process and pass it the <a href="http://www.gnu.org/software/bash/manual/bashref.html#index-_0040" rel="noreferrer"><code>"$@"</code></a> argument to include all remaining arguments. Notice the quotes, they should be kept, since they cause the expansion of the argument list to be properly quoted.</p> |
8,509,996 | Is there a way to get the row number in Mysql like the rownum in oracle | <p>Is there a way to get the row number in Mysql like the rownum in oracle, If not then is there any indirect way of doing it?
please suggest.</p> | 8,510,069 | 2 | 1 | null | 2011-12-14 18:47:00.93 UTC | 9 | 2016-06-11 11:54:04.63 UTC | null | null | null | null | 961,125 | null | 1 | 17 | mysql|sql|oracle | 33,663 | <p>Until MySQL finally supports <a href="http://modern-sql.com/slides">modern SQL</a>, the only way to get something similar is this: </p>
<pre><code>SELECT @rownum:=@rownum + 1 as row_number,
t.*
FROM (
< your original query goes here >
) t,
(SELECT @rownum := 0) r
</code></pre> |
19,342,908 | How to create a many-to-many mapping in Entity Framework? | <p>Here is the case, I have 2 entities, such as Contract、Media。 </p>
<pre><code>public class Media : Entity
{
public string Name {get; set;}
public bool Enabled
*//other properties can be ignored..*
}
public class Contract : Entity
{
public string Code {get; set;}
*//other properties can be ignored..*
}
</code></pre>
<p>Contract has many Medias, it seems that they are many to many.</p>
<p><strong>But!! at ef code first, i need 3 more fields in the ContractMedia table(ef auto generated).
such as StartDate,EndDate and Price. these could not be added in Media entity.</strong></p>
<p>How to map at this case??</p> | 19,343,047 | 2 | 1 | null | 2013-10-13 07:37:56.197 UTC | 33 | 2021-09-17 22:41:32.243 UTC | 2016-04-22 22:45:34.413 UTC | null | 1,459,996 | null | 2,751,088 | null | 1 | 57 | c#|entity-framework|many-to-many | 75,564 | <p>If you want to create many to many relationship with additional data in association table, you have to make the association table as entity. The pure many to many relationship is only in pure table with entity id's.</p>
<p>In you case it will be:</p>
<pre><code>public class Media // One entity table
{
public int Id { get; set; }
public string Name { get; set; }
public bool Enabled { get; set; }
public virtual ICollection<ContractMedia> ContractMedias { get; set; }
}
public class Contract // Second entity table
{
public int Id { get; set; }
public string Code { get; set }
public virtual ICollection<ContractMedia> ContractMedias { get; set; }
}
public class ContractMedia // Association table implemented as entity
{
public int MediaId { get; set; }
public int ContractId { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public double Price { get; set; }
public virtual Media Media { get; set; }
public virtual Contract Contract { get; set; }
}
</code></pre>
<p>And after you created models/entities, you need to define relationships in context:</p>
<pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ContractMedia>()
.HasKey(c => new { c.MediaId, c.ContractId });
modelBuilder.Entity<Contract>()
.HasMany(c => c.ContractMedias)
.WithRequired()
.HasForeignKey(c => c.ContractId);
modelBuilder.Entity<Media>()
.HasMany(c => c.ContractMedias)
.WithRequired()
.HasForeignKey(c => c.MediaId);
}
</code></pre>
<p>Also you can refer to these links: <br />
<a href="https://stackoverflow.com/questions/15153390/many-to-many-mapping-with-extra-fields-in-fluent-api">Many to many mapping with extra fields in Fluent API</a><br />
<a href="https://stackoverflow.com/questions/5434125/entity-framework-codefirst-many-to-many-relationship-with-additional-information">Entity Framework CodeFirst many to many relationship with additional information</a><br />
<a href="https://stackoverflow.com/questions/7050404/create-code-first-many-to-many-with-additional-fields-in-association-table">Create code first, many to many, with additional fields in association table</a></p> |
868,407 | Hide an element's next sibling with Javascript | <p>I have an element grabbed from <code>document.getElementById('the_id')</code>. How can I get its next sibling and hide it? I tried this but it didn't work:</p>
<pre><code>elem.nextSibling.style.display = 'none';
</code></pre>
<p>Firebug error was <code>elem.nextSibling.style is undefined</code>.</p> | 868,418 | 4 | 0 | null | 2009-05-15 12:28:05.847 UTC | 6 | 2013-06-05 17:59:23.29 UTC | null | null | null | null | 37,947 | null | 1 | 15 | javascript|element|hide|siblings | 44,363 | <p>it's because Firefox considers the whitespace between element nodes to be text nodes (whereas IE does not) and therefore using <code>.nextSibling</code> on an element gets that text node in Firefox.</p>
<p>It's useful to have a function to use to get the next element node. Something like this</p>
<pre><code>/*
Credit to John Resig for this function
taken from Pro JavaScript techniques
*/
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType !== 1);
return elem;
}
</code></pre>
<p>then you can do</p>
<pre><code>var elem = document.getElementById('the_id');
var nextElem = next(elem);
if (nextElem)
nextElem.style.display = 'none';
</code></pre> |
609,937 | What is the benefit of inheriting from std::binary_function (or std::unary function)? | <p>What is the benefit of inheriting from std::binary_function (or std::unary_function)?</p>
<p>For example I have such code:</p>
<pre><code>class Person
{
public:
Person();
Person(int a, std::string n);
Person(const Person& src);
int age;
std::string name;
};
Person::Person()
: age(0)
, name("")
{};
Person::Person(int a, std::string n)
: age(a)
, name(n)
{};
Person::Person(const Person& src)
{
age = src.age;
name = src.name;
};
struct PersonPrint : public std::unary_function<Person, void>{
void operator() (Person p){
std::cout << " Person age: " << p.age
<< " name: " << p.name << std::endl;
}
};
struct PersonGreater : public std::binary_function<Person, Person, bool>{
bool operator()(const Person& p1, const Person p2){
if (p1.age > p2.age) return true;
if (p1.name.compare(p2.name) > 0) return true;
return false;
}
};
int main(int count, char** args)
{
std::vector<Person> personVec;
Person p1(10, "Person1");
Person p2(12, "Person2");
Person p3(12, "Person3");
personVec.push_back(p1);
personVec.push_back(p2);
personVec.push_back(p3);
std::cout << "before sort: " << std::endl;
std::for_each(personVec.begin(), personVec.end(), PersonPrint());
std::sort(personVec.begin(), personVec.end(), PersonGreater());
std::cout << "after: " << std::endl;
std::for_each(personVec.begin(), personVec.end(), PersonPrint());
}
</code></pre>
<p>But I also could write this code without inheritance form <code>std::unary_function/std::binary_function</code>?</p>
<pre><code> struct PersonPrint {
void operator() (Person p) {
std::cout << " Person age: " << p.age << " name: " << p.name << std::endl;
}
};
struct PersonGreater {
bool operator()(const Person& p1, const Person p2) {
if (p1.age > p2.age) return true;
if (p1.name.compare(p2.name) > 0) return true;
return false;
}
};
</code></pre>
<p><strong>UPDATED</strong></p>
<p>std::binary_function and std::unary_function are deprecated as of C++11 see comment by @AlexandreC.</p> | 609,952 | 4 | 6 | null | 2009-03-04 10:03:07.527 UTC | 7 | 2015-02-12 07:27:17.923 UTC | 2015-02-12 07:27:17.923 UTC | dirkgently | 71,910 | Darius Kucinskas | 71,910 | null | 1 | 28 | c++|stl | 9,346 | <p>Inheritance from [unary|binary]_function just gives you an additional typedefs in your class:</p>
<p>For unary_function</p>
<pre><code>argument_type
result_type
</code></pre>
<p>For binary_function</p>
<pre><code>first_argument_type
second_argument_type
result_type
</code></pre>
<p>Which are those types you pass to [unary|binary]_function.
In your case there is no benefits.</p>
<p>If you ever going to use your Functors with other std Functors modificators like not1, bind1st you have to inherit from [unart|binart]_function.</p>
<p>And if you are going to store this template information for your purpose it is better to use ready solution.</p> |
973,916 | LINQ Where in collection clause | <p>I've been looking on google but not finding anything that does the trick for me.</p>
<p>as you know SQL has a "where x in (1,2,3)" clause which allows you to check against multiple values.
I'm using linq but I can't seem to find a piece of syntax that does the same as the above statement.</p>
<p>I have a collection of category id's (List) against which I would like to check</p>
<p>I found something that uses the .contains method but it doesn't even build.</p> | 973,932 | 4 | 0 | null | 2009-06-10 06:03:23.707 UTC | 5 | 2014-11-07 12:06:05.95 UTC | 2012-01-03 14:59:50.063 UTC | user212218 | null | null | 112,406 | null | 1 | 32 | c#|linq-to-sql | 54,398 | <p>You have to use the Contains method on your id list:</p>
<pre><code>var query = from t in db.Table
where idList.Contains(t.Id)
select t;
</code></pre> |
22,239 | Why does int main() {} compile? | <p>(I'm using Visual C++ 2008) I've always heard that main() is <em>required</em> to return an integer, but here I didn't put in <code>return 0;</code> and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a <code>return;</code> also causes the error to appear. But leaving it out completely, it compiles just fine.</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
cout << "Hey look I'm supposed to return an int but I'm not gonna!\n";
}
</code></pre>
<p>Could this be a bug in VC++?</p> | 22,262 | 4 | 0 | null | 2008-08-22 12:49:37.213 UTC | 9 | 2015-10-08 15:18:53.373 UTC | 2009-07-17 20:19:31.917 UTC | sparkes | 113,116 | da_code_monkey | 2,222 | null | 1 | 37 | c++|return-value|program-entry-point | 10,218 | <blockquote>
<h1>3.6.1 Main function</h1>
<p>....</p>
<p>2 An implementation shall not predefine the <code>main</code> function. This function shall not be overloaded. It shall have a return type of type <code>int</code>, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:</p>
<pre><code>int main() { /* ... */ }
</code></pre>
<p>and</p>
<pre><code>int main(int argc, char* argv[]) {
/* ... */
}
</code></pre>
<p>.... and it continues to add ...</p>
<p>5 A <code>return</code> statement in <code>main</code> has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling <code>exit</code> with the return value as the argument. <strong>If control reaches the end of <code>main</code> without encountering a return statement, the effect is that of executing return 0</strong>;</p>
</blockquote>
<p>attempting to find an online copy of the C++ standard so I could quote this passage <a href="http://zamanbakshifirst.blogspot.com/2006/11/c-c-main-should-return-void.html" rel="noreferrer">I found a blog post that quotes all the right bits better than I could.</a></p> |
1,031,674 | How do I write a jquery function that accepts a callback as a parameter | <p>I Have the following function. </p>
<pre><code>function ChangeDasPanel(controllerPath, postParams) {
$.post(controllerPath, postParams, function(returnValue) {
$('#DasSpace').hide("slide", { direction: "right" }, 1000, function() {
$('#DasSpace').contents().remove();
$('#DasSpace').append(returnValue).css("display", "block");
$('#DasSpace').show("slide", { direction: "right" }, 1000);
});
});
};
</code></pre>
<p>But I want to be able to call it like this</p>
<pre><code>ChangeDasPanel("../Home/Test", {} ,function (){
//do some stuff on callback
}
</code></pre>
<p>How can I implement support for callbacks in my function?</p> | 1,031,709 | 4 | 0 | null | 2009-06-23 10:07:00.207 UTC | 21 | 2014-03-20 05:27:51.88 UTC | null | null | null | null | 77,249 | null | 1 | 49 | javascript|jquery|function|callback | 89,912 | <pre><code>function ChangeDasPanel(controllerPath, postParams, f) {
$.get(
controllerPath,
postParams,
function(returnValue) {
var $DasSpace = $('#DasSpace');
$DasSpace.hide(
"slide", { direction: "right" }, 1000,
function() {
$DasSpace.contents().remove();
$DasSpace.append(returnValue).css("display", "block");
$DasSpace.show("slide", { direction: "right" }, 1000);
}
);
if (typeof f == "function") f(); else alert('meh');
}
);
};
</code></pre>
<p>You can pass functions like any other object in JavaScript. Passing in a callback function is straight-forward, you even do it yourself in the <code>$.post()</code> call.</p>
<p>You can decide whether you want to have your callback called as part of the <code>$.post()</code> callback or on its own.</p> |
195,975 | How to make a char string from a C macro's value? | <p>For example, how to avoid writing the 'func_name' twice?</p>
<pre><code>#ifndef TEST_FUN
# define TEST_FUN func_name
# define TEST_FUN_NAME "func_name"
#endif
</code></pre>
<p>I'd like to follow the <a href="http://en.wikipedia.org/wiki/Single_Point_of_Truth" rel="noreferrer">Single Point of Truth</a> rule.</p>
<p>Version of C preprocessor:</p>
<pre><code>$ cpp --version
cpp (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14)
</code></pre> | 196,018 | 4 | 1 | null | 2008-10-12 20:16:05.19 UTC | 21 | 2016-02-01 22:01:32.393 UTC | 2016-02-01 22:01:32.393 UTC | Jonathan Leffler | 4,370,109 | J.F. Sebastian | 4,279 | null | 1 | 55 | c|c-preprocessor|dry | 124,993 | <p><a href="https://stackoverflow.com/users/9611/shoosh">He who is Shy</a><sup>*</sup> gave you the germ of an <a href="https://stackoverflow.com/a/195980/15168">answer</a>, but only the germ. The basic technique for converting a value into a string in the C pre-processor is indeed via the '#' operator, but a simple transliteration of the proposed solution gets a compilation error:</p>
<pre><code>#define TEST_FUNC test_func
#define TEST_FUNC_NAME #TEST_FUNC
#include <stdio.h>
int main(void)
{
puts(TEST_FUNC_NAME);
return(0);
}
</code></pre>
<p>The syntax error is on the 'puts()' line - the problem is a 'stray #' in the source.</p>
<p>In section 6.10.3.2 of the C standard, 'The # operator', it says:</p>
<blockquote>
<p>Each # preprocessing token in the
replacement list for a function-like
macro shall be followed by a parameter
as the next preprocessing token in the
replacement list.</p>
</blockquote>
<p>The trouble is that you can convert macro arguments to strings -- but you can't convert random items that are not macro arguments.</p>
<p>So, to achieve the effect you are after, you most certainly have to do some extra work.</p>
<pre><code>#define FUNCTION_NAME(name) #name
#define TEST_FUNC_NAME FUNCTION_NAME(test_func)
#include <stdio.h>
int main(void)
{
puts(TEST_FUNC_NAME);
return(0);
}
</code></pre>
<p>I'm not completely clear on how you plan to use the macros, and how you plan to avoid repetition altogether. This slightly more elaborate example might be more informative. The use of a macro equivalent to STR_VALUE is an idiom that is necessary to get the desired result.</p>
<pre><code>#define STR_VALUE(arg) #arg
#define FUNCTION_NAME(name) STR_VALUE(name)
#define TEST_FUNC test_func
#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)
#include <stdio.h>
static void TEST_FUNC(void)
{
printf("In function %s\n", TEST_FUNC_NAME);
}
int main(void)
{
puts(TEST_FUNC_NAME);
TEST_FUNC();
return(0);
}
</code></pre>
<hr>
<p><sup>* At the time when this answer was first written, <a href="https://stackoverflow.com/users/9611/shoosh">shoosh</a>'s name used 'Shy' as part of the name.</sup></p> |
129,445 | postgreSQL - psql \i : how to execute script in a given path | <p>I'm new to postgreSQL and I have a simple question:</p>
<p>I'm trying to create a simple script that creates a DB so I can later call it like this:</p>
<pre><code>psql -f createDB.sql
</code></pre>
<p>I want the script to call other scripts (separate ones for creating tables, adding constraints, functions etc), like this:</p>
<pre><code>\i script1.sql
\i script2.sql
</code></pre>
<p>It works fine provided that createDB.sql is in the <strong>same dir</strong>.</p>
<p>But if I move script2 to a directory under the one with createDB, and modify the createDB so it looks like this:</p>
<pre><code>\i script1.sql
\i somedir\script2.sql
</code></pre>
<p>I get an error:</p>
<blockquote>
<p>psql:createDB.sql:2: somedir: Permission denied</p>
</blockquote>
<p>I'm using Postgres Plus 8.3 for windows, default postgres user.</p>
<p><strong>EDIT:</strong></p>
<p>Silly me, unix slashes solved the problem.</p> | 129,496 | 4 | 0 | null | 2008-09-24 19:49:48.807 UTC | 13 | 2017-02-23 07:11:03.93 UTC | 2015-09-11 15:06:18.547 UTC | gizmo | 4,333,555 | null | 21,853 | null | 1 | 80 | postgresql | 179,253 | <p>Postgres started on Linux/Unix. I suspect that reversing the slash with fix it.</p>
<pre><code>\i somedir/script2.sql
</code></pre>
<p>If you need to fully qualify something</p>
<pre><code>\i c:/somedir/script2.sql
</code></pre>
<p>If that doesn't fix it, my next guess would be you need to escape the backslash.</p>
<pre><code>\i somedir\\script2.sql
</code></pre> |
740,119 | Default passwords of Oracle 11g? | <p>I installed Oracle 11g. I didn't change the passwords for SYSTEM and SYS. However now I find that the default passwords do not work. Please help.</p> | 740,884 | 4 | 0 | null | 2009-04-11 13:52:48.703 UTC | 29 | 2016-07-29 09:39:37.453 UTC | 2009-04-11 14:08:57.417 UTC | null | 60,261 | null | 69,746 | null | 1 | 85 | oracle11g | 447,250 | <p>It is possible to connect to the database without specifying a password. Once you've done that you can then reset the passwords. I'm assuming that you've installed the database on your machine; if not you'll first need to connect to the machine the database is running on.</p>
<ol>
<li><p>Ensure your user account is a member of the <code>dba</code> group. How you do this depends on what OS you are running.</p></li>
<li><p>Enter <code>sqlplus / as sysdba</code> in a Command Prompt/shell/Terminal window as appropriate. This should log you in to the database as SYS.</p></li>
<li><p>Once you're logged in, you can then enter</p>
<pre><code>alter user SYS identified by "newpassword";
</code></pre>
<p>to reset the SYS password, and similarly for SYSTEM.</p></li>
</ol>
<p>(Note: I haven't tried any of this on Oracle 12c; I'm assuming they haven't changed things since Oracle 11g.)</p> |
805,280 | Loading up a web.xml for integration tests with jetty | <p>OK this is kind of related to : <a href="https://stackoverflow.com/questions/728805/using-jetty-to-install-and-run-servlet-tests-programmatically">Using jetty to install and run servlet tests programmatically</a></p>
<p>got great answers there, and have been able to load up servlets programmatically and its all made of awesome. </p>
<p>What I would like to do however is load up a web.xml in a test (all in the classpath) and have it run up a server (using the current classpath) - I have seen in docs how to point it to a directory to do that, but I want to work off the classpath (better for in place testing). Essentially validating my web.xml. </p>
<p>(its not relevant, but this app is in scala, but I have had no issue with that, everything works as advertised).</p> | 1,244,719 | 1 | 2 | null | 2009-04-30 03:51:27.333 UTC | 11 | 2009-08-07 13:34:06.23 UTC | 2017-05-23 12:08:38.51 UTC | null | -1 | null | 699 | null | 1 | 8 | java|jvm|jetty | 8,395 | <p>It sounds like what you want to do is load a proper web application programatically, as opposed to loading individual servlets (and I think you want to do it without having a full WAR file to work from).</p>
<pre><code>Server server = new Server( port );
WebAppContext root = new WebAppContext();
root.setWar("/path/to/somewhere");
root.setContextPath("/");
server.addHandler( root );
server.start();
</code></pre>
<p>The trick is that the <code>/path/to/somewhere</code> should contain a <code>WEB-INF</code> directory and your <code>web.xml</code> file should live inside there. Nothing else needs to live within that directory structure, as everything else can be automatically loaded from your classpath (though if you wanted to, you could make that a path to an actual WAR file or complete exploded WAR tree).</p> |
39,840,030 | Distance between point and a line (from two points) | <p>I'm using Python+Numpy (can maybe also use Scipy) and have three 2D points </p>
<pre><code>(P1, P2, P3);
</code></pre>
<p>I am trying to get the distance from P3 perpendicular to a line drawn between P1 and P2. Let <code>P1=(x1,y1)</code>, <code>P2=(x2,y2)</code> and <code>P3=(x3,y3)</code></p>
<p>In vector notation this would be pretty easy, but I'm fairly new to python/numpy and can't get anythng that works (or even close).</p>
<p>Any tips appreciated, thanks!</p> | 39,840,218 | 9 | 0 | null | 2016-10-03 20:40:11.667 UTC | 20 | 2022-01-22 17:27:55.627 UTC | 2017-04-28 19:20:43.29 UTC | null | 4,126,111 | null | 1,185,675 | null | 1 | 41 | python|numpy|vector|scipy|point | 77,582 | <p>Try using the <em>norm</em> function from <code>numpy.linalg</code></p>
<pre><code>d = norm(np.cross(p2-p1, p1-p3))/norm(p2-p1)
</code></pre> |
39,566,952 | Cordova Info.plist NSCameraUsageDescription key is missing | <p>After recent changes Apple requires specific keys if your app attempts to access privacy-sensitive data. So I added NSCameraUsageDescription key in my config.xml like this:</p>
<pre><code><platform name="ios">
<config-file parent="NSCameraUsageDescription" target="*-Info.plist">
<string>We are using a camera to </string>
</config-file>
</platform>
</code></pre>
<p>Then</p>
<pre><code>cordova build ios --release --device
</code></pre>
<p>produces the ipa which apparently doesn't have the right info in info.plist. It feels like I'm missing something.</p>
<p><strong>Question 1:</strong>
What do I need to put into config.xml to solve NSCameraUsageDescription issue?
<strong>Question 2:</strong>
Is it possible to use localization for this string?</p>
<p>Thank you!</p> | 39,571,192 | 8 | 0 | null | 2016-09-19 06:48:53.537 UTC | 6 | 2019-08-13 20:36:33.347 UTC | 2019-08-13 20:36:33.347 UTC | null | 701,869 | null | 701,869 | null | 1 | 31 | ios|cordova|hybrid-mobile-app | 43,834 | <p>NEW ANSWER:</p>
<p>Since Cordova CLI 6.5.0 you can write in the <code>info.plist</code> directly by using the <code>edit-config</code> tag in the <code>config.xml</code> like this:</p>
<pre><code> <string>your usage message</string>
</edit-config>
</code></pre>
<p>But make sure you are using latest version of the plugins or values might be overwritten by the plugin variables.</p>
<p>For localizations you can use the <code>resource-file</code> tag and InfoPlist.strings files like in this plugin (but you don't need the plugin, resource-file tag is supported from the config.xml)</p>
<p><a href="https://github.com/MBuchalik/cordova-plugin-ios-permissions" rel="nofollow noreferrer">https://github.com/MBuchalik/cordova-plugin-ios-permissions</a></p>
<hr>
<p>OLD ANSWER:</p>
<p><strike>You can't write on the <code>info.plist</code> from the <code>config.xml</code> using the <code>config-file</code> tag yet (it's being worked on)</p>
<p>Latest version of the camera plugin allows you to add the <code>NSCameraUsageDescription</code> when you install the plugin </p>
<p><code>cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message"</code></p>
<p>Right now it's not possible to localize this string</strike></p> |
72,138,080 | Gitlab pipeline - reports config contains unknown keys: cobertura | <p>I'm not able run the gitlab pipeline due to this error</p>
<pre><code>Invalid CI config YAML file
jobs:run tests:artifacts:reports config contains unknown keys: cobertura
</code></pre> | 72,138,320 | 2 | 0 | null | 2022-05-06 08:01:50.047 UTC | null | 2022-05-06 12:28:04.55 UTC | null | null | null | null | 7,081,016 | null | 1 | 36 | gitlab|gitlab-ci|pipeline|cobertura | 11,338 | <p>Check the latest correct doc here: <a href="https://docs.gitlab.com/ee/ci/yaml/artifacts_reports.html#artifactsreportscoverage_report" rel="noreferrer">https://docs.gitlab.com/ee/ci/yaml/artifacts_reports.html#artifactsreportscoverage_report</a></p>
<p>Some of the docs are in somewhat of a messy state right now, due to the new release as mentioned.</p>
<p>This was the fix for me:</p>
<pre><code> artifacts:
expire_in: 2 days
reports:
coverage_report:
coverage_format: cobertura
path: python_app/coverage.xml
</code></pre> |
33,209,938 | What is the purpose of angular-sanitize ? | <p>I was just going through the examples for a angular and openlayers directive <strong><a href="https://github.com/tombatossals/angular-openlayers-directive" rel="noreferrer">HERE</a></strong> and came across the following example:</p>
<pre><code><!DOCTYPE html>
<html ng-app="demoapp">
<head>
<script src="../bower_components/openlayers3/build/ol.js"></script>
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script src="../dist/angular-openlayers-directive.js"></script>
<link rel="stylesheet" href="../bower_components/openlayers3/build/ol.css" />
<script>
var app = angular.module('demoapp', ['openlayers-directive']);
app.controller('DemoController', [ '$scope', function($scope) {
angular.extend($scope, {
center: {
lat: 0,
lon: 0,
autodiscover: true
}
});
}]);
</script>
</head>
<body ng-controller="DemoController">
<openlayers ol-center="center" height="400px"></openlayers>
<h1>Center autodiscover example</h1>
<form>
Latitude : <input type="number" step="any" ng-model="center.lat" />
Longitude : <input type="number" step="any" ng-model="center.lon" />
Zoom : <input type="number" step="any" ng-model="center.zoom" />
<button ng-click="center.autodiscover=true">Discover position</button>
</form>
</body>
</html>
</code></pre>
<p>The example can be seen as a live example <strong><a href="http://tombatossals.github.io/angular-openlayers-directive/examples/022-center-autodiscover-example.html" rel="noreferrer">HERE</a></strong>. </p>
<p>My question is about the files being loaded, I don't quite understand why the below script being loaded: </p>
<pre><code><script src="../bower_components/angular-sanitize/angular-sanitize.min.js"></script>
</code></pre>
<p>What is the purpose of the above script ? </p>
<p><strong>EDIT::</strong> : i found out the git repo and the docs here for this module in angular <strong><a href="https://docs.angularjs.org/api/ngSanitize" rel="noreferrer">HERE</a></strong>. , but i still don't understand the purpose of this script , the documentation does't even have a single example. </p>
<p>I have coded in jQuery a fair bit , so can somebody explain this in jQuery terms ? </p> | 33,209,988 | 1 | 0 | null | 2015-10-19 08:32:39.387 UTC | 8 | 2019-07-08 19:20:26.953 UTC | null | null | null | null | 4,381,665 | null | 1 | 27 | javascript|angularjs | 44,572 | <p>If you include the <code>angular-sanitize</code> script, inputs are sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are then serialized back to properly escaped html string. This means that no unsafe input can make it into the returned string. </p>
<p>I have included a small example below inspired by this <a href="http://odetocode.com/blogs/scott/archive/2014/09/10/a-journey-with-trusted-html-in-angularjs.aspx">blog post</a>. If you run this script with <code>var app = angular.module("app", ["ngSanitize"]);</code> the html links are rendered correctly. However, if you comment this statement out and uncomment <code>var app = angular.module("app", []);</code> the following error message is raised: <code>Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.</code></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.min.js"></script>
<!-- BEGIN disable refresh -->
<script type="text/javascript">
//Including ngSanitize ensures html links get properly sanitized
var app = angular.module("app", ["ngSanitize"]);
//If you use this code instead no html links get displayed
//var app = angular.module("app", []);
app.controller("mainController", function($scope) {
var main = this;
main.links = [
"<a href='http://google.com'>Google</a>",
"<a href='http://odetocode.com'>OdeToCode</a>",
"<a href='http://twitter.com'>Twitter</a>"
];
});
</script>
</head>
<body ng-app="app">
<section ng-controller="mainController as main">
<nav>
<ul>
<li ng-repeat="link in main.links" ng-bind-html="link">
</li>
</ul>
</nav>
</section>
</body>
</html></code></pre>
</div>
</div>
</p> |
33,315,210 | error: command 'x86_64-linux-gnu-gcc' when installing mysqlclient | <p>I installed django 1.8.5 in virtualenv and using python 3.4.3
the worked displayed the <strong>it works</strong> page when using sqlite</p>
<p>I wanted to use mysql and I'm trying to install mysqlclient using</p>
<p><code>pip install mysqlclient</code></p>
<p>and I'm getting the following message</p>
<pre><code>----------------------------------------
Failed building wheel for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient
Complete output from command /home/sasidhar/django/env/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip-build-5lj39q67/mysqlclient/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-da2_35zs-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/sasidhar/django/env/include/site/python3.4/mysqlclient:
running install
running build
running build_py
copying MySQLdb/release.py -> build/lib.linux-x86_64-3.4/MySQLdb
running build_ext
building '_mysql' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,6,'final',1) -D__version__=1.3.6 -I/usr/include/mysql -I/usr/include/python3.4m -I/home/sasidhar/django/env/include/python3.4m -c _mysql.c -o build/temp.linux-x86_64-3.4/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g -DNDEBUG
_mysql.c:40:20: fatal error: Python.h: No such file or directory
#include "Python.h"
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
Command "/home/sasidhar/django/env/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip-build-5lj39q67/mysqlclient/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-da2_35zs-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/sasidhar/django/env/include/site/python3.4/mysqlclient" failed with error code 1 in /tmp/pip-build-5lj39q67/mysqlclient
</code></pre>
<p>I did try installing libraries suggested in <a href="https://stackoverflow.com/questions/26053982/error-setup-script-exited-with-error-command-x86-64-linux-gnu-gcc-failed-wit">error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1</a></p>
<p>and still the problem persists
please help me solve this problem<br>
Thanks guys!! </p> | 33,315,233 | 5 | 0 | null | 2015-10-24 06:28:06.42 UTC | 10 | 2020-04-17 21:05:24.59 UTC | 2017-05-23 12:34:24.333 UTC | null | -1 | null | 3,057,648 | null | 1 | 17 | mysql|django|python-3.4 | 19,517 | <p>You need to install python-dev:</p>
<pre><code>sudo apt-get install python-dev
</code></pre>
<p>And, since you are using python3:</p>
<pre><code>sudo apt-get install python3-dev
</code></pre>
<p>This command should help you.</p>
<p>If you are using mac os you might try:</p>
<pre><code>brew update && brew rm python3 && brew install python3
</code></pre>
<p>You need to brew has been installed already, otherwise you can install it. It is very useful for getting packages in Mac OS. <a href="http://brew.sh/">http://brew.sh/</a></p> |
47,175,526 | Try with multiple Resource in Java | <p>I am new in <code>Java8</code>, and I want to know if, for the <code>AutoCloseable</code> resource, I have to add a <code>try</code> for each <code>resource</code>, or it will work with the code above</p>
<pre><code>try (Connection conn = getConnection();) {
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(sql);
while (rset.next()) {
TelefonicaDataVO vo = new TelefonicaDataVO();
vo.setTelefonicaDataId(rset.getString("Telefonica_PSD_ID"));
vo.setReceptionDate(nvl(rset.getTimestamp("CREATION_DATE")));
vo.setMessage(nvl(rset.getString("MESSAGE")));
ret.add(vo);
}
}
</code></pre> | 47,175,609 | 1 | 0 | null | 2017-11-08 09:06:50.85 UTC | 10 | 2017-12-11 07:35:33.627 UTC | 2017-12-11 07:35:33.627 UTC | null | 3,926,506 | null | 7,661,910 | null | 1 | 41 | java|try-with-resources|autocloseable | 33,819 | <p>Try with resources can be used with multiple resources by declaring them all in the <strong><code>try</code></strong> block and this feature introduced in <strong>java 7</strong> not in <strong>java 8</strong> If you have multiple you can give like below</p>
<pre><code>try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
</code></pre>
<p>In this example, the <code>try-with-resources</code> statement contains two declarations that are separated by a semicolon: <strong>ZipFile</strong> and <strong>BufferedWriter</strong>. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. <strong>Note that the close methods of resources are called in the opposite order of their creation.</strong>.</p>
<p>Please see <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="noreferrer">documentation</a> for more info</p> |
20,013,989 | Configure node npm package.json so that "npm test" works on both unix and windows | <p>I have developed a node.js npm module, developing under Windows. Today I wrote some Mocha tests. After many struggles, it seemed that for <code>npm test</code> to work, <code>package.json</code> had to look like this: (there may be other options???)</p>
<pre><code>"scripts": { "test": "node node_modules/mocha/bin/mocha" }
</code></pre>
<p>instead of what's in all the Unix based books, </p>
<pre><code>"scripts": { "test": "./node_modules/.bin/mocha" }
</code></pre>
<p>How can I set package.json up to work on both Windows and Unix? I'm assuming that Travis-CI runs Unix, so, should I link the build to that, it will blow up with the Windows version.</p>
<p>I found a two year old thread where somebody requested a feature for exactly this. That thread seemed to die out. This <a href="https://stackoverflow.com/questions/10396305/npm-package-bin-script-for-windows">SO question</a> seems to be close, but it isn't exactly what I want and, frankly, I can't understand the answer. :-( Can anybody clarify?</p>
<p>For the time being, I am going</p>
<pre><code>"scripts": {
"test": "node node_modules/mocha/bin/mocha",
"testOnUnixUseThis" : "./node_modules/.bin/mocha (I think)",
"testOnWindowsUseThis" : "node node_modules/mocha/bin/mocha"
},
</code></pre>
<p>Unfortunately, you cant go <code>npm test testOnWindowsUseThis</code> or <code>npm testOnWindowsUseThis</code>. And it doesn't fix the Travis-CI issue. But at least a person who downloads the module can (hopefully) see what is going on. </p>
<p>Any better ideas? Am I the only person still developing under Windows??? :-)</p> | 20,014,206 | 5 | 0 | null | 2013-11-16 02:43:26.967 UTC | 11 | 2021-02-28 22:56:25.667 UTC | 2017-05-23 12:03:05.75 UTC | null | -1 | null | 949,300 | null | 1 | 31 | windows|node.js|unix|npm | 47,452 | <p>I've always been able to <code>npm install -g mocha</code> or <code>npm install mocha</code> and then just add</p>
<pre><code>"scripts": {
"test": "mocha spec"
}
</code></pre>
<p>to package.json. That may or may not work in EVERY environment. I know, for instance, with lineman, you have to use bin/mocha. Also, if you don't find a way around this, set your test script up for Unix and then add a second script called "wintest" or something that does whatever you need it to do in Windows. You can name your scripts whatever you want. The default ones (test, start, etc.) can be used with <code>npm [command]</code>; any non-standard ones (like wintest) can be used with <code>npm run-script [command]</code>, and they will still work.</p>
<p>A little back story on how/why this works:</p>
<p>When you install a module globally, it's available on PATH (or whatever the windows equivalent is). When you install a project dependency, if that module has any binaries, those are symlinked to <code>node_modules/.bin</code> and when you run <code>npm run [some-command]</code>, npm helpfully adds <code>node_modules/.bin</code> to PATH <em>for that command</em>. So when mocha is installed globally <code>"test": "mocha spec"</code> uses your globally installed mocha to run tests. When it's a project dependency, it uses the one in <code>node_modules/.bin</code>. The one gotcha I've found with this is that npm adds <code>node_modules/.bin</code> to the <em>front</em> of PATH, so local binaries will always take precedence over global ones. <em>Almost all of the time</em>, this is what you want, but it's worth knowing that that's how it works (I recently had a bug related to this).</p>
<p>EDIT:</p>
<p>Not sure at what point in npm history this changed, but <code>npm run <script-name></code> now works (don't need to do <code>npm run-script <script-name></code> anymore). Possibly <code>run-script</code> still works as well. I'd expect it to, but I haven't tried it.</p> |
21,572,725 | Finding out the installed version of twig | <p>Is there a way to find out my installed version of Twig?</p>
<p>Something like </p>
<pre><code><p>The current version is {% twig.version %}</p>
</code></pre>
<p>(although I know that's not even close to being right).</p> | 21,572,829 | 5 | 0 | null | 2014-02-05 09:04:17.223 UTC | 5 | 2022-04-08 12:58:55.953 UTC | 2014-02-05 09:27:22.15 UTC | null | 457,148 | null | 457,148 | null | 1 | 36 | php|twig | 17,673 | <p>Try it:</p>
<pre><code><p>The current version is {{ constant('Twig_Environment::VERSION') }}</p>
</code></pre> |
20,510,243 | Clear the form field after successful submission of php form | <p>I am making a simple Form the problem i am facing is when i submit the form values still remains in the field. and I want to clear it after SUCCESSFUL submission. Please help.</p>
<p>here is my code for the form..</p>
<pre><code><label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
<option value="">Select One</option>
<option value="FREE Account">FREE Account</option>
<option value="Premium Account Monthly">Premium Account Monthly</option>
<option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" value="<?php echo $_POST['lastname'];?>"><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" value="<?php echo $_POST['email'];?>"><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required" value="<?php echo $_POST['password'];?>"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required" value="<?php echo $_POST['confirmpassword'];?>"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required" value="<?php echo $_POST['strtadd1'];?>"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" value="<?php echo $_POST['strtadd2'];?>"><br>
<label class="w">City :</label><input name="city" type="text" placeholder="City" required="required" value="<?php echo $_POST['firstname'];?>"><br>
<label class="w">Country :</label><select autofocus="" id="a1_txtBox1" name="country" required="required" placeholder="select one" value="<?php echo $_POST['country'];?>">
</code></pre>
<p>Any help would be appriciated</p> | 20,510,258 | 14 | 0 | null | 2013-12-11 03:59:27.573 UTC | 7 | 2021-09-27 02:45:35.533 UTC | 2017-01-16 14:47:11.18 UTC | null | 6,173,350 | null | 3,077,217 | null | 1 | 7 | php|forms | 182,596 | <p>They remain in the fields because you are explicitly telling PHP to fill the form with the submitted data.</p>
<pre><code><input name="firstname" type="text" placeholder="First Name" required="required"
value="<?php echo $_POST['firstname'];?>">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HERE
</code></pre>
<p>Just remove this, or if you want a condition to not do so make a <code>if</code> statement to that <code>echo</code> or just cleanup the <code>$_POST</code> fields.</p>
<pre><code>$_POST = array(); // lets pretend nothing was posted
</code></pre>
<p>Or, if successful, redirect the user to another page:</p>
<pre><code>header("Location: success.html");
exit; // Location header is set, pointless to send HTML, stop the script
</code></pre>
<p>Which by the way is the prefered method. If you keep the user in a page that was reached through a <code>POST</code> method, if he refreshes the page the form will be submitted again.</p> |
24,180,034 | Authenticated access to WebAPI via Facebook token from Android App | <p>I'm trying to make my Android Application to log into my WebAPI services. I want to share my ideas in order to verify them.</p>
<p>If the access to WebAPI is performed via WebSite the steps are:</p>
<p>1- Call WebAPI method for logging in</p>
<p>2- WebAPI redirect client to facebook</p>
<p>3- Facebook login and returns a Token</p>
<p>4- If I use that token in the next calls I'll be authenticated as the right user.</p>
<p>And this works.</p>
<p>If the access to WebAPI is performed via Android APP, how can I get the access token?
Actually I'm doing something like:</p>
<p>1- Contact Facebook via Login Button</p>
<p>2- Getting logged id to Facebook receiving a Token</p>
<p>3- Trying to perform WebAPI calls adding the Authentication: Bearer CODE to my calls</p>
<p>At that point I'm wandering..</p>
<p>How can my application now that I'm THAT particular user? If I perform something like</p>
<pre><code>GET /API/METHOD1
Authentication: Bearer CODE
</code></pre>
<p>How can it knows that the CODE is me if the Android Application never told him? Does the application automatically contact Facebook in order to receive an answer like "yeah! I release that token, it is related to..."</p>
<p>Or I'm misunderstanding everything?</p>
<p>The other way I can figure it out is that I must use an "hybrid approach" like:</p>
<p>1- Call WebAPI (as via browser)
2- Get Redirect link to Facebook
3- Get the token</p>
<p>But.. At that point, how can I swith between Facebook App / Facebook Site to my Android application again?</p>
<p>Sorry for the mess, I'm trying to find out the logic beside this auth process.</p> | 24,181,314 | 1 | 0 | null | 2014-06-12 08:45:12.307 UTC | 10 | 2017-07-07 04:42:46.393 UTC | null | null | null | null | 530,384 | null | 1 | 8 | android|facebook|token|asp.net-web-api | 4,632 | <p>Ok, I think I've got it!</p>
<p>when WebAPI receives the Facebook Token doesn't know anything about user and authorizations. BUT, due to the token, can access to Facebook "as the caller".</p>
<p>By this way the application could perform something like:</p>
<ol>
<li><p>Android -> Facebook Login -> Get FBToken</p></li>
<li><p>Android -> Web API -> Send FBToken</p></li>
<li><p>Web API -> Facebook -> /me Sending FBToken</p></li>
<li><p>Facebook -> Web API -> Identity</p></li>
<li><p>Web API -> Andoid -> This is the token for you Identity</p></li>
<li><p>Android -> Web API -> Give me Auth Method, Authorization: Bearer WebAPIToken</p></li>
</ol>
<p>I found out a useful class online: (based on <a href="https://stackoverflow.com/questions/21092723/webapi-asp-net-identity-facebook-login">WebApi ASP.NET Identity Facebook login</a>)</p>
<pre><code>private async Task<FacebookUserViewModel> VerifyFacebookAccessToken(string accessToken)
{
FacebookUserViewModel fbUser = null;
var path = "https://graph.facebook.com/me?access_token=" + accessToken;
var client = new HttpClient();
var uri = new Uri(path);
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
fbUser = Newtonsoft.Json.JsonConvert.DeserializeObject<FacebookUserViewModel> (content);
}
return fbUser;
}
public class FacebookUserViewModel
{
[JsonProperty("id")]
public string ID { get; set; }
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
}
</code></pre>
<p>So, you could have a WebAPI like:</p>
<pre><code> [HttpGet]
[AllowAnonymous]
public async Task<string> GetTokenFromFacebook(string accessToken)
{
var user = await VerifyFacebookAccessToken(accessToken);
//Search on your DB for the user ID or email
//Get token for user
return token;
}
</code></pre>
<p>A complete and perfect explanation is here:
<a href="http://thewayofcode.wordpress.com/2014/03/01/asp-net-webapi-identity-system-how-to-login-with-facebook-access-token/" rel="noreferrer">http://thewayofcode.wordpress.com/2014/03/01/asp-net-webapi-identity-system-how-to-login-with-facebook-access-token/</a></p>
<p>Example of token creation</p>
<pre><code> var tokenExpirationTimeSpan = TimeSpan.FromDays(14);
var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, UserName, null, "Facebook"));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.ToString(), null, "LOCAL_AUTHORITY"));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
var accesstoken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
</code></pre>
<p>I hope it helps!</p> |
27,850,472 | Html5 video background, keep center of video in center | <p>I am trying to keep a background video centered regardless of how big the user drags the video. It's currently cutting off the right side of the videos when i scroll smaller. Here's what I have:</p>
<pre><code><section id="home">
<div class="video_shader"></div>
<div class="video_contain">
<video autoplay="" loop="" poster="img/still.jpg" id="bgvid">
<source src="/realWebm.webm" type="video/webm" />
<source src="/realdeal.mp4" type="video/mp4">
<source src="/reaOg.ogv" type="video/ogg" />
</video>
</div>
</section>
.video_contain{
display: block;
position: absolute;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
video {
min-width: 100%;
min-height: 100%;
z-index: -100;
background-position: center;
background-size: cover;
}
#home {
width: 100vw;
height: 100vh;
display:block;
position: relative;
}
</code></pre>
<p>I would like the center of the video to be the center of the page always, even if the sides get cut off - that's actually ideal if it happens that way. Would appreciate any help. Thanks for reading!</p> | 27,850,657 | 10 | 0 | null | 2015-01-08 22:13:00 UTC | 18 | 2020-05-15 00:01:56.297 UTC | null | null | null | null | 3,201,696 | null | 1 | 38 | css|html|video | 73,597 | <p>here's how I typically do background video, and how I did it for the <strong><a href="https://stre.am/" rel="noreferrer">stre.am</a></strong> landing page:</p>
<pre><code>.video_contain {
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
}
video {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
min-height: 50%;
min-width: 50%;
}
</code></pre>
<p><img src="https://i.stack.imgur.com/CnYk7.jpg" alt="stream fs vid for mobile"></p> |
20,945,944 | Jekyll & Liquid: Output category list with post count? | <p>I'm somehow stuck and don't find the right way to do it.</p>
<p>I want to output a category list with the number of posts in each categorie.</p>
<p>I got this far: <a href="https://paste.xinu.at/dOLtod/" rel="nofollow noreferrer">https://paste.xinu.at/dOLtod/</a> </p>
<p>but I never managed to get the real count. I tried so many ways and nothing worked, for example going through each post and checked on every category if it equals {{ category | first }}.</p>
<p>Here is the code without the count:</p>
<pre><code><ul class="dropdown-menu">
{% for category in site.categories %}
<li class="camelize_me">
<a href="/tags/{{category | first}}/">
{{category | first }}
<span class="badge">
<!-- Post count here -->
</span>
</a>
</li>
{% endfor %}
</ul>
</code></pre>
<p>Has anyone an idea to get this done?</p> | 21,080,786 | 3 | 0 | null | 2014-01-06 08:35:22.073 UTC | 9 | 2020-04-04 18:56:08.15 UTC | 2018-02-10 18:37:14.977 UTC | null | 472,495 | null | 3,164,650 | null | 1 | 15 | jekyll|liquid | 11,390 | <p>I have written a code snippet that not only shows post count in each category, but also navigates to the posts of a specific category which got clicked. I hope you find it helpful:</p>
<pre><code><ul class="tag-box inline">
{% assign tags_list = site.categories %}
{% if tags_list.first[0] == null %}
{% for tag in tags_list %}
<li><a href="#{{ tag }}">{{ tag | capitalize }} <span>{{ site.tags[tag].size }}</span></a></li>
{% endfor %}
{% else %}
{% for tag in tags_list %}
<li><a href="#{{ tag[0] }}">{{ tag[0] | capitalize }} <span>{{ tag[1].size }}</span></a></li>
{% endfor %}
{% endif %}
{% assign tags_list = nil %}
</ul>
{% for tag in site.categories %}
<h2 id="{{ tag[0] }}">{{ tag[0] | capitalize }}</h2>
<ul class="post-list">
{% assign pages_list = tag[1] %}
{% for post in pages_list %}
{% if post.title != null %}
{% if group == null or group == post.group %}
<li><a href="{{ site.url }}{{ post.url }}">{{ post.title }}<span class="entry-date"><time datetime="{{ post.date | date_to_xmlschema }}" itemprop="datePublished">{{ post.date | date: "%B %d, %Y" }}</time></a></li>
{% endif %}
{% endif %}
{% endfor %}
{% assign pages_list = nil %}
{% assign group = nil %}
</ul>
{% endfor %}
</code></pre> |
22,886,353 | Printing colors in python terminal | <p>I'd like to make a program that prints colors in the python terminal but I don't know how. I've heard that you can use certain escape sequences to print text in color, but I'm not sure of this. How can I print a string in a specific color using the python terminal?</p>
<p>Side note: I run a version of Linux.</p> | 22,886,382 | 1 | 0 | null | 2014-04-05 20:26:58.137 UTC | 4 | 2016-04-15 17:52:12.897 UTC | 2016-04-15 17:52:12.897 UTC | null | 3,500,191 | null | 3,500,191 | null | 1 | 22 | python|terminal | 75,647 | <p>Try the <a href="https://pypi.python.org/pypi/termcolor" rel="noreferrer"><code>termcolor</code></a> module.</p>
<pre><code>from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
</code></pre>
<p>See <a href="https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python/293633#293633">Print in terminal with colors using Python?</a></p>
<p>Also, you could use ANSI codes:</p>
<pre><code>class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
print(bcolors.WARNING + "Warning" + bcolors.ENDC)
</code></pre> |
22,717,586 | Create a Web Worker from a Chrome Extension content script | <p>I'm trying to create a Web Worker from my extension's content script, but it's getting blocked by a SecurityError (same origin policy). What's the best way to do this?</p>
<p>From my content script:</p>
<pre><code>var workerURL = chrome.extension.getURL("js/searchWorker.js");
var lunrWorker = new Worker(workerURL);
</code></pre>
<p>From the manifest:</p>
<pre><code>"content_scripts": [
{
"matches": ["http://localhost:8000/*"],
"js": ["js/jquery.min.js", "js/jquery.highlight.js", "js/index.js"],
"css": ["css/bootstrap.css", "css/styles.css"]
}
]
</code></pre>
<p>I also tried setting this in my manifest, but it didn't help:</p>
<pre><code>"content_security_policy": "default-src 'none'; style-src 'self'; script-src 'self';",
</code></pre>
<p>(Sidenote: the CSS isn't being injected into the page, I'm not sure if that's a symptom of the same problem or unrelated)</p> | 22,719,772 | 1 | 0 | null | 2014-03-28 15:53:40.937 UTC | 14 | 2016-07-26 20:31:58.573 UTC | 2014-05-03 18:05:15.81 UTC | null | 446,203 | null | 446,203 | null | 1 | 14 | javascript|google-chrome-extension|web-worker | 7,052 | <p><a href="http://crbug.com/357664" rel="noreferrer">http://crbug.com/357664</a> is the bug report about not being able to load extension scripts as a web worker.</p>
<p>The workaround to this problem is to load the worker script using XMLHttpRequest, then <a href="https://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string">load the worker from a string</a>. When I faced this problem in the past, I created a wrapper that transparently modifies the <code>Worker</code> constructor, so you can use <code>new Worker(chrome.runtime.getURL('worker.js'))</code> without any problems.</p>
<p>See <a href="https://github.com/Rob--W/chrome-api/tree/master/patch-worker/patch-worker.js" rel="noreferrer"><code>patch-worker.js</code></a> (<a href="https://github.com/Rob--W/chrome-api/blob/master/patch-worker/README.md" rel="noreferrer">documentation</a>) for the implementation of the previous idea.</p>
<p><code>patch-worker.js</code> has some limitations (e.g. <code>importScripts</code> does not work as expected), mainly related to the fact that it does not run in the <code>chrome-extension:</code>-origin. To solve these problems, I created another library that uses an iframe to create the Worker. See <a href="https://github.com/Rob--W/chrome-api/tree/master/worker_proxy" rel="noreferrer"><code>worker_proxy</code></a> for the source code and documentation.</p> |
45,930,750 | How to output per-class accuracy in Keras? | <p>Caffe can not only print overall accuracy, but also per-class accuracy.</p>
<p>In Keras log, there's only overall accuracy. It's hard for me to calculate the separate class accuracy.</p>
<pre><code>Epoch 168/200
0s - loss: 0.0495 - acc: 0.9818 - val_loss: 0.0519 - val_acc: 0.9796
Epoch 169/200
0s - loss: 0.0519 - acc: 0.9796 - val_loss: 0.0496 - val_acc: 0.9815
Epoch 170/200
0s - loss: 0.0496 - acc: 0.9815 - val_loss: 0.0514 - val_acc: 0.9801
</code></pre>
<p>Anybody who knows how to output per-class accuracy in keras?</p> | 45,940,876 | 4 | 0 | null | 2017-08-29 04:35:18.7 UTC | 11 | 2022-01-24 17:00:48.843 UTC | 2021-07-19 08:18:01.75 UTC | null | 4,685,471 | null | 8,481,526 | null | 1 | 29 | python|machine-learning|keras|neural-network|conv-neural-network | 25,018 | <p>Precision & recall are more useful measures for multi-class classification (see <a href="https://en.wikipedia.org/wiki/Confusion_matrix" rel="noreferrer">definitions</a>). Following the Keras <a href="https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py" rel="noreferrer">MNIST CNN</a> example (10-class classification), you can get the per-class measures using <code>classification_report</code> from <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html#sklearn.metrics.classification_report" rel="noreferrer">sklearn.metrics</a>:</p>
<pre class="lang-python prettyprint-override"><code>from sklearn.metrics import classification_report
import numpy as np
Y_test = np.argmax(y_test, axis=1) # Convert one-hot to index
y_pred = model.predict_classes(x_test)
print(classification_report(Y_test, y_pred))
</code></pre>
<p>Here is the result:</p>
<pre class="lang-python prettyprint-override"><code> precision recall f1-score support
0 0.99 1.00 1.00 980
1 0.99 0.99 0.99 1135
2 1.00 0.99 0.99 1032
3 0.99 0.99 0.99 1010
4 0.98 1.00 0.99 982
5 0.99 0.99 0.99 892
6 1.00 0.99 0.99 958
7 0.97 1.00 0.99 1028
8 0.99 0.99 0.99 974
9 0.99 0.98 0.99 1009
avg / total 0.99 0.99 0.99 10000
</code></pre> |
29,162,278 | Benefits of JavaConfig over XML configurations in Spring? | <p>Earlier the configurations used to be in hard coded in the code, later it was externalized to .property files (for sake of avoiding hard coded values, avoiding changing code for the sake of changing configurations..etc) then it moved to XML (for sake of being more standardized, error free..etc)</p>
<p>Now, while reading about @Configuration in Spring 3 , looks like we are again moving back to the initial approach.</p>
<blockquote>
<p>Why would we want to hard-code configurations in the code rather than
having it externalized ?</p>
</blockquote> | 29,162,830 | 2 | 0 | null | 2015-03-20 08:26:10.51 UTC | 14 | 2019-12-08 13:42:08.013 UTC | null | null | null | null | 1,538,815 | null | 1 | 48 | spring|annotations|spring-3|spring-annotations | 30,106 | <p>There are some advantages</p>
<ol>
<li>Java is type safe. Compiler will report issues if you are
configuring right bean class qualifiers. </li>
<li>XML based on configuration can quickly grow big. [Yes we can split
and import but still]</li>
<li>Search is much simpler, refactoring will be bliss. Finding a bean
definition will be far easier.</li>
</ol>
<p>There are still people who like XML configuration and continue to do it. </p>
<p>References:
<a href="https://blog.codecentric.de/en/2012/07/spring-dependency-injection-styles-why-i-love-java-based-configuration/">Java configuration advantages</a>
<a href="http://java.dzone.com/articles/consider-replacing-spring-xml">Some more reasons</a></p> |
40,066,731 | Node v6 failing on object spread | <p>I had a question about why node v6.7 would be failing to run this code:</p>
<pre><code>var a = {
foo: 'bar'
}
var b = {
...a,
my: 'sharona'
}
console.log(b)
</code></pre>
<p>Anyone have an idea why that would be? I thought v6 supported object spreading..? But I guess not? Here is the error I'm seeing:</p>
<pre><code>/home/teselagen/ve/tnrtest.js:6
...a,
^^^
SyntaxError: Unexpected token ...
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:528:28)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
</code></pre> | 40,066,802 | 2 | 2 | null | 2016-10-16 04:09:48.277 UTC | 5 | 2018-06-05 03:46:34.23 UTC | null | null | null | null | 2,178,112 | null | 1 | 58 | node.js|ecmascript-6 | 36,872 | <p>Looks like ES6 spread operator only works for arrays and iterables. It is specifically designed to <strong>NOT WORK</strong> for objects: <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator" rel="noreferrer">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator</a></p>
<p>Relevant quote:</p>
<blockquote>
<p>Only apply for iterables</p>
<pre><code>var obj = {"key1":"value1"};
function myFunction(x) {
console.log(x); // undefined
}
myFunction(...obj);
var args = [...obj];
console.log(args, args.length) //[] 0
</code></pre>
</blockquote>
<p>Though the MDN article previously suggested that trying to use the spread operator on objects should result in undefined instead of throwing an error. As of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator$revision/1254317" rel="noreferrer">this revision</a>, the current MDN article discusses support for "Spread for object literals"</p>
<p>Additionally the node.js compatibility table claims node.js fully comply with the specification of the spread operator with arrays and iterables, but specifically indicates that object rest/spread properties are not supported: <a href="http://node.green/#ESNEXT-candidate--stage-3--object-rest-spread-properties" rel="noreferrer">http://node.green/#ESNEXT-candidate--stage-3--object-rest-spread-properties</a>, at least not until Node version 8.60 (at which point the color turns green to indicate that beginning in 8.3, Node <em>does</em> support the object spread/rest operator, <a href="https://stackoverflow.com/a/40066910/1175496">as pointed out in the other answer</a>)</p> |
42,802,431 | Angular 2 Load CSS background-image from assets folder | <p>My folder structure looks like</p>
<pre><code>-myapp
-assets
-home-page-img
-header-bg.jpg
-src
-app
-home-page
-home-page.component.css
-home-page.component.html
-home-page.component.ts
</code></pre>
<p>Inside my home-page.component.css, I have the following</p>
<pre><code>header {
width: 200px;
height: 200px;
background-image: url('/src/assets/home-page-img/header-bg.jpg');
}
My angular-cli.json
"assets": [
"assets",
"favicon.ico"
]
</code></pre>
<p>When I run the code, I get</p>
<pre><code>GET http://localhost:4200/src/assets/home-page-img/header-bg.jpg 404 (Not Found)
</code></pre>
<p>For demonstrating purpose, If I change background-image to the following, I get a whole different error</p>
<pre><code>background-image: url('assets/home-page-img/header-bg.jpg');
./src/app/home-page/home-page.component.css
Module not found: Error: Can't resolve './assets/home-page-img/header-bg.jpg' in '/Users/JohnSmith/Desktop/my-app/src/app/home-page'
</code></pre>
<p>How can I get that image to load?</p> | 42,803,416 | 11 | 5 | null | 2017-03-15 06:22:17.967 UTC | 13 | 2022-08-26 07:59:55.327 UTC | null | null | null | null | 7,528,750 | null | 1 | 67 | html|css|angular | 125,280 | <p>try </p>
<pre><code>background-image: url('../../assets/home-page-img/header-bg.jpg');
</code></pre> |
53,231,667 | Bundler: You must use Bundler 2 or greater with this lockfile | <p>I'm working with heroku and every time I try to push my app this message shows out:</p>
<pre><code>remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Ruby app detected
remote:
remote: !
remote: ! You must use Bundler 2 or greater with this lockfile.
remote: !
remote: /tmp/d20181109-104-g861yi/bundler-1.15.2/gems/bundler-1.15.2/lib/bundler/lockfile_parser.rb:108:in `warn_for_outdated_bundler_version': You must use Bundler 2 or greater with this lockfile. (Bundler::LockfileError)
remote: from /tmp/d20181109-104-g861yi/bundler-1.15.2/gems/bundler-1.15.2/lib/bundler/lockfile_parser.rb:95:in `initialize'
remote: from /app/tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/lib/language_pack/helpers/bundler_wrapper.rb:130:in `new'
remote: from /app/tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/lib/language_pack/helpers/bundler_wrapper.rb:130:in `block in parse_gemfile_lock'
remote: from /app/tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/lib/language_pack/instrument.rb:18:in `block (2 levels) in instrument'
remote: from /app/tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/lib/language_pack/instrument.rb:40:in `yield_with_block_depth'
remote: from /app/tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/lib/language_pack/instrument.rb:17:in `block in instrument'
remote: from /app/tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/vendor/ruby/heroku-18/lib/ruby/2.5.0/benchmark.rb:308:in `realtime'
remote: from /app/tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/lib/language_pack/instrument.rb:16:in `instrument'
remote: from /app/tmp/buildpacks/b7af5642714be4eddaa5f35e2b4c36176b839b4abcd9bfe57ee71c358d71152b4fd2cf925c5b6e6816adee359c4f0f966b663a7f8649b0729509d510091abc07/lib/language_pack/helpers/bundler_wrapper.rb:86:in `instrument'
remote: ! Push rejected, failed to compile Ruby app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to my-proyect-1234.
remote:
</code></pre>
<p>It says 'remote: ! You must use Bundler 2 or greater with this lockfile.'</p>
<blockquote>
<p>But my Bundler version is 2.0.0.pre.1</p>
</blockquote>
<p>Don't know what to do, I tried uninstalling bundle and installing it again, I errased the Gemfile.lock and typing <code>bundle</code> again</p> | 53,604,505 | 20 | 1 | null | 2018-11-09 18:46:47.223 UTC | 24 | 2022-02-16 23:31:29.05 UTC | 2019-10-12 17:21:39.503 UTC | null | 10,907,864 | null | 7,680,956 | null | 1 | 119 | ruby-on-rails|heroku|ruby-on-rails-5|heroku-cli | 126,654 | <p>I deleted the project and made a git clone from the Heroku app, don´t know if it is a good solution, but it worked for me.</p> |
30,625,280 | How to create a simple divider in the new NavigationView? | <p>Google introduced the <code>NavigationView</code> in the Design Support Library version 22.2.0 with which you can create a drawer very easily using a menu resource.</p>
<p>How can I create a simple divider line between two items? Grouping the items didn't work. Creating a sub items section does create a divider line, but it requires a title, which I don't want.</p>
<p>Any help would be appreciated.</p> | 30,625,471 | 14 | 1 | null | 2015-06-03 16:06:20.943 UTC | 41 | 2021-01-26 01:35:28.84 UTC | 2015-06-19 12:47:27.61 UTC | null | 4,626,831 | null | 2,968,428 | null | 1 | 163 | android|navigation-drawer|android-support-library|android-design-library|navigationview | 102,622 | <p>All you need to do is define a <code>group</code> with an <strong>unique ID</strong>, I have checked the implementation if group has different id's it will create a divider.</p>
<h2>Example menu, creating the separator:</h2>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<group android:id="@+id/grp1" android:checkableBehavior="single" >
<item
android:id="@+id/navigation_item_1"
android:checked="true"
android:icon="@drawable/ic_home"
android:title="@string/navigation_item_1" />
</group>
<group android:id="@+id/grp2" android:checkableBehavior="single" >
<item
android:id="@+id/navigation_item_2"
android:icon="@drawable/ic_home"
android:title="@string/navigation_item_2" />
</group>
</menu>
</code></pre> |
29,681,906 | Python: Pandas dataframe from Series of dict | <p>I have a Pandas dataframe:</p>
<pre><code>type(original)
pandas.core.frame.DataFrame
</code></pre>
<p>which includes the series object <code>original['user']</code>:</p>
<pre><code>type(original['user'])
pandas.core.series.Series
</code></pre>
<p><code>original['user']</code> points to a number of dicts:</p>
<pre><code>type(original['user'].ix[0])
dict
</code></pre>
<p>Each dict has the same keys:</p>
<pre><code>original['user'].ix[0].keys()
[u'follow_request_sent',
u'profile_use_background_image',
u'profile_text_color',
u'id',
u'verified',
u'profile_location',
# ... keys removed for brevity
]
</code></pre>
<p>Above is (part of) one of the dicts of <code>user</code> fields in a tweet from <a href="https://dev.twitter.com/rest" rel="noreferrer">tweeter API</a>. I want to build a data frame from these dicts.</p>
<p>When I try to make a data frame directly, I get only one column for each row and this column contains the whole dict:</p>
<pre><code>pd.DataFrame(original['user'][:2])
user
0 {u'follow_request_sent': False, u'profile_use_...
1 {u'follow_request_sent': False, u'profile_use_..
</code></pre>
<p>When I try to create a data frame using from_dict() I get the same result:</p>
<pre><code>pd.DataFrame.from_dict(original['user'][:2])
user
0 {u'follow_request_sent': False, u'profile_use_...
1 {u'follow_request_sent': False, u'profile_use_..
</code></pre>
<p>Next I tried a list comprehension which returned an error:</p>
<pre><code>item = [[k, v] for (k,v) in users]
ValueError: too many values to unpack
</code></pre>
<p>When I create a data frame from a single row, it nearly works:</p>
<pre><code>df = pd.DataFrame.from_dict(original['user'].ix[0])
df.reset_index()
index contributors_enabled created_at default_profile default_profile_image description entities favourites_count follow_request_sent followers_count following friends_count geo_enabled id id_str is_translation_enabled is_translator lang listed_count location name notifications profile_background_color profile_background_image_url profile_background_image_url_https profile_background_tile profile_image_url profile_image_url_https profile_link_color profile_location profile_sidebar_border_color profile_sidebar_fill_color profile_text_color profile_use_background_image protected screen_name statuses_count time_zone url utc_offset verified
0 description False Mon May 26 11:58:40 +0000 2014 True False {u'urls': []} 0 False 157
</code></pre>
<p>It works almost like I want it to, except it sets the <code>description</code> field as the default index.</p>
<p>Each of the dicts has 40 keys but I only need about 10 of them and I have 28734 rows in data frame.</p>
<p>How can I filter out the keys which I do not need?</p> | 29,685,357 | 3 | 2 | null | 2015-04-16 17:26:41.993 UTC | 6 | 2022-02-23 00:18:42.26 UTC | 2017-02-08 15:21:23.213 UTC | null | 6,079,108 | null | 3,153,869 | null | 1 | 38 | python|pandas|dataframe | 21,397 | <p>what I would try to do is the following:</p>
<pre><code>new_df = pd.DataFrame(list(original['user']))
</code></pre>
<p>this will convert the series to list then pass it to pandas dataframe and it should take care of the rest.</p> |
4,093,611 | Request method 'POST' not supported | <p>According to the Spring Documentation <a href="http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/" rel="noreferrer">here</a>:</p>
<blockquote>
<p>While HTTP defines these four methods, HTML only supports two: GET and POST. Fortunately, there are two possible workarounds: you can either use JavaScript to do your PUT or DELETE, or simply do a POST with the 'real' method as an additional parameter (modeled as a hidden input field in an HTML form).</p>
</blockquote>
<p>They have done the latter, and can be achieved with the following spring MVC form tag:</p>
<pre><code><form:form method="delete">
<input type="submit" value="Delete"/>
</form:form>
</code></pre>
<p>The problem is when i click 'Delete' my page throws the following error:</p>
<pre><code>HTTP Status 405 - Request method 'POST' not supported
</code></pre>
<p>I changed the debug level of <code>org.springframework.web</code> to debug and found the following message:</p>
<pre><code>DEBUG AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [foo.bar.MessageForm@da9246]:
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
</code></pre>
<p>I used <a href="https://addons.mozilla.org/en-US/firefox/addon/9780/" rel="noreferrer">RestClient</a> with DELETE method and the method is called as expected. What am I doing wrong here?</p> | 4,093,704 | 1 | 3 | null | 2010-11-04 03:17:53.75 UTC | 2 | 2015-02-24 20:56:10.45 UTC | null | null | null | null | 392,222 | null | 1 | 8 | java|spring-mvc|url-rewriting | 46,969 | <p>You need to configure HiddenHttpMethodFilter in your web.xml </p>
<p>Details can be found <a href="http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/" rel="noreferrer">here</a>:</p> |
6,613,746 | text on left and right side of element | <p>Using CSS what is the best way to have text on both the right and the left side of an element and be in the same spot vertically?</p>
<p>Thus ending up with the following layout:<br/>
<img src="https://i.stack.imgur.com/Rvc7F.png" alt="enter image description here"></p>
<p>The container has a fixed width, so I don't want to use positioning, because I know I don't have to.</p> | 6,613,776 | 2 | 0 | null | 2011-07-07 16:15:35.223 UTC | 3 | 2014-01-12 17:43:41.13 UTC | null | null | null | null | 552,067 | null | 1 | 17 | html|css|text | 49,068 | <p>(1) Add two divs within the element that contain each text string</p>
<pre><code><div>
<div class="div1">Left Text</div>
<div class="div2">Right Text</div>
</div>
</code></pre>
<p>(2) Float the two divs next to each other</p>
<pre><code>.div1 {
float: left;
}
.div2 {
float:right;
}
</code></pre>
<p>(3) Set the text-align properties for the right div (this will ensure that the text is pushed all the way to the right as in your example).</p>
<pre><code>.div2 {
float:right;
text-align: right;
}
</code></pre> |
7,611,081 | Can I access the skipped "parent" of SelectMany when using dotted syntax in Linq? | <p>In query syntax I can write </p>
<pre><code>var greendoorsWithRooms = from room in house.roooms
from door in room.doors
where door.Color = green
select new {d=door,r=room}
</code></pre>
<p>Is there a way I could achieve the same with dotted syntax?</p>
<pre><code>var greendoorsWithRooms = house.rooms.SelectMany(room=>room.Doors)
.Where(door=>door.Color==green)
.Select(door=>new{ <room is not in scope> }
</code></pre>
<p>I am teaching some non-programmers to use LINQPad against a proprietary object model so that we don't have to create GUI around every odd case. It would be beneficial if they didn't have to learn query syntax. Presently, I've supplied snippets solving this using foreach, but the question still comes up once in a while.</p> | 7,611,501 | 3 | 0 | null | 2011-09-30 13:28:30.61 UTC | 2 | 2021-05-06 18:10:52.37 UTC | 2016-11-01 10:40:34.587 UTC | null | 80,577 | null | 80,577 | null | 1 | 33 | c#|linq | 10,513 | <p>This is also possible:</p>
<pre><code>house.rooms.SelectMany(room => room.Doors.Where(door => door.Color == green),
(room, door) => new { r = room, d = door })
</code></pre>
<p>It's <a href="http://msdn.microsoft.com/en-us/library/bb534631.aspx" rel="noreferrer">this</a> overload of <code>SelectMany</code>.</p> |
7,442,310 | Adding elements to JList in Swing Java | <p>I have a function that executes when a button is clicked. Suppose there is a loop to add 1 to 10 to a <code>JList</code>. I add that data to <code>DefaultListModel</code>. It works perfectly and the numbers get added. Then I added a <code>Thread.sleep(1000)</code> within the loop. But the output is different. I wanted to add 1 element every second. But now it waits for 10secs and the add all 1 to 10 together at the end of 10th second. Am I wrong anywhere?</p>
<pre><code>List processList = listNumbers.getSelectedValuesList();
DefaultListModel resultList = new DefaultListModel();
listResult.setModel(resultList);
for (int i = 0; i < processList.size(); i++) {
resultList.addElement(String.valueOf(i));
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
}
}
</code></pre> | 7,442,516 | 4 | 0 | null | 2011-09-16 08:56:50.063 UTC | 2 | 2013-10-31 15:02:49.42 UTC | 2011-09-16 09:06:51.87 UTC | null | 440,621 | null | 440,621 | null | 1 | 10 | java|swing|jlist | 51,132 | <p>You should update your list in a separate thread otherwise you end up blocking the event dispatch thread.</p>
<p>Try the following:</p>
<pre><code>final DefaultListModel model = new DefaultListModel();
final JList list = new JList(model);
//another thread to update the model
final Thread updater = new Thread() {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
for (int i = 0; i < 10; i++) {
model.addElement(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
updater.start();
</code></pre> |
21,916,615 | Horizontal timeline in pure css | <p>I'm trying to make a timeline in pure CSS however I seem to be running into some problems.</p>
<p>When I try to set the timeline div as overflow-x: scroll it still scrolls on the y access.</p>
<p>This is what I've got: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#timeline {
height: 500px;
width: auto;
margin: 0;
background: red;
}
.event {
height: 500px;
}
.founded {
width: 400px;
float: left;
background: blue;
}
.grant {
width: 800px;
background: yellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol id="timeline">
<li class="event founded"></li>
<li class="event grant"></li>
</ol></code></pre>
</div>
</div>
</p>
<p>I just want each additional entry to follow the previous one and for it all be scroll-able horizontally. If anyone could point me in the right direction that would be amazing. </p>
<p>Thanks.</p> | 21,920,076 | 2 | 2 | null | 2014-02-20 18:36:20.293 UTC | 3 | 2020-01-05 12:25:03.57 UTC | 2020-01-05 12:25:03.57 UTC | null | 896,358 | null | 2,933,987 | null | 1 | 7 | html|css | 42,426 | <p>I literally JUST had to make one of these. This is what I came up with:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
padding: 25px;
font-family: sans-serif;
}
.timeline {
white-space: nowrap;
overflow-x: scroll;
padding: 30px 0 10px 0;
position: relative;
}
.entry {
display: inline-block;
vertical-align: top;
background: #13519C;
color: #fff;
padding: 10px;
font-size: 12px;
text-align: center;
position: relative;
border-top: 4px solid #06182E;
border-radius: 3px;
min-width: 200px;
max-width: 500px;
}
.entry img {
display: block;
max-width: 100%;
height: auto;
margin-bottom: 10px;
}
.entry:after {
content: '';
display: block;
background: #eee;
width: 7px;
height: 7px;
border-radius: 6px;
border: 3px solid #06182E;
position: absolute;
left: 50%;
top: -30px;
margin-left: -6px;
}
.entry:before {
content: '';
display: block;
background: #06182E;
width: 5px;
height: 20px;
position: absolute;
left: 50%;
top: -20px;
margin-left: -2px;
}
.entry h1 {
color: #fff;
font-size: 18px;
font-family: Georgia, serif;
font-weight: bold;
margin-bottom: 10px;
}
.entry h2 {
letter-spacing: .2em;
margin-bottom: 10px;
font-size: 14px;
}
.bar {
height: 4px;
background: #eee;
width: 100%;
position: relative;
top: 13px;
left: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bar"></div>
<div class="timeline">
<div class="entry">
<h1>1990</h1>
<h2>Entry Title</h2>
<img src="http://dummyimage.com/300x200/000/fff" /> Here's the info about this date
</div>
<div class="entry">
<h1>1995</h1>
Here's the info about this date
</div>
<div class="entry">
<h1>2000</h1>
Here's the info about this date
</div>
<div class="entry">
<h1>2005</h1>
Here's the info about this date
</div>
<div class="entry">
<h1>2010</h1>
Here's the info about this date
</div>
</div></code></pre>
</div>
</div>
</p> |
1,389,881 | Transaction in REST WCF service | <p>We are having a REST WCF service.
we want the save operation on this REST service to be in transaction.
Is there a way to pass Transaction object over the wire to REST WCF service?</p> | 1,390,393 | 4 | 0 | null | 2009-09-07 15:26:59.447 UTC | 9 | 2013-11-12 13:11:08.203 UTC | 2009-09-07 18:00:15.25 UTC | null | 6,819 | null | 164,125 | null | 1 | 11 | wcf|rest|transactions|wcf-rest | 5,934 | <p>Here is a quote from Roy Fielding, the guy who invented the term REST</p>
<blockquote>
<p>If you find yourself in need of a
distributed transaction protocol, then
how can you possibly say that your
architecture is based on REST? I
simply cannot see how you can get from
one situation (of using RESTful
application state on the client and
hypermedia to determine all state
transitions) to the next situation of
needing distributed agreement of
transaction semantics wherein the
client has to tell the server how to
manage its own resources.</p>
<p>...for now I consider "rest transaction"
to be an oxymoron.</p>
</blockquote>
<p>This is from a <a href="http://tech.groups.yahoo.com/group/rest-discuss/message/12837" rel="noreferrer">message</a> on the REST-discuss list from June 9th, 2009.</p> |
1,550,878 | Nearest-neighbor interpolation algorithm in MATLAB | <p>I am trying to write my own function for scaling up an input image by using the Nearest-neighbor interpolation algorithm. The bad part is I am able to see how it works but cannot find the algorithm itself. I will be grateful for any help.</p>
<p>Here's what I tried for scaling up the input image by a factor of 2:</p>
<pre><code>function output = nearest(input)
[x,y]=size(input);
output = repmat(uint8(0),x*2,y*2);
[newwidth,newheight]=size(output);
for i=1:y
for j=1:x
xloc = round ((j * (newwidth+1)) / (x+1));
yloc = round ((i * (newheight+1)) / (y+1));
output(xloc,yloc) = input(j,i);
end
end
</code></pre>
<p>Here is the output after <a href="https://stackoverflow.com/users/5987/mark-ransom">Mark</a>'s suggestion <img src="https://i.stack.imgur.com/KnNpF.png" alt="alt text"></p> | 1,551,208 | 4 | 1 | null | 2009-10-11 14:53:56.083 UTC | 11 | 2017-02-27 20:02:09.69 UTC | 2017-05-23 12:32:31.727 UTC | null | -1 | null | 151,937 | null | 1 | 20 | matlab|image-processing|interpolation|nearest-neighbor|resize-image | 59,178 | <p>A while back I went through the code of the <a href="http://www.mathworks.com/help/images/ref/imresize.html" rel="nofollow noreferrer"><code>imresize</code></a> function in the <a href="https://www.mathworks.com/products/image.html" rel="nofollow noreferrer">MATLAB Image Processing Toolbox</a> to create a simplified version for just nearest neighbor interpolation of images. Here's how it would be applied to your problem:</p>
<pre><code>%# Initializations:
scale = [2 2]; %# The resolution scale factors: [rows columns]
oldSize = size(inputImage); %# Get the size of your image
newSize = max(floor(scale.*oldSize(1:2)),1); %# Compute the new image size
%# Compute an upsampled set of indices:
rowIndex = min(round(((1:newSize(1))-0.5)./scale(1)+0.5),oldSize(1));
colIndex = min(round(((1:newSize(2))-0.5)./scale(2)+0.5),oldSize(2));
%# Index old image to get new image:
outputImage = inputImage(rowIndex,colIndex,:);
</code></pre>
<p>Another option would be to use the built-in <a href="http://www.mathworks.com/help/matlab/ref/interp2.html" rel="nofollow noreferrer"><code>interp2</code></a> function, although you mentioned not wanting to use built-in functions in one of your comments.</p>
<p><strong>EDIT: EXPLANATION</strong></p>
<p>In case anyone is interested, I thought I'd explain how the solution above works...</p>
<pre><code>newSize = max(floor(scale.*oldSize(1:2)),1);
</code></pre>
<p>First, to get the new row and column sizes the old row and column sizes are multiplied by the scale factor. This result is rounded down to the nearest integer with <a href="http://www.mathworks.com/help/matlab/ref/floor.html" rel="nofollow noreferrer"><code>floor</code></a>. If the scale factor is less than 1 you could end up with a weird case of one of the size values being 0, which is why the call to <a href="http://www.mathworks.com/help/matlab/ref/max.html" rel="nofollow noreferrer"><code>max</code></a> is there to replace anything less than 1 with 1.</p>
<pre><code>rowIndex = min(round(((1:newSize(1))-0.5)./scale(1)+0.5),oldSize(1));
colIndex = min(round(((1:newSize(2))-0.5)./scale(2)+0.5),oldSize(2));
</code></pre>
<p>Next, a new set of indices is computed for both the rows and columns. First, a set of indices for the upsampled image is computed: <code>1:newSize(...)</code>. Each image pixel is considered as having a given width, such that pixel 1 spans from 0 to 1, pixel 2 spans from 1 to 2, etc.. The "coordinate" of the pixel is thus treated as the center, which is why 0.5 is subtracted from the indices. These coordinates are then divided by the scale factor to give a set of pixel-center coordinates for the original image, which then have 0.5 added to them and are rounded off to get a set of integer indices for the original image. The call to <a href="http://www.mathworks.com/help/matlab/ref/min.html" rel="nofollow noreferrer"><code>min</code></a> ensures that none of these indices are larger than the original image size <code>oldSize(...)</code>.</p>
<pre><code>outputImage = inputImage(rowIndex,colIndex,:);
</code></pre>
<p>Finally, the new upsampled image is created by simply indexing into the original image.</p> |
49,579,282 | Can't find module cPickle using Python 3.5 and Anaconda | <p>I am trying to use cPickle on a windows box, using Anaconda. I am using python 3.5. I am not using a virtualenv (though probably should be).</p>
<p>When I try to import cPickle I get <em>"ImportError: No module named 'cPickle'"</em></p>
<pre><code>Python 3.5.0 |Anaconda custom (64-bit)| (default, Dec 1 2015, 11:46:22) [MSC v.
1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cPickle
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'cPickle'
</code></pre>
<p>My understanding is that cPickle comes built in with Python 3.5, so I can't understand why cPickle is not found. Any idea what has gone wrong/how I can clean things up/how to troubleshoot the issue.</p> | 49,579,373 | 2 | 3 | null | 2018-03-30 18:09:09.883 UTC | 3 | 2021-09-28 19:51:10.88 UTC | null | null | null | null | 8,283,463 | null | 1 | 50 | python|anaconda|pickle|versioning | 73,698 | <p>There is no <code>cPickle</code> in Python 3. Just import <code>pickle</code>. <code>pickle</code> will automatically use the C accelerator.</p> |
10,714,911 | AlertDialog's items not displayed | <p>I create an <code>AlertDialog</code> with an <code>AlertDialog.Builder</code> and set some items with <code>setItems()</code>. The dialog is shown but I cannot see any of the items. All I see is the message.</p>
<pre><code>final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
dialogBuilder.setMessage("Pick a color");
dialogBuilder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do anything you want here
}
});
dialogBuilder.create().show();
</code></pre>
<p>If I set the <code>PositiveButton</code>, I can see that button just fine. I also tried setting <code>MultiChoiceItems</code> and <code>SingleChoiceItems</code> but neither of these work either.</p> | 10,715,081 | 7 | 2 | null | 2012-05-23 06:55:24.077 UTC | 12 | 2020-05-05 11:49:29.503 UTC | 2017-04-13 19:25:30.63 UTC | null | 3,711,928 | null | 1,411,864 | null | 1 | 53 | android|android-alertdialog | 21,734 | <p>Use <code>setTitle</code> instead of <code>setMessage</code> which sets message body and overrides the items list.</p> |
Subsets and Splits