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
59,390,492
DSL element 'android.dataBinding.enabled' is obsolete and has been replaced with 'android.buildFeatures.dataBinding'
<p>Gets following warning when building the project</p> <pre><code>DSL element 'android.dataBinding.enabled' is obsolete and has been replaced with 'android.buildFeatures.dataBinding'. </code></pre> <p>I am using <code>Android Studio Canary 6</code></p>
59,390,493
8
0
null
2019-12-18 10:54:40.74 UTC
12
2022-08-17 13:06:54.393 UTC
null
null
null
null
7,356,355
null
1
203
android|android-databinding
89,423
<p>Starting from <code>Android Gradle Plugin 4.0.0-alpha05</code> there is a new block called <code>buildFeatures</code> to enable build features.</p> <p>So in order to enable databinding with new AGP plugin you have do like following in module (ex: app) level gradle file</p> <p><strong>build.gradle ( Groovy DSL )</strong></p> <pre><code>// shorter version // android.buildFeatures.dataBinding true // longer version android { buildFeatures { dataBinding true // for view binding: // viewBinding true } } </code></pre> <p><strong>build.gradle.kts ( Kotlin DSL )</strong></p> <pre><code>// shorter version // android.buildFeatures.dataBinding = true // longer version android { buildFeatures { dataBinding = true // for view binding: // viewBinding = true } } </code></pre> <p>Reference: <a href="https://developer.android.com/studio/releases/gradle-plugin#buildFeatures" rel="noreferrer">https://developer.android.com/studio/releases/gradle-plugin#buildFeatures</a></p>
59,458,433
flutter --flow-control-collections are needed, but are they?
<p>After upgrading flutter (both master and stable versions) and dart, I get an error about the experiment --flow-control-collections not being enabled for various for-loops that I'm using in the project. I tried to fix it using <a href="https://stackoverflow.com/questions/55477046/how-can-i-enable-flutter-dart-language-experiments">this entry</a> but that just made things weirder. So, now I have the below error that tells me that I need the control-flow-collections experiement to be enabled while simultaneously telling me that it's no longer required.</p> <p><a href="https://i.stack.imgur.com/kN3zV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kN3zV.png" alt=" eex"></a></p> <p>This error comes up for every for-loop that I'm using.</p> <p>Here's my flutter --version result:</p> <pre><code>Stable: Flutter 1.12.13+hotfix.5 • channel stable • https://github.com/flutter/flutter.git Framework • revision 27321ebbad (13 days ago) • 2019-12-10 18:15:01 -0800 Engine • revision 2994f7e1e6 Tools • Dart 2.7.0 Master: Flutter 1.13.6-pre.16 • channel master • https://github.com/flutter/flutter.git Framework • revision fcaf9c4070 (2 days ago) • 2019-12-21 14:03:01 -0800 Engine • revision 33813929e3 Tools • Dart 2.8.0 (build 2.8.0-dev.0.0 886615d0f9) </code></pre> <p>Any ideas how to resolve this?</p>
59,461,135
4
0
null
2019-12-23 16:23:34.46 UTC
6
2021-05-03 10:58:10.383 UTC
2020-05-08 20:18:52.633 UTC
null
4,770,729
null
4,770,729
null
1
30
flutter|dart|upgrade
19,820
<p><em>Hey, I had the same issue this morning but found a fix.</em></p> <p>1) Keep the analysis_options.yaml in your root folder with this code:</p> <pre><code>analyzer: enable-experiment: - control-flow-collections </code></pre> <p>2) Don't use brackets {} in between your for loops <strong>Ex:</strong></p> <pre><code>&lt;Widget&gt;[ for (final category in categories) CategoryWidget(category: category) ], </code></pre> <p><strong>3) Important step which is probably why it's not working for you:</strong> Change your Dart version constraint in the pubspec.yml file in your root folder to 2.5.2</p> <pre><code>environment: sdk: "&gt;=2.5.2 &lt;3.0.0" </code></pre>
35,073,669
Window Resize - React + Redux
<p>I'm new to Redux and I'm wondering if anyone has some tips on best practices for handling non React events like window resize. In my research, I found this link from the official React documentation: <a href="https://facebook.github.io/react/tips/dom-event-listeners.html">https://facebook.github.io/react/tips/dom-event-listeners.html</a></p> <p>My questions is, when using Redux, should I store the window size in my Store or should I be keeping it in my individual component state?</p>
35,075,190
3
0
null
2016-01-28 22:49:50.413 UTC
12
2017-02-16 04:57:22.857 UTC
2017-02-16 04:57:22.857 UTC
null
1,612,318
null
2,898,229
null
1
27
javascript|reactjs|redux
17,001
<p>Good question. I like to to have a ui part to my store. The reducer for which might look like this:</p> <pre><code>const initialState = { screenWidth: typeof window === 'object' ? window.innerWidth : null }; function uiReducer(state = initialState, action) { switch (action.type) { case SCREEN_RESIZE: return Object.assign({}, state, { screenWidth: action.screenWidth }); } return state; } </code></pre> <p>The action for which is pretty boilerplate. (<code>SCREEN_RESIZE</code> being a constant string.)</p> <pre><code>function screenResize(width) { return { type: SCREEN_RESIZE, screenWidth: width }; } </code></pre> <p>Finally you wire it together with an event listener. I would put the following code in the place where you initialise your <code>store</code> variable.</p> <pre><code>window.addEventListener('resize', () =&gt; { store.dispatch(screenResize(window.innerWidth)); }); </code></pre> <h2>Media Queries</h2> <p>If your app takes a more binary view of screen size (e.g. large/small), you might prefer to use a media query instead. e.g.</p> <pre><code>const mediaQuery = window.matchMedia('(min-width: 650px)'); if (mediaQuery.matches) { store.dispatch(setLargeScreen()); } else { store.dispatch(setSmallScreen()); } mediaQuery.addListener((mq) =&gt; { if (mq.matches) { store.dispatch(setLargeScreen()); } else { store.dispatch(setSmallScreen()); } }); </code></pre> <p>(I'll leave out the action and reducer code this time. It's fairly obvious what they look like.)</p> <p>One drawback of this approach is that the store may be initialised with the wrong value, and we're relying on the media query to set the correct value after the store has been initialised. Short of shoving the media query into the reducer file itself, I don't know the best way around this. Feedback welcome.</p> <h3>UPDATE</h3> <p>Now that I think about it, you can probably get around this by doing something like the following. (But beware, I have not tested this.)</p> <pre><code>const mediaQuery = window.matchMedia('(min-width: 650px)'); const store = createStore(reducer, { ui: { largeScreen: mediaQuery.matches } }); mediaQuery.addListener((mq) =&gt; { if (mq.matches) { store.dispatch(setLargeScreen()); } else { store.dispatch(setSmallScreen()); } }); </code></pre> <p><strong>UPDATE II:</strong> The drawback of this last approach is that the <code>ui</code> object will replace the entire <code>ui</code> state not just the <code>largeScreen</code> field. Whatever else there is of the initial <code>ui</code> state gets lost.</p>
49,984,905
Count number of words per row
<p>I'm trying to create a new column in a DataFrame that contains the word count for the respective row. I'm looking for the total number of words, not frequencies of each distinct word. I assumed there would be a simple/quick way to do this common task, but after googling around and reading a handful of SO posts (<a href="https://stackoverflow.com/questions/13970203/how-to-count-average-sentence-length-in-words-from-a-text-file-contains-100-se">1</a>, <a href="https://stackoverflow.com/questions/36108377/how-to-use-the-split-function-on-every-row-in-a-dataframe-in-python">2</a>, <a href="https://stackoverflow.com/questions/9288169/python-word-length-function-example-needed">3</a>, <a href="https://stackoverflow.com/questions/10677020/real-word-count-in-nltk#10677060">4</a>) I'm stuck. I've tried the solutions put forward in the linked SO posts, but got lots of attribute errors back.</p> <pre><code>words = df['col'].split() df['totalwords'] = len(words) </code></pre> <p>results in</p> <pre><code>AttributeError: 'Series' object has no attribute 'split' </code></pre> <p>and</p> <pre><code>f = lambda x: len(x[&quot;col&quot;].split()) -1 df['totalwords'] = df.apply(f, axis=1) </code></pre> <p>results in</p> <pre><code>AttributeError: (&quot;'list' object has no attribute 'split'&quot;, 'occurred at index 0') </code></pre>
49,984,997
5
0
null
2018-04-23 15:37:42.73 UTC
8
2022-03-04 04:47:51.78 UTC
2022-03-04 04:46:51.413 UTC
user7864386
null
null
5,703,997
null
1
34
python|string|python-3.x|pandas|dataframe
34,531
<h3><code>str.split</code> + <code>str.len</code></h3> <p><code>str.len</code> works nicely for any non-numeric column.</p> <pre><code>df['totalwords'] = df['col'].str.split().str.len() </code></pre> <hr /> <h3><code>str.count</code></h3> <p>If your words are single-space separated, you may simply count the spaces plus 1.</p> <pre><code>df['totalwords'] = df['col'].str.count(' ') + 1 </code></pre> <hr /> <h3>List Comprehension</h3> <p>This is faster than you think!</p> <pre><code>df['totalwords'] = [len(x.split()) for x in df['col'].tolist()] </code></pre>
45,155,379
What's the difference between using ARAnchor to insert a node and directly insert a node?
<p>In ARKit, I have found 2 ways of inserting a node after the hitTest</p> <ol> <li><p>Insert an ARAnchor then create the node in <a href="https://developer.apple.com/documentation/arkit/arscnviewdelegate/2865801-renderer" rel="nofollow noreferrer"><code>renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -&gt; SCNNode?</code></a></p> <pre><code> let anchor = ARAnchor(transform:hit.worldTransform) sceneView.session.add(anchor:anchor) </code></pre> </li> <li><p>Insert the node directly</p> <pre><code> node.position = SCNVector3(hit.worldTransform.columns.3.x, hit.worldTransform.columns.3.y, hit.worldTransform.columns.3.z) sceneView.scene.rootNode.addChildNode(node) </code></pre> </li> </ol> <p>Both look to work for me, but why one way or the other?</p>
45,182,794
2
0
null
2017-07-18 00:01:05.173 UTC
20
2021-04-09 18:18:49.633 UTC
2021-04-09 18:18:49.633 UTC
null
14,351,818
null
1,328,466
null
1
39
swift|augmented-reality|arkit
13,370
<p><strong>Update:</strong> As of iOS 11.3 (aka "ARKit 1.5"), there <em>is</em> a difference between adding an <code>ARAnchor</code> to the session (and then associating SceneKit content with it through <code>ARSCNViewDelegate</code> callbacks) and just placing content in SceneKit space.</p> <p>When you add an anchor to the session, you're telling ARKit that a certain point in world space is relevant to your app. ARKit can then do some extra work to make sure that its world coordinate space lines up accurately with the real world, at least in the vicinity of that point. </p> <p>So, if you're trying to make virtual content appear "attached" to some real-world point of interest, like putting an object on a table or wall, you should see less "drift" due to world-tracking inaccuracy if you give that object an anchor than if you just place it in SceneKit space. And if that object moves from one static position to another, you'll want to remove the original anchor and add one at the new position afterward.</p> <p>Additionally, in iOS 11.3 you can <a href="https://developer.apple.com/documentation/arkit/arsessionobserver/2941046-sessionshouldattemptrelocalizati" rel="noreferrer">opt in</a> to "relocalization", a process that helps ARKit resume a session after it gets interrupted (by a phone call, switching apps, etc). The session still works while it's trying to figure out how to map where you were before to where you are now, which might result in the world-space positions of anchors changing once relocalization succeeds.</p> <p>(On the other hand, if you're just making space invaders that float in the air, perfectly matching world space isn't as important, and thus you won't really see much difference between anchor-based and non-anchor-based positioning.) </p> <p>See the bit around "Use anchors to improve tracking quality around virtual objects" in Apple's <a href="https://developer.apple.com/documentation/arkit/handling_3d_interaction_and_ui_controls_in_augmented_reality" rel="noreferrer">Handling 3D Interaction and UI Controls in Augmented Reality</a> article / sample code.</p> <p><em>The rest of this answer remains historically relevant to iOS 11.0-11.2.5 and explains some context, so I'll leave it below...</em></p> <hr> <p>Consider first the use of <code>ARAnchor</code> <em>without</em> SceneKit. </p> <ul> <li><p>If you're using <code>ARSKView</code>, you need a way to reference positions / orientations in 3D (real-world) space, because SpriteKit isn't 3D. You need <code>ARAnchor</code> to keep track of positions in 3D so that they can get mapped into 2D. </p></li> <li><p>If you're building your own engine with Metal (or GL, for some strange reason)... that's not a 3D scene description API — it's a GPU programming API — so it doesn't really have a notion of world space. You can use <code>ARAnchor</code> as a bridge between ARKit's notion of world space and whatever you build. </p></li> </ul> <p>So in some cases you need <code>ARAnchor</code> because that's the only sensible way to refer to 3D positions. (And of course, if you're using plane detection, you need <code>ARPlaneAnchor</code> because ARKit will actually move those relative to scene space as it refined its estimates of where planes are.)</p> <hr> <p>With <code>ARSCNView</code>, SceneKit already has a 3D world coordinate space, and ARKit does all the work of making that space match up to the real-world space ARKit maps out. So, given a <code>float4x4</code> transform that describes a position (and orientation, etc) in world space, you can either:</p> <ul> <li>Create an <code>ARAnchor</code>, add it to the session, and respond to <code>ARSCNViewDelegate</code> callback to provide SceneKit content for each anchor, which ARKit will add to and position in the scene for you. </li> <li>Create an <code>SCNNode</code>, set its <code>simdTransform</code>, and add it as a child of the scene's <code>rootNode</code>. </li> </ul> <p>As long as you have a running <code>ARSession</code>, there's no difference between the two approaches — they're equivalent ways to say the same thing. So if you like doing things the SceneKit way, there's nothing wrong with that. (You can even use <code>SCNVector3</code> and <code>SCNMatrix4</code> instead of SIMD types if you want, but you'll have to convert back and forth if you're also getting SIMD types from ARKit APIs.) </p> <hr> <p>The one time these approaches differ is when the session is reset. If world tracking fails, you resume an interrupted session, and/or you start a session over again, "world space" may no longer line up with the real world in the same way it did when you placed content in the scene. </p> <p>In this case, you can have ARKit remove anchors from the session — see the <a href="https://developer.apple.com/documentation/arkit/arsession/2875735-run" rel="noreferrer"><code>run(_:options:)</code></a> method and <a href="https://developer.apple.com/documentation/arkit/arsession.runoptions" rel="noreferrer"><code>ARSession.RunOptions</code></a>. (Yes, all of them, because at this point you can't trust any of them to be valid anymore.) If you placed content in the scene using anchors and delegate callbacks, ARKit will nuke all the content. (You get delegate callbacks that it's being removed.) If you placed content with SceneKit API, it stays in the scene (but most likely in the wrong place).</p> <p>So, which to use sort of depends on how you want to handle session failures and interruptions (and outside of that there's no real difference). </p>
26,271,151
Precise memory layout control in Rust?
<p>As far as I know, the Rust compiler is allowed to pack, reorder, and add padding to each field of a struct. How can I specify the precise memory layout if I need it? </p> <p>In C#, I have the <code>StructLayout</code> attribute, and in C/C++, I could use various compiler extensions. I could verify the memory layout by checking the byte offset of expected value locations.</p> <p>I'd like to write OpenGL code employing custom shaders, which needs precise memory layout. Is there a way to do this without sacrificing performance?</p>
26,271,748
3
0
null
2014-10-09 05:47:09.117 UTC
7
2019-11-29 04:08:57.503 UTC
2016-05-04 02:57:35.193 UTC
null
155,423
null
246,776
null
1
30
rust|memory-layout
8,451
<p>As described in <a href="https://doc.rust-lang.org/book/first-edition/ffi.html" rel="noreferrer">the FFI guide</a>, you can add attributes to structs to use the same layout as C:</p> <pre><code>#[repr(C)] struct Object { a: i32, // other members } </code></pre> <p>and you also have the ability to pack the struct:</p> <pre><code>#[repr(C, packed)] struct Object { a: i32, // other members } </code></pre> <p>And for detecting that the memory layout is ok, you can initialize a struct and check that the offsets are ok by casting the pointers to integers:</p> <pre><code>#[repr(C, packed)] struct Object { a: u8, b: u16, c: u32, // other members } fn main() { let obj = Object { a: 0xaa, b: 0xbbbb, c: 0xcccccccc, }; let a_ptr: *const u8 = &amp;obj.a; let b_ptr: *const u16 = &amp;obj.b; let c_ptr: *const u32 = &amp;obj.c; let base = a_ptr as usize; println!("a: {}", a_ptr as usize - base); println!("b: {}", b_ptr as usize - base); println!("c: {}", c_ptr as usize - base); } </code></pre> <p>outputs:</p> <pre class="lang-none prettyprint-override"><code>a: 0 b: 1 c: 3 </code></pre>
28,122,019
How to Submit Form on Select Change
<p>I have the following form. I'd like it to be submitted automatically via jQuery when the user makes a selection, without needing to press the submit button. How do I do this?</p> <pre><code>&lt;form action="" method="post"&gt; &lt;select name="id" id="cars"&gt; &lt;option value=""&gt;Choose&lt;/option&gt; &lt;option value="1"&gt;Toyota&lt;/option&gt; &lt;option value="2"&gt;Nissan&lt;/option&gt; &lt;option value="3"&gt;Dodge&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" name="submit" value="Submit"&gt; &lt;/form&gt; </code></pre> <p>adeneo, I tried your suggestion but it's still not working. Here's the complete code, anything wrong?</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('#cars').on('change', function() { this.form.submit(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="" method="post"&gt; &lt;select name="id" id="cars"&gt; &lt;option value=""&gt;Select...&lt;/option&gt; &lt;option value="1"&gt;Toyota&lt;/option&gt; &lt;option value="2"&gt;Nissan&lt;/option&gt; &lt;option value="3"&gt;Dodge&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" name="submit" value="Submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
28,122,244
7
0
null
2015-01-24 03:37:00.483 UTC
2
2020-04-21 02:02:09.307 UTC
2015-01-24 03:49:58.187 UTC
null
4,488,896
null
4,488,896
null
1
24
jquery|forms|select|submit
109,833
<p>Your form is missing an action value, which prevents submitting the form at the end. But in the mid-time you should correct this code:</p> <pre><code>$(document).ready(function() { $('#cars').on('change', function() { document.forms[myFormName].submit(); }); }); </code></pre> <p>You can also submit a form by triggering submit button click event:</p> <pre><code>$(document).ready(function() { $('#cars').on('change', function() { var $form = $(this).closest('form'); $form.find('input[type=submit]').click(); }); }); </code></pre>
22,595,174
Google OAUTH: The redirect URI in the request did not match a registered redirect URI
<p>I am trying to make an upload to YouTube from my Java based web app, I spent a few days to understand what and where is the problem and I cannot get it, for now I am pulling my hair out off my head.</p> <p>I registered my web app in Google Console, so I got a pair of Client ID and Secret and a possibility to download JSON type file with my config.</p> <p>So here is the config:</p> <pre><code>{ "web":{ "auth_uri":"https://accounts.google.com/o/oauth2/auth", "client_secret":"***", "token_uri":"https://accounts.google.com/o/oauth2/token", "client_email":"***", "redirect_uris":["http://localhost:8080/WEBAPP/youtube-callback.html","http://www.WEBAPP.md/youtube-callback.html"], "client_x509_cert_url":"***", "client_id":"***", "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs", "javascript_origins":["http://www.WEBAPP.md/"] } } </code></pre> <p>How is possible that I am getting the default URL from Google?</p> <p><code>The redirect URI in the request: http://localhost:8080/Callback did not match a registered redirect URI</code></p> <p>It always gives me the default <code>http://localhost:8080/Callback</code> URL instead of mine.</p> <p>And IDE console shows me that:</p> <p><code>Please open the following address in your browser: https://accounts.google.com/o/oauth2/auth?client_id=***&amp;redirect_uri=http://localhost:8080/Callback&amp;response_type=code&amp;scope=https://www.googleapis.com/auth/youtube.upload Attempting to open that address in the default browser now...</code></p> <p>I am using the last version of dependencies: <em>google-api-services-youtube v3-rev99-1.17.0-rc</em> and <em>google-api-services-youtubeAnalytics v1-rev35-1.17.0-rc</em></p>
22,829,362
5
0
null
2014-03-23 18:31:08.113 UTC
17
2022-04-01 14:23:49.063 UTC
null
null
null
null
715,437
null
1
75
java|youtube-api|google-oauth|youtube-data-api|google-oauth-java-client
167,444
<p>When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:</p> <pre><code>https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&amp;redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&amp;response_type=code&amp;scope=https://www.googleapis.com/auth/youtube.upload </code></pre> <p>(the callback URI passed as a parameter must be url-encoded, btw).</p> <p>When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the <code>redirect_uri</code>. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.</p> <p>If you visit:</p> <p><a href="http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow" rel="noreferrer">http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow</a></p> <p>You can see better samples of the java client there, demonstrating that you have to override the <code>getRedirectUri</code> method to specify your callback path so the default isn't used. </p> <p>The redirect URIs are in the <code>client_secrets.json</code> file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows. </p> <p>If you visit <a href="https://developers.google.com/api-client-library/java/apis/youtube/v3" rel="noreferrer">https://developers.google.com/api-client-library/java/apis/youtube/v3</a> You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.</p>
21,195,179
Plot a histogram from a Dictionary
<p>I created a <code>dictionary</code> that counts the occurrences in a <code>list</code> of every key and I would now like to plot the histogram of its content.</p> <p>This is the content of the dictionary I want to plot:</p> <pre><code>{1: 27, 34: 1, 3: 72, 4: 62, 5: 33, 6: 36, 7: 20, 8: 12, 9: 9, 10: 6, 11: 5, 12: 8, 2: 74, 14: 4, 15: 3, 16: 1, 17: 1, 18: 1, 19: 1, 21: 1, 27: 2} </code></pre> <p>So far I wrote this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt pos = np.arange(len(myDictionary.keys())) width = 1.0 # gives histogram aspect to the bar diagram ax = plt.axes() ax.set_xticks(pos + (width / 2)) ax.set_xticklabels(myDictionary.keys()) plt.bar(myDictionary.keys(), ******, width, color='g') # ^^^^^^ what should I put here? plt.show() </code></pre> <p>I tried by simply doing</p> <pre><code>plt.bar(myDictionary.keys(), myDictionary, width, color='g') </code></pre> <p>but this is the result:</p> <p><img src="https://i.stack.imgur.com/3lj8q.png" alt="enter image description here"></p> <p>and I don't know why the 3 bars are shifted and also I'd like the histogram to be displayed in a ordered fashion.</p> <p>Can somebody tell me how to do it?</p>
21,195,331
5
0
null
2014-01-17 20:23:31.597 UTC
13
2021-03-21 20:43:02.293 UTC
2014-01-17 21:30:45.573 UTC
null
907,921
null
907,921
null
1
58
python|dictionary|matplotlib|histogram
134,427
<p>You can use the function for plotting histograms like this:</p> <pre><code>a = np.random.random_integers(0,10,20) #example list of values plt.hist(a) plt.show() </code></pre> <p>Or you can use <code>myDictionary</code> just like this:</p> <pre><code>plt.bar(myDictionary.keys(), myDictionary.values(), width, color='g') </code></pre>
21,177,007
Get first post of an Instagram user
<p>I was wondering if there was a way to download the FIRST post a user has ever posted on Instagram using the Instagram API, specifically the /users/{user-id}/media/recent endpoint. I could easily do this by paginating through all of the user's media, but this could take an especially long time for users with many posts, or users with pictures that have many likes or comments. So, is there any way to download the very first post, or the chunk of posts containing the first one?</p> <p>I'm doing this because I need to get the date that the first image was posted in order to calculate an average posts per day value (number of posts / days since first post was posted). If there is an easier way of doing so, please let me know!</p> <p>Thank you for your help! Elliott</p>
21,198,262
2
0
null
2014-01-17 02:55:43.25 UTC
1
2014-01-18 00:06:33.523 UTC
null
null
null
null
3,155,071
null
1
3
instagram
62,011
<p>You the user/media/recent api with <code>max_timestamp</code>:</p> <pre><code>https://api.instagram.com/v1/users/55431/media/recent/?max_timestamp=1292304000&amp;client_id= </code></pre> <p>call the API with different <code>max_timestamp</code> value for last 3 years using bubble sort, if the response has <code>data</code> and does not have a <code>pagination</code> value, then get the last image object in the response, this will be the very first image.</p> <hr> <p>Instagram has been around since last 3 years I think, get timestamp for a year and half ago and make an API call:</p> <p>IF there is no <code>data</code> in response, then go to newer time and make API call and check response.</p> <p>IF there is <code>data</code> in response and has <code>pagination</code> value, then make another API call with older time and check response.</p> <p>IF there is <code>data</code> in response and has no <code>pagination</code> value in API response, then get the last image object in this response, this is your first image!</p>
32,581,049
MapKit iOS 9 detailCalloutAccessoryView usage
<p>After watching <a href="https://developer.apple.com/videos/wwdc/2015/?id=206" rel="noreferrer">WWDC video 206</a> I assumed this would be a trivial task of adding the detail callout view to a mapView annotation view.</p> <p>So, I assume Im doing something wrong.</p> <p>With my pin view set up</p> <pre><code>func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -&gt; MKAnnotationView? { let view:MKAnnotationView! if let dequed = routeMapView.dequeueReusableAnnotationViewWithIdentifier("pin") { view = dequed } else { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin") } let x = UIView(frame: CGRectMake(0, 0, 200, 200)) x.backgroundColor = UIColor.redColor() // shows the red //view.leftCalloutAccessoryView = x // working as no subtitle - but no red view view.detailCalloutAccessoryView = x view.canShowCallout = true return view } </code></pre> <p>I only get this</p> <p><a href="https://i.stack.imgur.com/m5tQV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/m5tQV.png" alt="enter image description here"></a></p> <p>I know the view is working, because if I try it with the <code>leftCalloutAccessoryView</code> I get <a href="https://i.stack.imgur.com/L8QOj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/L8QOj.png" alt="enter image description here"></a></p> <p>I must be missing something. Note, if I just add an image to the <code>detailCalloutAccessoryView</code> like</p> <pre><code>view.detailCalloutAccessoryView = UIImage(named:"YourImageName") </code></pre> <p>The image is there, size correctly etc</p> <p>I just cannot figure out how to put in my own custom view.</p> <p>Thanks</p>
32,897,201
4
0
null
2015-09-15 08:17:08.183 UTC
10
2018-07-25 13:57:06.94 UTC
2015-09-28 02:18:26.037 UTC
null
1,173,037
null
1,173,037
null
1
21
ios|mapkit|mkannotationview
11,319
<p>You have to add some constraints for width and height of your view:</p> <pre><code>func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -&gt; MKAnnotationView? { var av = mapView.dequeueReusableAnnotationViewWithIdentifier("id") if av == nil { av = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "id") } let myView = UIView() myView.backgroundColor = .greenColor() let widthConstraint = NSLayoutConstraint(item: myView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 40) myView.addConstraint(widthConstraint) let heightConstraint = NSLayoutConstraint(item: myView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 20) myView.addConstraint(heightConstraint) av!.detailCalloutAccessoryView = myView av!.canShowCallout = true return av! } </code></pre> <p><a href="https://i.stack.imgur.com/twK8D.png" rel="noreferrer"><img src="https://i.stack.imgur.com/twK8D.png" alt="Munich 1972"></a></p> <p>Adding an <code>intrinsicContentSize</code> also works.</p> <p>I did some testing and found out, that MapKit automagically sets <code>translatesAutoresizingMaskIntoConstraints</code> to false, when you set a view to <code>detailCalloutAccessoryView</code>.</p> <p>In the WWDC 2015 session <a href="https://developer.apple.com/videos/wwdc/2015/?id=206" rel="noreferrer">"What's New in MapKit"</a> it was told, that "auto layout is supported". I reckon that Apple really means, that you have to use auto layout?!</p>
41,829,158
.NET Core locking files
<p>I have a ASP.NET Core app. I run the application by running the command </p> <pre><code>dotnet run </code></pre> <p>I'm seeing the following error in one out of five situations when I build this ASP.NET Core app.</p> <blockquote> <p>C:...\error CS2012: Cannot open 'C:...\bin\Debug\netcoreapp1.0\AAA.Web.dll' for writing -- 'The process cannot access the file 'C:...\bin\Debug\netcoreapp1.0\AAA.Web.dll' because it is being used by another process.'</p> </blockquote> <p>In addition to the above issue, I also see no updates that I make in the CSHTML file. I have to stop the <code>dotnet run</code> command, build the app again and then run the <code>dotnet run</code> command.</p> <p>How can I fix these issues?</p> <p><a href="https://i.stack.imgur.com/Wdu4D.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Wdu4D.png" alt="enter image description here"></a></p>
53,982,082
13
0
null
2017-01-24 13:14:06.66 UTC
4
2021-03-19 05:00:48.28 UTC
2018-12-31 01:37:28.75 UTC
null
3,728,901
null
1,768,008
null
1
51
asp.net-core|.net-core
36,380
<p>This may also help when running your aspnetcore app in IIS.</p> <p>Add the following to your csproj:</p> <pre><code> &lt;Target Name="PreBuild" BeforeTargets="PreBuildEvent"&gt; &lt;Exec Command="echo &amp;quot;App Offline&amp;quot; /a &amp;gt; &amp;quot;$(ProjectDir)app_offline.htm&amp;quot;" /&gt; &lt;/Target&gt; &lt;Target Name="PostBuild" AfterTargets="PostBuildEvent"&gt; &lt;Exec Command="del &amp;quot;$(ProjectDir)app_offline.htm&amp;quot;" /&gt; &lt;/Target&gt; </code></pre>
41,968,732
Set order of columns in pandas dataframe
<p>Is there a way to reorder columns in pandas dataframe based on my personal preference (i.e. not alphabetically or numerically sorted, but more like following certain conventions)?</p> <p>Simple example:</p> <pre><code>frame = pd.DataFrame({ 'one thing':[1,2,3,4], 'second thing':[0.1,0.2,1,2], 'other thing':['a','e','i','o']}) </code></pre> <p>produces this:</p> <pre><code> one thing other thing second thing 0 1 a 0.1 1 2 e 0.2 2 3 i 1.0 3 4 o 2.0 </code></pre> <p>But instead, I would like this:</p> <pre><code> one thing second thing other thing 0 1 0.1 a 1 2 0.2 e 2 3 1.0 i 3 4 2.0 o </code></pre> <p>(Please, provide a generic solution rather than specific to this case. Many thanks.)</p>
41,968,766
11
0
null
2017-01-31 22:34:03.73 UTC
40
2022-05-18 18:57:19.343 UTC
2017-01-31 23:04:11.313 UTC
null
2,336,654
null
5,553,319
null
1
146
python|pandas
269,660
<p>Just select the order yourself by typing in the column names. Note the double brackets:</p> <pre><code>frame = frame[['column I want first', 'column I want second'...etc.]] </code></pre>
5,916,581
Relationship between UIVIew and CALayer regarding background image on iOS
<p>Trying to understand the relationship between UIView and CALayer. I read Apple documentation but it doesn't describe in detail the relationship between the two.</p> <ol> <li><p>Why is it that when I add the background image to view "customViewController.view", I get the unwanted black color of the image.</p></li> <li><p>And when I add the background image to the layer "customViewController.view.layer", the black area of the image is gone (which is what I wanted), but the background image is flipped upside down. Why is that?</p></li> <li><p>If I were to add labels/views/buttons/etc. to the view, will the layer's background image block them because CAlayer is backed by UIView?</p></li> <li><p>When you set the background color of a UIView does it automatically set the background color of the associated layer?</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; customViewController = [[CustomViewController alloc] init]; customViewController.view.frame = CGRectMake(213, 300, 355, 315); customViewController.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]]; // customViewController.view.layer.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]].CGColor; [self.view addSubview:customViewController.view]; } </code></pre></li> </ol> <p>Background image in view:</p> <p><img src="https://lh4.googleusercontent.com/_d2JwJUrXxVM/TcROGNhnmWI/AAAAAAAABhU/GjaR_Lh_-KM/s400/secondscreen.png" alt="background in view"></p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; customViewController = [[CustomViewController alloc] init]; customViewController.view.frame = CGRectMake(213, 300, 355, 315); // customViewController.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]]; customViewController.view.layer.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]].CGColor; [self.view addSubview:customViewController.view]; } </code></pre> <p>Background image in view.layer:</p> <p><img src="https://lh5.googleusercontent.com/_d2JwJUrXxVM/TcROBJTA72I/AAAAAAAABhQ/l_jgSYNMZa8/s400/firstscreen.png" alt="background image in layer"></p>
5,917,849
1
0
null
2011-05-06 20:19:01.573 UTC
9
2011-05-07 17:20:34.63 UTC
2011-05-06 22:25:08.533 UTC
null
296,387
null
514,744
null
1
12
iphone|ios|uiview|uikit|calayer
11,593
<ol> <li><p>UIView as created opaque by default. When you set the backgroundColor to a pattern with transparency it is choosing black as the background color. You can set <code>customViewController.view.opaque = NO;</code> to allow the background of the view behind yours to show through.</p></li> <li><p>When you set the backgroundColor of the layer to a pattern with transparency you are bypassing the UIView logic, so the opaqueness of the view is ignored; so also is the the UIView's transform. CoreGraphics and friends use a coordinate system where the positive y-axis points upwards. UIKit flips this coordinate system. This is why the image appears upside down. </p></li> <li><p>If you add labels/views/buttons/etc. the will appear correctly on top of the layer's background pattern.</p></li> <li><p>When you set the view's background color it appears as if the layer's background color is indeed set. (I have not seen this documented anywhere).</p></li> </ol> <p>Essentially the UIKit's UIView stuff is a high-level interface which ends up rendered onto layers. </p> <p>Hope this helps.</p> <p>EDIT 5/7/2011</p> <p>You can get the image to show the right way up by flipping the layer's coordinate system BUT you shouldn't do this to view.layer; UIKit doesn't expect you to mess with this layer, so if your flip its coordinate system any UIKit drawing will be flipped; you need to use a sublayer.</p> <p>So your code would look like this:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; customViewController = [[CustomViewController alloc] init]; customViewController.view.frame = CGRectMake(213, 300, 355, 315); CALayer* l = [CALayer layer]; l.frame = customViewController.bounds; CGAffineTransform t = CGAffineTransformMake(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); l.affineTransform = t; l.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]].CGColor; [customViewController.view.layer addSublayer:l]; [self.view addSubview:customViewController.view]; } </code></pre> <p>Note: normally when you flip coordinates you include the height. For layers you don't need to do this. I haven't dug into why this is so. </p> <p>As you can see there is a lot more code involved here and there is no real advantage to doing it this way. I really recommend you stick to the UIKit approach. I only posted the code in response to your curiosity. </p>
24,802,244
Custom validation in Django admin
<p>I have a very simple Django app in order to record the lectures given my colleagues.Since it is quite elementary,I am using the Django admin itself. Here is my models.py:</p> <pre><code>#models.py from django.db import models class Lecture(models.Model): topic = models.CharField(max_length=100) speaker = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() </code></pre> <p>I need to ensure that nobody enters the start date after the end date in the admin forms,so I read the django docs for custom validation in the admin and implemented the following in my admin.py:</p> <pre><code>#admin.py from models import Lecture from django.contrib import admin from django import forms class LectureForm(forms.ModelForm): class Meta: model = Lecture def clean(self): start_date = self.cleaned_data.get('start_date') end_date = self.cleaned_data.get('end_date') if start_date &gt; end_date: raise forms.ValidationError("Dates are incorrect") return self.cleaned_data class LectureAdmin(admin.ModelAdmin): form = LectureForm list_display = ('topic', 'speaker', 'start_date', 'end_date') admin.site.register(Lecture, LectureAdmin) </code></pre> <p>However,this has no effect whatsoever on my admin and I am able to save lectures where start_date is after end_date as seen in the image:<img src="https://i.stack.imgur.com/3pvc7.png" alt="enter image description here"></p> <p>What am I doing wrong ??</p>
24,802,290
3
0
null
2014-07-17 11:25:47.643 UTC
11
2020-07-20 09:29:48.69 UTC
2017-05-12 18:29:18.71 UTC
null
203,583
null
1,813,039
null
1
55
python|django|django-forms|django-admin|django-validation
46,614
<p>You have an indentation issue. Your <code>clean</code> method is indented within the form's Meta class. Move it back one level. Also, ensure that the <code>return</code> statement is indented within the method.</p>
37,947,541
What is the difference between Firebase push-notifications and FCM messages?
<p>Heloo, I am building an app where I am using push notifications via Firebase Console. I want to know what is a difference between simply push-notification and cloud message? Is it that messages from cloud messaging are data messages(have key and value) and notifications are just text without key and value?Am I right?</p>
37,948,441
1
0
null
2016-06-21 14:42:05.447 UTC
21
2018-04-05 06:06:54.093 UTC
null
null
null
null
6,450,105
null
1
30
google-cloud-messaging|firebase-cloud-messaging|firebase-notifications
21,768
<p>Firebase API has two types of messages, they call them: </p> <ul> <li>notification</li> <li>data</li> </ul> <h2>Explanation:</h2> <ol> <li><strong>notification</strong> - messages that goes directly to Android's Notification tray only if your application is in <strong>background/killed</strong> or gets delivered to <code>onMessageReceived()</code> method if your app is in <strong>foreground</strong>.</li> </ol> <p>Sample: </p> <pre><code>{ "notification" : { "body" : "Hi"} } </code></pre> <ol start="2"> <li><strong>data payload</strong> - Doesn't matter whether your application is in forground or background or killed, these messages will always be delivered to <code>onMessageReceived()</code> method.</li> </ol> <p>Sample: </p> <pre><code>{ "data" : { "message" : "Hi", "whatever_key": "value"} } </code></pre> <p><a href="https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages" rel="noreferrer">Reference link</a></p> <p><strong>IMPORTANT :</strong> You can't send data payload messages from <strong>Firebase Console</strong>, Console only delivers notification message. However using API you can send both type of messages. </p> <p><em>To send a data payload message you have to make a curl request:</em> </p> <h2>HTTP POST Request</h2> <pre><code>https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA { "data": { "score": "5x1", "time": "15:10" }, "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." } </code></pre> <p>You can get the server key (AIzaSyZ-1u...0GBYzPu7Udno5aA), from firebase console: <strong>Your project -> settings -> Project settings -> Cloud messaging -> Server Key</strong></p>
37,925,035
Notepad plus plus shortcut for reloading files
<p>Is there any keyboard shortcut for reloading files in n++ ? How can i configure my own?</p> <p>Steps to reproduce:</p> <ul> <li>right click and reload on header tab.</li> </ul>
37,925,153
3
0
null
2016-06-20 14:25:33.68 UTC
5
2020-07-01 07:08:44.507 UTC
null
null
null
null
3,181,491
null
1
31
notepad++
17,959
<p>Steps for mapping a keyboard shortcut for reloading files in n++. </p> <ol> <li>First open Notepad++ application </li> <li><p>Now go to Settings tab >Shortcut mapper</p></li> <li><p>Now here select the first tab which is <strong>main menu</strong></p></li> <li><p>You can find the "<em>reload from disk</em>" option under the selected options. <em>Note: Typically this is amongst the top commands, e.g. item #6</em>.</p></li> <li><p>Now all you have to do is to assign an unused shortcut key mapping to it.</p></li> </ol> <p><em>Note: If you want to use <code>F5</code> like in a web-browser, it is better to first remove existing F5 shortcut assigned to "Run..." (close to bottom of <strong>main menu</strong>)</em> </p>
37,806,982
Difference between static function and singleton class in swift
<p>I want to create a class where all utility methods will be kept and these methods will be used throughout the app.<br> <strong>Problem:1</strong><br> Is it good to create a singleton class and keep all necessary methods there or should I create a class where all function will be static.<br> <strong>Problem:2</strong><br> What is main difference between above two approaches in swift ?<br> <strong>Problem:3</strong><br> How it will impact performance and memory in iOS?</p>
37,812,213
3
0
null
2016-06-14 08:39:54.467 UTC
22
2021-06-19 08:08:30.277 UTC
2021-06-19 08:08:30.277 UTC
null
3,743,875
null
3,743,875
null
1
41
ios|swift|singleton|static-methods
12,348
<p>Sure this sounds confusing and can be debated. However, from the best practices i can put some suggestions. </p> <p><strong>Singleton</strong> is usually used to create a resource intensive and one timer initialisation for instance: a database connector, login handler and such. </p> <p><strong>Utility class</strong> are classes that only have static functions and variables. It should not deal with async task and expensive resource handling like opening a database connector. </p> <p>In your case, if the utility is doing some resource intensive process its better to wrap in a singleton. If not, then Static functions in a class is better in my opinion. This is so also because, Swift will dispatch all static functions in a class using <strong>static dispatch</strong>. Whereas this cannot be true in Singleton although Swift likes to optimizes. </p> <p><strong>Static Dispatch are 4 times faster than Dynamic Dispatch</strong> as far as Objective-C runtime is used. This is true for swift too. However, it only takes 4 nano seconds to dispatch Dynamiclly. </p> <p>I hope this makes you clear. </p>
51,238,643
Which versions of npm came with which versions of node?
<p>Which versions of npm came with which versions of node? I can't find such a list.</p>
51,243,675
2
0
null
2018-07-09 05:22:14.957 UTC
8
2020-05-14 15:01:04.07 UTC
null
null
null
null
627,729
null
1
28
node.js|npm
7,531
<p>At <a href="https://nodejs.org/dist/" rel="noreferrer">https://nodejs.org/dist/</a> there is <a href="https://nodejs.org/dist/index.json" rel="noreferrer">index.json</a> which indicates each version of nodejs and which version of npm is bundled with it.</p> <hr> <p><strong>index.json</strong></p> <p>An excerpt from one of the objects in the array of <code>index.json</code> reads:</p> <pre class="lang-json prettyprint-override"><code>[ { "version": "v10.6.0", //&lt;--- nodejs version "date": "2018-07-04", "files": [ ... ], "npm": "6.1.0", //&lt;--- npm version "v8": "6.7.288.46", "uv": "", "zlib": "1.2.11", "openssl": "1.1.0h", "modules": "64", "lts": false }, ... ] </code></pre> <p>Whereby each object in the array has a <code>version</code> <em>(i.e. the nodejs version)</em> and <code>npm</code> <em>(i.e. the npm version)</em> key/value pair. </p> <hr> <h2>Programmatically obtaining the versions</h2> <p>Consider utilizing the following node.js script to request the data from the <code>https://nodejs.org/dist/index.json</code> endpoint.</p> <p><strong>get-versions.js</strong></p> <pre class="lang-js prettyprint-override"><code>const { get } = require('https'); const ENDPOINT = 'https://nodejs.org/dist/index.json'; function requestVersionInfo(url) { return new Promise((resolve, reject) =&gt; { get(url, response =&gt; { let data = ''; response.on('data', chunk =&gt; data += chunk); response.on('end', () =&gt; resolve(data)); }).on('error', error =&gt; reject(new Error(error))); }); } function extractVersionInfo(json) { return JSON.parse(json).map(({ version, npm = null }) =&gt; { return { nodejs: version.replace(/^v/, ''), npm }; }); } (async function logVersionInfo() { try { const json = await requestVersionInfo(ENDPOINT); const versionInfo = extractVersionInfo(json); console.log(JSON.stringify(versionInfo, null, 2)); } catch ({ message }) { console.error(message); } })(); </code></pre> <p>Running the following command:</p> <pre class="lang-none prettyprint-override"><code>node ./path/to/get-versions.js </code></pre> <p>will print something like the following to your console:</p> <blockquote> <pre class="lang-json prettyprint-override"><code>[ { "nodejs": "14.2.0", "npm": "6.14.4" }, { "nodejs": "14.1.0", "npm": "6.14.4" }, { "nodejs": "14.0.0", "npm": "6.14.4" }, { "nodejs": "13.14.0", "npm": "6.14.4" }, ... ] </code></pre> </blockquote> <p>As you can see it lists each version of nodejs and it's respective version of npm.</p>
1,268,942
SSH Java-library for Android?
<p>I'm trying to create an app for Android that simply sends a command to an SSH server. No response needed, I just need to be able to send a command. I was wondering if there's any java library out there that I could use?</p> <p>No advanced stuff needed, just a pure connection to send the command.</p>
1,367,997
1
0
null
2009-08-12 21:49:36.07 UTC
15
2017-11-19 00:15:51.743 UTC
null
null
null
null
155,439
null
1
23
java|android|ssh|command
30,523
<p>You are searching for <a href="http://www.jcraft.com/jsch/" rel="noreferrer">JSch</a>. </p> <p>Other libs are <a href="https://github.com/freznicek/jaramiko" rel="noreferrer">jaramiko</a>, <a href="http://www.paramiko.org/" rel="noreferrer">paramiko</a>, <a href="https://github.com/jenkinsci/trilead-ssh2" rel="noreferrer">trilead-ssh2</a> . A place where you can browse the source for trilead is <a href="http://code.google.com/p/connectbot/source/browse/trunk/connectbot#connectbot/src/com/trilead/ssh2" rel="noreferrer">the connectbot project</a>. Please notice that connectbot also uses this unmaintained lib.</p> <p>It also exists a commercial SSH Java lib: <a href="http://www.sshtools.co.uk/en/j2ssh-maverick/" rel="noreferrer">J2SSH Maverick</a> </p> <p>Note: Answer refactored due to comment.</p>
40,561,484
What data type should be used for timestamp in DynamoDB?
<p>I am new to DynamoDB. I wish to create a table which using DeviceID as the hash key, Timestamp as my range key and some data.</p> <pre><code>{ DeviceID: 123, Timestamp: "2016-11-11T17:21:07.5272333Z", X: 12, Y: 35 } </code></pre> <p>In SQL, we can use datetime type for Timestamp, but in DynamoDB there is none. </p> <ol> <li><p>What data type should I use? String? Number?<br> <a href="https://i.stack.imgur.com/DjTuN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DjTuN.png" alt="enter image description here"></a></p></li> <li><p>For the chosen data type, what kind of timestamp format should I write in? ISO format (e.g: 2016-11-11T17:21:07.5272333Z) or epoch time (e.g: 1478943038816)? </p></li> <li><p>I need to search through the table through a range of time, e.g: 1/1/2015 10:00:00am until 31/12/2016 11:00:00pm</p></li> </ol>
40,564,372
4
6
null
2016-11-12 09:34:02.753 UTC
19
2022-03-10 19:32:39.327 UTC
2022-03-10 19:32:39.327 UTC
null
1,357,094
null
719,998
null
1
133
datetime|amazon-web-services|amazon-dynamodb|sqldatatypes
157,225
<p>The <strong>String data type</strong> should be used for Date or Timestamp.</p> <blockquote> <p>You can use the String data type to represent a date or a timestamp. One way to do this is by using ISO 8601 strings, as shown in these examples:</p> <p>2016-02-15</p> </blockquote> <blockquote> <p>2015-12-21T17:42:34Z</p> </blockquote> <blockquote> <p>20150311T122706Z</p> </blockquote> <p><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.String" rel="noreferrer">DynamoDB Data type for Date or Timestamp</a></p> <p>Yes, the Range queries are supported when the date is stored as String. The <strong>BETWEEN</strong> can be used on FilterExpresssion. I have got the items in the result using the below filter expressions.</p> <p><strong>FilterExpression without time:-</strong></p> <pre><code>FilterExpression : 'createdate between :val1 and :val2', ExpressionAttributeValues : { ':hkey' : year_val, ':rkey' : title, &quot;:val1&quot; : &quot;2010-01-01&quot;, &quot;:val2&quot; : &quot;2010-12-31&quot; } </code></pre> <p><strong>FilterExpression with time:-</strong></p> <pre><code>FilterExpression : 'createdate between :val1 and :val2', ExpressionAttributeValues : { ':hkey' : year_val, ':rkey' : title, &quot;:val1&quot; : &quot;2010-01-01T00:00:00&quot;, &quot;:val2&quot; : &quot;2010-12-31T00:00:00&quot; } </code></pre> <p><strong>Database Values:-</strong></p> <p><strong>Format 1 - with timezone:</strong></p> <pre><code>{&quot;Item&quot;:{&quot;createdate&quot;:{&quot;S&quot;:&quot;2010-12-21T17:42:34+00:00&quot;},&quot;title&quot;:{&quot;S&quot;:&quot;The Big New Movie 2010&quot;},&quot;yearkey&quot;:{&quot;N&quot;:&quot;2010&quot;},&quot;info&quot;:{&quot;M&quot;:{&quot;rating&quot;:{&quot;N&quot;:&quot;0&quot;},&quot;plot&quot;:{&quot;S&quot;:&quot;Nothing happens at all.&quot;}}}}} </code></pre> <p><strong>Format 2 - without timezone:-</strong></p> <pre><code>{&quot;Item&quot;:{&quot;createdate&quot;:{&quot;S&quot;:&quot;2010-12-21T17:42:34Z&quot;},&quot;title&quot;:{&quot;S&quot;:&quot;The Big New Movie 2010&quot;},&quot;yearkey&quot;:{&quot;N&quot;:&quot;2010&quot;},&quot;info&quot;:{&quot;M&quot;:{&quot;rating&quot;:{&quot;N&quot;:&quot;0&quot;},&quot;plot&quot;:{&quot;S&quot;:&quot;Nothing happens at all.&quot;}}}}} </code></pre>
51,483,005
the type of schema applied to the document is not supported package.json
<p>Can anyone explain what this warning in my package.json file is? I have searched a little bit but I cannot seem to understand if this is just compatibility/strange behavior or if there is something going on worse than that.</p> <p>I have taken a screenshot of the warning message below. I apologize if this has been answered elsewhere and I overlooked it.</p> <p><a href="https://imgur.com/YzZHgxF" rel="noreferrer"><img src="https://i.imgur.com/YzZHgxF.png" title="source: imgur.com" /></a></p> <p>Attached is my package.json in full:</p> <pre><code>{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "projects": { "project": { "architect": { "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "exclude": [ "**/node_modules/**" ], "tsConfig": [ "tsconfig.json" ] } }, "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "aot": true, "assets": [ "src/favicon.ico" ], "index": "src/index.html", "main": "src/main.ts", "outputPath": "dist", "polyfills": "src/polyfills.ts", "scripts": [ "node_modules/uikit/dist/js/uikit.min.js", "node_modules/uikit/dist/js/uikit-icons.min.js" ], "styles": [ "node_modules/uikit/dist/css/uikit.min.css", "src/styles.scss", "node_modules/bootstrap/dist/css/bootstrap.min.css" ], "tsConfig": "tsconfig.json" }, "configurations": { "development": { "baseHref": "/aspnetcoreangular/", "buildOptimizer": true, "extractCss": true, "extractLicenses": true, "namedChunks": false, "optimization": true, "outputHashing": "all", "sourceMap": false, "vendorChunk": false }, "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.production.ts" } ], "baseHref": "/aspnetcoreangular/", "buildOptimizer": true, "extractCss": true, "extractLicenses": true, "namedChunks": false, "optimization": true, "outputHashing": "all", "sourceMap": false, "vendorChunk": false }, "staging": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.staging.ts" } ], "baseHref": "/aspnetcoreangular/", "buildOptimizer": true, "extractCss": true, "extractLicenses": true, "namedChunks": false, "optimization": true, "outputHashing": "all", "sourceMap": false, "vendorChunk": false } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "project:build" } } }, "cli": { "warnings": { "typescriptMismatch": false, "versionMismatch": false } }, "prefix": "app", "projectType": "application", "root": "", "sourceRoot": "src" } } } </code></pre>
67,433,808
2
1
null
2018-07-23 16:03:00.627 UTC
3
2021-07-09 19:39:33.197 UTC
null
null
null
null
1,333,874
null
1
31
json|visual-studio|package.json
14,122
<p><a href="https://developercommunity.visualstudio.com/t/support-json-schema-draft-06-draft-07/796216" rel="nofollow noreferrer">https://developercommunity.visualstudio.com/t/support-json-schema-draft-06-draft-07/796216</a></p> <p>VS still doesn't support draft 7 for json-schemes and is stuck at draft 4-5. Hence the warning.</p> <p>It's a false positive.</p> <p><strong>EDIT</strong></p> <p>Mike (see below) suggests a work around. Be sure to check it out and give Mike an upvote if it works (so that he'll be the first answer listed).</p>
2,393,895
How to Use Scintilla .NET in C# Project?
<p>I am attempting to use Scintilla .NET in a project (I want a good editor + syntax highlighting, etc). Unfortunately, when I reference the binaries in my project, I can't seem to actually use the Scintilla controls. I get two different errors.</p> <ol> <li><p>The first happens when adding SciLexer.dll as a reference to my project. I get a message that says: <em>A reference to SciLexer.dll could not be added. Please make sure the file is accessible, and that it is a valid assembly or COM component.</em></p></li> <li><p>The second error occurs when I try to use the controls from ScintillaNET.dll. If I try to drag the component into a form, I get the following message: Failed to create component Scintilla. The error message follows: System.ComponentModel.Win32Exception: %1 is not a valid Win32 application at ScintillaNet.Scintilla.get_CreateParams()</p></li> </ol> <p>Any help with either of these problems would be much appreciated. For the record, I am running Visual Studio 2008 running on a 64-bit Windows 7 platform.</p> <p>Thanks.</p>
2,394,002
5
1
null
2010-03-06 19:53:16.403 UTC
6
2017-02-15 09:07:19.4 UTC
null
null
null
null
132,528
null
1
40
c#|.net|visual-studio|scintilla
27,854
<p>It's been a little while since I used Scintilla, but my understanding is that SciLexer.dll is an entirely native DLL, which is why you can't add a reference to it from Visual Studio.</p> <p>Instead, you should 'arrange' for SciLexer.dll to appear in the right directory at runtime so that it can be loaded by ScintillaNET.dll. The safest way to do this would be to add SciLexer.dll to your Visual Studio project as a plain file (not as a reference), then change the properties on the file to have it copied to the output directory when your project is built.</p> <p>Given that you're on 64-bit, I expect that you'll need to <a href="https://stackoverflow.com/questions/516730/visual-studio-any-cpu-target">build your app specifically as 32-bit and not AnyCPU</a>. As I say, it's been a while since I did this, but when I did, Scintilla only had 32-bit binaries.</p>
3,103,840
How do you load a local jpeg or png image file into an iPhone app?
<p>Or I should ask why is it so difficult for me? The answer is probably that I'm new to iPhone development and I'm trying to ditch my old methods and step into the new platform of the future. From start to finish, I have a few questions about this process...</p> <ol> <li>If I create a .png image, where does it go in my project's directory (i.e. my computer's hard drive)? Can I put it anywhere on my hard drive and Xcode will copy it in the right place when I load it into Xcode?</li> <li>Once it exists on my hard drive somewhere, how do I add it to my Xcode project? Can I just drag the file into any folder in the "Groups &amp; Files" tree?</li> <li>Once I drag it into Xcode, what copy settings do I want to use in that copy file dialog box that pops up? Copy items into destination group's folder checkbox? Reference Type? Recursively create groups for added folders?</li> <li>Once the .png image has properly been added to my project, what's the easiest way to get it into an CGImageRef? The documentation shows an example using the <code>CGImageCreateWithPNGDataProvider</code> helper method, but says it's not supported by the iOS SDK. I'd like to use the CGImageRef for repeatedly drawing the image to a bitmap context.</li> </ol> <p>Thanks so much in advance and I apologize for the lengthy question, I'm just surprised it's such a convoluted process compared to some other platforms.</p>
3,104,235
6
0
null
2010-06-23 17:07:33.57 UTC
1
2016-06-06 14:17:06.313 UTC
2010-06-23 17:47:45.207 UTC
null
191,808
null
191,808
null
1
16
iphone|xcode|ipad|core-graphics|quartz-graphics
44,003
<p>If you load into UIImage, you can get a CGImageReg:</p> <pre><code> UIImage *image = [UIImage imageNamed:@"image.png"]; CGImageRef imageRef = [image CGImage]; </code></pre>
3,127,539
Ubuntu: Android device debug
<p>I have a HTC Desire which i would like to debug and run my Android application on. But when i in Eclipse gets the Window where i can choose between devices my HTC Desire is listed with only questionmarks (????????). What am i doing wrong?</p> <p>I have tried this:</p> <p>Enabled USB Debugging on my device and enabled debugging in my application Manifest.xml file.</p> <p>In Terminal i have do this:</p> <ol> <li>Log in as root and create this file: /etc/udev/rules.d/51-android.rules.</li> <li>SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"</li> <li>sudo service udev restart</li> </ol> <p>What else could i try or have forgotten?</p>
3,129,903
6
3
null
2010-06-27 13:49:15.69 UTC
16
2015-10-25 02:00:51.717 UTC
2015-06-10 00:04:21.903 UTC
null
1,778,421
null
155,035
null
1
26
android|linux|ubuntu|adb
28,046
<p>You need to run adb manually using sudo. If you just run adb without sudo (or if you let Eclipse/ADT do it for you), it won't have the permissions necessary to see your devices.</p> <p>If it's already running, then sudo adb kill-server and sudo adb start-server.</p>
2,702,928
Returning a struct pointer
<p>Suppose I have the following struct and function returning a pointer:</p> <pre><code>typedef struct { int num; void *nums; int size; } Mystruct; Mystruct *mystruct(int num, int size) { //Is the following correct? Is there a more efficient way? Mystruct mystruct; mystruct.num = num; mystruct.size = size; mystruct.nums = malloc(num*sizeof(size)); Mystruct *my; *my = mystruct; return my; } </code></pre> <p>I want to define any Mystruct pointer using the above function. Should I declare a Mystruct variable, define the properties of Mystruct, assign a pointer to it, and return the pointer or define the properties of a mystruct property through a pointer immediately?</p>
2,702,940
6
2
null
2010-04-24 02:10:30.893 UTC
13
2015-03-01 22:08:16.09 UTC
2010-04-24 02:25:54.19 UTC
null
280,730
null
322,885
null
1
28
c|pointers|struct
95,769
<blockquote> <p>Should I declare a Mystruct variable, define the properties of Mystruct, assign a pointer to it, and return the pointer</p> </blockquote> <p>Definitely not, because the variable defined in the function (in "auto" storage class) will disappear as the function exits, and you'll return a dangling pointer.</p> <p>You could <em>accept</em> a pointer to a <code>Mystruct</code> (caller's responsibility to allocate that) and fill it in; or, you can use <code>malloc</code> to create a new one (caller's responsibility to free it when it's done). The second option at least lets you keep the function signature you seem to be keen on:</p> <pre><code>Mystruct *mystruct(int num, int size) { Mystruct *p = malloc(sizeof(MyStruct)); .... return p; } </code></pre> <p>but it's often an inferior one -- since the caller has to have responsibilities anyway, may as well go with the first option and potentially gain performance (if the caller can use an auto-class instance because it knows the scope of use is bounded).</p>
2,878,983
Capture key press without placing an input element on the page?
<p>How to capture key press, e.g., Ctrl+Z, without placing an input element on the page in JavaScript? Seems that in IE, keypress and keyup events can only be bound to input elements (input boxes, textareas, etc)</p>
2,879,095
6
5
null
2010-05-21 01:11:53.977 UTC
17
2021-12-27 11:25:46.887 UTC
2011-07-24 18:14:59.933 UTC
null
560,648
null
312,483
null
1
89
javascript
121,015
<p>jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:</p> <pre><code>$(document).keypress(function(e){ var checkWebkitandIE=(e.which==26 ? 1 : 0); var checkMoz=(e.which==122 &amp;&amp; e.ctrlKey ? 1 : 0); if (checkWebkitandIE || checkMoz) $("body").append("&lt;p&gt;ctrl+z detected!&lt;/p&gt;"); }); </code></pre> <p>Tested in IE7,Firefox 3.6.3 &amp; Chrome 4.1.249.1064</p> <p>Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:</p> <pre><code>$(document).keydown(function(e){ if (e.keyCode==90 &amp;&amp; e.ctrlKey) $("body").append("&lt;p&gt;ctrl+z detected!&lt;/p&gt;"); }); </code></pre>
2,540,202
How can I check for unused import in many Python files?
<p>I remember when I was developing in C++ or Java, the compiler usually complains for unused methods, functions or imports. In my Django project, I have a bunch of Python files which have gone through a number of iterations. Some of those files have a few lines of import statement at the top of the page and some of those imports are not used anymore. Is there a way to locate those unused imports besides eyeballing each one of them in each file?</p> <p>All my imports are explicit, I don't usually write <code>from blah import *</code></p>
2,540,221
12
1
null
2010-03-29 18:12:06.93 UTC
15
2021-08-11 13:23:26.803 UTC
null
null
null
null
117,642
null
1
61
python
51,932
<p><a href="https://launchpad.net/pyflakes" rel="noreferrer">PyFlakes</a> (similar to <a href="https://en.wikipedia.org/wiki/Lint_(software)" rel="noreferrer">Lint</a>) will give you this information.</p> <pre><code>pyflakes python_archive.py Example output: python_archive.py:1: 'python_archive2.SomeClass' imported but unused </code></pre>
2,512,386
how to merge 200 csv files in Python
<p>Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?</p>
2,512,572
22
5
null
2010-03-25 00:24:29.107 UTC
45
2021-08-16 05:30:29.577 UTC
2019-08-08 13:41:42.643 UTC
null
1,011,724
null
239,534
null
1
98
python|csv|merge|concatenation
193,030
<p>As ghostdog74 said, but this time with headers:</p> <pre><code>fout=open("out.csv","a") # first file: for line in open("sh1.csv"): fout.write(line) # now the rest: for num in range(2,201): f = open("sh"+str(num)+".csv") f.next() # skip the header for line in f: fout.write(line) f.close() # not really needed fout.close() </code></pre>
42,262,887
Enabling brand icon in `cardNumber` type element in Stripe
<p>When using <a href="https://stripe.com/docs/elements" rel="noreferrer">Stripe elements</a>, is there a way to <em>not</em> use the <code>card</code> element, but still get the auto brand icon show up somewhere (preferably in the <code>cardNumber</code> input field)?</p>
61,649,867
4
0
null
2017-02-16 00:49:55.823 UTC
6
2022-04-11 18:00:45.757 UTC
null
null
null
null
1,436,657
null
1
45
stripe-payments
11,904
<p>In 2020+, you can use the <code>showIcon</code> option.</p> <pre class="lang-js prettyprint-override"><code>const cardNumber = elements.create('cardNumber', { showIcon: true, placeholder: 'Card Number', }); </code></pre>
10,823,033
Sending arguments from Batch file to Python script
<p>I'm running Python 3.2 on Win XP. I run a python script thru a batch file via this:</p> <p><code>C:\Python32\python.exe test.py %1</code></p> <p><code>%1</code> is an argument that i pass to do some processing in the python script. </p> <p>I have 2 variables in the batch file that I also want to send as arguments to the python script.</p> <p><code>set $1=hey_hi_hello</code></p> <p><code>set $2=hey_hi</code></p> <p>I want to be able to do something like this if possible:</p> <p><code>C:\Python32\python.exe test.py %1 $1 $2</code></p> <p>And then retrieve these argiments in the python script via <code>sys.argv[2]</code> and <code>sys.argv[3]</code></p> <p>Would appreciate any help with this. Thank you.</p>
10,823,125
2
0
null
2012-05-30 19:34:05.263 UTC
7
2021-09-16 03:59:14.953 UTC
null
null
null
null
530,955
null
1
12
python|batch-file|windows-xp
48,633
<p>your_script.bat:</p> <pre><code>set VAR_1=this set VAR_2=that python your_script.py %1 %VAR_1% %VAR_2% </code></pre>
10,361,903
What does "Clear Graphics Context" means?
<p>In Xcode 4.3, when you choose some UIView object placed in .xib, you can find out there is an option saying "Clear Graphics Context". What does it means?</p>
10,363,801
2
0
null
2012-04-28 08:31:10.083 UTC
4
2013-10-16 07:30:56.657 UTC
null
null
null
null
237,589
null
1
51
ios|uiview
21,713
<blockquote> <p>When it is checked, iOS will draw the entire area covered by the object in transparent black before it actually draws the object.<br />It is rarely needed.</p> </blockquote> <hr> <p><a href="http://books.google.com.ua/books?id=sikKz-oQNFIC&amp;lpg=PA88&amp;ots=Bs5y9c16Pn&amp;dq=Clear%20Graphics%20Context%20checkbox&amp;hl=ru&amp;pg=PA81#v=onepage&amp;q&amp;f=false" rel="noreferrer">Beginning IOS 5 Development: Exploring the IOS SDK, page 81, paragraph3.</a></p>
10,539,419
javascript get element's tag
<p>Lets say this is my HTML:</p> <pre><code>&lt;div id="foo"&gt; &lt;input id="goo" value="text" /&gt; &lt;span id="boo"&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>I would like to be able to determine what tag belongs to a html element. </p> <p>Example element with id "foo" = <code>div</code>, "goo" = <code>input</code>, "boo" = <code>span</code> ...</p> <p>So something like this:</p> <pre><code>function getTag (id) { var element = document.getElementById(id); return element.tag; } </code></pre>
10,539,440
1
0
null
2012-05-10 17:40:24.917 UTC
2
2021-07-06 10:29:15.233 UTC
null
null
null
null
783,663
null
1
57
javascript|html|tags
74,115
<p><a href="https://developer.mozilla.org/en/DOM/element.tagName" rel="noreferrer"><strong>HTMLElement.tagName</strong></a></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 element = document.getElementById('myImgElement'); console.log('Tag name: ' + element.tagName); // Tag name: IMG</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;img src="http://placekitten.com/200/200" id="myImgElement" alt=""&gt;</code></pre> </div> </div> </p> <p><strong>NOTE</strong>: It returns tags in capitals. E.g. <code>&lt;img /&gt;</code> will return <code>IMG</code>.</p>
10,751,271
Accessing FXML controller class
<p>I would like to communicate with a FXML controller class at any time, to update information on the screen from the main application or other stages.</p> <p>Is this possible? I havent found any way to do it.</p> <p>Static functions could be a way, but they don't have access to the form's controls.</p> <p>Any ideas?</p>
10,753,277
4
0
null
2012-05-25 08:47:50.373 UTC
25
2017-02-06 16:45:15.08 UTC
null
null
null
null
546,975
null
1
79
javafx-2|fxml
106,627
<p>You can get the controller from the <code>FXMLLoader</code></p> <pre><code>FXMLLoader fxmlLoader = new FXMLLoader(); Pane p = fxmlLoader.load(getClass().getResource("foo.fxml").openStream()); FooController fooController = (FooController) fxmlLoader.getController(); </code></pre> <p>store it in your main stage and provide getFooController() getter method.<br> From other classes or stages, every time when you need to refresh the loaded "foo.fxml" page, ask it from its controller:</p> <pre><code>getFooController().updatePage(strData); </code></pre> <p>updatePage() can be something like:</p> <pre><code>// ... @FXML private Label lblData; // ... public void updatePage(String data){ lblData.setText(data); } // ... </code></pre> <p>in the FooController class.<br> This way other page users do not bother about page's internal structure like what and where <code>Label lblData</code> is. </p> <p>Also look the <a href="https://stackoverflow.com/a/10718683/682495">https://stackoverflow.com/a/10718683/682495</a>. In JavaFX 2.2 <code>FXMLLoader</code> is improved.</p>
6,064,548
Send commands to a GNU screen
<p>I have a GNU screen named demo, I want to send commands to it. How do I do this?</p> <pre><code>screen -S demo -X /home/aa/scripts/outputs.sh </code></pre> <p>yeilds <code>No screen session found.</code></p> <p>and doing <code>screen -ls</code> shows that it isn't running. </p>
6,065,178
2
5
null
2011-05-19 20:33:40.357 UTC
9
2018-11-15 01:34:51.883 UTC
2015-05-09 21:35:05.44 UTC
null
255,439
null
255,439
null
1
24
bash|gnu-screen
25,365
<p>If the Screen session isn't running, you won't be able to send things to it. Start it first.</p> <p>Once you've got a session, you need to distinguish between Screen commands and keyboard input. <code>screen -X</code> expects a Screen command. The <code>stuff</code> command sends input, and if you want to run that program from a shell prompt, you'll have to pass a newline as well.</p> <pre><code>screen -S demo -X stuff '/home/aa/scripts/outputs.sh ' </code></pre> <p>Note that this may be the wrong approach. Are you sure you want to type into whatever is active in that session? To direct the input at a particular window, use</p> <pre><code>screen -S demo -p 1 -X stuff '/home/aa/scripts/outputs.sh ' </code></pre> <p>where 1 is the window number (you can use its title instead).</p> <p>To start a new window in that session, use the <code>screen</code> command instead. (That's the <code>screen</code> Screen command, not the <code>screen</code> shell command.)</p> <pre><code>screen -S demo -p 1 -X screen '/home/aa/scripts/outputs.sh' </code></pre>
31,009,597
Do I need to reindex after vacuum full on Postgres 9.4
<p>I am using Postgres 9.4.</p> <p>I just ran vacuum full. I read about the differences between vacuum and vacuum full and considered a lot if I should run vacuum or vacuum full. As far as I can say, I required vacuum full and my db size came down from 48 GB to 24 GB.</p> <p>Would the old indexes would have become obsolete after vacuum full and do I need to run reindex?</p> <p>I ran "vacuum full verbose analyze", so analyze is done along with vacuum full.</p> <p>I read at several places that for Postgres > 9.0, I don't need reindex after vacuum full, but I want to be sure that it is the case.</p>
31,012,925
1
1
null
2015-06-23 17:33:03.123 UTC
5
2015-06-23 20:31:13.27 UTC
null
null
null
null
839,549
null
1
38
postgresql|vacuum
21,033
<p>A <code>REINDEX</code> immediately after a <code>VACUUM FULL</code> is <strong>useless</strong> because <code>VACUUM FULL</code> itself rebuilds the indexes.</p> <p>This is mentioned in the 9.4 documentation in <a href="http://www.postgresql.org/docs/9.4/static/routine-vacuuming.html#VACUUM-FOR-SPACE-RECOVERY">Recovering Disk Space</a> :</p> <blockquote> <p>...to reclaim the excess disk space it occupies, you will need to use VACUUM FULL, or alternatively CLUSTER or one of the table-rewriting variants of ALTER TABLE. These commands rewrite an entire new copy of the table and <strong>build new indexes for it</strong>.</p> </blockquote> <p>You are correct that this was not the case before version 9.0, which had <code>VACUUM FULL</code> reimplemented differently.</p> <p>Up to version 8.4, the reference doc for <a href="http://www.postgresql.org/docs/8.4/static/sql-vacuum.html">VACUUM</a> mentioned the need to reindex:</p> <blockquote> <p><s>The FULL option does not shrink indexes; a periodic REINDEX is still recommended. In fact, it is often faster to drop all indexes, VACUUM FULL, and recreate the indexes.</s></p> </blockquote> <p>But this caveat is now obsolete.</p>
31,583,771
How to disable WebStorm semicolon check?
<p>How to disable WebStorm semicolon check in Node.js?</p> <p>I have tried the following method but they do not work:</p> <ul> <li>Checked out the option <code>use semicolon to terminate statement</code></li> <li>Changed JavaScript version to ecma6</li> </ul>
31,584,542
7
1
null
2015-07-23 09:47:23.757 UTC
16
2021-09-29 08:36:29.853 UTC
2019-03-24 11:05:14.833 UTC
null
10,607,772
null
3,060,739
null
1
85
node.js|ecmascript-6|webstorm
34,184
<ol> <li><code>Settings/Preferences | Editor | Inspections</code></li> <li><code>JavaScript | Code style issues | Unterminated statement</code> -- disable this inspection</li> </ol> <p>You can also reach the same inspection by:</p> <ol> <li>Placing caret on problematic place in your Editor and bringing Quick Fix menu (<kbd>Alt + Enter</kbd> or by clicking on light bulb icon)</li> <li>Choosing right option in appeared menu (if not sure which one then try step #3 for few of them)</li> <li><kbd>Arrow Right</kbd> (or click on small triangle on the right side) to open submenu</li> <li>Choose desired action</li> </ol> <p><strong>P.S.</strong> JSLinh/JSHint and alike may also produce such warnings if you are using these tools.</p> <hr> <p>As for the actual code generated by IDE (e.g. when using <code>Code | Reformat...</code> or using code completion popup/functionality) -- such option is available at</p> <ul> <li><code>Settings/Preferences | Editor | Code Style | JavaScript</code> (similar path for TypeScript)</li> <li><code>Punctuation</code> tab</li> </ul> <p><a href="https://i.stack.imgur.com/KSKCC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KSKCC.png" alt="enter image description here"></a></p>
31,539,727
Laravel password validation rule
<p>How to added password validation rule in the validator?</p> <p><strong>Validation rule:</strong></p> <p>The password contains characters from at least three of the following five categories:</p> <ul> <li>English uppercase characters (A – Z)</li> <li>English lowercase characters (a – z)</li> <li>Base 10 digits (0 – 9)</li> <li>Non-alphanumeric (For example: !, $, #, or %)</li> <li>Unicode characters</li> </ul> <p>How to add above rule in the validator rule?</p> <p><strong>My Code Here</strong></p> <pre><code>// create the validation rules ------------------------ $rules = array( 'name' =&gt; 'required', // just a normal required validation 'email' =&gt; 'required|email|unique:ducks', // required and must be unique in the ducks table 'password' =&gt; 'required', 'password_confirm' =&gt; 'required|same:password' // required and has to match the password field ); // do the validation ---------------------------------- // validate against the inputs from our form $validator = Validator::make(Input::all(), $rules); // check if the validator failed ----------------------- if ($validator-&gt;fails()) { // get the error messages from the validator $messages = $validator-&gt;messages(); // redirect our user back to the form with the errors from the validator return Redirect::to('home') -&gt;withErrors($validator); } </code></pre>
31,549,892
7
2
null
2015-07-21 12:59:49.54 UTC
37
2022-08-17 00:00:31.31 UTC
2016-09-07 22:16:46.113 UTC
null
3,088,349
null
246,963
null
1
77
php|laravel|validation|laravel-5
171,310
<p>I have had a similar scenario in Laravel and solved it in the following way.</p> <p>The password contains characters from at least three of the following five categories:</p> <ul> <li>English uppercase characters (A – Z)</li> <li>English lowercase characters (a – z)</li> <li>Base 10 digits (0 – 9)</li> <li>Non-alphanumeric (For example: !, $, #, or %)</li> <li>Unicode characters</li> </ul> <p>First, we need to create a regular expression and validate it.</p> <p><strong>Your regular expression would look like this:</strong></p> <pre><code>^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$ </code></pre> <p>I have tested and validated it on <a href="https://regex101.com/r/lC1vM1/277" rel="nofollow noreferrer">this</a> site. Yet, perform your own in your own manner and adjust accordingly. This is only an example of regex, you can manipulate the way you want.</p> <p><strong>So your final Laravel <a href="https://laravel.com/docs/5.6/validation#rule-regex" rel="nofollow noreferrer">regex rule</a> should be like this:</strong></p> <pre><code>'password' =&gt; [ 'required', 'min:6', 'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/', 'confirmed' ] </code></pre> <p><strong>Note:</strong></p> <ol> <li>I have tested and validated it on both the regular expression site and a Laravel 5 test environment, and it works.</li> <li>I have used min:6, this is optional, but it is always a good practice to have a security policy that reflects different aspects, one of which is minimum password length.</li> <li>I suggest you to use password confirmed to ensure user typing correct password.</li> <li>Within the 6 characters, our regex should contain at least 3 of a-z or A-Z and number and special character.</li> <li>Always test your code in a test environment before moving to production.</li> <li>What I have done in this answer is just example of regex password</li> </ol> <p><strong>Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/23117999/laravel-validation-custom-message">Laravel Validation custom message</a></li> <li><a href="https://stackoverflow.com/questions/20320148/custom-validation-message-for-regex-rule-in-laravel">Custom validation message for regex rule in Laravel?</a></li> <li><a href="https://stackoverflow.com/questions/23996289/laravel-custom-validation-messages">Laravel custom validation messages</a></li> </ul>
52,123,627
How do I resolve "cannot find module for path X" importing a local Go module?
<p>In my Go project, I want to break out some generic functionality into a Go module, separate from the main project. I'm doing this outside of GOPATH in keeping with go's future. I don't want to publish the module on GitHub or anywhere else. </p> <p>All my attempts to import this module into the main project result in:</p> <pre><code>cannot find module for path X </code></pre> <p>I've run <code>go mod init X</code> in the module's folder. The contents of its <code>go.mod</code> file is:</p> <pre><code>module X </code></pre> <p>Building or installing this module seems to do nothing. I've found no sign of it in <code>$GOPATH/pgk/mod</code>.</p> <p>I've tried a variety of import statements:</p> <ul> <li><code>import "X"</code></li> <li><code>import "../x"</code> (<a href="https://tip.golang.org/cmd/go/#hdr-Relative_import_paths" rel="noreferrer">relative path to the module directory</a>)</li> <li><code>import "../x/X"</code> (path to the directory + module name)</li> </ul> <p>Help!</p>
52,124,448
5
1
null
2018-08-31 23:26:15.563 UTC
8
2022-02-12 15:29:40.47 UTC
2019-02-28 23:27:50.457 UTC
null
8,910,547
null
8,910,547
null
1
25
go|vgo
34,882
<p>So you wrote a Go &quot;library&quot; module <code>X</code> which:</p> <ul> <li>you don't want to publish on GitHub or elsewhere</li> <li>you want to import and use in your project (the &quot;main&quot; module).</li> </ul> <h2>Use a <code>replace</code> directive along with <code>require</code></h2> <p>In your main module's <code>go.mod</code>, add the following lines:</p> <pre><code>require &quot;X&quot; v0.0.0 replace &quot;X&quot; v0.0.0 =&gt; &quot;{local path to the X module}&quot; </code></pre> <p>The path should point to the root directory of <code>X</code>. It can be absolute or relative.</p> <p>To import package <em>util</em> from module <em>X</em>:</p> <pre><code>import &quot;X/util&quot; </code></pre> <p>(You don't import modules. You import packages from modules.)</p> <hr /> <h2>Explanation</h2> <p><a href="https://github.com/golang/go/wiki/Modules" rel="noreferrer">Go's module functionality</a> is designed for publicly published modules. Normally, a module's name is both its unique identifier and the path to its public repo. When your <a href="https://github.com/golang/go/wiki/Modules#gomod" rel="noreferrer">go.mod</a> declares a module dependency with the <code>require</code> directive, Go will automatically find and retrieve the specified version of the module at that path.</p> <p>If, for example, your <code>go.mod</code> file contains <code>require github.com/some/dependency v1.2.3</code>, Go will retrieve the module from GitHub at that path. But if it contains <code>require X v0.0.0</code>, &quot;X&quot; isn't an actual path and you will get the error <code>cannot find module for path X</code>.</p> <p>The <code>replace</code> directive allows you to specify a replacement path for a given module identifier and version. There are <a href="https://github.com/golang/go/wiki/Modules#when-should-i-use-the-replace-directive" rel="noreferrer">many reasons you'd want to do this</a>, such as to test changes to a module before pushing them to the public repo. But you can also use it to bind a module identifier to local code you don't ever intend to publish.</p> <p>More details in the Go Modules documentation:</p> <ul> <li><a href="https://github.com/golang/go/wiki/Modules#can-i-work-entirely-outside-of-vcs-on-my-local-filesystem" rel="noreferrer">Can I work entirely outside of VCS on my local filesystem?</a></li> <li><a href="https://github.com/golang/go/wiki/Modules#when-should-i-use-the-replace-directive" rel="noreferrer">When should I use the replace directive?</a></li> </ul> <p>Hope this helps.</p>
18,892,911
Reporting Services - Count Column Values if equals A
<p>I have a dataset called 'dsAllStuTargetData' - i'm trying to count the number of the 'A' values that appear in the column 'Target'.</p> <p>I'm doing this using a textbox with an expression, I can count the total number of values using the following:</p> <pre><code>=Count(Fields!Target.Value, "dsAllStuTargetData") </code></pre> <p>However when I try to count where the value equals 'A' it doesn't work.</p> <pre><code>=Count(IIF(Fields!Target.Value, "dsAllStuTargetData")="A",1,0) </code></pre>
18,893,516
2
0
null
2013-09-19 11:04:15.04 UTC
3
2013-09-19 11:34:20.803 UTC
null
null
null
null
1,686,127
null
1
12
reporting-services
49,583
<p>For this case you need a <code>Sum</code>, not a <code>Count</code>, i.e. something like:</p> <pre><code>=Sum(IIf(Fields!Target.Value = "A", 1, 0), "dsAllStuTargetData") </code></pre> <p><code>Count</code> will just count the number of rows; the <code>IIf</code> doesn't do anything there - something like <code>CountDistinct</code> can be affected in certain cases but this will not work here.</p> <p>However, <code>Sum</code> will take the total of all rows which meet the <code>IIf</code> condition, i.e. the total of all <code>1</code> values in the DataSet, which is what you're after.</p>
25,914,071
CORS error for application running from file:// scheme
<p>I have an AngularJS/Cordova app which polls a JSON service on a remote server:</p> <pre><code>$http({method: 'GET', url: 'http://example.com/index.php'}) </code></pre> <p>Developing in the browser and running off my intranet apache server (<code>http://dev</code>) I get "No 'Access-Control-Allow-Origin' header is present" so I fix this by adding:</p> <pre><code>Header set Access-Control-Allow-Origin "http://dev" </code></pre> <p>All works fine, and I see <code>Origin:http://dev</code> in my Chrome dev tools.</p> <p>So, having to think about this for the first time, I wonder what the Origin will be when the app runs in the Android/iOS webviews. I decide to do a build and deploy on my devices and expect to see the same error in remote debugging (Safari for iOS and Weinre for Android), but to my surprise it works (without sending any CORS headers)! I also find that in both devices the app runs in the webview under the file:// scheme, rather than (what I assumed) a http server of some sorts provided by the phone OS.</p> <p>So research seems to suggest that CORS is not required for file:// - such a "site' may access any XHR resource on any domain. But, when I test this on desktop browsers I find that while Safari does not need CORS for file:// but Chrome does, and FireFox works either way without CORS</p> <p>So my questions:</p> <p>1) why is my app working without CORS in Android/iOS - is it because CORS does not apply to file://, or, is Cordova doing something to make it work in the device?</p> <p>I have <code>&lt;access origin="*"/&gt;</code> in my config</p> <p>2) if, pending answers to Q1, I should want to be on the safe site and explicitly allow requests from apps, what value do you give Access-Control-Allow-Origin for file:// "hosts"? in my debugging there is no Origin header in the requests from file://</p> <p>3) in addition to blocking the XHR request to the remote server, Chrome is also blocking my app templates (I'm using separate files), see below. Is this a potential issue with my app, or just a Chrome issue that I do not need to worry about? </p> <pre><code>XMLHttpRequest cannot load file:///Volumes/projects/phonegap/www/templates/tabs.html. Cross origin requests are only supported for HTTP. </code></pre>
25,914,800
1
0
null
2014-09-18 13:28:37.803 UTC
8
2021-08-11 14:53:27.067 UTC
2020-08-25 05:46:09.24 UTC
null
441,757
null
602,088
null
1
19
javascript|ajax|angularjs|cordova|cors
25,502
<p>There are two ways for CORS headers to signal that a cross-domain XHR should be allowed:</p> <ul> <li>sending <code>Access-Control-Allow-Origin: *</code> (allow all hosts)</li> <li>put the host you would like to allow into the <code>Origin</code> header by your backend</li> </ul> <p>As for the <code>file://</code> URLs they will produce a <strong>null</strong> <code>Origin</code> which can't be authorized via the second option (<em>echo-back</em>).</p> <p>As <a href="https://stackoverflow.com/questions/21297169/cors-and-phonegap-apps">mentioned</a>:</p> <blockquote> <p>Cross-domain policy does not apply to PhoneGap (for a variety of reasons, basically because your app is essentially running off the file:// URI on-device).</p> <p>Please be aware that you will have to set up a whitelist for your apps to access these external domains.</p> </blockquote> <p>As for the <strong>Chrome</strong> problem, which can be seen in the developer's console:</p> <p><code>Failed to load resource: net::ERR_FILE_NOT_FOUND file:///C:/2.html</code> <code>XMLHttpRequest cannot load file:///C:/2.html. Received an invalid response. Origin 'null' is therefore not allowed access.</code></p> <p>there was a discussion on <a href="https://code.google.com/p/chromium/issues/detail?id=40787" rel="noreferrer">Chromium project's issue tracker, #40787</a>. They mark the issues as <strong>won't fix</strong> as that behaviour is happening by design.</p> <p>There is a workaround proposed to simply switch off CORS in Chrome for development purposes, starting chrome with <code>--allow-file-access-from-files --disable-web-security</code></p> <p>e.g. for Windows</p> <pre><code>`C:\Users\YOUR_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files --disable-web-security` </code></pre> <p>Here is some more cordova related answer:</p> <ul> <li><a href="https://stackoverflow.com/questions/21297169/cors-and-phonegap-apps">CORS and phonegap apps</a></li> <li><a href="http://docs.phonegap.com/en/1.8.0rc1/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide" rel="noreferrer">Domain whitelisting in Apache Cordova</a> - a security model that controls access to outside domains.</li> </ul> <p>Check these resources for more info on CORS:</p> <ul> <li><a href="https://stackoverflow.com/questions/5138057/cross-origin-resource-sharing-and-file">Cross-Origin resource sharing and file://</a></li> <li><a href="http://www.html5rocks.com/en/tutorials/cors/" rel="noreferrer">A nice CORS tutorial: http://www.html5rocks.com/en/tutorials/cors/</a></li> <li><a href="http://www.sitepoint.com/working-around-origin-policy/" rel="noreferrer">Working around origin policy</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" rel="noreferrer">HTTP access control (CORS) (Mozilla)</a></li> </ul> <p>Check also Browser support for CORS:</p> <ul> <li><a href="http://caniuse.com/#feat=cors" rel="noreferrer">http://caniuse.com/#feat=cors</a></li> </ul> <p>And for the record <a href="http://www.w3.org/TR/cors/" rel="noreferrer">formal CORS specification on W3C</a> :)</p>
51,881,196
To display the names of all students who have secured more than 50 in all subjects that they have appeared in
<p>Write a query to display the names of all students who have secured more than 50 in all subjects that they have appeared in, ordered by student name in ascending order.<a href="https://i.stack.imgur.com/KOsPh.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I have used this below query but didn't getting desired result as it is not comparing the result by grouping the student_id as whole. Can anyone suggest any changes in query please.</p> <pre><code>select distinct student_name from student s join mark m on s.student_id = m.student_id join subject sb on m.subject_id = sb.subject_id where m.value IN (select value from mark m1 join student s1 on m1.student_id = s1.student_id join subject sb1 on m1.subject_id = sb1.subject_id where value &gt; 50 group by s1.student_id,m1.value, sb1.subject_id) order by 1; </code></pre>
51,881,543
8
1
null
2018-08-16 16:03:20.41 UTC
0
2022-03-26 16:18:15.407 UTC
2018-08-18 06:06:20.157 UTC
user177800
null
null
10,151,280
null
1
-4
oracle
43,101
<p>I don't think that you need such a complex subquery. All you need to do is just find out the minimum marks for a student (<a href="https://www.w3schools.com/sql/sql_join.asp" rel="nofollow noreferrer">INNER JOIN</a> ensures that only those subjects are considered, which have been attempted by the student). </p> <p>Do a simple <a href="https://www.w3schools.com/sql/sql_join.asp" rel="nofollow noreferrer">JOIN</a> between student and marks table on student_id. We do a <a href="https://www.w3schools.com/sql/sql_groupby.asp" rel="nofollow noreferrer">GROUP BY</a> on the <code>student_id</code> and get <code>minimum_marks</code> for each student. If the <code>minimum_marks</code> > 50, it means that the student has > 50 marks in all the subjects. Try the following, this will work in <strong>MySQL</strong> (as per the Original tag by OP):</p> <pre><code>SELECT s.student_name, MIN(m.value) AS minimum_marks FROM student s JOIN mark m ON s.student_id = m.student_id GROUP BY s1.student_id HAVING minimum_marks &gt; 50 ORDER BY s.student_name ASC </code></pre> <p><strong>Edit</strong> As per Oracle (since OP edited later), <a href="https://community.oracle.com/thread/2379402" rel="nofollow noreferrer">aliased fields/expressions are not allowed</a> in the <code>HAVING</code> clause. Revised query would look like:</p> <pre><code>SELECT s.student_name, MIN(m.value) AS minimum_marks FROM student s JOIN mark m ON s.student_id = m.student_id GROUP BY s1.student_id HAVING MIN(m.value) &gt; 50 ORDER BY s.student_name ASC </code></pre>
8,377,055
Submit data via web form and extract the results
<p>My python level is Novice. I have never written a web scraper or crawler. I have written a python code to connect to an api and extract the data that I want. But for some the extracted data I want to get the gender of the author. I found this web site <code>http://bookblog.net/gender/genie.php</code> but downside is there isn't an api available. I was wondering how to write a python to submit data to the form in the page and extract the return data. It would be a great help if I could get some guidance on this.</p> <p>This is the form dom: </p> <pre><code>&lt;form action="analysis.php" method="POST"&gt; &lt;textarea cols="75" rows="13" name="text"&gt;&lt;/textarea&gt; &lt;div class="copyright"&gt;(NOTE: The genie works best on texts of more than 500 words.)&lt;/div&gt; &lt;p&gt; &lt;b&gt;Genre:&lt;/b&gt; &lt;input type="radio" value="fiction" name="genre"&gt; fiction&amp;nbsp;&amp;nbsp; &lt;input type="radio" value="nonfiction" name="genre"&gt; nonfiction&amp;nbsp;&amp;nbsp; &lt;input type="radio" value="blog" name="genre"&gt; blog entry &lt;/p&gt; &lt;p&gt; &lt;/form&gt; </code></pre> <p>results page dom:</p> <pre><code>&lt;p&gt; &lt;b&gt;The Gender Genie thinks the author of this passage is:&lt;/b&gt; male! &lt;/p&gt; </code></pre>
8,377,373
3
0
null
2011-12-04 17:14:48.67 UTC
13
2012-12-03 20:43:14.627 UTC
2012-12-03 20:43:14.627 UTC
null
1,529,339
null
200,317
null
1
16
python|web-crawler|web-scraping
48,431
<p>No need to use mechanize, just send the correct form data in a POST request.</p> <p>Also, using regular expression to parse HTML is a bad idea. You would be better off using a HTML parser like lxml.html.</p> <pre><code>import requests import lxml.html as lh def gender_genie(text, genre): url = 'http://bookblog.net/gender/analysis.php' caption = 'The Gender Genie thinks the author of this passage is:' form_data = { 'text': text, 'genre': genre, 'submit': 'submit', } response = requests.post(url, data=form_data) tree = lh.document_fromstring(response.content) return tree.xpath("//b[text()=$caption]", caption=caption)[0].tail.strip() if __name__ == '__main__': print gender_genie('I have a beard!', 'blog') </code></pre>
8,526,681
Extract random effect variances from lme4 mer model object
<p>I have a mer object that has fixed and random effects. How do I extract the variance estimates for the random effects? Here is a simplified version of my question.</p> <pre><code>study &lt;- lmer(Reaction ~ Days + (1|Subject), data = sleepstudy) study </code></pre> <p>This gives a long output - not too long in this case. Anyway, how do I explicitly select the</p> <pre><code>Random effects: Groups Name Variance Std.Dev. Subject (Intercept) 1378.18 37.124 Residual 960.46 30.991 </code></pre> <p>part of the output? I want the values themselves.</p> <p>I have taken long looks at</p> <pre><code>str(study) </code></pre> <p>and there's nothing there! Also checked any extractor functions in the lme4 package to no avail. Please help!</p>
8,527,030
7
0
null
2011-12-15 21:13:39.603 UTC
13
2021-06-26 21:51:46.693 UTC
null
null
null
null
790,612
null
1
50
r|random|effects|lme4
45,935
<p><code>lmer</code> returns an S4 object, so this should work:</p> <pre><code>remat &lt;- summary(study)@REmat print(remat, quote=FALSE) </code></pre> <p>Which prints:</p> <pre><code> Groups Name Variance Std.Dev. Subject (Intercept) 1378.18 37.124 Residual 960.46 30.991 </code></pre> <p>...In general, you can look at the source of the <code>print</code> and <code>summary</code> methods for "mer" objects:</p> <pre><code>class(study) # mer selectMethod("print", "mer") selectMethod("summary", "mer") </code></pre>
60,915,381
Retrofit2, maven project, Illegal reflective access warning
<p>I just started a new maven project and did a simple implementation of the Retrofit client. I'm getting the following warnings:</p> <pre><code>WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by retrofit2.Platform (file:/C:/Users/Admin/.m2/repository/com/squareup/retrofit2/retrofit/2.8.1/retrofit-2.8.1.jar) to constructor java.lang.invoke.MethodHandles$Lookup(java.lang.Class,int) WARNING: Please consider reporting this to the maintainers of retrofit2.Platform WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release Process finished with exit code 0 </code></pre> <p>here is the code</p> <pre><code>import retrofit2.Retrofit; import retrofit2.SimpleXmlConverterFactory; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; public class RetrofitClient { private static Retrofit retrofit = null; private RetrofitClient() { } public static EndPoints getAPI(String baseUrl) { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(SimpleXmlConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } return retrofit.create(EndPoints.class); } } </code></pre> <p>Interface is simply</p> <pre><code>import retrofit2.Call; import retrofit2.http.GET; public interface EndPoints { @GET("teststatuses") Call&lt;String&gt; testStatus(); } </code></pre> <p>Call looks like this:</p> <pre><code>EndPoints endPoints = RetrofitClient.getAPI("http://localhost:8080/"); Call&lt;String&gt; repos = endPoints.testStatus(); System.out.println(repos.execute()); </code></pre> <p>The project runs java language level 11 with SDK 11</p>
61,259,233
5
0
null
2020-03-29 14:09:15.173 UTC
3
2022-04-01 05:47:51.57 UTC
null
null
null
null
12,994,462
null
1
28
java|retrofit
11,260
<p>There was an <a href="https://github.com/square/retrofit/issues/3341" rel="nofollow noreferrer">issue</a> filed about this, to which one of the Retrofit maintainers responded:</p> <blockquote> <p>The reflection works around a bug in the JDK which was fixed in 14 but it's only used for default methods. As it's only a warning, it's not preventing your call from working.</p> </blockquote> <p>So your options are either to</p> <ol> <li>stick with Retrofit 2.8.x, and <ul> <li>ignore the warning, or</li> <li>upgrade to Java 14</li> </ul> </li> <li>downgrade to Retrofit 2.7.*</li> </ol>
27,374,330
@IBDesignable error: IB Designables: Failed to update auto layout status: Interface Builder Cocoa Touch Tool crashed
<p>I have a very simple subclass of UITextView that adds the &quot;Placeholder&quot; functionality that you can find native to the Text Field object. Here is my code for the subclass:</p> <pre><code>import UIKit import Foundation @IBDesignable class PlaceholderTextView: UITextView, UITextViewDelegate { @IBInspectable var placeholder: String = &quot;&quot; { didSet { setPlaceholderText() } } private let placeholderColor: UIColor = UIColor.lightGrayColor() private var textColorCache: UIColor! override init(frame: CGRect) { super.init(frame: frame) self.delegate = self } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.delegate = self } func textViewDidBeginEditing(textView: UITextView) { if textView.text == placeholder { textView.text = &quot;&quot; textView.textColor = textColorCache } } func textViewDidEndEditing(textView: UITextView) { if textView.text == &quot;&quot; &amp;&amp; placeholder != &quot;&quot; { setPlaceholderText() } } func setPlaceholderText() { if placeholder != &quot;&quot; { if textColorCache == nil { textColorCache = self.textColor } self.textColor = placeholderColor self.text = placeholder } } } </code></pre> <p>After changing the class for the <code>UITextView</code> object in the Identity Inspector to <code>PlaceholderTextView</code>, I can set the <code>Placeholder</code> property just fine in the Attribute Inspector. The code works great when running the app, but does not display the placeholder text in the interface builder. I also get the following non-blocking errors (I assume this is why it's not rendering at design time):</p> <blockquote> <p>error: IB Designables: Failed to update auto layout status: Interface Builder Cocoa Touch Tool crashed</p> <p>error: IB Designables: Failed to render instance of PlaceholderTextView: Rendering the view took longer than 200 ms. Your drawing code may suffer from slow performance.</p> </blockquote> <p>I'm not able to figure out what is causing these errors. The second error doesn't make any sense, as I'm not even overriding drawRect(). Any ideas?</p>
31,159,281
22
1
null
2014-12-09 08:26:22.83 UTC
45
2020-11-08 08:21:21.503 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
300,408
null
1
161
ios|swift|xcode|storyboard|interface-builder
83,780
<p>There are crash reports generated when Interface Builder Cocoa Touch Tool crashes. Theses are located in <code>~/Library/Logs/DiagnosticReports</code> and named <code>IBDesignablesAgentCocoaTouch_*.crash</code>. In my case they contained a useful stack-trace that identified the issue in my code.</p>
26,614,465
Python pandas apply function if a column value is not NULL
<p>I have a dataframe (in Python 2.7, pandas 0.15.0):</p> <pre><code>df= A B C 0 NaN 11 NaN 1 two NaN ['foo', 'bar'] 2 three 33 NaN </code></pre> <p>I want to apply a simple function for rows that does not contain NULL values in a specific column. My function is as simple as possible:</p> <pre><code>def my_func(row): print row </code></pre> <p>And my apply code is the following:</p> <pre><code>df[['A','B']].apply(lambda x: my_func(x) if(pd.notnull(x[0])) else x, axis = 1) </code></pre> <p>It works perfectly. If I want to check column 'B' for NULL values the <code>pd.notnull()</code> works perfectly as well. But if I select column 'C' that contains list objects:</p> <pre><code>df[['A','C']].apply(lambda x: my_func(x) if(pd.notnull(x[1])) else x, axis = 1) </code></pre> <p>then I get the following error message: <code>ValueError: ('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()', u'occurred at index 1')</code></p> <p>Does anybody know why <code>pd.notnull()</code> works only for integer and string columns but not for 'list columns'?</p> <p>And is there a nicer way to check for NULL values in column 'C' instead of this:</p> <pre><code>df[['A','C']].apply(lambda x: my_func(x) if(str(x[1]) != 'nan') else x, axis = 1) </code></pre> <p>Thank you!</p>
26,614,921
7
0
null
2014-10-28 17:15:31.987 UTC
12
2022-04-09 11:33:43.573 UTC
null
null
null
null
2,740,380
null
1
45
python|list|pandas|null|apply
131,782
<p>The problem is that <code>pd.notnull(['foo', 'bar'])</code> operates elementwise and returns <code>array([ True, True], dtype=bool)</code>. Your if condition trys to convert that to a boolean, and that's when you get the exception.</p> <p>To fix it, you could simply wrap the isnull statement with <code>np.all</code>:</p> <pre><code>df[['A','C']].apply(lambda x: my_func(x) if(np.all(pd.notnull(x[1]))) else x, axis = 1) </code></pre> <p>Now you'll see that <code>np.all(pd.notnull(['foo', 'bar']))</code> is indeed <code>True</code>.</p>
522,043
How do you handle associations between aggregates in DDD?
<p>I'm still wrapping my head around DDD, and one of the stumbling blocks I've encountered is in how to handle associations between separate aggregates. Say I've got one aggregate encapsulating Customers and another encapsulating Shipments.</p> <p>For business reasons Shipments are their own aggregates, and yet they need to be explicitly tied to Customers. Should my Customer domain entity have a list of Shipments? If so, how do I populate this list at the repository level - given I'll have a CustomerRepository and a ShipmentRepository (one repo per aggregate)?</p> <p>I'm saying 'association' rather than 'relationship' because I want to stress that this is a domain decision, not an infrastructure one - I'm designing the system from the model first.</p> <p>Edit: I know I don't need to model tables directly to objects - that's the reason I'm designing the model first. At this point I don't care about the database at all - just the associations between these two aggregates.</p>
522,190
3
3
null
2009-02-06 20:31:42.663 UTC
11
2009-02-10 01:25:19.877 UTC
2009-02-06 22:43:58.14 UTC
Erik
16,942
Erik
16,942
null
1
18
domain-driven-design|aggregate
2,585
<p>There's no reason your ShipmentRepository can't aggregate customer data into your shipment models. Repositories do not have to have a 1-to-1 mapping with tables.</p> <p>I have several repositories which combine multiple tables into a single domain model.</p>
435,442
How can I send a JSON response from a Perl CGI program?
<p>I am writing a JSON response from a perl/cgi program. The header's content type needs to be "application/json". But it doesn't seems to be recognized as response is thrown as a text file. </p> <p>I would be capturing response using JSON library of jQuery. Where am I missing in sending the JSON response. </p>
435,541
3
5
null
2009-01-12 13:48:10.117 UTC
4
2013-11-29 08:06:14.187 UTC
2009-01-12 18:59:30.55 UTC
brian d foy
2,766,176
Rakesh
50,851
null
1
20
javascript|perl|json
48,105
<p>I am doing this in a perl/cgi program.</p> <p>I use these in the top of my code:</p> <pre><code>use CGI qw(:standard); use JSON; </code></pre> <p>Then I print the json header:</p> <pre><code>print header('application/json'); </code></pre> <p>which is a content type of:</p> <pre><code>Content-Type: application/json </code></pre> <p>And then I print out the JSON like this:</p> <pre><code>my $json-&gt;{"entries"} = \@entries; my $json_text = to_json($json); print $json_text; </code></pre> <p>My javascript call/handles it like this:</p> <pre><code> $.ajax({ type: 'GET', url: 'myscript.pl', dataType: 'json', data: { action: "request", last_ts: lastTimestamp }, success: function(data){ lastTs = data.last_mod; for (var entryNumber in data.entries) { //Do stuff here } }, error: function(){ alert("Handle Errors here"); }, complete: function() { } }); </code></pre> <p>You don't necessarily have to use the JSON library if you don't want to install it, you could print straight JSON formatted text, but it makes converting perl objects to JSON prety easy.</p>
1,338,518
One-liner Python code for setting string to 0 string if empty
<p>What is a one-liner code for setting a string in python to the string, 0 if the string is empty?</p> <pre><code># line_parts[0] can be empty # if so, set a to the string, 0 # one-liner solution should be part of the following line of code if possible a = line_parts[0] ... </code></pre>
1,338,532
3
3
null
2009-08-27 02:12:49.287 UTC
11
2018-09-27 08:12:07.093 UTC
null
null
null
null
150,842
null
1
27
python|string
23,724
<pre><code>a = line_parts[0] or "0" </code></pre> <p>This is one of the nicest Python idioms, making it easy to provide default values. It's often used like this for default values of functions:</p> <pre><code>def fn(arg1, arg2=None): arg2 = arg2 or ["weird default value"] </code></pre>
218,033
Is there a performance difference between Javac debug on and off?
<p>If I switch on the generating of debug info with Javac then the class files are 20-25% larger. Has this any performance effects on running the Java program? If yes on which conditions and how many. I expect a little impact on loading the classes because the files are larger but this should be minimal.</p>
218,194
3
0
null
2008-10-20 10:49:14.033 UTC
12
2018-09-19 17:14:29.967 UTC
2009-11-13 16:56:47.383 UTC
null
20,774
Horcrux7
12,631
null
1
61
java|performance|debugging|javac
18,823
<p>In any language, debugging information is meta information. It by its nature increases the size of the object files, thus increasing load time. During execution outside a debugger, this information is actually completely ignored. As outlined (although not clearly) in the <a href="http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#1546" rel="noreferrer">JVM spec</a> the debug information is stored outside the bytecode stream. This means that at execution time there is no difference in the class file. If you want to be sure though, try it out :-).</p> <p>Ps. Often for debugging there is value in turning off optimization. That <em>does</em> have a performance impact.</p>
39,536,358
Visual Studio: Tab key selects and highlights code
<p>If I place my cursor inside a multi-line comment:</p> <pre><code>/* * place cursor after the asterisk and before the word 'place' */ if (x == 0) { // some code } </code></pre> <p>... and hit <kbd>tab</kbd>, Visual Studio doesn't add whitespace as usual. Instead, it highlights the entire comment (all three lines, in the example). If I hit <kbd>tab</kbd> again, it will select and highlight the next statement or block of statements. In my example, it highlights the entire <code>if</code>.</p> <p>How do I fix this and make Visual Studio tab things over? I want <kbd>tab</kbd> to behave like a <kbd>tab</kbd>.</p> <p>I'm using Visual Studio 2013 Ultimate with Resharper 9. It started doing this yesterday, and I have no idea why.</p>
39,536,514
1
0
null
2016-09-16 16:36:46.603 UTC
8
2016-09-16 16:48:31.46 UTC
null
null
null
user47589
null
null
1
31
visual-studio-2013|resharper|keyboard-shortcuts
6,077
<p>Figured it out. It wasn't in VS' settings! Somehow Resharper's configuration was changed. In Resharper's settings:</p> <pre><code>Environment &gt; Editor &gt; Editor Behavior </code></pre> <p>Uncheck the box labeled "Structural Navigation". Click "Save". </p>
22,153,521
What are the differences between rbenv, rvm, and chruby?
<p>I'm new-ish to Ruby and Rails. I am looking for a purely objective list of features and advantages/disadvantages of each. In an effort to keep preference out of this, please refrain from answering unless you have used all 3 systems. </p>
22,153,979
1
0
null
2014-03-03 17:40:04.413 UTC
13
2018-10-19 21:13:40.797 UTC
2014-03-03 18:13:48.92 UTC
null
1,193,216
null
2,097,600
null
1
57
ruby|rvm|rbenv|chruby
28,544
<p>There's three main options available today:</p> <ul> <li><a href="http://rvm.io" rel="noreferrer">rvm</a> which is the most established, but also the most intrusive in terms of shell modifications.</li> <li><a href="https://github.com/sstephenson/rbenv" rel="noreferrer">rbenv</a> which is lower impact, and still works as well.</li> <li><a href="https://github.com/postmodern/chruby" rel="noreferrer">chruby</a> which purports to be even lighter than <code>rbenv</code>.</li> </ul> <p>Personally I prefer <code>rbenv</code> because it works well with <a href="http://brew.sh/" rel="noreferrer">Homebrew</a> and doesn't mangle the shell environment as much, but tend to use <code>rvm</code> on servers where that doesn't matter because they're set up for a very specific purpose.</p>
20,584,156
Tell Apache to use a specific PHP version installed using phpbrew
<p>I had the PHP, MySQL, and Apache stack installed for development. That installation is using configuration files from:</p> <pre><code>/etc/apache2/ /etc/php5/ </code></pre> <p>Later I installed multiple PHP version using <code>phpbrew</code>. All versions are accessible and switchable from CLI. But Apache always stays on the default version that was not installed using <strong>phpbrew</strong>.</p> <p>Here is a list of my installed PHP versions.</p> <pre><code>$ phpbrew list Installed versions: php-5.4.13 (/home/admin1/.phpbrew/php/php-5.4.13) +default -- --with-bz2=/usr php-5.5.5 (/home/admin1/.phpbrew/php/php-5.5.5) php-5.3.27 (/home/admin1/.phpbrew/php/php-5.3.27) </code></pre> <p>I have tried changing configuration file paths so they point to phpbrew's PHP. But nothing seems to be working.</p> <p>How can I tell Apache to use phpbrew's PHP version?</p>
20,706,294
5
0
null
2013-12-14 13:55:33.483 UTC
17
2021-06-10 16:23:04.663 UTC
2016-12-27 15:09:27.077 UTC
null
63,550
null
1,115,957
null
1
24
php|apache|multiple-versions
30,160
<p>You need to build a PHP with <code>apxs2</code>:</p> <p><strong>1)</strong> Ensure your have installed <code>sudo apt-get install apache2-dev</code>.</p> <p><strong>2)</strong> Run <code>phpbrew install 5.4.22 +apxs2=/usr/bin/apxs2</code></p> <p>Then you should see the built module file in your Apache configuration file.</p>
42,975,609
How to capture botocore's NoSuchKey exception?
<p>I'm trying to write "good" python and capture a S3 no such key error with this:</p> <pre><code>session = botocore.session.get_session() client = session.create_client('s3') try: client.get_object(Bucket=BUCKET, Key=FILE) except NoSuchKey as e: print &gt;&gt; sys.stderr, "no such key in bucket" </code></pre> <p>But NoSuchKey isn't defined and I can't trace it to the import I need to have it defined.</p> <p><code>e.__class__</code> is <code>botocore.errorfactory.NoSuchKey</code> but <code>from botocore.errorfactory import NoSuchKey</code> gives an error and <code>from botocore.errorfactory import *</code> doesn't work either and I don't want to capture a generic error. </p>
42,978,638
4
1
null
2017-03-23 12:09:00.48 UTC
16
2019-08-21 19:40:13.49 UTC
null
null
null
null
228,141
null
1
163
python|botocore
55,954
<pre><code>from botocore.exceptions import ClientError try: response = self.client.get_object(Bucket=bucket, Key=key) return json.loads(response["Body"].read()) except ClientError as ex: if ex.response['Error']['Code'] == 'NoSuchKey': logger.info('No object found - returning empty') return dict() else: raise </code></pre>
41,356,279
How to get current year in android?
<p>I tried</p> <pre><code>int year = Calendar.get(Calendar.YEAR); </code></pre> <p>but it is giving me compile time error that </p> <blockquote> <p>Non-static method 'get(int)' cannot be referenced from a static context.</p> </blockquote> <p>I am calling this method from call method of observable.</p> <pre><code>Observable.combineLatest(ob1 ob2, ob3, new Func3&lt;String, String, String, Boolean&gt;() { @Override public Boolean call(String a, String b, String c) {... </code></pre> <p>I had also seen <code>(new Date()).getYear();</code> but it is deprecated.</p>
41,356,320
8
1
null
2016-12-28 06:05:45.23 UTC
4
2022-07-26 02:05:36.88 UTC
null
null
null
null
6,390,459
null
1
54
java|android
70,183
<p>Yeah, you get an error because this is not a static method. First you need to create an instance of the Calendar class.<br> i.e.</p> <pre><code>Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); </code></pre> <p>If your min API version is &lt;26, you can do a shorthand as well:</p> <pre><code>val yearInt = Year.now().value </code></pre>
19,844,561
Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar
<p>I'm new to the bootstrap framework.</p> <p><strong>Logo Increasing Height of NavBar:</strong></p> <p>In my navigation bar, I have inserted a logo that has a height of 50px. This obviously makes the navbar taller. I have not adjusted any CSS for this, it is simply the logo that is forcing the increased height.</p> <p><strong>Problem:</strong></p> <p>The links in the navbar are aligned to the top of the now taller navbar.</p> <p><strong>Goal:</strong></p> <p>I'd like the links vertically centered in the navbar as that will look much better.</p> <hr> <p>My assumption was to play with line-height values or padding. However, that introduced the problem of still taking effect on mobile browsers (when it switches to the toggle menu) so my expanded menu ends up being way too tall that it looked silly.</p> <p>Any insight is greatly appreciated?</p> <p>My CSS is the default bootstrap CSS downloaded with the latest version 3.0.2.</p> <p>Here is my HTML:</p> <pre><code>&lt;!-- Begin NavBar --&gt; &lt;div class="navbar navbar-inverse navbar-static-top" role="navigation"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".menu2"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;span class="navbar-brand" href="#"&gt;&lt;img src="img/logo.png" width="210" height="50" alt="My Logo"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="navbar-collapse collapse menu2"&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li&gt;&lt;a href="#"&gt;Link 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>It is those "Link 1", "Link 2", "Link 3" and "Link 4" links that are aligning to the top, when I really want them to be aligned vertically in the center.</p>
19,848,751
6
0
null
2013-11-07 19:09:30.307 UTC
15
2018-10-10 08:16:13.08 UTC
2018-10-10 08:16:13.08 UTC
null
3,885,376
null
1,440,176
null
1
54
css|twitter-bootstrap|twitter-bootstrap-3
106,383
<p>add this to your stylesheet. line-height should match the height of your logo</p> <pre><code>.navbar-nav li a { line-height: 50px; } </code></pre> <p>Check out the fiddle at: <a href="http://jsfiddle.net/nD4tW/">http://jsfiddle.net/nD4tW/</a></p>
6,163,152
How to patch *just one* instance of Autocomplete on a page?
<p>This answer -- <a href="https://stackoverflow.com/questions/2435964/jqueryui-how-can-i-custom-format-the-autocomplete-plug-in-results/2436493#2436493">jQueryUI: how can I custom-format the Autocomplete plug-in results?</a> -- describes how to monkeypatch the jqueryUI autocomplete widget, so that it displays things in a particular way. The approach it uses is to replace a function on the <code>$.ui.autocomplete.prototype</code>. </p> <p>This means that <em>all</em> autocomplete widgets will get this patch. </p> <p>Is there a way to patch the autocomplete widget for <em>just one input element</em>? What is it? </p> <p>When I examine <code>$('$input').autocomplete</code> , I don't see any of the autocomplete fns there (_renderItem, _renderMenu, _search, etc). </p>
6,164,621
3
0
null
2011-05-28 17:14:47.38 UTC
11
2013-02-06 13:46:07.423 UTC
2017-05-23 11:58:41.133 UTC
null
-1
null
48,082
null
1
21
jquery-ui|autocomplete|jquery-ui-autocomplete
8,358
<p>Check out the <a href="http://jqueryui.com/demos/autocomplete/#custom-data" rel="noreferrer">custom data and display demo</a>. This demo is not modifying the prototype object of the autocomplete widget, meaning that only that instance of the widget is effected:</p> <pre><code>$("selector").autocomplete({ ... }).data( "autocomplete" )._renderItem = function( ul, item ) { return $( "&lt;li&gt;&lt;/li&gt;" ) .data( "item.autocomplete", item ) .append( "&lt;a&gt;" + item.label + "&lt;br&gt;" + item.desc + "&lt;/a&gt;" ) .appendTo( ul ); }; </code></pre> <p>Here's a working demo: <a href="http://jsfiddle.net/vJSwq/" rel="noreferrer">http://jsfiddle.net/vJSwq/</a></p>
5,743,866
Json values in jQuery foreach loop
<p>I'm getting the following JSON response from the server:</p> <pre class="lang-json prettyprint-override"><code>[{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"}, {"id":"2","pid":"0","type":"Group","code":"g","status":"1"}, {"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"}, {"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"}, {"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}] </code></pre> <p>How can I make jQuery foreach loop and get only values of <code>id</code> and <code>type</code>.</p>
5,743,990
4
0
null
2011-04-21 12:09:39.917 UTC
2
2014-01-24 04:51:56.907 UTC
2014-01-24 04:51:56.907 UTC
null
1,366,033
null
625,870
null
1
6
jquery|json
39,747
<pre><code> var json = '[{"id":"1","pid":"0","type":"Individual","code":"i","status":"1"},{"id":"2","pid":"0","type":"Group","code":"g","status":"1"},{"id":"15","pid":"0","type":"asdasd","code":"asd","status":"1"},{"id":"16","pid":"0","type":"asdas","code":"asd","status":"1"},{"id":"17","pid":"0","type":"my check","code":"mt","status":"1"}]'; $.each($.parseJSON(json), function() { alert(this.id + " " + this.type); }); </code></pre>
6,206,472
What is the best way to write to a file in a parallel thread in Java?
<p>I have a program that performs lots of calculations and reports them to a file frequently. I know that frequent write operations can slow a program down a lot, so to avoid it I'd like to have a second thread dedicated to the writing operations.</p> <p>Right now I'm doing it with this class I wrote (the impatient can skip to the end of the question):</p> <pre><code>public class ParallelWriter implements Runnable { private File file; private BlockingQueue&lt;Item&gt; q; private int indentation; public ParallelWriter( File f ){ file = f; q = new LinkedBlockingQueue&lt;Item&gt;(); indentation = 0; } public ParallelWriter append( CharSequence str ){ try { CharSeqItem item = new CharSeqItem(); item.content = str; item.type = ItemType.CHARSEQ; q.put(item); return this; } catch (InterruptedException ex) { throw new RuntimeException( ex ); } } public ParallelWriter newLine(){ try { Item item = new Item(); item.type = ItemType.NEWLINE; q.put(item); return this; } catch (InterruptedException ex) { throw new RuntimeException( ex ); } } public void setIndent(int indentation) { try{ IndentCommand item = new IndentCommand(); item.type = ItemType.INDENT; item.indent = indentation; q.put(item); } catch (InterruptedException ex) { throw new RuntimeException( ex ); } } public void end(){ try { Item item = new Item(); item.type = ItemType.POISON; q.put(item); } catch (InterruptedException ex) { throw new RuntimeException( ex ); } } public void run() { BufferedWriter out = null; Item item = null; try{ out = new BufferedWriter( new FileWriter( file ) ); while( (item = q.take()).type != ItemType.POISON ){ switch( item.type ){ case NEWLINE: out.newLine(); for( int i = 0; i &lt; indentation; i++ ) out.append(" "); break; case INDENT: indentation = ((IndentCommand)item).indent; break; case CHARSEQ: out.append( ((CharSeqItem)item).content ); } } } catch (InterruptedException ex){ throw new RuntimeException( ex ); } catch (IOException ex) { throw new RuntimeException( ex ); } finally { if( out != null ) try { out.close(); } catch (IOException ex) { throw new RuntimeException( ex ); } } } private enum ItemType { CHARSEQ, NEWLINE, INDENT, POISON; } private static class Item { ItemType type; } private static class CharSeqItem extends Item { CharSequence content; } private static class IndentCommand extends Item { int indent; } } </code></pre> <p>And then I use it by doing:</p> <pre><code>ParallelWriter w = new ParallelWriter( myFile ); new Thread(w).start(); /// Lots of w.append(" things ").newLine(); w.setIndent(2); w.newLine().append(" more things "); /// and finally w.end(); </code></pre> <p>While this works perfectly well, I'm wondering: <strong>Is there a better way to accomplish this?</strong></p>
6,206,773
4
1
null
2011-06-01 19:16:43.33 UTC
12
2021-12-10 16:33:47.323 UTC
2016-03-16 20:20:13.327 UTC
null
573,032
null
771,837
null
1
26
java|multithreading|file
25,616
<p>Your basic approach looks fine. I would structure the code as follows:</p> <pre class="lang-java prettyprint-override"><code> import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; public interface FileWriter { FileWriter append(CharSequence seq); FileWriter indent(int indent); void close(); } class AsyncFileWriter implements FileWriter, Runnable { private final File file; private final Writer out; private final BlockingQueue&lt;Item&gt; queue = new LinkedBlockingQueue&lt;Item&gt;(); private volatile boolean started = false; private volatile boolean stopped = false; public AsyncFileWriter(File file) throws IOException { this.file = file; this.out = new BufferedWriter(new java.io.FileWriter(file)); } public FileWriter append(CharSequence seq) { if (!started) { throw new IllegalStateException(&quot;open() call expected before append()&quot;); } try { queue.put(new CharSeqItem(seq)); } catch (InterruptedException ignored) { } return this; } public FileWriter indent(int indent) { if (!started) { throw new IllegalStateException(&quot;open() call expected before append()&quot;); } try { queue.put(new IndentItem(indent)); } catch (InterruptedException ignored) { } return this; } public void open() { this.started = true; new Thread(this).start(); } public void run() { while (!stopped) { try { Item item = queue.poll(100, TimeUnit.MICROSECONDS); if (item != null) { try { item.write(out); } catch (IOException logme) { } } } catch (InterruptedException e) { } } try { out.close(); } catch (IOException ignore) { } } public void close() { this.stopped = true; } private static interface Item { void write(Writer out) throws IOException; } private static class CharSeqItem implements Item { private final CharSequence sequence; public CharSeqItem(CharSequence sequence) { this.sequence = sequence; } public void write(Writer out) throws IOException { out.append(sequence); } } private static class IndentItem implements Item { private final int indent; public IndentItem(int indent) { this.indent = indent; } public void write(Writer out) throws IOException { for (int i = 0; i &lt; indent; i++) { out.append(&quot; &quot;); } } } } </code></pre> <p>If you do not want to write in a separate thread (maybe in a test?), you can have an implementation of <code>FileWriter</code> which calls <code>append</code> on the <code>Writer</code> in the caller thread.</p>
6,058,904
Removing a Google maps Circle/shape
<p>I am creating a Circle using the google.maps.Circle() method. This all works fine and dandy, but how can I remove said circle?</p> <p>My code:</p> <pre><code>var populationOptionsAgain = { strokeColor: "#c4c4c4", strokeOpacity: 0.35, strokeWeight: 0, fillColor: "#ffffff", fillOpacity: 0.35, map: map, center: results[0].geometry.location, radius: 40000 }; cityCircle = new google.maps.Circle(populationOptionsAgain); </code></pre>
6,058,983
4
0
null
2011-05-19 12:52:47.13 UTC
6
2019-04-23 18:02:10.587 UTC
2011-05-23 13:02:18.763 UTC
null
73,488
null
285,178
null
1
30
javascript|google-maps
49,064
<p>You need to call the <a href="http://code.google.com/apis/maps/documentation/javascript/overlays.html#RemovingOverlays">setMap</a> method on the Circle object to null:</p> <pre><code>cityCircle.setMap(null); </code></pre>
6,071,618
Why is my .data() function returning [ instead of the first value of my array?
<p>I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:</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>var stuff = $('div').data('stuff'); alert(stuff[0]);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div data-stuff="['a','b','c']"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Why does this appear to alert '[' and not 'a' (see JSFiddle link)</p> <p><strong>JSFiddle Link:</strong> <a href="http://jsfiddle.net/ktw4v/3/" rel="nofollow noreferrer">http://jsfiddle.net/ktw4v/3/</a></p>
6,071,653
4
0
null
2011-05-20 12:03:14.23 UTC
12
2022-06-09 19:40:12.623 UTC
2022-06-09 19:40:12.623 UTC
null
2,756,409
null
516,629
null
1
90
javascript|jquery|html|json
95,770
<p>It's treating your variable as a string, the zeroth element of which is <code>[</code>.</p> <p>This is happening because your string is not <a href="http://www.json.org/" rel="noreferrer">valid JSON</a>, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.</p> <p>If you fix your quotation marks your original code works (see <a href="http://jsfiddle.net/ktw4v/12/" rel="noreferrer">http://jsfiddle.net/ktw4v/12/</a>)</p> <pre><code>&lt;div data-stuff='["a","b","c"]'&gt; &lt;/div&gt; var stuff = $('div').data('stuff'); </code></pre> <p>When jQuery sees valid JSON in a data attribute it will <a href="http://api.jquery.com/data#data2" rel="noreferrer">automatically unpack it for you</a>.</p>
52,710,248
Anchor Boxes in YOLO : How are they decided
<p>I have gone through a couple of <code>YOLO</code> tutorials but I am finding it some what hard to figure if the Anchor boxes for each cell the image is to be divided into is predetermined. In one of the guides I went through, The image was divided into <strong>13x13</strong> cells and it stated each cell predicts <strong>5</strong> anchor boxes(bigger than it, ok here's my first problem because it also says it would first detect what object is present in the small cell before the prediction of the boxes).</p> <p>How can the small cell predict anchor boxes for an object bigger than it. Also it's said that each cell classifies before predicting its anchor boxes how can the small cell classify the right object in it without querying neighbouring cells if only a small part of the object falls within the cell </p> <p><code>E.g.</code> say one of the <strong>13</strong> cells contains only the white pocket part of a man wearing a T-shirt how can that cell classify correctly that a man is present without being linked to its neighbouring cells? with a normal CNN when trying to localize a single object I know the bounding box prediction relates to the whole image so at least I can say the network has an idea of what's going on everywhere on the image before deciding where the box should be.</p> <p><strong>PS:</strong> What I currently think of how the YOLO works is basically each cell is assigned predetermined anchor boxes with a classifier at each end before the boxes with the highest scores for each class is then selected but I am sure it doesn't add up somewhere. </p> <blockquote> <p><strong>UPDATE:</strong> Made a mistake with this question, it should have been about how regular bounding boxes were decided rather than anchor/prior boxes. So I am marking <code>@craq</code>'s answer as correct because that's how anchor boxes are decided according to the YOLO v2 paper</p> </blockquote>
57,516,744
2
1
null
2018-10-08 21:18:50.98 UTC
9
2022-06-16 12:44:28.437 UTC
2019-10-29 15:41:35.233 UTC
null
10,138,416
null
10,138,416
null
1
14
deep-learning|artificial-intelligence|object-detection|yolo
13,263
<p>I think there are two questions here. Firstly, the one in the title, asking where the anchors come from. Secondly, how anchors are assigned to objects. I'll try to answer both.</p> <ol> <li>Anchors are determined by <a href="https://github.com/AlexeyAB/darknet/blob/master/scripts/gen_anchors.py" rel="noreferrer">a k-means procedure</a>, looking at all the bounding boxes in your dataset. If you're looking at vehicles, the ones you see from the side will have an aspect ratio of about 2:1 (width = 2*height). The ones viewed from in front will be roughly square, 1:1. If your dataset includes people, the aspect ratio might be 1:3. Foreground objects will be large, background objects will be small. The k-means routine will figure out a selection of anchors that represent your dataset. k=5 for yolov3, but there are different numbers of anchors for each YOLO version.</li> </ol> <p>It's useful to have anchors that represent your dataset, because YOLO learns how to make small adjustments to the anchor boxes in order to create an accurate bounding box for your object. YOLO can learn small adjustments better/easier than large ones.</p> <ol start="2"> <li>The assignment problem is trickier. As I understand it, part of the training process is for YOLO to learn which anchors to use for which object. So the "assignment" isn't deterministic like it might be for the Hungarian algorithm. Because of this, in general, multiple anchors will detect each object, and you need to do non-max-suppression afterwards in order to pick the "best" one (i.e. highest confidence).</li> </ol> <p>There are a couple of points that I needed to understand before I came to grips with anchors:</p> <ul> <li>Anchors can be any size, so they can extend beyond the boundaries of the 13x13 grid cells. They have to be, in order to detect large objects.</li> <li>Anchors only enter in the final layers of YOLO. YOLO's neural network makes 13x13x5=845 predictions (assuming a 13x13 grid and 5 anchors). The predictions are interpreted as offsets to anchors from which to calculate a bounding box. (The predictions also include a confidence/objectness score and a class label.)</li> <li>YOLO's loss function compares each object in the ground truth with one anchor. It picks the anchor (before any offsets) with highest IoU compared to the ground truth. Then the predictions are added as offsets to the anchor. All other anchors are designated as background.</li> <li>If anchors which have been assigned to objects have high IoU, their loss is small. Anchors which have not been assigned to objects should predict background by setting confidence close to zero. The final loss function is a combination from all anchors. Since YOLO tries to minimise its overall loss function, the anchor closest to ground truth gets trained to recognise the object, and the other anchors get trained to ignore it.</li> </ul> <p>The following pages helped my understanding of YOLO's anchors:</p> <p><a href="https://medium.com/@vivek.yadav/part-1-generating-anchor-boxes-for-yolo-like-network-for-vehicle-detection-using-kitti-dataset-b2fe033e5807" rel="noreferrer">https://medium.com/@vivek.yadav/part-1-generating-anchor-boxes-for-yolo-like-network-for-vehicle-detection-using-kitti-dataset-b2fe033e5807</a></p> <p><a href="https://github.com/pjreddie/darknet/issues/568" rel="noreferrer">https://github.com/pjreddie/darknet/issues/568</a></p>
6,089,548
css3 height transition not working
<p>i have a problem using css3 transitions how can i make the transition smooth it appears instantly <br/> i want the div box to slowly change its height when i hover over it</p> <p><br/> the html code</p> <pre><code>&lt;div id="imgs"&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/smile.png" alt=":)" title=":)" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/sad.png" alt=":(" title=":(" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/wink.png" alt=";)" title=";)" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/razz.png" alt=":P" title=":P" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/grin.png" alt=":D" title=":D" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/plain.png" alt=":|" title=":|" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/surprise.png" alt=":O" title=":O" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/confused.png" alt=":?" title=":?" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/glasses.png" alt="8)" title="8)" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/eek.png" alt="8o" title="8o" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/cool.png" alt="B)" title="B)" /&gt; &lt;img src="http://chat.ecobytes.net/img/emoticons/smile-big.png" alt=":-)" title=":-)" /&gt; &lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/9gJsY/" rel="noreferrer">jsfiddle</a></p>
6,089,591
5
2
null
2011-05-22 17:25:11.47 UTC
1
2021-03-30 23:07:38.023 UTC
2012-09-10 01:21:24.247 UTC
null
732,981
null
732,981
null
1
29
html|css|css-transitions
66,629
<p>I believe you need to set a specified height instead of auto. <a href="http://jsfiddle.net/BN4Ny/">http://jsfiddle.net/BN4Ny/</a> this does a smooth expansion. Not sure if you wanted that little close open effect though. I just forked your jsfiddle and added a specified height.</p>
6,135,226
Update a column with a COUNT of other fields is SQL?
<p>I have the following tables set up:</p> <pre><code>Articles: ID | TITLE | CONTENT | USER | NUM_COMMENTS COMMENTS ID | ARTICLE_ID | TEXT </code></pre> <p>I need a sql statement which updates the NUM_Comments field of the articles table with teh count of the comments made against the article like:</p> <pre><code>update articles a, comments f set a.num_comments = COUNT(f.`id`) where f.article_id = a.id </code></pre> <p>The sql above doesn't work and I get an Invalid Use fo Group function error. I'm using MySQL Here.</p>
6,135,269
5
4
null
2011-05-26 07:39:09.34 UTC
2
2020-12-24 22:34:16.263 UTC
2020-12-24 22:34:16.263 UTC
null
1,783,163
null
89,752
null
1
33
mysql|sql|mysql-error-1111
87,144
<p>You can't have a join in an update statement. It should be</p> <pre><code>update articles set num_comments = (select count (*) from comments where comments.article_id = articles.id) </code></pre> <p>This will update the entire articles table, which may not be what you want. If you intend to update only one article then add a 'where' clause after the subquery.</p>
5,923,587
How to get data from each dynamically created EditText in Android?
<p>I have successfully created EditTexts depending on the user input in Android, and also I have assigned them unique ID's using <code>setId()</code> method. </p> <p>Now what I want to do is to get values from the dynamically created <code>EditText</code>s when the user tap a button, then store all of them in String variables. i.e. value from EditText having id '1' should be saved in str1 of type String, and so on depending on the number of EditTexts.</p> <p>I am using <code>getid()</code>, and <code>gettext().toString()</code> methods but it seems a bit tricky... I cannot assign each value of EditText to a String variable. When I try to do that a <code>NullPointerException</code> occurs, and if it is not the case where no user input data is shown, I display it in a toast.</p> <p>Heres, the code:</p> <pre><code>EditText ed; for (int i = 0; i &lt; count; i++) { ed = new EditText(Activity2.this); ed.setBackgroundResource(R.color.blackOpacity); ed.setId(id); ed.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); linear.addView(ed); } </code></pre> <p>How do I now pass the value from each EditText to each different string variable? If some body could help with a sample code it would be nice.</p>
5,923,764
5
0
null
2011-05-07 19:45:14.643 UTC
32
2016-12-06 12:44:54.453 UTC
2014-06-01 20:19:21.44 UTC
null
3,530,081
null
736,597
null
1
41
java|android|string|android-edittext
54,136
<p>In every iteration you are rewriting the <code>ed</code> variable, so when loop is finished <code>ed</code> only points to the last EditText instance you created.</p> <p>You should store all references to all EditTexts:</p> <pre><code>EditText ed; List&lt;EditText&gt; allEds = new ArrayList&lt;EditText&gt;(); for (int i = 0; i &lt; count; i++) { ed = new EditText(Activity2.this); allEds.add(ed); ed.setBackgroundResource(R.color.blackOpacity); ed.setId(id); ed.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); linear.addView(ed); } </code></pre> <p>Now <code>allEds</code> list hold references to all EditTexts, so you can iterate it and get all the data.</p> <p><strong>Update:</strong></p> <p>As per request:</p> <pre><code>String[] strings = new String[](allEds.size()); for(int i=0; i &lt; allEds.size(); i++){ string[i] = allEds.get(i).getText().toString(); } </code></pre>
6,166,795
Eclipse crashes at startup; Exit code=13
<p>I am trying to work with Eclipse Helios on my x64 machine (Im pretty sure now that this problem could occur with any eclipse) but it just doesn't cooperate. <br/>When I try to run eclipse I get the following: <img src="https://i.stack.imgur.com/6ZbDY.jpg" alt="exit code=13"></p> <p>I have installed</p> <ul> <li>Helios EE x64 (latest version)</li> <li>JDK 1.6.025 (x64)</li> </ul> <p>I have linked my Environment Variables up correctly and tried to compile a Java file through <code>cmd</code> and have succeeded. </p> <p>Whenever I tried running eclipse i get <code>exit code=13 (required java version=1.5)</code></p> <p><strong>I tried running the following in cmd:</strong> <code>-vm "mypath\jdk1.6.025\jre\bin"</code> command as forums suggested </p> <p>as well as other paths <code>-vm "mypath\jdk1.6.025\bin"</code> <code>-vm "mypath\jdk1.6.025\jre\bin\javaw.exe"</code> even <code>-vm "mypath\jre6\bin"</code> out of desperation to no avail.</p> <hr> <p>I am all out of ideas and I wonder if anybody had this problem. I even downloaded the helios x86 version and x86 JDK version yet it did not fix the problem. (I changed the environment variables) I changed everything back but I'm stuck...</p> <p><strong>Related Question:</strong> <a href="https://stackoverflow.com/questions/4945178/cannot-run-eclipse-jvm-terminated-exit-code-13">Cannot Run Eclipse</a></p>
6,186,968
6
3
null
2011-05-29 08:53:04.073 UTC
null
2014-12-26 08:37:33.08 UTC
2017-05-23 12:01:11.803 UTC
null
-1
null
774,972
null
1
8
java|eclipse|java-6|exit-code
52,762
<p>It turns out that a directory had an <code>!</code> in its name and eclipse had a problem with that.</p> <p>Once I switched the directory (from Desktop which is located in the user directory which had <code>!</code> in it to C:/ ) everything worked fine. (look at the Djava.class.path in the image located in my the question above for the whole path - it should make it clear what the problem was)</p> <p>Vista allows you to create a username that contains <code>!</code> character and then a lot of programs have issues with it </p> <p><strong>Update</strong></p> <p>If somebody is still getting this problem even though their path is ok I suggest</p> <ul> <li>trying to look at the Environment Variables </li> <li>then try uninstalling the Helios EE ( or any other version of ee you are running ) and JDK and then reinstalling the 86x versions of both (they should still work on the 64x platform).</li> <li>for further explanation look <a href="https://stackoverflow.com/questions/4945178/cannot-run-eclipse-jvm-terminated-exit-code-13">here</a></li> </ul> <p>Thank you everybody that tried to help</p>
6,142,053
Powershell, output xml to screen
<p>I'm learning PowerShell. I can load an xml file into a variable and manipulate it. I can then call the object's save method to save to disk. I expected there to be a way to output the resulting xml to screen, though. I can't seem to find one. Is there a way, other than outputting to file and then file-to-screen?</p>
6,142,095
6
0
null
2011-05-26 16:41:08.827 UTC
8
2022-02-10 12:10:20.32 UTC
null
null
null
null
316,760
null
1
32
xml|powershell
48,045
<p>Look at <a href="https://github.com/Pscx/Pscx" rel="nofollow noreferrer">PSCX module</a>. You will find <code>Format-Xml</code> cmdlet that does exactly that.</p> <p>Example:</p> <pre><code>Import-Module pscx $xml = [xml]'&lt;root&gt;&lt;so&gt;&lt;user name="john"&gt;thats me&lt;/user&gt;&lt;user name="jane"&gt;do you like her?&lt;/user&gt;&lt;/so&gt;&lt;/root&gt;' Format-Xml -InputObject $xml </code></pre> <p>will produce:</p> <pre><code>&lt;root&gt; &lt;so&gt; &lt;user name="john"&gt;thats me&lt;/user&gt; &lt;user name="jane"&gt;do you like her?&lt;/user&gt; &lt;/so&gt; &lt;/root&gt; </code></pre> <p>For more info look at <code>help format-xml -full</code></p>
6,203,231
Which HTTP methods match up to which CRUD methods?
<p>In RESTful style programming, we should use HTTP methods as our building blocks. I'm a little confused though which methods match up to the classic CRUD methods. GET/Read and DELETE/Delete are obvious enough.</p> <p>However, what is the difference between PUT/POST? Do they match one to one with Create and Update?</p>
6,210,103
9
0
null
2011-06-01 14:57:08.997 UTC
93
2022-09-15 14:25:44.417 UTC
null
null
null
null
67,521
null
1
222
http|rest|crud|http-method
134,323
<pre><code>Create = PUT with a new URI POST to a base URI returning a newly created URI Read = GET Update = PUT with an existing URI Delete = DELETE </code></pre> <p>PUT can map to both Create and Update depending on the existence of the URI used with the PUT.</p> <p>POST maps to Create.</p> <p>Correction: POST can also map to Update although it's typically used for Create. POST can also be a partial update so we don't need the proposed PATCH method.</p>
6,208,363
Sharing a URL with a query string on Twitter
<p>I'm trying to put a Twitter share link in an email. Because this is in an email I can't rely on JavaScript, and have to use the &quot;Build Your Own&quot; Tweet button.</p> <p>For example, sharing a link to Google:</p> <pre><code>&lt;a href=&quot;http://www.twitter.com/share?url=http://www.google.com/&gt;Tweet&lt;/a&gt; </code></pre> <p>This works fine. The problem I'm having is when the URL has a query string.</p> <pre><code>&lt;a href=&quot;http://www.twitter.com/share?url=http://mysite.org/foo.htm?bar=123&amp;baz=456&quot;&gt;Tweet&lt;/a&gt; </code></pre> <p>URLs with query strings confuse Twitter's URL shortening service, t.co. I've tried URL encoding this in various ways and cannot get anything to work. The closest I have gotten is by doing this.</p> <pre><code>&lt;a href=&quot;http://www.twitter.com/share?url=http://mysite.org/foo.htm%3Fbar%3D123%26baz%3D456&quot;&gt;Tweet&lt;/a&gt; </code></pre> <p>Here I've encoded only the query string. When I do this, t.co successfully shortens the URL, but upon following the shortened link, it takes you to the encoded URL. I see <code>http://mysite.org/foo.htm%3Fbar%3D123%26baz%3D456</code> in the address bar, and get the following error in the browser</p> <blockquote> <p>Not Found</p> <p>The requested URL /foo.htm?bar=123&amp;baz=456 was not found on this server.</p> </blockquote> <p>I'm at a loss as to how to solve this problem.</p> <p><strong>Edit:</strong> Re: onteria_</p> <p>I've tried encoding the entire URL. When I do that no URL shows up in the Tweet.</p>
6,208,612
13
1
null
2011-06-01 22:13:13.81 UTC
36
2021-02-24 07:00:59.853 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
374,953
null
1
154
twitter|query-string|share|url-encoding
305,284
<p>This can be solved by using <code>https://twitter.com/intent/tweet</code> instead of <code>http://www.twitter.com/share</code>. Using the <code>intent/tweet</code> function, you simply URL encode your entire URL and it works like a charm.</p> <p><a href="https://dev.twitter.com/web/intents">https://dev.twitter.com/web/intents</a></p>
18,115,563
Open Chromecast YouTube video from my Android app
<p>I'm able to use my own whitelisted url for feeding my chromecast videos, but can I make it stream a YouTube video directly from my app?</p> <p>I assume all I would need is to launch the YouTube app remotely and feed it a video ID somehow, but I can't find out how to do that.</p> <p>Has anyone done this from an Android app?</p> <p>Thanks.</p>
19,396,879
2
0
null
2013-08-07 23:36:12.433 UTC
8
2013-10-16 06:48:24.747 UTC
2013-08-07 23:41:11.3 UTC
null
1,205,715
null
1,002,963
null
1
8
android|google-cast|chromecast
5,654
<p>Not sure if you are still looking for a solution for this. The way to do it is as follows:</p> <pre><code>MimeData data = new MimeData("v=g1LsT1PVjUA", MimeData.TYPE_TEXT); mSession.startSession("YouTube", data); </code></pre> <p>The above should create a YouTube session and play the video.</p>
25,385,289
How to set the size of a column in a Bootstrap responsive table
<p>How do you set the size of a column in a Bootstrap responsive table? I don't want the table to loose its reponsive features. I need it to work in IE8 as well. I have included HTML5SHIV and Respond.</p> <p>I'm using Bootstrap 3 (3.2.0)</p> <pre><code>&lt;div class="table-responsive"&gt; &lt;table id="productSizes" class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Size&lt;/th&gt; &lt;th&gt;Bust&lt;/th&gt; &lt;th&gt;Waist&lt;/th&gt; &lt;th&gt;Hips&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;6&lt;/td&gt; &lt;td&gt;79 - 81&lt;/td&gt; &lt;td&gt;61 - 63&lt;/td&gt; &lt;td&gt;89 - 91&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;8&lt;/td&gt; &lt;td&gt;84 - 86&lt;/td&gt; &lt;td&gt;66 - 68&lt;/td&gt; &lt;td&gt;94 - 96&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre>
25,385,798
3
2
null
2014-08-19 13:55:08.983 UTC
26
2021-11-08 13:08:26.117 UTC
2014-08-19 14:03:42.967 UTC
null
225,799
null
225,799
null
1
100
css|html|twitter-bootstrap|twitter-bootstrap-3
307,727
<p><strong>Bootstrap 4.0</strong></p> <p>Be aware of all <a href="https://getbootstrap.com/docs/4.0/migration/" rel="noreferrer">migration</a> changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class <code>d-flex</code>, and drop the <code>xs</code> to allow bootstrap to automatically detect the viewport.</p> <pre><code>&lt;div class="container-fluid"&gt; &lt;table id="productSizes" class="table"&gt; &lt;thead&gt; &lt;tr class="d-flex"&gt; &lt;th class="col-1"&gt;Size&lt;/th&gt; &lt;th class="col-3"&gt;Bust&lt;/th&gt; &lt;th class="col-3"&gt;Waist&lt;/th&gt; &lt;th class="col-5"&gt;Hips&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr class="d-flex"&gt; &lt;td class="col-1"&gt;6&lt;/td&gt; &lt;td class="col-3"&gt;79 - 81&lt;/td&gt; &lt;td class="col-3"&gt;61 - 63&lt;/td&gt; &lt;td class="col-5"&gt;89 - 91&lt;/td&gt; &lt;/tr&gt; &lt;tr class="d-flex"&gt; &lt;td class="col-1"&gt;8&lt;/td&gt; &lt;td class="col-3"&gt;84 - 86&lt;/td&gt; &lt;td class="col-3"&gt;66 - 68&lt;/td&gt; &lt;td class="col-5"&gt;94 - 96&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p></p> <p><a href="https://www.bootply.com/ZYDzwLgu59" rel="noreferrer">bootply</a></p> <p><strong>Bootstrap 3.2</strong></p> <p><a href="https://getbootstrap.com/docs/3.3/css/#tables" rel="noreferrer">Table</a> column width use the same layout as <a href="https://getbootstrap.com/docs/3.3/css/#grid" rel="noreferrer">grids</a> do; using <code>col-[viewport]-[size]</code>. Remember the column sizes should total 12; <code>1 + 3 + 3 + 5 = 12</code> in this example.</p> <pre><code> &lt;thead&gt; &lt;tr&gt; &lt;th class="col-xs-1"&gt;Size&lt;/th&gt; &lt;th class="col-xs-3"&gt;Bust&lt;/th&gt; &lt;th class="col-xs-3"&gt;Waist&lt;/th&gt; &lt;th class="col-xs-5"&gt;Hips&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; </code></pre> <p>Remember to set the <code>&lt;th&gt;</code> elements rather than the <code>&lt;td&gt;</code> elements so it sets the whole column. Here is a working <a href="http://www.bootply.com/qOTyt3bg8g" rel="noreferrer">BOOTPLY</a>.</p> <p>Thanks to @Dan for reminding me to always work mobile view (<code>col-xs-*</code>) first.</p>
24,499,304
Why does Django REST Framework provide different Authentication mechanisms
<p>Why does Django REST Framework implement a different Authentication mechanism than the built-in Django mechanism?</p> <p>To wit, there are two settings classes that one can configure:</p> <ol> <li><code>settings.AUTHENTICATION_BACKENDS</code> which handles the Django-level authentication, and</li> <li><code>settings.REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES']</code> which authenticates at the REST-Framework level</li> </ol> <p>The problem I'm experiencing is that I have a Middleware layer which checks whether a user is logged-in or not.</p> <p>When using a web client which authenticates via sessions, this works fine. However, from mobile or when running the test suite (i.e. authenticating using HTTP headers and tokens), the middleware detects the user as an <code>AnonymousUser</code>, but by the time we get to the REST Framework layer, the HTTP <code>Authorization</code> header is read, and the user is logged-in.</p> <p>Why do these not both happen BEFORE the middleware? Furthermore, why doesn't REST Framework's authentication methods not rely on the Django authentication backend?</p>
24,500,309
2
1
null
2014-06-30 21:34:38.757 UTC
5
2019-10-16 14:39:57.51 UTC
null
null
null
null
358,431
null
1
31
django|authentication|django-rest-framework|restful-authentication
6,392
<p>Django Rest Framework does not perform authentication in middleware by default for the same reason that Django does not perform authentication in middleware by default: middleware applies to ALL views, and is overkill when you only want to authenticate access to a small portion of your views. Also, having the ability to provide different authentication methods for different API endpoints is a very handy feature.</p> <p>Rest Framework's authentication methods do not rely on the Django authentication backend because the Django's backend is optimised for the common case, and is intimitely linked to the user model. Rest Framework aims to make it easy to:</p> <ol> <li>Use many different authentication methods. (You want HMAC based authentication? done! This is not possible with django auth framework)</li> <li>Serve API data without ever needing a database behind it. (You have a redis database with all your data in-memory? Serve it in milliseconds without ever waiting for a round trip to DB user model.) </li> </ol>
21,736,970
Using requests module, how to handle 'set-cookie' in request response?
<p>I'm attempting to open a login page (GET), fetch the cookies provided by the webserver, then submit a username and password pair to log into the site (POST).</p> <p>Looking at <a href="https://stackoverflow.com/questions/6878418/putting-a-cookie-in-a-cookiejar">this Stackoverflow question/answer</a>, I would think that I would just do the following:</p> <pre><code>import requests from http.cookiejar import CookieJar url1 = 'login prompt page' url2 = 'login submission URL' jar = CookieJar() r = requests.get(url1, cookies=jar) r2 = requests.post(url2, cookies=jar, data=&quot;username and password data payload&quot;) </code></pre> <p>However, in <code>r</code> there is a <code>Set-Cookie</code> in the headers, but that isn't changing the <code>jar</code> object. In fact, nothing is being populated into <code>jar</code> as the linked question's response would indicate.</p> <p>I'm getting around this in my code by having a headers dict and after doing the GET or POST, using this to handle the <code>Set-Cookie</code> header:</p> <pre><code>headers['Cookie'] = r.headers['set-cookie'] </code></pre> <p>Then passing around the headers in the requests methods. Is this correct, or is there a better way to apply the <code>Set-Cookie</code>?</p>
21,737,100
3
1
null
2014-02-12 18:50:53.917 UTC
12
2022-04-29 23:35:34.027 UTC
2022-04-29 23:35:34.027 UTC
null
3,064,538
null
1,200,874
null
1
25
python|cookies|python-requests
45,968
<p>Ignore the cookie-jar, let <code>requests</code> handle cookies for you. Use a <a href="https://docs.python-requests.org/en/latest/user/advanced/#session-objects" rel="nofollow noreferrer"><code>Session</code> object</a> instead, it'll persist cookies and send them back to the server:</p> <pre><code>with requests.Session() as s: r = s.get(url1) r = s.post(url2, data=&quot;username and password data payload&quot;) </code></pre>
33,238,518
What could happen if I don't close response.Body?
<p>In Go, I have some http responses and I sometimes forget to call: </p> <pre><code>resp.Body.Close() </code></pre> <p>What happens in this case? will there be a memory leak? Also is it safe to put in <code>defer resp.Body.Close()</code> immediately after getting the response object?</p> <pre><code>client := http.DefaultClient resp, err := client.Do(req) defer resp.Body.Close() if err != nil { return nil, err } </code></pre> <p>What if there is an error, could <code>resp</code> or <code>resp.Body</code> be nil? </p>
33,238,755
5
1
null
2015-10-20 13:49:41.227 UTC
32
2021-05-21 21:27:07.143 UTC
2020-03-30 14:18:35.073 UTC
null
13,860
null
1,259,261
null
1
142
go
77,985
<blockquote> <p>What happens in this case? will there be a memory leak? </p> </blockquote> <p>It's a resource leak. The connection won't be re-used, and can remain open in which case the file descriptor won't be freed.</p> <blockquote> <p>Also is it safe to put in defer resp.Body.Close() immediately after getting the response object?</p> </blockquote> <p>No, follow the example provided in the documentation and close it immediately after checking the error. </p> <pre><code>client := http.DefaultClient resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() </code></pre> <p>From the <code>http.Client</code> documentation:</p> <blockquote> <p>If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. If the Body is not both read to EOF and closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request.</p> </blockquote>
9,534,408
numpy.genfromtxt produces array of what looks like tuples, not a 2D array—why?
<p>I'm running <code>genfromtxt</code> like below:</p> <pre><code>date_conv = lambda x: str(x).replace(":", "/") time_conv = lambda x: str(x) a = np.genfromtxt(input.txt, delimiter=',', skip_header=4, usecols=[0, 1] + radii_indices, converters={0: date_conv, 1: time_conv}) </code></pre> <p>Where <code>input.txt</code> is from <a href="https://gist.github.com/1958483" rel="noreferrer">this gist</a>.</p> <p>When I look at the results, it is a 1D array not a 2D array:</p> <pre><code>&gt;&gt;&gt; np.shape(a) (918,) </code></pre> <p>It seems to be an array of tuples instead:</p> <pre><code>&gt;&gt;&gt; a[0] ('06/03/2006', '08:27:23', 6.4e-05, 0.000336, 0.001168, 0.002716, 0.004274, 0.004658, 0.003756, 0.002697, 0.002257, 0.002566, 0.003522, 0.004471, 0.00492, 0.005602, 0.006956, 0.008442, 0.008784, 0.006976, 0.003917, 0.001494, 0.000379, 6.4e-05) </code></pre> <p>If I remove the converters specification from the <code>genfromtxt</code> call it works fine and produces a 2D array:</p> <pre><code>&gt;&gt;&gt; np.shape(a) (918, 24) </code></pre>
9,534,653
1
0
null
2012-03-02 13:51:08.773 UTC
7
2020-12-15 08:43:11.123 UTC
2012-03-02 14:55:00.913 UTC
null
192,839
null
1,912
null
1
42
python|import|numpy|genfromtxt
21,446
<p>What is returned is called a <strong>structured ndarray</strong>, see e.g. here: <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="noreferrer">http://docs.scipy.org/doc/numpy/user/basics.rec.html</a>. This is because your data is not homogeneous, i.e. not all elements have the same type: the data contains both strings (the first two columns) and floats. Numpy arrays have to be homogeneous (see <a href="http://docs.scipy.org/doc/numpy/user/whatisnumpy.html" rel="noreferrer">here</a> for an explanation).</p> <p>The structured array 'solves' this constraint of homogeneity by using tuples for each record or row, that's the reason the returned array is 1D: one series of tuples, but each tuple (row) consists of several fields, so you can regard it as rows and columns. The different columns are accessible as <code>a['nameofcolumn']</code> e.g. <code>a['Julian_Day']</code>.</p> <p>The reason that it returns a 2D array when removing the converters for the first two columns is that in that case, <code>genfromtxt</code> regards all data of the same type, and a normal ndarray is returned (the default type is float, but you can specify this with the <code>dtype</code> argument). </p> <p><strong>EDIT</strong>: If you want to make use of the column names, you can use the <code>names</code> argument (and set the <code>skip_header</code> at only three):</p> <pre><code>a2 = np.genfromtxt("input.txt", delimiter=',', skip_header=3, names = True, dtype = None, usecols=[0, 1] + radii_indices, converters={0: date_conv, 1: time_conv}) </code></pre> <p>the you can do e.g.:</p> <pre><code>&gt;&gt;&gt; a2['Dateddmmyyyy'] array(['06/03/2006', '06/03/2006', '18/03/2006', '19/03/2006', '19/03/2006', '19/03/2006', '19/03/2006', '19/03/2006', '19/03/2006', '19/03/2006'], dtype='|S10') </code></pre>
34,392,569
Automapper: passing parameter to Map method
<p>I'm using <a href="https://automapper.org/" rel="noreferrer">Automapper</a> in a project and I need to dynamically valorize a field of my destination object.</p> <p>In my configuration I have something similar:</p> <pre><code>cfg.CreateMap&lt;Message, MessageDto&gt;() // ... .ForMember(dest =&gt; dest.Timestamp, opt =&gt; opt.MapFrom(src =&gt; src.SentTime.AddMinutes(someValue))) //... ; </code></pre> <p>The <code>someValue</code> in the configuration code is a parameter that I need to pass at runtime to the mapper and is not a field of the source object.</p> <p>Is there a way to achieve this? Something like this:</p> <pre><code>Mapper.Map&lt;MessageDto&gt;(msg, someValue)); </code></pre>
34,419,562
4
2
null
2015-12-21 09:35:14.177 UTC
11
2022-01-16 11:38:05.677 UTC
2018-05-02 10:07:31.15 UTC
null
1,061,499
null
1,061,499
null
1
60
c#|.net|automapper-3
73,003
<p>You can't do exactly what you want, but you can get pretty close by specifying mapping options when you call Map. Ignore the property in your config:</p> <pre><code>cfg.CreateMap&lt;Message, MessageDto&gt;() .ForMember(dest =&gt; dest.Timestamp, opt =&gt; opt.Ignore()); </code></pre> <p>Then pass in options when you call your map:</p> <pre><code>int someValue = 5; var dto = Mapper.Map&lt;Message, MessageDto&gt;(message, opt =&gt; opt.AfterMap((src, dest) =&gt; dest.TimeStamp = src.SendTime.AddMinutes(someValue))); </code></pre> <p>Note that you need to use the <code>Mapper.Map&lt;TSrc, TDest&gt;</code> overload to use this syntax.</p>
10,614,754
What is "naive" in a naive Bayes classifier?
<p>What is naive about Naive Bayes?</p>
10,614,801
5
1
null
2012-05-16 08:32:04.77 UTC
11
2021-02-19 04:28:54.197 UTC
2019-04-10 21:01:56.807 UTC
null
570,918
null
1,198,226
null
1
37
algorithm|classification|naivebayes
24,370
<p>There's actually a very good example <a href="http://en.wikipedia.org/wiki/Naive_Bayes" rel="noreferrer">on Wikipedia</a>:</p> <blockquote> <p>In simple terms, a naive Bayes classifier assumes that the presence (or absence) of a particular feature of a class is unrelated to the presence (or absence) of any other feature, given the class variable. For example, a fruit may be considered to be an apple if it is red, round, and about 4" in diameter. Even if these features depend on each other or upon the existence of the other features, a naive Bayes classifier considers all of these properties to independently contribute to the probability that this fruit is an apple.</p> </blockquote> <p>Basically, it's "naive" because it makes assumptions that may or may not turn out to be correct.</p>
7,585,699
List of useful environment settings in Java
<p>I've been wondering a long time if there was a comprehensive list of (probably static) methods/fields that store runtime information for the JVM. An incomplete list of examples:</p> <ul> <li>System.out / System.in</li> <li>System.currentTimeMillis()</li> <li>System.getProperty()</li> <li>System.getConsole()</li> <li>Runtime.freeMemory()</li> <li>Etc</li> </ul> <p>Does anyone have a link or something?</p> <p>EDIT: I'm not so dumb as to have not checked the docs for System and Runtime :P I was just wondering if there were other classes where similar methods to determine the state of the machine you're running on are stored.</p>
7,616,206
2
3
null
2011-09-28 15:34:32.73 UTC
14
2018-06-29 02:42:20.343 UTC
2017-03-01 20:30:07.537 UTC
null
15,168
null
948,176
null
1
28
java|static|runtime|environment
4,946
<h2>General Properties</h2> <p>I use this code to get a handle on some of the things known to Java classes that are of particular interest to me.</p> <p><img src="https://i.stack.imgur.com/ahk3I.png" alt="System Properties"></p> <pre><code>import java.awt.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.util.*; import java.security.*; /** A small GUId app. that shows many system and environment properties. Designed to be compatible with Java 1.4+ (hence many requirements like no foreach, no generics, no StringBuilder..). @author Andrew Thompson @version 2008-06-29 */ class SystemProperties { static String sentence = "The quick brown fox jumped over the lazy dog."; static String sep = System.getProperty("line.separator"); static String fontText = sentence + sep + sentence.toUpperCase() + sep + "0123456789 !@#$%^&amp;*()_+ []\\;',./ {}|:\"&lt;&gt;?"; static String[] convertObjectToSortedStringArray(Object[] unsorted) { String[] sorted = new String[unsorted.length]; for (int ii = 0; ii &lt; sorted.length; ii++) { sorted[ii] = (String) unsorted[ii]; } Arrays.sort(sorted); return sorted; } static String dataPairToTableRow(String property, Object value) { String val = valueToString(property, value); return "&lt;tr&gt;" + "&lt;th&gt;" + "&lt;code&gt;" + property + "&lt;/code&gt;" + "&lt;/th&gt;" + "&lt;td&gt;" + val + "&lt;/td&gt;" + "&lt;/tr&gt;"; } static String valueToString(String property, Object value) { if (value instanceof Color) { Color color = (Color) value; String converted = "&lt;div style='width: 100%; height: 100%; " + "background-color: #" + Integer.toHexString(color.getRed()) + Integer.toHexString(color.getGreen()) + Integer.toHexString(color.getBlue()) + ";'&gt;" + value.toString() + "&lt;/div&gt;"; return converted; } else if (property.toLowerCase().endsWith("path") || property.toLowerCase().endsWith("dirs")) { return delimitedToHtmlList( (String) value, System.getProperty("path.separator")); } else { return value.toString(); } } static String delimitedToHtmlList(String values, String delimiter) { String[] parts = values.split(delimiter); StringBuffer sb = new StringBuffer(); sb.append("&lt;ol&gt;"); for (int ii = 0; ii &lt; parts.length; ii++) { sb.append("&lt;li&gt;"); sb.append(parts[ii]); sb.append("&lt;/li&gt;"); } return sb.toString(); } static Component getExampleOfFont(String fontFamily) { Font font = new Font(fontFamily, Font.PLAIN, 24); JTextArea ta = new JTextArea(); ta.setFont(font); ta.setText(fontText); ta.setEditable(false); // don't allow these to get focus, as it // interferes with desired scroll behavior ta.setFocusable(false); return ta; } static public JScrollPane getOutputWidgetForContent(String content) { JEditorPane op = new JEditorPane(); op.setContentType("text/html"); op.setEditable(false); op.setText(content); return new JScrollPane(op); } public static void main(String[] args) { JTabbedPane tabPane = new JTabbedPane(); StringBuffer sb; String header = "&lt;html&gt;&lt;body&gt;&lt;table border=1 width=100%&gt;"; sb = new StringBuffer(header); Properties prop = System.getProperties(); String[] propStrings = convertObjectToSortedStringArray( prop.stringPropertyNames().toArray()); for (int ii = 0; ii &lt; propStrings.length; ii++) { sb.append( dataPairToTableRow( propStrings[ii], System.getProperty(propStrings[ii]))); } tabPane.addTab( "System", getOutputWidgetForContent(sb.toString())); sb = new StringBuffer(header); Map environment = System.getenv(); String[] envStrings = convertObjectToSortedStringArray( environment.keySet().toArray()); for (int ii = 0; ii &lt; envStrings.length; ii++) { sb.append( dataPairToTableRow( envStrings[ii], environment.get(envStrings[ii]))); } tabPane.addTab( "Environment", getOutputWidgetForContent(sb.toString())); sb = new StringBuffer(header); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for (int j = 0; j &lt; gs.length; j++) { GraphicsDevice gd = gs[j]; sb.append( dataPairToTableRow( "Device " + j, gd.toString() + " " + gd.getIDstring())); GraphicsConfiguration[] gc = gd.getConfigurations(); for (int i = 0; i &lt; gc.length; i++) { sb.append( dataPairToTableRow( "Config " + i, (int) gc[i].getBounds().getWidth() + "x" + (int) gc[i].getBounds().getHeight() + " " + gc[i].getColorModel() + ", " + " Accelerated: " + gc[i].getImageCapabilities().isAccelerated() + " True Volatile: " + gc[i].getImageCapabilities().isTrueVolatile())); } } tabPane.addTab( "Graphics Environment", getOutputWidgetForContent(sb.toString())); String[] fonts = ge.getAvailableFontFamilyNames(); JPanel fontTable = new JPanel(new BorderLayout(3, 1)); // to enable key based scrolling in the font panel fontTable.setFocusable(true); JPanel fontNameCol = new JPanel(new GridLayout(0, 1, 2, 2)); JPanel fontExampleCol = new JPanel(new GridLayout(0, 1, 2, 2)); fontTable.add(fontNameCol, BorderLayout.WEST); fontTable.add(fontExampleCol, BorderLayout.CENTER); for (int ii = 0; ii &lt; fonts.length; ii++) { fontNameCol.add(new JLabel(fonts[ii])); fontExampleCol.add(getExampleOfFont(fonts[ii])); } tabPane.add("Fonts", new JScrollPane(fontTable)); sb = new StringBuffer(header); sb.append("&lt;thead&gt;"); sb.append("&lt;tr&gt;"); sb.append("&lt;th&gt;"); sb.append("Code"); sb.append("&lt;/th&gt;"); sb.append("&lt;th&gt;"); sb.append("Language"); sb.append("&lt;/th&gt;"); sb.append("&lt;th&gt;"); sb.append("Country"); sb.append("&lt;/th&gt;"); sb.append("&lt;th&gt;"); sb.append("Variant"); sb.append("&lt;/th&gt;"); sb.append("&lt;/tr&gt;"); sb.append("&lt;/thead&gt;"); Locale[] locales = Locale.getAvailableLocales(); SortableLocale[] sortableLocale = new SortableLocale[locales.length]; for (int ii = 0; ii &lt; locales.length; ii++) { sortableLocale[ii] = new SortableLocale(locales[ii]); } Arrays.sort(sortableLocale); for (int ii = 0; ii &lt; locales.length; ii++) { String prefix = ""; String suffix = ""; Locale locale = sortableLocale[ii].getLocale(); if (locale.equals(Locale.getDefault())) { prefix = "&lt;b&gt;"; suffix = "&lt;/b&gt;"; } sb.append(dataPairToTableRow( prefix + locale.toString() + suffix, prefix + locale.getDisplayLanguage() + suffix + "&lt;/td&gt;&lt;td&gt;" + prefix + locale.getDisplayCountry() + suffix + "&lt;/td&gt;&lt;td&gt;" + prefix + locale.getDisplayVariant() + suffix)); } tabPane.add("Locales", getOutputWidgetForContent(sb.toString())); Locale.getDefault(); int border = 5; JPanel p = new JPanel(new BorderLayout()); p.setBorder(new EmptyBorder(border, border, border, border)); p.add(tabPane, BorderLayout.CENTER); p.setPreferredSize(new Dimension(400, 400)); JFrame f = new JFrame("Properties"); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.getContentPane().add(p, BorderLayout.CENTER); f.pack(); f.setMinimumSize(f.getPreferredSize()); f.setSize(600, 500); f.setLocationRelativeTo(null); f.setVisible(true); } } class SortableLocale implements Comparable { Locale locale; SortableLocale(Locale locale) { this.locale = locale; } public String toString() { return locale.toString(); } public Locale getLocale() { return locale; } public int compareTo(Object object2) { SortableLocale locale2 = (SortableLocale) object2; //Locale locale2 = (Locale)object2; return locale.toString().compareTo( locale2.toString()); } } </code></pre> <h2>Media</h2> <p>Properties related to synthesized and sampled sound, and images.</p> <p><img src="https://i.stack.imgur.com/MLtWo.png" alt="Media Types"></p> <pre><code>/* &lt;applet code='MediaTypes' width='900' height='600'&gt; &lt;param name='show' value='Sound|Sampled|Mixers|Primary Sound Capture Driver'&gt; &lt;/applet&gt; */ import javax.imageio.ImageIO; import javax.sound.sampled.*; import javax.sound.midi.*; import java.awt.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.tree.*; import javax.swing.event.*; import javax.swing.text.Position; public class MediaTypes extends JApplet { JTable table; boolean sortable = false; JTree tree; @Override public void init() { Runnable r = () -&gt; { MediaTypes mediaTypes = new MediaTypes(); String show = ""; if (getParameter("show")!=null) { show = getParameter("show"); } JPanel p = new JPanel(); mediaTypes.createGui(p, show); add(p); validate(); }; SwingUtilities.invokeLater(r); } public static void main(String[] args) { Runnable r = () -&gt; { MediaTypes mediaTypes = new MediaTypes(); JPanel p = new JPanel(); mediaTypes.createGui(p); JOptionPane.showMessageDialog(null,p); }; SwingUtilities.invokeLater(r); } public Object[][] mergeArrays(String name1, Object[] data1, String name2, Object[] data2) { Object[][] data = new Object[data1.length+data2.length][2]; for (int ii=0; ii&lt;data1.length; ii++) { data[ii][0] = name1; data[ii][1] = data1[ii]; } int offset = data1.length; for (int ii=offset; ii&lt;data.length; ii++) { data[ii][0] = name2; data[ii][1] = data2[ii-offset]; } return data; } public void createGui(JPanel panel) { createGui(panel, ""); } public String getShortLineName(String name) { String[] lineTypes = { "Clip", "SourceDataLine", "TargetDataLine", "Speaker", "Microphone", "Master Volume", "Line In" }; for (String shortName : lineTypes) { if ( name.toLowerCase().replaceAll("_", " ").contains(shortName.toLowerCase() )) { return shortName; } } return name; } public void createGui(JPanel panel, String path) { //DefaultMutableTreeNode selected = null; panel.setLayout( new BorderLayout(5,5) ); final JLabel output = new JLabel("Select a tree leaf to see the details."); panel.add(output, BorderLayout.SOUTH); table = new JTable(); try { table.setAutoCreateRowSorter(true); sortable = true; } catch (Throwable ignore) { // 1.6+ functionality - not vital } JScrollPane tableScroll = new JScrollPane(table); Dimension d = tableScroll.getPreferredSize(); d = new Dimension(450,d.height); tableScroll.setPreferredSize(d); panel.add( tableScroll, BorderLayout.CENTER ); DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Media"); DefaultTreeModel treeModel = new DefaultTreeModel(rootNode); DefaultMutableTreeNode imageNode = new DefaultMutableTreeNode("Image"); rootNode.add(imageNode); Object[][] data; int offset; String[] columnNames; data = mergeArrays( "Reader", ImageIO.getReaderFileSuffixes(), "Writer", ImageIO.getWriterFileSuffixes() ); columnNames = new String[]{"Input/Output", "Image File Suffixes"}; MediaData md = new MediaData( "Suffixes", columnNames, data); imageNode.add(new DefaultMutableTreeNode(md)); data = mergeArrays( "Reader", ImageIO.getReaderMIMETypes(), "Writer", ImageIO.getWriterMIMETypes() ); columnNames = new String[]{"Input/Output", "Image MIME Types"}; md = new MediaData( "MIME", columnNames, data); imageNode.add(new DefaultMutableTreeNode(md)); DefaultMutableTreeNode soundNode = new DefaultMutableTreeNode("Sound"); rootNode.add(soundNode); DefaultMutableTreeNode soundSampledNode = new DefaultMutableTreeNode("Sampled"); soundNode.add(soundSampledNode); md = new MediaData("Suffixes", "Sound File Suffixes", AudioSystem.getAudioFileTypes()); soundSampledNode.add(new DefaultMutableTreeNode(md)); Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); String[][] mixerData = new String[mixerInfo.length][4]; for (int ii=0; ii&lt;mixerData.length; ii++) { mixerData[ii][0] = mixerInfo[ii].getName(); mixerData[ii][1] = mixerInfo[ii].getVendor(); mixerData[ii][2] = mixerInfo[ii].getVersion(); mixerData[ii][3] = mixerInfo[ii].getDescription(); } columnNames = new String[]{"Name", "Vendor", "Version", "Description"}; md = new MediaData("Mixers", columnNames, mixerData); DefaultMutableTreeNode soundSampledMixersNode = new DefaultMutableTreeNode(md); soundSampledNode.add(soundSampledMixersNode); for (Mixer.Info mixerInfo1 : mixerInfo) { Mixer mixer = AudioSystem.getMixer(mixerInfo1); data = mergeArrays( "Source", mixer.getSourceLineInfo(), "Target", mixer.getTargetLineInfo() ); columnNames = new String[]{ "Input/Output", "Line Info" }; md = new MediaData(mixerInfo1.getName(), columnNames, data); DefaultMutableTreeNode soundSampledMixerNode = new DefaultMutableTreeNode(md); soundSampledMixersNode.add( soundSampledMixerNode ); Line.Info[] source = mixer.getSourceLineInfo(); Line.Info[] target = mixer.getTargetLineInfo(); Line[] all = new Line[source.length + target.length]; try { for (int jj=0; jj&lt;source.length; jj++) { all[jj] = AudioSystem.getLine(source[jj]); } for (int jj=source.length; jj&lt;all.length; jj++) { all[jj] = AudioSystem.getLine(target[jj-source.length]); } columnNames = new String[]{"Attribute", "Value"}; for (Line line : all) { Control[] controls = line.getControls(); if (line instanceof DataLine) { DataLine dataLine = (DataLine)line; AudioFormat audioFormat = dataLine.getFormat(); data = new Object[7+controls.length][2]; data[0][0] = "Channels"; data[0][1] = audioFormat.getChannels(); data[1][0] = "Encoding"; data[1][1] = audioFormat.getEncoding(); data[2][0] = "Frame Rate"; data[2][1] = audioFormat.getFrameRate(); data[3][0] = "Sample Rate"; data[3][1] = audioFormat.getSampleRate(); data[4][0] = "Sample Size (bits)"; data[4][1] = audioFormat.getSampleSizeInBits(); data[5][0] = "Big Endian"; data[5][1] = audioFormat.isBigEndian(); data[6][0] = "Level"; data[6][1] = dataLine.getLevel(); } else if (line instanceof Port) { Port port = (Port)line; Port.Info portInfo = (Port.Info)port.getLineInfo(); data = new Object[2+controls.length][2]; data[0][0] = "Name"; data[0][1] = portInfo.getName(); data[1][0] = "Source"; data[1][1] = portInfo.isSource(); } else { System.out.println( "?? " + line ); } int start = data.length-controls.length; for (int kk=start; kk&lt;data.length; kk++) { data[kk][0] = "Control"; int index = kk-start; data[kk][1] = controls[index]; } md = new MediaData(getShortLineName(line.getLineInfo().toString()), columnNames, data); soundSampledMixerNode.add(new DefaultMutableTreeNode(md)); } } catch(Exception e) { e.printStackTrace(); } } int[] midiTypes = MidiSystem.getMidiFileTypes(); data = new Object[midiTypes.length][2]; for (int ii=0; ii&lt;midiTypes.length; ii++) { data[ii][0] = midiTypes[ii]; String description = "Unknown"; switch (midiTypes[ii]) { case 0: description = "Single Track"; break; case 1: description = "Multi Track"; break; case 2: description = "Multi Song"; } data[ii][1] = description; } columnNames = new String[]{"Type", "Description"}; md = new MediaData("MIDI", columnNames, data); DefaultMutableTreeNode soundMIDINode = new DefaultMutableTreeNode(md); soundNode.add(soundMIDINode); columnNames = new String[]{ "Attribute", "Value"}; MidiDevice.Info[] midiDeviceInfo = MidiSystem.getMidiDeviceInfo() ; for (MidiDevice.Info midiDeviceInfo1 : midiDeviceInfo) { data = new Object[6][2]; data[0][0] = "Name"; data[0][1] = midiDeviceInfo1.getName(); data[1][0] = "Vendor"; data[1][1] = midiDeviceInfo1.getVendor(); data[2][0] = "Version"; String version = midiDeviceInfo1.getVersion(); data[2][1] = version.replaceAll("Version ", ""); data[3][0] = "Description"; data[3][1] = midiDeviceInfo1.getDescription(); data[4][0] = "Maximum Transmitters"; data[5][0] = "Maximum Receivers"; try { MidiDevice midiDevice = MidiSystem.getMidiDevice(midiDeviceInfo1); Object valueTransmitter; if (midiDevice.getMaxTransmitters()==AudioSystem.NOT_SPECIFIED) { valueTransmitter = "Not specified"; } else { valueTransmitter = midiDevice.getMaxTransmitters(); } Object valueReceiver; if (midiDevice.getMaxReceivers()==AudioSystem.NOT_SPECIFIED) { valueReceiver = "Not specified"; } else { valueReceiver = midiDevice.getMaxReceivers(); } data[4][1] = valueTransmitter; data[5][1] = valueReceiver; }catch(MidiUnavailableException mue) { data[4][1] = "Unknown"; data[5][1] = "Unknown"; } md = new MediaData(midiDeviceInfo1.getName(), columnNames, data); soundMIDINode.add( new DefaultMutableTreeNode(md) ); } tree = new JTree(treeModel); tree.setRootVisible(false); tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener((TreeSelectionEvent tse) -&gt; { if (sortable) { output.setText("Click table column headers to sort."); } DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); if (nodeInfo instanceof MediaData) { MediaData mediaData = (MediaData)nodeInfo; table.setModel( new DefaultTableModel( mediaData.getData(), mediaData.getColumnNames()) ); } }); for (int ii=0; ii&lt;tree.getRowCount(); ii++) { tree.expandRow(ii); } String[] paths = path.split("\\|"); int row = 0; TreePath treePath = null; for (String prefix : paths) { treePath = tree.getNextMatch( prefix, row, Position.Bias.Forward ); row = tree.getRowForPath(treePath); } panel.add(new JScrollPane(tree),BorderLayout.WEST); tree.setSelectionPath(treePath); tree.scrollRowToVisible(row); } } class MediaData { String name; String[] columnNames; Object[][] data; MediaData(String name, String columnName, Object[] data) { this.name = name; columnNames = new String[1]; columnNames[0] = columnName; this.data = new Object[data.length][1]; for (int ii=0; ii&lt;data.length; ii++) { this.data[ii][0] = data[ii]; } } MediaData(String name, String[] columnNames, Object[][] data) { this.name = name; this.columnNames = columnNames; this.data = data; } @Override public String toString() { return name; } public String[] getColumnNames() { return columnNames; } public Object[][] getData() { return data; } } </code></pre> <h2>Other</h2> <p>You might also investigate:</p> <ul> <li><code>InetAddress</code></li> <li><code>KeyStore</code></li> <li>Managers <ul> <li><code>CookieManager</code></li> <li><code>KeyManagerFactory</code></li> <li><code>LogManager</code></li> </ul></li> </ul>
31,729,240
How to analyzing Page Speed in Chrome Dev tools
<p>I'm trying to get my head around the Network Tab in Chrome Dev tools to understand how long the page is taking to load and the difference between DomContentLoaded, Load and Finished at the bottom of the Network Tab.</p> <p><a href="https://i.stack.imgur.com/CYj6h.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/CYj6h.jpg" alt="enter image description here"></a></p> <p>From the users perspective when is the page ready for reading, viewing, interacting with etc? Is it DomContentLoaded, Load or Finished? </p> <p>Also what about from an SEO perspective what event is Google using to measure page speed? </p> <p><strong>DOMContent loaded</strong></p> <p>As I understand it DOMContent loaded means the WebPages <strong>HTML document</strong> has been downloaded and parsed by the browser but assets such as images, css &amp; javascript may still have to be downloaded, is this correct?</p> <p>From the user visiting the webpage is it ready at this time?</p> <p>Does <a href="https://developers.google.com/speed/docs/insights/BlockingJS" rel="noreferrer">render-blocking JavaScript and CSS</a> delay this event?</p> <p>In the Chrome network tab above why is DOMContentLoaded 1.97s at the bottom in blue text yet the blue line in the timeline is just before the 3 second mark?</p> <p><strong>Load Event</strong> </p> <p>I imagine this event is fired once everything is finished downloading and has been fully rendered, what colour line is this represented by as again the red line is at the 2s mark but at the bottom of the Network tab it says Network 2.95s in Red!?</p> <p>Is this a good point to consider the page is ready to view for the user. If you look at <a href="http://www.amazon.co.uk/" rel="noreferrer">amazon.co.uk</a> this isn't till about 14 seconds and the <strong>Finished time</strong> goes all the way up to 3.5 min which I suppose are Ajax requests. Which makes me think neither of these events really represent when the Page is ready for the user to view. <a href="https://i.stack.imgur.com/XQdbY.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/XQdbY.jpg" alt="enter image description here"></a></p>
39,886,182
1
1
null
2015-07-30 16:27:16.603 UTC
10
2016-10-06 01:38:48.757 UTC
null
null
null
null
1,814,446
null
1
24
performance|google-chrome|optimization
11,964
<h1>What's happening in the browser after you press enter?</h1> <ul> <li>the browser downloads the file</li> <li>the browser parses the file</li> <li>the browser calculates javascript events and rendering operations</li> </ul> <h1>From a technical point of view:</h1> <h2>DomContentLoaded:</h2> <p>The <code>DomContentLoaded</code> event is fired when the initial HTML document has been completely downloaded and parsed.</p> <h3>Please consider that:</h3> <p>if you have a <code>&lt;script src="test.js"&gt;&lt;/script&gt;</code>:<br> 1. Browser download and parse index.html and test.js<br> 2. Browser parse and evaluate script<br> 3. Browser will fire a <code>DomContentLoaded</code> </p> <p>if you have a <code>&lt;script src="test.js" async&gt;&lt;/script&gt;</code>:<br> 1. Browser download and parse index.html<br> 2. Browser will fire a <code>DomContentLoaded</code><br> and in the mean while is download the js </p> <h2>Load:</h2> <p>The <code>Load</code> event is fired when on fully load page, so when HTML and the BLOCKING resources are downloaded and parsed.</p> <p>The BLOCKING resources are CSS and Javascript. The NOT BLOCKING is async javascript. </p> <h2>Finished:</h2> <p>The <code>Finished</code> event is fired when HTML + BLOCKING + NON BLOCKING resources are downloaded | parsed and all the <code>XMLHttpRequest()</code> and <code>Promise</code> are completed.</p> <p>In case you have a loop that is checking for updates you'll keep seeing updating this value.</p> <h1>From the javascript perspective:</h1> <p>The only two events you care about are <code>DOMContentLoaded</code> and <code>Load</code> because it's when the browser will run your js.</p> <h2>consider this:</h2> <blockquote> <p>DOMContentLoaded == window.onDomReady()<br> Load == window.onLoad()</p> </blockquote> <h1>From a user perspective:</h1> <p>So, as a user when I feel the page fast? What's the secret?</p> <p>Well, to answer this question you have to open the <code>Timeline</code> panel. On the capture line select: <code>Network</code>, <code>Screenshot</code> and <code>Paint</code>. (Those are not really mandatory, but they help to understand).</p> <p>Refresh the page.</p> <p>You will see 3 vertical lines: </p> <ul> <li>1 blue line: DomContentLoaded event </li> <li>1 red line: Load event </li> <li>1 green line: First Paint </li> </ul> <h2>Now, What's the First Paint? What does it mean?</h2> <p>It means that Chrome it starts to render something to the user. If you check the screenshots, you'll be able to see when the user has a minimal version of the page to interact with. </p> <p>From a UX perspective, it's important the user start to see something (even the page rendering) as soon as possible. <em>Google has 300ms (Finish 800ms)</em>, <em>Amazon is around 1.6s (Finish 41s)</em></p> <h1>For the SEO:</h1> <p>For the SEO no worries. It's much easier. Use the <a href="https://developers.google.com/speed/pagespeed/insights/" rel="noreferrer">PageSpeed Insights</a> and follow the suggestions.</p> <h1>References:</h1> <ul> <li><a href="https://stackoverflow.com/questions/2414750/difference-between-domcontentloaded-and-load-events">DOMContentLoaded vs Load</a></li> <li><a href="http://www.nateberkopec.com/2015/10/07/frontend-performance-chrome-timeline.html" rel="noreferrer">Ludicrously Fast Page Loads</a></li> </ul>
17,978,637
Finding Contiguous Areas of Bits in 2D Bit Array
<h2>The Problem</h2> <p>I have a bit array which represents a 2-dimensional "map" of "tiles". This image provides a graphical example of the bits in the bit array: </p> <p><img src="https://i.stack.imgur.com/tDBi7.gif" alt="Bit Array Example"></p> <p>I need to determine how many contiguous "areas" of bits exist in the array. In the example above, there are two such contiguous "areas", as illustrated here: </p> <p><img src="https://i.stack.imgur.com/MDWY1.gif" alt="Contiguous Areas"></p> <p>Tiles must be located directly N, S, E or W of a tile to be considered "contiguous". Diagonally-touching tiles do not count.</p> <h2>What I've Got So Far</h2> <p>Because these bit arrays can become relatively large (several MB in size), I have intentionally avoided using any sort of recursion in my algorithm. </p> <p>The pseudo-code is as follows:</p> <pre><code>LET S BE SOURCE DATA ARRAY LET C BE ARRAY OF IDENTICAL LENGTH TO SOURCE DATA USED TO TRACK "CHECKED" BITS FOREACH INDEX I IN S IF C[I] THEN CONTINUE ELSE SET C[I] IF S[I] THEN EXTRACT_AREA(S, C, I) EXTRACT_AREA(S, C, I): LET T BE TARGET DATA ARRAY FOR STORING BITS OF THE AREA WE'RE EXTRACTING LET F BE STACK OF TILES TO SEARCH NEXT PUSH I UNTO F SET T[I] WHILE F IS NOT EMPTY LET X = POP FROM F IF C[X] THEN CONTINUE ELSE SET C[X] IF S[X] THEN PUSH TILE NORTH OF X TO F PUSH TILE SOUTH OF X TO F PUSH TILE WEST OF X TO F PUSH TILE EAST OF X TO F SET T[X] RETURN T </code></pre> <p><img src="https://i.stack.imgur.com/KraOB.gif" alt="Animation of My Algorithm"></p> <h2>What I Don't Like About My Solution</h2> <ul> <li>Just to run, it requires two times the memory of the bitmap array it's processing.</li> <li>While extracting an "area", it uses three times the memory of the bitmap array.</li> <li>Duplicates exist in the "tiles to check" stack - which seems ugly, but not worth avoiding the way I have things now.</li> </ul> <h2>What I'd Like To See</h2> <ul> <li>Better memory profile</li> <li>Faster handling of large areas</li> </ul> <hr> <h2>Solution / Follow-Up</h2> <p>I re-wrote the solution to explore the edges only (per @hatchet 's suggestion). </p> <p>This was very simple to implement - and eliminated the need to keep track of "visited tiles" completely. </p> <p>Based on three simple rules, I can traverse the edges, track min/max x &amp; y values, and complete when I've arrived at the start again. </p> <p>Here's the demo with the three rules I used:</p> <p><img src="https://i.stack.imgur.com/4i1WI.gif" alt="Solution"></p>
17,979,564
2
10
null
2013-07-31 18:58:05.09 UTC
12
2015-04-30 14:22:17.603 UTC
2013-08-05 18:54:57.497 UTC
null
355,583
null
355,583
null
1
33
algorithm|graph-algorithm
8,242
<p>One approach would be a perimeter walk. Given a starting point anywhere along the edge of the shape, remember that point.</p> <p>Start the bounding box as just that point.</p> <p>Walk the perimeter using a clockwise rule set - if the point used to get to the current point was above, then first look right, then down, then left to find the next point on the shape perimeter. This is kind of like the simple strategy of solving a maze where you continuously follow a wall and always bear to the right.</p> <p>Each time you visit a new perimeter point, expand the bounding box if the new point is outside it (i.e. keep track of the min and max x and y.</p> <p>Continue until the starting point is reached.</p> <p>Cons: if the shape has lots of single pixel 'filaments', you'll be revisiting them as the walk comes back.</p> <p>Pros: if the shape has large expanses of internal occupied space, you never have to visit them or record them like you would if you were recording visited pixels in a flood fill.</p> <p>So, conserves space, but in some cases at the expense of time.</p> <p><strong>Edit</strong></p> <p>As is so often the case, this problem is known, named, and has multiple algorithmic solutions. The problem you described is called Minimum Bounding Rectangle. One way to solve this is using <a href="http://www.imageprocessingplace.com/downloads_V3/root_downloads/tutorials/contour_tracing_Abeer_George_Ghuneim/alg.html" rel="noreferrer">Contour Tracing</a>. The method I described above is in that class, and is called <a href="http://www.imageprocessingplace.com/downloads_V3/root_downloads/tutorials/contour_tracing_Abeer_George_Ghuneim/moore.html" rel="noreferrer">Moore-Neighbor Tracing</a> or <a href="http://www.imageprocessingplace.com/downloads_V3/root_downloads/tutorials/contour_tracing_Abeer_George_Ghuneim/ray.html" rel="noreferrer">Radial Sweep</a>. The links I've included for them discuss them in detail and point out a problem I hadn't caught. Sometimes you'll revisit the start point <em>before</em> you have traversed the entire perimeter. If your start point is for instance somewhere along a single pixel 'filament', you will revisit it before you're done, and unless you consider this possibility, you'll stop prematurely. The website I linked to talks about ways to address this stopping problem. Other pages at that website also talk about two other algorithms: Square Tracing, and Theo Pavlidis's Algorithm. One thing to note is that these consider diagonals as contiguous, whereas you don't, but that should just something that can be handled with minor modifications to the basic algorithms.</p> <p>An alternative approach to your problem is <a href="http://en.wikipedia.org/wiki/Connected-component_labeling" rel="noreferrer">Connected-component labeling</a>. For your needs though, this may be a more time expensive solution than you require.</p> <p>Additional resource:</p> <p><a href="http://www.thebigblob.com/moore-neighbor-contour-tracing-algorithm-in-c/" rel="noreferrer">Moore Neighbor Contour Tracing Algorithm in C++</a></p>
21,395,011
Python module with access to english dictionaries including definitions of words
<p>I am looking for a python module that helps me get the definition(s) from an english dictionary for a word.</p> <p>There is of course <code>enchant</code>, which helps me check if the word exists in the English language, but it does not provide definitions of them (at least I don't see anything like that in the docs)</p> <p>There is also WordNet, which is accessible with NLTK. It has definitions and even sample sentences, but WordNet does not contain all English words. Common words like "how", "I", "You", "should", "could"... are not part of WordNet.</p> <p>Is there any python module that gives access to a full english dictionary including definitions of words?</p>
21,790,940
5
3
null
2014-01-28 01:07:22.41 UTC
16
2018-03-31 21:07:16.223 UTC
null
null
null
null
2,013,672
null
1
21
python|dictionary|module|nlp|nltk
33,283
<p><a href="http://developer.wordnik.com/" rel="noreferrer" title="Wordnik">Wordnik</a> seems to have quite a nice API, and a <a href="https://github.com/wordnik/wordnik-python" rel="noreferrer">nice-looking Python module</a> too. It has definitions, example sentences, etc. so you should be covered. It does also have common words like "how", "should", and "could."</p>
28,151,325
How is "as" operator translated when the right-side operand is generic?
<p>I have just posted an <a href="https://stackoverflow.com/a/28150199/3010968">answer</a> to <a href="https://stackoverflow.com/q/28149927/3010968">this question</a> but I'm not entirely convinced of my answer.There are two things I'm wondering, consider this code:</p> <pre><code>class Foo&lt;T&gt; { void SomeMethod() { string str = "foo"; Foo&lt;T&gt; f = str as Foo&lt;T&gt;; } } </code></pre> <p>According to <code>C# Specification 5.0</code>, there are two different kinds of conversion of <code>as operator</code>. </p> <blockquote> <p>If the compile-time type of <code>E</code> is not <code>dynamic</code>, the operation <code>E as T</code> produces the same result as</p> <pre><code>E is T ? (T)(E) : (T)null </code></pre> <p>If the compile-time type of <code>E</code> is <code>dynamic</code>, unlike the cast operator the <code>as operator</code> is not dynamically bound (§7.2.2). Therefore the expansion in this case is:</p> <pre><code>E is T ? (T)(object)(E) : (T)null </code></pre> </blockquote> <p>Since, this is invalid because of <code>(Foo&lt;T&gt;)str</code></p> <pre><code>str is Foo&lt;T&gt; ? (Foo&lt;T&gt;)str : (Foo&lt;T&gt;)null; </code></pre> <p>I thought it should be translated as:</p> <pre><code>str is Foo&lt;T&gt; ? (Foo&lt;T&gt;)(object)str : (Foo&lt;T&gt;)null; </code></pre> <p>But the spec says this only happens when the type of <code>E</code> is <code>dynamic</code>.</p> <p>So my questions are:</p> <ol> <li>Is the compiler translating this expression to a code that is normally invalid?</li> <li>When the type of <code>E</code> is dynamic why first it casts <code>E</code> to <code>object</code> then <code>T</code> while the <code>(T)E</code> is completely valid?</li> </ol>
28,155,221
1
1
null
2015-01-26 13:49:03.797 UTC
8
2016-09-03 11:35:19.49 UTC
2017-05-23 10:29:11.683 UTC
null
-1
null
3,010,968
null
1
17
c#|.net|dynamic|casting|as-operator
292
<blockquote> <p>Is the compiler translating this expression to a code that is normally invalid?</p> </blockquote> <p>After staring at the spec for about an hour, I'm starting to convince myself that this is simply an edge-case which was <em>overlooked</em> in the specification. Note that this is merely a way for the C# language composers to express the <code>as</code> operator with the semantics of the <code>is</code> operator.</p> <p>The compiler <em>doesn't actually</em> convert the <code>as</code> operator to a ternary operator with an <code>is</code>. It will emit an IL call to <code>isinst</code>, both for <code>as</code> and <code>is</code>:</p> <pre><code>IL_0000: nop IL_0001: ldstr "foo" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: isinst class ConsoleApplication2.Foo`1&lt;!T&gt; IL_000d: stloc.1 IL_000e: ret </code></pre> <p>Looking at the compiled DLL, the <code>as</code> operator remains untouched.</p> <blockquote> <p>When the type of E is dynamic why first it casts E to object then T while the (T)E is completely valid?</p> </blockquote> <p>This is described in the fine-print of the specification:</p> <blockquote> <p>If the compile-time type of E is dynamic, <strong>unlike the cast operator the as operator is not dynamically bound</strong> (§7.2.2). Therefore the expansion in this case is:</p> </blockquote> <pre><code>E is T ? (T)(object)(E) : (T)null </code></pre> <p>The cast to <code>object</code> is needed to make the use of <code>as</code> possible with <code>dynamic</code> objects. <code>as</code> is a <em>compile-time</em> operation while <code>dynamic</code> objects are bound only at <em>run-time</em>. </p> <p>The compiler actually treats <code>dynamic</code> type objects as type <code>object</code> to begin with:</p> <pre><code>class Foo&lt;T&gt; { public void SomeMethod() { dynamic str = "foo"; Foo&lt;T&gt; f = str as Foo&lt;T&gt;; } } </code></pre> <p><code>str</code> is actually treated as <code>object</code> to begin with:</p> <pre><code>.class private auto ansi beforefieldinit Foo`1&lt;T&gt; extends [mscorlib]System.Object { // Methods .method public hidebysig instance void SomeMethod () cil managed { // Method begins at RVA 0x2050 // Code size 15 (0xf) .maxstack 1 .locals init ( [0] object, [1] class Foo`1&lt;!T&gt; ) IL_0000: nop IL_0001: ldstr "foo" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: isinst class Foo`1&lt;!T&gt; IL_000d: stloc.1 IL_000e: ret } // end of method Foo`1::SomeMethod } </code></pre> <h2>Edit:</h2> <p>After talking to Vladimir Reshetnikov from the Managed Languages Team, he explains what the semantic of the representation from the "as operator" to "cast operator" actually tries to convay:</p> <blockquote> <p>I agree, there is some imprecise language in the spec too. It says 'as' operator is always applicable if an open type involved, but then describes its evaluation in terms of casts, that might be not valid in some cases. It <em>should say</em> that casts in the expansion <strong>do not represent normal C# cast operator but just represent conversions that are permitted in 'as' operators.</strong> I'll take a note to fix it. Thanks!</p> </blockquote>
28,335,803
isSame() function in moment.js or Date Validation
<p>I need to validate the date from the user and check if it is in a particular format. If yes, then it will be accepted else it will not be. I am looking for sort of </p> <pre><code>value.match("regular expression") </code></pre> <p>The above works fine if, I have to choose from few formats. So, I came across this moment.js and interested in knowing how to use isSame(). I tried implementing it but unsuccessful. Like :</p> <pre><code>var x=moment("MM/DD/YYYY") ; x.isSame("28-02-1999"); // am getting false which is right var x=moment("28-02-1999","DD-MM-YYYY") ; x.isSame("28-02-1999"); // am getting false which is wrong </code></pre> <p>So, please help in that. Thanks</p>
28,346,741
1
1
null
2015-02-05 03:40:44.453 UTC
9
2020-02-07 18:32:08.777 UTC
null
null
null
null
3,050,590
null
1
58
javascript|validation|date|momentjs
108,118
<h2><a href="http://momentjs.com/docs/#/query/is-same/">Docs - Is Same</a></h2> <blockquote> <p>Check if a moment is the same as another moment.</p> <p><code>moment('2010-10-20').isSame('2010-10-20'); // true</code> </p> <p>If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter. </p> <p><code>moment('2010-10-20').isSame('2009-12-31', 'year'); // false</code><br> <code>moment('2010-10-20').isSame('2010-01-01', 'year'); // true</code><br> <code>moment('2010-10-20').isSame('2010-12-31', 'year'); // true</code><br> <code>moment('2010-10-20').isSame('2011-01-01', 'year'); // false</code> </p> </blockquote> <p>Your code</p> <pre><code>var x=moment("28-02-1999","DD-MM-YYYY"); // working x.isSame("28-02-1999"); // comparing x to an unrecognizable string </code></pre> <p>If you try <code>moment("28-02-1999")</code>, you get an invalid date. So comparing x to an invalid date string returns false.</p> <p>To fix it, either use the <a href="http://momentjs.com/docs/#/parsing/string/">default date format</a> (ISO 8601):</p> <pre><code>var x = moment("28-02-1999","DD-MM-YYYY"); x.isSame("1999-02-28"); // YYYY-MM-DD </code></pre> <p>Or pass <code>isSame</code> a moment object.</p> <pre><code>var x = moment("28-02-1999","DD-MM-YYYY"); x.isSame( moment("28-02-1999","DD-MM-YYYY") ); </code></pre>
1,960,758
Print list items
<pre><code>List&lt;string&gt; list = new List&lt;string&gt;(); list.Add("A"); list.Add("B"); List&lt;string&gt; list1 = new List&lt;string&gt;(); list.Add("a"); list.Add("b"); for (int i = 0; i &lt; list.Count; i++) { // print another list items. for (int j = 0; j &lt; list1.Count; j++) { Console.WriteLine("/" + list[i] + "/" + list1[j]); } } </code></pre> <p>I want to code like this <code>string tmpS =+ list[i];</code> to Join the next list item togeter.</p> <p>then print <code>tmpS</code></p> <p>but compile error CS0023: Operator '+' cannot be applied to operand of type 'string'.</p> <p>How to print all the items below.(any sort is ok)</p> <p><b> A Aa Ab Aab Aba AB ABa ABb ABab ABba B Ba Bb Bab Bba </b></p> <p>(The Caps number No swap. the small characters should be swaped. and always follow Caps Numbers Append small characters.)</p>
1,961,372
3
2
null
2009-12-25 08:09:28.293 UTC
1
2015-01-08 07:32:48.19 UTC
2015-01-08 07:32:48.19 UTC
null
67,579
null
215,912
null
1
8
c#|data-structures
98,268
<p>it makes a long time I did not worked on a pure algorithmic problem!</p> <p>This program should do the trick:</p> <pre><code>class Program { static void Main(string[] args) { List&lt;string&gt; uppers = new List&lt;string&gt;(); uppers.Add("A"); uppers.Add("B"); List&lt;string&gt; lowers = new List&lt;string&gt;(); lowers.Add("a"); lowers.Add("b"); List&lt;string&gt; combinedUppers = GetCombinedItems(uppers); List&lt;string&gt; combinedLowers = GetCombinedItems(lowers); List&lt;string&gt; combinedUppersLowers = GetCombinedList(combinedUppers, combinedLowers); foreach (string combo in combinedUppersLowers) { Console.WriteLine(combo); } Console.Read(); } static private List&lt;string&gt; GetCombinedItems(List&lt;string&gt; list) { List&lt;string&gt; combinedItems = new List&lt;string&gt;(); for (int i = 0; i &lt; list.Count; i++) { combinedItems.Add(list[i]); for (int j = 0; j &lt; list.Count; j++) { if (list[i] != list[j]) { combinedItems.Add(String.Format("{0}{1}", list[i], list[j])); } } } return combinedItems; } static private List&lt;string&gt; GetCombinedList(List&lt;string&gt; list1, List&lt;string&gt; list2) { List&lt;string&gt; combinedList = new List&lt;string&gt;(); for (int i = 0; i &lt; list1.Count; i++) { combinedList.Add(list1[i]); for (int j = 0; j &lt; list2.Count; j++) { combinedList.Add(String.Format("{0}{1}", list1[i], list2[j])); } } for (int i = 0; i &lt; list2.Count; i++) { combinedList.Add(list2[i]); for (int j = 0; j &lt; list1.Count; j++) { combinedList.Add(String.Format("{0}{1}", list2[i], list1[j])); } } return combinedList; } } </code></pre> <p>Regards.</p> <hr> <p>This program gives you this output:</p> <blockquote> <p>A Aa Aab Ab Aba AB ABa ABab ABb ABba B Ba Bab Bb Bba BA BAa BAab BAb BAba a aA aAB aB aBA ab abA abAB abB abBA b bA bAB bB bBA ba baA baAB baB baBA</p> </blockquote>
1,912,023
Caret in objective C
<p>What does the caret in objective C mean?</p> <p>ie.</p> <p><code>void (^handler)(NSInteger);</code></p> <p>from <a href="http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/IB_UserGuide/QuickStart/QuickStart.html#//apple_ref/doc/uid/TP40005344-CH22-SW5" rel="noreferrer">Mac Dev Center</a></p>
1,912,357
3
2
null
2009-12-16 03:13:35.82 UTC
5
2020-09-08 18:14:55.687 UTC
2009-12-16 16:25:56.067 UTC
null
404
null
165,495
null
1
40
objective-c|syntax
17,556
<p>It depends on the context. In the example you show, it's used to denote a Block. The caret symbol is also the <a href="http://en.wikipedia.org/wiki/Bitwise_operation#XOR" rel="nofollow noreferrer">bitwise XOR operator</a> in C-based languages — that's what most programmers would identify it as, so it's good to understand that it can be both depending on where it appears, much like <code>*</code>, etc.</p> <p>And while we're suggesting references, one simply has to include <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Blocks/" rel="nofollow noreferrer">Apple's official Blocks reference</a>.</p>
8,658,789
Using Spring cache annotation in multiple modules
<p>I have a util module that produces a jar to be used in other applications. I'd like this module to use caching and would prefer to use Spring's <code>annotation-driven</code> caching.</p> <p>So <code>Util-Module</code> would have something like this:</p> <hr> <p><strong>DataManager.java</strong></p> <pre class="lang-java prettyprint-override"><code>... @Cacheable(cacheName="getDataCache") public DataObject getData(String key) { ... } ... </code></pre> <p><strong>data-manager-ehcache.xml</strong></p> <pre class="lang-xml prettyprint-override"><code>... &lt;cache name="getDataCache" maxElementsInMemory="100" eternal="true" /&gt; ... </code></pre> <p><strong>data-manager-spring-config.xml</strong></p> <pre class="lang-xml prettyprint-override"><code>... &lt;cache:annotation-driven cache-manager="data-manager-cacheManager" /&gt; &lt;!-- ???? ---&gt; &lt;bean id="data-manager-cacheManager" class="org.springframework.cache.ehcache.EhcacheCacheManager" p:cache-manager="data-manager-ehcache"/&gt; &lt;bean id="data-manager-ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="data-manager-ehcache.xml"/&gt; ... </code></pre> <hr> <p>I would also like my deployable unit to have caching via Spring annotation, while including the above jar as a dependency. So my <code>Deployable-Unit</code> would have something like this:</p> <hr> <p><strong>MyApp.java</strong></p> <pre class="lang-java prettyprint-override"><code>... @Cacheable(cacheName="getMyAppObjectCache") public MyAppObject getMyAppObject(String key) { ... } ... </code></pre> <p><strong>my-app-ehcache.xml</strong></p> <pre class="lang-xml prettyprint-override"><code>... &lt;cache name="getMyAppObjectCache" maxElementsInMemory="100" eternal="true" /&gt; ... </code></pre> <p><strong>my-app-spring-config.xml</strong></p> <pre class="lang-xml prettyprint-override"><code>... &lt;cache:annotation-driven cache-manager="my-app-cacheManager" /&gt; &lt;!-- ???? ---&gt; &lt;bean id="my-app-cacheManager" class="org.springframework.cache.ehcache.EhcacheCacheManager" p:cache-manager="my-app-ehcache"/&gt; &lt;bean id="my-app-ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="my-app-ehcache.xml"/&gt; ... </code></pre> <hr> <h2>Question:</h2> <p>Is it possible to use annotation driven caching in both your main project and a dependency module while keeping the configurations separated?</p> <p>If not, an explanation of why it isn't would be appreciated. If so, an explanation of what needs to change in the above configuration would be appreciated. </p>
9,126,558
5
1
null
2011-12-28 16:50:37.547 UTC
12
2016-07-18 11:19:57.277 UTC
2011-12-28 18:26:10.85 UTC
null
301,832
null
378,151
null
1
31
spring|caching|annotations|ehcache|spring-annotations
18,230
<p>this seems to be fixed in 3.2M1, see <a href="https://jira.springsource.org/browse/SPR-8696" rel="noreferrer">https://jira.springsource.org/browse/SPR-8696</a></p>
8,953,274
Message "unknown type name 'uint8_t'" in MinGW
<p>I get &quot;unknown type name 'uint8_t'&quot; and others like it using C in MinGW.</p> <p>How can I solve this?</p>
8,953,288
4
1
null
2012-01-21 13:20:29.503 UTC
6
2021-04-26 13:57:02.473 UTC
2021-04-26 13:14:10.603 UTC
null
63,550
null
1,925,248
null
1
84
c|windows|mingw
258,786
<p>Try including <code>stdint.h</code> or <code>inttypes.h</code>.</p>
8,729,410
PHP - Get key name of array value
<p>I have an array as the following:</p> <pre><code>function example() { /* some stuff here that pushes items with dynamically created key strings into an array */ return array( // now lets pretend it returns the created array 'firstStringName' =&gt; $whatEver, 'secondStringName' =&gt; $somethingElse ); } $arr = example(); // now I know that $arr contains $arr['firstStringName']; </code></pre> <p>I need to find out the index of <code>$arr['firstStringName']</code> so that I am able to loop through <code>array_keys($arr)</code> and return the key string <code>'firstStringName'</code> by its index. How can I do that?</p>
8,729,491
9
1
null
2012-01-04 15:32:53.727 UTC
39
2019-07-20 08:46:12.72 UTC
2012-05-05 00:07:27.05 UTC
null
11,343
null
890,144
null
1
208
php|arrays|array-key
520,908
<p>If you have a value and want to find the key, use <a href="http://php.net/manual/en/function.array-search.php" rel="noreferrer"><code>array_search()</code></a> like this:</p> <pre><code>$arr = array ('first' =&gt; 'a', 'second' =&gt; 'b', ); $key = array_search ('a', $arr); </code></pre> <p><code>$key</code> will now contain the key for value <code>'a'</code> (that is, <code>'first'</code>).</p>
8,930,915
Append a dictionary to a dictionary
<p>I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example:</p> <pre><code>orig = { 'A': 1, 'B': 2, 'C': 3, } extra = { 'D': 4, 'E': 5, } dest = # Something here involving orig and extra print dest { 'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5 } </code></pre> <p>I think this all can be achieved through a <code>for</code> loop (maybe?), but is there some method of dictionaries or any other module that saves this job for me? The actual dictionaries I'm using are really big...</p>
8,930,969
7
1
null
2012-01-19 17:55:48.903 UTC
61
2021-01-25 20:02:50.187 UTC
2020-02-24 15:27:42.177 UTC
null
63,550
null
264,632
null
1
506
python|dictionary
828,180
<p>You can do</p> <pre><code>orig.update(extra) </code></pre> <p>or, if you don't want <code>orig</code> to be modified, make a copy first:</p> <pre><code>dest = dict(orig) # or orig.copy() dest.update(extra) </code></pre> <p>Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,</p> <pre><code>&gt;&gt;&gt; d1 = {1: 1, 2: 2} &gt;&gt;&gt; d2 = {2: 'ha!', 3: 3} &gt;&gt;&gt; d1.update(d2) &gt;&gt;&gt; d1 {1: 1, 2: 'ha!', 3: 3} </code></pre>
741,054
Mapping between stl C++ and C# containers
<p>Can someone point out a good mapping between the usual C++ STL containers such as vector, list, map, set, multimap... and the C# generic containers?</p> <p>I'm used to the former ones and somehow I've accustomed myself to express algorithms in terms of those containers. I'm having some hard time finding the C# equivalent to those.</p> <p>Thank you!</p>
741,085
4
2
null
2009-04-12 00:29:04.897 UTC
9
2016-09-29 14:10:51.237 UTC
null
null
null
null
79,536
null
1
15
c#|c++|stl|containers
12,364
<p>Here's a <strong>rough</strong> equivalence:</p> <ol> <li><code>Dictionary&lt;K,V&gt;</code> &lt;=> <code>unordered_map&lt;K,V&gt;</code></li> <li><code>HashSet&lt;T&gt;</code> &lt;=> <code>unordered_set&lt;T&gt;</code></li> <li><code>List&lt;T&gt;</code> &lt;=> <code>vector&lt;T&gt;</code></li> <li><code>LinkedList&lt;T&gt;</code> &lt;=> <code>list&lt;T&gt;</code></li> </ol> <p>The .NET BCL (base class library) does not have red-black trees (stl map) or priority queues (make_heap(), push_heap(), pop_heap()).</p> <p>.NET collections don't use "iterators" the way C++ does. They all implement <code>IEnumerable&lt;T&gt;</code>, and can be iterated over using the "<code>foreach</code> statement". If you want to manually control iteration you can call "<code>GetEnumerator()</code>" on the collection which will return an <code>IEnumerator&lt;T&gt;</code> objet. <code>IEnumerator&lt;T&gt;.MoveNext()</code> is roughly equivalent to "++" on a C++ iterator, and "Current" is roughly equivalent to the pointer-deference operator ("*"). </p> <p>C# does have a language feature called "iterators". They are not the same as "iterator objects" in the STL, however. Instead, they are a language feature that allows for automatic implementation of <code>IEnumerable&lt;T&gt;</code>. See documentation for the <code>yield return</code> and <code>yield break</code> statements for more information.</p>
41,090,302
How to style ng-content
<p>Am following this tutorial on transclusion <a href="https://scotch.io/tutorials/angular-2-transclusion-using-ng-content" rel="noreferrer">https://scotch.io/tutorials/angular-2-transclusion-using-ng-content</a></p> <p>However there is no mention on how to style elements that end up replacing ng-content. </p> <p>It seems that I can only target those element in the css if preceeded by the <code>/deep/</code> keyword, which is normally used when targeting a nested component. Is this correct? </p>
41,090,797
4
0
null
2016-12-11 19:37:36.553 UTC
6
2020-07-30 13:40:14.813 UTC
2019-05-09 12:09:47.897 UTC
null
5,736,236
null
1,275,105
null
1
45
angular|angular-template
50,463
<p><strong>update</strong></p> <p><code>::slotted</code> is now supported by all new browsers and can be used with <code>ViewEncapsulation.ShadowDom</code></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted</a></p> <p><strong>original</strong></p> <p><code>::content xxx { ... }</code> might work as well or <code>:host xxx { ... }</code>. The shimming is not very strict or accurate. AFAIK (<code>&gt;&gt;&gt;</code> <code>/deep/</code> old) <code>::ng-deep</code> (supported by SASS) and a space do currently the same.</p>
42,441,543
Npm package.json inheritance
<p>Is there a mechanism in npm like parent pom in Maven. The goal is to have a common base configuration for scripts, dependencies, devDependencies. Not based on templates like yeoman or so, but based on a parent version. So that, any project that changes his parent version gets the changes in this parent automatically.</p> <p>Can you point me to hints to achieve this?</p> <p>Thanks!</p>
42,448,980
4
0
null
2017-02-24 14:47:53.243 UTC
4
2022-07-11 14:04:33.113 UTC
null
null
null
null
533,644
null
1
33
maven|npm|package
22,325
<p>Currently there is no built-in npm mechanism to achieve this, and there's not likely to be one in the future.</p> <p>See the discussion <a href="https://github.com/npm/npm/issues/8112" rel="noreferrer">here</a> and this <a href="https://github.com/npm/npm/issues/8112#issuecomment-192489694" rel="noreferrer">comment</a> particularly.</p>
41,403,458
How do I send HTML Formatted emails, through the gmail-api for python
<p>Using the sample code from the <a href="https://developers.google.com/gmail/api/v1/reference/users/messages/send" rel="noreferrer">GMail API Example: Send Mail</a>, and after following rules for authentication, it's simple enough to send a programmatically generated email, via a gmail account. What isn't obvious from the example is how to set that email to be HTML formatted.</p> <hr> <h2>The Question</h2> <p><strong>How do I get HTML formatting in my gmail-api send messages, using python?</strong></p> <h3>I have this...</h3> <p><code>message_body = "Hello!\nYou've just received a test message!\n\nSincerely,\n-Test Message Generator\n"</code></p> <h3>and I want it to be this...</h3> <pre><code>Hello! You've just received a test message! Sincerely, -Test Message Generator </code></pre> <hr> <h2>Example Source Code from GMail-API</h2> <p>Below is a slightly modified version of the example, but still works:</p> <pre><code>import argparse import base64 from pprint import pformat from pprint import pprint import httplib2 import os from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage SCOPES = 'https://mail.google.com/' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Test EMail App' def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def create_message(sender, to, cc, subject, message_text): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: An object containing a base64url encoded email object. """ print(sender + ', ' + to + ', ' + subject + ', ' + message_text) message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject message['cc'] = cc pprint(message) return {'raw': base64.urlsafe_b64encode(message.as_string())} def send_message(service, user_id, message_in): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Sent Message. """ pprint(message_in) try: message = (service.users().messages().send(userId=user_id, body=message_in).execute()) pprint(message) print ('Message Id: %s' % message['id']) return message except errors.HttpError, error: print ('An error occurred: %s' % error) def main(cli): """Shows basic usage of the Gmail API. Creates a Gmail API service object and outputs a list of label names of the user's Gmail account. """ credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) email_msg = create_message(cli.addr_from, cli.addr_to, cli.addr_cc, cli.subject, cli.message) msg_out = service.users().messages().send(userId = 'me', body = email_msg).execute() pprint(msg_out) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-m', '--message', help = 'The message to send in the email', default='&lt;MESSAGE = unfinished&gt;') parser.add_argument('-t', '--addr_to', help = 'the list of comma separated emails to send', default='[email protected]') parser.add_argument('-s', '--subject', help = 'the email subject', default='&lt;SUBJECT = undefined&gt;') parser.add_argument('-c', '--addr_cc', help = 'email CC\'s', default='') parser.add_argument('-f', '--addr_from', help = 'Email address to send from', default='[email protected]') cli = parser.parse_args() pprint(dir(cli)) main(cli) </code></pre> <p>Tried as I might, with this code, and variations on it, I could not get html formatted code, nor could I get simple escape characters to create carriage returns where they needed to be.</p> <hr> <h2>Here's what didn't work</h2> <p>Trying the following didn't work either:</p> <ol> <li>modifying <code>line 69</code> to add additional message dictionary parameters... ie. <ul> <li><code>{'raw': base64.urlsafe_b64encode(message.as_string()), 'payload': {'mimeType': 'text/html'}}</code></li> <li>As documented here in the <a href="https://developers.google.com/gmail/api/v1/reference/users/messages" rel="noreferrer">GMail API Docs</a></li> <li><a href="https://i.stack.imgur.com/zhI0l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zhI0l.png" alt="enter image description here"></a></li> </ul></li> <li>Adding a variety of escaped backslashes into the message text: <ul> <li><code>\n</code>... ie: <code>\\n</code> nor <code>\\\n</code> and just rendered as those exact characters</li> <li>Adding <code>&lt;br&gt; &lt;/br&gt; &lt;br/&gt;</code> did not add new lines and just rendered as those exact characters</li> <li>Adding <code>\r</code> did not add new lines and just rendered as that exact character</li> </ul></li> </ol> <hr> <h2>Reasons this is not a duplicate question</h2> <ul> <li><a href="https://stackoverflow.com/questions/26841905/sending-email-multipart-signed-rfc-3156-via-gmail-apis">This SO link deals with multipart/signed messages</a> <ul> <li>I am uninterested in multipart messaging because it is an inelegant solution. I want the WHOLE message to be <code>HTML</code>. </li> <li>Additionally, this link has no accepted answer, and the one answer present is a non-answer as it simply states that they are sending a problem statement to Google.</li> </ul></li> <li>This one deals with c#, which I am not interested in since I'm writing in python <ul> <li><a href="https://stackoverflow.com/questions/8628683/how-to-send-html-formatted-email">This one also uses SMTP which I'm not interested in</a></li> </ul></li> <li><a href="https://stackoverflow.com/questions/5188605/gmail-displays-plain-text-email-instead-html?noredirect=1&amp;lq=1">This one is for Rails</a></li> </ul>
41,403,459
3
0
null
2016-12-30 22:27:06.87 UTC
9
2022-08-24 23:52:39.58 UTC
2017-05-23 12:25:57.563 UTC
null
-1
null
4,901,647
null
1
46
python|html|gmail|gmail-api|mime-message
18,028
<p>After doing a lot of digging around, I started looking in to the python side of the message handling, and noticed that a python object is actually constructing the message to be sent for base64 encoding into the gmail-api message object constructor.</p> <blockquote> <p>See line 63 from above: <code>message = MIMEText(message_text)</code></p> </blockquote> <p><strong>The one trick that finally worked for me</strong>, after all the attempts to modify the header values and payload dict (which is a member of the <code>message</code> object), was to set (<code>line 63</code>):</p> <ul> <li><code>message = MIMEText(message_text, 'html')</code> &lt;-- add the <code>'html'</code> as the second parameter of the MIMEText object constructor</li> </ul> <hr> <p><strong>The default code supplied by Google</strong> for their gmail API only tells you how to send plain text emails, but they hide how they're doing that. ala... <code>message = MIMEText(message_text)</code></p> <p>I had to look up the python class <a href="https://docs.python.org/2/library/email.mime.html#email.mime.text.MIMEText" rel="noreferrer"><code>email.mime.text.MIMEText</code></a> object. That's where you'll see this definition of the constructor for the MIMEText object:</p> <ul> <li>class email.mime.text.MIMEText(_text[, _subtype[, _charset]]) We want to explicitly pass it a value to the <code>_subtype</code>. In this case, we want to pass: <code>'html'</code> as the <code>_subtype</code>.</li> </ul> <hr> <p><strong>Now, you won't have anymore unexpected word wrapping</strong> applied to your messages by Google, or the Python <code>mime.text.MIMEText</code> object</p> <hr> <h1>The Fixed Code</h1> <pre class="lang-py prettyprint-override"><code>def create_message(sender, to, cc, subject, message_text): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: An object containing a base64url encoded email object. """ print(sender + ', ' + to + ', ' + subject + ', ' + message_text) message = MIMEText(message_text,'html') message['to'] = to message['from'] = sender message['subject'] = subject message['cc'] = cc pprint(message) return {'raw': base64.urlsafe_b64encode(message.as_string())} </code></pre>
48,235,040
Run X application in a Docker container reliably on a server connected via SSH without "--net host"
<p>Without a Docker container, it is straightforward to run an X11 program on a remote server using the SSH X11 forwarding (<strong>ssh -X</strong>). I have tried to get the same thing working when the application runs inside a Docker container on a server. When SSH-ing into a server with the -X option, an X11 tunnel is set up and the environment variable "$DISPLAY" is automatically set to typically "localhost:10.0" or similar. If I simply try to run an X application in a Docker, I get this error:</p> <pre><code>Error: GDK_BACKEND does not match available displays </code></pre> <p>My first idea was to actually pass the $DISPLAY into the container with the "-e" option like this:</p> <pre><code>docker run -ti -e DISPLAY=$DISPLAY name_of_docker_image </code></pre> <p>This helps, but it does not solve the issue. The error message changes to:</p> <pre><code>Unable to init server: Broadway display type not supported: localhost:10.0 Error: cannot open display: localhost:10.0 </code></pre> <p>After searching the web, I figured out that I could do some <strong>xauth</strong> magic to fix the authentication. I added the following:</p> <pre><code>SOCK=/tmp/.X11-unix XAUTH=/tmp/.docker.xauth xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge - chmod 777 $XAUTH docker run -ti -e DISPLAY=$DISPLAY -v $XSOCK:$XSOCK -v $XAUTH:$XAUTH \ -e XAUTHORITY=$XAUTH name_of_docker_image </code></pre> <p>However, this only works if also add "<strong>--net host</strong>" to the docker command:</p> <pre><code>docker run -ti -e DISPLAY=$DISPLAY -v $XSOCK:$XSOCK -v $XAUTH:$XAUTH \ -e XAUTHORITY=$XAUTH --net host name_of_docker_image </code></pre> <p>This is not desirable since it makes the whole host network visible for the container.</p> <p>What is now missing in order to get it fully to run on a remote server in a docker without "--net host"?</p>
48,235,281
4
0
null
2018-01-12 22:43:33.557 UTC
21
2022-05-04 07:27:15.82 UTC
2018-01-17 12:08:38.613 UTC
null
5,744,809
null
5,744,809
null
1
41
docker|ssh|x11|x11-forwarding
23,296
<p>I figured it out. When you are connecting to a computer with SSH and using X11 forwarding, <strong>/tmp/.X11-unix</strong> is not used for the X communication and the part related to $XSOCK is unnecessary.</p> <p>Any X application rather uses the hostname in $DISPLAY, typically "localhost" and connects using TCP. This is then tunneled back to the SSH client. When using "--net host" for the Docker, "localhost" will be the same for the Docker container as for the Docker host, and therefore it will work fine.</p> <p>When not specifying "--net host", the Docker is using the default bridge network mode. <strong>This means that "localhost" means something else inside the container than for the host</strong>, and X applications inside the container will not be able to see the X server by referring to "localhost". So in order to solve this, one would have to replace "localhost" with the actual IP-address of the host. This is usually "172.17.0.1" or similar. Check "ip addr" for the "docker0" interface.</p> <p>This can be done with a sed replacement:</p> <pre><code>DISPLAY=`echo $DISPLAY | sed 's/^[^:]*\(.*\)/172.17.0.1\1/'` </code></pre> <p>Additionally, the SSH server is commonly not configured to accept remote connections to this X11 tunnel. This must then be changed by editing <strong>/etc/ssh/sshd_config</strong> (at least in Debian) and setting:</p> <pre><code>X11UseLocalhost no </code></pre> <p>and then restart the SSH server, and re-login to the server with "ssh -X".</p> <p>This is almost it, but there is one complication left. If any firewall is running on the Docker host, the TCP port associated with the X11-tunnel must be opened. The port number is the number between the <strong>:</strong> and the <strong>.</strong> in $DISPLAY added to 6000.</p> <p>To get the TCP port number, you can run:</p> <pre><code>X11PORT=`echo $DISPLAY | sed 's/^[^:]*:\([^\.]\+\).*/\1/'` TCPPORT=`expr 6000 + $X11PORT` </code></pre> <p>Then (if using <em>ufw</em> as firewall), open up this port for the Docker containers in the 172.17.0.0 subnet:</p> <pre><code>ufw allow from 172.17.0.0/16 to any port $TCPPORT proto tcp </code></pre> <p>All the commands together can be put into a script:</p> <pre><code>XSOCK=/tmp/.X11-unix XAUTH=/tmp/.docker.xauth xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | sudo xauth -f $XAUTH nmerge - sudo chmod 777 $XAUTH X11PORT=`echo $DISPLAY | sed 's/^[^:]*:\([^\.]\+\).*/\1/'` TCPPORT=`expr 6000 + $X11PORT` sudo ufw allow from 172.17.0.0/16 to any port $TCPPORT proto tcp DISPLAY=`echo $DISPLAY | sed 's/^[^:]*\(.*\)/172.17.0.1\1/'` sudo docker run -ti --rm -e DISPLAY=$DISPLAY -v $XAUTH:$XAUTH \ -e XAUTHORITY=$XAUTH name_of_docker_image </code></pre> <p>Assuming you are not root and therefore need to use sudo.</p> <p>Instead of <code>sudo chmod 777 $XAUTH</code>, you could run:</p> <pre><code>sudo chown my_docker_container_user $XAUTH sudo chmod 600 $XAUTH </code></pre> <p>to prevent other users on the server from also being able to access the X server if they know what you have created the /tmp/.docker.auth file for.</p> <p>I hope this should make it properly work for most scenarios.</p>
46,069,709
Combining two csv files using pandas
<p>Can anyone check for me what's wrong with my code. I want it merge two csv file into one csv file.</p> <p><strong>I hve tried to google and I still cant merge it, it will create new file but will show nothing inside.</strong> <a href="https://stackoverflow.com/a/16266144/7624469">https://stackoverflow.com/a/16266144/7624469</a></p> <blockquote> <p><strong>a.csv</strong></p> </blockquote> <pre><code>ID User A1 Fi A2 Ki </code></pre> <blockquote> <p><strong>b.csv</strong></p> </blockquote> <pre><code>ID User A4 Fsdi A5 Kisd </code></pre> <blockquote> <p>The output that I want will look like this </p> <p><strong>combined.csv</strong></p> </blockquote> <pre><code>ID User A1 Fi A2 Ki A4 Fsdi A5 Kisd </code></pre> <p><strong>test.py</strong></p> <pre><code>import pandas, sys import pandas as pd a = pd.read_csv("C:/JIRA Excel File/a.csv") b = pd.read_csv("C:/JIRA Excel File/b.csv") merged = a.merge(b, on='ID') merged.to_csv('C:/JIRA Excel File/result.csv', index=False) </code></pre>
46,070,094
2
0
null
2017-09-06 07:55:33.97 UTC
6
2018-09-26 15:26:33.303 UTC
2017-09-06 19:54:26.917 UTC
null
4,909,087
null
8,293,303
null
1
16
python|pandas|csv|dataframe|concat
44,220
<p>Using <code>df.append</code>:</p> <pre><code>out = df1.append(df2) print(out) ID User 0 A1 Fi 1 A2 Ki 0 A4 Fsdi 1 A5 Kisd with open('C:/JIRA Excel File/result.csv', 'w', encoding='utf-8') as f: out.to_csv(f, index=False) </code></pre>
56,445,257
ValueError: Client secrets must be for a web or installed app
<p>I am running the quickstart.py example code under <a href="https://developers.google.com/slides/quickstart/python" rel="noreferrer"> Python Quickstart</a> and I am getting the following error:</p> <blockquote> <p>ValueError: Client secrets must be for a web or installed app.</p> </blockquote> <p>I created a <code>credentials.json</code> file with project owner rights.</p> <p>The error occurs in the following piece of code:</p> <pre><code>if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) </code></pre> <p>I notice also that the token.pickle file is not being created. This is the error output:</p> <pre><code> File &quot;updateSlidev01.py&quot;, line 51, in &lt;module&gt; main() File &quot;updateSlidev01.py&quot;, line 31, in main flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) File &quot;/Library/Python/2.7/site-packages/google_auth_oauthlib/flow.py&quot;, line 174, in from_client_secrets_file return cls.from_client_config(client_config, scopes=scopes, **kwargs) File &quot;/Library/Python/2.7/site-packages/google_auth_oauthlib/flow.py&quot;, line 147, in from_client_config 'Client secrets must be for a web or installed app.') ValueError: Client secrets must be for a web or installed app. </code></pre>
56,588,100
2
2
null
2019-06-04 13:46:08.61 UTC
3
2022-08-19 11:34:20.64 UTC
2020-09-18 18:15:04.363 UTC
null
555,121
null
6,886,568
null
1
49
python|google-api|google-api-python-client
38,873
<p>The problem was that I was using the json generated under Service account keys Manage service accounts and not the one under OAuth 2.0 client IDs.</p> <p>Follow this instructor for creating oauth client id. <a href="https://developers.google.com/workspace/guides/create-credentials#oauth-client-id" rel="nofollow noreferrer">https://developers.google.com/workspace/guides/create-credentials#oauth-client-id</a></p>
22,115,936
Install Bundler gem using Ansible
<p>I am trying to install Bundler on my VPS using Ansible.</p> <p>I already have rbenv set up and the global ruby is 2.1.0.</p> <p>If I SSH as root into the server and run <code>gem install bundler</code>, it installs perfectly.</p> <p>I have tried the following three ways of using Ansible to install the Bundler gem and all three produce no errors, but when I SSH in and run <code>gem list</code>, Bundler is nowhere to be seen.</p> <p>Attempt 1:</p> <pre><code>--- - name: Install Bundler shell: gem install bundler </code></pre> <p>Attempt 2:</p> <pre><code>--- - name: Install Bundler shell: gem install bundler </code></pre> <p>Attempt 3:</p> <pre><code>--- - name: Install Bundler gem: name=bundler state=latest </code></pre> <p>I have also tried the last attempt with <code>user_install=yes</code> and also with <code>user_install=no</code> and neither make any difference.</p> <p>Any ideas how I can get it to install Bundler correctly via Ansible?</p> <p>I've been working on this for a little while now and I have 1 ruby version installed: 2.1.0 and ahve found that the shims directory for rbenv does not contain a shim for <code>bundle</code>.</p> <p>Should a shim for <code>bundle</code> be in there? I'm just getting confused as to why capistrano cannot find the <code>bundle</code> command as it's listed when I run <code>sudo gem list</code> but NOT when I run <code>gem list</code>?</p> <pre><code>root@weepingangel:/usr/local/rbenv/shims# echo $PATH /usr/local/rbenv/shims:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games root@weepingangel:/usr/local/rbenv/shims# gem environment RubyGems Environment: - RUBYGEMS VERSION: 2.2.0 - RUBY VERSION: 2.1.0 (2013-12-25 patchlevel 0) [x86_64-linux] - INSTALLATION DIRECTORY: /usr/local/rbenv/versions/2.1.0/lib/ruby/gems/2.1.0 - RUBY EXECUTABLE: /usr/local/rbenv/versions/2.1.0/bin/ruby - EXECUTABLE DIRECTORY: /usr/local/rbenv/versions/2.1.0/bin - SPEC CACHE DIRECTORY: /root/.gem/specs - RUBYGEMS PLATFORMS: - ruby - x86_64-linux - GEM PATHS: - /usr/local/rbenv/versions/2.1.0/lib/ruby/gems/2.1.0 - /root/.gem/ruby/2.1.0 - GEM CONFIGURATION: - :update_sources =&gt; true - :verbose =&gt; true - :backtrace =&gt; false - :bulk_threshold =&gt; 1000 - :sources =&gt; ["http://gems.rubyforge.org", "http://gems.github.com"] - "gem" =&gt; "--no-ri --no-rdoc" - REMOTE SOURCES: - http://gems.rubyforge.org - http://gems.github.com - SHELL PATH: - /usr/local/rbenv/versions/2.1.0/bin - /usr/local/rbenv/libexec - /usr/local/rbenv/shims - /usr/local/sbin - /usr/local/bin - /usr/sbin - /usr/bin - /sbin - /bin - /usr/games </code></pre> <p>Any ideas?</p> <p>So, I think the two main problems I have:</p> <ol> <li><p>Why is bundler only visible when I run <code>sudo gem list</code>?</p></li> <li><p>My deploy is saying:</p> <pre><code>INFO [18d5838c] Running /usr/bin/env bundle install --binstubs /var/rails_apps/neiltonge/shared/bin --path /var/rails_apps/neiltonge/shared/bundle --without development test --deployment --quiet on 188.226.159.96 DEBUG [18d5838c] Command: cd /var/rails_apps/neiltonge/releases/20140301205432 &amp;&amp; ( PATH=$PATH /usr/bin/env bundle install --binstubs /var/rails_apps/neiltonge/shared/bin --path /var/rails_apps/neiltonge/shared/bundle --without development test --deployment --quiet ) DEBUG [18d5838c] /usr/bin/env: bundle: No such file or directory </code></pre> <p>and this is my <code>$PATH</code>:</p> <pre><code>/usr/local/rbenv/shims:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games </code></pre></li> </ol> <p>Why can't bundle be located?</p>
22,121,802
6
1
null
2014-03-01 14:58:04.443 UTC
8
2020-04-26 17:10:13.657 UTC
2016-04-24 05:44:28.397 UTC
null
2,947,502
null
1,125,496
null
1
34
ruby|ubuntu|rubygems|bundler|ansible
20,020
<p>The problem is that, when running <code>gem install bundler</code> via ansible, you're not initializing rbenv properly, since <code>rbenv init</code> is run in <code>.bashrc</code> or <code>.bash_profile</code>. So the <code>gem</code> command used is the system one, not the one installed as a rbenv shim. So whenever you install a gem, it is installed system-wide, not in your rbenv environment.</p> <p>To have rbenv initialized properly, you must execute bash itself and explicitely state that it's a login shell, so it reads it's initialization files :</p> <pre><code>ansible your_host -m command -a 'bash -lc "gem install bundler"' -u your_rbenv_user </code></pre> <p>Leave the <code>-u your_rbenv_user</code> part if you really want to do this as root.</p> <p>If the above command works, you can easily turn it into a playbook action :</p> <pre><code>- name: Install Bundler become_user: your_rbenv_user command: bash -lc "gem install bundler" </code></pre> <p>It's cumbersome, but it's the only way I found so far.</p>
23,452,449
How do I show a loading spinner when submitting for a partial view in asp.net MVC?
<p>I've written an application that loads partial views when you click "Continue". Sometimes the server hangs a little so I'd like to show some sort of loading message or spinner when the user clicks submit so they know the page is doing something. </p> <p>This is just your standard form but my submit code looks like this(included a field so you can see an example):</p> <pre><code> &lt;div class="form-group"&gt; @Html.LabelFor(m =&gt; m.JointAdditionalIncomeSource, new { @class = "col-sm-2 control-label" }) &lt;div class="col-sm-10"&gt; &lt;div class="col-sm-4"&gt; @Html.TextBoxFor(m =&gt; m.JointAdditionalIncomeSource, new { @class = "form-control", placeholder = "Additional Income Source" }) @Html.ValidationMessageFor(m =&gt; m.JointAdditionalIncomeSource) &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-offset-3 col-sm-10"&gt; &lt;div class="col-sm-4"&gt; &lt;input type="submit" value="Back" id="back" class="btn btn-default" /&gt; &lt;input type="submit" value="Continue" id="continue" class="btn btn-default" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I've looked around on google for ways to do this and so far haven't had any luck. Jquery wouldn't be a bad method to use if anyone has an example of that.</p> <p>Updates:</p> <p>This is my current code that is not working.</p> <pre><code>&lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;script src="~/Scripts/jquery-1.10.2.min.js"&gt;&lt;/script&gt; &lt;script src="~/Scripts/jquery.unobtrusive-ajax.min.js"&gt;&lt;/script&gt; &lt;script&gt; $('#continue').submit(function () { $('#LoanType').hide(); }); &lt;/script&gt; &lt;script type="text/javascript"&gt; function onBegin() { $("#divLoading").html('&lt;image src="../Content/ajax-loader.gif" alt="Loading, please wait" /&gt;'); } function onComplete() { $("#divLoading").html(""); } &lt;/script&gt; </code></pre> <p></p> <pre><code>&lt;body&gt; &lt;!--If user has javascript disabled--&gt; &lt;noscript&gt; &lt;div style="position: fixed; top: 0px; left: 0px; z-index: 3000; height: 100%; width: 100%; background-color: #FFFFFF"&gt; &lt;p style="margin-left: 10px"&gt;To continue using this application please enable Javascript in your browser.&lt;/p&gt; &lt;/div&gt; &lt;/noscript&gt; &lt;!-- WIZARD --&gt; &lt;div id="MyWizard" class="site-padding-top container"&gt; &lt;div data-target="#step1" id="step1" class="app-bg"&gt; &lt;div class="form-horizontal"&gt; &lt;div id="LoanType"&gt; &lt;div class="divider-app"&gt; &lt;p&gt;Loan Type&lt;/p&gt; &lt;/div&gt; @using (Ajax.BeginForm("SelectLoanType", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "step2" })) { &lt;div class="form-group"&gt; @Html.LabelFor(m =&gt; m.LoanType, new { @class = "col-sm-2 control-label" }) &lt;div class="col-sm-10"&gt; &lt;div class="col-sm-4"&gt; @Html.DropDownListFor(m =&gt; m.LoanType, new SelectList(Model.AllAvailableLoanTypes.Select(x =&gt; new { Value = x, Text = x }), "Value", "Text"), new { @class = "form-control", id = "loanType" }) &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group" id="LoanTypeSubmit"&gt; &lt;div class="col-lg-offset-3 col-sm-10"&gt; &lt;div class="col-sm-4"&gt; &lt;input type="submit" value="Continue" id="continue" class="btn btn-default" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; } &lt;div id="divLoading"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>The delay in the controller is working.</p>
23,452,857
2
2
null
2014-05-04 04:00:14.447 UTC
5
2022-07-05 17:01:31.34 UTC
2014-05-05 03:27:34.14 UTC
null
2,820,641
null
2,820,641
null
1
10
javascript|jquery|asp.net|asp.net-mvc
50,950
<p>Here goes the complete solution - </p> <p>Lets say you have an ajax controller like this - </p> <pre><code> public ActionResult Ajax() { return View(); } </code></pre> <p>Which serves the following ajax view - </p> <pre><code>@{ ViewBag.Title = "Ajax"; } &lt;h2&gt;Ajax&lt;/h2&gt; &lt;script src="~/Scripts/jquery-1.10.2.min.js"&gt;&lt;/script&gt; &lt;script src="~/Scripts/jquery.unobtrusive-ajax.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function onBegin() { $("#divLoading").html('&lt;image src="../Content/ajax-loader.gif" alt="Loading, please wait" /&gt;'); } function onComplete() { $("#divLoading").html(""); } &lt;/script&gt; @using (Ajax.BeginForm("LoadRules", "Home", new AjaxOptions { UpdateTargetId = "Rules", OnBegin = "onBegin", OnComplete = "onComplete" })) { &lt;input type="submit" value="Load Rules" /&gt; } &lt;div id="divLoading"&gt;&lt;/div&gt; &lt;div id="Rules"&gt;&lt;/div&gt; </code></pre> <p>Then when you click on the submit button it will hit the following controller, which has a delay of 5 secs (simulation of long running task) in serving the partial view - </p> <pre><code> public ActionResult LoadRules(DDLModel model) { System.Threading.Thread.Sleep(5000); return PartialView("MyPartial"); } </code></pre> <p>and the partial view is a simple view - </p> <pre><code>&lt;div&gt; This is Partial View &lt;/div&gt; </code></pre> <p>Here to show the loaded I simply used the following gif file - </p> <p><img src="https://i.stack.imgur.com/fLQzF.gif" alt="enter image description here"></p> <p>when we click on the submit button it will show the progress in the following way - </p> <p><img src="https://i.stack.imgur.com/Ql1q5.png" alt="enter image description here"></p> <p>And once the delay of 5 secs completes on the server side, it will show the partial view - </p> <p><img src="https://i.stack.imgur.com/l6Zji.png" alt="enter image description here"></p>
25,449,469
Show Current Location and Update Location in MKMapView in Swift
<p>I am learning how to use the new Swift language (only Swift, no Objective-C). To do it, I want to do a simple view with a map (<code>MKMapView</code>). I want to find and update the location of the user (like in the Apple Map app).</p> <p>I tried this, but nothing happened:</p> <pre><code>import MapKit import CoreLocation class MapView : UIViewController, CLLocationManagerDelegate { @IBOutlet weak var map: MKMapView! var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() if (CLLocationManager.locationServicesEnabled()) { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } } } </code></pre> <p>Could you please help me?</p>
25,451,592
11
1
null
2014-08-22 14:31:54.383 UTC
16
2022-04-22 07:22:15.313 UTC
2018-11-30 09:07:46.36 UTC
null
4,377,671
null
3,968,157
null
1
51
ios|swift|mkmapview|cllocationmanager
143,538
<p>You have to override <code>CLLocationManager.didUpdateLocations</code> (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:</p> <pre><code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last{ let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.map.setRegion(region, animated: true) } } </code></pre> <p>NOTE: If your target is iOS 8 or above, you must include the <code>NSLocationAlwaysUsageDescription</code> or <code>NSLocationWhenInUseUsageDescription</code> key in your Info.plist to get the location services to work.</p>