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
55,079,070
How to accept &str, String and &String in a single function?
<p>I want to write a single function, that accepts a <code>&amp;str</code>, a <code>String</code> and a borrowed <code>&amp;String</code>. I've written the following 2 functions:</p> <pre><code>fn accept_str_and_ref_string(value: &amp;str) { println!("value: {}", value); } fn accept_str_and_string&lt;S: Into&lt;String&gt;&gt;(value: S) { let string_value: String = value.into(); println!("string_value: {}", string_value); } fn main() { let str_foo = "foo"; let string_foo = String::from("foo"); accept_str_and_ref_string(str_foo); accept_str_and_ref_string(&amp;string_foo); accept_str_and_string(str_foo); accept_str_and_string(string_foo); } </code></pre> <p>Is it possible to implement one function so that I can do this:</p> <pre><code>accept_all_strings(str_foo); accept_all_strings(&amp;string_foo); accept_all_strings(string_foo); </code></pre>
55,079,159
2
2
null
2019-03-09 15:50:08.217 UTC
8
2022-08-30 20:37:51.477 UTC
2020-05-19 19:20:05.357 UTC
null
155,423
null
5,228,853
null
1
31
string|rust|borrowing
7,651
<p>You can use the <a href="https://doc.rust-lang.org/std/convert/trait.AsRef.html" rel="noreferrer"><code>AsRef&lt;str&gt;</code></a> trait:</p> <pre><code>// will accept any object that implements AsRef&lt;str&gt; fn print&lt;S: AsRef&lt;str&gt;&gt;(stringlike: S) { // call as_ref() to get a &amp;str let str_ref = stringlike.as_ref(); println!("got: {:?}", str_ref) } fn main() { let a: &amp;str = "str"; let b: String = String::from("String"); let c: &amp;String = &amp;b; print(a); print(c); print(b); } </code></pre> <p>The <code>print</code> function will support any type that implements <code>AsRef&lt;str&gt;</code>, which includes <code>&amp;str</code>, <code>String</code> and <code>&amp;String</code>.</p>
55,031,823
How to make Puppeteer work with a ReactJS application on the client-side
<p>I am fairly new to React and I am developing an app which will take actual screenshots of a web page and the app can draw and add doodles on top of the screenshot taken. I initially used html2canvas and domToImage to take client-side screenshots but it doesn't render the image exactly as it is shown in the web page.</p> <p>Reddit user /pamblam0 suggested I look into Google's Puppeteer. How it works is that it launches a headless chromium browser which goes to my react app on localhost then gets a screenshot of that whole page easily. My problem however, is that puppeteer doesn't play nice inside a react app. It gives me a ws error which, as explained on a google search can be fixed by simply installing ws (which doesn't work by the way).</p> <p>What happens now my puppeteer script works out my react app. From what I understand it doesn't work with client side app (I might be wrong). What I want to happen is that whenever I click the button from my react app, puppeteer should execute and return a base64 string which will then be passed to a component in my react app.</p> <p>Here is what I've done so far.</p> <p><strong>puppeteerApp.js</strong></p> <pre><code>const puppeteer = require('puppeteer'); const takeScreenshot = async () =&gt; { puppeteer.launch().then(async browser =&gt; { const page = await browser.newPage(); const options = { path: 'saved_images/webshot.png', encoding: 'base64' } await page.goto('http://localhost:3000/', { waitUntil: 'networkidle2' }); const elem = await page.$('iframe').then(async (iframe) =&gt; { return await iframe.screenshot(options) }); await browser.close() }); } takeScreenshot(); </code></pre> <p>Code from react app. <strong>App.js</strong></p> <pre><code>import React, { Component } from 'react'; import ScreenshotsContainer from './containers/ScreenshotsContainer/ScreenshotsContainer' import ImageContainer from './containers/ImageContainer/ImageContainer'; import html2canvas from 'html2canvas'; import domtoimage from 'dom-to-image'; import Button from './components/UI/Button/Button' import classes from './App.module.css'; import { CSSTransition } from 'react-transition-group' import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; class App extends Component { constructor(props) { super(props); this.state = { imgURIArray: [], img: null, showImageContainer: false, showScreenshotContainer: false, selectedImageURI: null, showSaveAnimation: false, showNotify: false } } storeImageToArrayHandler = (imgURI) =&gt; { if (imgURI !== "") { this.setState({ imgURIArray: [...this.state.imgURIArray, imgURI] }, () =&gt; { this.setState({ showImageContainer: !this.state.showImageContainer }) }) } } getScreenshotHandler = () =&gt; { //use puppeteer here!!! } getSelectedImageFromContainerHandler(selectedImageURI) { this.setState({ selectedImageURI: selectedImageURI, showImageContainer: !this.state.showImageContainer }) } showImageContainerHandler(showImageContainer) { this.setState({ showImageContainer: showImageContainer }) } showScreenshotContainerHandler = () =&gt; { this.setState({ showScreenshotContainer: !this.state.showScreenshotContainer }) } notify = (submitSuccessful, msg) =&gt; { let message = msg ? msg : "" submitSuccessful ? toast.success(message, { autoClose: 3000, position: toast.POSITION.TOP_CENTER }) : toast.error(message, { position: toast.POSITION.TOP_CENTER }); } render() { let buttonOps = ( &lt;CSSTransition in={!this.state.showScreenshotContainer} appear={true} timeout={300} classNames="fade" &gt; &lt;div className={classes.optionButtons}&gt; &lt;Button icon={"fas fa-camera"} type={"button-success"} gridClass={""} buttonName={""} style={{ width: "100%", height: "70px" }} onClick={() =&gt; this.getScreenshotHandler} /&gt; &lt;Button icon={"fas fa-images"} type={"button-primary "} gridClass={""} buttonName={""} style={{ width: "100%", height: "70px" }} onClick={() =&gt; this.showScreenshotContainerHandler} /&gt; &lt;/div&gt; &lt;/CSSTransition&gt; ) return ( &lt;div&gt; { this.state.showImageContainer ? &lt;div&gt; &lt;ImageContainer img={this.state.img} showImageContainer={showImageContainer =&gt; this.showImageContainerHandler(showImageContainer)} storeImageToArrayHandler={imgURI =&gt; this.storeImageToArrayHandler(imgURI)} notify={(submitSuccessful, msg) =&gt; this.notify(submitSuccessful, msg)} /&gt; &lt;/div&gt; : null } &lt;CSSTransition in={this.state.showScreenshotContainer} appear={true} timeout={300} classNames="slide" unmountOnExit onExited={() =&gt; { this.setState({ showScreenshotContainer: false }) }} &gt; &lt;ScreenshotsContainer imgURIArray={this.state.imgURIArray} getSelectedImageFromContainerHandler={imgURI =&gt; this.getSelectedImageFromContainerHandler(imgURI)} showScreenshotContainerHandler={() =&gt; this.showScreenshotContainerHandler} notify={(submitSuccessful, msg) =&gt; this.notify(submitSuccessful, msg)} /&gt; &lt;/CSSTransition&gt; {this.state.showImageContainer ? null : buttonOps} {/* &lt;button onClick={this.notify}&gt;Notify !&lt;/button&gt; */} &lt;ToastContainer /&gt; &lt;/div &gt; ); } } export default App; </code></pre> <p>Any help would be appreciated. Thanks!</p>
55,049,611
1
2
null
2019-03-06 20:41:51.65 UTC
9
2019-05-01 09:29:49.097 UTC
2019-04-06 14:21:38.977 UTC
null
5,627,599
null
9,372,558
null
1
26
javascript|node.js|reactjs|puppeteer
28,395
<p>Your React.js application runs on the client-side (in the browser). Puppeteer cannot run inside that environment as you cannot start a full browser inside the browser.</p> <p>What you need is a server which does that for you. You could ether offer a HTTP endpoint (option 1) or expose your puppeteer Websocket (option 2):</p> <h2>Option 1: Provide a HTTP endpoint</h2> <p>For this option, you setup a server which handles the incoming request and runs the task (making a screenshot) for you:</p> <p><strong>server.js</strong></p> <pre class="lang-js prettyprint-override"><code>const puppeteer = require('puppeteer'); const express = require('express'); const app = express(); app.get('/screenshot', async (req, res) =&gt; { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(req.query.url); // URL is given by the "user" (your client-side application) const screenshotBuffer = await page.screenshot(); // Respond with the image res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': screenshotBuffer.length }); res.end(screenshotBuffer); await browser.close(); }) app.listen(4000); </code></pre> <p>Start the application with <code>node server.js</code> and you can now pass the URL to your server and get a screenshot back from your server: <code>http://localhost:4000/screenshot?url=https://example.com/</code></p> <p>The response from the server could then be used as as the source of an image element in your application.</p> <h2>Option 2: Exposing the puppeteer Websocket to the client</h2> <p>You could also control the browser (which runs on the server) from the client-side by by exposing the Websocket.</p> <p>For that you need to expose the Websocket of your server like this: </p> <p><strong>server.js</strong></p> <pre class="lang-js prettyprint-override"><code>const puppeteer = require('puppeteer'); (async () =&gt; { const browser = await puppeteer.launch(); const browserWSEndpoint = browser.wsEndpoint(); browser.disconnect(); // Disconnect from the browser, but don't close it console.log(browserWSEndpoint); // Communicate the Websocket URL to the client-side // example output: ws://127.0.0.1:55620/devtools/browser/e62ec4c8-1f05-42a1-86ce-7b8dd3403f91 })(); </code></pre> <p>Now you can control the browser (running on the server) form the client-side with a <a href="https://github.com/GoogleChrome/puppeteer/tree/master/utils/browser" rel="noreferrer">puppeteer bundle</a> for the client. In this scenario you could now connect to the browser via <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerconnectoptions" rel="noreferrer">puppeteer.connect</a> and make a screenshot that way.</p> <p>I would strongly recommend using option 1, as in option 2 you are fully exposing your running browser to the client. Even with option 1, you still need to handle user input validation, timeouts, navigation errors, etc.</p>
19,966,065
Angularjs - disabling AND unchecking a checked box
<p>I have a complex set of checkboxes in groups filled with data from multidimensional arrays and there are some specific things that need to happen with them... I extracted the minimum of what I need so I will try to explain</p> <p>In this fiddle </p> <p><a href="http://jsfiddle.net/EVZUV/" rel="noreferrer">http://jsfiddle.net/EVZUV/</a></p> <p>the first checkbox is enabled and the second is disabled. When the first checkbox is checked the second becomes enabled. What I am trying to get is to UNCHECK the second box if it is becomes disabled again when the first checkbox is unchecked.</p> <p>Here is the code I have that almost works</p> <pre><code>&lt;input type="checkbox" ng-model="disablelist" ng-click="checkitems"&gt;Check this box to enable the other.. &lt;br&gt;&lt;br&gt; &lt;input type="checkbox" ng-disabled="!disablelist" ng-checked="checkitems"&gt;When this checkbox is disabled it also must get unchecked </code></pre> <p>I am just getting intong-js and some ideas are pretty "whaaa .." to me,, but it looks good so I am persisting for now.</p> <p>Thanks!!</p>
19,966,219
2
0
null
2013-11-13 22:46:55.423 UTC
1
2014-03-28 21:41:25.9 UTC
null
null
null
null
1,743,071
null
1
11
javascript|angularjs|checkbox
40,048
<p>Simple solution here: <a href="http://jsfiddle.net/7mKtF/2/">http://jsfiddle.net/7mKtF/2/</a></p> <p>HTML:</p> <pre><code>&lt;div ng-app="myApp"&gt; &lt;input type="checkbox" ng-model="disablelist"&gt;Check this box to enable the other.. &lt;br&gt;&lt;br&gt; &lt;input type="checkbox" ng-disabled="!disablelist" ng-checked="disablelist &amp;&amp; 0"&gt;When this checkbox is disabled it also must get unchecked &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>var app = angular.module('myApp', []); </code></pre> <p>Basically, I've updated your <code>ng-checked</code> statement to include the <code>disablelist</code> property. Using boolean logic, the second checkbox will evaluate to false if <code>disablelist</code> is false.</p> <p>EDIT:</p> <p>Also worth noting that the way you currently have it, your <code>ng-click</code> binding actually doesn't do anything. You would want to use <code>ng-click</code> to call a function variable, using argument parentheses.</p>
20,059,000
Where are .NET 4.0 MemoryCache performance counters?
<p>Where are .NET 4.0 MemoryCache performance counters?</p> <p>I am looking for their name and I can't find any.</p> <p>Thank you,</p>
20,059,960
1
0
null
2013-11-18 22:09:08.753 UTC
11
2014-06-01 14:50:23.147 UTC
null
null
null
null
1,088,979
null
1
32
c#|.net|caching|.net-4.0|memorycache
7,567
<p>That's a loaded question with a very long answer. I doubt it is going to be helpful, let's talk about the <em>real</em> problem you are trying to solve. Those performance counters have to be registered first before you can see them.</p> <p>Start an elevated console prompt (right-click the shortcut and use Run as Administrator) and type these commands:</p> <pre><code>cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 lodctr netmemorycache.ini </code></pre> <p>That adds the required registry entries so the MemoryCache can create these counters at runtime. Start your program so an instance of MemoryCache is created. Run Perfmon.exe, right-click the graph, Add Counters and pick from the added ".NET Memory Cache 4.0" category. Also select the instance of your program.</p>
5,616,089
GET variables with spaces - they work, but is it correct or ok?
<p>I have a PHP page where I'm passing the city name via a "city" URL/GET variable. Currently, it's passing the actual city name even if it has spaces (eg <code>.php?city=New York</code>). I then take the $city GET variable and run a MySQL query against cities.name.</p> <p>This works just fine - but I've always been under the impression any variables, URL/GET or otherwise should never have spaces. I'm more than capable of either replacing the spaces w/ underscores, or removing them, and putting them back in for the query...etc - but I thought I'd ask first in case spaces are completely fine, and it was just my superstition telling me otherwise.</p>
5,616,107
3
0
null
2011-04-11 01:57:32.89 UTC
3
2017-11-26 05:26:13.887 UTC
2016-03-01 08:47:03.57 UTC
null
31,671
null
673,664
null
1
15
php|variables
38,651
<p>Spaces are fine, and are generally encoded with <code>+</code>.</p> <p>To be extra safe, use <code>urlencode()</code> on your values if manually adding them to your GET params.</p> <pre><code>echo urlencode('New York'); // New+York </code></pre> <p><a href="http://codepad.org/WO3vUUOD">CodePad</a>.</p> <p>Otherwise, if your form if submitting as GET params, just leave them as they are :)</p> <blockquote> <p>I then take the $city GET variable and run a MySQL query against cities.name.</p> </blockquote> <p>Make sure you are using the suitable database escaping mechanism to be safe from SQL injection.</p>
6,102,297
How do I clean up my Github fork so I can make clean pull requests?
<p>I forked a repository on Github. I've made some minor changes and submitted pull requests to the upstream, but along the way my fork has become so mangled I'm unable to generate clean pull requests; when I start a pull request from a branch with six changes, Github wants to submit thirteen, with seven of them already existing upstream (natch). </p> <p>My problem seems to be related to <a href="https://stackoverflow.com/q/5561161/306084">only pulling the latest commits</a>, but when I create a new branch and cherry-pick commits I still have extras. I've futzed with <a href="https://stackoverflow.com/q/3867284/306084">rebasing</a> as well, but now it looks like even <a href="https://github.com/pjmorse/sproutguides" rel="noreferrer">my master</a> is so messed up I can't generate a clean copy of <a href="https://github.com/sproutcore/sproutguides" rel="noreferrer">upstream</a>. This is apparently because I didn't understand that I needed to <a href="https://stackoverflow.com/questions/5968964/avoid-unwanted-merge-commits-and-other-commits-when-doing-pull-request-in-github/5969100#5969100">rebase instead of merging</a>, so clearly I've made mistakes; what I'm trying to do is figure out how to unsnarl that knot and get back to a clean state where I can move forward usefully.</p> <p>I kind of want to blow away my fork and make a new fork of the upstream, but I gather that, too, is difficult. </p> <p>Having confessed my Git sins, how do I obtain github absolution?</p>
6,103,022
3
2
null
2011-05-23 19:57:33.267 UTC
53
2018-09-27 22:34:59.917 UTC
2017-05-23 11:33:13.66 UTC
null
-1
null
306,084
null
1
84
git|github
22,494
<p><strong>Step 1: Pull upstream changes</strong><br> It's recommended to add the upstream repo as "upstream" as explained on the <a href="http://help.github.com/fork-a-repo/" rel="noreferrer">Fork a Repo</a> page:</p> <pre><code>git pull --rebase upstream master </code></pre> <p>The <code>--rebase</code> option places your changes on top of the latest commit without merges.</p> <p><strong>Step 2: (Optional) Merge your commits into 1 commit</strong></p> <pre><code>git reset --soft upstream/master </code></pre> <p>This command will "undo" all your commits, but won't change the files. So you can commit all your changes in a single commit.</p> <pre><code>git commit -a </code></pre> <p><strong>Step 3: Check &amp; test your changes</strong></p> <p>To show the changes use a GUI like the built-in <code>gitk</code>, <a href="https://www.sourcetreeapp.com" rel="noreferrer">Sourcetree</a>, <a href="http://code.google.com/p/tortoisegit/" rel="noreferrer">TortoiseGit</a> or <a href="https://www.git-tower.com" rel="noreferrer">Tower</a> <em>(paid)</em>, etc.</p> <p><strong>Step 4: Push</strong></p> <p><code>git push</code> will throw an error, because the push would change the target repository's history.<br> If you're confident the changes shown in step 3 are correct then push with "-f"</p> <pre><code>git push -f origin master </code></pre> <p><br /> <strong>Additional information</strong><br> The command to add a remote is:</p> <pre><code>git remote add upstream git://github.com/[username]/[project].git </code></pre> <p>You can also also pull from a direct URL:</p> <pre><code>git pull --rebase git://github.com/[username]/[project].git </code></pre> <p>But then you'll need the hash of the latest upstream commit instead of "upstream/master" in the other steps.</p>
5,798,264
IISExpress Log File Location
<p>IISExpress writes log and configuration data to pre-determined location out of the box.</p> <p>The directory is an "IISExpress" directory stored in a user's Documents directory.</p> <p>In the directory is stored the following folders files underneath.</p> <ul> <li>Config</li> <li>Logs</li> <li>TraceLogFiles</li> </ul> <p>The location of my home directory is on a network share, determined by group policy</p> <p>Currently we are encountering scenarios where visual studio locks up when stopping debugging Silverlight applications using IIS Express.</p> <p><strong>I was looking to change the location for the log &amp; configuration data for IISExpress to see if this fixes the problem of visual studio locking up. Is it possible to change the default location of log &amp; config files ?</strong></p>
5,799,798
3
1
null
2011-04-27 01:15:00.287 UTC
18
2019-03-20 05:39:35.193 UTC
2017-02-22 22:01:54.69 UTC
null
88,373
null
395,440
null
1
122
iis|iis-express
103,294
<p>1 . By default applicationhost.config file defines following two log file locations. Here IIS_USER_HOME would be expanded as <code>%userprofile%\documents\IISExpress\</code>.</p> <pre><code>&lt;siteDefaults&gt; &lt;logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" /&gt; &lt;traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" /&gt; &lt;/siteDefaults&gt; </code></pre> <p>You can update above directory paths to change the log file locations.</p> <p>2 . If you are running IIS Express from command line, you can use '/config' switch to provide configuration file of your choice. Following link may help you <a href="http://learn.iis.net/page.aspx/870/running-iis-express-from-the-command-line/" rel="noreferrer">http://learn.iis.net/page.aspx/870/running-iis-express-from-the-command-line/</a></p>
5,847,290
How to display console.log() output in PhoneGap app using Eclipse and HTC Desire HD?
<p>I am developing PhoneGap webapp where I use some javascript, and sometimes I need to see console.log() output. I can easily see it when running in Chrome, it also works fine, when running this app in Android emulator - output of console.log() shows up in Eclipse LogCat window. But when I run this app on my HTC Desire HD, LogCat just shows some Android-specific output, but nothing coming from my webapp. </p> <p>Anybody has idea how to display console.log() output from PhoneGap-app running on HTC Desire HD ?</p>
5,849,262
4
0
null
2011-05-01 08:12:05.39 UTC
11
2015-08-17 12:23:35.203 UTC
null
null
null
null
385,264
null
1
28
eclipse|cordova|android
63,358
<p>See the PhoneGap mail list <a href="https://groups.google.com/forum/#!topic/phonegap/FiALy94hwTE" rel="nofollow noreferrer">thread</a>. Also, two stackoverflow threads <a href="https://stackoverflow.com/questions/4860021/android-problem-with-debugging-javascript-in-webview">here</a> and <a href="https://stackoverflow.com/questions/5538516/javascript-console-log-on-htc-android-devices-and-adb-logcat">here</a>.</p> <p>It seems that console.log is disabled on HTC devices running Android 2.2. </p> <p>The best workaround I've found is to use <a href="https://github.com/apache/cordova-weinre" rel="nofollow noreferrer">weinre</a>, which intercepts the console.log to show the output in its desktop browser console.</p> <p><strong>Update</strong>: PhoneGap 1.3.0 now supports console.log directly to LogCat from the HTC Evo without any workarounds. (The same program doesn't work with PhoneGap 1.1.0)</p>
52,669,596
Promise All with Axios
<p>I just read an Article related to promise and was unable to comprehend how we can do <strong>multiple API call using Axios via Promise.all</strong> </p> <p>So consider there are 3 URL, lets call it something like this </p> <pre><code>let URL1 = "https://www.something.com" let URL2 = "https://www.something1.com" let URL3 = "https://www.something2.com" </code></pre> <p>And an array in which we will store Value </p> <pre><code> let promiseArray = [] </code></pre> <p>Now, I want to run this in parallel (<code>Promise.all</code>), but I am unable to figure our how will we do it? Because axios have a promise in itself (or at-least that's how I have used it).</p> <pre><code>axios.get(URL).then((response) =&gt; { }).catch((error) =&gt; { }) </code></pre> <p><strong>Question:</strong> Can someone please tell me how we can we send multiple request using promise.all and axios</p>
52,669,775
7
1
null
2018-10-05 16:10:07.897 UTC
24
2022-03-17 13:27:05.56 UTC
2020-02-13 10:53:49.66 UTC
null
6,021,597
null
10,433,835
null
1
67
javascript|promise|axios
105,624
<p>The <code>axios.get()</code> method will return a promise.</p> <p>The <code>Promise.all()</code> requires an array of promises. For example:</p> <pre><code>Promise.all([promise1, promise2, promise3]) </code></pre> <p>Well then...</p> <pre><code>let URL1 = "https://www.something.com" let URL2 = "https://www.something1.com" let URL3 = "https://www.something2.com" const promise1 = axios.get(URL1); const promise2 = axios.get(URL2); const promise3 = axios.get(URL3); Promise.all([promise1, promise2, promise3]).then(function(values) { console.log(values); }); </code></pre> <p>You might wonder how the response value of <code>Promise.all()</code> looks like. Well then, you could easily figure it out yourself by taking a quick look at this example:</p> <pre><code>var promise1 = Promise.resolve(3); var promise2 = 42; var promise3 = new Promise(function(resolve, reject) { setTimeout(resolve, 100, 'foo'); }); Promise.all([promise1, promise2, promise3]).then(function(values) { console.log(values); }); // expected output: Array [3, 42, "foo"] </code></pre> <p>For more information: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all</a></p>
1,386,782
JButton needs to change JTextfield text
<p>This is homework. Beginning Java class. Still wrapping my head around this stuff. </p> <p>The project is to make an Inventory Management System. </p> <p>I have everything figured out except how to make this button change the text in a JTextField. It needs to add info from an array of a product (DVD's in this case). The book talks about different ways to manage things like font, position and state of a JTextField but it does not cover formatting or calling a method for the text. </p> <p>Here is an example of what I want to do using a JTextArea. This is essentially what I want to do with my JTextFields.</p> <pre><code> ... // setup the interface JPanel panel = new JPanel(); txt = new JTextArea(15,40); txt.setEditable(false);//user shouldn't change it panel.add(txt); JButton next = new JButton("Next"); panel.add(next); getContentPane().add(panel); displayDVD(); } // view software public void displayDVD() { txt.setText("DVD Details:\n"); txt.append("Item number: " + inv.get(currentDisplay).getItem() + "\n"); txt.append("DVD name: " + inv.get(currentDisplay).getName() + "\n"); txt.append("Units in stock: " + inv.get(currentDisplay).getUnits() + "\n"); txt.append("Price: $" + String.format("%.2f",inv.get(currentDisplay).getPrice()) + "\n"); txt.append("Total value: $" + String.format("%.2f",inv.get(currentDisplay).value()) + "\n"); txt.append("Fee: $" + String.format("%.2f",inv.get(currentDisplay).fee()) + "\n\n"); txt.append("Total value: $" + String.format("%.2f",inv.value())); } </code></pre> <p>And here is my actual code so far</p> <pre><code>// GUI with navigation and file manipulation buttons import javax.swing.*; // provides basic window features import java.awt.event.*; import java.awt.GridLayout; import java.awt.BorderLayout; public class AppGUI extends JFrame { private Inventory inv; private int currentDisplay = 0; private JPanel topButtonJPanel; private JButton topButtons[]; private JPanel labelJPanel; private JLabel labels[]; private JPanel fieldJPanel; private JTextField fields[]; private JPanel buttonJPanel; private JButton buttons[]; // LabelFrame constructor adds JLabels to JFrame public AppGUI() { super( "Inventory Program v.5" ); setLayout( new BorderLayout() ); // set frame layout setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// quit if the window is closed // initialize values RatedDVD d1 = new RatedDVD(1, "The Invisible Man", 0, 4999.99, "PG"); RatedDVD d2 = new RatedDVD(2, "The Matrix", 1, 13.01, "PG13"); RatedDVD d3 = new RatedDVD(3, "Se7en", 7, 11.11, "R"); RatedDVD d4 = new RatedDVD(4, "Oceans Eleven", 11, 9.02, "PG13"); RatedDVD d5 = new RatedDVD(5, "Hitch Hikers Guide to the Galaxy", 42, 10.00, "G"); // create inv and enter values inv = new Inventory(); inv.add(d1); inv.add(d2); inv.add(d3); inv.add(d4); inv.add(d5); inv.sort(); topButtons = new JButton[ 6 ]; // create topButtons array topButtonJPanel = new JPanel(); // set up panel topButtonJPanel.setLayout( new GridLayout( 1, topButtons.length, 2, 2 ) ); topButtons[0] = new JButton( "Load file" ); topButtons[1] = new JButton( "Add" ); topButtons[2] = new JButton( "Modify" ); topButtons[3] = new JButton( "Delete" ); topButtons[4] = new JButton( "Search" ); topButtons[5] = new JButton( "Save" ); for(int count=0;count&lt;topButtons.length;count++){topButtonJPanel.add(topButtons[count]);} //add( topButtonJPanel, BorderLayout.NORTH ); // this is for next weeks assignment labels = new JLabel[8]; labelJPanel = new JPanel(); labelJPanel.setLayout( new GridLayout( labels.length, 1 )); labels[0] = new JLabel( "Item ID" ); labels[1] = new JLabel( "Name" ); labels[2] = new JLabel( "Rating" ); labels[3] = new JLabel( "# in Stock" ); labels[4] = new JLabel( "Price" ); labels[5] = new JLabel( "Restocking Fee" );//[DEBUG] ref actual Variable labels[6] = new JLabel( "Inventory Value with Fee (5%)" ); labels[7] = new JLabel( "Total Value with Fee(for all items)" ); for(int count=0;count&lt;labels.length;count++){labelJPanel.add(labels[count]);} add( labelJPanel, BorderLayout.WEST ); fields = new JTextField[8]; fieldJPanel = new JPanel(); int spaces = 28; fieldJPanel.setLayout( new GridLayout( labels.length, 1 )); fields[0] = new JTextField( "", spaces ); fields[1] = new JTextField( "", spaces ); fields[2] = new JTextField( "", spaces ); fields[3] = new JTextField( "", spaces ); fields[4] = new JTextField( "", spaces ); fields[5] = new JTextField( "", spaces ); fields[6] = new JTextField( "", spaces ); fields[7] = new JTextField( "", spaces ); for(int count=0;count&lt;fields.length;count++) { fields[count].setEditable( false ); fieldJPanel.add(fields[count]); } add( fieldJPanel, BorderLayout.EAST ); buttons = new JButton[ 5 ]; // create buttons array buttonJPanel = new JPanel(); // set up panel buttonJPanel.setLayout( new GridLayout( 1, buttons.length, 2, 2 ) ); buttons[0] = new JButton( "First" ); buttons[0].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentDisplay != 0)currentDisplay = 0; //advance to the end } }); buttons[1] = new JButton( "Prev" ); buttons[1].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentDisplay != 0)currentDisplay--; //advance to the end else currentDisplay = (inv.size()-1); } }); Icon bug1 = new ImageIcon( getClass().getResource( "bug1.gif" ) ); buttons[2] = new JButton( bug1 ); buttons[3] = new JButton( "Next" ); buttons[3].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentDisplay &lt; inv.size()-1)currentDisplay++; //advance to the end else currentDisplay = 0; stkover }}); buttons[4] = new JButton( "Last" ); buttons[4].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentDisplay != inv.size()-1)currentDisplay = inv.size()-1; //advance to the end else currentDisplay = (inv.size()-1); } }); for(int count=0;count&lt;buttons.length;count++){buttonJPanel.add(buttons[count]);} add( buttonJPanel, BorderLayout.SOUTH ); }// end method }// end class AppGUI </code></pre> <p>Any hints tips or nudges appreciated. Don't do it all for me though please.</p>
1,386,825
3
1
null
2009-09-06 21:33:54.443 UTC
5
2013-02-15 22:11:02.9 UTC
2013-02-15 22:11:02.9 UTC
null
121,668
null
121,668
null
1
1
java|arrays|jbutton|jtextfield
43,175
<p>You add an action listener to the button (so that it will listen to the button action (click)). Then program that action to change the TextField value.</p> <pre><code>final JButton aButton = ...; final JTextField aTextField = ...; final String aNewText = "New TextField Value"; aButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { aTextField.setText(aNewText); } }); </code></pre> <p>Observe that variables accessed with in 'actionPerformed' must be final (except the fields).</p> <p>Hope this helps.</p>
29,698,198
MS Access database (2010) how to create temporary table/procedure/view from Query Designer
<p>Is there any way how to create temporary table/view/stored procedure in MS Access database (2010) using Query Designer? </p> <p>Whenever i try to execute something like this:</p> <pre><code>SELECT * INTO #temp_table FROM (SELECT column_1, column_2 FROM table) </code></pre> <p>MS Access throws an error:</p> <blockquote> <p>Syntax error in CREATE TABLE statement.</p> </blockquote> <p>With no further information.</p>
29,700,096
5
0
null
2015-04-17 11:43:31.787 UTC
null
2017-03-21 22:50:20.337 UTC
null
null
null
null
1,784,053
null
1
5
ms-access|ms-access-2010
46,063
<p>Access SQL does not support executing more than one SQL statement at a time, so the notion of a #temp table does not really apply. If you require a temporary table then you need to </p> <ul> <li>create a "real" table,</li> <li>do your work with it, and then</li> <li>delete (drop) the table when you're done.</li> </ul>
53,368,303
Why am I getting "unused Result which must be used ... Result may be an Err variant, which should be handled" even though I am handling it?
<pre><code>fn main() { foo().map_err(|err| println!("{:?}", err)); } fn foo() -&gt; Result&lt;(), std::io::Error&gt; { Ok(()) } </code></pre> <p>results:</p> <pre class="lang-none prettyprint-override"><code>warning: unused `std::result::Result` that must be used --&gt; src/main.rs:2:5 | 2 | foo().map_err(|err| println!("{:?}", err)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: #[warn(unused_must_use)] on by default = note: this `Result` may be an `Err` variant, which should be handled Finished dev [unoptimized + debuginfo] target(s) in 0.58s Running `target/debug/playground` </code></pre> <p><a href="https://play.rust-lang.org/?version=beta&amp;mode=debug&amp;edition=2018&amp;gist=ab5084d87397e890a61c4495fc195e22" rel="noreferrer">playground link</a></p>
53,368,681
1
1
null
2018-11-19 04:25:34.113 UTC
null
2018-11-19 14:26:36.877 UTC
2018-11-19 14:26:36.877 UTC
null
155,423
null
356,011
null
1
32
rust
15,348
<p>You're not handling the result, you're mapping the result from one type to another.</p> <pre><code>foo().map_err(|err| println!("{:?}", err)); </code></pre> <p>What that line does is call <code>foo()</code>, which returns <code>Result&lt;(), std::io::Error&gt;</code>. Then <code>map_err</code> uses the type returned by your closure (in this case, <code>()</code>), and modifies the error type and returns <code>Result&lt;(), ()&gt;</code>. This is the result that you are not handling. Since you seem to want to just ignore this result, the simplest thing to do would probably be to call <code>ok()</code>.</p> <pre><code>foo().map_err(|err| println!("{:?}", err)).ok(); </code></pre> <p><code>ok()</code> converts <code>Result&lt;T,E&gt;</code> to <code>Option&lt;T&gt;</code>, converting errors to <code>None</code>, which you won't get a warning for ignoring.</p> <p>Alternatively:</p> <pre><code>match foo() { Err(e) =&gt; println!("{:?}", e), _ =&gt; () } </code></pre>
32,401,493
How to create/customize your own scorer function in scikit-learn?
<p>I am using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html" rel="noreferrer">Support Vector Regression</a> as an estimator in <a href="http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html" rel="noreferrer">GridSearchCV</a>. But I want to change the error function: instead of using the default (R-squared: coefficient of determination), I would like to define my own custom error function.</p> <p>I tried to make one with <code>make_scorer</code>, but it didn't work.</p> <p>I read the documentation and found that it's possible to create <a href="http://scikit-learn.org/dev/developers/contributing.html#apis-of-scikit-learn-objects" rel="noreferrer">custom estimators</a>, but I don't need to remake the entire estimator - only the error/scoring function.</p> <p>I think I can do it by defining a callable as a scorer, like it says in the <a href="http://scikit-learn.org/stable/modules/model_evaluation.html#implementing-your-own-scoring-object" rel="noreferrer">docs</a>.</p> <p>But I don't know how to use an estimator: in my case SVR. Would I have to switch to a classifier (such as SVC)? And how would I use it?</p> <p>My custom error function is as follows:</p> <pre><code>def my_custom_loss_func(X_train_scaled, Y_train_scaled): error, M = 0, 0 for i in range(0, len(Y_train_scaled)): z = (Y_train_scaled[i] - M) if X_train_scaled[i] &gt; M and Y_train_scaled[i] &gt; M and (X_train_scaled[i] - Y_train_scaled[i]) &gt; 0: error_i = (abs(Y_train_scaled[i] - X_train_scaled[i]))**(2*np.exp(z)) if X_train_scaled[i] &gt; M and Y_train_scaled[i] &gt; M and (X_train_scaled[i] - Y_train_scaled[i]) &lt; 0: error_i = -(abs((Y_train_scaled[i] - X_train_scaled[i]))**(2*np.exp(z))) if X_train_scaled[i] &gt; M and Y_train_scaled[i] &lt; M: error_i = -(abs(Y_train_scaled[i] - X_train_scaled[i]))**(2*np.exp(-z)) error += error_i return error </code></pre> <p>The variable <code>M</code> isn't null/zero. I've just set it to zero for simplicity.</p> <p>Would anyone be able to show an example application of this custom scoring function? Thanks for your help!</p>
36,560,637
2
1
null
2015-09-04 15:20:08.073 UTC
26
2020-05-08 15:54:23.583 UTC
2016-04-15 00:16:18.007 UTC
null
5,076,471
null
4,371,803
null
1
54
python|scikit-learn
56,907
<p>As you saw, this is done by using <code>make_scorer</code> (<a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html#sklearn.metrics.make_scorer" rel="noreferrer">docs</a>).</p> <pre><code>from sklearn.grid_search import GridSearchCV from sklearn.metrics import make_scorer from sklearn.svm import SVR import numpy as np rng = np.random.RandomState(1) def my_custom_loss_func(X_train_scaled, Y_train_scaled): error, M = 0, 0 for i in range(0, len(Y_train_scaled)): z = (Y_train_scaled[i] - M) if X_train_scaled[i] &gt; M and Y_train_scaled[i] &gt; M and (X_train_scaled[i] - Y_train_scaled[i]) &gt; 0: error_i = (abs(Y_train_scaled[i] - X_train_scaled[i]))**(2*np.exp(z)) if X_train_scaled[i] &gt; M and Y_train_scaled[i] &gt; M and (X_train_scaled[i] - Y_train_scaled[i]) &lt; 0: error_i = -(abs((Y_train_scaled[i] - X_train_scaled[i]))**(2*np.exp(z))) if X_train_scaled[i] &gt; M and Y_train_scaled[i] &lt; M: error_i = -(abs(Y_train_scaled[i] - X_train_scaled[i]))**(2*np.exp(-z)) error += error_i return error # Generate sample data X = 5 * rng.rand(10000, 1) y = np.sin(X).ravel() # Add noise to targets y[::5] += 3 * (0.5 - rng.rand(X.shape[0]/5)) train_size = 100 my_scorer = make_scorer(my_custom_loss_func, greater_is_better=True) svr = GridSearchCV(SVR(kernel='rbf', gamma=0.1), scoring=my_scorer, cv=5, param_grid={"C": [1e0, 1e1, 1e2, 1e3], "gamma": np.logspace(-2, 2, 5)}) svr.fit(X[:train_size], y[:train_size]) print svr.best_params_ print svr.score(X[train_size:], y[train_size:]) </code></pre>
5,621,019
Jquery - change <span>text</span> with dropdown selector
<p>This might be easy, but I'm a JQuery dunce and keep getting errors!</p> <p>Basically, I have a basic JQuery 1.4+ function that updates an input value - but now I'm having a hard time figuring out how to also use JQuery to simultaneously update a text in the area when different values are chosen with a dropdown selector. The Script and HTML looks like this:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { $('#mycups3').change(function() { var x = $(this).val(); $('#myhidden3').val(x); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form action="" method="post"&gt; &lt;input type="hidden" id="myhidden3" name="quantity" value="1" /&gt; &lt;input type="submit" name="submit" class="button" id="" value="Button" /&gt; &lt;select id='mycups3'&gt; &lt;option value='1'&gt;1 Item&lt;/option&gt; &lt;option value='2'&gt;2 Items&lt;/option&gt; &lt;option value='3'&gt;3 Items&lt;/option&gt; &lt;/select&gt; &lt;span&gt;$1.50&lt;/span&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>What I want to add: When using the dropdown selector, I also want the value in the <code>&lt;span&gt;$1.50&lt;/span&gt;</code> to update. Example - selecting a value of '1' makes the text string in <code>span</code> show $1.50 - selecting a value of '2' in the dropdown makes the text string show $3.00 (or whatever) etc!</p> <p>Any clues are greatly appreciated! Thanks!</p>
5,621,087
6
1
null
2011-04-11 12:07:41.473 UTC
3
2015-06-10 12:03:26.83 UTC
2015-06-10 12:03:26.83 UTC
null
1,146,264
null
350,828
null
1
6
javascript|jquery|html|forms
39,214
<p>Try this:</p> <pre><code>&lt;script type='text/javascript'&gt; $(function() { $('#mycups3').change(function() { var x = $(this).val(); $('#myhidden3').val(x); $(this).next("span").text("$" + (x * 1.5).toFixed(2)); }); }); &lt;/script&gt; </code></pre>
5,735,379
What does #include actually do?
<p>In C (or a language based on C), one can happily use this statement:</p> <pre><code>#include "hello.h"; </code></pre> <p>And voila, every function and variable in <code>hello.h</code> is automagically usable.</p> <p>But what does it actually do? I looked through compiler docs and tutorials and spent some time searching online, but the only impression I could form about the magical <code>#include</code> command is that it "copy pastes" the contents of <code>hello.h</code> instead of that line. There's gotta be more than that.</p>
5,735,389
6
1
null
2011-04-20 19:09:37.457 UTC
8
2020-09-04 14:40:31.003 UTC
2011-04-20 19:11:02.977 UTC
null
592,746
null
617,762
null
1
32
c|include
20,965
<p>Logically, that copy/paste is exactly what happens. I'm afraid there isn't any more to it. You don't need the <code>;</code>, though.</p> <p>Your specific example is covered by the spec, section <strong>6.10.2 Source file inclusion</strong>, paragraph 3:</p> <blockquote> <p>A preprocessing directive of the form</p> <p><strong><code># include</code></strong> <code>"</code><em>q-char-sequence</em><code>"</code> <em>new-line</em></p> <p>causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the <code>"</code> delimiters.</p> </blockquote>
5,476,059
Handling Multiple Roles in MVC - Action-based Accessibility
<p>I currently have a project that I seem to have ran into an issue regarding Roles and thought I would get some opinions on how to best handle the problem. </p> <p>The system will require editable, flexible roles that control not only the access of specific areas, but also the use of system functions (Adding Users, Editing Users, Viewing Reports etc.)</p> <p>The system currently allows users to have multiple roles, each of those roles has explicitly defined areas of access/actions, for example:</p> <ul> <li><strong>Role A</strong> can access areas 1,2,3 and can Add Users.</li> <li><strong>Role B</strong> can access areas 1,5,7 and can Modify Users.</li> <li><strong>Role C</strong> can access areas 4,6 and only View Users.</li> </ul> <p>so a User could be in Roles A and C, and thus access : 1,2,3,4 and 6, and could Add and View Users.</p> <p>My first solution was to create a dictionary that would store all of the possible areas of access/access options into a Dictionary like so:</p> <pre><code>Dictionary&lt;string,bool&gt; </code></pre> <p>then when it is instantiated it pulls all of the properties from the database and then iterates through the roles to determine if they are accessible.</p> <p>All of that currently works just fine - however the project is quite Javascript/jQuery intensive so many of these options are called by client-side functions. I am trying to avoid having to wrap all of these client side functions with:</p> <pre><code>&lt;%if(AccessDictionary[key]) //Enable or Disable Action &lt;%}%&gt; </code></pre> <p><strong>So basically, I am wondering about the following things:</strong></p> <ol> <li><strong>After a user logs in, what is the best way to store this Dictionary? Statically? In the Session?</strong></li> <li><strong>What would be the best method of storage such that the Dictionary will be easily accessed in the View? (As I currently see no way around wrapping my client-side functions)</strong></li> </ol> <p>Any advice or ideas would be greatly appreciated!</p>
5,476,355
1
1
null
2011-03-29 16:51:51.377 UTC
15
2012-06-18 20:30:01.127 UTC
2011-03-29 21:01:02.273 UTC
null
557,445
null
557,445
null
1
11
c#|asp.net|asp.net-mvc-2|dictionary|roles
7,943
<p>I would store this information in the user data part of the authentication cookie. So when a user logs in:</p> <pre><code>public ActionResult Login(string username, string password) { // TODO: validate username/password couple and // if they are valid get the roles for the user var roles = "RoleA|RoleC"; var ticket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddMilliseconds(FormsAuthentication.Timeout.TotalMilliseconds), false, roles ); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { // IIRC this property is only available in .NET 4.0, // so you might need a constant here to match the domain property // in the &lt;forms&gt; tag of the web.config Domain = FormsAuthentication.CookieDomain, HttpOnly = true, Secure = FormsAuthentication.RequireSSL, }; Response.AppendCookie(authCookie); return RedirectToAction("SomeSecureAction"); } </code></pre> <p>Then I would write a custom authroize attribute which will take care of reading and parsing the authentication ticket and store a generic user in the HttpContext.User property with its corresponding roles:</p> <pre><code>public class MyAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext.User.Identity.IsAuthenticated) { var authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { var ticket = FormsAuthentication.Decrypt(authCookie.Value); var roles = ticket.UserData.Split('|'); var identity = new GenericIdentity(ticket.Name); httpContext.User = new GenericPrincipal(identity, roles); } } return base.AuthorizeCore(httpContext); } } </code></pre> <p>Next you could decorate your controllers/actions with this attribute to handle authorization:</p> <pre><code>// Only users that have RoleA or RoleB can access this action // Note that this works only with OR =&gt; that's how the base // authorize attribute is implemented. If you need to handle AND // you will need to completely short-circuit the base method call // in your custom authroize attribute and simply handle this // case manually [MyAuthorize(Roles = "RoleA,RoleB")] public ActionResult Foo() { ... } </code></pre> <p>In order to check whether a user is in a given role simply:</p> <pre><code>bool isInRole = User.IsInRole("RoleC"); </code></pre> <p>Armed with this information you can now start thinking of how to organize your view models. In those view models I would include boolean properties such as <code>CanEdit</code>, <code>CanViewReport</code>, ... which will be populated by the controller.</p> <p>Now if you need this mapping in each action and views things might get repetitive and boring. This is where global custom action filters come into play (they don't really exist in ASP.NET MVC 2, only in ASP.NET MVC 3 so you might need a base controller decorated with this action filter which simulates more or less the same functionality). You simply define such global action filter which executes after each action and injects some common view model to the ViewData (holy ...., can't believe I am pronouncing those words) and thus make it available to all views in a transverse of the other actions manner.</p> <p>And finally in the view you would check those boolean value properties in order to include or not different areas of the site. As far as the javascript code is concerned if it is unobtrusively AJAXifying areas of the site then if those areas are not present in the DOM then this code won't run. And if you needed more fine grained control you could always use HTML5 <code>data-*</code> attributes on your DOM elements to give hints to your external javascript functions on the authorizations of the user.</p>
24,479,109
Maven for Eclipse 1.5.0 plugin cannot be installed under Kepler
<p>I downloaded Eclipse Kepler and tried to install M2Eclipse from its <a href="http://download.eclipse.org/technology/m2e/releases">update site</a>.</p> <p>After selecting Maven Integration for Eclipse, I clicked Next and got the following error:</p> <blockquote> <p>Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found</p> </blockquote> <p>So I searched through the internet to find out how to install the Guava Eclipse plugin. Some say it's from the Eclipse marketplace, but it cannot be downloaded. I downloaded the <a href="https://code.google.com/p/guava-libraries/wiki/Release16">binary</a> and tried to copy it to Eclipse's plugin directory. Still the same result.</p> <pre><code>cp ~/Downloads/guava-16.0.1.jar /Applications/eclipse/plugins/com.google.guava_16.0.1.v1234.jar </code></pre> <p>How do I install the m2e plugin for Kepler?</p>
24,482,661
6
1
null
2014-06-29 18:46:27.103 UTC
8
2017-08-11 11:22:24.66 UTC
2015-06-12 14:58:19.42 UTC
null
880,772
null
1,172,561
null
1
37
eclipse|maven|guava|m2e
34,317
<p>m2e 1.5.0 <a href="http://dev.eclipse.org/mhonarc/lists/m2e-users/msg04751.html" rel="nofollow noreferrer">requires Eclipse Luna</a>. It will not work with Kepler or Indigo. (thanks to <a href="https://stackoverflow.com/users/218028/hdave">@HDave</a> for the link)</p> <p>So you have to use an older version of m2e under Kepler.</p> <p>During installation, <strong>uncheck "Show only the latest versions of available software"</strong>. Then only check the 1.4.1 version or lower version in the candidate list. It doesn't require the Guava dependency. </p>
48,938,385
Github unable to access SSL connect error
<p>I have been using git lots for the last few months. git push worked 12 hours ago now all attempts generate errors, with verbose it produces this:</p> <pre><code>GIT_CURL_VERBOSE=1 git push * Couldn't find host github.com in the .netrc file; using defaults * About to connect() to github.com port 443 (#0) * Trying 192.30.253.112... * Connected to github.com (192.30.253.112) port 443 (#0) * Initializing NSS with certpath: sql:/etc/pki/nssdb * CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none * NSS error -12190 * Expire cleared * Closing connection #0 fatal: unable to access 'https://github.com/waveney/wmff/': SSL connect error </code></pre> <p>Any bright ideas? No changes to server from when it worked to now, restart made no difference</p>
48,939,640
3
2
null
2018-02-22 22:38:42.943 UTC
12
2020-07-01 13:25:26.833 UTC
null
null
null
null
3,477,902
null
1
40
ssl|github
38,350
<p>I was having the same problem on various CentOS 6 VM's and it turned out to be an issue with stale curl and nss libraries (thanks to this thread for pointing me in the right direction: <a href="https://stackoverflow.com/questions/21887315/curl-ssl-connect-error-35-with-nss-error-5961">cURL SSL connect error 35 with NSS error -5961</a>).</p> <p>The fix that worked for me is just:</p> <pre><code>yum update -y nss curl libcurl </code></pre>
9,562,475
jQuery Full Calendar Default View Setting
<p>I am using jQuery Full calendar.</p> <p>But I am not getting how to set the week view as Default view in full calendar.</p>
9,562,496
8
0
null
2012-03-05 06:25:27.35 UTC
2
2022-06-26 04:14:22.96 UTC
2017-10-21 09:13:29.41 UTC
null
3,885,376
null
1,123,948
null
1
17
jquery
45,838
<p>Try:</p> <pre> <code> $('#calendar').fullCalendar({ defaultView: 'basicWeek' aspectRatio: 1.5 }); </code> </pre> <p>Ref: <a href="http://arshaw.com/fullcalendar/docs/views/Available_Views/" rel="noreferrer">FullCalendar Available Views</a></p> <p><strong>Edited:</strong></p> <pre> <code> $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, defaultView: 'basicWeek' .... </code> </pre>
9,109,738
Specified element is already the logical child of another element. Disconnect it first
<p>here is the error I have when I want to attach a FrameworkElement to a new Window to publish it to a PNG file.</p> <p>So my idea is to remove the parent-child link, call my method, and add the child again with this code :</p> <pre><code>this.RemoveLogicalChild(element); PublishFrameworkElement(element, stream); this.AddLogicalChild(element); </code></pre> <p>But I got the exact same error...</p> <p>I looked a lot of questions about this error, here on SO, but none answered to my problem What am I missing ?</p> <p>EDIT : here is the code that worked for me :</p> <pre><code>var element = _GeneratedContent as FrameworkElement; var ParentPanelCollection = (element.Parent as Panel).Children as UIElementCollection; ParentPanelCollection.Clear(); FileStream stream = [...] if (element != null) { PublishFrameworkElement(element, stream); ParentPanelCollection.Add(element); } stream.Close(); </code></pre>
9,110,203
4
0
null
2012-02-02 09:17:32.117 UTC
null
2017-11-20 18:52:53.77 UTC
2012-02-02 10:44:00.897 UTC
null
946,425
null
946,425
null
1
21
c#|wpf|frameworkelement
39,969
<p>If <code>element</code> is the child of a Panel (e.g. Grid) you have to remove it from the Panel's <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.panel.children.aspx" rel="noreferrer">Children</a> collection. If it is set as <code>Content</code> of a <code>ContentControl</code>, you'd have to set that Content to null (or anything else that is not <code>element</code>).</p>
10,505,350
Does master page get called first?
<p>I would assume this is true, but wanted to throw this question up. Is the master page executed first in ASP.NET, or does the page which is getting retrieved? </p> <p>I am asking because I want some processing to be done in the master page, results of which are loaded into a static object and which can then be used by the called page (for instance user data)</p>
10,505,409
4
1
null
2012-05-08 19:41:45.067 UTC
10
2012-05-08 21:04:02.51 UTC
2012-05-08 19:47:57.107 UTC
user57508
null
null
1,260,028
null
1
10
c#|asp.net|.net|master-pages
12,512
<p>Sorry for just quoting, but i don't know what to add:</p> <blockquote> <p>Individual ASP.NET server controls have their own life cycle that is similar to the page life cycle. For example, a control's Init and Load events occur during the corresponding page events.</p> <p>Although both Init and Load recursively occur on each control, they happen in reverse order. The Init event (and also the Unload event) for each child control occur before the corresponding event is raised for its container (bottom-up). However the Load event for a container occurs before the Load events for its child controls (top-down). <strong>Master pages behave like child controls on a page: the master page Init event occurs before the page Init and Load events, and the master page Load event occurs after the page Init and Load events.</strong></p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a></p> <p><img src="https://i.stack.imgur.com/yOUGl.png" alt="enter image description here"></p>
10,587,561
Password protected zip file in java
<p>I have created zip file using java as below snippet</p> <pre><code>import java.io.*; import java.util.zip.*; public class ZipCreateExample { public static void main(String[] args) throws IOException { System.out.print("Please enter file name to zip : "); BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); String filesToZip = input.readLine(); File f = new File(filesToZip); if(!f.exists()) { System.out.println("File not found."); System.exit(0); } System.out.print("Please enter zip file name : "); String zipFileName = input.readLine(); if (!zipFileName.endsWith(".zip")) zipFileName = zipFileName + ".zip"; byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream (new FileOutputStream(zipFileName)); out.setLevel(Deflater.DEFAULT_COMPRESSION); FileInputStream in = new FileInputStream(filesToZip); out.putNextEntry(new ZipEntry(filesToZip)); int len; while ((len = in.read(buffer)) &gt; 0) { out.write(buffer, 0, len); } out.closeEntry(); in.close(); out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); System.exit(0); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); System.exit(0); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(0); } } } </code></pre> <p>Now I want when I click on the zip file it should prompt me to type password and then decompress the zip file. Please any help,How should I go further?</p>
10,587,717
6
1
null
2012-05-14 16:42:37.483 UTC
12
2021-09-06 09:51:47.347 UTC
2016-05-05 07:06:10.977 UTC
null
157,882
null
1,142,496
null
1
36
java|zip
105,755
<p>Standard Java API does not support password protected zip files. Fortunately good guys have already implemented such ability for us. Please take a look on this article that explains how to create password protected zip.<br /> (The link was dead, latest archived version: <a href="https://web.archive.org/web/20161029174700/http://java.sys-con.com/node/1258827" rel="nofollow noreferrer">https://web.archive.org/web/20161029174700/http://java.sys-con.com/node/1258827</a>)</p>
7,130,425
Spring Property Injection in a final attribute @Value - Java
<p>A simple question on Spring injection from a properties file for a final attribute.</p> <p>I have a properties file which I want to store a file path in. Generally when I use properties files I setup class attributes using something like this:</p> <pre><code>private @Value(&quot;#{someProps['prop.field']}&quot;) String someAttrib ; </code></pre> <p>Then in my <code>spring.xml</code> I would have something like:</p> <pre><code>&lt;util:properties id=&quot;someProps&quot; location=&quot;classpath:/META-INF/properties/somePropFile.properties&quot; /&gt; </code></pre> <p>This works well, is simple and makes code nice and neat. But I'm not sure what is the neatest pattern to use when trying to inject properties values into final class attributes?</p> <p>Obviously something like:</p> <pre><code>private static final @Value(&quot;#{fileProps['dict.english']}&quot;) String DICT_PATH; </code></pre> <p>will not work. Is there another way?</p>
7,132,244
2
1
null
2011-08-20 07:25:32.877 UTC
10
2020-08-04 08:33:02.18 UTC
2020-08-04 08:33:02.18 UTC
null
839,554
null
744,415
null
1
49
java|spring|dependency-injection|properties|properties-file
54,538
<p>The only way you can inject values into a final field is through <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-constructor-injection" rel="noreferrer">Constructor Injection</a>. Everything else would be an awful hack on Spring's side.</p>
7,401,340
Retrieving files from Directory Node Js
<p>I am using readDirSync to get the files from a Diretory. PLease find the code and error as following.</p> <pre><code>var fs = require('fs'); var files = fs.readdirSync('./application/models/'); for(var i in files) { var definition = require('../application/models/'+files[i]).Model; console.log('Model Loaded: ' + files[i]); } </code></pre> <p>I am getting error for line number 2 . ENOENT, No such file or directory './application/models/' at Object.readdirSync (fs.js:376:18)</p> <p>I have application/models on the same dir. I already checked for '/application/models/' and 'application/models/' but failed. I can see the same thing running on server.</p> <p>Please help</p> <p>Thanks</p>
9,796,585
2
1
null
2011-09-13 11:48:08.987 UTC
4
2016-01-18 15:03:01.277 UTC
2011-09-13 12:06:07.04 UTC
null
419,970
null
902,389
null
1
50
node.js
78,678
<p>If you are using relative path when calling <code>readdirSync</code>, make sure it is relative to <code>process.cwd()</code>. However, <strong>"require" should be relative to the current script.</strong></p> <p>For example, given the following structure</p> <pre><code>server.js (node process) /lib/importer.js (the current script) /lib/application/models/ </code></pre> <p>you may need to write <em>importer.js</em> as: </p> <pre><code>var fs = require('fs'); var files = fs.readdirSync('./lib/application/models/'); for (var i in files) { var definition = require('./application/models/' + files[i]).Model; console.log('Model Loaded: ' + files[i]); } </code></pre>
31,271,491
How to search through all the ajax responses in network tab in Chrome?
<p>How to search through all the ajax responses in network tab in Chrome?</p> <p>I want to do this is because it is difficult for a JavaScript developer to get to know which information is coming from which service call, especially if you are new to the project and business logic is not clear. Also, opening each service in a network tab and searching in responses of so many service calls is difficult and time consuming.</p>
50,872,863
6
4
null
2015-07-07 14:29:31.263 UTC
13
2022-09-23 15:12:55.683 UTC
2018-02-23 22:27:55.477 UTC
null
4,076,315
null
3,221,274
null
1
107
google-chrome-devtools
36,012
<p>This has now been implemented on the Network tab. Whenever a search criteria is added, Chrome will offer searching through all headers and bodies.</p> <p><a href="https://i.stack.imgur.com/1Rg5o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Rg5o.png" alt="enter image description here" /></a></p> <p>More from <a href="https://developers.google.com/web/updates/2018/04/devtools#network-search" rel="nofollow noreferrer">offical doc</a>,</p> <blockquote> <p>Open the Network panel then press Command+F (Mac) or Control+F (Windows, Linux, Chrome OS) to open the new Network Search pane.</p> </blockquote> <p><a href="https://i.stack.imgur.com/8gm0h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8gm0h.png" alt="search network" /></a></p>
19,067,785
switch case on NSString in objective c
<p>i want to use case statement with NSString please change my code to correct code</p> <pre><code>NSString *day = @"Wed"; switch (day) { case @"Sat": NSlog(@"Somthing..."); break; case @"Sun": NSlog(@"Somthing else..."); break; . . . . default: break; } </code></pre>
19,067,915
2
2
null
2013-09-28 14:00:11.737 UTC
10
2014-08-28 07:41:17.877 UTC
null
null
null
null
1,322,149
null
1
12
objective-c|nsstring|switch-statement
26,910
<p>If you want some slightly smarter dispatch than a long list of conditionals you can use a dictionary of blocks:</p> <pre><code>NSString *key = @"foo"; void (^selectedCase)() = @{ @"foo" : ^{ NSLog(@"foo"); }, @"bar" : ^{ NSLog(@"bar"); }, @"baz" : ^{ NSLog(@"baz"); }, }[key]; if (selectedCase != nil) selectedCase(); </code></pre> <p>If you have a really long list of cases and you do this often, there might be a tiny performance advantage in this. You should cache the dictionary, then (and don't forget to copy the blocks).</p> <p>Sacrificing legibility for convenience and brevity here's a version that fits everything into a single statement and adds a default case:</p> <pre><code>((void (^)())@{ @"foo" : ^{ NSLog(@"foo"); }, @"bar" : ^{ NSLog(@"bar"); }, @"baz" : ^{ NSLog(@"baz"); }, }[key] ?: ^{ NSLog(@"default"); })(); </code></pre> <p>I prefer the former.</p>
17,814,410
Check if two rows are the EXACT SAME in MS Excel
<p>In MS Excel, what is the best way to see if two rows are the exact same? I've tried with conditional formatting but it only seems like I can only check for duplicat CELLS and not whole rows. Thanks in advance for the help!</p>
17,814,654
2
3
null
2013-07-23 15:22:48.87 UTC
3
2018-07-12 16:45:23.243 UTC
null
null
null
null
2,521,744
null
1
12
excel
96,916
<p>You need an array formula that compares the 2 rows.</p> <p>If you want to find out if rows 1 and 2 are exactly the same, enter this formula in a cell that isn't in row 1 or 2:</p> <pre><code>=AND(EXACT(1:1,2:2)) </code></pre> <p>Instead of pressing <kbd>Enter</kbd> after typing the formula, press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd>, which will tell Excel you want an Array formula.</p> <p>The result will be TRUE if they match and FALSE if they don't. You'll see curly braces around your formula if you've correctly entered it as an array formula.</p> <p>Note that the EXACT formula will perform a case-sensitive comparison. Omit it if you want a case-insensitive comparison:</p> <pre><code>=AND(1:1=2:2) </code></pre> <p>entered with <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd> as well.</p> <p>One last thing: if you want to check part of a row instead of the whole row, simply specify that in the formula.</p> <pre><code>=AND(EXACT(A1:E1,A2:E2)) </code></pre> <p>entered with <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd>, of course.</p>
3,951,302
Jquery select class from variable
<p>I am using Jquery to find a class by variable. So,</p> <pre><code>var className = "whatever"; </code></pre> <p><em>$("#container ul li") if contains element with className, do this</em></p> <p>How do I write the above code?</p> <p>Is it</p> <pre><code>$("#container ul li").find("."+ className).each(function(){ console.log("I found one"); }); </code></pre> <p>Obviously the code doesn't work</p>
3,951,306
1
0
null
2010-10-16 23:39:14.19 UTC
3
2010-10-16 23:50:37.143 UTC
2010-10-16 23:50:37.143 UTC
null
113,716
null
460,055
null
1
12
jquery|jquery-selectors
41,077
<p>Is the <code>className</code> on the <code>&lt;li&gt;</code> element? If so, you could do this:</p> <pre><code>$('#container ul li.' + className)... </code></pre> <p>You're just concatenating the className into the selector string (with <a href="http://api.jquery.com/class-selector" rel="noreferrer">the class selector</a>).</p> <p>Or this will give you the same result.</p> <pre><code>$('#container ul li').filter('.' + className)... </code></pre> <p>Which is the similar to your <code>.find()</code> solution, but <a href="http://api.jquery.com/filter/" rel="noreferrer">uses <code>.filter()</code></a> to limit the <code>&lt;li&gt;</code> elements found to those with the <code>className</code>.</p> <hr> <p>If the element with the <code>className</code> is a descendant of the <code>&lt;li&gt;</code> element, then <a href="http://api.jquery.com/find/" rel="noreferrer">using <code>.find()</code></a> should work, or you could do:</p> <pre><code>$('#container ul li .' + className)... </code></pre> <p>...which almost looks the same as the one above, but introduces a space after <code>li</code>, which is <a href="http://api.jquery.com/descendant-selector" rel="noreferrer">a descendant selector</a>.</p>
20,890,943
Why is JavaScript's Set Timeout not working?
<p>I'm trying to use setTimeout, But it doesn't work. Any help is appreciated.</p> <p>Anyone know how to fix this?</p> <pre><code>var button = document.getElementById(&quot;reactionTester&quot;); var start = document.getElementById(&quot;start&quot;); function init() { var startInterval/*in milliseconds*/ = 1000; setTimeout(startTimer(), startInterval); } function startTimer() { document.write(&quot;hey&quot;); } </code></pre>
20,890,982
7
2
null
2014-01-02 20:08:34.13 UTC
9
2022-04-11 18:11:11.467 UTC
2022-04-11 18:11:11.467 UTC
null
2,251,258
null
2,251,258
null
1
51
javascript
136,790
<p>This line:</p> <pre><code>setTimeout(startTimer(), startInterval); </code></pre> <p>You're invoking <code>startTimer()</code>. Instead, you need to pass it in as a function <em>to be invoked</em>, like so:</p> <pre><code>setTimeout(startTimer, startInterval); </code></pre>
41,210,823
Using plt.imshow() to display multiple images
<p>How do I use the matlib function plt.imshow(image) to display multiple images?</p> <p>For example my code is as follows:</p> <pre><code>for file in images: process(file) def process(filename): image = mpimg.imread(filename) &lt;something gets done here&gt; plt.imshow(image) </code></pre> <p>My results show that only the last processed image is shown effectively overwriting the other images</p>
41,210,974
4
1
null
2016-12-18 17:12:19.12 UTC
9
2022-05-22 11:49:07.917 UTC
null
null
null
null
5,662,769
null
1
54
python|matplotlib
152,487
<p>You can set up a framework to show multiple images using the following:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.image as mpimg def process(filename: str=None) -&gt; None: """ View multiple images stored in files, stacking vertically Arguments: filename: str - path to filename containing image """ image = mpimg.imread(filename) # &lt;something gets done here&gt; plt.figure() plt.imshow(image) for file in images: process(file) </code></pre> <p>This will stack the images vertically</p>
41,212,273
Pandas(Python) : Fill empty cells with with previous row value?
<p>I want to fill empty cells with with previous row value if they start with number. For example, I have </p> <pre><code> Text Text 30 Text Text Text Text Text Text 31 Text Text Text Text 31 Text Text Text Text Text Text 32 Text Text Text Text Text Text Text Text Text Text Text Text </code></pre> <p>I however, want to have </p> <pre><code>Text Text 30 Text Text 30 Text Text 30 Text Text 31 Text Text Text Text 31 Text Text 31 Text Text 31 Text Text 32 Text Text Text Text Text Text Text Text Text Text Text Text </code></pre> <p>I tried to reach this by using this code:</p> <pre><code>data = pd.read_csv('DATA.csv',sep='\t', dtype=object, error_bad_lines=False) data = data.fillna(method='ffill', inplace=True) print(data) </code></pre> <p>but it did not work. </p> <p>Is there anyway to do this?</p>
41,213,232
3
2
null
2016-12-18 19:55:10.147 UTC
11
2022-04-15 19:03:27.207 UTC
null
null
null
null
6,437,260
null
1
29
python|python-3.x|pandas
54,092
<p>First, replace your empty cells with NaNs:</p> <pre><code>df[df[0]==""] = np.NaN </code></pre> <p>Now, Use <code>ffill()</code>:</p> <pre><code>df.fillna(method='ffill') # 0 #0 Text #1 30 #2 30 #3 30 #4 31 #5 Text #6 31 #7 31 #8 31 #9 32 </code></pre>
2,143,460
How to convert C# code to a PowerShell Script?
<p>I regularly have to convert an existing C# code snippet/.CS file to a PowerShell script. How could I automate this process?</p> <p>While I am aware that there are methods that can <a href="https://stackoverflow.com/questions/343182/how-to-convert-cs-file-to-a-powershell-cmdlet">convert a .cs file to a cmdlet</a>, I'm only interested in converting the C# code to a script or module. </p>
2,143,945
3
1
null
2010-01-26 23:19:20.553 UTC
16
2020-09-29 15:04:56.987 UTC
2017-05-23 12:34:27.913 UTC
null
-1
null
35,483
null
1
33
c#|powershell|powershell-2.0
37,919
<p>I know you're looking for something that somehow converts C# directly to PowerShell, but I thought this is close enough to suggest it.</p> <p>In PS v1 you can use a compiled .NET DLL:</p> <pre><code>PS&gt; $client = new-object System.Net.Sockets.TcpClient PS&gt; $client.Connect($address, $port) </code></pre> <p>In PS v2 you can add C# code directly into PowerShell and use it without 'converting' using Add-Type (copied straight from <a href="http://technet.microsoft.com/en-us/library/dd315241.aspx" rel="noreferrer">MSDN</a> )</p> <pre><code>C:\PS&gt;$source = @" public class BasicTest { public static int Add(int a, int b) { return (a + b); } public int Multiply(int a, int b) { return (a * b); } } "@ C:\PS&gt; Add-Type -TypeDefinition $source C:\PS&gt; [BasicTest]::Add(4, 3) C:\PS&gt; $basicTestObject = New-Object BasicTest C:\PS&gt; $basicTestObject.Multiply(5, 2) </code></pre>
9,002,403
How to add xml encoding <?xml version="1.0" encoding="UTF-8"?> to xml Output in SQL Server
<p>Probably a duplicate of unanswered. <a href="https://stackoverflow.com/questions/4184163/sql-server-2008-add-xml-encoding-to-xml-output">SQL Server 2008 - Add XML Declaration to XML Output</a></p> <p>Please let me know if this is possible. I read in some blogs </p> <p><a href="http://forums.asp.net/t/1455808.aspx/1" rel="noreferrer">http://forums.asp.net/t/1455808.aspx/1</a></p> <p><a href="http://www.devnewsgroups.net/group/microsoft.public.sqlserver.xml/topic60022.aspx" rel="noreferrer">http://www.devnewsgroups.net/group/microsoft.public.sqlserver.xml/topic60022.aspx</a></p> <p>But I couldn't understand why I can't do this.</p>
9,002,485
4
1
null
2012-01-25 12:04:38.463 UTC
1
2021-11-17 04:10:12.717 UTC
2018-12-04 22:56:52.63 UTC
null
577,765
null
591,785
null
1
22
sql-server|xml|sql-server-2008|utf-8|character-encoding
70,035
<p>You have to add it manually. SQL Server always stores xml internally as ucs-2 so it is impossible for SQL to generate it a utf-8 encoding header</p> <p>See <a href="http://technet.microsoft.com/en-us/library/ms187107%28SQL.90%29.aspx" rel="noreferrer">"Limitations of the xml Data Type"</a> on MSDN</p> <blockquote> <p>The XML declaration PI, for example, <code>&lt;?xml version='1.0'?&gt;</code>, is not preserved when storing XML data in an xml data type instance. This is by design. The XML declaration (<code>&lt;?xml ... ?&gt;</code>) and its attributes (version/encoding/stand-alone) are lost after data is converted to type xml. The XML declaration is treated as a directive to the XML parser. The XML data is stored internally as ucs-2.</p> </blockquote>
27,299,420
How to get rid of warning messages after installing R?
<p>The following output can be obtained after installation of R by homebrew and without in my OSX:</p> <pre><code>During startup - Warning messages: 1: Setting LC_CTYPE failed, using "C" 2: Setting LC_COLLATE failed, using "C" 3: Setting LC_TIME failed, using "C" 4: Setting LC_MESSAGES failed, using "C" 5: Setting LC_MONETARY failed, using "C" # this line is not occurring in OSX 10.10.1 Yosemite but other four are. </code></pre> <p>I found an existing <a href="https://stackoverflow.com/questions/9689104/installing-r-on-mac-warning-messages-setting-lc-ctype-failed-using-c">question</a> but the solution does not work for me. I do this</p> <ol> <li>Open Terminal</li> <li>Write or paste in: <code>defaults write org.R-project.R force.LANG en_US.UTF-8</code></li> <li>Close Terminal</li> <li>Start R</li> </ol> <p>and the warning messages are still shown. I guess this works when installing R using the package from the R project page.</p> <p>How to get rid of these warning messages after installation of R in OSX?</p>
29,571,000
5
4
null
2014-12-04 16:47:24.107 UTC
13
2019-08-28 11:43:48.827 UTC
2017-05-23 10:30:59.773 UTC
null
-1
null
218,471
null
1
23
r|macos|osx-yosemite
25,139
<p>For R this is what worked from the terminal</p> <pre><code>$ defaults write org.R-project.R force.LANG en_US.UTF-8 </code></pre> <p>See <a href="https://stackoverflow.com/questions/9689104/installing-r-on-mac-warning-messages-setting-lc-ctype-failed-using-c">Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using &quot;C&quot;</a></p>
19,730,067
Excel: How to create dynamic data validation list based on data table
<p>Imagine I'm writing a menu-planner in Excel for my kids (easier to describe than my actual problem) ...</p> <p>I have a list of available foods: apples, bananas, carrots, dates, eggs, fish, etc.</p> <p>I have a list of kids: John, Karen, Lional, Mike, etc.</p> <p>Then, I have a simple table that lists the food each kid likes: Under John's column there will be an 'x' against apples, bananas and fish, but blanks against the others.</p> <pre><code> J K L M --------------- a x x x b x x c x x x d x e x x f x </code></pre> <p>Now, in the main part of my menu-planner, I want to have some cells with data validation that allow me to select food for each kid, using the above 'likes' table:</p> <pre><code>Name Food A2 B2 </code></pre> <p>Cell A2 will contain data validation that gives an in-cell drop-down with all kids names (J, K, L, M) (that's easy - I can do that bit!)</p> <p>Cell B2 needs to contain a dynamically generated list of foods that are liked by the selected kid. So, if I select John in A2, then B2 list would be {a, b, f}. If I select Lionel, B2 list would be {a, b, c, e}. Clearly, as my kid's tastes change, I can just update my 'likes' table by adding/removing 'x', and the drop-downs in B2 will auto-update.</p> <p>How do I create the drop-down validation list for cell B2? (I'd prefer to do this without resorting to VBA please)</p>
19,732,641
4
1
null
2013-11-01 15:38:17.793 UTC
2
2016-07-12 10:41:16.007 UTC
null
null
null
null
1,317,258
null
1
5
excel|validation|dynamic
41,194
<p>I assumed that your data table is in range A1:E7.</p> <p><strong>Step 1. Create a list of choices for each kid</strong></p> <p>For each kid create a list with all their preferences listed (at the end of the list I added "-" as placeholders). Enter this formula in G2 and drag to range G2:J7:</p> <pre><code>=IF(G1="-";"-";IF(ISNA(OFFSET($A$1;IFERROR(MATCH(G1;$A$2:$A$7;0);0)+ MATCH("x";OFFSET(B$2;IFERROR(MATCH(G1;$A$2:$A$7;0);0);0;7;1);0);0;1;1)); "-";OFFSET($A$1;IFERROR(MATCH(G1;$A$2:$A$7;0);0)+MATCH("x";OFFSET(B$2; IFERROR(MATCH(G1;$A$2:$A$7;0);0);0;7;1);0);0;1;1))) </code></pre> <p>Also put kids names above data columns (G1:J1).</p> <p><strong>Step 2. Create conditional data validation</strong></p> <p>Given that your first data validation list (name) is in cell L2 and you've followed step 1, use this formula for data validation for food:</p> <pre><code>=OFFSET(F$2;0;MATCH(L2;$G$1:$J$1;0);6-COUNTIF(OFFSET(F$2:F$7;0; MATCH(L2;$G$1:$J$1;0));"-")) </code></pre> <p>This formula both excludes all empty choices ("-") in the list and gives the right list based on kid's name.</p> <hr> <p><strong>UPDATE. Alternative solution with INDEX/MATCH</strong></p> <p>OFFSET is a volatile formula (i.e. Excel recalculates it whenever there is any change in your workbook) so you might want to do this with INDEX instead. Here is the formula for my step 1 above:</p> <pre><code>=IF(G1="-";"-";IFERROR(INDEX($A$2:$A$7;IFERROR(MATCH(G1;$A$2:$A$7;0);0)+ MATCH("x";INDEX(B$2:B$7;IFERROR(MATCH(G1;$A$2:$A$7;0)+1;1);1):B$7;0);1);"-")) </code></pre> <p>As for the step two, it seems that formula for data validation gets recalculated only when you select the cell so OFFSET doesn't have volatility in data validation lists. As INDEX cannot return a range and Excel doesn't allow INDEX(..):INDEX(..) ranges for data validation, OFFSET is better for data validation lists.</p>
19,786,301
Python: Remove Exif info from images
<p>In order to reduce the size of images to be used in a website, I reduced the quality to 80-85%. This decreases the image size quite a bit, up to an extent.</p> <p>To reduce the size further without compromising the quality, my friend pointed out that raw images from cameras have a lot of metadata called Exif info. Since there is no need to retain this Exif info for images in a website, we can remove it. This will further reduce the size by 3-10 kB.</p> <p>But I'm not able to find an appropriate library to do this in my Python code. I have browsed through related questions and tried out some of the methods:</p> <p>Original image: <a href="http://mdb.ibcdn.com/8snmhp4sjd75vdr27gbadolc003i.jpg" rel="noreferrer">http://mdb.ibcdn.com/8snmhp4sjd75vdr27gbadolc003i.jpg</a></p> <ol> <li><p><a href="http://www.imagemagick.org/www/mogrify.html" rel="noreferrer">Mogrify</a></p> <pre><code>/usr/local/bin/mogrify -strip filename </code></pre> <p>Result: <a href="http://s23.postimg.org/aeaw5x7ez/8snmhp4sjd75vdr27gbadolc003i_mogrify.jpg" rel="noreferrer">http://s23.postimg.org/aeaw5x7ez/8snmhp4sjd75vdr27gbadolc003i_mogrify.jpg</a> This method reduces the size from 105 kB to 99.6 kB, but also changed the color quality.</p></li> <li><p><a href="https://exiftool.org/" rel="noreferrer">Exif-tool</a></p> <pre><code>exiftool -all= filename </code></pre> <p>Result: <a href="http://s22.postimg.org/aiq99o775/8snmhp4sjd75vdr27gbadolc003i_exiftool.jpg" rel="noreferrer">http://s22.postimg.org/aiq99o775/8snmhp4sjd75vdr27gbadolc003i_exiftool.jpg</a> This method reduces the size from 105 kB to 72.7 kB, but also changed the color quality.</p></li> <li><a href="https://stackoverflow.com/questions/765396/exif-manipulation-library-for-python/765403#765403">This answer</a> explains in detail how to manipulate the Exif info, but how do I use it to remove the info?</li> </ol> <p>Can anyone please help me remove all the extra metadata without changing the colours, dimensions, and other properties of an image?</p>
19,786,636
5
2
null
2013-11-05 10:05:28.153 UTC
9
2022-07-08 10:40:43.723 UTC
2019-12-11 20:16:30.73 UTC
null
3,525,475
null
952,112
null
1
17
python|image-processing|python-imaging-library|exif|exiftool
29,699
<p>You can try loading the image with the <a href="http://www.pythonware.com/products/pil/" rel="noreferrer">Python Image Lirbary (PIL)</a> and then save it again to a different file. That should remove the meta data.</p>
62,232,753
What are the differences between a pointer and a reference in Rust?
<p>A pointer <code>*</code> and a reference <code>&amp;</code> in Rust share the same representation (they both represent the memory address of a piece of data).</p> <p>What's the practical differences when writing code though?</p> <p>When porting C++ code to Rust, can they be replaced safely (C++ pointer --&gt; rust pointer, C++ reference --&gt; rust reference) ?</p>
62,234,967
2
2
null
2020-06-06 13:58:58.33 UTC
14
2022-05-14 18:14:04.287 UTC
2022-05-14 18:14:04.287 UTC
null
3,924,118
null
2,613,506
null
1
32
c++|pointers|rust|reference|porting
12,297
<p>Use references when you can, use pointers when you must. If you're not doing FFI or memory management beyond what the compiler can validate, you don't need to use pointers.</p> <p>Both references and pointers exist in two variants. There are shared references <code>&amp;</code> and mutable references <code>&amp;mut</code>. There are const pointers <code>*const</code> and mut pointers <code>*mut</code> (which map to const and non-const pointers in C). However, the semantics of references is completely different from the semantics of pointers.</p> <p>References are generic over a type and over a lifetime. Shared references are written <code>&amp;'a T</code> in long form (where <code>'a</code> and <code>T</code> are parameters). The lifetime parameter can be <a href="https://doc.rust-lang.org/nomicon/lifetime-elision.html" rel="noreferrer">omitted</a> in many situations. The lifetime parameter is used by the compiler to ensure that a reference doesn't live longer than the borrow is valid for.</p> <p>Pointers have no lifetime parameter. Therefore, the compiler cannot check that a particular pointer is valid to use. That's why dereferencing a pointer is considered <code>unsafe</code>.</p> <p>When you create a shared reference to an object, that <em>freezes</em> the object (i.e. the object becomes immutable while the shared reference exists), unless the object uses some form of interior mutability (e.g. using <code>Cell</code>, <code>RefCell</code>, <code>Mutex</code> or <code>RwLock</code>). However, when you have a const pointer to an object, that object may still change while the pointer is alive.</p> <p>When you have a mutable reference to an object, you are <em>guaranteed</em> to have exclusive access to that object through this reference. Any other way to access the object is either disabled temporarily or impossible to achieve. For example:</p> <pre><code>let mut x = 0; { let y = &amp;mut x; let z = &amp;mut x; // ERROR: x is already borrowed mutably *y = 1; // OK x = 2; // ERROR: x is borrowed } x = 3; // OK, y went out of scope </code></pre> <p>Mut pointers have no such guarantee.</p> <p>A reference cannot be null (much like C++ references). A pointer can be null.</p> <p>Pointers may contain any numerical value that could fit in a <code>usize</code>. Initializing a pointer is not <code>unsafe</code>; only dereferencing it is. On the other hand, producing an invalid reference is considered <a href="https://doc.rust-lang.org/reference/behavior-considered-undefined.html" rel="noreferrer">undefined behavior</a>, even if you never dereference it.</p> <p>If you have a <code>*const T</code>, you can freely cast it to a <code>*const U</code> or to a <code>*mut T</code> using <code>as</code>. You can't do that with references. However, you can cast a reference to a pointer using <code>as</code>, and you can &quot;upgrade&quot; a pointer to a reference by dereferencing the pointer (which, again, is <code>unsafe</code>) and then borrowing the place using <code>&amp;</code> or <code>&amp;mut</code>. For example:</p> <pre><code>use std::ffi::OsStr; use std::path::Path; pub fn os_str_to_path(s: &amp;OsStr) -&gt; &amp;Path { unsafe { &amp;*(s as *const OsStr as *const Path) } } </code></pre> <p>In C++, references are &quot;automatically dereferenced pointers&quot;. In Rust, you often still need to dereference references explicitly. The exception is when you use the <code>.</code> operator: if the left side is a reference, the compiler will automatically dereference it (recursively if necessary!). Pointers, however, are not automatically dereferenced. This means that if you want to dereference and access a field or a method, you need to write <code>(*pointer).field</code> or <code>(*pointer).method()</code>. There is no <code>-&gt;</code> operator in Rust.</p>
304,117
Data Modelling Advice for Blog Tagging system on Google App Engine
<p>Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is cheap, don't worry about data duplication" as you might in a normalized RDBMS. </p> <p>What I'd like to model is:</p> <p>A blog article which can be given 0-n tags. Many blog articles can share the same tag. When retrieving data would like to allow retrieval of all articles matching a tag. In many ways very similar to the approach taken here at stackoverflow.</p> <p>My normal mindset would be to create a many-to-may relationship between tags and blog articles. However, I'm thinking in the context of GAE that this would be expensive, although I have seen examples of it being done. </p> <p>Perhaps using a ListProperty containing each tag as part of the article entities, and a second data model to track tags as they're added and deleted? This way no need for any relationships and the ListProperty still allows queries where any list element matching will return results.</p> <p>Any suggestions on the most efficient way to approach this on GAE?</p>
307,727
4
0
2008-11-21 11:45:47.37 UTC
2008-11-20 01:56:32.207 UTC
12
2019-02-12 16:36:24.503 UTC
2019-02-12 16:36:24.503 UTC
null
643,848
null
26,241
null
1
8
python|google-app-engine|data-modeling
3,135
<p>Thanks to both of you for your suggestions. I've implemented (first iteration) as follows. Not sure if it's the best approach, but it's working.</p> <p>Class A = Articles. Has a StringListProperty which can be queried on it's list elements</p> <p>Class B = Tags. One entity per tag, also keeps a running count of the total number of articles using each tag.</p> <p>Data modifications to A are accompanied by maintenance work on B. Thinking that counts being pre-computed is a good approach in a read-heavy environment.</p>
1,019,070
Querying Core Data with Predicates - iPhone
<p>So I'm trying to fetch objects from core data. I have list of say 80 objects, and I want to be able to search through them using a UISearchBar. They are displayed in a table.</p> <p>Using the apple documentation on predicates, I've put the following code in one of the UISearchBar delegate methods.</p> <pre><code>- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { if (self.searchBar.text !=nil) { NSPredicate *predicate =[NSPredicate predicateWithFormat:@"name LIKE %@", self.searchBar.text]; [fetchedResultsController.fetchRequest setPredicate:predicate]; } else { NSPredicate *predicate =[NSPredicate predicateWithFormat:@"All"]; [fetchedResultsController.fetchRequest setPredicate:predicate]; } NSError *error = nil; if (![[self fetchedResultsController] performFetch:&amp;error]) { // Handle error NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); // Fail } [self.tableView reloadData]; [searchBar resignFirstResponder]; [_shadeView setAlpha:0.0f]; } </code></pre> <p>If I type in the search field an exact match to the name property of one of those objects, the search works, and it repopulates the table with a single cell with the name of the object. If I don't search the name exact, I end up with no results. </p> <p>Any Thoughts?</p>
1,019,211
4
2
null
2009-06-19 17:17:58.643 UTC
9
2012-04-20 08:09:16.037 UTC
2012-04-20 08:09:16.037 UTC
null
218,577
null
123,691
null
1
10
iphone
11,559
<p>It seems as though iPhone doesn't like the LIKE operator. I replaced it with 'contains[cd]' and it works the way I want it to.</p>
414,207
Best practices re sharing IDbConnection or connection string/factory in your .Net code
<p>I'm wondering what would be the best prectice regarding mainataining connections to the database in .Net application (ADO.NET but I guess the practice should be the same for any data layer). Should I create a database connection and propagate it throughout my application, or would it be better to just pass connection strings/factories and create a connection ad-hoc, when it is needed. </p> <p>As I understand perfomance hit is not signifcant with pooling and it allows me to recover from broken connections quite easily (just a new connection will be created) but then again a connection object is a nice, relatively high-level abstraction and creating a new connection for every operation (not SQL command, but application operation) generates additional, duplicated code and feels like a waste of time/resources(?).</p> <p>What do you think about these 2 cases, what are their cons/pros and which approach are you using in your real-life applications?</p> <p>Thanks</p>
414,330
4
0
null
2009-01-05 19:29:01.5 UTC
15
2009-12-22 17:27:15.17 UTC
null
null
null
Karol Kolenda
51,765
null
1
19
.net|database|connection-string
8,881
<p>I found myself needing to pass around a connection object so I could allow several business objects to save themselves to the database inside a single transaction.</p> <p>If each business object had to create its own SQLConnection to the database, the transaction would escalate to a distributed transaction and I wanted to avoid that. </p> <p>I did not like having to pass the SQLConnection object as a parameter to save an object, so I created a ConnectionManager that handles creating the SQLConnection object for me, tracking the use of the SQLConnection object, and disconnecting the SQLConnection object when not in use.</p> <p>Here is some code as an example of the ConnectionManager:</p> <pre><code>public class ConnectionManager: IDisposable { private ConnectionManager instance; [ThreadStatic] private static object lockObject; private static Object LockObject { get { if (lockObject == null) lockObject = new object(); return lockObject; } } [ThreadStatic] private static Dictionary&lt;string, ConnectionManager&gt; managers; private static Dictionary&lt;string, ConnectionManager&gt; Managers { get { if (managers == null) managers = new Dictionary&lt;string, ConnectionManager&gt;(); return managers; } } private SqlConnection connection = null; private int referenceCount; private string name; public static ConnectionManager GetManager(string connectionName) { lock (LockObject) { ConnectionManager mgr; if (Managers.ContainsKey(connectionName)) { mgr = Managers[connectionName]; } else { mgr = new ConnectionManager(connectionName); Managers.Add(connectionName, mgr); } mgr.AddRef(); return mgr; } } private ConnectionManager(string connectionName) { name = connectionName; connection = new SqlConnection(GetConnectionString(connectionName)); connection.Open(); } private string GetConnectionString(string connectionName) { string conString = Configuration.ConnectionString; return conString; } public SqlConnection Connection { get { return connection; } } private void AddRef() { referenceCount += 1; } private void DeRef() { lock (LockObject) { referenceCount -= 1; if (referenceCount == 0) { connection.Dispose(); Managers.Remove(name); } } } #region IDisposable Members public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { DeRef(); } } ~ConnectionManager() { Dispose(false); } #endregion } </code></pre> <p>Here is how I would use it from a business object:</p> <pre><code>public void Save() { using (ConnectionManager mrg = ConnectionManager.GetManager("SQLConnectionString") { using (SQLCommand cmd = new SQLCommand) { cmd.connection = mgr.Connection // More ADO Code Here } _childObject.Save(); //this child object follows the same pattern with a using ConnectionManager. } } </code></pre> <p>I save a business object and all of its children are saved as well using the same connection object. When the scope falls away from original parent, the using statement closes the connection.</p> <p>This is a pattern I learned from Rocky Lhotka in his CSLA framework. </p> <p>Keith</p>
487,108
How to suppress specific warnings in g++
<p>I want to suppress specific warnings from g++. I'm aware of the <code>-Wno-XXX</code> flag, but I'm looking for something more specific. I want <strong>some</strong> of the warnings in <code>-Weffc++</code>, but not <strong>all</strong> of them. Something like what you can do with lint - disable specific messages.</p> <p>Is there a built in way in gcc to do this? Do I have to write a wrapper script?</p>
487,520
4
2
null
2009-01-28 10:13:30.46 UTC
3
2021-07-15 08:56:05.16 UTC
2017-07-17 20:14:32.023 UTC
null
675,568
Gilad Naor
11,515
null
1
36
c++|gcc|g++
28,885
<p><s>Unfortunately, this feature isn't provided by g++.</s> In VC++, you could use <a href="http://msdn.microsoft.com/en-us/library/2c8f766e(VS.80).aspx" rel="nofollow noreferrer">#pragma warning</a> to disable some specific warnings. In gcc, the closest you can have is <a href="http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html" rel="nofollow noreferrer">diagnostic pragmas</a>, which let you enable/disable certain types of diagnostics for certain files or projects.</p> <p><em>Edit</em>: GCC supports pushing/popping warnings since 4.6.4 (see <a href="https://gcc.gnu.org/gcc-4.6/changes.html" rel="nofollow noreferrer">changelog</a>)</p>
937,491
Invalid syntax when using "print"?
<p>I'm learning Python and can't even write the first example:</p> <pre><code>print 2 ** 100 </code></pre> <p>this gives <code>SyntaxError: invalid syntax</code></p> <p>pointing at the 2.</p> <p>Why is this? I'm using version 3.1</p>
937,516
4
4
null
2009-06-02 00:51:52.457 UTC
20
2013-01-04 14:53:07.497 UTC
2011-12-11 00:20:26.053 UTC
user166390
null
null
115,717
null
1
117
python
320,499
<p>That is because in Python 3, they have replaced the <code>print</code> <em>statement</em> with the <code>print</code> <em>function</em>.</p> <p>The syntax is now more or less the same as before, but it requires parens:</p> <p>From the "<a href="http://docs.python.org/3.0/whatsnew/3.0.html" rel="noreferrer">what's new in python 3</a>" docs:</p> <pre><code>Old: print "The answer is", 2*2 New: print("The answer is", 2*2) Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline Old: print # Prints a newline New: print() # You must call the function! Old: print &gt;&gt;sys.stderr, "fatal error" New: print("fatal error", file=sys.stderr) Old: print (x, y) # prints repr((x, y)) New: print((x, y)) # Not the same as print(x, y)! </code></pre>
816,071
prototype based vs. class based inheritance
<p>In JavaScript, every object is at the same time an instance and a class. To do inheritance, you can use any object instance as a prototype.</p> <p>In Python, C++, etc.. there are classes, and instances, as separate concepts. In order to do inheritance, you have to use the base class to create a new class, which can then be used to produce derived instances.</p> <p>Why did JavaScript go in this direction (prototype-based object orientation)? what are the advantages (and disadvantages) of prototype-based OO with respect to traditional, class-based OO?</p>
816,075
4
3
null
2009-05-03 01:39:10.043 UTC
131
2022-07-21 17:22:24.93 UTC
2018-11-02 12:41:07.01 UTC
null
2,370,483
null
78,374
null
1
229
javascript|oop|inheritance|prototype-programming
78,444
<p>There are about a hundred terminology issues here, mostly built around someone (not you) trying to make their idea sound like The Best.</p> <p>All object oriented languages need to be able to deal with several concepts:</p> <ol> <li>encapsulation of data along with associated operations on the data, variously known as data members and member functions, or as data and methods, among other things.</li> <li>inheritance, the ability to say that these objects are just like that other set of objects EXCEPT for these changes</li> <li>polymorphism ("many shapes") in which an object decides for itself what methods are to be run, so that you can depend on the language to route your requests correctly.</li> </ol> <p>Now, as far as comparison:</p> <p>First thing is the whole "class" vs "prototype" question. The idea originally began in Simula, where with a class-based method each class represented a set of objects that shared the same state space (read "possible values") and the same operations, thereby forming an equivalence class. If you look back at Smalltalk, since you can open a class and add methods, this is effectively the same as what you can do in Javascript.</p> <p>Later OO languages wanted to be able to use static type checking, so we got the notion of a fixed class set at compile time. In the open-class version, you had more flexibility; in the newer version, you had the ability to check some kinds of correctness at the compiler that would otherwise have required testing.</p> <p>In a "class-based" language, that copying happens at compile time. In a prototype language, the operations are stored in the prototype data structure, which is copied and modified at run time. Abstractly, though, a class is still the equivalence class of all objects that share the same state space and methods. When you add a method to the prototype, you're effectively making an element of a new equivalence class.</p> <p>Now, why do that? primarily because it makes for a simple, logical, elegant mechanism at run time. now, to create a new object, <em>or</em> to create a new class, you simply have to perform a deep copy, copying all the data and the prototype data structure. You get inheritance and polymorphism more or less for free then: method lookup <em>always</em> consists of asking a dictionary for a method implementation by name.</p> <p>The reason that ended up in Javascript/ECMA script is basically that when we were getting started with this 10 years ago, we were dealing with much less powerful computers and much less sophisticated browsers. Choosing the prototype-based method meant the interpreter could be very simple while preserving the desirable properties of object orientation.</p>
307,696
Does Microsoft SkyDrive have an API?
<p>So with the <a href="http://lifehacker.com/5094242/skydrive-will-upgrade-to-25gb-of-online-storage" rel="nofollow noreferrer">recent news that Microsoft Skydrive is going to get bumped to 25GB of storage</a> per account, does anyone know if SkyDrive has an API? </p> <p>(And if so, where are the docs?)</p>
7,638,882
1
1
null
2008-11-21 03:04:58.06 UTC
9
2015-12-14 19:20:51.087 UTC
2015-01-12 14:24:17.827 UTC
null
993,547
Dan
19,020
null
1
35
api|documentation|storage|onedrive
31,736
<p>SkyDrive (renamed 'OneDrive') has an official API. Details can be found by going to <a href="https://dev.onedrive.com/" rel="nofollow noreferrer">The OneDrive Developer center</a>. </p> <p>You can also find code samples for working with the OneDrive API, along with source code for the SDKs, <a href="https://github.com/OneDrive" rel="nofollow noreferrer">on GitHub</a></p>
55,934,490
Why are await and async valid variable names?
<p>I was experimenting with how <code>/</code> is interpreted when around different keywords and operators, and found that the following syntax is perfectly legal:</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>// awaiting something that isn't a Promise is fine, it's just strange to do: const foo = await /barbaz/ myFn()</code></pre> </div> </div> </p> <p>Error:</p> <blockquote> <p>Uncaught ReferenceError: await is not defined</p> </blockquote> <p>It looks like it tries to parse the <code>await</code> as a <em>variable name</em>..? I was expecting</p> <blockquote> <p>await is only valid in async function</p> </blockquote> <p>or maybe something like</p> <blockquote> <p>Unexpected token await</p> </blockquote> <p>To my horror, you can even assign things to it:</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>const await = 'Wait, this actually works?'; console.log(await);</code></pre> </div> </div> </p> <p>Shouldn't something so obviously wrong cause a syntax error, as it does with <code>let</code>, <code>finally</code>, <code>break</code>, etc? Why is this allowed, and what the heck is going on in the first snippet?</p>
55,934,491
1
0
null
2019-05-01 09:56:54.37 UTC
14
2020-03-24 05:35:58.65 UTC
null
null
null
null
9,515,207
null
1
52
javascript|async-await|specifications|language-design|ecmascript-2017
5,067
<p>Reserved keywords cannot be used as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Reserved_word_usage" rel="noreferrer">identifiers (variable names)</a>. Unlike most other special Javascript words (like those listed in the question, <code>let</code>, <code>finally</code>, ...), <code>await</code> is <em>not</em> a reserved keyword, so using it as a variable name does not throw a SyntaxError. Why wasn't it made into a reserved keyword when the new syntax came out?</p> <h1>Backwards compatibility</h1> <p>Back in 2011, when ES5 was still a relatively new thing, code that used <code>await</code> (and <code>async</code>) as variable names was perfectly valid, so you may have seen something like this on a couple sites:</p> <pre><code>function timeout(ms) { var await = $.Deferred(); setTimeout(await.resolve, ms); return await.promise(); }; </code></pre> <p>The choice of that variable name may seem odd, but there was nothing <em>wrong</em> with it. <code>await</code> and <code>async</code> have never been reserved keywords - if the writers of the ES2017 specification made <code>await</code> into a reserved keyword, and browsers implemented that change, people visiting those older sites on newer browsers would not be able to use those sites; they would likely be broken.</p> <p>So perhaps if they were made into reserved keywords, a <em>few</em> sites which chose a peculiar variable name wouldn't work properly - why should the existence of those sites permanently affect the future evolution of ECMAscript and result in confusing code like in the question?</p> <p><strong>Because browsers will refuse to implement a feature which breaks existing sites.</strong> If a user finds that a site does not work on one browser, but works on another, that will incentivize them to switch browsers - the maker of the first browser would not want that, because that would mean less market share for them, even if it's a feature which makes the language more consistent and understandable. In addition, the editors of the specification do not want to add something that will never be implemented (or will only be implemented sporadically), because then the specification would lose some of its status as a standard - contrary to its main goal.</p> <p>You could see these interactions in action with <a href="https://github.com/tc39/proposal-flatMap/pull/56" rel="noreferrer"><code>Array.prototype.flatten</code></a> and <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1075059" rel="noreferrer"><code>Array.prototype.contains</code></a> - when browsers started shipping them, it was found that they broke a few existing sites due to name conflicts, so the browsers backed out of the implementation, and the specification had to be tweaked (the methods were renamed to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat" rel="noreferrer"><code>.flat</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes" rel="noreferrer"><code>.includes</code></a>).</p> <hr /> <p>There actually <em>is</em> a situation in which <code>await</code> cannot be used as an identifier, which is inside of ES6 modules:</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>&lt;script type="module"&gt; const await = 'Does it work?'; &lt;/script&gt;</code></pre> </div> </div> </p> <p>This is because while ES6 (ES2015) modules were being figured out, <code>async</code>/<code>await</code> was already on the horizon (<a href="https://github.com/tc39/ecmascript-asyncawait/commit/97b5cbee1594b2861f3e9f4771beb39747ba064c" rel="noreferrer">initial commit for the <code>async</code>/<code>await</code> proposal</a> can be seen at the beginning of 2014), so while designing modules, <code>await</code> could be made a reserved keyword in preparation for the future, without breaking any existing sites.</p> <hr /> <p>With regards to the first snippet in the question:</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>const foo = await /barbaz/ myFn()</code></pre> </div> </div> </p> <p>This is syntactically valid because <code>await</code> is a valid variable name outside of <code>async</code> functions, and the interpreter thinks you're trying to <em>divide</em>, rather than use a regular expression:</p> <pre><code>const foo = await / barbaz / myFn() </code></pre> <p>Not relying on Automatic Semicolon Insertion would have identified the problem earlier, because the last <code>/</code> could not have been interpreted as division:</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>const foo = await /barbaz/; myFn();</code></pre> </div> </div> </p> <p>This exact somewhat-ambiguous situation was actually specifically brought up in a <a href="https://github.com/rwaldron/tc39-notes/blob/master/es7/2016-07/jul-28.md#10iv-async-functions" rel="noreferrer">TC39 meeting</a> on <code>async</code>/<code>await</code>:</p> <blockquote> <p><strong>YK:</strong> What are you worried about?</p> <p><strong>WH:</strong> Ambiguities on code sequences that start with await/ and then get interpreted in diverging ways (due to the await-as-identifier vs await-as-operator distinction that flips the / between division and starting a regexp) by cover grammars vs. real grammars. It's a potential bug farm.</p> </blockquote>
57,667,198
Typescript Error: type 'string' can't be used to index type X
<p>I have a simple code:</p> <pre><code>const allTypes = { jpg: true, gif: true, png: true, mp4: true }; const mediaType = url.substring(url.lastIndexOf('.') + 1).toLowerCase(); return Boolean(allTypes[mediaType]); </code></pre> <p>TypeScript is complaining:</p> <pre><code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ jpg: boolean; gif: boolean; png: boolean; mp4: boolean; }'. No index signature with a parameter of type 'string' was found on type '{ jpg: boolean; gif: boolean; png: boolean; mp4: boolean; }'. TS7 </code></pre> <p>I think I need to treat <code>mediaType</code> as <code>keyof typeof allTypes</code>, but don't know how.</p> <p>For sake of completion, the complete code is:</p> <pre><code>// these are all the types of media we support const allTypes = { jpg: true, gif: true, png: true, mp4: true }; const MediaGallery = () =&gt; { const classes = useStyles(); const [ filters, setFilters ] = useState(allTypes); return ( &lt;div className={classes.root}&gt; {mediaList .filter(({ url }) =&gt; { const type = url.substring(url.lastIndexOf('.') + 1).toLowerCase(); return Boolean(filters[type]); }) .map(({ url, caption, hash }) =&gt; &lt;Media url={url} caption={caption} key={hash} /&gt;)} &lt;FiltersPanel onFiltersChanged={(newFilters: any) =&gt; setFilters(newFilters)} /&gt; &lt;/div&gt; ); }; </code></pre>
57,667,278
2
0
null
2019-08-27 03:03:30.883 UTC
6
2022-08-01 21:51:52.26 UTC
2022-08-01 21:51:52.26 UTC
null
472,495
null
302,351
null
1
34
typescript
31,785
<p>All you need is to define the <strong>index signature</strong>:</p> <pre class="lang-js prettyprint-override"><code>const allTypes: {[key: string]: boolean} = { jpg: true, gif: true, png: true, mp4: true }; </code></pre> <h1><a href="https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types" rel="noreferrer">Indexable Types</a></h1> <blockquote> <p>Similarly to how we can use interfaces to describe function types, we can also describe types that we can “index into” like <code>a[10]</code>, or <code>ageMap[&quot;daniel&quot;]</code>. Indexable types have an <em>index signature</em> that describes the types we can use to index into the object, along with the corresponding return types when indexing. Let’s take an example:</p> <pre><code>interface StringArray { [index: number]: string; } let myArray: StringArray; myArray = [&quot;Bob&quot;, &quot;Fred&quot;]; let myStr: string = myArray[0]; </code></pre> <p>Above, we have a <code>StringArray</code> interface that has an index signature. This index signature states that when a <code>StringArray</code> is indexed with a <code>number</code>, it will return a <code>string</code>.</p> </blockquote> <h1><a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type" rel="noreferrer">Utility type: <code>Record&lt;Keys, Type&gt;</code></a></h1> <p>Another solution is to use the TypeScript utility type <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type" rel="noreferrer"><code>Record&lt;Keys, Type&gt;</code></a>:</p> <blockquote> <p>Constructs an object type whose property keys are <code>Keys</code> and whose property values are <code>Type</code>. This utility can be used to map the properties of a type to another type.</p> </blockquote> <pre class="lang-js prettyprint-override"><code>const allTypes: Record&lt;string, boolean&gt; = { jpg: true, gif: true, png: true, mp4: true }; for (const key of Object.keys(allTypes)) { console.log(`${key}: ${allTypes[key]}`); } </code></pre>
2,536,194
android image exif reader 3rd party api
<p>Is there any 3rd part api for android to read exif tags from image which support api level starting from 1.5.</p>
2,571,105
2
1
null
2010-03-29 06:46:48.277 UTC
9
2016-05-25 10:32:10.703 UTC
null
null
null
null
216,431
null
1
5
android|libexif
9,799
<p>The <a href="http://www.drewnoakes.com/code/exif/" rel="nofollow noreferrer">metadata extraction library</a> by Drew Noakes works well for extracting EXIF tags on earlier Android platform versions, <strike>with a slight modification</strike>. I am using it on Android 1.6 to extract tags from JPEG images.</p> <blockquote> <p>NOTE: Newer versions of <a href="https://drewnoakes.com/code/exif/" rel="nofollow noreferrer">metadata-extractor</a> work directly on Android without modification.</p> </blockquote> <p><strike>You will need to <a href="http://www.drewnoakes.com/code/exif/releases/" rel="nofollow noreferrer">download</a> and build the source code yourself, and package it with your app. (I'm using release 2.3.1.) Make the following changes to <code>com.drew.imaging.jpeg.JpegMetadataReader</code>:</p> <ul> <li><p>Remove the following import statement: </p> <p><code>import com.sun.image.codec.jpeg.JPEGDecodeParam;</code></p></li> <li><p>Delete the following method (which you won't need on Android):</p> <p><code>public static Metadata readMetadata(JPEGDecodeParam decodeParam) { ... }</code></p></li> </ul> <p>Remove the <code>com.drew.metadata.SampleUsage</code> class, which references the method deleted above. Also remove all of the test packages. </strike></p> <p>That's all there is to it. Here's an example of using the <code>JpegMetadataReader</code> to extract a date-time tag from a JPEG image stored on the SD card:</p> <pre><code>import com.drew.imaging.jpeg.JpegMetadataReader; import com.drew.metadata.Directory; import com.drew.metadata.Metadata; import com.drew.metadata.exif.ExifDirectory; // other imports and class definition removed for brevity public static Date extractExifDateTime(String imagePath) { Log.d("exif", "Attempting to extract EXIF date/time from image at " + imagePath); Date datetime = new Date(0); // or initialize to null, if you prefer try { Metadata metadata = JpegMetadataReader.readMetadata(new File(imagePath)); Directory exifDirectory = metadata.getDirectory(ExifDirectory.class); // these are listed in order of preference int[] datetimeTags = new int[] { ExifDirectory.TAG_DATETIME_ORIGINAL, ExifDirectory.TAG_DATETIME, ExifDirectory.TAG_DATETIME_DIGITIZED }; int datetimeTag = -1; for (int tag : datetimeTags) { if (exifDirectory.containsTag(tag)) { datetimeTag = tag; break; } } if (datetimeTag != -1) { Log.d("exif", "Using tag " + exifDirectory.getTagName(datetimeTag) + " for timestamp"); SimpleDateFormat exifDatetimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); datetime = exifDatetimeFormat.parse(exifDirectory.getString(datetimeTag)); } else { Log.d("exif", "No date/time tags were found"); } } catch (Exception e) { Log.w("exif", "Unable to extract EXIF metadata from image at " + imagePath, e); } return datetime; } </code></pre>
2,777,831
How can I get RubyGems 1.3.6 on Ubuntu 10.4
<p>I've just installed a new vm (VirtualBox) with Ubuntu 10.4 and Ruby1.9.1. I've got the package for RUbyGems1.9.1 but when I do gem --version I still get 1.3.5. </p>
2,778,084
2
0
null
2010-05-06 01:19:58.693 UTC
21
2013-02-14 20:40:48.49 UTC
null
null
null
null
2,636,656
null
1
54
rubygems
21,577
<p>I got it working using</p> <pre><code>gem install rubygems-update cd /var/lib/gems/1.9.1/bin sudo ./update_rubygems </code></pre>
39,624,675
add Shadow on UIView using swift 3
<p>prior swift 3 i was adding shadow in my UIView like this :</p> <pre><code>//toolbar is an UIToolbar (UIView) toolbar.layer.masksToBounds = false toolbar.layer.shadowOffset = CGSize(width: -1, height: 1) toolbar.layer.shadowRadius = 1 toolbar.layer.shadowOpacity = 0.5 </code></pre> <p>but the above code is not working in swift 3 , instead of shadow my whole View's color is turned to ugly gray</p> <p>anyone knows how can we add shadow in swift 3 ?</p>
40,720,122
20
0
null
2016-09-21 19:08:47.57 UTC
29
2022-09-10 12:23:14.477 UTC
2018-12-26 22:01:45.067 UTC
null
10,154,634
null
5,828,248
null
1
84
ios|swift3
179,314
<p><strong>CODE SNIPPET:</strong> </p> <pre><code>extension UIView { // OUTPUT 1 func dropShadow(scale: Bool = true) { layer.masksToBounds = false layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.5 layer.shadowOffset = CGSize(width: -1, height: 1) layer.shadowRadius = 1 layer.shadowPath = UIBezierPath(rect: bounds).cgPath layer.shouldRasterize = true layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } // OUTPUT 2 func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) { layer.masksToBounds = false layer.shadowColor = color.cgColor layer.shadowOpacity = opacity layer.shadowOffset = offSet layer.shadowRadius = radius layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath layer.shouldRasterize = true layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } } </code></pre> <blockquote> <p><strong>NOTE</strong>: If you don't pass <em>any</em> parameter to that function, then the scale argument will be true by default. You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function. </p> </blockquote> <p><strong>OUTPUT 1:</strong></p> <pre><code>shadowView.dropShadow() </code></pre> <p><a href="https://i.stack.imgur.com/IQ51j.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IQ51j.png" alt="enter image description here"></a></p> <p><strong>OUTPUT 2:</strong></p> <pre><code>shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true) </code></pre> <p><a href="https://i.stack.imgur.com/igPWX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/igPWX.png" alt="enter image description here"></a></p> <blockquote> <p><code>layer.shouldRasterize = true</code> will make the shadow static and cause a shadow for the initial state of the <code>UIView</code>. So I would recommend not to use <code>layer.shouldRasterize = true</code> in dynamic layouts like view inside a <code>UITableViewCell</code>.</p> </blockquote>
47,336,825
Benefit of using forEachOrdered with Parallel streams
<p>The official Oracle documentation says:</p> <blockquote> <p>Note that you may lose the benefits of parallelism if you use operations like forEachOrdered with parallel streams. <a href="https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html" rel="noreferrer">Oracle - Parallelism</a></p> </blockquote> <p>Why would anyone use <code>forEachOrdered</code> with parallel stream if we are losing parallelism?</p>
47,337,690
3
0
null
2017-11-16 18:33:26.077 UTC
12
2018-06-22 22:25:25.34 UTC
2018-06-22 22:25:25.34 UTC
null
814,438
null
1,478,852
null
1
17
java|java-8
3,863
<p>depending on the <em>situation</em>, one does not lose <em>all</em> the benefits of parallelism by using <code>ForEachOrdered</code>.</p> <p>Assume that we have something as such:</p> <pre><code>stringList.parallelStream().map(String::toUpperCase) .forEachOrdered(System.out::println); </code></pre> <p>In this case, we can guarantee that the <code>ForEachOrdered</code> terminal operation will print out the strings in uppercase in the encounter order <em>but</em> we should not assume that the elements will be passed to the <code>map</code> intermediate operation in the same order they were picked for processing. The <code>map</code> operation will be executed by multiple threads concurrently. So one may still benefit from parallelism but it's just that we’re not leveraging the full potential of parallelism. To conclude, we <em>should</em> use <code>ForEachOrdered</code> when it matters to perform an action in the encounter order of the stream.</p> <p><strong>edit following your comment:</strong></p> <blockquote> <p>What happens when you skip <code>map</code> operation? I am more interested in <code>forEachOrdered</code> right after <code>parallelStream()</code></p> </blockquote> <p>if you're referring to something as in:</p> <pre><code> stringList.parallelStream().forEachOrdered(action); </code></pre> <p>there is <em>no benefit</em> in doing such thing and I doubt that's what the designers had in mind when they decided to create the method. in such case, it would make more sense to do:</p> <pre><code>stringList.stream().forEach(action); </code></pre> <p>to extend on your question <em>"Why would anyone use forEachOrdered with parallel stream if we are losing parallelism"</em>, say you wanted to perform an action on each element with respect to the streams encounter order; in such case <em>you will need to use</em> <code>forEachOrdered</code> as the <code>forEach</code> terminal operation is <em>non deterministic</em> when used in parallel hence there is one version for <em>sequential</em> streams and one <em>specifically</em> for <em>parallel</em> streams.</p>
47,506,092
python requests.get always get 404
<p>I would like to try send requests.get to this <a href="https://www.591.com.tw/" rel="noreferrer">website</a>:</p> <pre><code>requests.get('https://rent.591.com.tw') </code></pre> <p>and I always get </p> <pre><code>&lt;Response [404]&gt; </code></pre> <p>I knew this is a common problem and tried different way but still failed. but all of other website is ok.</p> <p>any suggestion?</p>
47,506,205
3
0
null
2017-11-27 07:51:40.477 UTC
9
2021-08-15 15:51:12.687 UTC
2017-11-27 08:01:40.93 UTC
null
100,297
null
5,954,558
null
1
13
python|python-requests
38,954
<p>Webservers are black boxes. They are permitted to return any valid HTTP response, based on your request, the time of day, the phase of the moon, or any other criteria they pick. If another HTTP client gets a different response, consistently, try to figure out what the differences are in the request that Python sends and the request the other client sends.</p> <p>That means you need to:</p> <ul> <li>Record all aspects of the working request</li> <li>Record all aspects of the failing request</li> <li>Try out what changes you can make to make the failing request more like the working request, and minimise those changes.</li> </ul> <p>I usually point my requests to a <a href="http://httpbin.org" rel="noreferrer">http://httpbin.org</a> endpoint, have it record the request, and then experiment.</p> <p>For <code>requests</code>, there are several headers that are set automatically, and many of these you would not normally expect to have to change:</p> <ul> <li><code>Host</code>; this <em>must</em> be set to the hostname you are contacting, so that it can properly multi-host different sites. <code>requests</code> sets this one.</li> <li><code>Content-Length</code> and <code>Content-Type</code>, for POST requests, are usually set from the arguments you pass to <code>requests</code>. If these don't match, alter the arguments you pass in to <code>requests</code> (but watch out with <code>multipart/*</code> requests, which use a generated boundary recorded in the <code>Content-Type</code> header; leave generating that to <code>requests</code>).</li> <li><code>Connection</code>: leave this to the client to manage</li> <li><code>Cookies</code>: these are often set on an initial GET request, or after first logging into the site. Make sure you capture cookies with a <a href="https://requests.readthedocs.io/en/latest/user/advanced/#session-objects" rel="noreferrer"><code>requests.Session()</code> object</a> and that you are logged in (supplied credentials the same way the browser did).</li> </ul> <p>Everything else is fair game but if <code>requests</code> has set a default value, then more often than not those defaults are not the issue. That said, I usually start with the User-Agent header and work my way up from there.</p> <p>In this case, the site is filtering on the user agent, it looks like they are blacklisting <code>Python</code>, setting it to <em>almost any other value</em> already works:</p> <pre><code>&gt;&gt;&gt; requests.get('https://rent.591.com.tw', headers={'User-Agent': 'Custom'}) &lt;Response [200]&gt; </code></pre> <p>Next, you need to take into account that <code>requests</code> is <em>not a browser</em>. <code>requests</code> is only a HTTP client, a browser does much, much more. A browser parses HTML for additional resources such as images, fonts, styling and scripts, loads those additional resources too, and executes scripts. Scripts can then alter what the browser displays and load additional resources. If your <code>requests</code> results don't match what you see in the browser, but the <em>initial request the browser makes matches</em>, then you'll need to figure out what other resources the browser has loaded and make additional requests with <code>requests</code> as needed. If all else fails, use a project like <a href="https://requests.readthedocs.io/projects/requests-html/" rel="noreferrer"><code>requests-html</code></a>, which lets you run a URL through an actual, headless Chromium browser.</p> <p>The site you are trying to contact makes an additional AJAX request to <code>https://rent.591.com.tw/home/search/rsList?is_new_list=1&amp;type=1&amp;kind=0&amp;searchtype=1&amp;region=1</code>, take that into account if you are trying to scrape data from this site.</p> <p>Next, well-built sites will use security best-practices such as <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery#Prevention" rel="noreferrer">CSRF tokens</a>, which require you to make requests in the right order (e.g. a GET request to retrieve a form before a POST to the handler) and handle cookies or otherwise extract the extra information a server expects to be passed from one request to another.</p> <p>Last but not least, if a site is blocking scripts from making requests, they probably are either trying to enforce terms of service that prohibit scraping, or because they have an API they rather have you use. Check for either, and take into consideration that you might be blocked more effectively if you continue to scrape the site anyway.</p>
29,862,681
Java Spring multiple ApplicationContext
<p>The definition of the spring <code>ApplicationContext</code> is very ambiguous, I almost finish a whole book of tutorial but still cannot understand what is the <code>ApplicationContext</code> stand for.</p> <p>According the Spring API, <code>ApplicationContext</code> is:</p> <blockquote> <ul> <li><p>Central interface to provide configuration for an application. This is read-only while the application is running, but may be reloaded if the implementation supports this.</p></li> <li><p>The root interface for accessing a Spring bean container. This is the basic client view of a bean container.</p></li> </ul> </blockquote> <p>From above, my questions are:</p> <p>1) I keep seeing the book mentioned "container", what is the container refer to? One container does it mean one java process? or one container refer to one <code>ApplicationContext</code> object?</p> <p>2) If i instantiate two <code>ApplicationContext</code> in one java application (both in <code>main</code> body), are these two interfaces to one central container? Or two separate instances? See the code below, what is the difference between <code>context1</code> and <code>context2</code>? If there is a Singleton in <code>Beans.xml</code>, it is invoked by <code>context1</code> and <code>context2</code>, are they two separated instances or the same instance?</p> <pre><code>ApplicationContext context1 = new ClassPathXmlApplicationContext("Beans.xml"); ApplicationContext context2 = new ClassPathXmlApplicationContext("Beans.xml"); </code></pre>
29,862,798
7
0
null
2015-04-25 08:08:42.203 UTC
30
2021-06-12 12:56:11.25 UTC
2017-11-22 03:38:10.227 UTC
null
1,542,363
null
1,542,363
null
1
37
java|spring|web-applications|dependency-injection
51,348
<p>By container they refer to the core spring <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html" rel="noreferrer">Inversion of Control container</a>. The container provides a way to initialize/bootstrap your application (loading the configuration in xml files or annotations), through use of <a href="https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful">reflection</a>, and to manage the lifecycle of Java objects, which are called <em>beans</em> or <em>managed objects</em>. </p> <p>During this initial phase, you do not have (normally, yet it is possible) control in your application, instead you will get a completely initialized state for the application when the bootstrapping is done (or nothing, in case it fails). </p> <p>It is a replacement, or possibly an addition, to what is called an <em>EJB3 container</em>; yet, the spring provided one fails to adhere to the EJB defined standard. Historically, adoption of EJB has been limited by the complexity of that specification, with spring being a newly created project for having EJB3 comparable features running on a J2SE jvm and without an EJB container, and with much easier configuration.</p> <p><code>ApplicationContext</code> (as an <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html" rel="noreferrer">interface</a>, and by the direct implementation flavours) is the mean of implementing this IoC container, as opposed to the <code>BeanFactory</code>, which is now (a sparsely used and) <a href="https://stackoverflow.com/questions/243385/new-to-spring-beanfactory-vs-applicationcontext?rq=1">more direct way</a> of managing beans, which by the way provides the base implementation features for the ApplicationContext. </p> <p>As per your second question, you can have multiple instances of ApplicationContexts, in that case, they will be completely isolated, each with its own configuration.</p>
30,244,910
How to pivot Spark DataFrame?
<p>I am starting to use Spark DataFrames and I need to be able to pivot the data to create multiple columns out of 1 column with multiple rows. There is built in functionality for that in Scalding and I believe in Pandas in Python, but I can't find anything for the new Spark Dataframe.</p> <p>I assume I can write custom function of some sort that will do this but I'm not even sure how to start, especially since I am a novice with Spark. If anyone knows how to do this with built-in functionality or suggestions for how to write something in Scala, it is greatly appreciated.</p>
35,676,755
10
1
null
2015-05-14 18:42:41.827 UTC
40
2021-12-23 20:31:32.177 UTC
2021-12-23 20:31:32.177 UTC
null
1,386,551
null
3,919,958
null
1
84
dataframe|apache-spark|pyspark|apache-spark-sql|pivot
104,448
<p><a href="https://stackoverflow.com/a/33799008/1560062">As mentioned</a> by <a href="https://stackoverflow.com/users/2000823/user2000823">David Anderson</a> Spark provides <code>pivot</code> function since version 1.6. General syntax looks as follows:</p> <pre><code>df .groupBy(grouping_columns) .pivot(pivot_column, [values]) .agg(aggregate_expressions) </code></pre> <p>Usage examples using <a href="https://github.com/hadley/nycflights13" rel="noreferrer"><code>nycflights13</code></a> and <code>csv</code> format:</p> <p><strong>Python</strong>:</p> <pre class="lang-py prettyprint-override"><code>from pyspark.sql.functions import avg flights = (sqlContext .read .format("csv") .options(inferSchema="true", header="true") .load("flights.csv") .na.drop()) flights.registerTempTable("flights") sqlContext.cacheTable("flights") gexprs = ("origin", "dest", "carrier") aggexpr = avg("arr_delay") flights.count() ## 336776 %timeit -n10 flights.groupBy(*gexprs ).pivot("hour").agg(aggexpr).count() ## 10 loops, best of 3: 1.03 s per loop </code></pre> <p><strong>Scala</strong>:</p> <pre class="lang-scala prettyprint-override"><code>val flights = sqlContext .read .format("csv") .options(Map("inferSchema" -&gt; "true", "header" -&gt; "true")) .load("flights.csv") flights .groupBy($"origin", $"dest", $"carrier") .pivot("hour") .agg(avg($"arr_delay")) </code></pre> <p><strong>Java</strong>:</p> <pre><code>import static org.apache.spark.sql.functions.*; import org.apache.spark.sql.*; Dataset&lt;Row&gt; df = spark.read().format("csv") .option("inferSchema", "true") .option("header", "true") .load("flights.csv"); df.groupBy(col("origin"), col("dest"), col("carrier")) .pivot("hour") .agg(avg(col("arr_delay"))); </code></pre> <p><strong>R / SparkR</strong>:</p> <pre class="lang-r prettyprint-override"><code>library(magrittr) flights &lt;- read.df("flights.csv", source="csv", header=TRUE, inferSchema=TRUE) flights %&gt;% groupBy("origin", "dest", "carrier") %&gt;% pivot("hour") %&gt;% agg(avg(column("arr_delay"))) </code></pre> <p><strong>R / sparklyr</strong></p> <pre><code>library(dplyr) flights &lt;- spark_read_csv(sc, "flights", "flights.csv") avg.arr.delay &lt;- function(gdf) { expr &lt;- invoke_static( sc, "org.apache.spark.sql.functions", "avg", "arr_delay" ) gdf %&gt;% invoke("agg", expr, list()) } flights %&gt;% sdf_pivot(origin + dest + carrier ~ hour, fun.aggregate=avg.arr.delay) </code></pre> <p><strong>SQL</strong>:</p> <p>Note that PIVOT keyword in Spark SQL is supported starting from version 2.4. </p> <pre><code>CREATE TEMPORARY VIEW flights USING csv OPTIONS (header 'true', path 'flights.csv', inferSchema 'true') ; SELECT * FROM ( SELECT origin, dest, carrier, arr_delay, hour FROM flights ) PIVOT ( avg(arr_delay) FOR hour IN (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23) ); </code></pre> <p><strong>Example data</strong>:</p> <pre><code>"year","month","day","dep_time","sched_dep_time","dep_delay","arr_time","sched_arr_time","arr_delay","carrier","flight","tailnum","origin","dest","air_time","distance","hour","minute","time_hour" 2013,1,1,517,515,2,830,819,11,"UA",1545,"N14228","EWR","IAH",227,1400,5,15,2013-01-01 05:00:00 2013,1,1,533,529,4,850,830,20,"UA",1714,"N24211","LGA","IAH",227,1416,5,29,2013-01-01 05:00:00 2013,1,1,542,540,2,923,850,33,"AA",1141,"N619AA","JFK","MIA",160,1089,5,40,2013-01-01 05:00:00 2013,1,1,544,545,-1,1004,1022,-18,"B6",725,"N804JB","JFK","BQN",183,1576,5,45,2013-01-01 05:00:00 2013,1,1,554,600,-6,812,837,-25,"DL",461,"N668DN","LGA","ATL",116,762,6,0,2013-01-01 06:00:00 2013,1,1,554,558,-4,740,728,12,"UA",1696,"N39463","EWR","ORD",150,719,5,58,2013-01-01 05:00:00 2013,1,1,555,600,-5,913,854,19,"B6",507,"N516JB","EWR","FLL",158,1065,6,0,2013-01-01 06:00:00 2013,1,1,557,600,-3,709,723,-14,"EV",5708,"N829AS","LGA","IAD",53,229,6,0,2013-01-01 06:00:00 2013,1,1,557,600,-3,838,846,-8,"B6",79,"N593JB","JFK","MCO",140,944,6,0,2013-01-01 06:00:00 2013,1,1,558,600,-2,753,745,8,"AA",301,"N3ALAA","LGA","ORD",138,733,6,0,2013-01-01 06:00:00 </code></pre> <p><strong>Performance considerations</strong>:</p> <p>Generally speaking pivoting is an expensive operation. </p> <ul> <li><p>if you can, try to provide <code>values</code> list, as this avoids an extra hit to compute the uniques:</p> <pre class="lang-py prettyprint-override"><code>vs = list(range(25)) %timeit -n10 flights.groupBy(*gexprs ).pivot("hour", vs).agg(aggexpr).count() ## 10 loops, best of 3: 392 ms per loop </code></pre></li> <li><p><a href="https://stackoverflow.com/q/35427812/1560062">in some cases it proved to be beneficial</a> (likely no longer worth the effort in <a href="https://issues.apache.org/jira/browse/SPARK-13749" rel="noreferrer">2.0 or later</a>) to <code>repartition</code> and / or pre-aggregate the data</p></li> <li><p>for reshaping only, you can use <code>first</code>: <a href="https://stackoverflow.com/q/37486910/1560062">Pivot String column on Pyspark Dataframe</a></p></li> </ul> <p><strong>Related questions</strong>:</p> <ul> <li><a href="https://stackoverflow.com/q/41670103/8371915">How to melt Spark DataFrame?</a></li> <li><a href="https://stackoverflow.com/q/42465568/8371915">Unpivot in spark-sql/pyspark</a></li> <li><a href="https://stackoverflow.com/q/37864222/8371915">Transpose column to row with Spark</a></li> </ul>
36,736,178
How to delete object from Realm Database Android?
<p>I want remove all message object from realm those are equal to userid </p> <pre><code>RealmQuery&lt;Message&gt; rowQuery = realm.where(Message.class).equalTo(Message.USER_ID, userId); realm.beginTransaction(); //TODO : here I want to remove all messages where userId is equal to "9789273498708475" realm.commitTransaction(); </code></pre>
36,736,415
5
0
null
2016-04-20 07:02:15.76 UTC
7
2021-06-27 18:28:29.857 UTC
2016-11-10 21:24:06.653 UTC
null
1,363,438
null
2,264,402
null
1
48
android|database|realm
69,968
<p>In 0.88.3 and below you can do:</p> <pre><code>realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults&lt;Message&gt; rows = realm.where(Message.class).equalTo(Message.USER_ID,userId).findAll(); rows.clear(); } }); </code></pre> <p>From 0.89 (next release) this will be <code>deleteAllFromRealm()</code> instead. </p> <pre><code>realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults&lt;Message&gt; result = realm.where(Message.class).equalTo(Message.USER_ID,userId).findAll(); result.deleteAllFromRealm(); } }); </code></pre>
27,201,656
git: pushing a new, empty branch for an empty project?
<p>I have an empty project on remote, which I cloned. Now I want to start working on a branch, <code>testdev</code> and start working on it without putting any code to master.</p> <pre><code>$ git checkout -b testdev $ git status On branch testdev Initial commit nothing to commit (create/copy files and use "git add" to track) </code></pre> <p>Now I try to push this branch to bitbucket</p> <pre><code>$ git push origin testdev error: src refspec testdev does not match any. error: failed to push some refs to 'https://[email protected]/myremoterepo.git' </code></pre> <p>I tried <code>git add .</code> and <code>git commit -m "msg"</code> but that is useless as I don't have any files to track or commit. So how do I push an empty branch to an empty project?</p>
27,201,674
1
0
null
2014-11-29 11:20:35.913 UTC
9
2022-06-16 18:10:32.957 UTC
null
null
null
null
696,668
null
1
39
git|bitbucket
32,960
<p>If you repo is still empty, you might try and create an empty commit, to have <em>something</em> to push:</p> <pre><code>git commit --allow-empty -m &quot;initial commit&quot; git push -u origin testdev </code></pre> <p>See also &quot;<a href="https://stackoverflow.com/a/17096880/6309">Why do I need to explicitly push a new branch?</a>&quot;.</p> <hr /> <p>Git 2.35 (Q1 2022) allows information on remotes defined for an arbitrary repository to be read.</p> <p>See <a href="https://github.com/git/git/commit/4a2dcb1a08008bfc48c32f408e8622bd0c4ca297" rel="noreferrer">commit 4a2dcb1</a>, <a href="https://github.com/git/git/commit/56eed3422cb4605a616daab589b94a843a75651f" rel="noreferrer">commit 56eed34</a>, <a href="https://github.com/git/git/commit/085b98f6cdbe9ed794e19ded00ccd0431c30faa0" rel="noreferrer">commit 085b98f</a>, <a href="https://github.com/git/git/commit/fd3cb0501e175bcac042587cb7bb75e16034a5b7" rel="noreferrer">commit fd3cb05</a>, <a href="https://github.com/git/git/commit/e083ef5d54707a4bb855e8ac6f6ee0576a020349" rel="noreferrer">commit e083ef5</a> (17 Nov 2021) by <a href="https://github.com/chooglen" rel="noreferrer">Glen Choo (<code>chooglen</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/6d1e149ac04717efff7e0748509036a87cbb95e1" rel="noreferrer">commit 6d1e149</a>, 10 Dec 2021)</sup></p> <blockquote> <h2><a href="https://github.com/git/git/commit/4a2dcb1a08008bfc48c32f408e8622bd0c4ca297" rel="noreferrer"><code>remote</code></a>: die if branch is not found in repository</h2> <p><sup>Signed-off-by: Glen Choo</sup><br /> <sup>Reviewed-by: Jonathan Tan</sup></p> </blockquote> <blockquote> <p>In a subsequent commit, we would like external-facing functions to be able to accept &quot;struct repository&quot; and &quot;struct branch&quot; as a pair.<br /> This is useful for functions like <code>pushremote_for_branch()</code>, which need to take values from the <code>remote_state</code> and branch, even if branch == <code>NULL</code>.<br /> However, a caller may supply an unrelated repository and branch, which is not supported behavior.</p> <p>To prevent misuse, add a <code>die_on_missing_branch()</code> helper function that dies if a given branch is not from a given repository.<br /> Speed up the existence check by replacing the branches list with a <code>branches_hash</code> hashmap.</p> <p>Like <code>read_config()</code>, <code>die_on_missing_branch()</code> is only called from non-static functions; static functions are less prone to misuse because they have strong conventions for keeping <code>remote_state</code> and branch in sync.</p> </blockquote> <hr /> <p>With Git 2.37 (Q3 2022), a misconfigured '<code>branch..remote</code>' led to a bug in configuration parsing.</p> <p>It avoids <code>branch was not found in the repository</code>.</p> <p>See <a href="https://github.com/git/git/commit/f1dfbd9ee010e5cdf0d931d16b4b2892b33331e5" rel="noreferrer">commit f1dfbd9</a>, <a href="https://github.com/git/git/commit/91e2e8f63ebd92295ff0eb5f4095f9e1fba8bab0" rel="noreferrer">commit 91e2e8f</a> (31 May 2022) by <a href="https://github.com/chooglen" rel="noreferrer">Glen Choo (<code>chooglen</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/0b91d563d8d9615d1dc400b7c5e92ebd7933d01d" rel="noreferrer">commit 0b91d56</a>, 10 Jun 2022)</sup></p> <blockquote> <h2><a href="https://github.com/git/git/commit/91e2e8f63ebd92295ff0eb5f4095f9e1fba8bab0" rel="noreferrer"><code>remote.c</code></a>: don't BUG() on 0-length branch names</h2> <p><sup>Reported-by: &quot;Ing. Martin Prantl Ph.D.&quot;</sup><br /> <sup>Helped-by: Jeff King</sup><br /> <sup>Signed-off-by: Glen Choo</sup></p> </blockquote> <blockquote> <p><a href="https://github.com/git/git/commit/4a2dcb1a08008bfc48c32f408e8622bd0c4ca297" rel="noreferrer">4a2dcb1</a> (&quot;<code>remote</code>: die if branch is not found in repository&quot;, 2021-11-17, Git v2.35.0-rc0 -- <a href="https://github.com/git/git/commit/6d1e149ac04717efff7e0748509036a87cbb95e1" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/e773545c7fe7eca21b134847f4fc2cbc9547fa14" rel="noreferrer">batch #2</a>) introduced a regression where multiple config entries with an empty branch name, e.g.</p> <pre><code>[branch &quot;&quot;] remote = foo merge = bar </code></pre> <p>could cause Git to fail when it tries to look up branch tracking information.</p> <p>We parse the config key to get (branch name, branch name length), but when the branch name subsection is empty, we get a bogus branch name, e.g. &quot;<code>branch..remote</code>&quot; gives <code>(&quot;.remote&quot;, 0)</code>.<br /> We continue to use the bogus branch name as if it were valid, and prior to <a href="https://github.com/git/git/commit/4a2dcb1a08008bfc48c32f408e8622bd0c4ca297" rel="noreferrer">4a2dcb1</a>, this wasn't an issue because length = 0 caused the branch name to effectively be <code>&quot;&quot;</code> everywhere.</p> <p>However, that commit handles <code>length = 0</code> inconsistently when we create the branch:</p> <ul> <li>When <code>find_branch()</code> is called to check if the branch exists in the branch hash map, it interprets a length of 0 to mean that it should call <code>strlen</code> on the char pointer.</li> <li>But the code path that inserts into the branch hash map interprets a length of 0 to mean that the string is 0-length.</li> </ul> <p>This results in the bug described above:</p> <ul> <li>&quot;<code>branch..remote</code>&quot; looks for &quot;<code>.remote</code>&quot; in the branch hash map.<br /> Since we do not find it, we insert the <code>&quot;&quot;</code> entry into the hash map.</li> <li>&quot;<code>branch..merge</code>&quot; looks for &quot;<code>.merge</code>&quot; in the branch hash map.<br /> Since we do not find it, we again try to insert the <code>&quot;&quot;</code> entry into the hash map.<br /> However, the entries in the branch hash map are supposed to be appended to, not overwritten.</li> <li>Since overwriting an entry is a BUG(), Git fails instead of silently ignoring the empty branch name.</li> </ul> <p>Fix the bug by removing the convenience <code>strlen</code> functionality, so that 0 means that the string is 0-length.</p> </blockquote> <hr /> <p>With Git 2.37 (Q3 2022), fix <code>git remote</code> use-after-free (with another forget-to-free) fix.</p> <p>See <a href="https://github.com/git/git/commit/323822c72be59ce2900cc036c5bad4f10bafbb53" rel="noreferrer">commit 323822c</a>, <a href="https://github.com/git/git/commit/338959da3e46340dfcec3af361c6062c3a992668" rel="noreferrer">commit 338959d</a> (07 Jun 2022) by <a href="https://github.com/avar" rel="noreferrer">Ævar Arnfjörð Bjarmason (<code>avar</code>)</a>.<br /> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/fe66167535dd8b395f16fcba7863c36beb365ef9" rel="noreferrer">commit fe66167</a>, 13 Jun 2022)</sup></p> <blockquote> <h2><a href="https://github.com/git/git/commit/323822c72be59ce2900cc036c5bad4f10bafbb53" rel="noreferrer"><code>remote.c</code></a>: don't dereference NULL in freeing loop</h2> <p><sup>Signed-off-by: Ævar Arnfjörð Bjarmason</sup></p> </blockquote> <blockquote> <p>Fix a bug in <a href="https://github.com/git/git/commit/fd3cb0501e175bcac042587cb7bb75e16034a5b7" rel="noreferrer">fd3cb05</a> (&quot;<code>remote</code>: move static variables into per-repository struct&quot;, 2021-11-17, Git v2.35.0-rc0 -- <a href="https://github.com/git/git/commit/6d1e149ac04717efff7e0748509036a87cbb95e1" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/e773545c7fe7eca21b134847f4fc2cbc9547fa14" rel="noreferrer">batch #2</a>) where we'd <code>free(remote-&gt;pushurl[i])</code> after having <code>NULL</code>'d out <code>remote-&gt;pushurl</code>.<br /> itself.<br /> We free &quot;<code>remote-&gt;pushurl</code>&quot; in the next &quot;<code>for</code>&quot;-loop, so doing this appears to have been a copy/paste error.</p> <p>Before this change GCC 12's <code>-fanalyzer</code> would correctly note that we'd dereference <code>NULL</code> in this case, this change fixes that:</p> <pre><code>remote.c: In function ‘remote_clear’: remote.c:153:17: error: dereference of NULL ‘*remote.pushurl’ [CWE-476] [-Werror=analyzer-null-dereference] 153 | free((char *)remote-&gt;pushurl[i]); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [...] </code></pre> </blockquote>
24,538,100
Issue when centering vertically with flexbox when heights are unknown
<p>My layout has a container <code>flex-container</code> and a child.</p> <p>HTML:</p> <pre><code>&lt;div class=&quot;flex-container&quot;&gt; &lt;div&gt;text&lt;/div&gt; &lt;/div&gt; </code></pre> <p>The container and the child have an <strong>unknown height</strong>. And the goal is:</p> <ul> <li>If the child has a lower height than the container, it appears centered horizontally and vertically.</li> <li>If the child has a greater height than the container, it adjusts to the top and the bottom and we can do scroll.</li> </ul> <p>Scheme: <img src="https://i.stack.imgur.com/iN5v5.jpg" alt="enter image description here" /></p> <p>The fastest way for centering a element with flexbox is the follow:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-container { display: flex; align-items: center; /* vertical */ justify-content: center; /* horizontal */ width: 100%; height: 300px; /* for example purposes */ overflow-y: scroll; background: #2a4; } .flex-container &gt; div { background: #E77E23; width: 400px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flex-container"&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Codepen: <a href="http://www.codepen.io/ces/pen/slicw" rel="nofollow noreferrer">http://www.codepen.io/ces/pen/slicw</a></p> <p>But, if the container's child have a greater height, the child is not shown correctly. The child appears cutted (only the top part).</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html,body { height: 100%; width: 100%; padding: 0; margin: 0; } .flex-container { display: flex; align-items: center; // vertical justify-content: center; // horizontal width: 100%; height: 100px; overflow-y: scroll; background: #2a4; } .flex-container &gt; div { background: #E77E23; width: 400px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flex-container"&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Codepen: <a href="http://www.codepen.io/ces/pen/sGtfK" rel="nofollow noreferrer">http://www.codepen.io/ces/pen/sGtfK</a></p> <p>Scheme:</p> <p><img src="https://i.stack.imgur.com/Jx15X.jpg" alt="enter image description here" /></p> <p>Is there a way for resolve this issue?</p>
24,543,895
3
0
null
2014-07-02 18:07:50.11 UTC
25
2022-02-17 04:43:52.62 UTC
2020-07-10 13:52:48.803 UTC
null
3,549,317
null
3,549,317
null
1
68
css|flexbox|height|overflow
10,906
<p>I found the solution:</p> <pre><code>.flex-container { display: flex; /* only */ overflow-y: scroll; } .flex-container &gt; div { margin: auto; /* horizontal and vertical align */ } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { height: 100%; width: 100%; padding: 0; margin: 0; } .flex-container { display: flex; width: 100%; height: 100px; /* change height to 300px */ overflow-y: scroll; background: #2a4; } .flex-container &gt; div { padding: 1em 1.5em; margin: auto; background: #E77E23; width: 400px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flex-container"&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Codepen: <a href="http://codepen.io/ces/pen/Idklh" rel="nofollow noreferrer">http://codepen.io/ces/pen/Idklh</a></p>
22,006,587
how to make div background image responsive
<p><strong>How to make this image responsive</strong></p> <p>HTML:</p> <pre><code>&lt;section id="first" class="story" data-speed="8" data-type="background"&gt; &lt;div class="smashinglogo" id="welcomeimg" data-type="sprite" data-offsetY="100" data-Xposition="50%" data-speed="-2"&gt;&lt;/div&gt; &lt;/section&gt; </code></pre> <p>CSS:</p> <pre><code>#first .smashinglogo {background: url(../images/logo1.png) 50% 100px no-repeat fixed;} </code></pre>
22,006,657
8
0
null
2014-02-25 06:43:13.307 UTC
8
2017-12-20 08:13:12.547 UTC
2014-02-25 06:55:11.393 UTC
null
39,261
null
2,820,623
null
1
24
html|css|twitter-bootstrap
109,113
<p>Use <code>background-size</code> property to the value of <code>100% auto</code> to achieve what you are looking for.</p> <p><strong>For Instance,</strong></p> <pre><code>#first .smashinglogo{ background-size:100% auto; } </code></pre> <p>Hope this helps.</p> <p><em><strong>PS:</strong> As per your code above, you can remove <code>fixed</code> and add <code>100% auto</code> to achieve the output.</em></p>
29,097,393
gradle jacocoTestReport is not working?
<p>I have tried to get code coverage in a spring-gradle project using gradle jacoco plugin. </p> <p>The build.gradle contains the following</p> <pre><code>apply plugin: "jacoco" jacoco { toolVersion = "0.7.1.201405082137" reportsDir = file("$buildDir/customJacocoReportDir") } jacocoTestReport { reports { xml.enabled false csv.enabled false html.destination "${buildDir}/jacocoHtml" } } </code></pre> <p>I then ran </p> <pre><code>gradle test jacocoTestReport </code></pre> <p>Where after only the file test.exec is generated in build/reports folder.</p> <p>Other than that nothing happens. </p> <p><strong>How can I get the HTML report?</strong></p>
29,101,496
4
0
null
2015-03-17 11:00:37.217 UTC
1
2021-11-15 03:08:43.663 UTC
2017-02-28 16:18:34.077 UTC
null
1,169,349
null
3,884,173
null
1
27
gradle|build.gradle
53,881
<p>Following helped . its in samples/testing/jacaco of gradle-2.3-all.zip from <a href="https://gradle.org/releases/" rel="noreferrer">https://gradle.org/releases/</a></p> <pre><code>apply plugin: "java" apply plugin: "jacoco" jacoco { toolVersion = "0.7.1.201405082137" reportsDir = file("$buildDir/customJacocoReportDir") } repositories { mavenCentral() } dependencies { testCompile "junit:junit:4.+" } test { jacoco { append = false destinationFile = file("$buildDir/jacoco/jacocoTest.exec") classDumpFile = file("$buildDir/jacoco/classpathdumps") } } jacocoTestReport { reports { xml.enabled false csv.enabled false html.destination "${buildDir}/jacocoHtml" } } </code></pre>
40,726,438
Android - Detect when the last item in a RecyclerView is visible
<p>I have a method that will check if the last element in a RecyclerView is completely visible by the user, so far I have this code The problem is how to check if the RecyclerView has reached it's bottom ?</p> <p><strong>PS</strong> I have items dividers</p> <pre><code>public void scroll_btn_visibility_controller(){ if(/**last item is visible to user*/){ //This is the Bottom of the RecyclerView Scroll_Top_Btn.setVisibility(View.VISIBLE); } else(/**last item is not visible to user*/){ Scroll_Top_Btn.setVisibility(View.INVISIBLE); } } </code></pre> <p><strong>UPDATE :</strong> <strong>This is one of the attempts I tried</strong></p> <pre><code>boolean isLastVisible() { LinearLayoutManager layoutManager = ((LinearLayoutManager)rv.getLayoutManager()); int pos = layoutManager.findLastCompletelyVisibleItemPosition(); int numItems = disp_adapter.getItemCount(); return (pos &gt;= numItems); } public void scroll_btn_visibility_controller(){ if(isLastVisible()){ Scroll_Top.setVisibility(View.VISIBLE); } else{ Scroll_Top.setVisibility(View.INVISIBLE); } } </code></pre> <p>so far no success I think there is something wrong within these lines :</p> <pre><code>int pos = layoutManager.findLastCompletelyVisibleItemPosition(); int numItems = disp_adapter.getItemCount(); </code></pre>
43,117,555
5
4
null
2016-11-21 17:55:23.657 UTC
8
2022-06-28 21:00:45.79 UTC
2016-11-24 03:43:03.897 UTC
null
6,689,583
null
6,689,583
null
1
38
android|android-recyclerview
58,219
<p>try working with <code>onScrollStateChanged</code> it will solve your issue</p>
47,039,716
What does %i or %I do in Ruby?
<p>What's the meaning of <code>%i</code> or <code>%I</code> in ruby?</p> <p>I searched Google for</p> <pre><code>&quot;%i or %I&quot; ruby </code></pre> <p>but I didn't find anything relevant to Ruby.</p>
47,039,746
3
0
null
2017-10-31 16:02:40.493 UTC
10
2021-11-20 11:02:20.737 UTC
2021-11-20 11:02:20.737 UTC
null
4,957,508
null
3,618,156
null
1
96
ruby-on-rails|ruby
53,663
<pre><code>%i[ ] # Non-interpolated Array of symbols, separated by whitespace %I[ ] # Interpolated Array of symbols, separated by whitespace </code></pre> <p>The second link from my search results <a href="http://ruby.zigzo.com/2014/08/21/rubys-notation/" rel="noreferrer">http://ruby.zigzo.com/2014/08/21/rubys-notation/</a></p> <p>Examples in IRB:</p> <pre><code>%i[ test ] # =&gt; [:test] str = "other" %I[ test_#{str} ] # =&gt; [:test_other] </code></pre>
21,999,750
How to set to int value null? Java Android
<p>which is the best way to set already defined <strong>int</strong> to <strong>null</strong>?</p> <pre><code>private int xy(){ int x = 5; x = null; //-this is ERROR return x; } </code></pre> <p>so i choose this</p> <pre><code>private int xy(){ Integer x = 5; x = null; //-this is OK return (int)x; } </code></pre> <p>Then i need something like :</p> <pre><code>if(xy() == null){ // do something } </code></pre> <p>And my second question can i safely cast Integer to int?</p> <p>Thanks for any response.</p>
22,000,071
4
1
null
2014-02-24 21:48:11.047 UTC
null
2014-06-29 21:09:39.793 UTC
null
null
null
null
2,899,587
null
1
1
java|android|null|integer|int
54,784
<p>In this case, I would avoid using <code>null</code> all together.</p> <p>Just use <code>-1</code> as your <code>null</code></p> <p>If you need <code>-1</code> to be an acceptable (not null) value, then use a <code>float</code> instead. Since all your real answers are going to be integers, make your null <code>0.1</code></p> <p>Or, find a value that the <code>x</code> will never be, like <code>Integer.MAX_VALUE</code> or something.</p>
22,211,282
Convert column with data MM/DD/YYYY varchar to date in sql server?
<p>I've found some similar questions but haven't been able to get anything to work yet. I'm very much a novice with little SQL experience. </p> <p>I have a column END_DATE as Varchar(10) where all the rows follow the mm/dd/yyyy format and I would like to convert it to date. I have an empty column formatted as date if that helps. There are 36 million rows. </p>
22,211,335
4
1
null
2014-03-05 23:01:26.213 UTC
1
2016-06-23 10:06:03.74 UTC
null
null
null
null
2,891,633
null
1
5
sql|sql-server
42,160
<pre><code>SELECT CONVERT(DATETIME,YourColumn,101) FROM YourTable </code></pre> <p>101 is mm/dd/yyyy format.</p> <p>You zany backwards americans :)</p> <p>To update your existing column</p> <pre><code>UPDATE YourTable SET YourNewColumn = CONVERT(DATETIME,YourOldColumn,101) </code></pre> <p>Since it appears you have invalid data, use this method to isolate it:</p> <pre><code>UPDATE YourTable SET YourNewColumn = CONVERT(DATETIME,YourOldColumn,101) WHERE SomeTableKey BETWEEN ASmallCode AND ABiggerCode </code></pre> <p>Find a key in your table that you can use to divide up the data and try updating half the table... now halve it again and again until you find the offending data. Post the data here and we will come up with some code to allow for it.</p>
25,927,700
Laravel - Database, Table and Column Naming Conventions?
<p>I'm using laravel eloquent data objects to access my data, what is the best way to name my tables, columns, foreign/primary keys etc?</p> <p>I found, there are lots of naming conventions out there. I'm just wondering which one best suits for laravel eloquent models.</p> <p>I'm thinking of following naming convention:</p> <ol> <li>Singular table names (ex: Post)</li> <li>Singular column names (ex: userId - user id in the post table)</li> <li>Camel casing for multiple words in table names (ex: PostComment, PostReview, PostPhoto)</li> <li>Camel casing for multiple words in column names (ex: firstName, postCategoryId, postPhotoId)</li> </ol> <p>So with this, I could use similar syntax in the controller.</p> <pre><code>$result = Post::where('postCategoryId', '4')-&gt;get(); </code></pre> <p>Are there any recommended Laravel guidelines for this? Can I proceed with these naming conventions?</p> <p>If someone has better suggestions, I will be very happy to hear them.Thanks a lot!</p>
25,928,069
4
1
null
2014-09-19 06:31:41.367 UTC
6
2021-12-08 13:11:14.443 UTC
null
null
null
null
2,574,900
null
1
27
php|database|laravel|naming-conventions|eloquent
42,396
<p>Laravel has its own naming convention. For example, if your model name is <code>User.php</code> then Laravel expects class 'User' to be inside that file. It also expects <code>users</code> table for <code>User</code> model. However, you can override this convention by defining a table property on your model like,</p> <pre><code> class User extends Eloquent implements UserInterface, RemindableInterface { protected $table = 'user'; } </code></pre> <p>From Laravel official documentation:</p> <blockquote> <p>Note that we did not tell Eloquent which table to use for our User model. The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a <code>$table</code> property on your model</p> </blockquote> <p>If you will use user table id in another table as a foreign key then, it should be snake-case like <code>user_id</code> so that it can be used automatically in case of relation. Again, you can override this convention by specifying additional arguments in relationship function. For example,</p> <pre><code> class User extends Eloquent implements UserInterface, RemindableInterface { public function post(){ return $this-&gt;hasMany('Post', 'userId', 'id'); } } class Post extends Eloquent{ public function user(){ return $this-&gt;belongsTo('User', 'userId', 'id'); } } </code></pre> <p><a href="http://laravel.com/docs/eloquent#relationships" rel="nofollow noreferrer">Docs for Laravel eloquent relationship</a></p> <p>For other columns in table, you can name them as you like.</p> <p>I suggest you to go through documentation once.</p>
20,637,569
Assembly registers in 64-bit architecture
<p>Following the <a href="https://stackoverflow.com/a/15191217/2777359">answer about assembly registers' sizes</a>:</p> <ul> <li><p>First, what sizes are <code>eax</code>, <code>ax</code>, <code>ah</code> and their counterparts, in the 64-bit architecture? How to access a single register's byte and how to access all the 64-bit register's eight bytes?</p> <p>I'd love attention for both <strong>x86-64 (x64)</strong> and <strong>Itanium</strong> processors.</p> </li> <li><p>Second, what is the correct way to use the four registers for holding the first four parameters in function calls in <a href="http://www.viva64.com/en/l/0001/#ID0E6GAE" rel="noreferrer">the new calling convention</a>?</p> </li> </ul>
20,637,866
1
1
null
2013-12-17 15:04:56.777 UTC
13
2022-04-14 16:36:19.25 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,777,359
null
1
13
assembly|x86-64|32bit-64bit|cpu-registers|itanium
36,430
<p>With the old names <strong>all registers remain the same size</strong>, just like when x86-16 was extended to x86-32. To access 64-bit registers you use the new names with <a href="https://stackoverflow.com/q/43933379/995714">R-prefix</a> such as rax, rbx...</p> <p>Register names don't change so you just use the byte registers (al, bl, cl, dl, ah, bh, ch, dh) for the LSB and MSB of ax, bx, cx, dx like before.</p> <p>There are also <strong>8 new registers</strong> called r8-r15. You can access their LSBs by adding the suffix <code>b</code> (or <a href="https://stackoverflow.com/q/43991779/995714"><code>l</code> if you're using AMD</a>). For example r8b, r9b... You can also use the LSB of esi, edi, esp, ebp by the names sil, dil, spl, bpl with the new <a href="https://wiki.osdev.org/X86-64_Instruction_Encoding#REX_prefix" rel="nofollow noreferrer">REX prefix</a>, but you cannot use it at the same time with ah, bh, ch or dh.</p> <p>Likewise the new registers' lowest word or double word can be accessed through the suffix <code>w</code> or <code>d</code>.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>64-bit register</th> <th>Lower 32 bits</th> <th>Lower 16 bits</th> <th>Lower 8 bits</th> </tr> </thead> <tbody> <tr> <td>rax</td> <td>eax</td> <td>ax</td> <td>al</td> </tr> <tr> <td>rbx</td> <td>ebx</td> <td>bx</td> <td>bl</td> </tr> <tr> <td>rcx</td> <td>ecx</td> <td>cx</td> <td>cl</td> </tr> <tr> <td>rdx</td> <td>edx</td> <td>dx</td> <td>dl</td> </tr> <tr> <td>rsi</td> <td>esi</td> <td>si</td> <td>sil</td> </tr> <tr> <td>rdi</td> <td>edi</td> <td>di</td> <td>dil</td> </tr> <tr> <td>rbp</td> <td>ebp</td> <td>bp</td> <td>bpl</td> </tr> <tr> <td>rsp</td> <td>esp</td> <td>sp</td> <td>spl</td> </tr> <tr> <td>r8</td> <td>r8d</td> <td>r8w</td> <td>r8b (r8l)</td> </tr> <tr> <td>r9</td> <td>r9d</td> <td>r9w</td> <td>r9b (r9l)</td> </tr> <tr> <td>r10</td> <td>r10d</td> <td>r10w</td> <td>r10b (r10l)</td> </tr> <tr> <td>r11</td> <td>r11d</td> <td>r11w</td> <td>r11b (r11l)</td> </tr> <tr> <td>r12</td> <td>r12d</td> <td>r12w</td> <td>r12b (r12l)</td> </tr> <tr> <td>r13</td> <td>r13d</td> <td>r13w</td> <td>r13b (r13l)</td> </tr> <tr> <td>r14</td> <td>r14d</td> <td>r14w</td> <td>r14b (r14l)</td> </tr> <tr> <td>r15</td> <td>r15d</td> <td>r15w</td> <td>r15b (r15l)</td> </tr> </tbody> </table> </div> <p>See <a href="https://stackoverflow.com/a/1753627/995714">What are the names of the new X86_64 processors registers?</a></p> <hr /> <p>Regarding the <em>calling convention</em>, on each specific system there's <strong>only one convention</strong><sup>1</sup>.</p> <ul> <li><p><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/x64-architecture" rel="nofollow noreferrer">On Windows</a>:</p> <ul> <li>RCX, RDX, R8, R9 for the first four integer or pointer arguments</li> <li>XMM0, XMM1, XMM2, XMM3 for floating-point arguments</li> </ul> <p><br/><sup>1</sup>Since MSVC 2013 there's also a <strong>new extended convention</strong> on Windows called <a href="https://devblogs.microsoft.com/cppblog/introducing-vector-calling-convention/" rel="nofollow noreferrer"><code>__vectorcall</code></a> so the &quot;single convention policy&quot; is not true anymore.</p> </li> <li><p>On Linux and other systems that follow <a href="https://wiki.osdev.org/System_V_ABI" rel="nofollow noreferrer">System V AMD64 ABI</a>, more arguments can be passed on registers and there's a 128-byte <a href="https://en.wikipedia.org/wiki/Red_zone_(computing)" rel="nofollow noreferrer">red zone</a> below the stack which may make function calling faster.</p> <ul> <li>The first six integer or pointer arguments are passed in registers RDI, RSI, RDX, RCX, R8, and R9</li> <li>Floating-point arguments are passed in XMM0 through XMM7</li> </ul> </li> </ul> <p>For more information should read <a href="http://en.wikipedia.org/wiki/X86-64" rel="nofollow noreferrer">x86-64</a> and <a href="http://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_calling_conventions" rel="nofollow noreferrer">x86-64 calling conventions</a></p> <p>There's also a convention used in <a href="https://en.wikipedia.org/wiki/Plan_9_from_Bell_Labs" rel="nofollow noreferrer">Plan 9</a> where</p> <blockquote> <ul> <li>All registers are caller-saved</li> <li>All parameters are passed on the stack</li> <li>Return values are also returned on the stack, in space reserved below (stack-wise; higher addresses on amd64) the arguments.</li> </ul> </blockquote> <p><a href="https://go.dev/doc/asm" rel="nofollow noreferrer">Golang follows the Plan 9 calling convention</a>, but since go 1.17+ they're gradually introducing a <a href="https://github.com/golang/go/issues/40724" rel="nofollow noreferrer">register-based calling convention</a> for better performance. The calling convention can change in the future, and the compiler can generate stubs to automatically call assembly functions in older conventions. At the moment <a href="https://go.googlesource.com/go/+/refs/heads/dev.regabi/src/cmd/compile/internal-abi.md" rel="nofollow noreferrer">the ABI specifies that</a></p> <ul> <li>9 general-purpose registers will be used to pass integer arguments: RAX, RBX, RCX, RDI, RSI, R8, R9, R10, R11</li> <li>15 registers XMM0-XMM14 are used for floating-point arguments</li> </ul> <p><sub>In fact Plan 9 was always a weirdo. For example it forces a register to be 0 on RISC architectures without a hardware zero register. x86 register names on it are also consistent across 16, 32 and 64-bit x86 architectures with operand size indicated by mnemonic suffix. That means ax can be a 16, 32 or 64-bit register depending on the instruction suffix. If you're curious about it read</sub></p> <ul> <li><sub><a href="https://9p.io/sys/doc/asm.html" rel="nofollow noreferrer">A Manual for the Plan 9 assembler</a></sub></li> <li><sub><a href="https://nelhagedebugsshit.tumblr.com/post/84342207533/things-i-learned-writing-a-jit-in-go" rel="nofollow noreferrer">Go/plan9’s assembler is weird</a></sub></li> </ul> <hr /> <p>OTOH <a href="https://en.wikipedia.org/wiki/IA-64" rel="nofollow noreferrer">Itanium</a> is a <strong>completely different architecture</strong> and has no relation to x86-64 whatsoever. It's a pure 64-bit architecture so all normal registers are 64-bit, no 32-bit or smaller version is available. There are a lot of registers in it:</p> <blockquote> <ul> <li>128 general-purpose integer registers r0 through r127, each carrying 64 value bits and a trap bit. We'll learn more about the trap bit later.</li> <li>128 floating point registers f0 through f127.</li> <li>64 predicate registers p0 through p63.</li> <li>8 branch registers b0 through b7.</li> <li>An instruction pointer, which the Windows debugging engine for some reason calls iip. (The extra &quot;i&quot; is for &quot;insane&quot;?)</li> <li>128 special-purpose registers, not all of which have been given meanings. These are called &quot;application registers&quot; (ar) for some reason. I will cover selected register as they arise during the discussion.</li> <li>Other miscellaneous registers we will not cover in this series.</li> </ul> <p><a href="https://devblogs.microsoft.com/oldnewthing/?p=90821" rel="nofollow noreferrer">The Itanium processor, part 1: Warming up</a></p> </blockquote> <p>Read more on <a href="https://stackoverflow.com/q/11893364/995714">What is the difference between x64 and IA-64?</a></p>
4,828,207
How to use a JSON file in javascript
<p>First off, I am a newcomer to the Javascript realm. I have a JSON file, such as the following:</p> <pre><code>{"markers": [ { "abbreviation": "SPA", "latitude":-13.32, "longitude":-89.99, "markerImage": "flags/us.png", "information": "South Pole", }, .... lots more of these in between .... { "abbreviation": "ALE", "latitude":-62.5, "longitude":82.5, "markerImage": "flags/us.png", "information": "Alert", }, ] } </code></pre> <p>I have been doing a lot of research as to how I can bring this file back into my script only to find ways to encode strings into JSON files. Basically, I want to read this file through javascript, something like this... (I know this isn't how you code)</p> <pre><code>object data = filename.json document.write(data.markers.abbreviation[1]) </code></pre> <p>Can someone please give me clear instruction on how to go about doing this. Remember, I am a newcomer and need specifics since I'm not up to par with the javascript jargon.</p>
4,828,272
1
0
null
2011-01-28 12:29:02.187 UTC
11
2012-05-22 10:26:00.3 UTC
2012-05-22 10:26:00.3 UTC
null
1,016,716
null
593,817
null
1
21
javascript|json
77,480
<p>First you need a handle on a file. You need to get it somehow either through ajax or through server-side behaviour.</p> <p>You need to tell use where the file is. How you plan to get it and what serverside code your using.</p> <p>Once you have you can use <code>JSON.parse(string)</code> on it. You can include the <a href="https://github.com/douglascrockford/JSON-js">json2.js</a> file if you need to support older browsers.</p> <p>If you use jQuery you can also try <a href="http://api.jquery.com/jQuery.parseJSON/"><code>jQuery.parseJSON</code></a> for parsing instead.</p> <p>An option for remotely getting json would be using <a href="http://api.jquery.com/jQuery.getJSON/"><code>jQuery.getJSON</code></a></p> <p>To load it you can either use <a href="http://en.wikipedia.org/wiki/JSON#JSONP">JSONP</a> or some kind of library with ajax functionality like <a href="http://api.jquery.com/jQuery.ajax/"><code>jQuery.ajax</code></a> or <a href="http://www.prototypejs.org/learn/introduction-to-ajax"><code>Ajax.Request</code></a>. It can be done in raw javascript but that's just ugly and re-inventing the wheel.</p> <pre><code>$.getJSON("document.json", function(data) { console.log(data); // data is a JavaScript object now. Handle it as such }); </code></pre>
14,152,378
How to customize bootstrap sidebar/sidenav?
<p>I need to make use of Twitter Bootstrap Sidebar for creating a menu in my web application.(Highlighted in red). <img src="https://i.stack.imgur.com/g8vRs.png" alt="enter image description here"></p> <p>To create a menu as shown below. <img src="https://i.stack.imgur.com/iY6SO.png" alt="enter image description here"></p> <p>The top item has a dropdown as shown in mage. And Next items in menu should come below this.But this is what I get when I use the css.</p> <p><img src="https://i.stack.imgur.com/nHZzK.png" alt="enter image description here"></p> <p>Menu Item overlaping the other.</p> <p>Here is the <strong>bootstrap code:</strong></p> <pre><code>&lt;div class="span3 bs-docs-sidebar"&gt; &lt;ul class="nav nav-list bs-docs-sidenav affix"&gt; &lt;li class="active"&gt;&lt;a href="#dropdowns"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Dropdowns&lt;/a&gt;&lt;/li&gt; &lt;li class=""&gt;&lt;a href="#buttonGroups"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Button groups&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#buttonDropdowns"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Button dropdowns&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#navs"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Navs&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#navbar"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Navbar&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#breadcrumbs"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Breadcrumbs&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#pagination"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Pagination&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#labels-badges"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Labels and badges&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#typography"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Typography&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#thumbnails"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Thumbnails&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#alerts"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Alerts&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#progress"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Progress bars&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#media"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Media object&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#misc"&gt;&lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Misc&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Here is <strong>my code:</strong></p> <pre><code> &lt;div class="span3 bs-docs-sidebar"&gt; &lt;ul class="nav nav-list bs-docs-sidenav affix"&gt; &lt;li&gt; &lt;a class="dropdown-toggle" data-toggle="dropdown" href="#"&gt; &lt;i class="icon-user"&gt;&lt;/i&gt;dany &lt;span class="caret"&gt;&lt;/span&gt; &lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a id="logout" href="#"&gt;Sign Out&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="span3 bs-docs-sidebar"&gt; &lt;ul class="nav nav-list bs-docs-sidenav `affix`"&gt; &lt;li&gt;&lt;a href="#approval" id="approval"&gt;&lt;/i&gt;Approval Requests&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#setting" id="setting"&gt;&lt;/i&gt;Settings&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>The css class in bootstrap setting the position is <code>bs-docs-sidenav</code> and <code>affix</code> I belive. The css of docs.css of twitter bootstrap is <a href="http://twitter.github.com/bootstrap/assets/css/docs.css" rel="nofollow noreferrer">this</a></p> <p>Anyone please help to solve this issue as soon as possible.</p>
14,170,741
2
0
null
2013-01-04 06:40:56.083 UTC
5
2014-11-19 14:14:46.23 UTC
2013-01-04 06:47:32.707 UTC
null
1,676,610
null
1,676,610
null
1
4
html|css|web-applications|twitter-bootstrap
51,906
<p>You are using <code>span3</code> on both of your menus. That means the second menu will be placed on the next grid on the right, not below the first menu.</p> <p>I believe you should start like this-</p> <pre><code>&lt;div class="span3 bs-docs-sidebar"&gt; &lt;ul class="nav nav-list bs-docs-sidenav affix"&gt; &lt;li&gt; &lt;a class="dropdown-toggle" data-toggle="dropdown" href="#"&gt; &lt;i class="icon-user"&gt;&lt;/i&gt;dany &lt;span class="caret"&gt;&lt;/span&gt; &lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a id="logout" href="#"&gt;Sign Out&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav nav-list bs-docs-sidenav affix"&gt; &lt;li&gt;&lt;a href="#approval" id="approval"&gt;&lt;/i&gt;Approval Requests&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#setting" id="setting"&gt;&lt;/i&gt;Settings&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Now apply some CSS on the second menu e.g.</p> <p><code>&lt;ul class="nav nav-list bs-docs-sidenav affix" style="top: 200px;"&gt;</code></p>
26,451,590
Why should Java's value-based classes not be serialized?
<p>Since Version 8 Java has the concept of <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html"><em>value-based</em> classes</a>. This is in preparation of a future version which will most likely allow the definition of <a href="http://cr.openjdk.java.net/~jrose/values/values-0.html">value types</a>. Both definitions/descriptions mention serialization (bold face added by me):</p> <p>About the existing value-based classes:</p> <blockquote> <p>A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly via reference equality or indirectly via an appeal to synchronization, identity hashing, <strong>serialization</strong>, or any other identity-sensitive mechanism.</p> </blockquote> <p>About future value types:</p> <blockquote> <p>The default identity-based hash code for object, available via System.identityHashCode, also does not apply to value types. Internal operations like <strong>serialization</strong> which make identity-based distinctions of objects would either not apply to values (as they do not apply to primitives) or else they would use the value-based distinction supplied by the value type’s hashCode method.</p> </blockquote> <p>Because future JVM implementations might not use object headers and reference pointers for value-based classes, some of the limitations are clear. (E.g. not locking on an identity which the JVM must not uphold. A reference on which is locked could be removed and replaced by another later, which makes releasing the lock pointless and will cause deadlocks).</p> <p>But I don't get how serialization plays into this. Why is it considered an <em>"identity-sensitive mechanism"</em>? Why does it <em>"make identity-based distinctions of objects"</em>?</p>
26,451,921
2
1
null
2014-10-19 14:37:12.57 UTC
9
2014-10-19 15:37:30.163 UTC
null
null
null
null
2,525,313
null
1
20
java|serialization|java-8
4,051
<p>Serialization uses <code>System.identityHashCode</code> (via <code>IdentityHashMap</code>) to ensure that the topology of the object graph resulting from deserialization is topologically equivalent to that of the input graph. </p>
20,219,628
Problems with python easy install
<p>I have a problem using easy_install for matplotlib-venn. I'm on a windows computer using python2.7. I'm suspecting the path is not correct but I do not know how to fix the problem. Could anyone help me? I'm attaching the output from trying to run the easy_install command in the CMD prompter.</p> <pre><code>C:\Python27\Scripts&gt;easy_install matplotlib-venn Searching for matplotlib-venn Reading https://pypi.python.org/simple/matplotlib-venn/ Download error on https://pypi.python.org/simple/matplotlib-venn/: [Errno 11004] getaddrinfo failed -- Some packages may not be found! Couldn't find index page for 'matplotlib-venn' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: [Errno 11004] getaddrinfo fai led -- Some packages may not be found! No local packages or download links found for matplotlib-venn error: Could not find suitable distribution for Requirement.parse('matplotlib-ve nn') install for matplotlib-venn package </code></pre> <hr> <p>Output from trying the pip install suggestion:</p> <pre><code>C:\Python27\Scripts&gt;easy_install pip Searching for pip Best match: pip 1.4.1 Adding pip 1.4.1 to easy-install.pth file Installing pip-script.py script to C:\Python27\Scripts Installing pip.exe script to C:\Python27\Scripts Installing pip.exe.manifest script to C:\Python27\Scripts Installing pip-2.7-script.py script to C:\Python27\Scripts Installing pip-2.7.exe script to C:\Python27\Scripts Installing pip-2.7.exe.manifest script to C:\Python27\Scripts Using c:\python27\lib\site-packages Processing dependencies for pip Finished processing dependencies for pip C:\Python27\Scripts&gt;pip install matplotlib-venn Downloading/unpacking matplotlib-venn Cannot fetch index base URL https://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement matplotlib-venn Cleaning up... No distributions at all found for matplotlib-venn Storing complete log in C:\Users\jherman8\pip\pip.log </code></pre>
20,221,312
4
1
null
2013-11-26 14:21:35.57 UTC
3
2018-12-16 04:26:18.47 UTC
2017-11-01 16:45:27.267 UTC
null
5,874,320
null
2,219,369
null
1
8
python|python-2.7|matplotlib|easy-install|matplotlib-venn
62,590
<p>Based on </p> <pre><code>Download error on https://pypi.python.org/simple/matplotlib-venn/: [Errno 11004] getaddrinfo failed </code></pre> <p>and </p> <pre><code>Cannot fetch index base URL https://pypi.python.org/simple/ </code></pre> <p>it seems that your have network issue. Do you run your machine behind a firewall or a proxy?</p> <p>For <code>easy_install</code> to work behind proxy, you have to setup needed environments, for example</p> <pre><code>set http_proxy="user:password@server:port" set https_proxy="user:password@server:port" </code></pre> <p>For pip you can use <code>-proxy</code> argument. More details on pip usage behind proxy see in this thread: <a href="https://stackoverflow.com/a/11869484/1265154">How to use pip on windows behind an authenticating proxy</a></p>
55,317,539
TF30063:You are not authorized to access dev.azure.com but I can connect
<p>I am using Azure Devops and VS2017 15.9.7. I am logged into Devops and can sync. When I open my project I get a message</p> <pre><code>"TF30063": You are not authorized to access dev.azure.com/myproject </code></pre> <p>I have tried going into credentials manager and deleting all the credentials for the devops organisation.</p> <p>I have looked at <a href="https://stackoverflow.com/questions/12685111/error-tf30063-you-are-not-authorized-to-access-defaultcollection?rq=1">this question</a> and tried logging out via the browser within VS </p>
55,330,767
10
2
null
2019-03-23 19:26:47.667 UTC
9
2022-08-28 05:07:05.403 UTC
2019-03-24 19:56:58.097 UTC
null
1,592,821
null
1,592,821
null
1
35
visual-studio|azure-devops
35,602
<blockquote> <p>TF30063:You are not authorized to access dev.azure.com but I can connect</p> </blockquote> <p>I have encountered the same issue. (I need to switch back and forth between work account and test account). Of course, there could be so many reasons and it could be different for each (cached another account, or modified the password).</p> <p>To resolve this issue I have two methods/steps.</p> <hr> <p>Step 1 is to clear the credential from credential manager:</p> <p>Go to Control Panel (with small icon view)--><code>User Accounts</code>--><code>Manage your credentials</code> (on the left column)-->Select <code>Windows Credentials</code>-->Scroll down to the <code>Generic Credentials</code> section and look for your TFS server connection.</p> <hr> <p>Step 2 is to click on the operation that <em>Connects to the Team Projects</em> which is the button/plug icon in the <code>Team Explorer</code> tab. Then to also right click the project you are getting this issue on and select <code>Connect</code>:</p> <p><a href="https://i.stack.imgur.com/l383I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/l383I.png" alt="enter image description here"></a></p> <p>I also have tried other methods but not work for me, if possible, you can check if it is useful to you:</p> <p><a href="https://www.c-sharpcorner.com/article/how-to-fix-tf30063-error-you-are-not-authorized-to-access-team-foundation-serv/" rel="noreferrer">How To Fix TF30063 Error</a></p> <p><a href="https://stackoverflow.com/questions/12685111/error-tf30063-you-are-not-authorized-to-access-defaultcollection?answertab=votes#tab-top">Error TF30063: You are not authorized to access</a></p>
21,544,716
Implementing Comparable with a generic class
<p>I want to define a class that implements the generic Comparable interface. While in my class I also defined a generic type element <code>T</code>. In order to implement the interface, I delegate the comparison to <code>T</code>. Here is my code:</p> <pre><code>public class Item&lt;T extends Comparable&lt;T&gt;&gt; implements Comparable&lt;Item&gt; { private int s; private T t; public T getT() { return t; } @Override public int compareTo(Item o) { return getT().compareTo(o.getT()); } } </code></pre> <p>When I try to compile it, I get the following error information:</p> <pre><code>Item.java:11: error: method compareTo in interface Comparable&lt;T#2&gt; cannot be applied to given types; return getT().compareTo(o.getT()); ^ required: T#1 found: Comparable reason: actual argument Comparable cannot be converted to T#1 by method invocation conversion where T#1,T#2 are type-variables: T#1 extends Comparable&lt;T#1&gt; declared in class Item T#2 extends Object declared in interface Comparable 1 error </code></pre> <p>Can anybody tell me why and how to fix it?</p>
21,544,792
4
3
null
2014-02-04 05:35:46.923 UTC
9
2021-11-05 10:42:45.03 UTC
2018-07-11 14:46:57.043 UTC
null
2,891,664
null
1,450,620
null
1
24
java|generics|interface|comparable|raw-types
80,198
<p><code>Item</code> (without any type argument) is a <a href="https://stackoverflow.com/q/2770321/2891664">raw type</a>, so:</p> <ol> <li><p>We could pass any kind of <code>Item</code> to <code>Item.compareTo</code>. For example, this would compile:</p> <pre><code>new Item&lt;String&gt;().compareTo(new Item&lt;Integer&gt;()) </code></pre></li> <li><p>The method <code>o.getT()</code> returns <code>Comparable</code> instead of <code>T</code>, which causes the compilation error.</p> <p>In the example under the 1st point, after passing <code>Item&lt;Integer&gt;</code> to <code>Item.compareTo</code>, we would then erroneously pass an <code>Integer</code> to <code>String.compareTo</code>. The compilation error prevents us from writing the code which does that.</p></li> </ol> <p>I think you just need to remove the raw types:</p> <pre><code>public class Item&lt;T extends Comparable&lt;T&gt;&gt; implements Comparable&lt;Item&lt;T&gt;&gt; { ... @Override public int compareTo(Item&lt;T&gt; o) { return getT().compareTo(o.getT()); } } </code></pre>
1,856,189
Fullpage picture in two column layout
<p>I'd like to insert a picture (figure) into a document which is using a two-column layout. However, I want it to take one whole page and not be centered on one of the columns. Currently if I add a <code>[p]</code> modifier to the figure, the whole image lands on the last page, instead in the middle of the document.</p> <p>How can I force one page to switch back to a single-column layout and insert a single big picture there?</p>
1,861,447
4
0
null
2009-12-06 18:40:59.607 UTC
6
2020-04-24 16:29:56.113 UTC
null
null
null
null
31,667
null
1
25
latex
124,600
<p><code>\usepackage{multicol}</code> in your preamble.</p> <p>Then</p> <pre><code>\begin{document} \begin{multicols}{2} blah blah blah text \end{multicols} \begin{figure}[H] \includegraphics[width=1\textwidth]{arc} \end{figure} \begin{multicols}{2} blah blah blah text \end{multicols} \end{document} </code></pre> <p>This is ugly, and dirty. and you will need to fiddle with where you figure is in order to get the text balanced, but it is exactly what you asked for.</p>
1,531,664
In what order do templates in an XSLT document execute, and do they match on the source XML or the buffered output?
<p>Here is something that has always mystified me about XSLT:</p> <ol> <li>In what order do the templates execute, and</li> <li>When they execute, do they match on (a) the original source XML, or (b) the current output of the XSLT to that point?</li> </ol> <p>Example:</p> <pre><code>&lt;person&gt; &lt;firstName&gt;Deane&lt;/firstName&gt; &lt;lastName&gt;Barker&lt;/lastName&gt; &lt;/person&gt; </code></pre> <p>Here is a fragment of XSLT:</p> <pre><code>&lt;!-- Template #1 --&gt; &lt;xsl:template match="/"&gt; &lt;xsl:value-of select="firstName"/&gt; &lt;xsl:value-of select="lastName"/&gt; &lt;/xsl:template&gt; &lt;!-- Template #2 --&gt; &lt;xsl:template match="/person/firstName"&gt; First Name: &lt;xsl:value-of select="firstName"/&gt; &lt;/xsl:template&gt; </code></pre> <p>Two questions about this:</p> <ol> <li>I am assuming that Template #1 will execute first. I don't know why I assume this -- is it just because it appears first in the document?</li> <li>Will Template #2 execute? It matches a node in the source XML, but by the time the we get to this template (assuming it runs second), the "firstName" node will not be in the output tree.</li> </ol> <p>So, are "later" templates beholden to what has occurred in "earlier" templates, or do they operate on the source document, oblivious to what has been transformed "prior" to them? (All those words are in quotes, because I find it hard to discuss time-based issues when I really have little idea how template order is determined in the first place...)</p> <p>In the above example, we have a template that matches on the root node ("/") that -- when it is done executing -- has essentially removed all nodes from the output. This being the case, would this pre-empt all other templates from executing since there is nothing to match on after that first template is complete?</p> <p>To this point, I've been concerned with later templates not executing because the nodes they have operated on do not appear in the output, but what about the inverse? Can an "earlier" template create a node that a "later" template can do something with?</p> <p>On the same XML as above, consider this XSL:</p> <pre><code>&lt;!-- Template #1 --&gt; &lt;xsl:template match="/"&gt; &lt;fullName&gt; &lt;xsl:value-of select="firstName"/&gt; &lt;xsl:value-of select="lastName"/&gt; &lt;/fullName&gt; &lt;/xsl:template&gt; &lt;!-- Template #2 --&gt; &lt;xsl:template match="//fullName"&gt; Full Name: &lt;xsl:value-of select="."/&gt; &lt;/xsl:template&gt; </code></pre> <p>Template #1 creates a new node called "fullName". Template #2 matches on that same node. Will Template #2 execute because the "fullName" node exists in the output by the time we get around to Template #2?</p> <p>I realize that I'm deeply ignorant about the "zen" of XSLT. To date, my stylesheets have consisted of a template matching the root node, then are completely procedural from there. I'm tired of doing this. I would rather actually understand XSLT correctly, hence my question.</p>
1,542,734
4
3
null
2009-10-07 13:30:35.633 UTC
31
2013-03-09 13:12:18.31 UTC
2009-10-07 18:20:39.183 UTC
null
60,733
null
60,733
null
1
78
xslt
28,215
<p>I love your question. You're very articulate about what you do not yet understand. You just need something to tie things together. My recommendation is that you read <a href="http://lenzconsulting.com/how-xslt-works/" rel="noreferrer">"How XSLT Works"</a>, a chapter I wrote to address exactly the questions you're asking. I'd love to hear if it ties things together for you.</p> <p>Less formally, I'll take a stab at answering each of your questions.</p> <blockquote> <ol> <li>In what order do the templates execute, and</li> <li>When they execute, do they match on (a) the original source XML, or (b) the current output of the XSLT to that point?</li> </ol> </blockquote> <p>At any given point in XSLT processing, there are, in a sense, two contexts, which you identify as (a) and (b): where you are in the <em>source tree</em>, and where you are in the <em>result tree</em>. Where you are in the source tree is called the <em>current node</em>. It can change and jump all around the source tree, as you choose arbitrary sets of nodes to process using XPath. However, conceptually, you never "jump around" the result tree in the same way. The XSLT processor constructs it in an orderly fashion; first it creates the root node of the result tree; then it adds children, building the result in document order (depth-first). [Your post motivates me to pick up my software visualization for XSLT experiments again...]</p> <p>The order of template rules in a stylesheet never matters. You can't tell, just by looking at the stylesheet, in what order the template rules will be instantiated, how many times a rule will be instantiated, or even whether it will be at all. (<code>match="/"</code> is an exception; you can always know that it will get triggered.)</p> <blockquote> <p>I am assuming that Template #1 will execute first. I don't know why I assume this -- is it just because it appears first in the document?</p> </blockquote> <p>Nope. It would be called first even if you put it last in the document. Template rule order never matters (except under an error condition when you have more than one template rule with the same priority matching the same node; even then, it's optional for the implementor and you should never rely on such behavior). It gets called first because the first thing that <strong>always</strong> happens whenever you run an XSLT processor is a virtual call to <code>&lt;xsl:apply-templates select="/"/> </code>. The one virtual call constructs the entire result tree. Nothing happens outside it. You get to customize, or "configure", the behavior of that instruction by defining template rules.</p> <blockquote> <p>Will Template #2 execute? It matches a node in the source XML, but by the time the we get to this template (assuming it runs second), the "firstName" node will not be in the output tree.</p> </blockquote> <p>Template #2 (nor any other template rules) will never get triggered unless you have an <code>&lt;xsl:apply-templates/></code> call somewhere in the <code>match="/"</code> rule. If you don't have any, then no template rules other than <code>match="/"</code> will get triggered. Think of it this way: for a template rule to get triggered, it can't just match a node in the input. It has to match a node that you elect to <em>process</em> (using <code>&lt;xsl:apply-templates/></code>). Conversely, it will continue to match the node as many times as you choose to process it.</p> <blockquote> <p>Would [the <code>match="/"</code> template] pre-empt all other templates from executing since there is nothing to match on after that first template is complete?</p> </blockquote> <p>That rule preempts the rest by nowhere including <code>&lt;xsl:apply-templates/></code> in it. There are still plenty of nodes that <em>could</em> be processed in the source tree. They're always all there, ripe for the picking; process each one as many times as you want. But the only way to process them using template rules is to call <code>&lt;xsl:apply-templates/></code>.</p> <blockquote> <p>To this point, I've been concerned with later templates not executing because the nodes they have operated on do not appear in the output, but what about the inverse? Can an "earlier" template create a node that a "later" template can do something with?</p> </blockquote> <p>It's not that an "earlier" template creates a new node to be processed; it's that an "earlier" template in turn processes more nodes from the source tree, using that same instruction (<code>&lt;xsl:apply-templates</code>). You can think of it as calling the same "function" recursively, with different parameters each time (the nodes to process as determined by the context and the <code>select</code> attribute).</p> <p>In the end, what you get is a tree-structured stack of recursive calls to the same "function" (<code>&lt;xsl:apply-templates></code>). And this tree structure is <strong>isomorphic</strong> to your actual result. Not everyone realizes this or has thought about it this way; that's because we don't have any effective visualization tools...yet.</p> <blockquote> <p>Template #1 creates a new node called "fullName". Template #2 matches on that same node. Will Template #2 execute because the "fullName" node exists in the output by the time we get around to Template #2?</p> </blockquote> <p>Nope. The only way to do a chain of processing is to explicitly set it up that way. Create a variable, e.g., <code>$tempTree</code>, that contains the new <code>&lt;fullName></code> element and then process <em>it</em>, like this <code>&lt;xsl:apply-templates select="$tempTree"></code>. To do this in XSLT 1.0, you need to wrap the variable reference with an extension function (e.g., <code>exsl:node-set()</code>), but in XSLT 2.0 it will work just as is.</p> <p>Whether you're processing nodes from the original source tree or in a temporary tree that you construct, either way you need to explicitly say what nodes you want to process.</p> <p>What we haven't covered is how XSLT gets all its implicit behavior. You must also understand the <em>built-in template rules</em>. I write stylesheets all the time that don't even include an explicit rule for the root node (<code>match="/"</code>). Instead, I rely on the built-in rule for root nodes (apply templates to children), which is the same as the built-in rule for element nodes. Thus I can ignore large parts of the input, let the XSLT processor automatically traverse it, and only when it comes across a node I'm interested in will I do something special. Or I could write a single rule that copies everything recursively (called the identity transform), overriding it only where necessary, to make incremental changes to the input. After you've read "How XSLT Works", your next assignment is to look up the "identity transform".</p> <blockquote> <p>I realize that I'm deeply ignorant about the "zen" of XSLT. To date, my stylesheets have consisted of a template matching the root node, then are completely procedural from there. I'm tired of doing this. I would rather actually understand XSLT correctly, hence my question.</p> </blockquote> <p>I applaud you. Now it's time to take the "red pill": read <a href="http://lenzconsulting.com/how-xslt-works/" rel="noreferrer">"How XSLT Works"</a></p>
52,486,786
forkJoin is deprecated: resultSelector is deprecated, pipe to map instead
<p>I'm working on an Angular 6 project.</p> <p>Running <strong>ng lint</strong> gives the following Warning:</p> <p>&quot;forkJoin is deprecated: resultSelector is deprecated, pipe to map instead&quot;</p> <pre><code> forkJoin(...observables).subscribe( </code></pre> <p>Any idea? Can't seem to find any information about this deprecation.</p> <p>I just generated a brand new Angular application &quot;ng new forkApp&quot; with Angular CLI: 6.1.5</p> <p>source:</p> <pre><code>import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { forkJoin } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'forkApp'; constructor(private http: HttpClient) {} ngOnInit() { console.log('ngOnInit...'); const obs = []; for (let i = 1; i &lt; 4; i++) { const ob = this.http.get('https://swapi.co/api/people/' + i); obs.push(ob); } forkJoin(...obs) .subscribe( datas =&gt; { console.log('received data', datas); } ); } } </code></pre> <p>&quot;dependencies&quot; section from package.json file:</p> <pre><code> &quot;dependencies&quot;: { &quot;@angular/animations&quot;: &quot;^6.1.0&quot;, &quot;@angular/common&quot;: &quot;^6.1.0&quot;, &quot;@angular/compiler&quot;: &quot;^6.1.0&quot;, &quot;@angular/core&quot;: &quot;^6.1.0&quot;, &quot;@angular/forms&quot;: &quot;^6.1.0&quot;, &quot;@angular/http&quot;: &quot;^6.1.0&quot;, &quot;@angular/platform-browser&quot;: &quot;^6.1.0&quot;, &quot;@angular/platform-browser-dynamic&quot;: &quot;^6.1.0&quot;, &quot;@angular/router&quot;: &quot;^6.1.0&quot;, &quot;core-js&quot;: &quot;^2.5.4&quot;, &quot;rxjs&quot;: &quot;^6.0.0&quot;, &quot;zone.js&quot;: &quot;~0.8.26&quot; }, </code></pre> <p>Once all three GET requests are done I got all data in &quot;datas&quot; array. The issue is that once I run: <code>ng lint</code> I got this:</p> <p>C:\forkApp&gt;<strong>ng lint</strong></p> <blockquote> <p>WARNING: C:/forkApp/src/app/app.component.ts[26, 5]: forkJoin is deprecated: resultSelector is deprecated, pipe to map instead</p> </blockquote>
53,381,715
7
6
null
2018-09-24 20:20:29.62 UTC
8
2021-11-12 23:40:28.247 UTC
2020-09-23 15:44:24.463 UTC
null
2,050,306
null
2,050,306
null
1
82
angular|rxjs6
74,621
<p>I was able to fix this by getting rid of the ellipsis:</p> <p><code>forkJoin(observables).subscribe();</code></p> <p>As long as <code>observables</code> is already an array, it should have the same result.</p>
28,770,530
How to Hide ActionBar/Toolbar While Scrolling Down in Webview
<p>In Google chrome and play store. the app can hide the actionbar while scrolling and allows the user to Browse conveniently. Please Help me to do like this.</p> <p>I've used onTouchListener for webview it doesn't works.</p> <pre><code>mWebView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: getSupportActionBar().show(); break; case MotionEvent.ACTION_UP: getSupportActionBar().hide(); break; default: break; } return false; } }); </code></pre> <p>Thanks in Advance</p>
35,967,742
3
3
null
2015-02-27 17:07:37.06 UTC
16
2020-06-05 04:33:12.947 UTC
2016-03-18 06:23:38.297 UTC
null
4,233,197
null
4,142,237
null
1
22
android|android-webview|android-scrollview|android-scroll
27,283
<p>You can do this without any Java code using the design library's <code>CoordinatorLayout</code> and <code>NestedScrollView</code>, with <code>app:layout_scrollFlags</code> set on <code>Toolbar</code>. Here's how you do it. </p> <pre><code>&lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="fill_vertical" android:fillViewport="true" app:layout_behavior="@string/appbar_scrolling_view_behavior"&gt; &lt;WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p>You can play around with with different layout_scrollFlags and fitsSystemWindows behaviour once you get the hang of it.</p>
7,556,155
Git: Set up a fetch-only remote?
<p>When I run <code>git remote -v</code> in one of my Git repositories that has a remote(s) configured, I see that each remote has both fetch and push specs:</p> <pre><code>$ git remote -v &lt;remote-name&gt; ssh://host/path/to/repo (fetch) &lt;remote-name&gt; ssh://host/path/to/repo (push) </code></pre> <p>For remotes that point to peer developers there's no need to push, and Git will refuse to push to a non-bare repository anyway. Is there any way to configure these remotes as "fetch-only" with no push address or capabilities?</p>
7,556,269
5
1
null
2011-09-26 13:53:38.667 UTC
42
2019-10-30 13:00:13.25 UTC
null
null
null
null
263,607
null
1
166
git|workflow
36,818
<p>I don't think you can <em>remove</em> the push URL, you can only <em>override</em> it to be something other than the pull URL. So I think the closest you'll get is something like this:</p> <pre><code>$ git remote set-url --push origin no-pushing $ git push fatal: 'no-pushing' does not appear to be a git repository fatal: The remote end hung up unexpectedly </code></pre> <p>You are setting the push URL to <code>no-pushing</code>, which, as long as you don't have a folder of the same name in your working directory, git will not be able to locate. You are essentially forcing git to use a location that does not exist.</p>
7,060,016
Why does the toString method in java not seem to work for an array
<p>I want to convert a character array to a string object using the toString() method in java. Here is a snippet of the test code I used:</p> <pre><code>import java.util.Arrays; class toString{ public static void main(String[] args){ char[] Array = {'a', 'b', 'c', 'd', 'e', 'f'}; System.out.println(Array.toString()); } } </code></pre> <p>In principle, it should print <strong>abcdef</strong>, but it is printing random gibberish of the likes of <strong>[C@6e1408</strong> or <strong>[C@e53108</strong> each time the program executes. I don't need an alternative out of this but want to know why this is happening.</p>
7,060,025
9
0
null
2011-08-14 22:03:10.45 UTC
13
2018-07-19 21:44:39.013 UTC
2014-07-07 23:38:52.257 UTC
null
545,127
null
894,272
null
1
37
java|tostring|arrays
40,365
<p>To get a human-readable <code>toString()</code>, you must use <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#toString%28double%5B%5D%29" rel="noreferrer"><code>Arrays.toString()</code></a>, like this:</p> <pre><code>System.out.println(Arrays.toString(Array)); </code></pre> <p>Java's <code>toString()</code> for an array is to print <code>[</code>, followed by a character representing the type of the array's elements (in your case <code>C</code> for <code>char</code>), followed by <code>@</code> then the "identity hash code" of the array (think of it like you would a "memory address").</p> <p>This sad state of affairs is generally considered as a "mistake" with java.</p> <p>See <a href="https://stackoverflow.com/a/7284322/256196">this answer</a> for a list of other "mistakes". </p>
7,189,523
How to give space between two cells in tableview?
<p>I want a space between two cell in table view,</p> <p>I want cell like this,</p> <p><img src="https://i.stack.imgur.com/UlCcX.png" alt="enter image description here"></p> <p>How can i do that?</p>
7,189,568
26
2
null
2011-08-25 11:23:41.417 UTC
19
2022-06-30 05:55:53.967 UTC
2012-10-02 05:56:12.423 UTC
null
1,278,036
null
707,665
null
1
50
iphone|objective-c|cocoa-touch|uitableview|ios4
95,461
<p>You can create a Sections of TableView also in the UITableView... This methods are compulsory so create sections and in each section you can create single cell as in your picture..</p>
14,164,350
Identifying large bodies of text via BeautifulSoup or other python based extractors
<p>Given <a href="http://www.cnn.com/2013/01/04/justice/ohio-rape-online-video/index.html?hpt=hp_c2" rel="nofollow noreferrer">some random news article</a>, I want to write a web crawler to find the largest body of text present, and extract it. The intention is to extract the physical news article on the page.</p> <p>The original plan was to use a <strike><code>BeautifulSoup findAll(True)</code></strike> and to sort each tag by its <code>.getText()</code> value. <strong>EDIT: don't use this for html work, use the lxml library, it's python based and much faster than BeautifulSoup.</strong> command (which means extract all html tags)</p> <p>But this won't work for most pages, like the one I listed as an example, because the large body of text is split into many smaller tags, like paragraph dividers for example.</p> <p>Does anyone have any experience with this? Any help with something like this would be amazing.</p> <p>At the moment I'm using BeautifulSoup along with python, but willing to explore other possibilities.</p> <hr> <b>EDIT: Came back to this question after a few months later (wow i sounded like an idiot ^), and solved this with a combination of libraries & own code.</b> <p>Here are some deadly helpful python libraries for the task in sorted order of how much it helped me:</p> <p>#1 <a href="https://github.com/grangier/python-goose" rel="nofollow noreferrer">goose library</a> Fast, powerful, consistent #2 <a href="https://github.com/gfxmonk/python-readability" rel="nofollow noreferrer">readability library</a> Content is passable, slower on average than goose but faster than boilerpipe #3 <a href="https://github.com/misja/python-boilerpipe" rel="nofollow noreferrer">python-boilerpipe</a> Slower &amp; hard to install, no fault to the boilerpipe library (originally in java), but to the fact that this library is build on top of another library in java, which attributes to IO time &amp; errors, etc.</p> <p>I'll release benchmarks perhaps if there is interest.</p> <hr> <p><b>Indirectly related libraries, you should probably install them and read their docs:</b></p> <ul> <li><a href="http://nltk.org/" rel="nofollow noreferrer">NLTK text processing library</a><b> This is too good not to install. They provide text analysis tools along with html tools (like cleanup, etc).</b></li> <li><a href="http://lxml.de/" rel="nofollow noreferrer">lxml html/xml parser</a><b> Mentioned above. This beats BeautifulSoup in every aspect but usability. It's a bit harder to learn but the results are worth it. HTML parsing takes much less time, it's very noticeable. </b></li> <li><a href="https://code.google.com/p/webscraping/source/browse/" rel="nofollow noreferrer">python webscraper library</a> <b>I think the value of this code isn't the lib itself, but using the lib as a reference manual to build your own crawlers/extractors. It's very nicely coded / documented!</b></li> </ul> <p>A lot of the value and power in using python, a rather slow language, comes from it's open source libraries. They are especially awesome when combined and used together, and everyone should take advantage of them to solve whatever problems they may have!</p> <p>Goose library gets lots of solid maintenance, they just added Arabic support, it's great!</p>
14,165,771
2
9
null
2013-01-04 20:21:32.103 UTC
12
2021-02-08 09:52:47.707 UTC
2021-02-08 09:52:47.707 UTC
null
2,318,649
null
1,660,802
null
1
8
python|beautifulsoup|web-crawler
4,105
<p>You might look at the <a href="https://github.com/buriy/python-readability" rel="noreferrer">python-readability</a> package which does exactly this for you.</p>
14,274,727
Android browser refreshes page after selecting file via input element
<p>I have a mobile web page which includes an input element of type 'file', to allow users to upload image files to a server. The page works fine on iOS, and on a Nexus 4 (Android 4.2.1) in the Chrome Browser. </p> <p>When I use a Samsung S3 (Android 4.0.4) with the default browser clicking on the 'Choose file' button opens the image selection dialog as expected, however after I choose an image and close the dialog the web page gets refreshed, so I lose the image that was selected. Has anyone else seen this behaviour? Any suggestions for a workaround?</p> <p>The input element that I'm using is fairly standard, and looks like this:</p> <pre><code>&lt;input id="addPhoto" type="file" accept="image/*"/&gt; </code></pre> <p>Even without the 'accept' attribute I get the same problem.</p>
16,568,062
3
1
null
2013-01-11 09:03:21.073 UTC
8
2018-03-07 07:22:47.36 UTC
2013-01-11 09:24:01.203 UTC
null
138,256
null
138,256
null
1
33
android|mobile-website|html-input
9,674
<p>Have a look a this issue:</p> <p><a href="https://code.google.com/p/android/issues/detail?id=53088">https://code.google.com/p/android/issues/detail?id=53088</a></p> <p>Basically, what seems to be happening is this:</p> <ul> <li><p>Android does not have enough memory available for the file-chooser or camera app.</p></li> <li><p>It frees up memory by closing the browser</p></li> <li><p>After the file chooser/camera is closed the browser is opened again, triggering a page refresh, which renders the whole file choosing exercise useless.</p></li> </ul> <p>It seems to me that this is beyond the control of any browser based solution <strong>but I would love to be proven wrong on this assumption</strong>.</p>
14,194,752
rails 4 asset pipeline vendor assets images are not being precompiled
<p>I'm using rails 4 &amp; ruby 1.9.3 for my application and <code>fancybox2-rails</code> gem, but there's a general problem with asset pipeline. If I run <code>rake task</code> for precompile, then everything is fine except for images in <code>vendor/assets/images</code> and <code>../gems/ruby-1.9.3-p327/gems/fancybox2-rails-0.2.1/vendor/assets/images</code>. Images from these two folders are not being precompiled and eventually I have a problem with dead links to non-existing images. Any suggestions?</p>
14,195,512
3
0
null
2013-01-07 11:13:46.567 UTC
15
2017-02-04 07:28:48.793 UTC
2015-11-27 12:07:36.997 UTC
null
1,831,520
null
484,363
null
1
61
asset-pipeline|ruby-on-rails-4
26,526
<p>It seems like images are included by default only from app/assets folder. So the solution is to add this line to config/application.rb</p> <pre><code>config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif) </code></pre>
13,999,659
Conditionally change img src based on model data
<p>I want to represent model data as different images using Angular but having some trouble finding the "right" way to do it. The Angular <a href="http://docs.angularjs.org/guide/expression" rel="noreferrer">API docs on expressions</a> say that conditional expressions are not allowed...</p> <p>Simplifying a lot, the model data is fetched via AJAX and shows you the status of each interface on a router. Something like:</p> <pre><code>$scope.interfaces = ["UP", "DOWN", "UP", "UP", "UP", "UP", "DOWN"] </code></pre> <p>So, in Angular, we can display the state of each interface with something like:</p> <pre><code>&lt;ul&gt; &lt;li ng-repeat=interface in interfaces&gt;{{interface}} &lt;/ul&gt; </code></pre> <p>BUT - Instead of the values from the model, I'd like to show a suitable image. Something following this general idea.</p> <pre><code>&lt;ul&gt; &lt;li ng-repeat=interface in interfaces&gt; {{if interface=="UP"}} &lt;img src='green-checkmark.png'&gt; {{else}} &lt;img src='big-black-X.png'&gt; {{/if}} &lt;/ul&gt; </code></pre> <p><em>(I think Ember supports this type of construct)</em></p> <p>Of course, I could modify the controller to return image URLs based on the actual model data but that seems to violate the separation of model and view, no?</p> <p><a href="https://stackoverflow.com/questions/13781685/angularjs-ng-src-equivalent-for-background-imageurl/13782311#13782311">This SO Posting</a> suggested using a directive to change the bg-img source. But then we are back to putting URLs in the JS not the template...</p> <p>All suggestions appreciated. Thanks. </p> <p><em>please excuse any typos</em></p>
13,999,837
5
0
null
2012-12-22 02:50:25.287 UTC
21
2018-09-27 05:51:16.533 UTC
2017-05-23 10:31:29.493 UTC
null
-1
null
883,572
null
1
74
angularjs
108,402
<p>Instead of <code>src</code> you need <code>ng-src</code>. </p> <p>AngularJS views support binary operators</p> <pre><code>condition &amp;&amp; true || false </code></pre> <p>So your <code>img</code> tag would look like this</p> <pre><code>&lt;img ng-src="{{interface == 'UP' &amp;&amp; 'green-checkmark.png' || 'big-black-X.png'}}"/&gt; </code></pre> <p><strong>Note</strong> : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes.</p> <p><a href="http://plnkr.co/edit/vwNAE3tQxE6VzO0TLDsk?p=preview">plunker here</a> <em>(open dev tools to see the produced HTML)</em></p>
29,335,758
Using kbhit() and getch() on Linux
<p>On Windows, I have the following code to look for input without interrupting the loop:</p> <pre><code>#include &lt;conio.h&gt; #include &lt;Windows.h&gt; #include &lt;iostream&gt; int main() { while (true) { if (_kbhit()) { if (_getch() == 'g') { std::cout &lt;&lt; "You pressed G" &lt;&lt; std::endl; } } Sleep(500); std::cout &lt;&lt; "Running" &lt;&lt; std::endl; } } </code></pre> <p>However, seeing that there is no <code>conio.h</code>, whats the simplest way of achieving this very same thing on Linux?</p>
29,336,049
5
3
null
2015-03-29 22:36:16.08 UTC
12
2020-10-23 16:50:55.907 UTC
null
null
null
null
2,358,221
null
1
17
c++|linux|getch|conio|kbhit
57,520
<p>The ncurses howto cited above can be helpful. Here is an example illustrating how ncurses could be used like the conio example:</p> <pre><code>#include &lt;ncurses.h&gt; int main() { initscr(); cbreak(); noecho(); scrollok(stdscr, TRUE); nodelay(stdscr, TRUE); while (true) { if (getch() == 'g') { printw("You pressed G\n"); } napms(500); printw("Running\n"); } } </code></pre> <p>Note that with ncurses, the <code>iostream</code> header is not used. That is because mixing stdio with ncurses can have unexpected results.</p> <p>ncurses, by the way, defines <code>TRUE</code> and <code>FALSE</code>. A correctly configured ncurses will use the same data-type for ncurses' <code>bool</code> as the C++ compiler used for configuring ncurses.</p>
9,106,536
Why do I get permission denied when I try use "make" to install something?
<p>I'm trying to install something and it's throwing me an error: <code>Permission denied</code> when I try to run <code>make</code> on it.</p> <p>I'm not too fond of the universal rules of unix/linux and not too fond of user rights either. My best guess is that the user I'm logged in as does not have the privileges to run <code>make</code> commands, but hopefully it's something else that's not permitting me to install.</p> <p>Why do I get <code>Permission denied</code> and what should I check or configure in order to attempt permission be granted? </p> <p><b>EDIT</b></p> <p>Error Message:</p> <pre><code>gcc -I. -O3 -o pp-inspector pp-inspector.c make: execvp: gcc: Permission denied make: [pp-inspector] Error 127 (ignored) gcc -I. -O3 -c tis-vnc.c -DLIBOPENSSL -DLIBOPENSSLNEW -DLIBIDN -DHAVE_PR29_H -DLIBMYSQLCLIENT -DLIBPOSTGRES -DHAVE_MATH_H -I/usr/include/mysql make: execvp: gcc: Permission denied make: *** [tis-vnc.o] Error 127 </code></pre>
9,107,585
5
1
null
2012-02-02 02:53:46.063 UTC
9
2022-06-30 13:04:48.293 UTC
2012-02-02 03:02:14.03 UTC
null
42,229
null
42,229
null
1
30
linux|command-line|permissions|makefile
137,884
<p>On many source packages (e.g. for most GNU software), the building system may know about the <code>DESTDIR</code> <em>make</em> variable, so you can often do:</p> <pre><code> make install DESTDIR=/tmp/myinst/ sudo cp -va /tmp/myinst/ / </code></pre> <p>The advantage of this approach is that <code>make install</code> don't need to run as root, so you cannot end up with files compiled as root (or root-owned files in your build tree).</p>
19,357,965
in a for-loop, what does the (int i : tall) do, where tall is an array of int
<p>As the header says, I was tipped by some people that if I wanted to print the sum of everything in an array of numbers, I should use the above-mentioned parameter for a for-loop (code will follow if further explanation is needed). But what is the exact definiton of what that does? The :-part I mean. Is it; for every number i in the array tall?</p> <pre><code>import java.util.*; class Uke36{ public static void main(String[]args){ Scanner input=new Scanner(System.in); int[] tall=new int[5]; for (int i=0; i&lt;=4; i++){ System.out.println("Vennligst oppgi det " + (i+1) + ". tallet: "); tall[i]=input.nextInt(); } int sum = 0; for(int i : tall){ sum+=; } } } </code></pre>
19,357,984
7
2
null
2013-10-14 10:13:11.773 UTC
2
2019-09-09 06:57:50.87 UTC
null
null
null
null
2,812,314
null
1
13
java|arrays|for-loop
74,195
<p>This is how <code>for-each</code> loops are represented in Java.</p> <pre><code>for (int i : tall) { sum += i; } </code></pre> <p>Read it as: For each integer <code>i</code> in the array called <code>tall</code> ...</p>
580,622
Dynamic array... copy constructor, destructor, overloaded assignment operator
<p>I am studying for my midterm exam. There is going to be a question about setting up an array dynamically, and maybe doing a copy constructor, a destructor and overloading the assignment operator. Can you please verify if I am correct. Also I don't understand what overloading the assignment operator means. Can you help me out with this?</p> <pre><code>class A { int* myArray; //basically I created a pointer called myArray, A() //are my copy constructors correct? A(), and A(int size)? { myArray = 0; } A(int size) { myArray = new int[size]; } ~A() // I think my destructor is correct { delete [] myArray; } </code></pre> <p>Can you check my code please? Also how do I overload assignment operator?</p> <p>Thanks in advance.</p>
580,628
5
1
null
2009-02-24 06:00:00.61 UTC
8
2013-04-17 09:15:02.417 UTC
2012-10-02 19:33:41.337 UTC
dirkgently
300,311
null
69,699
null
1
5
c++|constructor
43,117
<p>The copy constructor is used for creation of object based on another's instance of the same type. You don't have such. You can define it using code like this:</p> <pre><code>A(const A &amp;other) { myArray = new int[other._size]; _size = other._size; memcpy(myArray, other.myArray, sizeof(int) * _size); } </code></pre> <p>You should change your class, so it will store _size of array, you also need to change visibility of your constructors and destructor to public.</p> <p>The overloaded assignment operator should look like this:</p> <pre><code>const A &amp;operator=(const A &amp;other) { if(this == &amp;other) return *this; // handling of self assignment, thanks for your advice, arul. delete[] myArray; // freeing previously used memory myArray = new int[other._size]; _size = other._size; memcpy(myArray, other.myArray, sizeof(int) * _size); return *this; } </code></pre> <p>You also can add a check of equality of array sizes in this assignment operator, so you will reuse your dynamic array without unnecessary reallocations of memory.</p>
1,329,458
MySQL - How to SUM times?
<p>I have a table that contains date-time values in this format:</p> <p><strong>START</strong> </p> <p>1/13/2009 7:00:00AM </p> <p><strong>END</strong></p> <p>1/13/2008 2:57:00PM</p> <p>I use the 'str to date' function to convert these into a date-time format.</p> <p>How do I calculate a difference between them? And then sum it all up so that it displays in total hours (ie total hours for week is 40:53).</p> <p>I was trying the timediff function but the results don't sum.</p>
1,329,523
5
0
null
2009-08-25 16:37:57.17 UTC
1
2011-05-16 23:49:31.25 UTC
null
null
null
null
127,776
null
1
10
mysql
55,132
<p>Try looking into <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_unix-timestamp" rel="noreferrer"><code>UNIX_TIMESTAMP</code></a> and <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_sec-to-time" rel="noreferrer"><code>SEC_TO_TIME</code></a>. </p> <p>You would sum up the differences between the timestamps, then use that value (would be in milliseconds) to get the time:</p> <pre><code>SELECT SEC_TO_TIME(time_milis / 1000) FROM ( SELECT SUM(UNIX_TIMESTAMP(date1) - UNIX_TIMESTAMP(date2)) as time_milis FROM table ) </code></pre>
1,129,517
C# How to find if an event is hooked up
<p>I want to be able to find out if an event is hooked up or not. I've looked around, but I've only found solutions that involved modifying the internals of the object that contains the event. I don't want to do this.</p> <p>Here is some test code that I thought would work:</p> <pre><code>// Create a new event handler that takes in the function I want to execute when the event fires EventHandler myEventHandler = new EventHandler(myObject_SomeEvent); // Get "p1" number events that got hooked up to myEventHandler int p1 = myEventHandler.GetInvocationList().Length; // Now actually hook an event up myObject.SomeEvent += m_myEventHandler; // Re check "p2" number of events hooked up to myEventHandler int p2 = myEventHandler.GetInvocationList().Length; </code></pre> <p>Unfort the above is dead wrong. I thought that somehow the "invocationList" in myEventHandler would automatically get updated when I hooked an event to it. But no, this is not the case. The length of this always comes back as one.</p> <p>Is there anyway to determine this from outside the object that contains the event?</p>
1,129,530
5
0
null
2009-07-15 05:16:42.397 UTC
24
2020-12-15 13:52:45.34 UTC
null
null
null
null
88,364
null
1
40
c#|hook|event-handling
60,834
<p>There is a subtle illusion presented by the C# <code>event</code> keyword and that is that an event has an invocation list.</p> <p>If you declare the event using the C# <code>event</code> keyword, the compiler will generate a private delegate in your class, and manage it for you. Whenever you subscribe to the event, the compiler-generated <code>add</code> method is invoked, which appends the event handler to the delegate's invocation list. There is no explicit invocation list for the event.</p> <p>Thus, the only way to get at the delegate's invocation list is to preferably:</p> <ul> <li>Use reflection to access the compiler-generated delegate OR</li> <li>Create a non-private delegate (perhaps internal) and implement the event's add/remove methods manually (this prevents the compiler from generating the event's default implementation)</li> </ul> <p>Here is an example demonstrating the latter technique.</p> <pre><code>class MyType { internal EventHandler&lt;int&gt; _delegate; public event EventHandler&lt;int&gt; MyEvent; { add { _delegate += value; } remove { _delegate -= value; } } } </code></pre>
626,631
How to Relocate Visual Studio project (.sln) file
<p>I would like to move the Visual Studio solution (myProject.sln) file into a folder.</p> <p>The problem with doing this is that all the relative paths in the project will break, how can you relocate the project without updating all relative paths inside the project manually?</p> <p>Thanks.</p>
626,646
5
0
null
2009-03-09 15:14:45.317 UTC
12
2018-10-25 02:35:45.613 UTC
2014-01-13 16:29:51.983 UTC
null
2,483,451
Brock Woolf
40,002
null
1
53
visual-studio|relative-path
34,867
<p>Just click on the solution in the Solution Explorer and then click on "Save myProject.sln as..." in the File Menu. This will save your .sln in the folder that you choose without breaking the references.</p>
340,827
How to MOQ an Indexed property
<p>I am attempting to mock a call to an indexed property. I.e. I would like to moq the following:</p> <pre><code>object result = myDictionaryCollection["SomeKeyValue"]; </code></pre> <p>and also the setter value</p> <pre><code>myDictionaryCollection["SomeKeyValue"] = myNewValue; </code></pre> <p>I am doing this because I need to mock the functionality of a class my app uses. </p> <p>Does anyone know how to do this with MOQ? I've tried variations on the following:</p> <pre><code>Dictionary&lt;string, object&gt; MyContainer = new Dictionary&lt;string, object&gt;(); mock.ExpectGet&lt;object&gt;( p =&gt; p[It.IsAny&lt;string&gt;()]).Returns(MyContainer[(string s)]); </code></pre> <p>But that doesn't compile.</p> <p>Is what I am trying to achieve possible with MOQ, does anyone have any examples of how I can do this?</p>
649,645
5
1
null
2008-12-04 14:51:36.163 UTC
4
2018-10-18 19:21:52.55 UTC
null
null
null
Ash
31,128
null
1
100
c#|tdd|mocking|moq
31,662
<p>It appears that what I was attempting to do with MOQ is not possible.</p> <p>Essentially I was attempting to MOQ a HTTPSession type object, where the key of the item being set to the index could only be determined at runtime. Access to the indexed property needed to return the value which was previously set. This works for integer based indexes, but string based indexes do not work.</p>
1,026,925
Algorithms for named entity recognition
<p>I would like to use named entity recognition (NER) to find adequate tags for texts in a database.</p> <p>I know there is a Wikipedia article about this and lots of other pages describing NER, I would preferably hear something about this topic from you:</p> <ul> <li>What experiences did you make with the various algorithms?</li> <li>Which algorithm would you recommend?</li> <li>Which algorithm is the easiest to implement (PHP/Python)?</li> <li>How to the algorithms work? Is manual training necessary?</li> </ul> <p>Example:</p> <p>"Last year, I was in London where I saw Barack Obama." => Tags: London, Barack Obama</p> <p>I hope you can help me. Thank you very much in advance!</p>
1,027,336
6
0
null
2009-06-22 12:26:33.677 UTC
17
2017-07-25 08:35:08.533 UTC
null
null
null
null
89,818
null
1
22
php|python|extract|analysis|named-entity-recognition
9,739
<p>To start with check out <a href="http://www.nltk.org/" rel="noreferrer">http://www.nltk.org/</a> if you plan working with python although as far as I know the code isn't "industrial strength" but it will get you started.</p> <p>Check out section 7.5 from <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html" rel="noreferrer">http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html</a> but to understand the algorithms you probably will have to read through a lot of the book.</p> <p>Also check this out <a href="http://nlp.stanford.edu/software/CRF-NER.shtml" rel="noreferrer">http://nlp.stanford.edu/software/CRF-NER.shtml</a>. It's done with java, </p> <p>NER isn't an easy subject and probably nobody will tell you "this is the best algorithm", most of them have their pro/cons.</p> <p>My 0.05 of a dollar.</p> <p>Cheers,</p>
32,583,345
how to do `var self = this` inside es6 class?
<p>I am running the below code in nodejs</p> <pre><code>this.x = 'global x'; class Point { constructor(x) { this.x = x; } toString() { return this.x; } } var obj = new Point(1); obj.toString();// 1 as expected var a = obj.toString;// Here I can do something like var a = obj.toString.bind(obj); to get rid of the situation. But I am curious to know how can we write `var self = this`; a();// TypeError: Cannot read property 'x' of undefined </code></pre> <p><code>a();</code> throws the error.<br> How can we do like <code>var self = this;</code> as we used to do in <code>es5</code> to prevent such a situation?</p>
32,588,722
2
6
null
2015-09-15 10:10:39.333 UTC
6
2015-11-06 08:23:15.13 UTC
2015-09-15 10:25:44.25 UTC
null
3,678,949
null
3,678,949
null
1
34
javascript|ecmascript-6
18,193
<blockquote> <p>How can we do like <code>var self = this;</code> as we used to do in ES5?</p> </blockquote> <p>You can do it exactly like you did in ES5 - ES6 is completely backward-compatible after all:</p> <pre><code>class Point { constructor(x) { this.x = x; var self = this; this.toString = function() { return self.x; }; } } </code></pre> <p>However, that's really not idiomatic ES6 (not talking about <code>const</code> instead of <code>var</code>). You'd rather use an arrow function that has a lexical-scoped <code>this</code>, so that you can avoid this <code>self</code> variable completely:</p> <pre><code>class Point { constructor(x) { this.x = x; this.toString = () =&gt; { return this.x; }; } } </code></pre> <p>(which could even be shortened to <code>this.toString = () =&gt; this.x;</code>)</p>
38,032,635
Pass multiple parameters to rest API - Spring
<p>I am trying to figure out if it is possible to pass a JSON object to rest API, Or pass a multiple parameters to that API ? And how to read these parameters in Spring ? Lets assume that the url looks like the below examples : </p> <p>Ex.1 <code>http://localhost:8080/api/v1/mno/objectKey?id=1&amp;name=saif</code></p> <p>Is it valid to pass a JSON object like in the url below ?</p> <p>Ex.2 <code>http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}</code></p> <p>Questions:</p> <p>1) Is it possible to pass a JSON object to the url like in Ex.2?</p> <p>2) How can we pass and parse the parameters in Ex.1? </p> <p>I tried to write some methods to achieve my goal, but could not find the right solution?</p> <p>I tried to pass JSON object as @RequestParam</p> <p><code>http://localhost:8080/api/v1/mno/objectKey?id=1</code> There was an unexpected error <code>(type=Unsupported Media Type, status=415). Content type 'null' not supported</code></p> <p><code>http://localhost:8080/api/v1/mno/objectKey/id=1</code> There was an unexpected error <code>(type=Not Found, status=404). No message available</code></p> <p><code>http://localhost:8080/api/v1/mno/objectKey/%7B%22id%22:1%7D</code> There was an unexpected error <code>(type=Not Found, status=404). No message available</code></p> <pre><code>@RequestMapping(value="mno/{objectKey}", method = RequestMethod.GET, consumes="application/json") public List&lt;Book&gt; getBook4(@RequestParam ObjectKey objectKey) { ... } </code></pre> <p>I tried to pass the JSON object as @PathVariable</p> <pre><code>@RequestMapping(value="ghi/{objectKey}",method = RequestMethod.GET) public List&lt;Book&gt; getBook2(@PathVariable ObjectKey objectKey) { ... } </code></pre> <p>I created this object to hold the id parameter and other parameters like name , etc .... </p> <pre><code>class ObjectKey{ long id; public long getId() { return id; } public void setId(long id) { this.id = id; } } </code></pre>
38,032,778
4
3
null
2016-06-25 20:20:52.24 UTC
25
2022-03-27 13:04:48.783 UTC
2016-06-25 21:18:41.09 UTC
null
3,960,264
null
5,285,894
null
1
48
java|json|spring|rest|spring-mvc
324,836
<blockquote> <p>(1) Is it possible to pass a JSON object to the url like in Ex.2?</p> </blockquote> <p>No, because <code>http://localhost:8080/api/v1/mno/objectKey/{&quot;id&quot;:1, &quot;name&quot;:&quot;Saif&quot;}</code> is not a valid URL.</p> <p>If you want to do it the RESTful way, use <code>http://localhost:8080/api/v1/mno/objectKey/1/Saif</code>, and defined your method like this:</p> <pre><code>@RequestMapping(path = &quot;/mno/objectKey/{id}/{name}&quot;, method = RequestMethod.GET) public Book getBook(@PathVariable int id, @PathVariable String name) { // code here } </code></pre> <blockquote> <p>(2) How can we pass and parse the parameters in Ex.1?</p> </blockquote> <p>Just add two request parameters, and give the correct path.</p> <pre><code>@RequestMapping(path = &quot;/mno/objectKey&quot;, method = RequestMethod.GET) public Book getBook(@RequestParam int id, @RequestParam String name) { // code here } </code></pre> <p><strong>UPDATE</strong> <em>(from comment)</em></p> <blockquote> <p>What if we have a complicated parameter structure ?</p> <pre><code>&quot;A&quot;: [ { &quot;B&quot;: 37181, &quot;timestamp&quot;: 1160100436, &quot;categories&quot;: [ { &quot;categoryID&quot;: 2653, &quot;timestamp&quot;: 1158555774 }, { &quot;categoryID&quot;: 4453, &quot;timestamp&quot;: 1158555774 } ] } ] </code></pre> </blockquote> <p>Send that as a <code>POST</code> with the JSON data in the request body, not in the URL, and specify a content type of <code>application/json</code>.</p> <pre><code>@RequestMapping(path = &quot;/mno/objectKey&quot;, method = RequestMethod.POST, consumes = &quot;application/json&quot;) public Book getBook(@RequestBody ObjectKey objectKey) { // code here } </code></pre>
21,333,646
Stream and the distinct operation
<p>I have the following code:</p> <pre><code>class C { String n; C(String n) { this.n = n; } public String getN() { return n; } @Override public boolean equals(Object obj) { return this.getN().equals(((C)obj).getN()); } } List&lt;C&gt; cc = Arrays.asList(new C("ONE"), new C("TWO"), new C("ONE")); System.out.println(cc.parallelStream().distinct().count()); </code></pre> <p>but I don't understand why <code>distinct</code> returns 3 and not 2.</p>
21,334,090
1
5
null
2014-01-24 13:13:38.283 UTC
4
2016-03-11 08:03:19.997 UTC
2015-02-14 08:48:19.31 UTC
null
1,441,122
null
65,120
null
1
38
java|java-8|java-stream
35,984
<p>You need to also override the <code>hashCode</code> method in class <code>C</code>. For example:</p> <pre><code>@Override public int hashCode() { return n.hashCode(); } </code></pre> <p>When two <code>C</code> objects are equal, their <code>hashCode</code> methods must return the same value.</p> <p>The API documentation for interface <code>Stream</code> does not mention this, but it's well-known that if you override <code>equals</code>, you should also override <code>hashCode</code>. The API documentation for <code>Object.equals()</code> mentions this:</p> <blockquote> <p>Note that it is generally necessary to override the <code>hashCode</code> method whenever this method is overridden, so as to maintain the general contract for the <code>hashCode</code> method, which states that equal objects must have equal hash codes.</p> </blockquote> <p>Apparently, <code>Stream.distinct()</code> indeed uses the hash code of the objects, because when you implement it like I showed above, you get the expected result: 2.</p>
21,260,039
How do I permanently exclude the bin and obj folders from TFS 2012 checkin?
<p>I mucked around with TFS settings and I accidentally included the bin and obj folders for TFS 2012 checkin, and even checked them in already. I don't want this because these files change often and aren't meant for inclusion.</p> <p>I've checked <a href="https://stackoverflow.com/questions/13765372/what-happened-to-exclude-from-source-control-in-vs2012">What happened to &quot;Exclude from Source Control&quot; in VS2012</a>. The accepted answer doesn't work because the bin &amp; obj folders and the DLLs inside those folders don't appear in the "Promote Candidate Changes" list, even after excluding them. The second most popular answer also doesn't work permanently. I press yes to all and it removes them from the included changes list, but when I do any action involving rebuilding, they're added to include list again.</p> <p>I'm looking for a permanent solution which will permanently exclude these folders and the files inside from checkin, and if possible also removes them from the TFS server.</p>
21,260,759
3
7
null
2014-01-21 13:50:05.987 UTC
5
2018-11-07 22:33:24.597 UTC
2017-05-23 12:09:53.373 UTC
null
-1
null
1,770,430
null
1
30
visual-studio-2012|tfvc
28,440
<p>TFS 2012 has the option to <a href="http://msdn.microsoft.com/en-us/library/ms245454.aspx#tfignore" rel="noreferrer">drop a <code>.tfIgnore</code> file in your workspace</a>.</p> <p>Visual studio has a UI to create the file for you:</p> <p>While you can manually create a <code>.tfignore</code> text file using the above rules, you can also automatically generate one when the Pending Changes page has detected a change.</p> <p>To automatically generate a <code>.tfignore</code> file</p> <ul> <li><p>In the Pending Changes page, in the Excluded Changes section, choose the Detected changes link.</p> </li> <li><p>The Promote Candidate Changes dialogue box appears.</p> </li> <li><p>Select a file, open its context menu, and choose <kbd>Ignore this local item</kbd>, <kbd>Ignore by extension</kbd>, or <kbd>Ignore by file name</kbd>.</p> </li> <li><p>Choose <kbd>OK</kbd> or <kbd>Cancel</kbd> to close the Promote Candidate Changes dialog box.</p> </li> <li><p>A <code>.tfignore</code> file appears in the Included Changes section of the Pending Changes page. You can open this file and modify it to meet your needs.</p> </li> <li><p>The <code>.tfignore</code> file is automatically added as an included pending change so that the rules you have created will apply to each team member who gets the file.</p> </li> </ul> <p>Or create it from the command line using <code>echo . &gt; .tfIgnore</code> and then open it using notepad.</p> <p>Another trick is to name the file <code>.tfIgnore.</code> in explorer and save it. You'll probably be prompted if you want to change the extension, the answer, in this case, is: yes.</p>
44,027,926
Update xampp from maria db 10.1 to 10.2
<p>I am looking for solution on how to update <code>mariadb</code> on <code>xampp 32 bit</code> on window system but not found any article on that.I just found this <a href="https://mariadb.com/kb/en/mariadb/upgrading-from-mariadb-55-to-mariadb-100/" rel="noreferrer">link</a>. Please help me how to update. I want <code>JSON</code> support that's why I am looking for update from <code>V10.1</code> to <code>V10.2</code>. Or if there is any other way to do this please let me know</p> <p>Current version is <code>10.1.19-MariaDB</code></p>
47,490,206
7
2
null
2017-05-17 14:37:48.253 UTC
19
2022-06-27 12:34:24.513 UTC
2017-05-17 14:40:13.67 UTC
null
3,026,639
null
3,026,639
null
1
39
php|database|xampp|mariadb
35,862
<p>1 : Shutdown or Quit your XAMPP server from Xampp control panel.<br> 2 : Download the <strong>ZIP version</strong> of <a href="https://downloads.mariadb.org/mariadb/10.2.10/" rel="noreferrer">MariaDB</a><br> 3 : Rename the xampp/mysql folder to mysql_old.<br> 4 : <strong>Unzip</strong> or <strong>Extract</strong> the contents of the MariaDB ZIP file into your XAMPP folder.<br> 5 : Rename the MariaDB folder, called something like mariadb-5.5.37-win32, to mysql.<br> 6 : Rename xampp/mysql/data to data_old.<br> 7 : Copy the xampp/mysql_old/data folder to xampp/mysql/.<br> 8 : Copy the xampp/mysql_old/backup folder to xampp/mysql/.<br> 9 : Copy the xampp/mysql_old/scripts folder to xampp/mysql/.<br> 10: Copy mysql_uninstallservice.bat and mysql_installservice.bat from xampp/mysql_old/ into xampp/mysql/.<br> 11 : Copy xampp/mysql_old/bin/my.ini into xampp/mysql/bin.<br> 12 : Edit xampp/mysql/bin/my.ini using a text editor like Notepad. Find <strong>skip-federated</strong> and add a # in front (to the left) of it to comment out the line if it exists. Save and exit the editor.<br> 13 : Start-up XAMPP.<br> <strong>Note</strong> If you can't get mysql to start from Xampp control panel. Add this 'skip-grant-tables' statement anywhere in xampp/mysql/bin/my.ini file<br> 14 : Run xampp/mysql/bin/mysql_upgrade.exe.<br> 15 : Shutdown and restart MariaDB (MySQL).<br> If still <strong>mysql is not started then follow below Note steps(!Important)</strong></p> <p><strong>Note</strong> :<strong>mysql error log file:</strong> c:\xampp\mysql\bin\mysqld.exe: unknown variable 'innodb_additional_mem_pool_size=2M' like please remove or commented this statement in my.ini file in this path <strong>xampp/mysql/bin/my.ini file</strong>.</p> <p>Help from this <a href="http://articlebin.michaelmilette.com/how-to-upgrade-mysql-to-mariadb-in-xampp-in-5-minutes-on-windows/#comment-22690" rel="noreferrer">link</a>.</p>
17,881,366
SVN Upgrade working copy - TortoiseSVN
<p>I upgraded my TortoiseSVN client to version 1.8 and made a fresh checkout of a repository.</p> <p>I made some changes in files and now trying to commit by right clicking on project folder but I'm not able to do it. It shows me 'SVN Upgrade working copy' in context menu, when I try to upgrade it from there, it does not work and kept asking me? I'm not able to commit my changes.</p> <p>Any idea how to upgrade my local repository? Or it is something to do with the server SVN version? </p>
20,115,565
2
4
null
2013-07-26 12:30:34.46 UTC
1
2014-01-23 19:30:15.103 UTC
null
null
null
null
827,716
null
1
25
svn|tortoisesvn
45,262
<p>It is just to reboot after installation and it will allow you to commit the files. </p>
23,251,900
ASP.NET MVC: 404 - File or directory not found. The resource you are looking for
<p>I recently deployed an ASP.NET MVC application on a Win server 2008, IIS 7 machine. It has MVC installed, and .NET framework 4.5 installed. Whenever I publish, and try to log in, I get this annoying error:</p> <pre><code>404 - File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable. </code></pre> <p>Meanwhile the controller action - Home/Login is intact and the Login.cshtml page is okay. Plus the web config file has</p> <pre> modules runAllManagedModulesForAllRequests="true"/> compilation debug="true" targetFramework="4.5"> assemblies> handlers> remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/> remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/> remove name="ExtensionlessUrlHandler-Integrated-4.0"/> add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" /handlers> </pre> <p>So I am wondering what is wrong. It is running under Integrated mode, ASP.NET 4.0 app pool. Static content and dynamic content are both enabled. I guess you can tell I have gone through most of the posts on this issue.:) Thanks in advance for the answer.</p>
23,253,286
3
2
null
2014-04-23 18:01:08.383 UTC
1
2019-03-14 13:58:11.727 UTC
null
null
null
null
464,512
null
1
3
asp.net-mvc|iis-7|windows-server-2003
39,291
<p>If possible, I would log onto the server that is hosting the application, Open IIS Manager, find your site and click view in browser. This will ensure that you have the URL correct and should give you more debugging information if something is going wrong.</p>
23,017,716
JSON.net: how to deserialize without using the default constructor?
<p>I have a class that has a default constructor and also an overloaded constructor that takes in a set of parameters. These parameters match to fields on the object and are assigned on construction. At this point i need the default constructor for other purposes so i would like to keep it if i can.</p> <p>My Problem: If I remove the default constructor and pass in the JSON string, the object deserializes correctly and passes in the constructor parameters without any issues. I end up getting back the object populated the way I would expect. However, as soon as I add the default constructor into the object, when i call <code>JsonConvert.DeserializeObject&lt;Result&gt;(jsontext)</code> the properties are no longer populated.</p> <p>At this point I have tried adding <code>new JsonSerializerSettings(){CheckAdditionalContent = true}</code> to the deserialization call. That did not do anything.</p> <p>Another note: the constructor parameters do match the names of the fields exactly except that the parameters are start with a lowercase letter. I wouldn't think this would matter since, like i mentioned, the deserialization works fine with no default constructor.</p> <p>Here is a sample of my constructors:</p> <pre><code>public Result() { } public Result(int? code, string format, Dictionary&lt;string, string&gt; details = null) { Code = code ?? ERROR_CODE; Format = format; if (details == null) Details = new Dictionary&lt;string, string&gt;(); else Details = details; } </code></pre>
23,017,892
6
3
null
2014-04-11 16:16:59.95 UTC
44
2022-02-16 19:02:43.34 UTC
2021-02-23 06:34:34.35 UTC
null
2,874,896
null
1,483,106
null
1
179
c#|json|json.net
154,313
<p>Json.Net prefers to use the default (parameterless) constructor on an object if there is one. If there are multiple constructors and you want Json.Net to use a non-default one, then you can add the <code>[JsonConstructor]</code> attribute to the constructor that you want Json.Net to call.</p> <pre><code>[JsonConstructor] public Result(int? code, string format, Dictionary&lt;string, string&gt; details = null) { ... } </code></pre> <p>It is important that the constructor parameter names match the corresponding property names of the JSON object (ignoring case) for this to work correctly. You do not necessarily have to have a constructor parameter for every property of the object, however. For those JSON object properties that are not covered by the constructor parameters, Json.Net will try to use the public property accessors (or properties/fields marked with <code>[JsonProperty]</code>) to populate the object after constructing it.</p> <p>If you do not want to add attributes to your class or don't otherwise control the source code for the class you are trying to deserialize, then another alternative is to create a custom <a href="http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverter.htm" rel="noreferrer">JsonConverter</a> to instantiate and populate your object. For example:</p> <pre><code>class ResultConverter : JsonConverter { public override bool CanConvert(Type objectType) { return (objectType == typeof(Result)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // Load the JSON for the Result into a JObject JObject jo = JObject.Load(reader); // Read the properties which will be used as constructor parameters int? code = (int?)jo["Code"]; string format = (string)jo["Format"]; // Construct the Result object using the non-default constructor Result result = new Result(code, format); // (If anything else needs to be populated on the result object, do that here) // Return the result return result; } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } </code></pre> <p>Then, add the converter to your serializer settings, and use the settings when you deserialize:</p> <pre><code>JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new ResultConverter()); Result result = JsonConvert.DeserializeObject&lt;Result&gt;(jsontext, settings); </code></pre>
2,037,579
Java OpenCV Bindings
<p>I am looking for OpenCV java bindings, all the references point to the processing library. I know processing is java but isn't there a standalone java lib? or should just use processing libs?</p>
2,176,156
5
0
null
2010-01-10 16:16:01.35 UTC
15
2017-01-03 10:09:19.37 UTC
null
null
null
null
89,904
null
1
23
java|opencv
33,573
<p>I have just found this, a java wrapper of OpenCV : <a href="https://github.com/bytedeco/javacv" rel="nofollow noreferrer">https://github.com/bytedeco/javacv</a></p> <p>Not tested, but I would love to have your point of view about this.</p>
2,268,239
Why is my Android emulator keyboard in Chinese character mode?
<p>I'm debugging my Android application using the AVD (Android Virtual Device). When I try to enter text in a text field, my characters are being interpreted as Chinese in the IME.</p> <p>I don't know how I got into this mode or how to get out of it (I just want to enter alphabetic keys)?</p> <p>Here's a screen shot:</p> <p><img src="https://i.stack.imgur.com/KAtNu.jpg" alt="http://u.go2.me/3cn"></p>
2,268,256
5
0
null
2010-02-15 18:57:58.12 UTC
23
2016-04-22 08:26:26.13 UTC
2011-08-11 00:27:14.657 UTC
null
71,421
null
178,521
null
1
160
android|android-emulator
56,135
<p>If you were running <a href="http://developer.android.com/guide/developing/tools/monkey.html" rel="noreferrer"><code>monkey</code></a> at some point, it probably changed the input method &mdash; it happens quite often.</p> <p>You can change the input method by long-pressing on an input field and choosing Input Method &rarr; Android Keyboard. I think you can also long-press on the bottom-left key on the virtual keyboard.</p> <p>Note you can also disable the Japanese and other input methods from being activated entirely via Settings &rarr; Keyboard &rarr; untick the box next to each IME.</p>