id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
5,764,956
Which is faster : if (bool) or if(int)?
<blockquote> <p><a href="https://stackoverflow.com/questions/5554725/which-value-is-better-to-use-boolean-true-or-integer-1">Which value is better to use? Boolean true or Integer 1?</a></p> </blockquote> <p>The above topic made me do some experiments with <code>bool</code> and <code>int</code> in <code>if</code> condition. So just out of curiosity I wrote this program:</p> <pre><code>int f(int i) { if ( i ) return 99; //if(int) else return -99; } int g(bool b) { if ( b ) return 99; //if(bool) else return -99; } int main(){} </code></pre> <p><code>g++ intbool.cpp -S</code> generates asm code for each functions as follows:</p> <ul> <li><p>asm code for <code>f(int)</code></p> <pre><code>__Z1fi: LFB0: pushl %ebp LCFI0: movl %esp, %ebp LCFI1: cmpl $0, 8(%ebp) je L2 movl $99, %eax jmp L3 L2: movl $-99, %eax L3: leave LCFI2: ret </code></pre></li> <li><p>asm code for <code>g(bool)</code></p> <pre><code>__Z1gb: LFB1: pushl %ebp LCFI3: movl %esp, %ebp LCFI4: subl $4, %esp LCFI5: movl 8(%ebp), %eax movb %al, -4(%ebp) cmpb $0, -4(%ebp) je L5 movl $99, %eax jmp L6 L5: movl $-99, %eax L6: leave LCFI6: ret </code></pre></li> </ul> <p>Surprisingly, <code>g(bool)</code> generates more <code>asm</code> instructions! Does it mean that <code>if(bool)</code> is little slower than <code>if(int)</code>? I used to think <code>bool</code> is especially designed to be used in conditional statement such as <code>if</code>, so I was expecting <code>g(bool)</code> to generate less asm instructions, thereby making <code>g(bool)</code> more efficient and fast. </p> <p>EDIT:</p> <p>I'm not using any optimization flag as of now. But even absence of it, why does it generate more asm for <code>g(bool)</code> is a question for which I'm looking for a reasonable answer. I should also tell you that <code>-O2</code> optimization flag generates exactly same asm. But that isn't the question. The question is what I've asked.</p> <hr>
5,765,029
8
14
null
2011-04-23 15:07:18.54 UTC
19
2018-05-04 01:10:08.867 UTC
2017-05-23 12:32:28.487 UTC
null
-1
null
415,784
null
1
104
c++|assembly|int|boolean
47,458
<p>Makes sense to me. Your compiler apparently defines a <code>bool</code> as an 8-bit value, and your system ABI requires it to "promote" small (&lt; 32-bit) integer arguments to 32-bit when pushing them onto the call stack. So to compare a <code>bool</code>, the compiler generates code to isolate the least significant byte of the 32-bit argument that g receives, and compares it with <code>cmpb</code>. In the first example, the <code>int</code> argument uses the full 32 bits that were pushed onto the stack, so it simply compares against the whole thing with <code>cmpl</code>.</p>
6,104,258
How to reset Heroku app and re-commit everything?
<p>I'm building an application which I'm also testing in Heroku. I ran into some problem today and had to rollback one commit in my local git repo, but Heroku now won't recognize my changes saying that "everything is up to date".</p> <p>So, running</p> <pre><code>git push heroku master </code></pre> <p>heroku responds with </p> <pre><code>Everything up-to-date </code></pre> <p>which isn't true.</p> <p>UPDATE: Things I've tried</p> <pre><code>git push -f heroku master git push --force heroku master git push heroku +master git push --force heroku +master </code></pre> <p>Did some changes in the source code and then</p> <pre><code>git add. git commit -a -m "Message" #(Then this commit shows in my git explorer) git push heroku master #Everything up-to-date </code></pre>
6,110,610
9
8
null
2011-05-23 23:38:18.113 UTC
30
2017-05-25 06:10:04.757 UTC
2011-05-24 11:03:27.517 UTC
null
351,901
null
351,901
null
1
54
ruby-on-rails-3|git|heroku
46,838
<p>Sounds weird. Maybe try pushing a different branch would do?</p> <pre><code>git branch production git checkout production #do some code changes git commit -am "some desperate code changes to try fix heroku" git push heroku production:master </code></pre> <p>Creating a new production branch is what I want you to test. Besides, it's nice to have a production branch that you can use to deploy.</p> <p>If it doesn't work, then I think the problem runs deeper and you need help from heroku.</p> <p>EDIT: Add the <em>heroku releases addon</em> too. Rolling back is as easy as <code>heroku rollback</code></p>
6,178,866
'txtName' is not declared. It may be inaccessible due to its protection level
<p>After putting a textbox on my page when I compile it I get the above error:</p> <p>'txtName' is not declared. It may be inaccessible due to its protection level.</p> <p>This is happening when I try to read the value of the textbox in the codebehind page.</p> <p>I'm not sure what's causing this...any ideas?</p> <p>In the aspx file I have:</p> <pre><code>&lt;%@ Page Language="VB" AutoEventWireup="false" CodeFile="signup.aspx.vb" Inherits="signup" %&gt; </code></pre> <p>In the codebehind aspx.vb file I have:</p> <pre><code>Imports System.Data.SqlClient Partial Class signup Inherits System.Web.UI.Page Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click </code></pre>
6,179,363
13
0
null
2011-05-30 16:54:04.683 UTC
4
2018-01-09 10:48:49.31 UTC
2011-05-30 17:41:06.927 UTC
null
115,983
null
115,983
null
1
19
asp.net
92,484
<p>Ok, I have this resolved now. It was becuase I had renamed a copy of the .aspx file and which still using the newer versions code behind file. </p> <p>The code behind file was looking for txtName.text but on the older version of the .aspx file txtName didnt exist!</p> <p>I have excluded the older version of the page from the project and it appears to run ok now.</p> <p>Thanks everyone for you help.</p>
5,999,118
How can I add or update a query string parameter?
<p>With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development.</p>
6,021,027
29
4
null
2011-05-14 00:46:38.543 UTC
126
2021-09-24 06:15:16.02 UTC
2017-09-05 07:35:11.08 UTC
null
542,251
null
373,674
null
1
447
javascript|jquery|query-string
504,270
<p>I wrote the following function which accomplishes what I want to achieve:</p> <pre><code>function updateQueryStringParameter(uri, key, value) { var re = new RegExp("([?&amp;])" + key + "=.*?(&amp;|$)", "i"); var separator = uri.indexOf('?') !== -1 ? "&amp;" : "?"; if (uri.match(re)) { return uri.replace(re, '$1' + key + "=" + value + '$2'); } else { return uri + separator + key + "=" + value; } } </code></pre>
18,069,678
How to use asynctask to display a progress bar that counts down?
<p>In my application i want the user to press a button and then wait 5 mins. i know this sounds terrible but just go with it. The time remaining in the 5 min wait period should be displayed in the progress bar.</p> <p>I was using a CountDownTimer with a text view to countdown but my boss wants something that looks better. hence the reasoning for a progress bar.</p>
18,069,882
1
6
null
2013-08-05 23:53:44.99 UTC
6
2014-02-02 11:35:35.983 UTC
null
null
null
null
1,313,781
null
1
7
android|android-asynctask|android-ui|countdown
40,404
<p>You can do something like this..</p> <pre><code>public static final int DIALOG_DOWNLOAD_PROGRESS = 0; private ProgressDialog mProgressDialog; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DOWNLOAD_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("waiting 5 minutes.."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(false); mProgressDialog.show(); return mProgressDialog; default: return null; } } </code></pre> <p>Then write an async task to update progress..</p> <pre><code>private class DownloadZipFileTask extends AsyncTask&lt;String, String, String&gt; { @Override protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override protected String doInBackground(String... urls) { //Copy you logic to calculate progress and call publishProgress("" + progress); } protected void onProgressUpdate(String... progress) { mProgressDialog.setProgress(Integer.parseInt(progress[0])); } @Override protected void onPostExecute(String result) { dismissDialog(DIALOG_DOWNLOAD_PROGRESS); } } </code></pre> <p>This should solve your purpose and it wont even block UI tread..</p>
42,293,488
Show and Hide Bottom Sheet Programmatically
<p>I have implemented Bottom Sheet functionality within my activity in onCreate() using <a href="https://stackoverflow.com/a/26723695">this</a> solution and <a href="https://github.com/soarcn/BottomSheet" rel="noreferrer">this</a> library</p> <pre><code> sheet = new BottomSheet.Builder(this, R.style.BottomSheet_Dialog) .title("New") .grid() // &lt;-- important part .sheet(R.menu.menu_bottom_sheet) .listener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO } }).build(); </code></pre> <p>Now, I would like to Show Bottom sheet, on click of button and in a same way want to hide bottom sheet on click of same button, if already Visible</p>
42,293,605
4
1
null
2017-02-17 08:57:26.017 UTC
12
2021-04-15 12:36:45.237 UTC
2017-05-23 12:00:06.253 UTC
null
-1
null
3,585,072
null
1
57
android|material-design|bottom-sheet
73,312
<p>Inside your <code>onClick()</code> of the button use: <code>sheet.show()</code>.</p> <p>Then when you want to dismiss it, use <code>sheet.dismiss()</code>;</p> <p>Here below a possible solution:</p> <pre><code>BottomSheet sheet = new BottomSheet.Builder(...).build(); Button button = (Button)findViewById(R.id.mybutton); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { //you can use isShowing() because BottomSheet inherit from Dialog class if (sheet.isShowing()){ sheet.dismiss(); } else { sheet.show(); } } }); </code></pre>
9,110,663
Append current date to the filename via Cron?
<p>I've created a Cron task at my webhost to daily backup my database and I would like it to append the current date to the filename.</p> <p>My Cron job looks like this</p> <pre><code>mysqldump -u username -pPassword db_name &gt; www/db_backup/db_backup+date%d%m%y.sql </code></pre> <p>But the file I get is this: <strong>db_backup+date</strong> no file extension or date.</p> <p>I've also tried this command </p> <pre><code>mysqldump -u username -pPassword db_name &gt; www/db_backup/db_backup_'date +%d%m%y'.sql </code></pre> <p>but that doesn't even give an file output.</p> <p>What is the right syntax for getting the date appended to my file??</p>
18,282,624
4
0
null
2012-02-02 10:24:08.027 UTC
8
2021-06-15 12:56:58.367 UTC
2019-10-30 21:50:55.697 UTC
null
608,639
null
188,082
null
1
51
cron|cron-task
60,705
<pre><code>* * * * * echo &quot;hello&quot; &gt; /tmp/helloFile_$(date +\%Y\%m\%d\%H\%M\%S).txt </code></pre> <p>You just need to escape the percent signs.</p> <p>Other date formats: <a href="http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/" rel="noreferrer">http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/</a></p>
34,376,061
Dagger and Kotlin. Dagger doesn't generate component classes
<p>I'm new with kotlin and Dagger. I have a little problem that I do not how to solve and I don't find a solution.</p> <p>So this is what I have:</p> <pre><code>@Module class AppModule (app: Application) { private var application: Application; init { this.application = app; } @Provides fun provideApplication(): Application? { return application; } @Provides fun provideResources(): Resources? { return application.resources; } } @Singleton @Component(modules = arrayOf(AppModule::class)) interface AppComponent: AppComponentBase { public class Initializer { private constructor(){} companion object { fun Init(app: Application): AppComponent? { return DaggerAppComponent.builder().appModule(AppModule(app)).build() } } } } </code></pre> <p><code>AppComponentBase</code>: This interface contain all the methods needed by this component.</p> <p>Now, the problem is that this <code>DaggerAppComponent</code> class is not generated by Dagger if I do this <code>DaggerAppComponent.builder().appModule(AppModule(app)).build()</code> invocation within the <code>companion object</code>. If a invoke the same line any were by the <code>companion object</code> dagger generate de class without any problem.</p> <p>An other thing I did look for a solution was create an other different class with the same structure, and importe the <code>DaggerAppComponent</code> as internal object, and I the same result happened. </p> <p>I don't what to have the initialization of the component outside. So, there any other alternative solution, or what am I doing wrong?.</p>
34,376,905
7
2
null
2015-12-19 22:31:03.397 UTC
4
2022-09-02 12:05:18.203 UTC
2019-05-14 19:10:15.197 UTC
null
608,312
null
4,564,530
null
1
47
kotlin|dagger-2
20,881
<p>You need to have the <a href="http://blog.jetbrains.com/kotlin/2015/05/kapt-annotation-processing-for-kotlin/" rel="noreferrer">kapt processor</a> in build.gradle:</p> <pre><code>kapt { generateStubs = true } dependencies { ... compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile 'com.google.dagger:dagger:2.0.2' kapt 'com.google.dagger:dagger-compiler:2.0.2' ... } </code></pre> <p>This extension will generate the code for dagger.</p> <p>Additionally, for newer gradle versions, you can also apply the plugin in your build.gradle:</p> <pre><code>apply plugin: 'kotlin-kapt' dependencies { ... compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile 'com.google.dagger:dagger:2.0.2' kapt 'com.google.dagger:dagger-compiler:2.0.2' ... } </code></pre> <p>You can check <a href="https://github.com/damianpetla/kotlin-dagger-example" rel="noreferrer">this project</a> for reference </p>
10,298,683
Adding a click event to an element?
<p>How can one assign a click event to an arbitrary span (<code>eg. &amp;lt;span id="foo"&gt;foo&amp;lt;/span&gt;</code>) in an ST2 app? </p> <p>I have a trivial example that illustrates the idea of what I'd like to do. In the example, I write the letters <code>A,B,C</code> and I'd like to tell the user which letter they clicked. </p> <p>Here's an image:</p> <p><img src="https://i.stack.imgur.com/dgZDC.png" alt="enter image description here"></p> <hr> <p><strong>CODE SNIPPET</strong></p> <pre><code>Ext.application({ launch: function() { var view = Ext.create('Ext.Container', { layout: { type: 'vbox' }, items: [{ html: '&amp;lt;span id="let_a"&gt;A&amp;lt;/span&gt; &amp;lt;span id="let_b"&gt;B&amp;lt;/span&gt; &amp;lt;span style="float:right" id="let_c"&gt;C&amp;lt;/span&gt;', style: 'background-color: #c9c9c9;font-size: 48px;', flex: 1 }] }); Ext.Viewport.add(view); } }); </code></pre>
10,306,635
1
1
null
2012-04-24 13:19:28.05 UTC
9
2018-04-15 11:20:40.56 UTC
2018-04-15 11:20:40.56 UTC
null
3,519,009
user568866
null
null
1
11
sencha-touch-2
11,407
<p>You can add a listener to a specific element using delegation. It is actually fairly simply to use.</p> <pre><code>Ext.Viewport.add({ html: 'test &lt;span class="one"&gt;one&lt;/span&gt; hmmm &lt;span class="two"&gt;two&lt;/span&gt;', listeners: [ { element: 'element', delegate: 'span.one', event: 'tap', fn: function() { console.log('One!'); } }, { element: 'element', delegate: 'span.two', event: 'tap', fn: function() { console.log('Two!'); } } ] }); </code></pre> <p>The main parts are <code>element</code> and <code>delegate</code>.</p> <ul> <li><code>element</code> will have the value of <code>element</code> in almost every case, unless you are working with custom components with custom templates.</li> <li><code>delegate</code> is a simple CSS selector. So it could be anything from <code>span</code> to <code>span .test.second</code></li> </ul> <p>Ideally, as <strong>Thiem</strong> said, you should take advantage of components as much as possible. They will give you much more flexibility. But I know there are definitely some cases where you need to do this. There will be no performance implications; in fact, it will be faster than using components. However, you should <strong>never</strong> implement listeners the way he suggested. It will not be performant and is extremely dirty (as he mentioned).</p>
7,600,022
how to generate Serial numbers +Add 1 in select statement
<p>I know we can generate row_number in select statement. But row_number starts from 1, I need to generate from 2 and onwards. </p> <p>example</p> <pre><code>party_code ---------- R06048 R06600 R06791 (3 row(s) affected) I want it like party_code serial number ---------- ------------- R06048 2 R06600 3 R06791 4 </code></pre> <p>Current I am using below select statement for generate regular row number.</p> <pre><code> SELECT party_code, ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number] FROM myTable ORDER BY party_code </code></pre> <p>How can modify above select statement and start from 2?</p>
7,600,065
2
2
null
2011-09-29 15:52:54.287 UTC
null
2011-09-29 15:58:03.377 UTC
null
null
null
null
158,008
null
1
7
sql|sql-server|tsql
88,143
<pre><code>SELECT party_code, 1 + ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number] FROM myTable ORDER BY party_code </code></pre> <p>to add: <code>ROW_NUMBER()</code> has an unusual syntax, and can be confusing with the various <code>OVER</code> and <code>PARTITION BY</code> clauses, but when all is said and done it is still just a function with a numeric return value, and that return value can be manipulated in the same way as any other number.</p>
7,552,033
Android build configurations for multiple customers
<p>I have Android application that needs to be delivered to multiple customers. For every customer I have different graphics and configuration XML files which specify features and URLs. </p> <p>At build time we should be able to specify the customer for which the application should be built. Then resources (like images and run-time configuration) appropriate for the specified client should be built into the app.</p> <p>The project is build with Maven.</p> <p>Any ideas?</p>
7,568,065
2
0
null
2011-09-26 07:49:33.51 UTC
9
2011-09-27 11:04:42.483 UTC
null
null
null
null
590,531
null
1
12
android|maven|build|build-process|maven-3
3,123
<p>I ended up using maven profiles and 'renameManifestPackage' and 'resourceOverlayDirectory' properties of the android maven plugin. </p> <p>The default res/ dir is overriden by 'resourceOverlayDirectory' specific for every customer.</p> <p>It worked out great.</p> <pre><code>&lt;!-- profile for zurich --&gt; &lt;profile&gt; &lt;id&gt;zurich&lt;/id&gt; &lt;properties&gt; &lt;customer&gt;zurich&lt;/customer&gt; &lt;customerPackage&gt;zurich.com&lt;/customerPackage&gt; &lt;customerResources&gt;customers/${customer}/res&lt;/customerResources&gt; &lt;customerApkName&gt;${customer}-${project.artifactId}&lt;/customerApkName&gt; &lt;/properties&gt; &lt;/profile&gt; </code></pre> <p>and in the build I have:</p> <pre><code>&lt;build&gt; &lt;sourceDirectory&gt;src&lt;/sourceDirectory&gt; &lt;!-- the name of the generated apk and jar --&gt; &lt;finalName&gt;${customerApkName}-${project.version}&lt;/finalName&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;!-- customer specific manifest and package --&gt; &lt;plugin&gt; &lt;groupId&gt;com.jayway.maven.plugins.android.generation2&lt;/groupId&gt; &lt;artifactId&gt;maven-android-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;renameManifestPackage&gt;${customerPackage}&lt;/renameManifestPackage&gt; &lt;resourceOverlayDirectory&gt;${customerResources}&lt;/resourceOverlayDirectory&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; </code></pre>
7,630,144
How to add google chrome omnibox-search support for your site?
<p>When I enter some of URLs in Google Chrome omnibox, I see message in it "Press TAB to search in $URL". For example, there are some russian sites habrahabr.ru or yandex.ru. When you press TAB you'll be able to search in that site, not in your search engine. How to make my site to be able for it? Maybe, I need to write some special code in my site pages?</p>
7,630,169
2
1
null
2011-10-03 00:24:36.527 UTC
138
2015-09-21 04:00:15.12 UTC
2012-10-28 09:59:46.473 UTC
null
8,331
null
965,187
null
1
171
html|google-chrome|browser|opensearch
42,156
<p>Chrome usually handles this through user preferences. (via <code>chrome://settings/searchEngines</code>)</p> <p>However, if you'd like to implement this specifically for your users, you need to add a OSD (Open Search Description) to your site.</p> <p><a href="https://stackoverflow.com/questions/1317051/making-usage-of-google-chromes-omnibox-tab-feature-for-on-personal-website">Making usage of Google Chrome&#39;s OmniBox [TAB] Feature for/on personal website?</a></p> <p>You then add this XML file to the root of your site, and link to it in your <code>&lt;head&gt;</code> tag:</p> <pre><code>&lt;link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml" /&gt; </code></pre> <p>Now, visitors to your page will automatically have your site's search information placed into Chrome's internal settings at <code>chrome://settings/searchEngines</code>.</p> <h2>OpenSearchDescription XML Format Example</h2> <pre><code>&lt;OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/"&gt; &lt;ShortName&gt;Your website name (shorter = better)&lt;/ShortName&gt; &lt;Description&gt; Description about your website search here &lt;/Description&gt; &lt;InputEncoding&gt;UTF-8&lt;/InputEncoding&gt; &lt;Image width="16" height="16" type="image/x-icon"&gt;your site favicon&lt;/Image&gt; &lt;Url type="text/html" method="get" template="http://www.yoursite.com/search/?query={searchTerms}"/&gt; &lt;/OpenSearchDescription&gt; </code></pre> <p>The important part is the <code>&lt;url&gt;</code> item. <code>{searchTerms}</code> will be replaced with what the user searches for in the omnibar.</p> <p>Here's a link to <a href="http://www.opensearch.org/Home" rel="noreferrer">OpenSearch</a> for more information.</p>
31,739,392
WebDriver cannot be resolved to a type FirefoxDriver cannot be resolved to a type
<p>I found a similar error as mine on stackoverflow and added selenium webdriver jar files to the project using the below method :</p> <p>right click on project--> goto build path--> configure build path--> click on "Add external jars"--> add selenium jar files from your local machine--> click ok--> now mouseover on WebDriver in your code--> click "import webdriver"--now run your code-->you will get rid of the exception.</p> <p>However, I am still getting an error. Here's the error :</p> <blockquote> <p>Exception in thread "main" java.lang.Error: Unresolved compilation problems: WebDriver cannot be resolved to a type FirefoxDriver cannot be resolved to a type</p> </blockquote>
31,783,073
7
2
null
2015-07-31 06:25:04.387 UTC
2
2019-07-30 10:48:50.943 UTC
2016-05-08 06:39:09.867 UTC
null
1,932,092
null
5,176,483
null
1
8
webdriver|selenium-firefoxdriver
91,461
<p>This error happens when you use Eclipse as IDE and try to run code that doesn't even compile. Check your Problems view in Eclipse, and fix the compilation errors before executing the application.</p>
31,536,952
How to fix text quality in Java graphics?
<p>Code:</p> <pre><code>import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; public class TextRectangle extends JFrame { private static final long serialVersionUID = 1L; public static void main(String[] a) { TextRectangle f = new TextRectangle(); f.setSize(300, 300); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.setColor(Color.BLACK); g2d.setFont(new Font("Calibri", Font.BOLD, 18)); g2d.drawString("Why does this text look so ugly?", 30, 150); } } </code></pre> <p>Result:</p> <p><img src="https://i.stack.imgur.com/rnZSQ.png" alt="result screenshot"></p> <p>As you can see the letter spacing is uneven. Sometimes it's 1px, sometimes it's 2 or even 3 pixels. Another issue is the dot above 'i' is wider than the bottom part.</p> <p><img src="https://i.stack.imgur.com/Pt8fl.png" alt="problem details"></p> <p>The same text written in a text editor looks much better. Do you know how to fix this problem?</p> <p>My environment is Windows 8.1, Java 1.8.</p>
31,537,742
1
3
null
2015-07-21 10:47:44.387 UTC
9
2015-07-21 11:54:18.357 UTC
2015-07-21 11:07:44.297 UTC
null
853,558
null
853,558
null
1
19
java|graphics
8,879
<p>The graphics context uses integer metrics by default - meaning that rounding is applied to the location vectors of the glyph shapes.</p> <p>You can switch to <strong>fractional metrics</strong> using:</p> <pre><code>g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); </code></pre> <p><img src="https://i.stack.imgur.com/PeTnn.png" alt="enter image description here"></p> <p>As you can see, no subpixel antialiasing was used (only gray antialias pixel). You can <strong>enable subpixel antialiasing</strong> for better legibility on LCD screens:</p> <pre><code>g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); </code></pre> <p><img src="https://i.stack.imgur.com/DVYPo.png" alt="enter image description here"></p> <p>There are 4 modes:</p> <ul> <li><code>VALUE_TEXT_ANTIALIAS_LCD_HRGB</code>: horizontally oriented RGB</li> <li><code>VALUE_TEXT_ANTIALIAS_LCD_HBGR</code>: horizontally oriented BGR</li> <li><code>VALUE_TEXT_ANTIALIAS_LCD_VRGB</code>: vertically oriented RGB</li> <li><code>VALUE_TEXT_ANTIALIAS_LCD_VBGR</code>: vertically oriented BGR</li> </ul> <p>I haven't found out where to query the appropriate value of the current display and orientation. Some displays can be tilted (landscape/portrait) or even rotated, requiring to redetect the mode when painting.</p> <p><strong>EDIT</strong></p> <p>I found something in the <a href="http://filthyrichclients.org/" rel="noreferrer">Filthy Rich Clients</a> book: apparently, the Java AWT Toolkit can provide appropriate rendering hints:</p> <pre><code>Map&lt;?, ?&gt; desktopHints = (Map&lt;?, ?&gt;) Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); Graphics2D g2d = (Graphics2D) g; if (desktopHints != null) { g2d.setRenderingHints(desktopHints); } // no need to set more rendering hints </code></pre> <p>On my system, this renders the text with fractional metrics and LCD HRGB antialiasing, same as with the code above. The hints on my system are:</p> <ul> <li>Text-specific antialiasing enable key: <strong>LCD HRGB antialiasing text mode</strong></li> <li>Text-specific LCD contrast key: <strong>120</strong></li> </ul>
19,164,699
Maintaining order in HashMap
<p>I have a list which I convert to a map to do some work. After that, i convert the map back again to a list, but this time the order is random. I need the same initial order retained in my second list. </p> <p>the obvious reason is that a HashMap doesn't maintain order. But I need to do something so that it does. I cannot change the Map implementation.How can I do that ?</p> <p>Consider the given code:</p> <pre><code>import java.util.*; public class Dummy { public static void main(String[] args) { System.out.println("Hello world !"); List&lt;String&gt; list = new ArrayList&lt;String&gt;(); list.add("A");list.add("B");list.add("C"); list.add("D");list.add("E");list.add("F"); Map&lt;String,String&gt; map = new HashMap&lt;String, String&gt;(); for(int i=0;i&lt;list.size();i=i+2) map.put(list.get(i),list.get(i+1)); // Use map here to do some work List&lt;String&gt; l= new ArrayList&lt;String&gt;(); for (Map.Entry e : map.entrySet()) { l.add((String) e.getKey()); l.add((String) e.getValue()); } } } </code></pre> <p>For ex - Initially, when I printed the list elements, it printed out </p> <pre><code>A B C D E F </code></pre> <p>Now, when I print the elements of <code>List l</code>, it printed out </p> <pre><code>E F A B C D </code></pre>
19,164,725
7
1
null
2013-10-03 16:43:42.033 UTC
4
2013-10-03 17:24:09.167 UTC
null
null
null
null
1,522,454
null
1
20
java
43,912
<p><code>HashMap</code> itself doesn't maintain insertion order - but <code>LinkedHashMap</code> does, so use that instead.</p> <p>As documented... <a href="http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html" rel="noreferrer"><code>HashMap</code></a>:</p> <blockquote> <p>This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.</p> </blockquote> <p>And <a href="http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html" rel="noreferrer"><code>LinkedHashMap</code></a>:</p> <blockquote> <p>Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).</p> </blockquote>
19,075,074
Unix Bash Shell Programming if directory exists
<p>So I'm trying to get into an if statement in a bash shell script but I think I'm doing something wrong, anyways here's my sample code.</p> <pre><code>#!/bin/bash read sd if [ -d "~/tmp/$sd" ]; then echo "That directory exists" else echo "That directory doesn't exists" fi ;; </code></pre> <p>Am I pointing it to the correct directory? I want the user to input something which will be put into "sd" and if that subdirectory exists then it'll say it does, if not then it will go to the else and say it doesn't exist.</p>
19,075,092
2
1
null
2013-09-29 06:15:34.377 UTC
3
2013-09-29 06:29:39.747 UTC
2013-09-29 06:20:04.63 UTC
null
1,491,895
null
2,318,083
null
1
13
linux|bash|shell|unix
41,145
<p>Try:</p> <pre><code>if [ -d ~/tmp/"$sd" ]; then </code></pre> <p>or:</p> <pre><code>if [ -d "$HOME/tmp/$sd" ]; then </code></pre> <p>Quoting prevents expansion of <code>~</code> into your home directory.</p>
35,658,606
How to get the first key of a hashmap?
<p>I have the following <code>HashMap&lt;String, Double&gt; map = new HashMap&lt;String, Double&gt;();</code></p> <p>How can i get the first key without iterating over it like this:</p> <pre><code>Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); it.remove(); } </code></pre> <p>Thanks</p>
35,658,677
7
2
null
2016-02-26 17:59:37.83 UTC
0
2020-01-29 02:15:49.477 UTC
null
null
null
null
5,152,497
null
1
13
java|hashmap
38,996
<p>To get the value of the "first" key, you can use it</p> <pre><code>map.get(map.keySet().toArray()[0]); </code></pre> <h2>In Java8,</h2> <p>You can use stream. For <strong>TreeMap/LinkedHashMap</strong>, where ordering is significant, you can write</p> <pre><code>map.entrySet().stream().findFirst(); </code></pre> <p>For <strong>HashMap</strong>, there is no order, so <code>findAny()</code> might return a different result on different calls</p> <pre><code>map.entrySet().stream().findAny(); </code></pre>
40,902,280
What is the recommended project structure for spring boot rest projects?
<p>I'm a beginner with spring boot. I'm involved in the beginning of a project where we would build rest services using spring boot. Could you please advise the recommended directory structure to follow when building a project that will just expose rest services?</p>
40,902,759
6
1
null
2016-12-01 03:45:28.973 UTC
51
2022-02-24 02:09:27.857 UTC
null
null
null
null
1,000,281
null
1
104
java|spring|rest|spring-boot
181,909
<p>You do <em>not</em> need to do anything special to start. Start with a normal java project, either maven or gradle or IDE project layout with starter dependency.</p> <p>You need just one main class, as per guide <a href="https://spring.io/guides/gs/spring-boot/" rel="noreferrer">here</a> and rest...</p> <p><strong>There is no constrained package structure. Actual structure will be driven by your requirement/whim and the directory structure is laid by build-tool / IDE</strong></p> <p>You can follow same structure that you might be following for a Spring MVC application.</p> <p>You can follow either way </p> <ul> <li><p>A project is divided into layers:<br></p> <p>for example: DDD style</p> <ul> <li>Service layer : service package contains service classes</li> <li>DAO/REPO layer : dao package containing dao classes</li> <li>Entity layers</li> </ul> <p><br>or <br></p> <p>any layer structure suitable to your problem for which you are writing problem. <br><br></p></li> <li><p>A project divided into modules or functionalities or features and A module is divided into layers like above</p></li> </ul> <p>I prefer the second, because it follows Business context. Think in terms of concepts.</p> <p>What you do is dependent upon how you see the project. It is your code organization skills.</p>
28,377,421
Why do I receive a timeout error from Pythons requests module?
<p>I use <code>requests.post(url, headers, timeout=10)</code> and sometimes I received a <code>ReadTimeout exception HTTPSConnectionPool(host='domain.com', port=443): Read timed out. (read timeout=10)</code></p> <p>Since I already set timeout as 10 seconds, why am I still receiving a ReadTimeout exception?</p>
28,377,445
3
1
null
2015-02-07 01:14:53.36 UTC
6
2020-06-05 15:28:26.077 UTC
2017-09-22 10:10:45.89 UTC
null
562,769
null
291,779
null
1
31
python|python-requests
74,887
<p>Per <a href="https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts" rel="noreferrer">https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts</a>, that is the expected behavior. As royhowie mentioned, wrap it in a try/except block (e.g.:</p> <pre><code>try: requests.post(url, headers, timeout=10) except requests.exceptions.Timeout: print "Timeout occurred" </code></pre> <p>)</p>
797,127
What's the differences between system and backticks and pipes in Perl?
<p>Perl supports three ways (that I know of) of running external programs:</p> <p><code>system</code>:</p> <pre><code> system PROGRAM LIST </code></pre> <p>as in:</p> <pre><code>system "abc"; </code></pre> <p>backticks as in:</p> <pre><code>`abc`; </code></pre> <p>running it through a pipe as in:</p> <pre><code>open ABC, "abc|"; </code></pre> <p>What are the differences between them? Here's what I know:</p> <ol> <li>You can use backticks and pipes to get the output of the command easily.</li> <li>that's it (more in future edits?)</li> </ol>
797,173
4
0
null
2009-04-28 10:00:09.337 UTC
5
2020-03-10 18:08:13.863 UTC
2009-04-28 18:20:25.767 UTC
null
2,766,176
null
1,084
null
1
29
perl|system|pipe|backticks
8,250
<ul> <li><code>system()</code>: runs command and returns command's <strong>exit status</strong></li> <li>backticks: runs command and returns the command's <strong>output</strong></li> <li>pipes : runs command and allows you to use <strong>them as an handle</strong></li> </ul> <p>Also backticks redirects the executed program's STDOUT to a variable, and system sends it to your main program's STDOUT.</p>
1,184,983
Load a Django template tag library for all views by default
<p>I have a small typography related templatetag library that I use on almost every page. Right now I need to load it for each template using</p> <pre><code>{% load nbsp %} </code></pre> <p>Is there a way to load it "globally" for all views and templates at once? Putting the load tag into a base template doesn't work.</p>
1,185,049
4
0
null
2009-07-26 16:43:12.567 UTC
28
2018-01-08 09:51:58.84 UTC
null
null
null
null
35,440
null
1
54
django|django-templates
16,859
<p>There is an <code>add_to_builtins</code> method in <code>django.template.loader</code>. Just pass it the name of your templatetags module (as a string).</p> <pre><code>from django.template.loader import add_to_builtins add_to_builtins('myapp.templatetags.mytagslib') </code></pre> <p>Now <code>mytagslib</code> is available automatically in any template.</p>
45,545,110
Make Pandas DataFrame apply() use all cores?
<p>As of August 2017, Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer">DataFame.apply()</a> is unfortunately still limited to working with a single core, meaning that a multi-core machine will waste the majority of its compute-time when you run <code>df.apply(myfunc, axis=1)</code>. </p> <p>How can you use all your cores to run apply on a dataframe in parallel? </p>
51,669,468
12
0
null
2017-08-07 10:49:23.063 UTC
75
2022-07-07 09:12:12.76 UTC
2020-06-03 21:55:14.543 UTC
null
1,079,075
null
6,903,458
null
1
166
pandas|dask
121,119
<p>You may use the <a href="https://github.com/jmcarpenter2/swifter" rel="noreferrer"><code>swifter</code></a> package:</p> <pre><code>pip install swifter </code></pre> <p>(Note that you may want to use this in a virtualenv to avoid version conflicts with installed dependencies.)</p> <p>Swifter works as a plugin for pandas, allowing you to reuse the <code>apply</code> function:</p> <pre><code>import swifter def some_function(data): return data * 10 data['out'] = data['in'].swifter.apply(some_function) </code></pre> <p>It will automatically figure out the most efficient way to parallelize the function, no matter if it's vectorized (as in the above example) or not.</p> <p><a href="https://github.com/jmcarpenter2/swifter/blob/master/examples/swifter_apply_examples.ipynb" rel="noreferrer">More examples</a> and a <a href="https://github.com/jmcarpenter2/swifter/blob/master/examples/swiftapply_speedcomparison.ipynb" rel="noreferrer">performance comparison</a> are available on GitHub. Note that the package is under active development, so the API may change.</p> <p>Also note that this <a href="https://github.com/jmcarpenter2/swifter/blob/master/docs/documentation.md#8-pandasdataframeswifterallow_dask_on_stringsenabletrueapply" rel="noreferrer">will not work automatically</a> for string columns. When using strings, Swifter will fallback to a “simple” Pandas <code>apply</code>, which will not be parallel. In this case, even forcing it to use <code>dask</code> will not create performance improvements, and you would be better off just splitting your dataset manually and <a href="https://docs.python.org/3/library/multiprocessing.html" rel="noreferrer">parallelizing using <code>multiprocessing</code></a>.</p>
48,727,863
Vue 'export default' vs 'new Vue'
<p>I just installed Vue and have been following some tutorials to create a project using the vue-cli webpack template. When it creates the component, I notice it binds our data inside of the following:</p> <pre><code>export default { name: 'app', data: [] } </code></pre> <p>Whereas in other tutorials I see data being bound from:</p> <pre><code>new Vue({ el: '#app', data: [] )} </code></pre> <p><strong>What is the difference, and why does it seem like the syntax between the two is different?</strong> I'm having trouble getting the 'new Vue' code to work from inside the tag I'm using from the App.vue generated by the vue-cli.</p>
48,728,051
4
0
null
2018-02-11 02:59:31.877 UTC
57
2022-07-15 02:46:40.113 UTC
null
null
null
null
3,394,235
null
1
202
vue.js|vue-component|vue-cli
158,861
<p>When you declare:</p> <pre class="lang-js prettyprint-override"><code>new Vue({ el: '#app', data () { return {} } )} </code></pre> <p>That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:</p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; ... &lt;body&gt; &lt;div id=&quot;app&quot;&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:</p> <pre class="lang-js prettyprint-override"><code>// my-component.js export default { name: 'my-component', data () { return {} } } </code></pre> <p>You can later import this and use it like:</p> <pre class="lang-js prettyprint-override"><code>// another-component.js &lt;template&gt; &lt;my-component&gt;&lt;/my-component&gt; &lt;/template&gt; &lt;script&gt; import myComponent from 'my-component' export default { components: { myComponent } data () { return {} } ... } &lt;/script&gt; </code></pre> <p>Also, be sure to declare your <code>data</code> properties as functions, otherwise they are not going to be reactive.</p>
32,857,922
Jedis and Lettuce async abilities
<p>I am using redis with Akka so I need no blocking calls. Lettuce has async-future call built into it. But Jedis is the recommended client by Redis. Can someone tell me if I am using both of them the right way. If so which one is better.</p> <p><strong>JEDIS</strong> I am using a static Jedis connection pool to get con and using Akka future callback to process the result. My concern here is when I use another thread (callable) to get the result that thread is eventually going to block for the result. While Lettuce might have some more efficient way of doing this.</p> <pre><code> private final class OnSuccessExtension extends OnSuccess&lt;String&gt; { private final ActorRef senderActorRef; private final Object message; @Override public void onSuccess(String valueRedis) throws Throwable { log.info(getContext().dispatcher().toString()); senderActorRef.tell((String) message, ActorRef.noSender()); } public OnSuccessExtension(ActorRef senderActorRef,Object message) { this.senderActorRef = senderActorRef; this.message=message; } } ActorRef senderActorRef = getSender(); //never close over a future if (message instanceof String) { Future&lt;String&gt; f =akka.dispatch.Futures.future(new Callable&lt;String&gt;() { public String call() { String result; try(Jedis jedis=JedisWrapper.redisPool.getResource()) { result = jedis.get("name"); } return result; } }, ex); f.onSuccess(new OnSuccessExtension(senderActorRef,message), ex); } </code></pre> <p><strong>LETTUCE</strong></p> <pre><code>ExecutorService executorService = Executors.newFixedThreadPool(10); public void onReceive(Object message) throws Exception { ActorRef senderActorRef = getSender(); //never close over a future if (message instanceof String) { final RedisFuture&lt;String&gt; future = lettuce.connection.get("name"); future.addListener(new Runnable() { final ActorRef sender = senderActorRef; final String msg =(String) message; @Override public void run() { try { String value = future.get(); log.info(value); sender.tell(message, ActorRef.noSender()); } catch (Exception e) { } } }, executorService); </code></pre> <p>If lettuce is a better option for Async calls. Then what type of executor should I go with in production environment. If possible can I use a Akka dispatcher as an execution context for Letture future call.</p>
32,870,558
2
0
null
2015-09-30 04:38:56.197 UTC
11
2021-08-31 15:46:14.843 UTC
null
null
null
null
3,335,579
null
1
33
java|asynchronous|redis|jedis|lettuce
22,818
<p>There is no one answer to your question because it depends.</p> <p>Jedis and lettuce are both mature clients. To complete the list of Java clients, there is also Redisson, which adds another layer of abstraction (Collection/Queue/Lock/... interfaces instead of raw Redis commands).</p> <p>It pretty much depends on how you're working with the clients. In general, Jedis (java based client to connect to redis) is single-threaded in terms of data access, so the only benefit you gain by concurrency is offloading the protocol and I/O work to different threads. That is not fully true to lettuce and Redisson since they use netty under the hood (netty binds one socket channel to a particular event loop thread).</p> <p>With Jedis, you can use only one connection only with one thread at a time. That correlates nicely with the Akka actor model because one actor instance is occupied only by one thread at a time.</p> <p>On the other side, you need as much Jedis connections as threads that deal with a particular actor. If you start sharing Jedis connections across different actors, you either go for connection pooling, or you need to have a dedicated Jedis connection per actor instance. Please keep in mind that you need to take care of the reconnection (once a Redis connection is broken) by yourself.</p> <p>With Redisson and lettuce, you get transparent reconnection if you wish to do so (That's the default value to lettuce, not sure about Redisson).</p> <p>By using lettuce and Redisson you can share one connection amongst all actors because they are thread-safe. You cannot share one lettuce connection in two cases:</p> <ol> <li>Blocking operations (since you would block all other users of the connection)</li> <li>Transactions (<code>MULTI</code>/<code>EXEC</code>, since you would mix different operations with the transactions and that is certainly a thing you do not want to do so)</li> </ol> <p>Jedis has no async interface, so you're required to do this by yourself. That's feasible, and I did something similar with MongoDB, offloading/decoupling the I/O part to other actors. You can use the approach from your code, but you're not required to provide an own executor service because you do non-blocking operations in the runnable listener.</p> <p>With lettuce 4.0 you'll get Java 8 support (which is way better in terms of the async API because of the CompletionStage interface), and you can even use RxJava (reactive programming) to approach concurrency.</p> <p>Lettuce is not opinionated on your concurrency model. It allows you to use it according to you needs, except the plain <code>Future</code>/<code>ListenableFuture</code> API of Java 6/7 and Guava is not very nice to use.</p> <p>HTH, Mark</p>
38,391,411
What is the d3.js v4.0 equivalent for d3.scale.category10()?
<p>I'm trying to learn d3 with the Interactive Web Visualization book, but a lot has changed with version 4.0. One thing I really can't figure out is if there is an equivalent for d3.scale.category10() to get an easy mapping to colors. Is there something like that in the new version or do we need to use math.random and code up something ourselves?</p>
38,391,511
2
0
null
2016-07-15 08:28:55.913 UTC
9
2019-02-12 20:07:36.8 UTC
null
null
null
null
2,748,005
null
1
87
d3.js
56,932
<p>Instead of </p> <pre><code>d3.scale.category10() </code></pre> <p>use </p> <pre><code>d3.scaleOrdinal(d3.schemeCategory10); </code></pre> <p>Create a color scale like this:</p> <pre><code>var color = d3.scaleOrdinal(d3.schemeCategory10); </code></pre> <p>use the color like this in the code same as in V3:</p> <pre><code>svg.append("rect") .attr("x", 10) .attr("y", 10) .attr("width", 100) .attr("height", 100) .style("fill", color(3)) </code></pre> <p>read <a href="https://github.com/d3/d3-scale/blob/master/README.md#schemeCategory10">here</a></p> <p>Reference <a href="https://github.com/d3/d3-scale/issues/63">here</a> </p> <p>working code <a href="https://plnkr.co/edit/KCu3HsHrA2dYvZaM0RCQ?p=preview">here</a></p>
33,628,862
GIT: error: pathspec 'xxx did not match any file(s) known to git
<p>I have some trouble with a git repository of mine and I cant find the error :(</p> <p>Thing is, I had this repository already in use for a PHP project. everything was fine. Then, I "added" composer to it. I.e., I copied the composer file to the repositorie's root, created a composer.json, and used "composer install". Hence, composer.lock and vendor/ were created for me.</p> <p>Since I didnt want those to be included in the repo, I added the following to the .gitignore</p> <pre><code>composer composer.lock vendor/ </code></pre> <p>Now, whenever I use "git add" oder "git commit" from the root, I will get the following errors:</p> <pre><code>$ git commit * -m "fixed issue #123" error: pathspec 'composer' did not match any file(s) known to git. error: pathspec 'composer.lock' did not match any file(s) known to git. error: pathspec 'vendor' did not match any file(s) known to git. </code></pre> <p>Obviously, the commit (or add) does not work so I have to manually specify files to add or commit. Bummer.</p> <p>I cannot find the problem :( Anyone knows how to fix this?</p> <p>BTW I am using git version 2.4.9 (Apple Git-60)</p>
54,200,220
3
0
null
2015-11-10 11:23:47.847 UTC
6
2022-04-12 09:58:56.383 UTC
null
null
null
null
3,996,393
null
1
7
git
56,970
<p>Well, years passed, new git versions were released, yet the problem still show up for me from time to time. The posted fixes unfortunately do not help. Yet, instead of committing with <code>git commit . -m "xyz"</code> doing a </p> <p><code>git commit -a -m "xyz"</code></p> <p>does wonders.</p> <p>Cheers.</p>
21,926,202
"libevent not found" error in tmux
<p>I am trying to install tmux in my Scientific Linux release 6.5 (Carbon) machine </p> <p>These are the steps I followed </p> <pre><code>wget http://downloads.sourceforge.net/tmux/tmux-1.9.tar.gz tar xvzf tmux-1.9.tar.gz </code></pre> <p>
</p> <pre><code>cd tmux-1.9 ./configure </code></pre> <p>

At this step it's showing the error:</p> <pre><code>configure: error: "libevent not found" 

 </code></pre> <p>To solve it I did the following:</p> <pre><code>emacs /etc/yum.repos.d/pgdg-92-sl.repo
 </code></pre> <p>
and added the following lines</p> <pre><code>[pgdg92] name=PostgreSQL 9.2 $releasever - $basearch baseurl=http://yum.postgresql.org/9.2/redhat/rhel-6.4-$basearch enabled=1 gpgcheck=0 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-92 [pgdg92-source] name=PostgreSQL 9.2 $releasever - $basearch - Source failovermethod=priority baseurl=http://yum.postgresql.org/srpms/9.2/redhat/rhel-6.4-$basearch enabled=0 gpgcheck=0 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-92 </code></pre> <p>Then did:</p> <pre><code>yum install libevent

 </code></pre> <p>It installed correctly</p> <p>
Still the error configure: <code>error: "libevent not found"</code> is not solved

</p> <p>Thanks in advance :)</p>
21,926,223
6
0
null
2014-02-21 05:43:03.527 UTC
8
2022-07-11 05:44:50.31 UTC
2014-02-21 05:53:39.047 UTC
null
1,894,388
null
3,321,846
null
1
56
linux|tmux
49,416
<p>If you're trying to build software then you need the development package. Install <code>libevent-devel</code>.</p> <p>On Debian/Ubuntu based distributions you can install it with</p> <pre><code>sudo apt install libevent-dev </code></pre>
21,595,140
Checkout, Fetch and Pull in BitBucket SourceTree
<p>I am using <strong>BitBucket</strong> for web based hosting of our projects. Along with that I am using their <strong>SourceTree</strong> for committing and such purpose. I am a bit confused with the <strong>Checkout</strong>, <strong>Fetch</strong> and <strong>Pull</strong> option available in the SourceTree interface and their usage. Can someone familiar with this tool explains the usage of these options available in SourceTree?</p>
21,596,370
1
0
null
2014-02-06 05:56:19.22 UTC
14
2017-02-08 08:01:16.113 UTC
null
null
null
null
1,660,031
null
1
37
git|github|bitbucket|atlassian-sourcetree|project-hosting
112,164
<p>Using <a href="https://www.atlassian.com/git/tutorials/syncing" rel="noreferrer">Atlassian's Git tutorial</a> (link updated) as a reference.</p> <p><strong>Git checkout</strong>:</p> <blockquote> <p>The git checkout command lets you navigate between the branches created by git branch. Checking out a branch updates the files in the working directory to match the version stored in that branch, and it tells Git to record all new commits on that branch. Think of it as a way to select which line of development you’re working on.</p> <p>Source: <a href="https://www.atlassian.com/git/tutorials/using-branches#git-checkout" rel="noreferrer">https://www.atlassian.com/git/tutorials/using-branches#git-checkout</a></p> </blockquote> <p><strong>Git pull</strong>:</p> <blockquote> <p>You can think of git pull as Git's version of svn update. It’s an easy way to synchronize your local repository with upstream changes. The following diagram explains each step of the pulling process.</p> <p>Source: <a href="https://www.atlassian.com/git/tutorials/syncing#git-pull" rel="noreferrer">https://www.atlassian.com/git/tutorials/syncing#git-pull</a></p> </blockquote> <p><strong>Git fetch</strong>:</p> <blockquote> <p>The git fetch command imports commits from a remote repository into your local repo. The resulting commits are stored as remote branches instead of the normal local branches that we’ve been working with. This gives you a chance to review changes before integrating them into your copy of the project.</p> <p>Source: <a href="https://www.atlassian.com/git/tutorials/syncing#git-fetch" rel="noreferrer">https://www.atlassian.com/git/tutorials/syncing#git-fetch</a></p> </blockquote>
19,139,417
How to dynamically get a property by name from a C# ExpandoObject?
<p>I have an <code>ExpandoObject</code> and want to make a getter for it that will return a property by name at runtime, where the name is specified in a string instead of hardcoded.</p> <p>For example, I CAN do this:</p> <pre><code>account.features.isEmailEnabled; </code></pre> <p>and that will return true. <code>account</code> is a <code>ExpandoObject</code>, and <code>features</code> is also an <code>ExpandoObject</code>. So I have an <code>ExpandoObject</code> that contains other <code>ExpandoObjects</code>.</p> <p>So what I want to be able to do is this:</p> <pre><code>account.features.GetProperty("isEmailEnabled"); </code></pre> <p>and have that return true.</p> <p>The reason is that I have many features, and I want to be able to write one generic getter method where I can pass in the name of the feature I want, and the method will pass me back the value for account.features.whatever (where "whatever" is specified by passing in a string to the generic getter method). Otherwise I am going to have to write 30-some getters one for each feature.</p> <p>I did a lot of research and tried doing something like:</p> <pre><code>var prop = account.features.GetType(); // this returns System.Dyanmic.ExpandoObject </code></pre> <p>followed by</p> <pre><code>var value = prop.GetProperty(featureNameAsString); </code></pre> <p>but <code>value</code> always comes back as null. I don't understand why. In the watch window I can do <code>account.features.isEmailEnabled</code> and it shows true and says its a boolean. But if I try to get at this value using the approach above and pass in <code>isEmailEnabled</code> as the <code>featureNameAsString</code> I just get null.</p> <p>Can someone please tell me what I may be doing wrong and what's a good approach, without it being too complex?</p> <p>I am working with ASP.NET under the 4.5.1 framework.</p>
19,139,499
1
0
null
2013-10-02 14:28:17.653 UTC
8
2013-10-02 14:31:14.87 UTC
2013-10-02 14:30:20.493 UTC
null
1,043,380
null
2,838,966
null
1
52
c#|asp.net|oop|dynamic|reflection
45,893
<p><code>ExpandoObject</code> provides access both via <code>dynamic</code> and via <code>IDictionary&lt;string,object&gt;</code> - so you could just use the dictionary API:</p> <pre><code>var byName = (IDictionary&lt;string,object&gt;)account.features; bool val = (bool)byName["isEmailEnabled"]; </code></pre> <p>Or if the name is fixed, just:</p> <pre><code>bool val = ((dynamic)account).features.isEmailEnabled; </code></pre>
29,271,440
Registering packages in Go without cyclic dependency
<p>I have a central package that provides several interfaces that other packages are dependent on (let us call one <code>Client</code>). Those other packages, provide several implementations of those first interfaces (<code>UDPClient</code>, <code>TCPClient</code>). I instantiate a <code>Client</code> by calling <code>NewClient</code> in the central package, and it selects and invokes the appropriate client implementation from one of the dependent packages.</p> <p>This falls apart when I want to tell the central package about those other packages, so it knows what clients it can create. Those dependent client implementations also import the central package, creating a cyclic dependency which Go does not allow.</p> <p>What's the best way forward? I'd prefer not to mash all those implementations in a single package, and creating a separate registry package seems overkill. Currently I have each implementation register itself with the central package, but this requires that the user knows to import every implementation in every separate binary that makes use of client.</p> <pre><code>import ( _ udpclient _ tcpclient client ) </code></pre>
29,272,910
2
0
null
2015-03-26 05:05:20.977 UTC
12
2016-08-03 04:40:32.8 UTC
null
null
null
null
149,482
null
1
24
go|packaging|cyclic-dependency
3,198
<p>The standard library solves this problem in multiple ways:</p> <h2>1) Without a "Central" Registry</h2> <p>Example of this is the different hash algorithms. The <a href="http://golang.org/pkg/crypto/" rel="noreferrer"><code>crypto</code></a> package just defines the <a href="http://golang.org/pkg/crypto/#Hash" rel="noreferrer"><code>Hash</code></a> interface (the type and its methods). Concrete implementations are in different packages (actually subfolders but doesn't need to be) for example <a href="http://golang.org/pkg/crypto/md5/" rel="noreferrer"><code>crypto/md5</code></a> and <a href="http://golang.org/pkg/crypto/sha256/" rel="noreferrer"><code>crypto/sha256</code></a>.</p> <p>When you need a "hasher", you explicitly state which one you want and instantiate that one, e.g. </p> <pre><code>h1 := md5.New() h2 := sha256.New() </code></pre> <p>This is the simplest solution and it also gives you good separation: the <code>hash</code> package does not have to know or worry about implementations.</p> <p>This is the preferred solution if you know or you can decide which implementation you want prior.</p> <h2>2) With a "Central" Registry</h2> <p>This is basically your proposed solution. Implementations have to register themselves in some way (usually in a package <code>init()</code> function).</p> <p>An example of this is the <a href="http://golang.org/pkg/image/" rel="noreferrer"><code>image</code></a> package. The package defines the <a href="http://golang.org/pkg/image/#Image" rel="noreferrer"><code>Image</code></a> interface and several of its implementations. Different image formats are defined in different packages such as <a href="http://golang.org/pkg/image/gif/" rel="noreferrer"><code>image/gif</code></a>, <a href="http://golang.org/pkg/image/jpeg/" rel="noreferrer"><code>image/jpeg</code></a> and <a href="http://golang.org/pkg/image/png/" rel="noreferrer"><code>image/png</code></a>.</p> <p>The <code>image</code> package has a <a href="http://golang.org/pkg/image/" rel="noreferrer"><code>Decode()</code></a> function which decodes and returns an <a href="http://golang.org/pkg/image/#Image" rel="noreferrer"><code>Image</code></a> from the specified <a href="http://golang.org/pkg/io/#Reader" rel="noreferrer"><code>io.Reader</code></a>. Often it is unknown what type of image comes from the reader and so you can't use the decoder algorithm of a specific image format.</p> <p>In this case if we want the image decoding mechanism to be extensible, a registration is unavoidable. The cleanest to do this is in package <code>init()</code> functions which is triggered by specifying the blank identifier for the package name when importing.</p> <p>Note that this solution also gives you the possibility to use a specific implementation to decode an image, the concrete implementations also provide the <code>Decode()</code> function, for example <a href="http://golang.org/pkg/image/png/#Decode" rel="noreferrer"><code>png.Decode()</code></a>.</p> <hr> <p>So the best way?</p> <p>Depends on what your requirements are. If you know or you can decide which implementation you need, go with #1. If you can't decide or you don't know and you need extensibility, go with #2.</p> <p>...Or go with #3 presented below.</p> <h2>3) Proposing a 3rd Solution: "Custom" Registry</h2> <p>You can still have the convenience of the "central" registry with interface and implementations separated with the expense of "auto-extensibility".</p> <p>The idea is that you have the interface in package <code>pi</code>. You have implementations in package <code>pa</code>, <code>pb</code> etc.</p> <p>And you create a package <code>pf</code> which will have the "factory" methods you want, e.g. <code>pf.NewClient()</code>. The <code>pf</code> package can refer to packages <code>pa</code>, <code>pb</code>, <code>pi</code> without creating a circular dependency.</p>
32,134,451
Call function on scroll only once
<p>I got a question regarding a function that will be called if the object is within my screen. But when the object is within my screen the function is been called and a alert is been fired. But if I close the alert and scroll further down the event is called again. I do not want that. How can I solve that?</p> <p><a href="http://jsfiddle.net/jxk63rw5/1/">Working example</a></p> <p>My code so far:</p> <pre><code>&lt;div id="wrapper"&gt; scroll down to see the div &lt;/div&gt; &lt;div id="tester"&gt;&lt;/div&gt; </code></pre> <p><strong>JS</strong></p> <pre><code>$(window).on('scroll',function() { if (checkVisible($('#tester'))) { alert("Visible!!!") } else { // do nothing } }); function checkVisible( elm, eval ) { eval = eval || "object visible"; var viewportHeight = $(window).height(), // Viewport Height scrolltop = $(window).scrollTop(), // Scroll Top y = $(elm).offset().top, elementHeight = $(elm).height(); if (eval == "object visible") return ((y &lt; (viewportHeight + scrolltop)) &amp;&amp; (y &gt; (scrolltop - elementHeight))); if (eval == "above") return ((y &lt; (viewportHeight + scrolltop))); } </code></pre> <p>What I want is that the If function only will be called 1 time and not on every scroll if the object is visible.</p>
32,134,470
5
0
null
2015-08-21 07:15:47.72 UTC
4
2022-04-18 15:30:53.16 UTC
2015-08-21 07:43:26.09 UTC
null
462,627
null
1,976,975
null
1
15
javascript|jquery
41,603
<p>Try using <code>.one()</code>:</p> <pre><code>$(window).one('scroll',function() { // Stuff }); </code></pre> <p>Or, unlink the event inside:</p> <pre><code>$(window).on('scroll',function() { // After Stuff $(window).off('scroll'); }); </code></pre> <p>Guess you might <strong>need this code</strong>:</p> <pre><code>// this will check if element is in viewport function checkVisible(elm, eval) { eval = eval || &quot;object visible&quot;; var viewportHeight = $(window).height(), // Viewport Height scrolltop = $(window).scrollTop(), // Scroll Top y = $(elm).offset().top, elementHeight = $(elm).height(); if (eval == &quot;object visible&quot;) return y &lt; viewportHeight + scrolltop &amp;&amp; y &gt; scrolltop - elementHeight; if (eval == &quot;above&quot;) return y &lt; viewportHeight + scrolltop; } $(window).on(&quot;scroll&quot;, function () { if (checkVisible($(&quot;#tester&quot;))) { alert(&quot;Visible!!!&quot;); $(window).off(&quot;scroll&quot;); } else { // do nothing } }); </code></pre> <p><strong>Fiddle: <a href="http://jsfiddle.net/c68nz3q6/" rel="nofollow noreferrer">http://jsfiddle.net/c68nz3q6/</a></strong></p>
25,674,612
ubuntu 14.04, pip cannot upgrade matplotllib
<p>When I try to upgrade my matplotlib using pip, it outputs:</p> <pre class="lang-none prettyprint-override"><code>Downloading/unpacking matplotlib from https://pypi.python.org/packages/source/m/matplotlib/matplotlib-1.4.0.tar.gz#md5=1daf7f2123d94745feac1a30b210940c Downloading matplotlib-1.4.0.tar.gz (51.2MB): 51.2MB downloaded Running setup.py (path:/tmp/pip_build_root/matplotlib/setup.py) egg_info for package matplotlib ============================================================================ Edit setup.cfg to change the build options BUILDING MATPLOTLIB matplotlib: yes [1.4.0] python: yes [2.7.6 (default, Mar 22 2014, 22:59:38) [GCC 4.8.2]] platform: yes [linux2] REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [version 1.8.2] six: yes [using six version 1.7.3] dateutil: yes [using dateutil version 2.2] tornado: yes [using tornado version 4.0.1] pyparsing: yes [using pyparsing version 2.0.2] pycxx: yes [Couldn't import. Using local copy.] libagg: yes [pkg-config information for 'libagg' could not be found. Using local copy.] Traceback (most recent call last): File "&lt;string&gt;", line 17, in &lt;module&gt; File "/tmp/pip_build_root/matplotlib/setup.py", line 154, in &lt;module&gt; result = package.check() File "setupext.py", line 940, in check if 'No such file or directory\ngrep:' in version: TypeError: argument of type 'NoneType' is not iterable Complete output from command python setup.py egg_info: ============================================================================ Edit setup.cfg to change the build options BUILDING MATPLOTLIB matplotlib: yes [1.4.0] python: yes [2.7.6 (default, Mar 22 2014, 22:59:38) [GCC 4.8.2]] platform: yes [linux2] REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [version 1.8.2] six: yes [using six version 1.7.3] dateutil: yes [using dateutil version 2.2] tornado: yes [using tornado version 4.0.1] pyparsing: yes [using pyparsing version 2.0.2] pycxx: yes [Couldn't import. Using local copy.] libagg: yes [pkg-config information for 'libagg' could not be found. Using local copy.] Traceback (most recent call last): File "&lt;string&gt;", line 17, in &lt;module&gt; File "/tmp/pip_build_root/matplotlib/setup.py", line 154, in &lt;module&gt; result = package.check() File "setupext.py", line 940, in check if 'No such file or directory\ngrep:' in version: TypeError: argument of type 'NoneType' is not iterable ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_root/matplotlib Storing debug log for failure in /home/username/.pip/pip.log </code></pre> <p>In the tail of the log it says:</p> <pre><code>Exception information: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip-1.5.6-py2.7.egg/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip-1.5.6-py2.7.egg/pip/commands/install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/usr/local/lib/python2.7/dist-packages/pip-1.5.6-py2.7.egg/pip/req.py", line 1229, in prepare_files req_to_install.run_egg_info() File "/usr/local/lib/python2.7/dist-packages/pip-1.5.6-py2.7.egg/pip/req.py", line 325, in run_egg_info command_desc='python setup.py egg_info') File "/usr/local/lib/python2.7/dist-packages/pip-1.5.6-py2.7.egg/pip/util.py", line 697, in call_subprocess % (command_desc, proc.returncode, cwd)) InstallationError: Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_root/matplotlib </code></pre> <p>Why did it fail? Many thanks!</p>
25,695,462
9
2
null
2014-09-04 20:38:33.353 UTC
17
2018-09-28 19:18:19.41 UTC
2014-09-05 09:36:11.697 UTC
null
3,959,454
null
4,009,531
null
1
51
python|matplotlib|pip
40,530
<p>This is a known bug that has been fixed (<a href="https://github.com/matplotlib/matplotlib/pull/3414">https://github.com/matplotlib/matplotlib/pull/3414</a>) on master. </p> <p>The bug is in the handling of searching for a <a href="http://www.freetype.org/">freetype</a> installation. If you install the Linux package freetype-dev, you will avoid this bug and be able to compile <code>matplotlib</code>.</p> <pre><code>sudo apt-get install libfreetype6-dev </code></pre>
4,111,905
How do you have the code pause for a couple of seconds in android?
<p>Basically I need a pause (based on just a few seconds) to be put into one action so that the user can see what happens before the next action is taken. So for blackjack, when it's the dealer's turn and he decides to hit, he hits, a card is added, and then he decides what to do next. So before he decides on what to do next, I want the code to pause so it can be "seen" as to what the dealer is doing this way the dealer doesn't complete his actions in less than a second and the player only sees the results. </p> <p>Thanks in advance!</p> <p>I should note I have tried using wait(insert number here); but i am told by eclipse that it causes a stack interception error or something of the sort and throws an exception, thus doing nothing : (</p> <p>Well this is interesting, (the way I've programed the things is "interesting" to say the least) I did the Thread.sleep(5000) and threw it under a try catch, it does sleep for 5 seconds and then continues doing the code. However my updates to views don't show until after I press a button(Is really hating event driven programming). </p>
4,114,569
1
0
null
2010-11-06 04:34:00.7 UTC
18
2010-11-06 18:42:39.75 UTC
2010-11-06 13:01:18.343 UTC
null
487,645
null
487,645
null
1
40
java|android|time|wait
87,830
<p>Learning to think in terms of events is indeed the key here. You can do it. :)</p> <p>The first rule is: never stall the UI thread. The UI thread is responsible for keeping your app feeling responsive. Any work you do there should not block; do what you need to do and return as quickly as possible. Definitely avoid doing I/O on the UI thread. (There are some places where you can't really help it due to lifecycle requirements, for example saving app state in <code>onPause</code>.) If you <strong>ever</strong> call <code>Thread.sleep</code> on the UI thread you are doing it wrong.</p> <p>Android enforces this with the "Application not responding" (or "ANR") error that the user sees. Whenever you see this in an Android app it means the developer did something that caused the UI thread to stall for too long. If the device is really bogged down for some reason this error might not actually be the app developer's fault, but usually it means the app is doing something wrong.</p> <p>You can use this model to your advantage by posting your own events. This gives you an easy way to tell your app, "do this later." In Android the key to posting your own events is in the <a href="http://developer.android.com/reference/android/os/Handler.html" rel="noreferrer"><code>Handler</code></a> class. The method <a href="http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable,%20long)" rel="noreferrer"><code>postDelayed</code></a> lets you schedule a <a href="http://developer.android.com/reference/java/lang/Runnable.html" rel="noreferrer"><code>Runnable</code></a> that will be executed after a certain number of milliseconds.</p> <p>If you have an Activity that looks something like this:</p> <pre><code>public class MyActivity extends Activity { private Handler mHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler.postDelayed(new Runnable() { public void run() { doStuff(); } }, 5000); } private void doStuff() { Toast.makeText(this, "Delayed Toast!", Toast.LENGTH_SHORT).show(); } } </code></pre> <p>Then 5 seconds after the activity is created you will see the toast created in <code>doStuff</code>.</p> <p>If you're writing a custom <code>View</code> it's even easier. Views have their own <a href="http://developer.android.com/reference/android/view/View.html#postDelayed(java.lang.Runnable,%20long)" rel="noreferrer"><code>postDelayed</code></a> method that will get everything posted to the correct <code>Handler</code> and you don't need to create your own.</p> <p>The second rule is: Views should <strong>only</strong> be modified on the UI thread. Those exceptions you're getting and ignoring mean something went wrong and if you ignore them your app will probably start misbehaving in interesting ways. If your app does most of its work in other threads you can <a href="http://developer.android.com/reference/android/view/View.html#post(java.lang.Runnable)" rel="noreferrer"><code>post</code></a> events directly to the view you want to modify so that the modifications will run correctly.</p> <p>If you have a reference to your <code>Activity</code> from that part of your code you can also use <a href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)" rel="noreferrer"><code>Activity#runOnUIThread</code></a>, which does exactly what the name implies. You might prefer this approach if posting to a single view doesn't really make sense in context.</p> <p>As for updates to views not appearing until you hit a button, what kind of views are these? Are they custom views that are drawing these updates? If so, are you remembering to call <a href="http://developer.android.com/reference/android/view/View.html#invalidate()" rel="noreferrer"><code>invalidate</code></a> after data changes to trigger the redraw? Views only redraw themselves after they have been invalidated.</p>
4,348,003
Using environment variable in a file path
<p>I've got an environment variable set that points to a specific folder (call it MYFOLDER for example). When typing in <code>%MYFOLDER%\SubFolder</code> into windows explorer the subfolder appears. However, when I pass <code>SelectedPath = @"%MYFOLDER%\SubFolder";</code> to a <code>FolderBrowserDialog</code>, it doesn't work.</p> <p>I tried using <code>Path.GetFullPath(..)</code>, but this seems to return the bin folder of the executable (while debugging in VS) with %MYFOLDER% on the end, instead of the path I'd expect.</p> <p>Anyone know how to get it to use the environment variable properly?</p>
4,348,030
1
0
null
2010-12-03 17:09:23.83 UTC
9
2016-04-02 07:42:35.787 UTC
null
null
null
null
283,505
null
1
84
c#|path|environment-variables|folderbrowserdialog
46,926
<p>Expand it first:</p> <pre><code>string path = Environment.ExpandEnvironmentVariables(value); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/system.environment.expandenvironmentvariables.aspx">http://msdn.microsoft.com/en-us/library/system.environment.expandenvironmentvariables.aspx</a></p>
54,954,385
React useEffect causing: Can't perform a React state update on an unmounted component
<p>When fetching data I'm getting: Can't perform a React state update on an unmounted component. The app still works, but react is suggesting I might be causing a memory leak.</p> <blockquote> <p>This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.&quot;</p> </blockquote> <p>Why do I keep getting this warning?</p> <p>I tried researching these solutions:</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal</a></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/AbortController</a></p> <p>but this still was giving me the warning.</p> <pre><code>const ArtistProfile = props =&gt; { const [artistData, setArtistData] = useState(null) const token = props.spotifyAPI.user_token const fetchData = () =&gt; { const id = window.location.pathname.split(&quot;/&quot;).pop() console.log(id) props.spotifyAPI.getArtistProfile(id, [&quot;album&quot;], &quot;US&quot;, 10) .then(data =&gt; {setArtistData(data)}) } useEffect(() =&gt; { fetchData() return () =&gt; { props.spotifyAPI.cancelRequest() } }, []) return ( &lt;ArtistProfileContainer&gt; &lt;AlbumContainer&gt; {artistData ? artistData.artistAlbums.items.map(album =&gt; { return ( &lt;AlbumTag image={album.images[0].url} name={album.name} artists={album.artists} key={album.id} /&gt; ) }) : null} &lt;/AlbumContainer&gt; &lt;/ArtistProfileContainer&gt; ) } </code></pre> <p><strong>Edit:</strong></p> <p>In my api file I added an <code>AbortController()</code> and used a <code>signal</code> so I can cancel a request.</p> <pre><code>export function spotifyAPI() { const controller = new AbortController() const signal = controller.signal // code ... this.getArtist = (id) =&gt; { return ( fetch( `https://api.spotify.com/v1/artists/${id}`, { headers: {&quot;Authorization&quot;: &quot;Bearer &quot; + this.user_token} }, {signal}) .then(response =&gt; { return checkServerStat(response.status, response.json()) }) ) } // code ... // this is my cancel method this.cancelRequest = () =&gt; controller.abort() } </code></pre> <p>My <code>spotify.getArtistProfile()</code> looks like this</p> <pre><code>this.getArtistProfile = (id,includeGroups,market,limit,offset) =&gt; { return Promise.all([ this.getArtist(id), this.getArtistAlbums(id,includeGroups,market,limit,offset), this.getArtistTopTracks(id,market) ]) .then(response =&gt; { return ({ artist: response[0], artistAlbums: response[1], artistTopTracks: response[2] }) }) } </code></pre> <p>but because my signal is used for individual api calls that are resolved in a <code>Promise.all</code> I can't <code>abort()</code> that promise so I will always be setting the state.</p>
54,964,237
19
4
null
2019-03-02 01:25:18.653 UTC
49
2022-07-09 05:34:41.757 UTC
2022-03-15 10:15:43.023 UTC
null
3,689,450
null
9,745,881
null
1
158
javascript|reactjs|react-hooks|fetch-api
367,435
<p>Sharing the <code>AbortController</code> between the <code>fetch()</code> requests is the right approach.<br> When <strong><em>any</em></strong> of the <code>Promise</code>s are aborted, <code>Promise.all()</code> will reject with <code>AbortError</code>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Component(props) { const [fetched, setFetched] = React.useState(false); React.useEffect(() =&gt; { const ac = new AbortController(); Promise.all([ fetch('http://placekitten.com/1000/1000', {signal: ac.signal}), fetch('http://placekitten.com/2000/2000', {signal: ac.signal}) ]).then(() =&gt; setFetched(true)) .catch(ex =&gt; console.error(ex)); return () =&gt; ac.abort(); // Abort both fetches on unmount }, []); return fetched; } const main = document.querySelector('main'); ReactDOM.render(React.createElement(Component), main); setTimeout(() =&gt; ReactDOM.unmountComponentAtNode(main), 1); // Unmount after 1ms</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="//cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.development.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.development.js"&gt;&lt;/script&gt; &lt;main&gt;&lt;/main&gt;</code></pre> </div> </div> </p>
25,207,703
Instance v state variables in react.js
<p>In react.js, is it better to store a timeout reference as an instance variable (this.timeout) or a state variable (this.state.timeout)?</p> <pre><code>React.createClass({ handleEnter: function () { // Open a new one after a delay var self = this; this.timeout = setTimeout(function () { self.openWidget(); }, DELAY); }, handleLeave: function () { // Clear the timeout for opening the widget clearTimeout(this.timeout); } ... }) </code></pre> <p>or</p> <pre><code>React.createClass({ handleEnter: function () { // Open a new one after a delay var self = this; this.state.timeout = setTimeout(function () { self.openWidget(); }, DELAY); }, handleLeave: function () { // Clear the timeout for opening the widget clearTimeout(this.state.timeout); } ... }) </code></pre> <p>both of these approaches work. I just want to know the reasons for using one over the other.</p>
25,208,809
2
3
null
2014-08-08 16:09:36.017 UTC
20
2017-10-05 18:12:02.8 UTC
2014-08-08 16:10:29.673 UTC
null
903,790
null
3,179,115
null
1
126
javascript|reactjs
57,051
<p>I suggest storing it on the instance but not in its <code>state</code>. Whenever <code>state</code> is updated (which should only be done by <a href="https://reactjs.org/docs/react-component.html#setstate" rel="noreferrer"><code>setState</code></a> as suggested in a comment), React calls <code>render</code> and makes any necessary changes to the real DOM.</p> <p>Because the value of <code>timeout</code> has no effect on the rendering of your component, it shouldn't live in <code>state</code>. Putting it there would cause unnecessary calls to <code>render</code>.</p>
39,470,412
Last row in column VBA
<p>I wrote a short VBA code to automate stuff.<br/> A short snippet is as follows:</p> <pre><code>Sub TEST() Rows("1:2").Select Selection.Delete Shift:=xlUp Range("A1").Select ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$O$148"), , xlYes).Name = _ "Table2" End Sub </code></pre> <p>However, every Excel file differs with regards to the number of rows. Now when I recorded this macro it just takes the range of $A$1:$O$148. How can I adjust this part so that it automatically recognizes the last row and/or range?</p> <p>I already tried:</p> <pre><code>.Range("A1").SpecialCells(xlCellTypeLastCell).Row </code></pre> <p>Instead of:</p> <pre><code>Range("$A$1:$O$148") </code></pre> <p>Thanks in advance!</p>
39,470,485
7
2
null
2016-09-13 12:42:35.5 UTC
2
2017-12-19 17:31:45.513 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
6,555,655
null
1
2
excel|vba
62,122
<p>This is the way I do it and I'm guessing this is a duplicate, but you can mimic hitting <code>End-Up</code> from a row well below your used range with</p> <pre><code>finalRow = Range("A65000").End(xlup).Row </code></pre> <p>then you can do</p> <pre><code>ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$O$" &amp; finalRow &amp; ""), , xlYes).Name = _ "Table2" </code></pre>
39,779,744
After installing anaconda - command not found: jupyter
<p>I have installed anaconda on my MAC laptop, and tried to run jupyter notebook to install it, but I get error jupyter command not found.</p>
39,779,791
13
2
null
2016-09-29 20:48:22.807 UTC
7
2021-10-25 17:11:46.297 UTC
2016-09-29 20:53:16.837 UTC
null
459,745
null
4,592,083
null
1
42
python|anaconda|jupyter-notebook
85,707
<p>You need to activate your conda environment (<code>source bin/activate</code>) and then do</p> <pre><code>$ pip install jupyter # Alternatively, you can do `conda install jupyter` $ jupyter notebook # to actually run the notebook server </code></pre>
69,867,669
Is there way in ggplot2 to place text on a curved path?
<p>Is there a way to put text along a density line, or for that matter, any path, in ggplot2? By that, I mean either once as a label, in this style of xkcd: <a href="https://xkcd.com/1835/" rel="noreferrer">1835</a>, <a href="https://xkcd.com/1950/" rel="noreferrer">1950</a> (middle panel), <a href="https://xkcd.com/1392/" rel="noreferrer">1392</a>, or <a href="https://xkcd.com/2234/" rel="noreferrer">2234</a> (middle panel). Alternatively, is there a way to have the line be repeating text, such as <a href="https://xkcd.com/930/" rel="noreferrer">this xkcd #930</a> ? My apologies for all the xkcd, I'm not sure what these styles are called, and it's the only place I can think of that I've seen this before to differentiate areas in this way.</p> <p>Note: I'm <em>not</em> talking about <a href="https://stackoverflow.com/questions/12675147/how-can-we-make-xkcd-style-graphs">the hand-drawn xkcd style</a>, nor <a href="https://stackoverflow.com/questions/57381627/add-text-labels-at-the-top-of-density-plots-to-label-the-different-groups">putting flat labels at the top</a></p> <p>I know I can place a straight/flat piece of text, such as via <code>annotate</code> or <code>geom_text</code>, but I'm curious about bending such text so it appears to be along the curve of the data.</p> <p>I'm also curious if there is a name for this style of text-along-line?</p> <p>Example ggplot2 graph using <code>annotate(...)</code>:</p> <p><a href="https://i.stack.imgur.com/Qf9eu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Qf9eu.png" alt="ggplot graph with horizontal text" /></a></p> <p>Above example graph modified with curved text in Inkscape:</p> <p><a href="https://i.stack.imgur.com/bXFLW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bXFLW.png" alt="modified version of first graph with text following curved paths" /></a></p> <hr /> <p>Edit: Here's the data for the first two trial runs in March and April, as requested:</p> <pre class="lang-r prettyprint-override"><code>df &lt;- data.frame( monthly_run = c('March', 'March', 'March', 'March', 'March', 'March', 'March', 'March', 'March', 'March', 'March', 'March', 'March', 'March', 'April', 'April', 'April', 'April', 'April', 'April', 'April', 'April', 'April', 'April', 'April', 'April', 'April', 'April'), duration = c(36, 44, 45, 48, 50, 50, 51, 54, 55, 57, 60, 60, 60, 60, 30, 40, 44, 47, 47, 47, 53, 53, 54, 55, 56, 57, 69, 77) ) ggplot(df, aes(x = duration, group = monthly_run, color = monthly_run)) + geom_density() + theme_minimal()` </code></pre>
70,851,442
2
2
null
2021-11-06 20:28:48.527 UTC
11
2022-02-02 10:17:54.78 UTC
2022-02-02 10:17:54.78 UTC
null
12,500,315
null
1,674,940
null
1
30
r|ggplot2|data-visualization|visualization
1,256
<p>In the end, this question prompted Teun van den Brand (@teunbrand) and I to develop the <code>geomtextpath</code> package, which is now on CRAN.</p> <p>So now the question could be answered much more directly and simply:</p> <pre class="lang-r prettyprint-override"><code>library(geomtextpath) ggplot(df, aes(x = duration, color = monthly_run)) + geom_textdensity(aes(label = monthly_run, hjust = monthly_run, vjust = monthly_run), size = 6) + scale_hjust_manual(values = c(0.4, 0.55)) + scale_vjust_manual(values = c(1.1, -0.2)) + scale_y_continuous(limits = c(0, 0.06)) + theme_minimal() + theme(legend.position = &quot;none&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/NvZUW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NvZUW.png" alt="enter image description here" /></a></p>
19,934,248
NameError: name 'datetime' is not defined
<p>I'm teaching myself Python and was just "exploring". Google says that datetime is a global variable but when I try to find todays date in the terminal I receive the NameError in the question title?</p> <pre><code>mynames-MacBook:pythonhard myname$ python Enthought Canopy Python 2.7.3 | 64-bit | (default, Aug 8 2013, 05:37:06) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; date = datetime.date.today() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'datetime' is not defined &gt;&gt;&gt; </code></pre>
19,934,262
2
1
null
2013-11-12 16:14:02.163 UTC
12
2021-03-27 19:18:55.097 UTC
null
null
null
null
1,024,586
null
1
68
python|datetime
211,448
<p>You need to import the module <a href="http://docs.python.org/2/library/datetime.html" rel="noreferrer"><code>datetime</code></a> first:</p> <pre><code>&gt;&gt;&gt; import datetime </code></pre> <p>After that it works:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; date = datetime.date.today() &gt;&gt;&gt; date datetime.date(2013, 11, 12) </code></pre>
6,981,467
Jena/ARQ: Difference between Model, Graph and DataSet
<p>I'm starting to work with the Jena Engine and I think I got a grasp of what semantics are. However I'm having a hard time understanding the different ways to represent a bunch of triples in Jena and ARQ:</p> <ul> <li>The first thing you stumble upon when starting is <code>Model</code> and the documentation says its Jenas name for RDF graphs.</li> <li>However there is also <code>Graph</code> which seemed to be the necessary tool when I want to query a union of models, however it does not seem to share a common interface with <code>Model</code>, although one can get the <code>Graph</code> out of a <code>Model</code></li> <li>Then there is <code>DataSet</code> in ARQ, which also seems to be a collection of triples of some sort.</li> </ul> <p>Sure, afer some looking around in the API, I found ways to somehow convert from one into another. However I suspect there is more to it than 3 different interfaces for the same thing.</p> <p>So, question is: What are the key design differences between these three? When should I use which one ? Especially: When I want to hold individual bunches of triples but query them as one big bunch (union), which of these datastructures should I use (and why)? Also, do I "loose" anything when "converting" from one into another (e.g. does <code>model.getGraph()</code> contain less information in some way than <code>model</code>)?</p>
6,982,965
2
0
null
2011-08-08 11:32:07.643 UTC
16
2011-08-08 14:13:19.153 UTC
null
null
null
null
612,889
null
1
34
java|jena
7,973
<p>Jena is divided into an API, for application developers, and an SPI for systems developers, such as people making storage engines, reasoners etc.</p> <p><code>DataSet</code>, <code>Model</code>, <code>Statement</code>, <code>Resource</code> and <code>Literal</code> are API interfaces and provide many conveniences for application developers.</p> <p><code>DataSetGraph</code>, <code>Graph</code>, <code>Triple</code>, <code>Node</code> are SPI interfaces. They're pretty spartan and simple to implement (as you'd hope if you've got to implement the things).</p> <p>The wide variety of API operations all resolve down to SPI calls. To give an example the <a href="http://jena.sourceforge.net/javadoc/com/hp/hpl/jena/rdf/model/Model.html" rel="noreferrer"><code>Model</code> interface</a> has four different <code>contains</code> methods. Internally each results in a call:</p> <pre><code>Graph#contains(Node, Node, Node) </code></pre> <p>such as</p> <pre><code>graph.contains(nodeS, nodeP, nodeO); // model.contains(s, p, o) or model.contains(statement) graph.contains(nodeS, nodeP, Node.ANY); // model.contains(s, p) </code></pre> <p>Concerning your question about losing information, with <code>Model</code> and <code>Graph</code> you don't (as far as I recall). The more interesting case is <code>Resource</code> versus <code>Node</code>. <code>Resources</code> know which model they belong to, so you can (in the api) write <code>resource.addProperty(...)</code> which becomes a <code>Graph#add</code> eventually. <code>Node</code> has no such convenience, and is not associated with a particular <code>Graph</code>. Hence <code>Resource#asNode</code> is lossy.</p> <p>Finally:</p> <blockquote> <p>When I want to hold individual bunches of triples but query them as one big bunch (union), which of these datastructures should I use (and why)?</p> </blockquote> <p>You're clearly a normal user, so you want the API. You want to store triples, so use <code>Model</code>. Now you want to query the models as one union: You could:</p> <ul> <li><code>Model#union()</code> everything, which will copy all the triples into a new model.</li> <li><code>ModelFactory.createUnion()</code> everything, which will create a dynamic union (i.e. no copying).</li> <li>Store your models as named models in a TDB or SDB dataset store, and use the <code>unionDefaultGraph</code> option.</li> </ul> <p>The last of these works best for large numbers of models, and large model, but is a little more involved to set up.</p>
7,407,273
Why is the conditional operator right associative?
<p>I can understand why the assignment operator is right associative. It makes sense that when</p> <pre><code>x = 4 + 3 </code></pre> <p>is evaluated, that 4 and 3 are added before being assigned to x.</p> <p>I am unclear as to how <code>?:</code> would benefit from being right associative. Does it only matter when two <code>?:</code>s were used like this</p> <pre><code>z = (a == b ? a : b ? c : d); </code></pre> <p>Then it is evaluated like this:</p> <pre><code>z = (a == b ? a : (b ? c : d)); </code></pre> <p>Surely it would make more sense to evaluate from left to right?</p>
7,407,350
3
4
null
2011-09-13 19:22:33.483 UTC
13
2018-11-20 17:45:37.98 UTC
2018-11-20 17:45:37.98 UTC
null
7,813,604
null
619,818
null
1
41
c|conditional-operator
20,253
<p>If it evaluated from left to right, it'd look like this:</p> <pre><code>z = ((a == b ? a : b) ? c : d); </code></pre> <p>That is, it would use the result of the first conditional (<code>a</code> or <code>b</code>) as the boolean condition of the second conditional. That doesn't make much sense: that's like saying:</p> <pre><code>int z, tmp; /* first conditional */ if(a == b) tmp = a; else tmp = b; /* second conditional */ if(tmp) z = c; else z = d; </code></pre> <p>While perhaps one day you'll want to do exactly this, it's far more likely that each <code>?:</code> that follows is meant to add more conditions, like <code>if</code> / <code>else if</code> / <code>else if</code> / <code>else</code>, which is what the right-associative binding yields:</p> <pre><code>int z; /* first conditional */ if(a == b) z = a; else /* second conditional */ if(b) z = c; else z = d; </code></pre>
7,672,018
JavaScript this.checked
<p>In JavaScript, if we write the following for example:</p> <pre><code>var c = this.checked; </code></pre> <p>What is <code>checked</code> here? Is it just a <strong>state</strong> that tells us if a checkbox for example is checked or <em>not</em>? So, can we use it to check that the checkbox is also not checked?</p>
7,672,041
4
1
null
2011-10-06 08:45:09.133 UTC
2
2013-03-27 19:38:24.313 UTC
2013-03-27 19:38:24.313 UTC
null
1,348,195
null
588,855
null
1
12
javascript
73,889
<blockquote> <p>Is it just a state that tells us if a checkbox for example is checked or not? So, can we use it to check that the checkbox is also not checked?</p> </blockquote> <p>Yes and yes</p>
24,092,414
iOS Floating Video Window like Youtube App
<p>Does anyone know of any existing library, or any techniques on how to get the same effect as is found on the Youtube App.</p> <p>The video can be "minimised" and hovers at the bottom of the screen - which can then be swiped to close or touched to re-maximised.</p> <p>See: </p> <p>Video Playing Normally: <a href="https://www.dropbox.com/s/o8c1ntfkkp4pc4q/2014-06-07%2001.19.20.png">https://www.dropbox.com/s/o8c1ntfkkp4pc4q/2014-06-07%2001.19.20.png</a></p> <p>Video Minimized: <a href="https://www.dropbox.com/s/w0syp3infu21g08/2014-06-07%2001.19.27.png">https://www.dropbox.com/s/w0syp3infu21g08/2014-06-07%2001.19.27.png</a></p> <p>(Notice how the video is now in a small floating window on the bottom right of the screen).</p> <p>Anyone have any idea how this was achieved, and if there are any existing tutorials or libraries that can be used to get this same effect?</p>
24,107,949
4
2
null
2014-06-07 00:23:02.543 UTC
16
2017-06-08 08:38:19.813 UTC
2014-06-08 11:30:37.137 UTC
null
584,430
null
584,430
null
1
13
ios|objective-c|video
14,593
<p>It sounded fun, so I looked at youtube. The video looks like it plays in a 16:9 box at the top, with a "see also" list below. When user minimizes the video, the player drops to the lower right corner along with the "see also" view. At the same time, that "see also" view fades to transparent.</p> <p>1) Setup the views like that and created outlets. Here's what it looks like in IB. (Note that the two containers are siblings)</p> <p><img src="https://i.stack.imgur.com/zKuDL.png" alt="enter image description here"></p> <p>2) Give the video view a swipe up and swipe down gesture recognizer:</p> <pre><code>@interface ViewController () @property (weak, nonatomic) IBOutlet UIView *tallMpContainer; @property (weak, nonatomic) IBOutlet UIView *mpContainer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeDown:)]; UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeUp:)]; swipeUp.direction = UISwipeGestureRecognizerDirectionUp; swipeDown.direction = UISwipeGestureRecognizerDirectionDown; [self.mpContainer addGestureRecognizer:swipeUp]; [self.mpContainer addGestureRecognizer:swipeDown]; } - (void)swipeDown:(UIGestureRecognizer *)gr { [self minimizeMp:YES animated:YES]; } - (void)swipeUp:(UIGestureRecognizer *)gr { [self minimizeMp:NO animated:YES]; } </code></pre> <p>3) And then a method to know about the current state, and change the current state.</p> <pre><code>- (BOOL)mpIsMinimized { return self.tallMpContainer.frame.origin.y &gt; 0; } - (void)minimizeMp:(BOOL)minimized animated:(BOOL)animated { if ([self mpIsMinimized] == minimized) return; CGRect tallContainerFrame, containerFrame; CGFloat tallContainerAlpha; if (minimized) { CGFloat mpWidth = 160; CGFloat mpHeight = 90; // 160:90 == 16:9 CGFloat x = 320-mpWidth; CGFloat y = self.view.bounds.size.height - mpHeight; tallContainerFrame = CGRectMake(x, y, 320, self.view.bounds.size.height); containerFrame = CGRectMake(x, y, mpWidth, mpHeight); tallContainerAlpha = 0.0; } else { tallContainerFrame = self.view.bounds; containerFrame = CGRectMake(0, 0, 320, 180); tallContainerAlpha = 1.0; } NSTimeInterval duration = (animated)? 0.5 : 0.0; [UIView animateWithDuration:duration animations:^{ self.tallMpContainer.frame = tallContainerFrame; self.mpContainer.frame = containerFrame; self.tallMpContainer.alpha = tallContainerAlpha; }]; } </code></pre> <p>I didn't add video to this project, but it should just drop in. Make the mpContainer the parent view of the MPMoviePlayerController's view and it should look pretty cool.</p>
1,757,370
Recursive same-table query in SQL Server 2008
<p>I have the following table in a SQL Server 2008 database:</p> <pre><code>Id Name ParentFolder -- ---- ------------ 1 Europe NULL 2 Asia NULL 3 Germany 1 4 UK 1 5 China 2 6 India 2 7 Scotland 4 </code></pre> <p>ParentFolder is a FK to Id in the same table. I would like to create a view that results in something like this:</p> <pre><code>Id Name FullName -- ---- -------- 1 Europe Europe 2 Asia Asia 3 Germany Europe/Germany 4 UK Europe/UK 5 China Asia/China 6 India Asia/India 7 Scotland Europe/UK/Scotland </code></pre> <p>As you can see, I need to build the FullName values by recursively using the ParentFolder relationship an arbitrary number of times until a NULL is found.</p> <p><strong>Edit.</strong> Each row in the table "knows" what other row is its parent, but does not know its absolute position in the hierarchy. For this reason, a lineage system where each row stores its absolute location in the hierarchy tree would not be appropriate.</p> <p>I am aware of the hierarchyid feature of SQL Server 2008 but, as far as I know, it only works with a fixed number of recursion levels. In my case, however, you never know how many levels you will find, and they may change from row to row.</p> <p>I have also seen similar questions to this posted here. However, I think that nobody asked about building "paths" for each row in a table. Sorry if I missed it.</p> <p>Many thanks.</p>
1,758,797
4
0
null
2009-11-18 16:45:09.61 UTC
15
2013-01-29 20:53:17.48 UTC
2009-11-18 17:01:51.26 UTC
null
210,818
null
210,818
null
1
14
sql-server-2008|recursion
34,572
<p>Try this one:</p> <pre><code> DECLARE @tbl TABLE ( Id INT ,[Name] VARCHAR(20) ,ParentId INT ) INSERT INTO @tbl( Id, Name, ParentId ) VALUES (1, 'Europe', NULL) ,(2, 'Asia', NULL) ,(3, 'Germany', 1) ,(4, 'UK', 1) ,(5, 'China', 2) ,(6, 'India', 2) ,(7, 'Scotland', 4) ,(8, 'Edinburgh', 7) ,(9, 'Leith', 8) ; WITH abcd AS ( -- anchor SELECT id, [Name], ParentID, CAST(([Name]) AS VARCHAR(1000)) AS "Path" FROM @tbl WHERE ParentId IS NULL UNION ALL --recursive member SELECT t.id, t.[Name], t.ParentID, CAST((a.path + '/' + t.Name) AS VARCHAR(1000)) AS "Path" FROM @tbl AS t JOIN abcd AS a ON t.ParentId = a.id ) SELECT * FROM abcd </code></pre>
1,616,957
How do you roll back (reset) a Git repository to a particular commit?
<p>I cloned a Git repository and then tried to roll it back to a particular commit early on in the development process. Everything that was added to the repository after that point is unimportant to me so I want to omit all subsequent changes from my local source code.</p> <p>However, when I try to roll back in the GUI tool it doesn't update my local file system - I always end up with the latest source code for the project.</p> <p>What's the correct way to just get the source for a repository as of a particular commit in the project's history and omit all later updates?</p>
1,616,959
4
1
null
2009-10-24 04:22:27.31 UTC
297
2017-08-18 23:59:28.32 UTC
2014-06-29 00:06:47 UTC
user456814
null
Lee Tang
null
null
1
786
git
755,229
<pre><code>git reset --hard &lt;tag/branch/commit id&gt; </code></pre> <hr> <p><strong><em>Notes:</em></strong></p> <ul> <li><p><code>git reset</code> without the <code>--hard</code> option resets the commit history, but not the files. With the <code>--hard</code> option the files in working tree are also reset. (<a href="https://stackoverflow.com/users/964/kauppi">credited user</a>)</p></li> <li><p>If you wish to commit that state so that the remote repository also points to the rolled back commit do: <code>git push &lt;reponame&gt; -f</code> (<a href="https://stackoverflow.com/users/96806/mariusz-nowak">credited user</a>)</p></li> </ul>
2,036,182
boost, shared ptr Vs weak ptr? Which to use when?
<p>In my current project I am using <code>boost::shared_ptr</code> quite extensively.</p> <p>Recently my fellow team mates have also started using <code>weak_ptr</code>. I don't know which one to use and when.</p> <p>Apart from this, what should I do if I want to convert <code>weak_ptr</code> to <code>shared_ptr</code>. Does putting a lock on <code>weak_ptr</code> to create a <code>shared_ptr</code> affect my code in other thread?</p>
2,036,298
4
0
null
2010-01-10 05:13:57.017 UTC
24
2017-07-19 00:01:42.627 UTC
2016-01-15 14:34:56.427 UTC
null
1,052,126
null
993,179
null
1
45
c++|memory-management|boost|shared-ptr|weak-ptr
23,917
<p>In general and summary, </p> <p><em>Strong pointers</em> guarantee their own validity. Use them, for example, when:</p> <ul> <li>You own the object being pointed at; you create it and destroy it</li> <li>You do not have defined behavior if the object doesn't exist</li> <li>You need to enforce that the object exists.</li> </ul> <p><em>Weak pointers</em> guarantee <em>knowing</em> their own validity. Use them, for example, when:</p> <ul> <li>You access it, but it's not yours.</li> <li>You have defined behavior if the object doesn't exist </li> </ul> <p>Lock() on a weak pointer returns a strong pointer; this is how you access the weak pointer. If the object is no longer valid (it's been deleted, etc), then the strong pointer will be NULL, otherwise, it will point at the object. You will need to check this. </p> <p>It's set up this way so that you cannot accidentally delete the object while you're using it, because you've made a temporary (local) strong pointer, and thus garunteed the object's existence while that strong pointer remains. When you're done using the object, you generally let the strong pointer fall out of scope (or reassigning it), which then allows the object to be deleted. For multithreading, treat them with same care you treat other things that don't have built-in thread safety, noting that the guarantee I mentioned above <em>will</em> hold when multithreading. AFAIK they don't do anything special past that.</p> <p>The boost shared pointers also have garbage-collector like features, since when the last strong pointer to an object goes away or points somewhere else, the object gets deleted. </p> <p>There's also the performance and circular dependencies mentioned in the other answers.</p> <p>Fundamentally, I would say that the boost shared pointer library allows you to not mess up putting together a program, but it is no substitute for taking the time to properly design your pointers, object ownerships and lifetimes. If you have such a design, you can use the library to enforce it. If you don't have such a design, you're likely to run into different problems than before. </p>
10,485,582
What is the Proper Way to Destroy a Map Instance?
<p>I recently developed an html5 mobile application. The application was a single page where navigation hash change events replaced the entire DOM. One section of the application was a Google Map using API v3. Before the map div is removed from the DOM, I want to remove any event handlers/listeners and free up as much memory as possible as the user may not return to that section again.</p> <p>What is the best way to destroy a map instance?</p>
28,281,733
7
2
null
2012-05-07 16:23:37.417 UTC
23
2018-10-04 19:27:46.22 UTC
2012-05-07 16:56:54.13 UTC
null
531,644
null
1,211,524
null
1
97
javascript|google-maps-api-3
73,896
<p>The <a href="https://issuetracker.google.com/issues/35821412#comment32" rel="noreferrer">official answer</a> is you don't. Map instances in a single page application should be reused and not destroyed then recreated.</p> <p>For some single page applications, this may mean re-architecting the solution such that once a map is created it may be hidden or disconnected from the DOM, but it is never destroyed/recreated.</p>
14,153,988
How should I parse this xml string in python?
<p>My XML string is - </p> <pre><code>xmlData = """&lt;SMSResponse xmlns="http://example.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;Cancelled&gt;false&lt;/Cancelled&gt; &lt;MessageID&gt;00000000-0000-0000-0000-000000000000&lt;/MessageID&gt; &lt;Queued&gt;false&lt;/Queued&gt; &lt;SMSError&gt;NoError&lt;/SMSError&gt; &lt;SMSIncomingMessages i:nil="true"/&gt; &lt;Sent&gt;false&lt;/Sent&gt; &lt;SentDateTime&gt;0001-01-01T00:00:00&lt;/SentDateTime&gt; &lt;/SMSResponse&gt;""" </code></pre> <p>I am trying to parse and get the values of tags - Cancelled, MessageId, SMSError, etc. I am using python's <a href="http://docs.python.org/2/library/xml.etree.elementtree.html#module-xml.etree.ElementTree" rel="noreferrer">Elementtree</a> library. So far, I have tried things like - </p> <pre><code>root = ET.fromstring(xmlData) print root.find('Sent') // gives None for child in root: print chil.find('MessageId') // also gives None </code></pre> <p>Although, I am able to print the tags with - </p> <pre><code>for child in root: print child.tag //child.tag for the tag Cancelled is - {http://example.com}Cancelled </code></pre> <p>and their respective values with - </p> <pre><code>for child in root: print child.text </code></pre> <p>How do I get something like - </p> <pre><code>print child.Queued // will print false </code></pre> <p>Like in PHP we can access them with the root - </p> <pre><code>$xml = simplexml_load_string($data); $status = $xml-&gt;SMSError; </code></pre>
14,154,164
4
0
null
2013-01-04 09:00:08.267 UTC
4
2013-01-04 09:46:04.42 UTC
2013-01-04 09:06:10.283 UTC
null
1,637,867
null
1,637,867
null
1
8
python|xml|elementtree
54,112
<p>Your document has a namespace on it, you need to include the namespace when searching:</p> <pre class="lang-py prettyprint-override"><code>root = ET.fromstring(xmlData) print root.find('{http://example.com}Sent',) print root.find('{http://example.com}MessageID') </code></pre> <p>output:</p> <pre class="lang-py prettyprint-override"><code>&lt;Element '{http://example.com}Sent' at 0x1043e0690&gt; &lt;Element '{http://example.com}MessageID' at 0x1043e0350&gt; </code></pre> <p>The <code>find()</code> and <code>findall()</code> methods also take a namespace map; you can search for a arbitrary prefix, and the prefix will be looked up in that map, to save typing:</p> <pre class="lang-py prettyprint-override"><code>nsmap = {'n': 'http://example.com'} print root.find('n:Sent', namespaces=nsmap) print root.find('n:MessageID', namespaces=nsmap) </code></pre>
13,927,295
How to read a specific key-value pair from mongodb collection
<p>If I have a mongodb collection <code>users</code> like this:</p> <pre><code>{ "_id": 1, "name": { "first" : "John", "last" :"Backus" }, } </code></pre> <p>How do I retrieve <code>name.first</code> from this without providing <code>_id</code> or any other reference. Also, is it possible that pulling just the `name^ can give me the array of embedded keys (first and last in this case)? How can that be done?</p> <p><code>db.users.find({"name.first"})</code> didn't work for me, I got a:</p> <blockquote> <p>SyntaxError "missing: after property id (shell):1</p> </blockquote>
13,927,354
3
0
null
2012-12-18 06:11:13.653 UTC
3
2022-04-18 00:11:55.54 UTC
2017-06-26 23:07:56.717 UTC
null
5,025,116
null
1,244,442
null
1
9
mongodb|mongodb-query
43,104
<p>The first argument to <code>find()</code> is the query criteria whereas the second argument to the <code>find()</code> method is a projection, and it takes the form of a document with a list of fields for inclusion or exclusion from the result set. You can either specify the fields to include (e.g. <code>{ field: 1 }</code>) or specify the fields to exclude (e.g. <code>{ field: 0 }</code>). The <code>_id</code> field is implicitly included, unless explicitly excluded.</p> <p>In your case, db.users.find({name.first}) will give an error as it is expected to be a search criteria. </p> <p>To get the name json : <code>db.users.find({},{name:1</code>})</p> <p>If you want to fetch only name.first</p> <pre><code>db.users.find({},{"name.first":1}) </code></pre> <p>Mongodb Documentation link <a href="http://docs.mongodb.org/manual/core/read-operations/" rel="noreferrer">here</a></p>
13,838,884
How to Bind a Command in WPF
<p>Sometimes we used complex ways so many times, we forgot the simplest ways to do the task.</p> <p>I know how to do command binding, but i always use same approach. </p> <p>Create a class that implements ICommand interface and from the view model i create new instance of that class and binding works like a charm.</p> <p>This is the code that i used for command binding</p> <pre><code> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; testCommand = new MeCommand(processor); } ICommand testCommand; public ICommand test { get { return testCommand; } } public void processor() { MessageBox.Show("hello world"); } } public class MeCommand : ICommand { public delegate void ExecuteMethod(); private ExecuteMethod meth; public MeCommand(ExecuteMethod exec) { meth = exec; } public bool CanExecute(object parameter) { return false; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { meth(); } } </code></pre> <p>But i want to know the basic way to do this, no third party dll no new class creation. Do this simple command binding using a single class. Actual class implements from ICommand interface and do the work.</p>
13,839,449
6
0
null
2012-12-12 11:36:10.663 UTC
5
2016-07-27 00:02:20.747 UTC
2012-12-18 09:08:04.517 UTC
null
1,102,482
null
1,102,482
null
1
14
c#|wpf|icommand|commandbinding
60,671
<p><a href="http://msdn.microsoft.com/en-us/library/gg406140.aspx" rel="noreferrer">Prism</a> already provided <a href="http://msdn.microsoft.com/en-us/library/microsoft.practices.prism.commands(v=pandp.40).aspx" rel="noreferrer">Microsoft.Practices.Prism.Commands.DelegateCommand</a></p> <p>I'm not sure is it considered as 3rd party. At least it's official and documented on MSDN.</p> <p>Some native build-in commands such copy, paste implements ICommand interface. IMHO it following the Open(for extends)/Close(for changes) principle. so that we can implement our own command.</p> <hr> <h1>Update</h1> <p>As WPF Commanding documented <a href="http://msdn.microsoft.com/en-us/library/ms752308.aspx" rel="noreferrer">here</a>, an excerpt...</p> <blockquote> <p>WPF provides a set of predefined commands. such as Cut, BrowseBack and BrowseForward, Play, Stop, and Pause.</p> <p>If the commands in the command library classes do not meet your needs, then you can create your own commands. There are two ways to create a custom command. The first is to start from the ground up and implement the ICommand interface. The other way, and <strong>the more common approach</strong>, is to create a <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx" rel="noreferrer">RoutedCommand</a> or a <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.routeduicommand.aspx" rel="noreferrer">RoutedUICommand</a>.</p> </blockquote> <p>I've tried RoutedCommand model at the beginning and ended up with implementing ICommand.</p> <p><strong>sample XAML binding</strong></p> <pre><code>&lt;CommandBinding Command="{x:Static custom:Window1.CustomRoutedCommand}" Executed="ExecutedCustomCommand" CanExecute="CanExecuteCustomCommand" /&gt; </code></pre> <p>RoutedCommand is not different from RoutedEvent. this seems like a better button's 'Clicked' event handler. It serves the purpose: To separate app logic from View but require some attach DependencyProperty or code-behind. </p> <p>personally I feel more comfortable with just implement my ICommand.</p>
13,807,406
Entity Framework Many to many through containing object
<p>I was curious if it is possible to map an intermediate table through a containing object.</p> <pre><code>public class Subscriber : IEntity { [Key] public int Id { get; set; } public string Name { get; set; } private ChannelList _subscribedList { get; set; } public int NumSubscribedChannels { get { return _subscribedList.Count(); } } } public class HelpChannel : IEntity { [Key] public int Id { get; set; } public string name { get; set; } public string category { get; set; } public int group { get; set; } } </code></pre> <p>I need to have a subscriber table, channel table and an intermediate table to link a subscriber to his/her channels. </p> <p>Is it possible to map the list that is within the ChannelList object to the Subscriber Model? </p> <p>I figured that's probably not possible and that I would need to just have a private List for EF to map. But I wasn't sure if EF will do that for private variables. Will it?</p> <p>I'm hoping that is does because if it has to be public to maintain the encapsulation.</p>
13,810,766
1
4
null
2012-12-10 19:01:30.403 UTC
13
2012-12-10 22:58:03.183 UTC
null
null
null
null
1,028,843
null
1
15
c#|asp.net-mvc|entity-framework
19,742
<p>You can map private properties in EF code-first. <a href="http://blog.oneunicorn.com/2012/03/26/code-first-data-annotations-on-non-public-properties/">Here</a> is a nice description how to do it. In your case it is about the mapping of <code>Subscriber._subscribedList</code>. What you can't do is this (in the context's override of <code>OnModelCreating</code>):</p> <pre><code>modelBuilder.Entity&lt;Subscriber&gt;().HasMany(x =&gt; x._subscribedList); </code></pre> <p>It won't compile, because <code>_subscribedList</code> is private.</p> <p>What you can do is create a nested mapping class in <code>Subscriber</code>:</p> <pre><code>public class Subscriber : IEntity { ... private ICollection&lt;HelpChannel&gt; _subscribedList { get; set; } // ICollection! public class SubscriberMapper : EntityTypeConfiguration&lt;Subscriber&gt; { public SubscriberMapper() { HasMany(s =&gt; s._subscribedList); } } } </code></pre> <p>and in <code>OnModelCreating</code>:</p> <pre><code>modelBuilder.Configurations.Add(new Subscriber.SubscriberMapping()); </code></pre> <p>You may want to make <code>_subscribedList</code> protected virtual, to allow lazy loading. But it is even possible to do eager loading with <code>Include</code>:</p> <pre><code>context.Subscribers.Include("_subscribedList"); </code></pre>
14,289,421
How to use mmap in python when the whole file is too big
<p>I have a python script which read a file line by line and look if each line matches a regular expression.</p> <p>I would like to improve the performance of that script by using memory map the file before I search. I have looked into mmap example: <a href="http://docs.python.org/2/library/mmap.html">http://docs.python.org/2/library/mmap.html</a></p> <p>My question is how can I mmap a file when it is too big (15GB) for the memory of my machine (4GB)</p> <p>I read the file like this:</p> <pre><code>fi = open(log_file, 'r', buffering=10*1024*1024) for line in fi: //do somemthong fi.close() </code></pre> <p>Since I set the buffer to 10MB, in terms of performance, is it the same as I mmap 10MB of file?</p> <p>Thank you.</p>
14,289,444
2
2
null
2013-01-12 01:59:30.673 UTC
11
2016-04-04 23:12:42.447 UTC
2013-01-12 02:10:25.953 UTC
null
286,802
null
286,802
null
1
17
python
17,361
<p>First, the memory of your machine is irrelevant. It's the size of your process's <a href="http://en.wikipedia.org/wiki/Virtual_address_space" rel="noreferrer"><em>address space</em></a> that's relevant. With a 32-bit Python, this will be somewhere under 4GB. With a 64-bit Python, it will be more than enough.</p> <p>The reason for this is that <a href="http://en.wikipedia.org/wiki/Mmap" rel="noreferrer"><code>mmap</code></a> isn't about <a href="http://en.wikipedia.org/wiki/Memory-mapped_file" rel="noreferrer">mapping a file</a> into physical memory, but into <a href="http://en.wikipedia.org/wiki/Virtual_memory" rel="noreferrer"><em>virtual memory</em></a>. An <code>mmap</code>ped file becomes just like a special swap file for your program. Thinking about this can get a bit complicated, but the Wikipedia links above should help.</p> <p>So, the first answer is "use a 64-bit Python". But obviously that may not be applicable in your case.</p> <p>The obvious alternative is to map in the first 1GB, search that, unmap it, map in the next 1GB, etc. The way you do this is by specifying the <code>length</code> and <code>offset</code> parameters to the <code>mmap</code> method. For example:</p> <pre><code>m = mmap.mmap(f.fileno(), length=1024*1024*1024, offset=1536*1024*1024) </code></pre> <p>However, the regex you're searching for could be found half-way in the first 1GB, and half in the second. So, you need to use windowing—map in the first 1GB, search, unmap, then map in a partially-overlapping 1GB, etc.</p> <p>The question is, how much overlap do you need? If you know the maximum possible size of a match, you don't need anything more than that. And if you don't know… well, then there is no way to actually solve the problem without breaking up your regex—if that isn't obvious, imagine how you could possibly find a 2GB match in a single 1GB window.</p> <p>Answering your followup question:</p> <blockquote> <p>Since I set the buffer to 10MB, in terms of performance, is it the same as I mmap 10MB of file?</p> </blockquote> <p>As with any performance question, if it really matters, you need to test it, and if it doesn't, don't worry about it.</p> <p>If you want me to guess: I think <code>mmap</code> may be faster here, but only because (as J.F. Sebastian implied) looping and calling <code>re.match</code> 128K times as often may cause your code to be CPU-bound instead of IO-bound. But you could optimize that away without <code>mmap</code>, just by using <code>read</code>. So, would <code>mmap</code> be faster than <code>read</code>? Given the sizes involved, I'd expect the performance of <code>mmap</code> to be much faster on old Unix platforms, about the same on modern Unix platforms, and a bit slower on Windows. (You can still get large performance benefits out of <code>mmap</code> over <code>read</code> or <code>read</code>+<code>lseek</code> if you're using <code>madvise</code>, but that's not relevant here.) But really, that's just a guess.</p> <p>The most compelling reason to use <code>mmap</code> is usually that it's simpler than <code>read</code>-based code, not that it's faster. When you have to use windowing even with <code>mmap</code>, and when you don't need to do any seeking with <code>read</code>, this is less compelling, but still, if you try writing the code both ways, I'd expect your <code>mmap</code> code would end up a bit more readable. (Especially if you tried to optimize out the buffer copies from the obvious <code>read</code> solution.)</p>
14,103,489
leaflet layer control events?
<p>All, I want to detect user layer selection in order to synchronize my sidebar with the displayed layers. </p> <p>But I don't see any layer control events in the API reference; How might I tell when such user layer selection has occurred? </p> <p>As an alternative, I've looked at the layer load and unload events, but I don't see any identification in what's returned. Did I miss that somehow?</p>
25,567,366
4
0
null
2012-12-31 15:43:38.703 UTC
9
2019-02-12 18:09:39.297 UTC
null
null
null
null
1,032,402
null
1
22
leaflet
31,528
<p>There are some events that let you know when the user activates / desactivates a layer.</p> <p>This may help you:</p> <p><a href="https://leafletjs.com/reference-1.4.0.html#map-baselayerchange" rel="noreferrer">https://leafletjs.com/reference-1.4.0.html#map-baselayerchange</a></p> <p>For example:</p> <pre><code>map.on('overlayadd', onOverlayAdd); function onOverlayAdd(e){ //do whatever } </code></pre>
14,028,293
google protocol buffers vs json vs XML
<p>I would like to know the merits &amp; de-merits of</p> <ul> <li>Google Protocol Buffers</li> <li>JSON</li> <li>XML</li> </ul> <p>I want to implement one common framework for two application, one in Perl and second in Java. So, would like to create common service which can be used by both technology i.e. Perl &amp; Java.</p> <p>Both are web-applications.</p> <p>Please share me your valuable thoughts &amp; suggestion on this. I have seen many links on google but all have mixed opinions.</p>
14,029,040
1
8
null
2012-12-25 06:32:28.697 UTC
90
2015-05-14 20:16:44.15 UTC
2015-05-14 20:16:44.15 UTC
null
404,623
null
1,747,158
null
1
233
xml|json|protocol-buffers|data-serialization
84,774
<p>Json</p> <ul> <li>human readable/editable</li> <li>can be parsed without knowing schema in advance</li> <li>excellent browser support</li> <li>less verbose than XML</li> </ul> <p>XML</p> <ul> <li>human readable/editable</li> <li>can be parsed without knowing schema in advance</li> <li>standard for SOAP etc</li> <li>good tooling support (xsd, xslt, sax, dom, etc)</li> <li>pretty verbose</li> </ul> <p>Protobuf</p> <ul> <li>very dense data (small output)</li> <li>hard to robustly decode without knowing the schema (data format is internally ambiguous, and needs schema to clarify)</li> <li>very fast processing</li> <li>not intended for human eyes (dense binary)</li> </ul> <p>All have good support on most platforms.</p> <p>Personally, I rarely use XML these days. If the consumer is a browser or a public API I tend to use json. For internal APIs I tend to use protobuf for performance. Offering both on public API (either via headers, or separate endpoints) works well too.</p>
9,444,887
Avoid extra "carriage return" in Print statement with Visual Basic?
<p>With Visual Basic, I'm confused with that the behavior of Print statement in that sometimes the following statement: would cause additional carriage return "^M" at the end of a line, but sometimes, it doesn't. I wondering why?</p> <pre><code>filePath = "d:\tmp\FAE-IMM-Report-2012-Week.org" If Dir(filePath) &lt;&gt; "" Then Kill filePath End If outFile = FreeFile() Open filePath For Output As outFile Print #outFile, "#+TITLE: Weekly Report" </code></pre> <p>would produce</p> <pre><code>#+TITLE: Weekly Report^M </code></pre> <p>while I wish without ^M:</p> <pre><code>#+TITLE: Weekly Report </code></pre> <p>In one test program, almost the same code would produce no "^M". </p> <h2>Please help! Thanks a lot.</h2> <p>Upon further experiment, I found that the following suggestion using vbNewline and ";" at the end of print content, still does not solve my problem. </p> <p>After careful isolation, I found the cause of the problem is an character that seems like a space, not exactly space, followed by newline and carriage return. Before printing the text containing the offending string, there was no carriage return, but once the offending line is printed, then every line including the previous line printed would have carriage return. </p> <p>I'm not sure what the exact the offending string is as my skill of VBA is not yet too well. </p> <p>Here is a copy of the offending text from a spreadsheet cell:</p> <pre><code> "There is something invisible after this visible text After the invisible text, then there might be a carriage return $Chr(13) and/or newline" </code></pre> <p>I'm not sure if the paste to web browser would preserve the content, though. By pasting to emacs, I did not see carriage return, while emacs should display it, if there is one. So I guess that there is no carriage return in the offending string. </p> <p>Below is the program demonstrate the problem:</p> <pre><code> Sub DemoCarriageReturnWillAppear() Dim filePath As String Dim outFile Dim offendingText filePath = "d:\tmp\demoCarriageReturn.org" If Dir(filePath) &lt;&gt; "" Then Kill filePath End If outFile = FreeFile() Open filePath For Output As outFile Print #outFile, "#+AUTHOR: Yu Shen" &amp; vbNewLine; Close #outFile 'At this moment, there is no carriage return Open filePath For Append As outFile offendingText = ThisWorkbook.Worksheets("Sheet1").Range("A1") Print #outFile, offendingText &amp; vbNewLine; Close #outFile 'Now, every line end has carriage return. 'It must be caused by something offending at the above print out content. End Sub </code></pre> <p>Here is the final result of the above procedure:</p> <pre><code> #+AUTHOR: Yu Shen^M There is something invisible after this visible text After the invisible text, then there might be a carriage return $Chr(13) or newline^M </code></pre> <p>Note the above "^M" is added by me, as carriage return would not be visible in browser. </p> <p>If you're interested, I can send you the excel file with the offending content. </p> <p>I need your help on how to avoid those offending string, or the carriage returns. (I even try to do string Replace of the carriage return or new line, as I found that once I manually deleted whatever caused change to another line, the problem would be gone. But calling Replace to replace vbNewline, Chr$(13), or vbCrLf did not make any difference. </p> <p>Thanks for your further help!</p> <p>Yu</p>
9,555,074
2
1
null
2012-02-25 14:33:51.78 UTC
null
2012-03-06 14:13:34.563 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
126,164
null
1
11
vba|excel|carriage-return
39,289
<p>To help the other people in the future, here is an summary of my problem and the solution. The extra carriage return on each line even with semi-colon at the print statement end was actually caused by a string of space followed by newline (Chr$(A)) in one of the print statement, once such string is printed, then all previous and subsequent printed content would have an extra carriage return!</p> <p>It seems a bug on VBA 6 (with Excel 2007), a nasty one!</p> <p>My work-around was to replace the newline by a space. </p> <p>Thanks for Tony's repeated help enabling me finally nailed down the cause. </p> <p>Here is the code to demonstrate the problem:</p> <pre><code>Sub DemoCarriageReturnWillAppearOnAllLines() Dim filePath As String Dim outFile Dim offendingText filePath = "d:\tmp\demoCarriageReturn.org" If Dir(filePath) &lt;&gt; "" Then Kill filePath End If outFile = FreeFile() Open filePath For Output As outFile Print #outFile, "#+AUTHOR: Yu Shen" &amp; vbNewLine; Close #outFile 'At this moment, there is no carriage return Open filePath For Append As outFile offendingText = " " &amp; Chr$(10) Print #outFile, offendingText &amp; vbNewLine; Close #outFile 'Now, every line end has carriage return. 'It must be caused by the offending at the above print out content. End Sub </code></pre> <p>After the first "Close #outFile", here is the content of the file demoCarriageReturn.org:</p> <pre><code>#+AUTHOR: Yu Shen </code></pre> <p>Note: with editor capable showing carriage return as visible ^M, there is no carriage return present. </p> <p>However, after the second "Close #outFile", here is the content of the same file with additional content:</p> <pre><code>#+AUTHOR: Yu Shen^M ^M </code></pre> <p>Note: there are two carriage returns appear. They are not intended. Especially, to the first line, the print statement has been executed, and at the previous close statement, it was found without carriage return. (To illustrate carriage return, I have to typing ^M in web page here. But it's in the file of the print out.)</p> <p>This is why I think that it's a bug, as the carriage returns are not intended. It's undesirable surprise. </p> <p>The following code shows that if I filter out the linefeed character the problem would be gone. </p> <pre><code>Sub DemoCarriageReturnWillNotAppearAtAll() Dim filePath As String Dim outFile Dim offendingText filePath = "d:\tmp\demoCarriageReturn.org" If Dir(filePath) &lt;&gt; "" Then Kill filePath End If outFile = FreeFile() Open filePath For Output As outFile Print #outFile, "#+AUTHOR: Yu Shen" &amp; vbNewLine; Close #outFile 'At this moment, there is no carriage return Open filePath For Append As outFile offendingText = " " &amp; Chr$(10) Print #outFile, Replace(offendingText, Chr$(10), "") &amp; vbNewLine; Close #outFile 'Now, no more carriage return. 'The only change is removing the linefeed character in the second print statement End Sub </code></pre> <p>After full execution of the above program, there is indeed no carriage return!</p> <pre><code>#+AUTHOR: Yu Shen </code></pre> <p>This shows that string combination of space followed by linefeed caused the bug, and removing linefeed can avoid the bug. </p> <p>The following code further demonstrate that if there is no offending string, even without newline and semi-colon at the end of print statement, there would not be undesired carriage return!</p> <pre><code>Sub DemoCarriageReturnWillNotAppearAtAllEvenWithoutNewLineFollowedBySemiColon() Dim filePath As String Dim outFile Dim offendingText filePath = "d:\tmp\demoCarriageReturn.org" If Dir(filePath) &lt;&gt; "" Then Kill filePath End If outFile = FreeFile() Open filePath For Output As outFile Print #outFile, "#+AUTHOR: Yu Shen" Close #outFile 'At this moment, there is no carriage return Open filePath For Append As outFile offendingText = " " &amp; Chr$(10) Print #outFile, Replace(offendingText, Chr$(10), "") Close #outFile 'Now, no more carriage return. 'The real change is removing the linefeed character in the second print statement End Sub </code></pre> <p>Also in the output result:</p> <pre><code>#+AUTHOR: Yu Shen </code></pre> <p>Still no the annoying carriage return!</p> <p>This shows that <strong>using newline followed by semi-colon at the end of print statement is not the solution to the problem of carriage return at every line!</strong> <em>The real solution is to avoid any string of space followed by linefeed in the print out content.</em> </p> <p>Yu</p>
58,648,739
How to check if python package is latest version programmatically?
<p>How do you check if a package is at its latest version programmatically in a script and return a true or false?</p> <p>I can check with a script like this:</p> <pre class="lang-py prettyprint-override"><code>package='gekko' import pip if hasattr(pip, 'main'): from pip import main as pipmain else: from pip._internal import main as pipmain pipmain(['search','gekko']) </code></pre> <p>or with command line: </p> <pre><code>(base) C:\User&gt;pip search gekko gekko (0.2.3) - Machine learning and optimization for dynamic systems INSTALLED: 0.2.3 (latest) </code></pre> <p>But how do I check programmatically and return true or false?</p>
58,649,262
8
4
null
2019-10-31 17:43:54.617 UTC
3
2021-03-31 10:53:32.25 UTC
2019-10-31 17:54:17.313 UTC
null
12,091,767
null
12,091,767
null
1
45
python|pip|gekko
13,188
<h1>Fast Version (Checking the package only)</h1> <p>The code below calls the package with an unavailable version like <code>pip install package_name==random</code>. The call returns all the available versions. The program reads the latest version.</p> <p>The program then runs <code>pip show package_name</code> and gets the current version of the package.</p> <p>If it finds a match, it returns True, otherwise False.</p> <p>This is a reliable option given that it stands on <code>pip</code></p> <pre><code>import subprocess import sys def check(name): latest_version = str(subprocess.run([sys.executable, '-m', 'pip', 'install', '{}==random'.format(name)], capture_output=True, text=True)) latest_version = latest_version[latest_version.find('(from versions:')+15:] latest_version = latest_version[:latest_version.find(')')] latest_version = latest_version.replace(' ','').split(',')[-1] current_version = str(subprocess.run([sys.executable, '-m', 'pip', 'show', '{}'.format(name)], capture_output=True, text=True)) current_version = current_version[current_version.find('Version:')+8:] current_version = current_version[:current_version.find('\\n')].replace(' ','') if latest_version == current_version: return True else: return False </code></pre> <h3>Edit 2021: The code below no longer works with the new version of pip</h3> <p>The following code calls for <code>pip list --outdated</code>:</p> <pre class="lang-py prettyprint-override"><code>import subprocess import sys def check(name): reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'list','--outdated']) outdated_packages = [r.decode().split('==')[0] for r in reqs.split()] return name in outdated_packages </code></pre>
44,740,423
Create json string from js Map and String
<p>My REST controller expects request input of the following format, which it successfully converts to a Java object containing a Map and a String as parameters:</p> <pre><code>{ "myMap" : { "key1": "value1", "key2": "value2", "key3": "value3"}, "myString": "string value" } </code></pre> <p>I am getting my data from an html form like so:</p> <pre><code>var myMap = new Map(); var String = document.getElementById('String').value; for (var i = 0 ; i&lt;anArray.length ; i++){ var input = document.getElementsByClassName('input_' + (i+1)); for (var j = 0 ; j&lt;3 ; j++){ if (input[j].checked){ myMap.set(input[j].name, input[j].id); } } } </code></pre> <p>Basically, this code boils down to:</p> <pre><code>var myMap = new Map(); myMap.set("key1", "value1"); myMap.set("key2", "value2"); myMap.set("key3", "value3"); </code></pre> <p>This results in a map containing {key1 => value1, key2 => value2, etc} and a String. I have been trying to turn this into a json string like so, but it doesn't seem to work:</p> <pre><code>var myJson = {}; myJson.myMap = myMap; myJson.myString = myString; var json = JSON.stringify(myJson); </code></pre> <p>However, I am ending up with the following string: `{"myMap":{},"String":"myString"}' . So I probably have to do something different to stringify a map, but nothing I try is working. </p> <p>Can anyone help me out?</p>
44,740,579
6
3
null
2017-06-24 19:55:27.76 UTC
1
2019-01-14 11:09:42.117 UTC
2017-06-24 20:05:10.943 UTC
null
7,813,415
null
7,813,415
null
1
15
javascript|json
39,860
<p>You can write a short conversion function to make a map into an object that can be stringified.</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>console.clear() function mapToObj(map){ const obj = {} for (let [k,v] of map) obj[k] = v return obj } const myMap = new Map(); myMap.set("key1", "value1"); myMap.set("key2", "value2"); myMap.set("key3", "value3"); const myString = "string value" const myJson = {}; myJson.myMap = mapToObj(myMap); myJson.myString = myString; const json = JSON.stringify(myJson); console.log(json)</code></pre> </div> </div> </p> <p>Here is a version that that presumably would work where Map exists but some other ES6 constructs do not (though, this seems like an editor settings issue).</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>console.clear() function mapToObj(map){ var obj = {} map.forEach(function(v, k){ obj[k] = v }) return obj } var myMap = new Map(); myMap.set("key1", "value1"); myMap.set("key2", "value2"); myMap.set("key3", "value3"); var myString = "string value" var myJson = {}; myJson.myMap = mapToObj(myMap); myJson.myString = myString; var json = JSON.stringify(myJson); console.log(json)</code></pre> </div> </div> </p>
24,883,585
Mouse coordinates don't match after Scaling and Panning canvas
<p>I'm very new to javascript and canvas and I have a program that's supposed to detect elements animated on an elliptical path. It later on goes to form a tree.. But this is the basic structure that I've linked onto jsfiddle. It works fine without scaling or panning but as soon as I try to scale or Pan, the mouse coordinates go haywire. I tried following markE's advice from <a href="https://stackoverflow.com/questions/21717001/html5-canvas-get-coordinates-after-zoom-and-translate">HTML5 canvas get coordinates after zoom and translate</a> But i'm definitely doing something wrong and I've clearly not understood whats happening with the canvas and the transformation matrix. I've spent about 3 days trying to change all the combinations I can think of but I can't seem to figure it out :s</p> <p><strong>SOLVED</strong>: Here's my code with zooming and mouse panning and for animating and detecting elements on an ellipse: <a href="http://jsfiddle.net/metalloyd/A8hgz/" rel="noreferrer">http://jsfiddle.net/metalloyd/A8hgz/</a></p> <pre><code> theCanvas = document.getElementById("canvasOne"); context = theCanvas.getContext("2d"); var status = document.getElementById('status'); var $canvas = $("#canvasOne"); var canvasOffset = $canvas.offset(); var offsetX = canvasOffset.left; var offsetY = canvasOffset.top; var scrollX = $canvas.scrollLeft(); var scrollY = $canvas.scrollTop(); var cw = theCanvas.width; var ch = theCanvas.height; var scaleFactor = 1.00; var panX = 0; var panY = 0; var mainX = 250; // setting the middle point position X value var mainY = 100; // setting the middle point position Y value var mainR = 125; // main ellipse radius R var no = 5; // number of nodes to display var div_angle = 360 / no; var circle = { centerX: mainX, centerY: mainY + 100, radius: mainR, angle: .9 }; var ball = { x: 0, y: 0, speed: .1 }; var a = 1.8; //Ellipse width var b = .5; //Ellipse height //Scale and Pan variables var translatePos = { x: 1, y: 1 }; var startDragOffset = {}; var mouseDown = false; var elements = [{}]; // Animate var animateInterval = setInterval(drawScreen, 1); //Animation function drawScreen() { context.clearRect(0, 0, cw, ch); // Background box context.beginPath(); context.fillStyle = '#EEEEEE'; context.fillRect(0, 0, theCanvas.width, theCanvas.height); context.strokeRect(1, 1, theCanvas.width - 2, theCanvas.height - 2); context.closePath(); context.save(); context.translate(panX, panY); context.scale(scaleFactor, scaleFactor); ball.speed = ball.speed + 0.001; for (var i = 1; i &lt;= no; i++) { // male new_angle = div_angle * i; //Starting positions for ball 1 at different points on the ellipse circle.angle = (new_angle * (0.0174532925)) + ball.speed; //elliptical x position and y position for animation for the first ball //xx and yy records the first balls coordinates xx = ball.x = circle.centerX - (a * Math.cos(circle.angle)) * (circle.radius); yy = ball.y = circle.centerY + (b * Math.sin(circle.angle)) * (circle.radius); //Draw the first ball with position x and y context.fillStyle = "#000000"; context.beginPath(); context.arc(ball.x, ball.y, 10, 0, Math.PI * 2, true); context.fill(); context.closePath(); //alert("male Positions "+"X: "+ball.x+ " Y: "+ball.y); // female new_angle = div_angle * i + 4; //Starting positions for ball 2 at different points on the ellipse circle.angle = (new_angle * (0.0174532925)) + ball.speed; //elliptical x position and y position for animation for the second ball //ball.x and ball.y record the second balls positions ball.x = circle.centerX - (a * Math.cos(circle.angle)) * (circle.radius); ball.y = circle.centerY + (b * Math.sin(circle.angle)) * (circle.radius); context.fillStyle = "#000000"; context.beginPath(); context.arc(ball.x, ball.y, 10, 0, Math.PI * 2, true); context.fill(); context.closePath(); //alert("female Positions "+"X: "+ball.x+ " Y: "+ball.y); //Record the ball positions in elements array for locating positions with mouse coordinates. elements[i] = { id: i, femaleX: ball.x, femaleY: ball.y, maleX: xx, maleY: yy, w: 10 //radius of the ball to draw while locating the positions }; //Text Numbering context.beginPath(); context.fillStyle = "blue"; context.font = "bold 16px Arial"; context.fillText(elements[i].id, ball.x - 20, ball.y + 20); context.closePath(); // line drawing--Connecting lines to the balls from the center. context.moveTo(mainX, mainY); context.lineTo((ball.x + xx) / 2, (ball.y + yy) / 2); //Draw line till the middle point between ball1 and ball2 context.stroke(); context.fill(); context.closePath(); } // center point context.fillStyle = "#000000"; context.beginPath(); context.arc(mainX, mainY, 15, 0, Math.PI * 2, true); context.fill(); context.closePath(); context.restore(); } // Event Listeners // Mouse move event to alert the position of the ball on screen document.getElementById("plus").addEventListener("click", function () { scaleFactor *= 1.1; drawScreen(); }, false); document.getElementById("minus").addEventListener("click", function () { scaleFactor /= 1.1; drawScreen(); }, false); // Event listeners to handle screen panning context.canvas.addEventListener("mousedown", function (evt) { mouseDown = true; startDragOffset.x = evt.clientX - translatePos.x; startDragOffset.y = evt.clientY - translatePos.y; }); context.canvas.addEventListener("mouseup", function (evt) { mouseDown = false; }); context.canvas.addEventListener("mouseover", function (evt) { mouseDown = false; }); context.canvas.addEventListener("mouseout", function (evt) { mouseDown = false; }); context.canvas.addEventListener("mousemove", function (evt) { if (mouseDown) { translatePos.x = evt.clientX - startDragOffset.x; translatePos.y = evt.clientY - startDragOffset.y; panX = translatePos.x; panY = translatePos.y; drawScreen(); } evt.preventDefault(); evt.stopPropagation(); var mouseX = parseInt(evt.clientX - offsetX); var mouseY = parseInt(evt.clientY - offsetY); var mouseXT = parseInt((mouseX - panX) / scaleFactor); var mouseYT = parseInt((mouseY - panY) / scaleFactor); status.innerHTML = mouseXT + " | " + mouseYT; for (var i = 1; i &lt; elements.length; i++) { var b = elements[i]; context.closePath(); context.beginPath(); context.arc(b.femaleX, b.femaleY, 10, 0, Math.PI * 2); context.arc(b.maleX, b.maleY, 10, 0, Math.PI * 2); if (context.isPointInPath(mouseXT, mouseYT)) { theCanvas.style.cursor = 'pointer'; alert(b.id + " female.x: " + b.femaleX + " female.y: " + b.femaleY + " ball.x: " + ball.x + " ball.y: " + ball.y); return; } else theCanvas.style.cursor = 'default'; context.closePath(); } });` </code></pre>
24,895,485
1
3
null
2014-07-22 09:25:46.217 UTC
8
2014-07-25 07:36:26.07 UTC
2017-05-23 10:31:12.887 UTC
null
-1
null
1,785,374
null
1
10
javascript|html|animation|canvas|html5-canvas
12,853
<p>Using the transformation matrix is useful or even necessary in these circumstances:</p> <ul> <li>If you are deeply nesting transformations.</li> <li>If you are altering different drawings with different transforms.</li> <li>If you need interim transformation coordinates.</li> <li>If you are doing transformations involving skew.</li> <li>If you are doing transformations involving rotation.</li> </ul> <p>But for the simpler case of panning and scaling the entire canvas there is a simpler method.</p> <p><strong>First, set up variables to hold the current amount of scaling and panning:</strong></p> <pre><code>var scaleFactor=1.00; var panX=0; var panY=0; </code></pre> <p><strong>Then use these pan &amp; scale variables to do all your drawings.</strong></p> <ul> <li>clear the canvas.</li> <li>save the untransformed canvas state.</li> <li>do translations with the <code>panX</code> variable.</li> <li>do scaling with the <code>scaleFactor</code> variable.</li> <li>draw all your elements as if they were in untranformed space.</li> <li>restore the context to its untransformed state.</li> </ul> <p>Example code:</p> <pre><code>function drawTranslated(){ ctx.clearRect(0,0,cw,ch); ctx.save(); ctx.translate(panX,panY); ctx.scale(scaleFactor,scaleFactor); ctx.beginPath(); ctx.arc(circleX,circleY,15,0,Math.PI*2); ctx.closePath(); ctx.fillStyle=randomColor(); ctx.fill(); ctx.restore(); } </code></pre> <p><strong>Now, about mouse coordinates:</strong></p> <p>The browser always returns the mouse position in untransformed coordinates. Your drawings have been done in transformed space. If you want to know where your mouse is in transformed space, you can convert untransformed mouse coordinates to transformed coordinates like this:</p> <pre><code>var mouseXTransformed = (mouseX-panX) / scaleFactor; var mouseYTransformed = (mouseY-panY) / scaleFactor; </code></pre> <p><strong>Here is example code and a Demo:</strong> <a href="http://jsfiddle.net/m1erickson/HwNp3/" rel="noreferrer">http://jsfiddle.net/m1erickson/HwNp3/</a></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /&gt; &lt;!-- reset css --&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery.min.js"&gt;&lt;/script&gt; &lt;style&gt; body{ background-color: ivory; } #canvas{border:1px solid red;} &lt;/style&gt; &lt;script&gt; $(function(){ var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var $canvas=$("#canvas"); var canvasOffset=$canvas.offset(); var offsetX=canvasOffset.left; var offsetY=canvasOffset.top; var scrollX=$canvas.scrollLeft(); var scrollY=$canvas.scrollTop(); var cw=canvas.width; var ch=canvas.height; var scaleFactor=1.00; var panX=0; var panY=0; var circleX=150; var circleY=150; var $screen=$("#screen"); var $transformed=$("#transformed"); var $trx=$("#trx"); drawTranslated(); $("#canvas").mousemove(function(e){handleMouseMove(e);}); $("#scaledown").click(function(){ scaleFactor/=1.1; drawTranslated(); }); $("#scaleup").click(function(){ scaleFactor*=1.1; drawTranslated(); }); $("#panleft").click(function(){ panX-=10; drawTranslated(); }); $("#panright").click(function(){ panX+=10; drawTranslated(); }); function drawTranslated(){ ctx.clearRect(0,0,cw,ch); ctx.save(); ctx.translate(panX,panY); ctx.scale(scaleFactor,scaleFactor); ctx.beginPath(); ctx.arc(circleX,circleY,15,0,Math.PI*2); ctx.closePath(); ctx.fillStyle=randomColor(); ctx.fill(); ctx.restore(); $trx.text("Pan: "+panX+", Scale: "+scaleFactor); } function handleMouseMove(e){ e.preventDefault(); e.stopPropagation(); var mouseX=parseInt(e.clientX-offsetX); var mouseY=parseInt(e.clientY-offsetY); var mouseXT=parseInt((mouseX-panX)/scaleFactor); var mouseYT=parseInt((mouseY-panY)/scaleFactor); $screen.text("Screen Coordinates: "+mouseX+"/"+mouseY); $transformed.text("Transformed Coordinates: "+mouseXT+"/"+mouseYT); } function randomColor(){ return('#'+Math.floor(Math.random()*16777215).toString(16)); } }); // end $(function(){}); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;Transformed coordinates are mouseXY in transformed space.&lt;br&gt;The circles center is always at translated [150,150]&lt;/h3&gt; &lt;h4 id=screen&gt;Screen Coordinates:&lt;/h4&gt; &lt;h4 id=transformed&gt;Transformed Coordinates:&lt;/h4&gt; &lt;h4 id=trx&gt;Pan &amp; Scale&lt;/h4&gt; &lt;button id=scaledown&gt;Scale Down&lt;/button&gt; &lt;button id=scaleup&gt;Scale Up&lt;/button&gt; &lt;button id=panleft&gt;Pan Left&lt;/button&gt; &lt;button id=panright&gt;Pan Right&lt;/button&gt;&lt;br&gt; &lt;canvas id="canvas" width=350 height=400&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
34,945,299
How to add SSL certificate to AWS EC2 with the help of new AWS Certificate Manager service
<p>AWS has come up with a new service <strong>AWS Certificate Manager</strong>. One thing I got from the description is that if we are using this service we don't have to pay for the certificate anymore.</p> <p>They are providing certificates for Elastic Load Balancer (ELB) and CloudFront, but I didn't find EC2 anywhere.</p> <p>Is there any way to use the certificate with EC2?</p>
34,947,410
4
4
null
2016-01-22 11:10:22.91 UTC
16
2020-04-15 20:32:48.12 UTC
2017-02-27 18:43:04.247 UTC
null
3,271,599
null
4,481,829
null
1
97
amazon-web-services|ssl|amazon-ec2
83,502
<blockquote> <p><strong>Q: Can I use certificates on Amazon EC2 instances or on my own servers?</strong></p> <p>No. At this time, certificates provided by ACM can only be used with specific AWS services.</p> <hr> <p><strong>Q: With which AWS services can I use certificates provided by ACM?</strong></p> <p>You can use ACM with the following AWS services:</p> <p>• Elastic Load Balancing</p> <p>• Amazon CloudFront</p> <p>• AWS Elastic Beanstalk</p> <p>• Amazon API Gateway</p> <p><a href="https://aws.amazon.com/certificate-manager/faqs/" rel="noreferrer">https://aws.amazon.com/certificate-manager/faqs/</a></p> </blockquote> <p>You can't install the certificates created by <a href="https://aws.amazon.com/certificate-manager" rel="noreferrer">Amazon Certificate Manager (ACM)</a> on resources you have direct low-level access to, like EC2 or servers outside of AWS, because you aren't provided with access to the private keys. These certs can only be deployed on resources managed by the AWS infrastructure -- ELB and CloudFront -- because the AWS infrastructure holds the only copies of the private keys for the certificates that it generates, and maintains them under tight security with auditable internal access controls.</p> <p>You'd have to have your EC2 machines listening <em>behind</em> CloudFront or ELB (or both, cascaded, would also work) in order to use these certs for content coming from EC2... because you can't install these certs directly on EC2 machines.</p>
138,383
What are the equivalents of colored grep?
<p>Sometimes coloring a logfile or other gives a good overview when looking for <em>stuff</em> and <em>behaviors</em></p> <p>I just saw that grep have a coloring feature</p> <pre><code>grep -C 99999 --color &lt;regexp&gt; &lt;filename&gt; </code></pre> <p>What other methods are there?</p>
138,390
5
0
null
2008-09-26 09:05:24.377 UTC
10
2022-03-18 09:16:56.717 UTC
2022-03-18 09:16:56.717 UTC
epatel
5,446,749
epatel
842
null
1
11
debugging|unix|logging|command-line|grep
7,467
<p>For searching source code, I use <a href="http://petdance.com/ack/" rel="noreferrer">ack</a>. It's got a lot of options that make sense for searching code (such as automatically ignoring SCM directories).</p>
392,864
Splash Screen waiting until thread finishes
<p>I still have a problem with the splash screen. I don't want to use the property <code>SC.TopMost=true</code>.</p> <p>Now my application scenario is as follows:</p> <p><strong>in progeram.cs:</strong></p> <pre><code>[STAThread] static void Main() { new SplashScreen(_tempAL);// where _tempAL is an arrayList Application.Run(new Form1(_tempAL)); } </code></pre> <p><strong>in SplashScreen class:</strong></p> <pre><code>public SplashScreen(ArrayList _Data) { DisplaySplash() } private void DisplaySplash() { this.Show(); this.TopMost = true; this.CenterToScreen(); this.SetTopLevel(true); _allServerNarrators = new string[10]; for (int i = 0; i &lt; _allServerNarrators.Length; i++) _allServerNarrators[i] = null; GetFromServer(); this.Hide(); _serverData = new ArrayList(); _thisData.Add(_allServerNarrators); _thisData.Add(_serverNarrators); } private void GetFromServer() { _serverNarrators = new ArrayList(); string _file = "Suras.serverNar"; if (!Directory.Exists("c:\\ASGAQuraan")) Directory.CreateDirectory("c:\\ASGAQuraan"); while (counter &lt; 4 &amp;&amp; _serverFiles == null) { if (Download("c:\\ASGAQuraan", _ftpServerIP, _file)) { StreamReader _strReader = new StreamReader ("c:\\ASGAQuraan\\"+_file,System.Text.Encoding.Default); string _line = _strReader.ReadLine(); string _word; while (true) { while (_line != null) { _word = _line.Substring(0, _line.IndexOf("*")); int _narId = Convert.ToInt32(_word); _line = _line.Substring(2); int k = 0; _serverNarratorNode = new ArrayList(); while (true) { int ind = _line.IndexOf("*"); if (ind &gt; 0 &amp;&amp; ind &lt; _line.Length) { string str = _line.Substring(0, (ind)); if (k == 0) { _allServerNarrators[_narId] = str; _serverNarratorNode.Add(str); } else { _serverNarratorNode.Add(str); } _line = _line.Substring(ind + 1); k++; } else { _line = null; break; } } _serverNarrators.Add(_serverNarratorNode); _serverFiles = "added"; } _line = _strReader.ReadLine(); if (_line == null) { break; } } } else counter++; } } </code></pre> <p>What I want is something in the splash screen class which waits until the thread finishes.</p> <p>For more details, please tell me what I need to tell you.</p>
392,904
5
2
null
2008-12-25 15:06:16.73 UTC
32
2013-11-26 12:23:10.17 UTC
2013-06-13 21:08:12.327 UTC
Jonathan Leffler
2,156,756
Eng.Basma
42,782
null
1
20
c#|winforms|splash-screen
20,340
<p>Following across 2 threads is a bit confusing, but I'm going to take a stab and say this...</p> <p>I don't fully understand your design here, but if the issue is that when you launch a second application the splash screen form turns white... It's most likely due to the fact that splash screen is busy executing all of that code in GetFromServer(). So busy that it has no time to re-paint itself.</p> <p>To remedy this problem I would suggest that you use the <a href="http://msdn.microsoft.com/en-us/library/8xs8549b.aspx" rel="nofollow noreferrer">BackGroundWorker component</a> to execute the GetFromServer method. This will run that method in a separate thread and leave the form's thread free to re-paint itself.</p>
84,820
Distributed hierarchical clustering
<p>Are there any algorithms that can help with hierarchical clustering? Google's map-reduce has only an example of k-clustering. In case of hierarchical clustering, I'm not sure how it's possible to divide the work between nodes. Other resource that I found is: <a href="http://issues.apache.org/jira/browse/MAHOUT-19" rel="noreferrer">http://issues.apache.org/jira/browse/MAHOUT-19</a> But it's not apparent, which algorithms are used.</p>
192,614
5
0
null
2008-09-17 16:00:53.167 UTC
14
2014-09-04 12:54:24.027 UTC
2008-09-19 14:57:46.537 UTC
cynicalman
410
Roman
12,695
null
1
22
algorithm|cluster-analysis|hierarchical-clustering
7,634
<p>First, you have to decide if you're going to build your hierarchy bottom-up or top-down. </p> <p>Bottom-up is called Hierarchical agglomerative clustering. Here's a simple, well-documented algorithm: <a href="http://nlp.stanford.edu/IR-book/html/htmledition/hierarchical-agglomerative-clustering-1.html" rel="noreferrer">http://nlp.stanford.edu/IR-book/html/htmledition/hierarchical-agglomerative-clustering-1.html</a>.</p> <p>Distributing a bottom-up algorithm is tricky because each distributed process needs the entire dataset to make choices about appropriate clusters. It also needs a list of clusters at its current level so it doesn't add a data point to more than one cluster at the same level.</p> <p>Top-down hierarchy construction is called <a href="http://nlp.stanford.edu/IR-book/html/htmledition/divisive-clustering-1.html" rel="noreferrer">Divisive clustering</a>. <a href="http://home.dei.polimi.it/matteucc/Clustering/tutorial_html/kmeans.html" rel="noreferrer">K-means</a> is one option to decide how to split your hierarchy's nodes. This paper looks at K-means and Principal Direction Divisive Partitioning (PDDP) for node splitting: <a href="http://scgroup.hpclab.ceid.upatras.gr/faculty/stratis/Papers/tm07book.pdf" rel="noreferrer">http://scgroup.hpclab.ceid.upatras.gr/faculty/stratis/Papers/tm07book.pdf</a>. In the end, you just need to split each parent node into relatively well-balanced child nodes.</p> <p>A top-down approach is easier to distribute. After your first node split, each node created can be shipped to a distributed process to be split again and so on... Each distributed process needs only to be aware of the subset of the dataset it is splitting. Only the parent process is aware of the full dataset.</p> <p>In addition, each split could be performed in parallel. Two examples for k-means:</p> <ul> <li><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.101.1882&amp;rep=rep1&amp;type=pdf" rel="noreferrer">http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.101.1882&amp;rep=rep1&amp;type=pdf</a></li> <li><a href="http://www.ece.northwestern.edu/~wkliao/Kmeans/index.html" rel="noreferrer">http://www.ece.northwestern.edu/~wkliao/Kmeans/index.html</a>.</li> </ul>
71,257
Suspend Process in C#
<p>How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.</p> <p>I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.</p>
71,457
5
0
null
2008-09-16 11:07:34.283 UTC
26
2021-01-04 18:00:53.397 UTC
2008-09-16 11:11:23.603 UTC
Lars Truijens
1,242
Thomas Danecker
9,632
null
1
27
c#|.net
44,251
<p>Here's my suggestion:</p> <pre><code> [Flags] public enum ThreadAccess : int { TERMINATE = (0x0001), SUSPEND_RESUME = (0x0002), GET_CONTEXT = (0x0008), SET_CONTEXT = (0x0010), SET_INFORMATION = (0x0020), QUERY_INFORMATION = (0x0040), SET_THREAD_TOKEN = (0x0080), IMPERSONATE = (0x0100), DIRECT_IMPERSONATION = (0x0200) } [DllImport("kernel32.dll")] static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); [DllImport("kernel32.dll")] static extern uint SuspendThread(IntPtr hThread); [DllImport("kernel32.dll")] static extern int ResumeThread(IntPtr hThread); [DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)] static extern bool CloseHandle(IntPtr handle); private static void SuspendProcess(int pid) { var process = Process.GetProcessById(pid); // throws exception if process does not exist foreach (ProcessThread pT in process.Threads) { IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); if (pOpenThread == IntPtr.Zero) { continue; } SuspendThread(pOpenThread); CloseHandle(pOpenThread); } } public static void ResumeProcess(int pid) { var process = Process.GetProcessById(pid); if (process.ProcessName == string.Empty) return; foreach (ProcessThread pT in process.Threads) { IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); if (pOpenThread == IntPtr.Zero) { continue; } var suspendCount = 0; do { suspendCount = ResumeThread(pOpenThread); } while (suspendCount &gt; 0); CloseHandle(pOpenThread); } } </code></pre>
1,177,517
Is there a more elegant way of adding an item to a Dictionary<> safely?
<p>I need to add key/object pairs to a dictionary, but I of course need to first check if the key already exists otherwise I get a "<strong>key already exists in dictionary</strong>" error. The code below solves this but is clunky.</p> <p><strong>What is a more elegant way of doing this without making a string helper method like this?</strong></p> <pre><code>using System; using System.Collections.Generic; namespace TestDictStringObject { class Program { static void Main(string[] args) { Dictionary&lt;string, object&gt; currentViews = new Dictionary&lt;string, object&gt;(); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2"); StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1"); foreach (KeyValuePair&lt;string, object&gt; pair in currentViews) { Console.WriteLine("{0} {1}", pair.Key, pair.Value); } Console.ReadLine(); } } public static class StringHelpers { public static void SafeDictionaryAdd(Dictionary&lt;string, object&gt; dict, string key, object view) { if (!dict.ContainsKey(key)) { dict.Add(key, view); } else { dict[key] = view; } } } } </code></pre>
1,177,534
5
0
null
2009-07-24 13:07:09.213 UTC
9
2020-05-19 00:08:35.327 UTC
null
null
null
null
4,639
null
1
172
c#|collections|dictionary
100,662
<p>Just use the indexer - it will overwrite if it's already there, but it doesn't <em>have</em> to be there first:</p> <pre><code>Dictionary&lt;string, object&gt; currentViews = new Dictionary&lt;string, object&gt;(); currentViews["Customers"] = "view1"; currentViews["Customers"] = "view2"; currentViews["Employees"] = "view1"; currentViews["Reports"] = "view1"; </code></pre> <p>Basically use <code>Add</code> if the existence of the key indicates a bug (so you want it to throw) and the indexer otherwise. (It's a bit like the difference between casting and using <code>as</code> for reference conversions.)</p> <p>If you're using C# 3 <em>and you have a distinct set of keys</em>, you can make this even neater:</p> <pre><code>var currentViews = new Dictionary&lt;string, object&gt;() { { "Customers", "view2" }, { "Employees", "view1" }, { "Reports", "view1" }, }; </code></pre> <p>That won't work in your case though, as collection initializers always use <code>Add</code> which will throw on the second <code>Customers</code> entry.</p>
992,807
Java: Converting a set to an array for String representation
<p>From Sun's <a href="http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html" rel="noreferrer">Java Tutorial</a>, I would have thought this code would convert a set into an array.</p> <pre><code>import java.util.*; public class Blagh { public static void main(String[] args) { Set&lt;String&gt; set = new HashSet&lt;String&gt;(); set.add("a"); set.add("b"); set.add("c"); String[] array = set.toArray(new String[0]); System.out.println(set); System.out.println(array); } } </code></pre> <p>However, this gives</p> <pre><code>[a, c, b] [Ljava.lang.String;@9b49e6 </code></pre> <p>What have I misunderstood?</p>
992,812
6
3
null
2009-06-14 13:12:11.687 UTC
5
2013-01-29 17:01:20.263 UTC
2013-01-29 17:01:20.263 UTC
null
20,654
null
10,439
null
1
32
java|arrays|set
101,148
<p>The code works fine.</p> <p>Replace:</p> <pre><code>System.out.println(array); </code></pre> <p>With:</p> <pre><code>System.out.println(Arrays.toString(array)); </code></pre> <p>Output:</p> <pre> [b, c, a] [b, c, a] </pre> <p>The <code>String</code> representation of an array displays the a "textual representation" of the array, obtained by <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#toString()" rel="noreferrer"><code>Object.toString</code></a> -- which is the class name and the hash code of the array as a hexidecimal string.</p>
69,526,369
A required file could not be downloaded while installing SQL Server 2019 Developer
<p>While Installing SQL Server 2019 Developer Edition, I am getting error - A required file could not be downloaded. This could mean the version of the installer is no longer supported. Please download again from download site.</p> <p><a href="https://i.stack.imgur.com/cXweN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cXweN.png" alt="enter image description here" /></a></p> <p>I am not getting what is missing file and how to resolve this.</p>
70,263,907
5
5
null
2021-10-11 12:40:22.937 UTC
9
2022-05-09 17:24:30.537 UTC
null
null
null
null
6,119,878
null
1
33
sql-server
26,510
<p>Open PowerShell as administrator and run</p> <pre><code>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type Dword Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type Dword </code></pre> <p>Source <a href="https://techcommunity.microsoft.com/t5/sql-server/sql-server-installer-unable-to-download-the-required-files/m-p/2120065/highlight/true#M890" rel="noreferrer">https://techcommunity.microsoft.com/t5/sql-server/sql-server-installer-unable-to-download-the-required-files/m-p/2120065/highlight/true#M890</a></p>
44,030,515
In Ruby how do I find the index of one of an array of elements?
<p>In Ruby 2.4, how do I find the earliest index of an element of an array in another array? That is, if any element of an array occurs in the other array, I want to get the first index. I thought find_index might do it, but</p> <pre><code>a = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] # =&gt; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] a.find_index(&quot;a&quot;) # =&gt; 0 a.find_index([&quot;b&quot;, &quot;c&quot;]) # =&gt; nil </code></pre> <p>In the above example, I would expect to see the output &quot;1&quot; because the element &quot;b&quot; occurs at index 1 in the array &quot;a&quot;.</p>
44,030,553
4
2
null
2017-05-17 16:40:55.3 UTC
6
2020-10-29 10:55:06.847 UTC
2020-10-29 10:55:06.847 UTC
null
5,025,116
user7055375
null
null
1
29
arrays|ruby
64,873
<p><code>find_index</code> takes a single element. You could find the minimum by doing something like </p> <pre><code>a = ["a", "b", "c"] to_find = ["b", "c"] to_find.map {|i| a.find_index(i) } .compact.min # =&gt; 1 </code></pre>
43,942,663
Incorrect syntax near '('. Expecting ID
<p>I've looked through several other questions of this type and have not found one that will help me resolve this issue. What I'm trying to do is this: I want to create a table for all employees for the purpose of assigning an <code>EmployeeID</code> that will be used across several other tables. That table and the others work fine. My issue arises when I try to create a new table based off the <code>EmployeeType</code> so I can bring up information based solely on employees of a specific type. On the <code>SELECT</code> statement for all three of the tables I get this error:</p> <blockquote> <p>Incorrect syntax near '('. Expecting ID.</p> </blockquote> <p>I've googled and googled for how to resolve it, but nothing I've tried is working. What am I missing?</p> <pre><code>CREATE TABLE Employees ( EmployeeID int NOT NULL PRIMARY KEY IDENTITY, EmpFirstName char(50) NOT NULL, EmpLastName char(50) NOT NULL, EmpAddress varchar(50) NOT NULL, EmpCity char(50) NOT NULL, EmpState char(2) NOT NULL, EmpZipCode varchar(10) NOT NULL, EmpPhone varchar(12) NOT NULL, EmpJobTitle char(30) NOT NULL, EmployeeType char(30) NOT NULL, Salary money NOT NULL, HoursPerWeek int NOT NULL, ); CREATE TABLE Collective AS (SELECT * FROM [dbo].[Employees] WHERE EmployeeID = Employees.EmployeeID AND EmployeeType = 'Collective'); CREATE TABLE PaidStaff AS (SELECT EmployeeID AS ReviewerID, EmpFirstName, EmpLastName, EmpAddress, EmpCity, EmpState, EmpZipCode, EmpPhone, EmpJobTitle Salary, HoursPerWeek FROM Employees WHERE EmployeeID = Employees.EmployeeID AND EmployeeType = 'PaidStaff'); CREATE TABLE Volunteers AS (SELECT EmployeeID AS ReviewerID, EmpFirstName, EmpLastName, EmpAddress, EmpCity, EmpState, EmpZipCode, EmpPhone, EmpJobTitle FROM Employees WHERE EmployeeType = 'Volunteer'); </code></pre>
43,942,736
2
2
null
2017-05-12 16:40:19.543 UTC
1
2017-05-12 16:48:11.767 UTC
2017-05-12 16:48:11.767 UTC
null
2,333,499
null
7,993,366
null
1
10
sql|sql-server|tsql
47,232
<p>SQL Server doesn't have a <code>CREATE TABLE .... AS (SELECT ...</code> feature. That just isn't valid T-SQL syntax - therefore the error.</p> <p>If you want to create a <strong>new table</strong> (which doesn't exist yet!) from a <code>SELECT</code>, you need to use this syntax instead:</p> <pre><code>SELECT EmployeeID AS ReviewerID, EmpFirstName, EmpLastName, EmpAddress, EmpCity, EmpState, EmpZipCode, EmpPhone, EmpJobTitle INTO dbo.Volunteers FROM dbo.Employees WHERE EmployeeType = 'Volunteer'; </code></pre> <p>This <strong><em>only</em></strong> works if that new table - <code>dbo.Volunteers</code> - <strong>does not exist yet</strong>.</p> <p>If you need to insert rows into an <em>existing table</em>, then you need to use this syntax:</p> <pre><code>INSERT INTO dbo.Volunteers (list-of-columns) SELECT (list-of-columns) FROM dbo.Employees WHERE EmployeeType = 'Volunteer'; </code></pre>
17,857,146
Is it possible to change default OLEDB connection timeout value? Run-time error (80040e31)
<p>I have one legacy app (VB) and I have an issue with the timeout error while connecting to SQL Server (probably through OLEDB).</p> <p><img src="https://i.stack.imgur.com/ArAgO.png" alt="enter image description here"></p> <p>Using SQL Profiler I figure out that the connection is dropped through exactly 30 seconds.</p> <p><img src="https://i.stack.imgur.com/2LYEy.png" alt="enter image description here"></p> <p>I don't have access to the source codes but I scanned exe resources and couldn't find any hardcoded connection string timeout values there.</p> <p>The last chance I think I have is to change the default OLEDB timeout somewhere outside the app.</p> <p><strong>My question is: it is possible to change default OLEDB timeout value?</strong></p> <hr> <p>UPDATE</p> <p>I found the connection string and changed timeout to 300 but it does not help...</p> <pre><code>Provider=SQLOLEDB.1;Persist Security Info=False;User ID=______;Password=______;Initial Catalog=________;Data Source=______;Connect Timeout=300 </code></pre> <p>After that I tried to replace current connection string with connection strings from different providers: <strong>ADO.NET</strong> and <strong>ODBC</strong> but every time I get an timeout error after 30 seconds - checkmate.</p> <p>P.S.</p> <p>I'll be happy to any advice</p>
17,917,006
3
4
null
2013-07-25 11:46:31.633 UTC
null
2015-01-10 17:54:20.99 UTC
2015-01-10 17:54:20.99 UTC
null
483,408
null
483,408
null
1
3
sql-server|vba|oledb|connection-timeout
38,935
<p>I found the answer <a href="https://stackoverflow.com/questions/27472/timeout-not-being-honoured-in-connection-string">here</a>. It is the command timeout and it must be configured from particular <code>command</code> object.</p>
47,079,114
Should I minimize the number of docker layers?
<p>The <a href="https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/" rel="noreferrer">documentation</a> doesn't elaborate on the topic a lot. It says:</p> <blockquote> <p>Minimize the number of layers</p> <p>Prior to Docker 17.05, and even more, prior to Docker 1.10, it was important to minimize the number of layers in your image. The following improvements have mitigated this need:</p> <p>In Docker 1.10 and higher, only RUN, COPY, and ADD instructions create layers. Other instructions create temporary intermediate images, and no longer directly increase the size of the build.</p> <p>Docker 17.05 and higher add support for multi-stage builds, which allow you to copy only the artifacts you need into the final image. This allows you to include tools and debug information in your intermediate build stages without increasing the size of the final image.</p> </blockquote> <p>It looks like the latest Docker versions don't solve the problem of handling many layers. They rather strive to reduce their number in the final image. Most importantly, the docs don't tell <strong>why</strong> many layers are bad.</p> <p>I'm aware of the <a href="https://stackoverflow.com/a/39383801/2116625">AUFS limit</a> of 42 layers. It makes sense to keep the number of layers small for widely used images because it helps other images built on top of them fit the restriction. However, there are another storage drivers and images for other purposes.</p> <p>It is also good to keep images small for an obvious reason - they take up disk space and network bandwidth. However, I don't think that <a href="https://stackoverflow.com/questions/39223249/multiple-run-vs-single-chained-run-in-dockerfile-what-is-better">chaining RUN statements</a> and thus squashing many layers into one helps in general. In case different RUNs update different parts of the filesystem one layer and many layers together should be approximately the same in size.</p> <p>On the other hand, many layers allow to make use of cache and rebuild images faster. They are also pulled in parallel.</p> <p>I work in a small team with a private Docker registry. We won't ever meet the 42 layers restriction and care mostly about performance and development speed.</p> <p>If so, should I minimize the number of docker layers?</p>
47,166,120
3
3
null
2017-11-02 15:34:35.357 UTC
12
2017-11-07 19:59:31.157 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,116,625
null
1
57
docker|optimization|dockerfile|layer
14,287
<blockquote> <p>I work in a small team with a private Docker registry. We won't ever meet the 42 layers restriction and care mostly about performance and development speed.</p> </blockquote> <p>If so, should I minimize the number of docker layers?</p> <p>In your case, no.<br> What needs to be minimized is the build time, which means:</p> <ul> <li>making sure the most general steps, and the longest are first, that will then cached, allowing you to fiddle with the last lines of your Dockerfile (the most specific commands) while having a quick rebuild time.</li> <li>making sure the longest RUN command come first and in their own layer (again to be cached), instead of being chained with other RUN commands: if one of those fail, the long command will have to be re-executed. If that long command is isolated in its own (Dockerfile line)/layer, it will be cached.</li> </ul> <hr> <p>That being said, <a href="https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/" rel="noreferrer">the documentation you mention</a> comes from <a href="https://github.com/docker/docker.github.io" rel="noreferrer"><code>docker/docker.github.io</code></a>, precisely <a href="https://github.com/docker/docker.github.io/pull/4992" rel="noreferrer">PR 4992</a> and <a href="https://github.com/docker/docker.github.io/pull/4854" rel="noreferrer">PR 4854</a>, after a <a href="https://docs.docker.com/engine/reference/builder/#label" rel="noreferrer"><code>docker build LABEL</code> section</a>.<br> So this section comes after a similar remark about <code>LABEL</code>, and just emphasize the commands creating layers.<br> Again, in your case, that would not be important.</p>
33,185,999
View or function '' is not updatable because the modification affects multiple base tables
<p>I'm attempting to create a sql script that should check to see if a row exists. If one doesn't exist, I want to create one and if one does exist, I want to update it.</p> <p>However, in my code below, the INSERT line throws the following error:</p> <blockquote> <p>View or function '' is not updatable because the modification affects multiple base tables.</p> </blockquote> <p>Is there a way to find out what other base tables this would affect and how to achieve my objective?</p> <p>SQL code:</p> <pre><code>IF NOT EXISTS (SELECT * FROM g4b_stockcountsummary WHERE g4b_stockcountid = @scid AND g4b_protoproductid = @ppid) BEGIN --stock count data doesn't exist for the given product/stock count, create new record SET @difference = @count - @expectedtotal INSERT INTO g4b_stockcountsummary (g4b_stockcountsummaryid, g4b_stockcountid, g4b_protoproductid, g4b_expectedtotal, g4b_counttotal, g4b_difference) VALUES (NEWID(), @scid, @ppid, @expectedtotal, @count, @difference) END ELSE BEGIN --stock count data already exists for the given product/stock count, update record DECLARE @originalcount INT SET @originalcount = (SELECT g4b_counttotal FROM g4b_stockcountsummary WHERE g4b_stockcountid = @scid AND g4b_protoproductid = @ppid) SET @count = @originalcount + @count SET @difference = @count - @expectedtotal UPDATE g4b_stockcountsummary SET g4b_expectedtotal = @expectedtotal, g4b_counttotal = @count, g4b_difference = @difference WHERE g4b_stockcountid = @scid AND g4b_protoproductid = @ppid END </code></pre>
33,186,052
1
3
null
2015-10-17 11:17:14.123 UTC
null
2015-10-17 20:28:34.64 UTC
2015-10-17 11:25:12.513 UTC
null
13,302
null
2,903,635
null
1
8
sql|sql-server|tsql
38,968
<p><code>g4b_stockcountsummary</code> is a view. Views <em>can be</em> updatable, but only under certain conditions. These are listed in the <a href="https://msdn.microsoft.com/en-us/library/ms187956.aspx" rel="noreferrer">documentation</a> and they start:</p> <blockquote> <p><strong>Updatable Views</strong></p> <p>You can modify the data of an underlying base table through a view, as long as the following conditions are true:</p> <ul> <li>Any modifications, including <code>UPDATE</code>, <code>INSERT</code>, and <code>DELETE</code> statements, must reference columns from only one base table.</li> </ul> </blockquote> <p>Hence, you cannot do what you want. You either need to fix the view or update each base table independently.</p> <p>I should point out that lad2025 is correct. You can use an <code>instead of</code> trigger on the view to support the <code>update</code>. The documentation is referring to the base update on the view.</p>
1,440,006
Java: SortedMap, TreeMap, Comparable? How to use?
<p>I have a list of objects I need to sort according to properties of one of their fields. I've heard that SortedMap and Comparators are the best way to do this.</p> <ol> <li>Do I implement Comparable with the class I'm sorting, or do I create a new class?</li> <li>How do I instantiate the SortedMap and pass in the Comparator?</li> <li>How does the sorting work? Will it automatically sort everything as new objects are inserted?</li> </ol> <p><strong>EDIT:</strong> This code is giving me an error:</p> <pre><code>private TreeMap&lt;Ktr&gt; collection = new TreeMap&lt;Ktr&gt;(); </code></pre> <p>(Ktr implements <code>Comparator&lt;Ktr&gt;</code>). Eclipse says it is expecting something like <code>TreeMap&lt;K, V&gt;</code>, so the number of parameters I'm supplying is incorrect.</p>
1,440,035
5
1
null
2009-09-17 16:45:39.487 UTC
4
2009-09-17 22:46:11 UTC
2009-09-17 17:02:14.693 UTC
null
147,601
null
147,601
null
1
7
java|interface|comparator|treemap|sortedmap
43,752
<ol> <li>The simpler way is to implement <code>Comparable</code> with your existing objects, although you could instead create a <code>Comparator</code> and pass it to the <code>SortedMap</code>.<br> Note that <a href="http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html" rel="noreferrer"><code>Comparable</code></a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a> are two different things; a class implementing <code>Comparable</code> compares <code>this</code> to another object, while a class implementing <code>Comparator</code> compares two <em>other</em> objects.</li> <li>If you implement <code>Comparable</code>, you don't need to pass anything special into the constructor. Just call <code>new TreeMap&lt;MyObject&gt;()</code>. (<strong>Edit:</strong> Except that of course <code>Maps</code> need two generic parameters, not one. Silly me!)<br> If you instead create another class implementing <code>Comparator</code>, pass an instance of that class into the constructor.</li> <li>Yes, according to the <a href="http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html" rel="noreferrer"><code>TreeMap</code> Javadocs</a>.</li> </ol> <hr> <p><strong>Edit:</strong> On re-reading the question, none of this makes sense. If you already have a list, the sensible thing to do is implement <code>Comparable</code> and then call <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List)" rel="noreferrer"><code>Collections.sort</code></a> on it. No maps are necessary.</p> <p>A little code:</p> <pre><code>public class MyObject implements Comparable&lt;MyObject&gt; { // ... your existing code here ... @Override public int compareTo(MyObject other) { // do smart things here } } // Elsewhere: List&lt;MyObject&gt; list = ...; Collections.sort(list); </code></pre> <p>As with the <code>SortedMap</code>, you could instead create a <code>Comparator&lt;MyObject&gt;</code> and pass it to <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)" rel="noreferrer"><code>Collections.sort(List, Comparator)</code></a>.</p>
1,660,676
XmlDocument.Load Vs XmlDocument.LoadXml
<p>I just came across with a problem using <code>XmlDocument.LoadXml</code>.</p> <p>The application was crashing, giving the following error:</p> <blockquote> <p>"Data at the root level is invalid. Line 1, position 1"</p> </blockquote> <p>After inspecting the XML and finding nothing wrong with it, I googled a bit and found a tip to use <code>XmlDocument.Load</code> instead of <code>XmlDocument.LoadXml</code>.</p> <p>I have tried it and it works perfectly.</p> <p>My question is: What is the difference between the 2 methods and what could have cause one to work and the other to fail? </p>
1,660,695
5
0
null
2009-11-02 11:16:05.987 UTC
1
2016-06-27 14:10:19.867 UTC
2016-06-27 14:10:19.867 UTC
null
107,625
null
32,037
null
1
23
c#|xmldocument
53,603
<p><a href="http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx" rel="noreferrer">XmlDocument.Load</a> is used to load XML either from a stream, TextReader, path/URL, or XmlReader. <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.loadxml.aspx" rel="noreferrer">XmlDocument.LoadXml</a> is used to load the XML contained within a string.</p> <p>They're fundamentally different ways of loading XML, depending on where the XML is actually stored. So it sounds like you were using the wrong method for where your XML is.</p>
1,814,736
Add image to layout in ruby on rails
<p>I would like to add an image in my template for my ruby on rails project where i currenly have the code <code>&lt;img src="../../../public/images/rss.jpg" alt="rss feed" /&gt;</code> in a the layout <code>stores.html.erb</code> file however this doesn't seem to load as it looks like its missing a route which i'm not sure what its supposed to be. </p> <p>Any ideas please?</p>
1,814,746
6
0
null
2009-11-29 05:25:34.5 UTC
22
2017-11-24 15:56:23.217 UTC
null
null
null
null
207,358
null
1
75
ruby-on-rails|ruby|image|layout
172,526
<p>Anything in the <code>public</code> folder is accessible at the root path (<code>/</code>) so change your img tag to read:</p> <pre><code>&lt;img src="/images/rss.jpg" alt="rss feed" /&gt; </code></pre> <p>If you wanted to use a rails tag, use this:</p> <pre><code>&lt;%= image_tag("rss.jpg", :alt =&gt; "rss feed") %&gt; </code></pre>
2,199,637
Is it possible to host a bare Git repository using Dropbox, to share code?
<p>I realize that there are <a href="https://stackoverflow.com/questions/1960799/using-gitdropbox-together-effectively">similar questions</a>, but my question is slightly different: I'm wondering whether sharing a <em>bare repository</em> via a synchronized Dropbox folder on multiple computers would work for <strong>sharing code</strong> via Git?</p> <p>In other words: <strong>is sharing a Git repo via Dropbox the same as sharing it from one centralized location, for example, via SSH or HTTP?</strong></p> <p>Does the repo get updated on each person's local drive? Is this the same as sharing a Git repo via a shared network drive?</p> <p><strong>Note:</strong> This is <strong>not</strong> an empirical question: it seems to work fine. I'm asking whether the way a Git repo is structured is compatible with this way of sharing. </p> <p><strong>EDIT</strong> To clarify/repeat, I'm talking about keeping the Git repository on Dropbox as a <strong><em>bare repository</em></strong>. I'm not talking about keeping the actual files that are under source control in Dropbox.</p>
5,044,399
8
4
null
2010-02-04 12:34:57.25 UTC
11
2017-02-14 12:50:08.553 UTC
2017-05-23 12:25:29.8 UTC
user456814
-1
null
8,047
null
1
21
git|dropbox
10,669
<p>I'm pretty sure that this is unsafe. There's a bunch of moving parts in a Git repository, and Dropbox could easily wreck one of them. For example, you might end up with incorrect branch tips (master, etc.) in the <code>refs</code> directory, or your object store might stop working if the <code>objects/info/packs</code> file has the wrong contents. Git repos are fairly simple and robust, but they are not just dumb unbreakable storage.</p> <p>Accessing remote repositories through SSH, git, or HTTP, or even locally on a network file system, is safe because the repository is only accessed through a <code>git</code> process, which makes sure that everything is moved into place in the right order. But Dropbox doesn't make any kind of guarantees about ordering, so you might lose data.</p> <p>Just use a Git server (or any SSH server) instead -- if you don't have one, <a href="https://github.com/plans" rel="nofollow noreferrer">GitHub</a>, <a href="https://bitbucket.org/product/pricing?tab=host-in-the-cloud" rel="nofollow noreferrer">Bitbucket</a> or <a href="https://about.gitlab.com/products/" rel="nofollow noreferrer">GitLab</a> come to mind. It'll save you a lot of trouble, and it's no harder to use than a local repository shared through Dropbox (you just have SSH URLs instead of local paths).</p>
2,318,806
Hiding PHP's X-Powered-By header
<p>I know in PHP, it sends the <code>X-Powered-By</code> header to have the PHP version.</p> <p>I also know by appending some checksums, you can get access to PHP's credits, and some random images (<a href="http://www.0php.com/php_easter_egg.php" rel="noreferrer">more info here</a>).</p> <p>I also know in php.ini you can turn <code>expose_php = off</code>.</p> <p>But here is something I have done on a few sites, and that is use</p> <pre><code>header('X-Powered-By: Alex'); </code></pre> <p>When I view the headers, I can see that it is now 'Alex' instead of the PHP version. My question is, will this send the previous PHP header first (before it reaches my <code>header()</code>, and is it detectable by any sniffer program? Or are headers 'collected' by PHP, <em>before</em> being sent back to the browser?</p> <p>By the way, this is not for security by obscurity, just curious how headers work in PHP.</p>
2,319,073
8
1
null
2010-02-23 14:26:13.797 UTC
9
2022-02-22 22:12:33.85 UTC
2012-06-02 12:19:41.867 UTC
null
367,456
null
31,671
null
1
50
php|header|http-headers
58,100
<p>In PHP, headers aren't sent until PHP encounters its first output statement.</p> <p>This includes anything before the first <code>&lt;?php</code>.</p> <p>This is also why setcookie sends throws a warning if you try to use it after something has been output:</p> <blockquote> <p>Warning: Cannot modify header information - headers already sent by (output started at /path/to/php/file.php:100) in /path/to/php/file.php on line 150</p> </blockquote> <p>Note that none of this applies if <a href="http://php.net/outcontrol" rel="noreferrer">output buffering</a> is in use, as the output will not be sent until the appropriate output buffering command is run.</p>
1,366,584
How do I calculate power-of in C#?
<p>I'm not that great with maths and C# doesn't seem to provide a power-of function so I was wondering if anyone knows how I would run a calculation like this:</p> <pre><code>var dimensions = ((100*100) / (100.00^3.00)); </code></pre>
1,366,594
9
1
null
2009-09-02 09:06:15.503 UTC
5
2022-09-24 13:41:06.82 UTC
2013-09-03 09:11:22.247 UTC
null
138,578
null
109,251
null
1
60
c#|math
136,552
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.math.pow.aspx" rel="noreferrer" title="System.Math.Pow">Math.Pow</a>. The function takes a value and raises it to a specified power:</p> <pre><code>Math.Pow(100.00, 3.00); // 100.00 ^ 3.00 </code></pre>
2,121,907
Drag & Drop Reorder Rows on NSTableView
<p>I was just wondering if there was an easy way to set an NSTableView to allow it to reorder its rows without writing any pasteboard code. I only need it to be able to do this internally, within one table. I have no issue writing the pboard code, except that I'm fairly sure that I saw Interface Builder have a toggle for this somewhere / saw it working by default. It certainly seems like a common enough task.</p> <p>Thanks</p>
2,135,977
10
0
null
2010-01-23 03:05:43.567 UTC
11
2022-08-22 06:34:51.083 UTC
null
null
null
null
257,261
null
1
21
macos|drag-and-drop|nstableview
12,599
<p>If you take a look at the tool tip in IB you'll see that the option you refer to</p> <pre><code>- (BOOL)allowsColumnReordering </code></pre> <p>controls, well, column reordering. I do not believe there is any other way to do this other than the standard drag-and-drop API for table views.</p> <p><strong>EDIT:</strong> <em>( 2012-11-25 )</em></p> <p>The answer refers to drag-and-drop reordering of <code>NSTableViewColumns</code>; and while it was the accepted answer at the time. It does not appear, now nearly 3 years on, to be correct. In service of making the information useful to searchers, I'll attempt to give the more correct answer.</p> <p>There is no setting that allows drag and drop reordering of <code>NSTableView</code> rows in Interface Builder. You need to implement certain <code>NSTableViewDataSource</code> methods, including:</p> <pre><code>- tableView:acceptDrop:row:dropOperation: - (NSDragOperation)tableView:(NSTableView *)aTableView validateDrop:(id &lt; NSDraggingInfo &gt;)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)operation - (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard </code></pre> <p>There are other SO question that address this reasonably thoroughly, including <a href="https://stackoverflow.com/questions/11116265/reordering-of-nstableview-rows-in-view-based-tableview">this one</a></p> <p>Apple link to <a href="https://developer.apple.com/documentation/appkit/nstableviewdatasource/1527733-tableview" rel="nofollow noreferrer">Drag and Drop APIs</a>.</p>
1,762,555
Creating .pem file for APNS?
<p>How do I create a .pem file to be stored in the hosting server for APN payload data?</p>
1,762,824
11
2
null
2009-11-19 11:06:47.44 UTC
178
2020-06-23 14:41:07.347 UTC
2016-01-20 02:22:35.04 UTC
null
289,319
null
97,651
null
1
188
iphone|ssl-certificate|apple-push-notifications|payload
164,532
<p>Here is what I did, From:<a href="http://blog.boxedice.com/2009/07/10/how-to-build-an-apple-push-notification-provider-server-tutorial/" rel="noreferrer">blog.boxedice.com</a> and "iPhone Advanced Projects" chapter 10 byJoe Pezzillo.</p> <p>With the aps_developer_identity.cer in the keychain:</p> <ol> <li>Launch Keychain Access from your local Mac and from the login keychain, filter by the Certificates category. You will see an expandable option called “Apple Development Push Services”</li> <li>Right click on “Apple Development Push Services” > Export “Apple Development Push Services ID123″. Save this as <code>apns-dev-cert.p12</code> file somewhere you can access it. There is no need to enter a password.</li> <li><p>The next command generates the cert in Mac’s Terminal for PEM format (Privacy Enhanced Mail Security Certificate):</p> <pre><code>openssl pkcs12 -in apns-dev-cert.p12 -out apns-dev-cert.pem -nodes -clcerts </code></pre></li> </ol> <p>On the server set the file permission of this unencrypted key by using chmod 400.</p>
1,579,162
Are design patterns really language weaknesses?
<p>Should today's patterns <a href="http://blog.plover.com/prog/design-patterns.html" rel="noreferrer">be seen as defects or missing features in Java and C++</a>?</p> <ul> <li><strong>Subroutine</strong> was a design pattern for machine language in the 50s and 60s. </li> <li><strong>Object-Oriented Class</strong> was a design pattern for C in the 70s.</li> <li><p><strong>Visitors, Abstract Factories, Decorators, and Façades</strong> are design patterns for Java and C++ today. </p> <p>What will tomorrow's languages look like? What patterns will <em>they</em> have?</p></li> </ul>
1,579,384
12
0
2009-10-16 19:26:52.96 UTC
2009-10-16 16:53:48.747 UTC
24
2021-01-05 04:17:27.03 UTC
2012-04-30 22:46:02.92 UTC
null
449,906
null
182,072
null
1
43
design-patterns|history|language-design
5,310
<p>Some canonized design patterns -- Adapter, Factory, Command, Visitor, etc -- are approximations of features which are baked into other languages. Off the top of my head:</p> <ul> <li><p>Event-handlers in C# are baked-in versions of the observer pattern. Think about how you'd wire up events in C# if you had to roll your own observer each time.</p></li> <li><p>Visitor pattern is a verbose approximation of <a href="http://nice.sourceforge.net/visitor.html" rel="noreferrer">multimethods</a>, <a href="http://en.wikipedia.org/wiki/Objective-C#Forwarding" rel="noreferrer">message forwarding</a>, or a really weak form of <a href="https://stackoverflow.com/questions/694651/what-task-is-best-done-in-a-functional-programming-style/694822#694822">pattern matching</a>.</p></li> <li><p>Command pattern wraps up a particular behavior so you can pass the object between methods, which more or less approximates first-class functions.</p></li> <li><p>Strategy pattern allows you to dynamically insert a behavior into an object, so that at any time you can modify the object by swapping out one behavior with another. In the functional programming world, we call this function composition.</p></li> <li><p>Abstract factory pattern accepts an argument and returns a factory as a result. In general, you can think of factories as basically wrappers around a function (more specifically, wrappers around a constructor). So, you pass arguments to a function and get a function as a result, making this pattern pretty analogous to currying.</p></li> <li><p>Decorator pattern allows you to attach or remove behaviors to an object at runtime. In JavaScript, you can add or remove functions without explicitly implementing the decorator pattern thanks to the "prototype" OO model.</p></li> </ul> <p>So, we have a bunch of design patterns which emulate features intrinsic to other languages. Feature envy doesn't necessarily indicate a weakness in the language -- it's the boilerplate code that you need to write <em>over and over and over</em> which indicates the language weakness.</p>
1,601,933
How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?
<p>When I have a link that is wired-up with a jQuery or JavaScript event such as:</p> <pre><code>&lt;a href="#"&gt;My Link&lt;/a&gt; </code></pre> <p>How do I prevent the page from scrolling to the top? When I remove the href attribute from the anchor the page doesn't scroll to the top but the link doesn't appear to be click-able.</p>
1,601,948
16
0
null
2009-10-21 16:20:18.927 UTC
46
2022-07-20 06:29:52.23 UTC
2015-02-24 13:52:14.353 UTC
null
1,709,587
null
77,538
null
1
158
javascript|html
190,536
<p>You need to prevent the default action for the click event (i.e. navigating to the link target) from occurring.</p> <p>There are two ways to do this.</p> <h2>Option 1: <code>event.preventDefault()</code></h2> <p>Call the <code>.preventDefault()</code> method of the event object passed to your handler. If you're using jQuery to bind your handlers, that event will be an instance of <a href="https://api.jquery.com/category/events/event-object/" rel="noreferrer"><code>jQuery.Event</code></a> and it will be the jQuery version of <a href="https://api.jquery.com/event.preventDefault/" rel="noreferrer"><code>.preventDefault()</code></a>. If you're using <code>addEventListener</code> to bind your handlers, it will be an <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event" rel="noreferrer"><code>Event</code></a> and the raw DOM version of <a href="https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault" rel="noreferrer"><code>.preventDefault()</code></a>. Either way will do what you need.</p> <p>Examples:</p> <pre><code>$('#ma_link').click(function($e) { $e.preventDefault(); doSomething(); }); document.getElementById('#ma_link').addEventListener('click', function (e) { e.preventDefault(); doSomething(); }) </code></pre> <h2>Option 2: <code>return false;</code></h2> <p><a href="https://api.jquery.com/on/" rel="noreferrer">In jQuery</a>:</p> <blockquote> <p>Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault()</p> </blockquote> <p>So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:</p> <pre><code>$('#ma_link').click(function(e) { doSomething(); return false; }); </code></pre> <p>If you're using raw DOM events, this will also work on modern browsers, since the HTML 5 spec dictates this behaviour. However, older versions of the spec did not, so if you need maximum compatibility with older browsers, you should call <code>.preventDefault()</code> explicitly. See <a href="https://stackoverflow.com/a/18971429/1709587">event.preventDefault() vs. return false (no jQuery)</a> for the spec detail.</p>
1,529,298
What's your Modus Operandi for solving a (programming) problem?
<p>While solving any programming problem, what is your <a href="http://en.wikipedia.org/wiki/Modus_operandi" rel="nofollow noreferrer">modus operandi</a>? How do you fix a problem?<br> Do you write everything you can about the observable behaviors of the bug or problem? </p> <p>Take me through the mental checklist of actions you take.</p> <p>(As they say - <em><code>First, solve the problem. Then, write the code</code></em>)</p>
1,529,313
30
6
2009-10-07 03:12:39.947 UTC
2009-10-07 03:12:39.947 UTC
27
2019-05-03 16:05:45.863 UTC
2013-07-19 14:56:40.847 UTC
user1228
null
null
170,339
null
1
33
language-agnostic
3,544
<p><strong>Step away from the computer</strong> and grab some paper and a pen or pencil if you prefer. </p> <p>If I'm around the computer then I try to program a solution right then and there and it normally doesn't work right or it's just crap. Pen and paper force me to think a little more.</p>
33,642,199
Spring boot Autowired not working in Configuration class
<p>I have a Spring Boot application which uses a Redis server for caching. I use Spring RedisTemplate for connecting to the Redis server. I configure the Redis parameters in a <code>@Confiuration</code> class. However, the redis url and port are stored in DB, and the corresponding DAO is contained as a member in another class (which also contains loads of other global information). I'm trying to autowire the parent class in the Configuration class, but I get an error. This is the code I have:</p> <pre><code>@Configuration public class MyConfiguration { @Autowired protected GlobalPropertiesLoader globalPropertiesLoader; @Bean JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory factory = new JedisConnectionFactory(); GlobalPropertiesDAO globalPropertiesDAO = globalPropertiesLoader.getGlobalProperties(); factory.setHostName(globalPropertiesDAO.getRedisUrl()); factory.setPort(globalPropertiesDAO.getRedisPort()); factory.setUsePool(true); return factory; } @Bean RedisTemplate&lt; String, Object &gt; redisTemplate() { final RedisTemplate&lt; String, Object &gt; template = new RedisTemplate&lt; String, Object &gt;(); template.setConnectionFactory( jedisConnectionFactory() ); template.setKeySerializer( new StringRedisSerializer() ); template.setHashValueSerializer( new GenericToStringSerializer&lt; Object &gt;( Object.class ) ); template.setValueSerializer( new GenericToStringSerializer&lt; Object &gt;( Object.class ) ); return template; } } </code></pre> <p>GlobalPropertiesLoader is the class which contains the DAO (GlobalPropertiesDAO) as an object. When I try to run my application, I get the following error:</p> <pre><code>Exception in thread "main" Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mypkg.CommonsConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected com.utils.GlobalPropertiesLoader com.mypkg.CommonsConfiguration.globalPropertiesLoader; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.utils.GlobalPropertiesLoader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1127) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) ... 50 more Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected com.utils.GlobalPropertiesLoader com.mypkg.CommonsConfiguration.globalPropertiesLoader; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.utils.GlobalPropertiesLoader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 61 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.utils.GlobalPropertiesLoader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) </code></pre> <p>What is the problem here? Is it not possible to Autowire in <code>@Configuration</code> class? Because I'm able to autowire the same class in other classes.</p> <p>::::::::::::::::::::: EDIT ::::::::::::::::::::</p> <p>I tried <code>@Import</code> as below:</p> <pre><code>@Configuration @Import({GlobalPropertiesLoader.class}) public class CommonsConfiguration { @Autowired GlobalPropertiesLoader globalPropertiesLoader; .... } </code></pre> <p>However, when I do this, I get the following error:</p> <pre><code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.utils.GlobalPropertiesLoader': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.persistence.repositories.GlobalPropertiesRepository com.utils.GlobalPropertiesLoader.globalPropertiesRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.persistence.repositories.GlobalPropertiesRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1127) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) ... 63 more Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.persistence.repositories.GlobalPropertiesRepository com.utils.GlobalPropertiesLoader.globalPropertiesRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.persistence.repositories.GlobalPropertiesRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 74 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.persistence.repositories.GlobalPropertiesRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) </code></pre> <p>This is the GlobalPropertiesLoader class:</p> <pre><code>@Component @Scope("singleton") public class GlobalPropertiesLoader { @Autowired public GlobalPropertiesRepository globalPropertiesRepository; private GlobalPropertiesDAO globalProperties; /* * Load GlobalProperties once upon loading the context. */ @PostConstruct public void init(){ globalProperties = globalPropertiesRepository.findOne(1L); .... } } </code></pre> <p>And the GlobalPropertiesRepository java:</p> <pre><code>@Repository public interface GlobalPropertiesRepository extends CrudRepository&lt;GlobalPropertiesDAO, Long&gt;{ } </code></pre> <p>Thanks.</p>
33,660,489
5
4
null
2015-11-11 00:24:00.85 UTC
4
2021-09-08 12:12:05.26 UTC
2015-11-11 21:37:17.323 UTC
null
2,789,812
null
2,789,812
null
1
18
spring|spring-boot
73,109
<p><strong>@Import</strong> is to add a configuration class into another configuration class.</p> <p><a href="http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s03.html" rel="noreferrer">http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s03.html</a></p> <p><strong>@ComponentScan</strong> is to scan for components declared in your code, like @Service, @Component, @Repository, among others.</p> <p><a href="http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch06s02.html" rel="noreferrer">http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch06s02.html</a></p> <p>I think you need to add in your configuration class the @ComponentScan so it can scan the package with your component classes.</p> <pre><code>@Configuration @ComponentScan(value = "org.foo.path.baseFolder") public class MyConfiguration { @Autowired protected GlobalPropertiesLoader globalPropertiesLoader; </code></pre>
8,799,419
What is the correct MIME Type for JSON?
<p>I am having problems converting the JSON string in Chrome.</p> <p>Thank you!</p>
8,799,424
1
2
null
2012-01-10 06:30:34.12 UTC
1
2016-02-18 15:38:16.863 UTC
null
null
null
null
1,140,202
null
1
42
json
29,596
<p>The MIME media type for JSON text is <code>application/json</code></p> <p>Hope this helps</p>
6,799,120
Script all data from SQL Server database
<p>I have two databases with equivalent structure and I need to extract data from one of them in form of <code>INSERT</code> statements (generate script to apply it on the other database). </p> <p>How can I do it using Management Studio?</p>
6,799,160
3
0
null
2011-07-23 08:05:41.403 UTC
8
2016-10-29 08:41:14.963 UTC
2011-07-23 08:14:37.437 UTC
null
13,302
null
377,133
null
1
25
sql|sql-server|tsql|sql-server-2008|ssms
43,766
<p>You could use the <strong>free</strong> <a href="http://www.ssmstoolspack.com/" rel="nofollow">SSMS Toolpack</a> add-in for SQL Server Management Studio.</p> <p>See the section on <em>Generate Insert statements from resultsets, tables or database</em></p> <p><strong>Update:</strong> OK, for SSMS Toolpack in SSMS 2012, a licensing scheme has been introduced. SSMS Toolpack for earlier versions of SSMS are however still free.</p>
6,575,159
Get image dimensions with Javascript before image has fully loaded
<p>I've read about various kinds of ways getting image dimensions once an image has fully loaded, but would it be possible to get the dimensions of any image once it just started to load?</p> <p>I haven't found much about this by searching (which makes me believe it's not possible), but the fact that a browser (in my case Firefox) shows the dimensions of any image I open up in a new tab right in the title after it just started loading the image gives me hope that there actually is a way and I just missed the right keywords to find it.</p>
6,575,319
3
0
null
2011-07-04 18:58:25.46 UTC
20
2017-01-05 09:52:02.91 UTC
null
null
null
null
828,591
null
1
46
javascript|image|loading|dimensions
50,062
<p>You are right that one can get image dimensions before it's fully loaded.</p> <p>Here's a solution (<a href="http://jsfiddle.net/aUk9P/" rel="noreferrer">demo</a>):</p> <pre><code>var img = document.createElement('img'); img.src = 'some-image.jpg'; var poll = setInterval(function () { if (img.naturalWidth) { clearInterval(poll); console.log(img.naturalWidth, img.naturalHeight); } }, 10); img.onload = function () { console.log('Fully loaded'); } </code></pre>
6,870,320
The EXECUTE permission is denied on the user-defined table types?
<p>I have a question about <a href="http://msdn.microsoft.com/en-us/library/bb522526.aspx">User-Defined Table Types</a> in SQL Server 2008.</p> <p>For the need of one of the ASP.NET application we defined our own table-types on SQL Server 2008 to use them as parameters in the stored procedures (when executing sql command in ASP.NET application we pass DataTable object as parameter for stored procedure <a href="http://www.codeproject.com/KB/database/sqlserver2008.aspx">see here for an example</a>)</p> <p>The problem is that when we run Sql command (execute stored procedure) from ASP.NET we get an error:</p> <blockquote> <p>The EXECUTE permission was denied on the object 'ourTableType', database 'ourDatabase', schema 'ourSchema'.</p> </blockquote> <p>Why is that so? Why do we need to set permission on user-defined table types? Why is not enough to have permission set just on stored procedure that uses it? And if we have to set it no matter what, why there is no <code>EXECUTE</code> permission type to set in properties window whatsoever (I can see only <code>Control</code>, <code>References</code>, <code>Take Ownership</code>, <code>View Definition</code>)?</p> <p>What I also don't understand is that setting permission to <code>Control</code> in properties window solves the problem and the stored procedure runs without problems.</p>
7,982,488
3
4
null
2011-07-29 08:09:43.94 UTC
21
2022-04-15 10:37:06.94 UTC
null
null
null
null
672,630
null
1
100
asp.net|security|sql-server-2008|stored-procedures|user-defined-types
59,162
<p>I really hope you've solved this by now, seeing as the question is almost 4 months old, but in case you haven't, here's what I think is the answer.</p> <pre><code>GRANT EXEC ON TYPE::[schema].[typename] TO [User] GO </code></pre>
6,736,052
DataBinding: 'System.Data.DataRowView' does not contain a property with the name
<p>I am getting this weird error... the primary key in my database is 'DocumentID' so I know that is not the issue. I am trying to get the select,edit &amp; delete gridview buttons to work but I need the datakeynames to be set correctly for them to be available to use. any ideas?</p> <pre><code>&lt;asp:GridView ID="GridView1" runat="server" DataSourceID="sdsDocuments" EnableModelValidation="True" SelectedIndex="0" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" DataKeyNames="DocumentID, DocumentTitle, DocumentBody"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="DocumentID" HeaderText="DocumentID" ReadOnly="True" SortExpression="ID" /&gt; &lt;asp:BoundField DataField="DocumentTitle" HeaderText="DocumentTitle" SortExpression="Title" /&gt; &lt;asp:BoundField DataField="DocumentBody" HeaderText="DocumentBody" SortExpression="Body" /&gt; &lt;asp:CommandField ShowSelectButton="True" ShowDeleteButton="True" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;asp:SqlDataSource ID="sdsDocuments" runat="server" ConnectionString="&lt;%$ ConnectionStrings:blcDocumentationConnectionString %&gt;" SelectCommand="SELECT [DocumentTitle], [DocumentBody] FROM [tblDocument]" /&gt; </code></pre> <p>Here is the stack trace...</p> <pre><code> [HttpException (0x80004005): DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'DocumentID'.] System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) +8672869 System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) +2178 System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +57 System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data) +14 System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +114 System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +31 System.Web.UI.WebControls.DataBoundControl.PerformSelect() +142 System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +73 System.Web.UI.WebControls.GridView.DataBind() +4 System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82 System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +72 System.Web.UI.Control.EnsureChildControls() +87 System.Web.UI.Control.PreRenderRecursiveInternal() +44 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Control.PreRenderRecursiveInternal() +171 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842 </code></pre>
6,736,181
4
0
null
2011-07-18 16:24:34.103 UTC
1
2020-06-24 14:20:35.293 UTC
null
null
null
null
636,824
null
1
15
asp.net|sql-server-2005
103,239
<p>Well, you haven't selected the <code>documentid</code> column and hence it's not present in either datatable or dataview which you are binding to grid OR referencing that column through datatable.</p> <p>Change your query to </p> <pre><code> SelectCommand="SELECT [DocumentID],[DocumentTitle], [DocumentBody] FROM [tblDocument]" /&gt; </code></pre>
18,563,579
How can I see the delayed job queue?
<p>I wonder if I succeeded to get <a href="https://github.com/collectiveidea/delayed_job">Delayed::Job</a> working. Can't see jobs in the <code>delayed_jobs</code> table.</p> <ul> <li>Is that normal?</li> <li>Is there any other ways too see job queue?</li> </ul>
18,563,660
2
0
null
2013-09-01 22:30:13.983 UTC
12
2019-09-11 21:12:10.25 UTC
2015-07-07 09:19:29.647 UTC
null
980,524
null
1,801,147
null
1
71
ruby-on-rails|delayed-job
48,574
<p>DelayedJob stores a database record for each enqueued job so you can retrieve them directly through the rails console (assuming you are using ActiveRecord or similar).</p> <p>Open the rails console:</p> <pre><code>$ rails c </code></pre> <p>and then query the enqueued jobs:</p> <pre><code>$ Delayed::Job.all </code></pre> <p>or</p> <pre><code>$ Delayed::Job.last </code></pre> <p>Check out the <a href="https://github.com/collectiveidea/delayed_job#gory-details" rel="noreferrer">documentation</a>.</p> <p>If you installed delayed_job with another database like Redis you may want to go and check in there the queued jobs.</p>
15,550,560
Background image not displaying in chrome browser
<p>I've created a small search widget, however the background doesn't appear when viewing it through chrome. I've tested IE, FF and safari which all appear OK.</p> <p><a href="http://paradigmsearch.co.uk/widget/?id=1" rel="noreferrer">http://paradigmsearch.co.uk/widget/?id=1</a></p> <p>I'm usually reluctant to put layout issue on SO. However, I've been going over this for a while. </p> <p>On the element:</p> <pre><code>&lt;div class="widget" id="id_300x250"&gt; </code></pre> <p>I'm applying the following CSS definitions</p> <pre><code>.widget { font-family: arial; height: 250px; width: 300px; border: none; background: url('/uploads/widget_background/cached/proportional/300x250/1_512648b566578.png') no-repeat center center; } </code></pre> <p>The background just isn't visible. If this is a really silly mark-up / css oversight then I apologies profusely.</p> <p>Currently using chrome browser Version 25.0.1364.172m</p>
15,550,900
2
2
null
2013-03-21 14:40:23.94 UTC
null
2020-01-19 19:02:19.877 UTC
2013-10-15 14:50:17.137 UTC
null
1,317,805
null
1,285,809
null
1
8
css|html|google-chrome
38,572
<p>This is a pretty funny issue which I only figured out when opening your page in Chrome's incognito mode: Your background image is being blocked by AdBlock.</p> <p>Also, for rendering purposes it's better practice to stick <code>style</code> elements in your page's <code>head</code>.</p>
27,637,184
What is DOM reflow?
<p>I was reading about the difference between two CSS properties <code>display:none</code> and <code>visibility:hidden</code> and encountered the <strong>DOM reflow</strong> term.</p> <p>The statement was</p> <blockquote> <p><code>display: none</code> causes a DOM reflow whereas <code>visibility: hidden</code> does not.</p> </blockquote> <p>So my question is:</p> <h3>What is DOM reflow and how does it work?</h3>
27,637,245
3
3
null
2014-12-24 12:47:14.74 UTC
43
2020-07-17 09:10:57.263 UTC
2020-07-17 09:10:57.263 UTC
null
3,249,501
null
3,540,289
null
1
85
html|css|dom|visibility|reflow
45,428
<blockquote> <p>A <strong>reflow</strong> computes the layout of the page. A reflow on an element recomputes the dimensions and position of the element, and it also triggers further reflows on that element’s children, ancestors and elements that appear after it in the DOM. Then it calls a final repaint. Reflowing is very expensive, but unfortunately it can be triggered easily.</p> <p>Reflow occurs when you:</p> <ul> <li>insert, remove or update an element in the DOM</li> <li>modify content on the page, e.g. the text in an input box</li> <li>move a DOM element</li> <li>animate a DOM element</li> <li>take measurements of an element such as offsetHeight or getComputedStyle</li> <li>change a CSS style</li> <li>change the className of an element</li> <li>add or remove a stylesheet</li> <li>resize the window</li> <li>scroll</li> </ul> </blockquote> <p>For more information, please refer here: <a href="https://sites.google.com/site/getsnippet/javascript/dom/repaints-and-reflows-manipulating-the-dom-responsibly" rel="noreferrer">Repaints and Reflows: Manipulating the DOM responsibly</a></p>
41,162,797
How to idiomatically test for non-null, non-empty strings in Kotlin?
<p>I am new to Kotlin, and I am looking for help in rewriting the following code to be more elegant.</p> <pre><code>var s: String? = "abc" if (s != null &amp;&amp; s.isNotEmpty()) { // Do something } </code></pre> <p>If I use the following code:</p> <pre><code>if (s?.isNotEmpty()) { </code></pre> <p>The compiler will complain that</p> <pre><code>Required: Boolean Found: Boolean? </code></pre> <p>Thanks.</p>
41,162,825
4
4
null
2016-12-15 11:15:24.657 UTC
3
2021-08-18 11:47:11.86 UTC
2020-01-21 14:54:16.263 UTC
null
385,478
null
928,315
null
1
35
kotlin|kotlin-null-safety
18,634
<p>You can use <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/is-null-or-empty.html" rel="noreferrer"><code>isNullOrEmpty</code></a> or its friend <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/is-null-or-blank.html" rel="noreferrer"><code>isNullOrBlank</code></a> like so:</p> <pre><code>if(!s.isNullOrEmpty()){ // s is not empty } </code></pre> <p>Both <code>isNullOrEmpty</code> and <code>isNullOrBlank</code> are extension methods on <code>CharSequence?</code> thus you can use them safely with <code>null</code>. Alternatively turn <code>null</code> into false like so:</p> <pre><code>if(s?.isNotEmpty() ?: false){ // s is not empty } </code></pre> <p>you can also do the following </p> <pre><code>if(s?.isNotEmpty() == true){ // s is not empty } </code></pre>
4,998,870
Adding services after container has been built
<p>Is it possible to register a service at run-time, meaning after the <code>ContainerBuilder</code> has been built and the <code>Container</code> has been created (and <code>ContainerBuilder</code> disposed of)?</p>
5,009,312
2
1
null
2011-02-15 00:29:39.587 UTC
18
2019-01-14 12:20:36.32 UTC
2015-05-12 09:36:39.82 UTC
null
1,300,910
null
96,140
null
1
95
ioc-container|autofac
19,789
<p>Yes you can, using the <code>Update</code> method on <code>ContainerBuilder</code>:</p> <pre><code>var newBuilder = new ContainerBuilder(); newBuilder.Register...; newBuilder.Update(existingContainer); </code></pre>
5,360,028
emacs, unsplit a particular window split
<p>I often want to unsplit window as follows:</p> <pre><code>+--------------+-------------+ +--------------+-------------+ | | | | | | | | | | | | | | | | | | +--------------+ | --&gt; | | | | | | | | | | | | | | | | | | | | | +--------------+-------------+ +--------------+-------------+ +--------------+--------------+ +-----------------------------+ | | | | | | | | | | | | | | | +--------------+--------------+ --&gt; +-----------------------------+ | | | | | | | | | | | | +-----------------------------+ +-----------------------------+ </code></pre> <p>Currently, I start with <kbd>ctrl</kbd>-<kbd>x</kbd> <kbd>1</kbd> and then split vertically/horizontally. but my real qustion is how can one remove a particular window split with out disturbing the other window structure? Is there any elisp function in built?</p>
5,360,302
2
3
null
2011-03-19 04:17:50.787 UTC
24
2022-04-21 09:37:34.003 UTC
2022-04-21 09:37:34.003 UTC
null
5,446,749
null
399,964
null
1
105
emacs|elisp
26,814
<p>You can use the <kbd>C-x</kbd><kbd>0</kbd> key combination to delete the current window.</p>
16,200,104
Jquery add and remove table rows
<p>I have a html table that dynamically adds and removes rows with jQuery. The number of rows is limited by jQuery counter which allows a user to add up to 4 rows. My problem is that when a user creates the 4th row they have reached the limit but when they delete a row the limit still remains in place and they can't add any more rows.</p> <p><a href="http://jsfiddle.net/nallad1985/sqrrt/" rel="nofollow noreferrer">http://jsfiddle.net/nallad1985/sqrrt/</a></p> <p><strong>HTML</strong></p> <pre><code>&lt;table id="myTable" class="order-list"&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;Name&lt;/td&gt; &lt;td&gt;Price&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;input type="text" name="name" /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" name="price1" /&gt; &lt;/td&gt; &lt;td&gt;&lt;a class="deleteRow"&gt;&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;tfoot&gt; &lt;tr&gt; &lt;td colspan="5" style="text-align: left;"&gt; &lt;input type="button" id="addrow" value="Add Row" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan=""&gt;Grand Total: $&lt;span id="grandtotal"&gt;&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tfoot&gt; </code></pre> <p></p> <p><strong>JQUERY</strong></p> <pre><code>$(document).ready(function () { var counter = 0; $("#addrow").on("click", function () { var counter = $('#myTable tr').length - 2; var newRow = $("&lt;tr&gt;"); var cols = ""; cols += '&lt;td&gt;&lt;input type="text" name="name' + counter + '"/&gt;&lt;/td&gt;'; cols += '&lt;td&gt;&lt;input type="text" name="price' + counter + '"/&gt;&lt;/td&gt;'; cols += '&lt;td&gt;&lt;input type="button" id="ibtnDel" value="Delete"&gt;&lt;/td&gt;'; newRow.append(cols); if (counter == 4) $('#addrow').attr('disabled', true).prop('value', "You've reached the limit"); $("table.order-list").append(newRow); counter++; }); $("table.order-list").on("change", 'input[name^="price"]', function (event) { calculateRow($(this).closest("tr")); calculateGrandTotal(); }); $("table.order-list").on("click", "#ibtnDel", function (event) { $(this).closest("tr").remove(); calculateGrandTotal(); }); }); function calculateRow(row) { var price = +row.find('input[name^="price"]').val(); } function calculateGrandTotal() { var grandTotal = 0; $("table.order-list").find('input[name^="price"]').each(function () { grandTotal += +$(this).val(); }); $("#grandtotal").text(grandTotal.toFixed(2)); } </code></pre>
16,200,251
4
0
null
2013-04-24 19:01:34.56 UTC
4
2018-08-26 16:58:15.21 UTC
2018-08-26 16:58:15.21 UTC
null
4,370,109
null
2,088,480
null
1
5
javascript|jquery|html-table
43,013
<p>Bunch of fixes,</p> <ol> <li>Removed extra handler for delete button </li> <li>change button ID to class as you should not duplicate ID. <a href="https://stackoverflow.com/a/15341367/297641">Read why you should not duplicate ID</a>.</li> <li>Added logic to enable the Add row button. See <strong><a href="http://jsfiddle.net/sqrrt/2/" rel="nofollow noreferrer">Fixed fiddle</a></strong>. </li> <li>Removed var declaration inside Add Row handler to update the global var</li> </ol> <p><a href="http://jsfiddle.net/sqrrt/2/" rel="nofollow noreferrer">http://jsfiddle.net/sqrrt/2/</a></p> <pre><code>$("table.order-list").on("click", ".ibtnDel", function (event) { $(this).closest("tr").remove(); calculateGrandTotal(); counter -= 1 $('#addrow').attr('disabled', false).prop('value', "Add Row"); }); </code></pre>
16,449,359
Getting error "array bound is not an integer constant before ']' token"
<p>I am trying to implement a stack using an array but I receive an error.</p> <pre><code>class Stack{ private: int cap; int elements[this-&gt;cap]; // &lt;--- Errors here int top; public: Stack(){ this-&gt;cap=5; this-&gt;top=-1; }; </code></pre> <p>The indicated line has these errors:</p> <pre><code>Multiple markers at this line - invalid use of 'this' at top level - array bound is not an integer constant before ']' token </code></pre> <p>What am I doing wrong?</p>
16,449,389
3
3
null
2013-05-08 20:12:01.677 UTC
2
2022-05-08 11:26:43.873 UTC
2013-05-08 20:14:19.33 UTC
null
501,557
null
1,849,859
null
1
10
c++|arrays
69,131
<p>In C++, the size of an array must be a constant known at compile-time. You'll get an error if that isn't the case.</p> <p>Here, you have</p> <pre><code>int elements[this-&gt;cap]; </code></pre> <p>Notice that <code>this-&gt;cap</code> isn't a constant known at compile-time, since it depends on how big <code>cap</code> is.</p> <p>If you want to have a variably-sized array whose size is determined later on, consider using <code>std::vector</code>, which can be resized at runtime.</p> <p>Hope this helps!</p>
16,130,871
How do I open a link in the same window and tab using the onclick event?
<p>I have a page that has multiple divs. I want to get some information from my database to display in some of those divs and I also want it to be displayed as I click on a link to the home div. </p> <p>I also need the page to be refreshed or reopened in the same window (not in a new page or tab). Last of all, I need the page to be in the home div. </p> <p>I tried the code below and it didn't work:</p> <pre><code>&lt;a href="#home" onclick="window.open('index.jsp#home')" &gt;home&lt;/a&gt; &lt;a href="#home" onclick="location.reload()"&gt;home&lt;/a&gt; &lt;a href="#home" onclick="location.href='index.jsp'"&gt;home&lt;/a&gt; </code></pre>
16,135,682
4
0
null
2013-04-21 12:01:15.817 UTC
7
2014-05-13 07:32:47.3 UTC
2013-10-25 21:31:48.123 UTC
null
543,572
null
2,304,200
null
1
10
javascript|jquery|ajax|jsp|onclick
77,724
<p>I used this and it worked</p> <pre><code>&lt;a href="#" class="home_btn" onclick="location.reload();location.href='index.jsp'"&gt;منوی اصلی&lt;/a&gt; </code></pre>
520,250
jQuery If DIV Doesn't Have Class "x"
<p>In jQuery I need to do an if statement to see if $this doesn't contain the class '.selected'.</p> <pre><code>$(".thumbs").hover(function(){ $(this).stop().fadeTo("normal", 1.0); },function(){ $(this).stop().fadeTo("slow", 0.3); }); </code></pre> <p>Basically when this function is run (on hover) I don't want to perform the fades if the class '.selected' has been appended to the div, this will mean that the image will be at full opacity to signify that it's selected. Searched on Google to no luck even though it's a simple question of how to use an IF statement...</p>
520,271
7
0
null
2009-02-06 13:17:38.67 UTC
35
2021-10-29 08:13:19.933 UTC
null
null
null
zuk1
26,823
null
1
221
jquery
292,577
<p>Use the <a href="http://docs.jquery.com/Selectors/not#selector" rel="noreferrer">"not</a>" selector.</p> <p>For example, instead of:</p> <p><code>$(".thumbs").hover()</code></p> <p>try:</p> <p><code>$(".thumbs:not(.selected)").hover()</code></p>
177,673
Html.TextBox conditional attribute with ASP.NET MVC Preview 5
<p>I have a strongly-typed MVC View Control which is responsible for the UI where users can create and edit Client items. I'd like them to be able to define the <code>ClientId</code> on creation, but not edit, and this to be reflected in the UI.</p> <p>To this end, I have the following line:</p> <pre><code>&lt;%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new { @readonly = (ViewData.Model.ClientId != null &amp;&amp; ViewData.Model.ClientId.Length &gt; 0 ? "readonly" : "false") } ) %&gt; </code></pre> <p>It seems that no matter what value I give the readonly attribute (even "false" and ""), Firefox and IE7 make the input read-only, which is annoyingly counter-intuitive. Is there a nice, ternary-operator-based way to drop the attribute completely if it is not required?</p>
178,024
8
0
null
2008-10-07 08:54:24.8 UTC
4
2017-05-09 23:38:57.18 UTC
2012-02-22 14:16:30.357 UTC
null
27,756
tags2k
192
null
1
30
asp.net-mvc|attributes|html-helper|readonly
51,995
<p>Tough problem... However, if you want to define only the <code>readonly</code> attribute, you can do it like this:</p> <pre><code>&lt;%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, ViewData.Model.ClientId != null &amp;&amp; ViewData.Model.ClientId.Length &gt; 0 ? new { @readonly = "readonly" } : null) %&gt; </code></pre> <p>If you want to define more attributes then you must define two anonymous types and have multiple copies of the attributes. For example, something like this (which I don't like anyway):</p> <pre><code>ClientId.Length &gt; 0 ? (object)new { @readonly = "readonly", @class = "myCSS" } : (object)new { @class = "myCSS" } </code></pre>