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
48,651,269
What are the pause containers?
<p>In my IBM Cloud Private, I see several pause containers.</p> <p>Can anyone explain the purpose of these? Normally, I can get to the bash shell in a running container but not the ones which are pause.</p> <pre><code># docker ps | grep pause ee5f3f6b9fc0 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_catalog-catalog-apiserver-8qxrf_kube-system_3b4b107d-0b72-11e8-9f22-005056227136_0 d238dad0c5b8 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_auth-apikeys-bk28g_kube-system_3b731880-0b72-11e8-9f22-005056227136_0 0196efb043ca ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_icp-router-htnhz_kube-system_3b8d25d3-0b72-11e8-9f22-005056227136_0 b09dc1759d09 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_unified-router-bskb6_kube-system_3af9d44e-0b72-11e8-9f22-005056227136_0 8a392f174c24 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_auth-pap-gfh7q_kube-system_3aa5b311-0b72-11e8-9f22-005056227136_0 0ac776eb9ced ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_platform-api-zr5pz_kube-system_3b2ce527-0b72-11e8-9f22-005056227136_0 107896ebfcd6 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_icp-ds-0_kube-system_3a9200f8-0b72-11e8-9f22-005056227136_0 f95df5fbcc4a ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_image-manager-0_kube-system_3ae74f5c-0b72-11e8-9f22-005056227136_0 a9d30804f222 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_auth-idp-h4fmt_kube-system_3ad78a99-0b72-11e8-9f22-005056227136_0 eaae55900637 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_catalog-ui-jv9sq_kube-system_3af5cb32-0b72-11e8-9f22-005056227136_0 4ace18a84d8b ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_auth-pdp-9vhzx_kube-system_3ae0a074-0b72-11e8-9f22-005056227136_0 98b70f6074c7 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_calico-policy-controller-5997c6c956-cx774_kube-system_39bfecef-0b72-11e8-9f22-005056227136_0 63a0340e3de8 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_rescheduler-jqtd4_kube-system_3a6d4b05-0b72-11e8-9f22-005056227136_0 cace008e71b1 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_kube-dns-9494dc977-7gwpx_kube-system_39a15b6b-0b72-11e8-9f22-005056227136_0 80a18b538ef3 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_platform-ui-k5g7h_kube-system_3a98aad3-0b72-11e8-9f22-005056227136_0 bea43bfc8d70 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_catalog-catalog-controller-manager-bd9f49c8c-4fqcp_kube-system_39653745-0b72-11e8-9f22-005056227136_0 f54f329e50ae ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_helm-api-5d8b6d6f9c-4rl2s_kube-system_396ade8d-0b72-11e8-9f22-005056227136_0 6812e3fee9cc ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_tiller-deploy-55fb4d8dcc-pcxbj_kube-system_396b0005-0b72-11e8-9f22-005056227136_0 69a840bc394b ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_helmrepo-5878d9d858-wlcrj_kube-system_396506a5-0b72-11e8-9f22-005056227136_0 03bc9ce0413d ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_heapster-5fd94775d5-28t6w_kube-system_396b0dd6-0b72-11e8-9f22-005056227136_0 8763167695b3 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_filebeat-ds-amd64-q54pc_kube-system_9b8515d6-0b52-11e8-99a8-005056227136_1 461e5de11ee1 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_calico-node-amd64-ql292_kube-system_53492619-0b51-11e8-99a8-005056227136_1 f73e2eb9dbaf ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_k8s-master-192.168.142.103_kube-system_c39080358687c72432da5f6de4b6fff9_1 c08f029af60e ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_k8s-mariadb-192.168.142.103_kube-system_6b640df7dae2cb064ebc450b273ce62a_1 0174b5c35963 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_k8s-proxy-192.168.142.103_kube-system_b9f441de4995384d245d71fdb65e2cc2_1 f6befd10c479 ibmcom/pause:3.0 "/pause" About an hour ago Up About an hour k8s_POD_k8s-etcd-192.168.142.103_kube-system_a5150d8f6ee1f8047b05f9b2d5cbcaba_1 </code></pre>
48,654,926
4
2
null
2018-02-06 20:18:15.087 UTC
9
2019-11-27 09:44:59.103 UTC
null
null
null
null
4,668,095
null
1
30
docker|ibm-cloud-private
33,662
<p>The 'pause' container is a container which holds the network namespace for the pod. Kubernetes creates pause containers to acquire the respective pod’s IP address and set up the network namespace for all other containers that join that pod.</p> <p>You can access below links for details.</p> <p><a href="https://groups.google.com/forum/#!topic/kubernetes-users/jVjv0QK4b_o" rel="noreferrer">https://groups.google.com/forum/#!topic/kubernetes-users/jVjv0QK4b_o</a></p> <p><a href="https://www.ianlewis.org/en/almighty-pause-container" rel="noreferrer">https://www.ianlewis.org/en/almighty-pause-container</a></p>
51,816,020
How to break the js files into chunks in vue cli 3 with webpack performance object?
<p>I have done a project using vue cli v3. After building the project I saw 2 warnings i.e.</p> <pre><code>warning asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: js/chunk-vendors.2557157d.js (474 KiB) warning entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: app (617 KiB) js/chunk-vendors.2557157d.js css/app.821fcb13.css js/app.b5a47a94.js </code></pre> <p>Now upon inspection I saw that if I add the following in webpack config</p> <pre><code>performance: { maxEntrypointSize: 512000, maxAssetSize: 512000 } </code></pre> <p>then it will automatically break the js files into small chunks. Now in vue cli 3 there is no webpack.config file.</p> <p>So, if you can please guide how to implement this so that files get auto chunked when it crosses some limit, it will be really helpful.</p> <p>This is where I saw it: <a href="https://github.com/webpack/webpack/issues/3486#issuecomment-397915908" rel="noreferrer">https://github.com/webpack/webpack/issues/3486#issuecomment-397915908</a></p> <p>Looking forward to your reply.</p> <p>P.S.: I've read <a href="https://vuejsdevelopers.com/2018/03/26/vue-cli-3/" rel="noreferrer">this</a> and tried creating the <strong>vue.config.js</strong> file and added the following inside the file</p> <pre><code>module.exports = { configureWebpack: { performance: { maxEntrypointSize: 512000, maxAssetSize: 512000 } } } </code></pre> <p>But it didn't do anything. Can anyone please help to let me know what should I do to make sure my js file chunks do not cross the recommended size by vue? </p> <h2>Update</h2> <p>As per the answer by Linus Borg I tried putting both of the following codes in the <code>vue.config.js</code> file. <strong>Try 1</strong>: </p> <pre><code>module.exports = { configureWebpack: { splitChunks: { minSize: 10000, maxSize: 250000, } } } </code></pre> <p>and <strong>Try 2</strong>: </p> <pre><code>module.exports = { configureWebpack: { splitChunks: { cacheGroups: { node_vendors: { test: /[\\/]node_modules[\\/]/, chunks: "all", priority: 1 } } } } } </code></pre> <p>After both of then when I built my project for production. I saw the same warning, without changing any size: <a href="https://i.imgur.com/7Hp7SXC.jpg" rel="noreferrer">https://i.imgur.com/7Hp7SXC.jpg</a> It seems none of them are affecting any changes. Any help? </p>
52,634,444
3
0
null
2018-08-13 06:03:25.997 UTC
4
2019-03-28 02:08:39.317 UTC
2018-08-13 09:05:11.53 UTC
null
2,308,992
null
2,308,992
null
1
30
webpack|vue.js|vue-cli
28,901
<p>The following added to my <strong>vue.config.js</strong> file is what finally chunked all my vendor assets when executing <code>npm run build</code> for my @vue/cli project (version 3.0.4).</p> <pre><code>module.exports = { configureWebpack:{ optimization: { splitChunks: { minSize: 10000, maxSize: 250000, } } } } </code></pre> <p>Hide warnings</p> <pre><code>module.exports = { configureWebpack:{ performance: { hints: false }, optimization: { splitChunks: { minSize: 10000, maxSize: 250000, } } } } </code></pre>
8,918,452
R changing format of scale on y-axis
<p>I have a plot that has $-amounts and dates on y and x axis respectively. Currently the dollar amounts range from $0-15 million. Something like this:</p> <pre><code>x &lt;- rnorm(20)^2 * 1000000 plot(x) </code></pre> <p>R does stuff like <code>'1.0e+07'</code> instead of <code>'10,000,000'</code> and also orients the text vertically instead of horizontally. </p> <p>My questions are:</p> <p>1) how would I get the scale text to be horizontally oriented?</p> <p>2) how would I get R to use <code>10MM</code> instead of <code>'10,000,000'</code> or <code>'1.0e+07'</code>?</p>
8,918,668
2
0
null
2012-01-18 22:27:11.157 UTC
7
2012-01-18 23:13:14.917 UTC
null
null
null
null
914,308
null
1
17
r|plot
65,377
<p>1) See the <code>scipen</code> option in <code>?options</code> which is a penalty against the use of scientific notation. For better control, you need to plot the axis by hand with labels you want.</p> <p>2) See <code>las</code> in <code>?par</code> which controls to orientation crudely of axis labels.</p> <p>For 1):</p> <pre><code>x &lt;- rnorm(20)^2 * 10000000 layout(matrix(1:2, ncol = 2)) plot(x) getOption("scipen") opt &lt;- options("scipen" = 20) getOption("scipen") plot(x) options(opt) layout(1) </code></pre> <p>which gives</p> <p><img src="https://i.stack.imgur.com/cdwCw.png" alt="enter image description here"></p> <p>To plot your own axis try</p> <pre><code>plot(x / 10000000, axes = FALSE) axis(1) pts &lt;- pretty(x / 10000000) axis(2, at = pts, labels = paste(pts, "MM", sep = "")) box() </code></pre> <p>Which gives</p> <p><img src="https://i.stack.imgur.com/6bm4z.png" alt="enter image description here"></p> <p>Where we use <code>pretty()</code> to select pretty locations for the ticks just as R would and then add a custom axis. Notice how we suppress axis drawing in the <code>plot()</code> call and then add back the axes and the plot frame with calls to <code>axis()</code> and <code>box()</code>.</p> <p>For 2) combining with 1)</p> <pre><code>opt &lt;- options("scipen" = 20) op &lt;- par(mar = c(5,7,4,2) + 0.1) ## extra margin to accommodate tick labs x &lt;- rnorm(20)^2 * 10000000 plot(x, las = 1, ylab = "") ## no y-axis label title(ylab = "label", line = 5.5) ## need to plot the axis label par(op) options(opt) </code></pre> <p>Which gives</p> <p><img src="https://i.stack.imgur.com/pyM5f.png" alt="enter image description here"></p> <p>Notice how we use <code>las</code> in the <code>plot()</code> call, and we need to create some extra margin space to accommodate the tick labels. We also need to plot the label by hand otherwise R will stick it in amongst the tick labels.</p> <p>For the custom axis labels, add the <code>las = 1</code> to the <code>axis()</code> call:</p> <pre><code>op &lt;- par(mar = c(5,5,4,2) + 0.1) plot(x / 10000000, axes = FALSE, ylab = "") axis(1) pts &lt;- pretty(x / 10000000) axis(2, at = pts, labels = paste(pts, "MM", sep = ""), las = 1) title(ylab = "my label", line = 4) box() par(op) </code></pre> <p>Which produces</p> <p><img src="https://i.stack.imgur.com/nppyv.png" alt="enter image description here"></p>
8,786,708
How to disable package and publish tasks for root aggregate module in multi-module build?
<p>I have a multiproject SBT project, which looks like the example on SBT doc:</p> <pre><code>import sbt._ import Keys._ object HelloBuild extends Build { lazy val root = Project(id = "hello", base = file(".")) aggregate(foo, bar) lazy val foo = Project(id = "hello-foo", base = file("foo")) lazy val bar = Project(id = "hello-bar", base = file("bar")) } </code></pre> <p>Because <code>root</code> is just a virtual project to aggregate both subprojects, I would like to avoid package generation (and artifact publication), but still generate package (and publish) for both subprojects.</p> <p>Is there an easy way to achieve it ?</p>
8,789,341
9
0
null
2012-01-09 10:06:11.963 UTC
11
2020-12-11 22:21:43.17 UTC
2014-06-19 09:41:21.567 UTC
null
1,305,344
null
220,447
null
1
38
scala|sbt
12,080
<p>Actually, it <em>is</em> pretty easy. Just override the setting for <code>publish</code> in the root project:</p> <pre><code>base = file(".")) settings (publish := { }) aggregate(foo, bar) </code></pre>
8,984,254
How to view the XML form of an Excel file?
<p>How can I view the XML form of an Excel <code>*.xlsx</code> file?</p>
8,984,319
3
0
null
2012-01-24 09:09:48.33 UTC
6
2021-08-01 19:05:09.313 UTC
2019-02-14 16:09:42.513 UTC
null
2,756,409
null
983,476
null
1
62
xml|excel
60,495
<p>XLSX files are just ZIP files, so unzip them using your favourite ZIP tool.</p>
57,577,462
Get width of a view using in SwiftUI
<p>I need to get width of a rendered view in <code>SwiftUI</code>, which is apparently not that easy.</p> <p>The way I see it is that I need a function that returns a view's dimensions, simple as that.</p> <pre><code>var body: some View { VStack(alignment: .leading) { Text(timer.name) .font(.largeTitle) .fontWeight(.heavy) Text(timer.time) .font(.largeTitle) .fontWeight(.heavy) .opacity(0.5) } } </code></pre>
57,577,752
2
0
null
2019-08-20 15:56:38.073 UTC
12
2022-08-02 19:04:31.127 UTC
2020-08-11 01:09:32.52 UTC
null
819,340
null
6,090,166
null
1
37
swift|swiftui|frame
52,477
<p>The only way to get the dimensions of a <code>View</code> is by using a <code>GeometryReader</code>. The reader returns the dimensions of the container.</p> <p>What is a geometry reader? the documentation says:</p> <blockquote> <p>A container view that defines its content as a function of its own size and coordinate space. <a href="https://developer.apple.com/documentation/swiftui/geometryreader" rel="noreferrer">Apple Doc</a></p> </blockquote> <p>So you could get the dimensions by doing this:</p> <pre><code>struct ContentView: View { @State var frame: CGSize = .zero var body: some View { HStack { GeometryReader { (geometry) in self.makeView(geometry) } } } func makeView(_ geometry: GeometryProxy) -&gt; some View { print(geometry.size.width, geometry.size.height) DispatchQueue.main.async { self.frame = geometry.size } return Text(&quot;Test&quot;) .frame(width: geometry.size.width) } } </code></pre> <p>The printed size is the dimension of the <code>HStack</code> that is the container of inner view.</p> <p>You could potentially using another <code>GeometryReader</code> to get the inner dimension.</p> <p>But remember, SwiftUI is a declarative framework. So you should avoid calculating dimensions for the view:</p> <p>read this to more example:</p> <ul> <li><a href="https://stackoverflow.com/questions/56487323/make-a-vstack-fill-the-width-of-the-screen-in-swiftui">Make a VStack fill the width of the screen in SwiftUI</a></li> <li><a href="https://stackoverflow.com/questions/56505043/how-to-make-view-the-size-of-another-view-in-swiftui/56661706#56661706">How to make view the size of another view in SwiftUI</a></li> </ul>
27,225,815
Android how to show DatePicker in Fragment?
<p>I am new on Android Fragments and I want to know that how can I show or implement <code>DatePicker</code> in simple <code>Fragment</code>and not a <code>FragmentActivity</code>. </p> <p>For example my class name is:</p> <pre><code>public class FragmentAddCard extends Fragment { } </code></pre> <p>Thanks.</p>
27,225,882
4
1
null
2014-12-01 09:58:54.527 UTC
8
2018-01-21 09:50:13.743 UTC
2014-12-01 14:34:14.74 UTC
null
3,555,472
null
3,555,472
null
1
17
android|android-fragments|android-datepicker
53,042
<p>In your button click call the DateFragment like this</p> <pre><code> dob.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { DialogFragment newFragment = new SelectDateFragment(); newFragment.show(getFragmentManager(), "DatePicker"); } }); </code></pre> <p>Here is the code snippet for DateFragment</p> <pre><code> public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar calendar = Calendar.getInstance(); int yy = calendar.get(Calendar.YEAR); int mm = calendar.get(Calendar.MONTH); int dd = calendar.get(Calendar.DAY_OF_MONTH); return new DatePickerDialog(getActivity(), this, yy, mm, dd); } public void onDateSet(DatePicker view, int yy, int mm, int dd) { populateSetDate(yy, mm+1, dd); } public void populateSetDate(int year, int month, int day) { dob.setText(month+"/"+day+"/"+year); } } </code></pre>
54,158,994
React suspense/lazy delay?
<p>I am trying to use the new React Lazy and Suspense to create a fallback loading component. This works great, but the fallback is showing only a few ms. Is there a way to add an additional delay or minimum time, so I can show animations from this component before the next component is rendered? </p> <p>Lazy import now</p> <pre><code>const Home = lazy(() =&gt; import("./home")); const Products = lazy(() =&gt; import("./home/products")); </code></pre> <p>Waiting component: </p> <pre><code>function WaitingComponent(Component) { return props =&gt; ( &lt;Suspense fallback={&lt;Loading /&gt;}&gt; &lt;Component {...props} /&gt; &lt;/Suspense&gt; ); } </code></pre> <p>Can I do something like this?</p> <pre><code>const Home = lazy(() =&gt; { setTimeout(import("./home"), 300); }); </code></pre>
54,159,114
8
4
null
2019-01-12 11:07:51.53 UTC
14
2022-04-17 20:50:56.463 UTC
null
null
null
null
964,012
null
1
53
javascript|reactjs
28,448
<p><code>lazy</code> function is supposed to return a promise of <code>{ default: ... }</code> object which is returned by <code>import()</code> of a module with default export. <code>setTimeout</code> doesn't return a promise and cannot be used like that. While arbitrary promise can:</p> <pre><code>const Home = lazy(() =&gt; { return new Promise(resolve =&gt; { setTimeout(() =&gt; resolve(import("./home")), 300); }); }); </code></pre> <p>If an objective is to provide <em>minimum</em> delay, this isn't a good choice because this will result in <em>additional</em> delay.</p> <p>A minimum delay would be:</p> <pre><code>const Home = lazy(() =&gt; { return Promise.all([ import("./home"), new Promise(resolve =&gt; setTimeout(resolve, 300)) ]) .then(([moduleExports]) =&gt; moduleExports); }); </code></pre>
963,183
What is the Best Way to Organize a ASP.Net MVC Solution Using Dependency Injection?
<p>I am early in development on a new ASP.Net MVC project and I using this project to get into DI. I'm pretty sure that I am going to go with Structure Map, but that isn't what I am asking about. What I am trying to figure out is how best to organize my solution. Do both the unit test project and the model get a configuration file to map their dependencies or is there one class to rule them all?</p> <p>Also, are there any newbie traps to avoid before I get too far into this?</p> <p>Many Thanks, All.....</p> <p><strong>Update</strong> I should add that when I say "organize the solution", I'm not referring to the number of files/folders, etc., but rather how to structure the classes that are involved with DI. In particular, how to manage the bootstrapper. I can see where poor phrasing on my part could cause confusion.</p>
1,164,513
3
1
null
2009-06-08 01:25:01.037 UTC
9
2010-06-18 17:54:36.597 UTC
2009-06-08 16:21:41.727 UTC
null
13,139
null
13,139
null
1
14
asp.net-mvc|dependency-injection|inversion-of-control|structuremap
2,363
<p>To encourage better TDD. Have two testing projects and or namespeaces X.Unit.Tests &amp; X.Integrations.Tests.</p> <p>I have my DI code in my main project in a "namespace directory" (/Config) but in my integration code tests, I might just call those registries or override if I required in my base fixtures or setups. </p> <p>E.g. </p> <p>/Config/ServiceRegistry.cs /Config/RepositoryRegistry.cs /Config/Bootstrapper.cs</p> <p>In global.asax I call Bootstrapper.Init() and this will call x.AddRegistry(new ServiceRegistry()) and so on.</p> <p>In my unit tests you dont need to be using DI only in your integration tests. In my IntegrationTests e.g. if I'm testing NHibernate through to the database I might initialise SM with RepositoryRegistry in TestSetUp with a helper method just wrappering GetInstance().</p> <p>I don't split out to projects .Bootstraper and .Domain until I have absolutely have to... Three projects, X, X.UnitTests, X.Integration if you required more move later. I came from a background/company enforce of having dozens of projects it felt dirty a first reducing but not now, I go hit the grow running quickly and reorganize solutions structure later if required.</p>
376,111
How do you override vim options via comments in a python source code file?
<p>I would like to set some vim options in one file in the comments section.</p> <p>For example, I would like to set this option in one file</p> <pre><code>set syntax=python </code></pre> <p>The file does not have a .py extension and I am not interested in making my vim installation recognise all files with this extension as python files.</p> <p>I know this can be done because I have seen it, but my googling for this has not yet been fruitful.</p>
376,200
3
0
null
2008-12-17 21:37:46.057 UTC
6
2017-05-25 13:52:03.7 UTC
null
null
null
Paul D. Eden
3,045
null
1
33
python|vim
13,427
<p>You're wanting a <a href="http://vim.wikia.com/wiki/Modeline_magic" rel="noreferrer">modeline</a> syntax, e.g.</p> <pre><code># vim: set syntax=python: </code></pre> <p>See: <a href="http://vim.wikia.com/wiki/Modeline_magic" rel="noreferrer">Modeline magic</a> at Vim Wikia for more details.</p>
374,444
Disadvantages of MARS (Multiple Active Result Sets)?
<p>Does anyone know of any disadvantages of MARS (Multiple Active Result Sets)? Does anyone know of any reason why one should avoid using MARS, like cases where cursors are more useful then MARS.</p>
624,646
3
0
null
2008-12-17 12:49:04.627 UTC
20
2022-07-06 08:20:03.73 UTC
2022-07-06 08:20:03.73 UTC
Samiksha
224,132
Samiksha
29,515
null
1
93
sql-server|sql-server-2005|sql-server-mars
44,207
<p>There are apparently at least two known (potential) drawbacks (from this (1) <a href="http://blogs.msdn.com/sqlnativeclient/archive/2006/09/27/774290.aspx" rel="nofollow noreferrer">Team blog</a>):</p> <ol> <li><p>Obviously this can cause potential problems for any legacy systems which weren't designed to run against a MARS enabled design - <em>&quot;existing code optimized to run in the non-MARS world may show a slight performance dip when run un-modified with MARS&quot;</em></p> </li> <li><p><em>“With MARS you can send multiple multi-statement batches to the server. The server will interleave execution of such batches, which means that if the batches change server state via SET or USE statements, for example, or use TSQL transaction management statements (BEGIN TRAN, COMMIT, ROLLBACK), both you and the server can get confused about what your actual intent is.”</em></p> </li> </ol> <p>I've yet to try out a MARS enabled design, but I'm coming very close to doing so on my current project. We have a slight issue with competing (and sometimes dependent) query operations (like lazy loading configuration data out of the same database that an active recordset is executing).</p> <p>There's more information on the MSDN site <a href="http://msdn.microsoft.com/en-us/library/ms131686.aspx" rel="nofollow noreferrer">(2) here</a></p> <p>[ (1) <a href="https://web.archive.org/web/20190911155929/https://blogs.msdn.microsoft.com/sqlnativeclient/2006/09/27/using-mars-with-sql-native-client/" rel="nofollow noreferrer">https://web.archive.org/web/20190911155929/https://blogs.msdn.microsoft.com/sqlnativeclient/2006/09/27/using-mars-with-sql-native-client/</a> ]<br/> [ (2) <a href="http://msdn.microsoft.com/en-us/library/ms131686.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms131686.aspx</a> ]</p>
373,295
Digital Certificate: How to import .cer file in to .truststore file using?
<p>Has anyone came across where they have to deal with .truststore file? and knowing how to import .cer into .truststore file? </p> <p>I am not sure if I have to use Java Keytool or Linux command (such as openssl command).</p> <p>Thanks</p>
373,307
3
0
null
2008-12-17 00:33:53.91 UTC
49
2019-10-27 11:38:29.297 UTC
null
null
null
Manet
44,534
null
1
101
digital-certificate|truststore
263,335
<pre><code># Copy the certificate into the directory Java_home\Jre\Lib\Security # Change your directory to Java_home\Jre\Lib\Security&gt; # Import the certificate to a trust store. keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return] Trust this certificate: [Yes] </code></pre> <p>changeit is the default truststore password</p>
39,753,594
How do I access class variable?
<pre><code>class TestController &lt; ApplicationController def test @goodbay = TestClass.varible end end class TestClass @@varible = "var" end </code></pre> <p>and i get error </p> <pre><code>undefined method 'varible' for TestClass:Class </code></pre> <p>on the line <code>@goodbay = TestClass.varible</code> </p> <p>What is wrong?</p>
39,753,678
3
0
null
2016-09-28 17:01:47.567 UTC
4
2022-04-27 13:05:07.087 UTC
2016-09-28 17:14:57.347 UTC
null
1,772,830
null
5,917,243
null
1
23
ruby
45,953
<p>In Ruby, reading and writing to <code>@instance</code> variables (and <code>@@class</code> variables) of an object must be done through a method on that object. For example:</p> <pre><code>class TestClass @@variable = "var" def self.variable # Return the value of this variable @@variable end end p TestClass.variable #=&gt; "var" </code></pre> <p>Ruby has some built-in methods to create simple accessor methods for you. If you will use an instance variable on the class (instead of a class variable):</p> <pre><code>class TestClass @variable = "var" class &lt;&lt; self attr_accessor :variable end end </code></pre> <p>Ruby on Rails offers <a href="http://apidock.com/rails/Module/mattr_accessor" rel="noreferrer">a convenience method</a> specifically for class variables:</p> <pre><code>class TestClass mattr_accessor :variable end </code></pre>
39,832,874
How do I change the color for ng2-charts?
<p>I have added ng2-charts to my project and display 2 charts - donut &amp; barchart. both are <strong>displayed in gray</strong> since I added</p> <pre><code> &lt;base-chart class=&quot;chart&quot; [colors]=&quot;chartColors&quot; ... &lt;/base-chart&gt; </code></pre> <p>to the <code>component.template.html</code>, and</p> <pre><code>public chartColors:Array&lt;any&gt; =[ { fillColor:'rgba(225,10,24,0.2)', strokeColor:'rgba(11,255,20,1)', pointColor:'rgba(111,200,200,1)', pointStrokeColor:'#fff', pointHighlightFill:'#fff', pointHighlightStroke:'rgba(200,100,10,0.8)' }, ... (3x) </code></pre> <p>to the <code>component.ts</code>.</p> <p>Are any other package imports necessary to change the color or is the setup wrong?</p> <p>Chromes html inspector shows the following html output rendered:</p> <pre><code>ng-reflect-colors=&quot;[object Object],[object Object],[object Object]&quot; </code></pre>
39,833,097
7
0
null
2016-10-03 13:29:52.907 UTC
8
2022-08-30 08:51:48.533 UTC
2020-12-24 00:16:15.49 UTC
null
1,783,163
null
6,560,380
null
1
32
angular|ng2-charts
54,689
<p>You should do this like:</p> <pre><code> public chartColors: Array&lt;any&gt; = [ { // first color backgroundColor: 'rgba(225,10,24,0.2)', borderColor: 'rgba(225,10,24,0.2)', pointBackgroundColor: 'rgba(225,10,24,0.2)', pointBorderColor: '#fff', pointHoverBackgroundColor: '#fff', pointHoverBorderColor: 'rgba(225,10,24,0.2)' }, { // second color backgroundColor: 'rgba(225,10,24,0.2)', borderColor: 'rgba(225,10,24,0.2)', pointBackgroundColor: 'rgba(225,10,24,0.2)', pointBorderColor: '#fff', pointHoverBackgroundColor: '#fff', pointHoverBorderColor: 'rgba(225,10,24,0.2)' }]; </code></pre> <p><strong>Gray</strong> color is set by default, which means your color options don't work, because of wrong properties names.</p> <p>Here you have an example, how colors properties are called:</p> <p><a href="https://github.com/valor-software/ng2-charts/blob/master/demo/src/app/components/charts/line-chart-demo.ts" rel="nofollow noreferrer">ng2-charts-github-source-code</a></p> <p><strong>@UPDATE:</strong></p> <p>If there is a need to update just backgroundColor and nothing else, code below will work too.</p> <pre><code>public chartColors: Array&lt;any&gt; = [ { // all colors in order backgroundColor: ['#d13537', '#b000b5', '#c0ffee', ...] } ] </code></pre>
36,433,961
CSS3 Marquee Effect, Without Empty Space
<p>This question here has an answer, which leaves a lot of empty space at the end of each iteration of the marquee: <a href="https://stackoverflow.com/questions/21233033/css3-marquee-effect">CSS3 Marquee Effect</a></p> <p>Is there a way to achieve a smooth <code>&lt;marquee&gt;&lt;/marquee&gt;</code> effect, using CSS3, that doesn't leave this space?</p> <p>I have a lot of small elements, which look a bit like SO's blue tags, that exclusively fill the content of the marquee, as opposed to one continuous body or a wall of text.</p>
36,434,361
3
2
null
2016-04-05 18:13:11.827 UTC
8
2020-08-14 07:13:12.343 UTC
2017-05-23 10:30:43.67 UTC
null
-1
null
5,328,239
null
1
10
html|css|marquee
37,071
<p>Here is a sample how you can do, and by setting the delay and duration you control the space between the texts</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.marquee { background-color: #ddd; width: 500px; margin: 0 auto; overflow: hidden; white-space: nowrap; } .marquee span { display: inline-block; font-size: 20px; position: relative; left: 100%; animation: marquee 8s linear infinite; } .marquee:hover span { animation-play-state: paused; } .marquee span:nth-child(1) { animation-delay: 0s; } .marquee span:nth-child(2) { animation-delay: 0.8s; } .marquee span:nth-child(3) { animation-delay: 1.6s; } .marquee span:nth-child(4) { animation-delay: 2.4s; } .marquee span:nth-child(5) { animation-delay: 3.2s; } @keyframes marquee { 0% { left: 100%; } 100% { left: -100%; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p class="marquee"&gt; &lt;span&gt;this is a&lt;/span&gt; &lt;span&gt;simple marquee&lt;/span&gt; &lt;span&gt;using css&lt;/span&gt; &lt;span&gt;only tech&lt;/span&gt; &lt;span&gt;with a delay&lt;/span&gt; &lt;/p&gt;</code></pre> </div> </div> </p>
28,437,601
Error after updating the Android.Support Library v7 AppCompat to the 21.0.3 version
<p>after updating the Android.Support Library v7 AppCompat to the 21.0.3 version I've got this errors:</p> <pre><code>1&gt;C:\Program Files (x86)\MSBuild\Xamarin\Androi\Xamarin.Android.Common.targets(236,2): error XA5207: Please install package: 'Android Support Library' available in SDK installer. Java library file C:\Users...\AppData\Local\Xamarin\Android.Support.v4\21.0.3\embedded\classes.jar doesn't exist. 1&gt;C:\Program Files (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(236,2): error XA5207: Please install package: 'Android Support Library' available in SDK installer. Java library file C:\Users...\AppData\Local\Xamarin\Android.Support.v4\21.0.3\embedded\libs/internal_impl-21.0.3.jar doesn't exist. 1&gt;C:\Program Files (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(236,2): error XA5206: Please install package: 'Android Support Library' available in SDK installer. Android resource directory C:\Users...\AppData\Local\Xamarin\Android.Support.v4\21.0.3\embedded./ doesn't exist. </code></pre> <p>I tried deleting the Android Support Library 21.0.3 from the SDK manager and download it again.</p> <p>There is similar question: <a href="https://stackoverflow.com/questions/28008604/android-support-library-and-media-router-jar-files-cannot-be-found">Android Support Library and Media Router .jar files cannot be found</a> however I am not using map in my project. How do I fix this?</p> <p>I'm using Visual Studio 2013, Compile using API 21 (Xamarin.Android v5.0 Support), Minimum terget API 16, Terget API 21</p>
29,287,971
5
1
null
2015-02-10 17:07:40.417 UTC
10
2018-05-23 21:11:23.857 UTC
2017-05-23 12:08:56.58 UTC
null
-1
null
3,897,367
null
1
24
android|visual-studio-2013|xamarin|android-support-library
11,234
<ol> <li>Delete folder: <code>21.0.3</code> (...\AppData\Local\Xamarin\Android.Support.v4\21.0.3)</li> <li>Rebuild your application. <br><br> <strong>Works fine to me:</strong></li> </ol> <p><img src="https://i.stack.imgur.com/d5Qz4.png" alt="VS xamarin"></p>
24,397,640
Rails - Nested includes on Active Records?
<p>I have a list of events that I fetch. I'm trying to include every user associated to this event and every profile associated to each user. The Users get included but not their profiles.</p> <p>How Would i do this</p> <pre><code>Event.includes(:users [{profile:}]) </code></pre> <p>The docs don't seem to be clear: <a href="http://guides.rubyonrails.org/active_record_querying.html">http://guides.rubyonrails.org/active_record_querying.html</a></p>
24,397,716
3
0
null
2014-06-24 22:52:49.283 UTC
85
2021-12-24 13:29:17.55 UTC
2016-03-31 17:42:19.827 UTC
null
4,494
null
242,769
null
1
209
ruby-on-rails|rails-activerecord
83,379
<p>I believe the following should work for you.</p> <pre><code>Event.includes(users: :profile) </code></pre> <p>If you want to include an association (we'll call it C) of an already included association (we'll call it B), you'd use the syntax above. However, if you'd like to include D as well, which is also an association of B, that's when you'd use the array as given in the example in the <a href="http://guides.rubyonrails.org/active_record_querying.html" rel="noreferrer">Rails Guide</a>.</p> <pre><code>A.includes(bees: [ :cees, :dees ]) </code></pre> <p>You could continue to nest includes like that (if you actually need to). Say that A is also associated with Z, and that C is associated to E and F.</p> <pre><code>A.includes({ bees: [{ cees: [:ees, :effs] }, :dees] }, :zees) </code></pre> <p>And for good fun, we'll also say that E is associated to J and X, and that D is associated to Y.</p> <pre><code>A.includes({ bees: [{ cees: [{ ees: [:jays, :exes] }, :effs] }, { dees: :wise } ] }, :zees) </code></pre>
36,004,976
Count frequency of values in pandas DataFrame column
<p>I want to count number of times each values is appearing in dataframe.</p> <p>Here is my dataframe - <code>df</code>:</p> <pre><code> status 1 N 2 N 3 C 4 N 5 S 6 N 7 N 8 S 9 N 10 N 11 N 12 S 13 N 14 C 15 N 16 N 17 N 18 N 19 S 20 N </code></pre> <p>I want to dictionary of counts: </p> <p>ex. <code>counts = {N: 14, C:2, S:4}</code></p> <p>I have tried <code>df['status']['N']</code> but it gives <code>keyError</code> and also <code>df['status'].value_counts</code> but no use. </p>
36,005,031
5
1
null
2016-03-15 07:29:29.913 UTC
12
2021-09-20 09:25:45.21 UTC
2016-03-15 07:38:57.003 UTC
null
2,901,002
null
2,286,762
null
1
71
python|django|pandas|dataframe
134,100
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="noreferrer"><code>value_counts</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html" rel="noreferrer"><code>to_dict</code></a>:</p> <pre><code>print df['status'].value_counts() N 14 S 4 C 2 Name: status, dtype: int64 counts = df['status'].value_counts().to_dict() print counts {'S': 4, 'C': 2, 'N': 14} </code></pre>
36,083,542
Error "command not found" after installing go-eval
<p>I'm trying to run <code>Go</code> in an interactive mode. </p> <p>I want to use <a href="https://github.com/sbinet/go-eval/" rel="noreferrer"><code>go-eval</code></a> for that, I followed their <code>README</code> instructions:</p> <ul> <li>I ran <code>go get github.com/sbinet/go-eval/</code> successfully</li> <li>I ran <code>go-eval</code> which resulted in <code>-bash: go-eval: command not found</code></li> </ul> <p>Some more information:</p> <ul> <li><p><code>echo $PATH</code> returns: <code>/usr/local/go/bin:...</code></p></li> <li><p><code>echo $GOPATH</code> returns: <code>$HOME/golang</code></p></li> <li><p>running <code>whereis go-eval</code> returns no output</p></li> <li><p>running <code>go install go-eval</code> returns:</p> <p><code>can't load package: package go-eval: cannot find package "go-eval" in any of: /usr/local/go/src/go-eval (from $GOROOT) $HOME/golang/src/go-eval (from $GOPATH)</code></p></li> </ul>
36,083,961
6
2
null
2016-03-18 11:46:23.267 UTC
7
2022-05-09 01:46:41.413 UTC
2019-12-22 22:28:04.233 UTC
null
503,099
null
503,099
null
1
38
macos|go
50,742
<p>You'll need to add <code>GOPATH/bin</code> to <code>PATH</code>.</p> <pre><code>PATH=&quot;$GOPATH/bin:$PATH&quot; </code></pre> <p><strong>Update</strong> <a href="https://golang.org/doc/go1.8#gopath" rel="noreferrer">[Go 1.8 and above]</a>: <code>GOPATH</code> will default to <code>$HOME/go</code>. The above <strong>will not work</strong> if <code>GOPATH</code> is not explicitly set.</p> <p>To set both, add this to your <code>.profile</code> file:</p> <pre><code>export GOPATH=&quot;$HOME/go&quot; PATH=&quot;$GOPATH/bin:$PATH&quot; </code></pre>
41,239,913
Why `additionalProperties` is the way to represent Dictionary/Map in Swagger/OpenAPI 2.0
<p>Although I have seen the examples in the <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject" rel="noreferrer">OpenAPI spec</a>:</p> <blockquote> <pre><code>type: object additionalProperties: $ref: '#/definitions/ComplexModel' </code></pre> </blockquote> <p>it isn't obvious to me <em>why</em> the use of <code>additionalProperties</code> is the correct schema for a Map/Dictionary.</p> <p>It also doesn't help that the only concrete thing that the spec has to say about <code>additionalProperties</code> is:</p> <blockquote> <p>The following properties are taken from the JSON Schema definition but their definitions were adjusted to the Swagger Specification. Their definition is the same as the one from JSON Schema, only where the original definition references the JSON Schema definition, the Schema Object definition is used instead.</p> <ul> <li>items</li> <li>allOf</li> <li>properties</li> <li>additionalProperties</li> </ul> </blockquote>
41,242,185
2
0
null
2016-12-20 10:18:15.037 UTC
9
2019-10-24 13:03:56.407 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
110,488
null
1
44
dictionary|hash|mapping|swagger|openapi
47,581
<p>Chen, I think <a href="https://stackoverflow.com/a/41240118/776186">your answer</a> is correct.</p> <p>Some further background that might be helpful:</p> <p>In JavaScript, which was the original context for JSON, an object is like a hash map of strings to values, where some values are data, others are functions. You can think of each name-value pair as a property. But JavaScript doesn't have classes, so the property names are not predefined, and each object can have its own independent set of properties.</p> <p>JSON Schema uses the <code>properties</code> keyword to validate name-value pairs that are known in advance; and uses <code>additionalProperties</code> (or <code>patternProperties</code>, not supported in OpenAPI 2.0) to validate properties that are not known.</p> <p>For clarity:</p> <ul> <li>The property names, or "keys" in the map, must be strings. They cannot be numbers, or any other value. </li> <li>As you said, the property names <em>should</em> be unique. Unfortunately the JSON spec doesn't strictly require uniqueness, but uniqueness is recommended, and expected by most JSON implementations. More background <a href="https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object?lq=1">here</a>.</li> <li><code>properties</code> and <code>additionalProperties</code> can be used alone or in combination. When additionalProperties is used alone, without properties, the object essentially functions as a <code>map&lt;string, T&gt;</code> where T is the type described in the additionalProperties sub-schema. Maybe that helps to answer your original question.</li> <li>When evaluating an object against a single schema, if a property name matches one of those specified in <code>properties</code>, its value only needs to be valid against the sub-schema provided for that property. The <code>additionalProperties</code> sub-schema, if provided, will only be used to validate properties that <em>are not</em> included in the <code>properties</code> map.</li> <li>There are some limitations of <code>additionalProperties</code> as implemented in Swagger's core Java libraries. I've documented these limitations <a href="https://support.reprezen.com/support/solutions/articles/6000162892-support-for-additionalproperties-in-swagger-2-0-schemas" rel="noreferrer">here</a>.</li> </ul>
5,723,935
Echoing a backspace
<p>Is it possible to echo a backspace in bash?</p> <p>Something like</p> <pre><code>echo $'stack\b' </code></pre> <p>Shouldn't output <code>stac</code>? Or I'm missing something?</p> <p>More specifically, I'd like to use that in:</p> <pre><code>ls | wc -l; echo $'\b items' </code></pre>
5,723,948
3
0
null
2011-04-19 23:30:26.707 UTC
6
2016-09-06 13:28:00.06 UTC
null
null
null
null
557,306
null
1
30
bash|echo
40,068
<p><code>\b</code> makes the cursor move left, but it does not erase the character. Output a space if you want to erase it.</p> <p>For some distributions you may also need to use <code>-e</code> switch of <code>echo</code>:</p> <blockquote> <pre><code> -e enable interpretation of backslash escapes </code></pre> </blockquote> <p>So it will look like</p> <pre><code> echo -e 'stack\b ' </code></pre> <p>Also, <code>files=(*) ; echo "${#files[@]} items"</code>.</p>
34,493,270
Element cannot have character [children], because the type's content type is element-only
<p>I tried validating my XML file with a XSD file but I get the following error message: </p> <blockquote> <p>[Error]: cvc-complex-type.2.3: Element 'paragraph' cannot have character [children], because the type's content type is element-only</p> </blockquote> <p>Which (if i am understanding it correctly) means a complex type cannot have a combination of simple and complex typed elements as children.</p> <p>But how do I fix this? I'm still kinda new to this, so the solution could be simple?</p> <p>My code is shown below:</p> <p>XSD:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:element name="biography"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="paragraph" maxOccurs="unbounded"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="name"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="first_name" type="xs:string" minOccurs="0"&gt;&lt;/xs:element&gt; &lt;xs:element name="last_name" type="xs:string"&gt;&lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="emphasize" maxOccurs="unbounded" minOccurs="0" type="xs:string"&gt;&lt;/xs:element&gt; &lt;xs:element name="profession" maxOccurs="unbounded" minOccurs="0" type="xs:string"&gt;&lt;/xs:element&gt; &lt;xs:element name="date" minOccurs="0"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="month" type="xs:string"&gt;&lt;/xs:element&gt; &lt;xs:element name="day" type="xs:int"&gt;&lt;/xs:element&gt; &lt;xs:element name="year" type="xs:int"&gt;&lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="definition" maxOccurs="unbounded"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="term" type="xs:string"&gt;&lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p>XML:</p> <pre><code>&lt;biography&gt; &lt;paragraph&gt; &lt;name&gt;&lt;first_name&gt;Alex&lt;/first_name&gt; &lt;last_name&gt;Turing&lt;/last_name&gt;&lt;/name&gt; was one of the first people to truly deserve the name &lt;emphasize&gt;computer scientist&lt;/emphasize&gt;. Although his contributions to the fields are too numerous to lst, his best-known are the famous &lt;emphasize&gt;Turing Test&lt;/emphasize&gt; and &lt;emphasize&gt;Turing Machine&lt;/emphasize&gt;. &lt;/paragraph&gt; &lt;definition&gt;The &lt;term&gt;Turing Test&lt;/term&gt; is to this day the standard test for determining whether a computer is truly intelligent. This test yet has to be passed.&lt;/definition&gt; &lt;definition&gt;A &lt;term&gt;Turing Machine&lt;/term&gt; is an abstract finite state automaton with infinite memory that can be proven equivalent to any other finite state automaton with arbitrarily large memory. Thus what is true for one Turing machine is true for all Turing machines no matter how implemented.&lt;/definition&gt; &lt;paragraph&gt; &lt;name&gt;&lt;last_name&gt;Turing&lt;/last_name&gt;&lt;/name&gt; was also an accomplished &lt;profession&gt;mathematician&lt;/profession&gt; and &lt;profession&gt;cryptographer&lt;/profession&gt;. His assistance was crucial in helping the Allies decode the German Enigma cipher. He committed suicide on &lt;date&gt;&lt;month&gt;June&lt;/month&gt; &lt;day&gt;7&lt;/day&gt;, &lt;year&gt;1954&lt;/year&gt;&lt;/date&gt; after being convicted of homosexuality and forced to take female hormone injections. &lt;/paragraph&gt; &lt;/biography&gt; </code></pre>
34,495,045
2
1
null
2015-12-28 12:07:37.707 UTC
2
2018-05-13 13:42:07.877 UTC
2015-12-28 15:37:34.597 UTC
null
290,085
null
5,723,143
null
1
13
xml|xsd|xml-validation
52,217
<p>This is precisely the purpose of <strong><em>mixed</em></strong> content:</p> <pre><code> &lt;xs:element name="paragraph" maxOccurs="unbounded"&gt; &lt;xs:complexType mixed="true"&gt; </code></pre> <p>And:</p> <pre><code> &lt;xs:element name="definition" maxOccurs="unbounded"&gt; &lt;xs:complexType mixed="true"&gt; </code></pre> <p>Note that you also probably want <code>paragraph</code> and <code>definition</code> to be in a <code>xs:choice macOccurs="unbounded"</code> given your XML.</p> <p>Here's your XSD updated with all changes needed so that your XML will be valid:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:element name="biography"&gt; &lt;xs:complexType&gt; &lt;xs:choice maxOccurs="unbounded"&gt; &lt;xs:element name="paragraph"&gt; &lt;xs:complexType mixed="true"&gt; &lt;xs:sequence&gt; &lt;xs:element name="name"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="first_name" type="xs:string" minOccurs="0"&gt;&lt;/xs:element&gt; &lt;xs:element name="last_name" type="xs:string"&gt;&lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="emphasize" maxOccurs="unbounded" minOccurs="0" type="xs:string"&gt;&lt;/xs:element&gt; &lt;xs:element name="profession" maxOccurs="unbounded" minOccurs="0" type="xs:string"&gt;&lt;/xs:element&gt; &lt;xs:element name="date" minOccurs="0"&gt; &lt;xs:complexType mixed="true"&gt; &lt;xs:sequence&gt; &lt;xs:element name="month" type="xs:string"&gt;&lt;/xs:element&gt; &lt;xs:element name="day" type="xs:int"&gt;&lt;/xs:element&gt; &lt;xs:element name="year" type="xs:int"&gt;&lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="definition"&gt; &lt;xs:complexType mixed="true"&gt; &lt;xs:sequence&gt; &lt;xs:element name="term" type="xs:string"&gt;&lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:choice&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre>
1,752,768
is there a max size to the length of a hidden input in html?
<p>in other words:</p> <pre><code>&lt;input type="hidden" value="Can I put as much as I want in here, or is there a limit?" /&gt; </code></pre> <p>and if so, what is it?</p>
1,752,794
2
1
null
2009-11-18 00:08:22.347 UTC
12
2013-01-16 16:39:34.277 UTC
null
null
null
null
24,197
null
1
102
html|input
68,840
<p>It depends on the method you send the form with.</p> <p>With GET, there is a commonly agreed on limit of about 1-2 kilobytes, depending on browser and server limitations.</p> <p>With POST, there is no technical limit in the browser, but usually one on the server side - see e.g. Apache's <code>LimitRequestBody</code>, PHP's <code>post_max_size</code> and so on.</p>
45,871,439
Before and After pseudo classes used with styled-components
<p>What is the proper way to apply <code>:before</code> and <code>:after</code> pseudo classes to styled components?</p> <p>I know that you can use </p> <p><code>&amp;:hover {}</code></p> <p>to apply the <code>:hover</code> pseudo class to a styled-component. </p> <p>Does this work for All pseudo elements like before and after? </p> <p>I have tried using the <code>&amp;:before</code> and <code>&amp;:after</code> strategy with some rather complex examples and i'm not sure if my attempts are not working because i've got something wrong with my example or it just doesn't work like that. </p> <p>Does someone have some insight on this? Thank you.</p>
45,871,869
5
2
null
2017-08-24 21:50:34.393 UTC
13
2021-09-18 19:42:01.86 UTC
null
null
null
null
6,792,170
null
1
71
reactjs|pseudo-class|styled-components
120,712
<p>Pseudo-selectors in <code>styled-components</code> work just like they do in CSS. (or rather, Sass) Whatever isn't working is likely a problem in your specific code, but that's hard to debug without seeing the actual code!</p> <p>Here is an example of how to use a simple <code>:after</code>:</p> <pre><code>const UnicornAfter = styled.div` &amp;:after { content: " "; } `; &lt;UnicornAfter&gt;I am a&lt;/UnicornAfter&gt; // renders: "I am a " </code></pre> <p>If you post your code I'll likely be able to help debug your specific issue!</p>
5,895,128
Attempted to access an unloaded appdomain when using System.DirectoryServices
<p>We've implemented a Membership Provider that authenticates to Active Directory and it's using System.DirectoryServices. While using this Membership Provider in an ASP.Net MVC 3 application on Visual Studio 2010 with webdev server we sometimes (1 out of 6 times) get an exception when logging in the application.</p> <pre><code>System.IO.FileNotFoundException: Could not load file or assembly 'System.Web' or one of its dependencies. The system cannot find the file specified. File name: 'System.Web' at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark&amp; stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark&amp; stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(AssemblyName an, Evidence securityEvidence, StackCrawlMark&amp; stackMark) at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADsPathname.Retrieve(Int32 lnFormatType) at System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo() at System.DirectoryServices.AccountManagement.ADStoreCtx.get_DnsDomainName() at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p) at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper() at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups() === Pre-bind state information === LOG: DisplayName = System.Web (Partial) WRN: Partial binding information was supplied for an assembly: WRN: Assembly Name: System.Web | Domain ID: 2 WRN: A partial bind occurs when only part of the assembly display name is provided. WRN: This might result in the binder loading an incorrect assembly. WRN: It is recommended to provide a fully specified textual identity for the assembly, WRN: that consists of the simple name, version, culture, and public key token. WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue. Calling assembly : HibernatingRhinos.Profiler.Appender, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0774796e73ebf640. </code></pre> <p>The calling assembly was HibernatingRhinos.Profiler.Appender so after disabling the profiler in log4net config we got to the real exception:</p> <pre><code>System.AppDomainUnloadedException: Attempted to access an unloaded appdomain. (Except at System.StubHelpers.StubHelpers.InternalGetCOMHRExceptionObject(Int32 hr, IntPtr pCPCMD, Object pThis) at System.StubHelpers.StubHelpers.GetCOMHRExceptionObject(Int32 hr, IntPtr pCPCMD, Object pThis) at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADsPathname.Retrieve(Int32 lnFormatType) at System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo() at System.DirectoryServices.AccountManagement.ADStoreCtx.get_DnsDomainName() at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p) at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper() at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups() </code></pre> <p>The exception is always thrown at the same method, but for now we are not able to reproduce it as it happens randomly, but approximately 1 out of 6 times. We do however not get the exception when using IIs instead of the built-in Visual Studio 2010 web server.</p> <p>It probably has something to do with racing conditions when using multiple appdomains in the context of Visual Studio webdev, but that's just guessing. We would really like to know what's the cause of the problem as we don't want to have these exceptions in a production environment.</p> <p>We found 2 similar cases but no one has found a real solution:</p> <p><a href="http://our.umbraco.org/forum/developers/extending-umbraco/19581-Problem-with-custom-membership-and-role-provider" rel="noreferrer">http://our.umbraco.org/forum/developers/extending-umbraco/19581-Problem-with-custom-membership-and-role-provider</a></p> <p><a href="http://forums.asp.net/t/1556949.aspx/1" rel="noreferrer">http://forums.asp.net/t/1556949.aspx/1</a></p> <p><strong>Update 18-05-2011</strong></p> <p>The smallest amount of code (in asp.net mvc) to reproduce the exception, where userName is your Active Directory loginname.</p> <pre><code>using System.DirectoryServices.AccountManagement; using System.Web.Mvc; namespace ADBug.Controllers { public class HomeController : Controller { public ActionResult Index() { string userName = "nickvane"; var principalContext = new PrincipalContext(ContextType.Domain); UserPrincipal userPrincipal = UserPrincipal.FindByIdentity( principalContext, IdentityType.SamAccountName, userName); if (userPrincipal != null) { PrincipalSearchResult&lt;Principal&gt; list = userPrincipal.GetAuthorizationGroups(); } return View(); } } } </code></pre> <p>Alas, the exception still happens at random, so no fully reproducable bug.</p>
11,297,545
6
2
null
2011-05-05 09:03:26.36 UTC
10
2015-06-11 03:32:11.043 UTC
2011-05-18 12:35:58.11 UTC
null
429,940
null
429,940
null
1
63
.net|asp.net-mvc|visual-studio-2010
68,749
<p>Here is what works for me (.Net 4):</p> <p>Instead of this:</p> <pre><code>principalContext = new PrincipalContext(ContextType.Domain) </code></pre> <p>create the principal context with the domain string as well:</p> <p>E.g.</p> <pre><code>principalContext = new PrincipalContext(ContextType.Domain,"MYDOMAIN") </code></pre> <p><strike>It should be fixed in 4.5.</strike> See comment, hasn't been fixed yet, but adding the second argument still works as workaround.</p>
6,062,528
Html.EditorFor Set Default Value
<p>Rookie question. I have a parameter being passed to a create view. I need to set a field name with a default value. @Html.EditorFor(model => model.Id) I need to set this input field with name Id with a default value that is being passed to the view via an actionlink.</p> <p>So, how can this input field [email protected](model => model.Id) -- get set with a default value.</p> <p><strong>Would the following work??</strong> Where the number 5 is a parameter I pass into the text field to set default value.</p> <pre><code>@Html.EditorFor(c => c.PropertyName, new { text = "5"; })</code></pre>
6,731,623
12
0
null
2011-05-19 17:30:00.303 UTC
13
2020-09-08 20:23:58.22 UTC
2013-03-15 05:02:18.553 UTC
null
727,208
null
715,447
null
1
80
c#|asp.net-mvc|asp.net-mvc-3
172,545
<p>The clean way to do so is to pass a new instance of the created entity through the controller:</p> <pre><code>//GET public ActionResult CreateNewMyEntity(string default_value) { MyEntity newMyEntity = new MyEntity(); newMyEntity._propertyValue = default_value; return View(newMyEntity); } </code></pre> <p>If you want to pass the default value through ActionLink</p> <pre><code>@Html.ActionLink("Create New", "CreateNewMyEntity", new { default_value = "5" }) </code></pre>
49,685,923
How to store best models checkpoints, not only newest 5, in Tensorflow Object Detection API?
<p>I'm training MobileNet on WIDER FACE dataset and I encountered problem I couldn't solve. TF Object Detection API stores only last 5 checkpoints in <code>train</code> dir, but what I would like to do, is to save best models relative to mAP metric (or at least leave many more models in <code>train</code> dir before deletion). For example, today I've looked at Tensorboard after next night of training and I see that overnight model has over-fitted and I can't restore best checkpoint, because it was deleted already.</p> <p>EDIT: I just use <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="noreferrer">Tensorflow Object Detection API</a>, it by default saves last 5 checkpoints in train dir which I point. I look for some configuration parameter or anything that will change this behavior.</p> <p>Has anyone have some fix in code/config param to set/workaround for that? It seems like I'm missing something, it should be obvious that what's in fact important is the best model, not the newest one (which can overfit).</p> <p>Thanks!</p>
49,699,464
5
1
null
2018-04-06 05:26:01.847 UTC
9
2021-02-03 12:27:24.65 UTC
2018-04-06 07:54:45.53 UTC
null
7,983,111
null
7,983,111
null
1
9
tensorflow|object-detection
11,984
<p>You can modify (hardcoding in your fork or opening a pull request and adding the options to protos) the arguments passed to <a href="https://www.tensorflow.org/api_docs/python/tf/train/Saver" rel="nofollow noreferrer">tf.train.Saver</a> in:</p> <p><a href="https://github.com/tensorflow/models/blob/master/research/object_detection/legacy/trainer.py#L376-L377" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/object_detection/legacy/trainer.py#L376-L377</a></p> <p>You will probably want to set:</p> <ul> <li>max_to_keep: Maximum number of recent checkpoints to keep. Defaults to 5.</li> <li>keep_checkpoint_every_n_hours: How often to keep checkpoints. Defaults to 10,000 hours.</li> </ul>
21,892,105
How to create a UIView bounce animation?
<p>I have the following CATransition for a UIView called <code>finalScoreView</code>, which makes it enter the screen from the top:</p> <pre><code>CATransition *animation = [CATransition animation]; animation.duration = 0.2; animation.type = kCATransitionPush; animation.subtype = kCATransitionFromBottom; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; [gameOver.layer addAnimation:animation forKey:@"changeTextTransition"]; [finalScoreView.layer addAnimation:animation forKey:@"changeTextTransition"]; </code></pre> <p>How do I make it so it bounces once after it comes down, then stays still? It should still enter the screen from the top but then bounce when it comes down.</p> <p>Any help would be much appreciated, thanks!</p>
21,892,424
4
1
null
2014-02-19 20:48:55.13 UTC
88
2020-10-27 14:25:07.343 UTC
2014-02-19 21:28:01.327 UTC
null
257,550
null
3,127,576
null
1
99
ios|iphone|animation|uiview|uikit
92,989
<p>With iOS7 and UIKit Dynamics, there is no longer any need to use <code>CAKeyframeAnimations</code> or <code>UIView</code> animations!</p> <p>Take a look at <a href="https://developer.apple.com/library/ios/samplecode/DynamicsCatalog/Introduction/Intro.html" rel="nofollow noreferrer">Apple's UIKit Dynamics Catalog app</a>. Alternately, <a href="http://www.teehanlax.com/blog/introduction-to-uikit-dynamics/" rel="nofollow noreferrer">Teehanlax has a clear, concise tutorial</a> with the <a href="https://github.com/TeehanLax/UIKit-Dynamics-Example" rel="nofollow noreferrer">full project in github</a>. If you want a more detailed tutorial about the ins-and-outs of dynamics, the <a href="http://www.raywenderlich.com/50197/uikit-dynamics-tutorial" rel="nofollow noreferrer">Ray Winderlich tutorial</a> is great. As always, the Apple docs are a great first stop, so check out the <a href="https://developer.apple.com/library/ios/documentation/uikit/reference/UIDynamicAnimator_Class/Reference/Reference.html" rel="nofollow noreferrer">UIDynamicAnimator Class reference</a> in the docs.</p> <p>Here's a bit of the code from the Teenhanlax tutorial:</p> <pre><code>self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view]; UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[self.redSquare]]; [self.animator addBehavior:gravityBehavior]; UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.redSquare]]; collisionBehavior.translatesReferenceBoundsIntoBoundary = YES; [self.animator addBehavior:collisionBehavior]; UIDynamicItemBehavior *elasticityBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self.redSquare]]; elasticityBehavior.elasticity = 0.7f; [self.animator addBehavior:elasticityBehavior]; </code></pre> <p>And here are the results</p> <p><img src="https://i.stack.imgur.com/VZQTK.gif" alt="Square bounce" /></p> <p>UIKit Dynamics is a really powerful and easy to use addition to iOS7 and you can get some great looking UI from it.</p> <p>Other examples:</p> <p><img src="https://i.stack.imgur.com/Axq7S.gif" alt="Button bounce" /></p> <p><img src="https://i.stack.imgur.com/fJF3p.gif" alt="Slide bounce" /></p> <p><img src="https://i.stack.imgur.com/QNHBp.gif" alt="Springy collection" /></p> <p><img src="https://i.stack.imgur.com/wIi4a.gif" alt="WWDC spring collection" /></p> <p>The steps to implement UIKit dynamics is always the same:</p> <ol> <li>Create a <code>UIDynamicAnimator</code> and store it in a strong property</li> <li>Create one or more <code>UIDynamicBehaviors</code>. Each behavior should have one or more items, typically a view to animate.</li> <li>Make sure that the initial state of the items used in the <code>UIDynamicBehaviors</code> is a valid state within the <code>UIDynamicAnimator</code> simulation.</li> </ol>
51,194,303
How to run a Python script in a '.py' file from a Google Colab notebook?
<pre><code>%%javascript IPython.OutputArea.prototype._should_scroll = function(lines) { return false; } %run rl_base.py </code></pre> <p>I run this giving error saying rl_base.py file not found. I have uploaded the same to gdrive in colab and from the same folder I am running my .ipynb file, containing the above code</p>
56,095,408
7
1
null
2018-07-05 14:49:34.5 UTC
19
2022-04-19 16:09:01.78 UTC
2019-11-13 14:03:20.47 UTC
null
2,458,922
null
2,458,922
null
1
51
python|python-3.x|jupyter-notebook|google-colaboratory
126,922
<p>If you have the test.py file in the corresponding folder in drive as in the below attached image, then the command which you use to run the test.py file is as mentioned below,</p> <pre><code>!python gdrive/My\ Drive/Colab\ Notebooks/object_detection_demo-master/test.py </code></pre> <h3>Additional Info:</h3> <p>If you jusst want to run <code>!python test.py</code> then you should change directory, by the following command before it,</p> <pre><code>%cd gdrive/My\ Drive/Colab\ Notebooks/object_detection_demo-master/ </code></pre> <p><a href="https://i.stack.imgur.com/xzJBk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xzJBk.png" alt="Folder Structure in Google Drive"></a></p>
9,545,732
What is HMODULE?
<p>I have a small problem. I have loaded DLL into the process (it's not mine) and I have to use function inside it. I have got offset to this function so only what I have to do is to get DLLs address and add to it the offset to get to the function. <code>GetModuleHandle()</code> returns <code>HMODULE</code> variable but actually I don't know what <code>HMODULE</code> is. Is it address of loaded DLL or some kind of other mark?</p> <p>And if it's not address of place where DLL is loaded, how can I get this address? I hope I make myself clear.</p>
9,545,949
3
0
null
2012-03-03 11:25:03.907 UTC
5
2021-10-30 20:55:25.823 UTC
2020-09-04 06:15:33.533 UTC
null
1,511,337
null
1,233,849
null
1
17
c++|winapi
42,032
<p>The method that you propose will work fine.</p> <p>It seems that you have injected a dll into a target process and wish to obtain the address of a function in that dll in the target process from the process that injected the dll.</p> <p>I assume that you also have the dll loaded in the process that injected the dll into the target process and that you want to create a remote thread in the target process and get it to execute the target function in the target process.</p> <p>Since the dll that you have injected may not be loaded at the same address in the target process as it is in the injecting process you cannot simply use the address that you would obtain from calling GetProcAddress on the function in the injecting process.</p> <p>An HMODULE is just the DLL's base address (see <a href="https://stackoverflow.com/a/557859/7925">this answer</a> for details). So you can take the HMODULE of the dll in your injecting process and subtract it from the address returned by GetProcAddress on your function. You can then add the HMODULE of the injected dll in the target process to this offset to get the address of the target function in the injected dll in the target process. Assuming this function has the correct signature, pass it as the thread function to your call to create the remote thread and you are now running the target function in the target process.</p> <p>I explain this in more detail in <a href="https://stackoverflow.com/questions/1162050/createremotethread-loadlibrary-and-postthreadmessage-whats-the-proper-ipc-me/1163681#1163681">this answer</a>.</p>
9,022,245
Get text from clipboard using GetText - avoid error on empty clipboard
<p>I'm using code like this to get text from off the Clipboard.</p> <pre><code>Dim DataObj As New MSForms.DataObject DataObj.GetFromClipboard myString = DataObj.GetText </code></pre> <p>I use error handling to get the past the case where the Clipboard is empty, and everything is fine as long as I keep Error Trapping set to Break on Unhandled Errors.</p> <p>However, for unrelated reasons I want to set Error Trapping to Break on All Errors, and this throws an error at <code>DataObj.GetText</code> when it finds the empty Clipboard. Is there any kind of test I can apply further upstream to avoid trying to process an empty Clipboard?</p>
9,024,237
2
0
null
2012-01-26 17:13:12.34 UTC
9
2020-08-16 08:09:37.657 UTC
2018-11-05 20:43:43.457 UTC
null
8,112,776
null
783,619
null
1
22
excel|vba|clipboard|copy-paste|clipboarddata
66,049
<p>Handle the errors with <code>On Error GoTo</code> as shown here:</p> <pre><code>Sub GetClipBoardText() Dim DataObj As MSForms.DataObject Set DataObj = New MsForms.DataObject '&lt;~~ Amended as per jp's suggestion On Error GoTo Whoa '~~&gt; Get data from the clipboard. DataObj.GetFromClipboard '~~&gt; Get clipboard contents myString = DataObj.GetText(1) MsgBox myString Exit Sub Whoa: If Err &lt;&gt; 0 Then MsgBox &quot;Data on clipboard is not text or is empty&quot; End Sub </code></pre> <p>You will notice that it will handle an empty clipboard as well.</p> <p>NB: to make the code work, you must <a href="https://stackoverflow.com/questions/45921953/what-is-the-user-defined-type-not-defined">have a reference</a> to &quot;Microsoft Forms 2.0 Object Library&quot; (this file can be found at <code>C:\windows\system32\FM20.dll</code> on 32-bit machines, or at <code>C:\Windows\sysWOW64\FM20.dll</code> on 64-bit machines), otherwise you'd get the error <strong>&quot;User-Defined type not defined&quot;</strong>.</p> <p>You can empty the clipboard before testing the above code by using the code below. Please paste it in a module.</p> <pre><code>Private Declare Function OpenClipboard Lib &quot;User32.dll&quot; _ (ByVal hWndNewOwner As Long) As Long Private Declare Function EmptyClipboard Lib &quot;User32.dll&quot; () As Long Private Declare Function CloseClipboard Lib &quot;User32.dll&quot; () As Long Public Sub ClearClipboard() Dim Ret Ret = OpenClipboard(0&amp;) If Ret &lt;&gt; 0 Then Ret = EmptyClipboard CloseClipboard End Sub </code></pre> <p>EDIT: you may also determine if the clipboard is empty by using this code:</p> <pre><code>Private Declare Function CountClipboardFormats Lib &quot;user32&quot; () As Long Sub Sample() If (CountClipboardFormats() = 0) = True Then MsgBox &quot;Clipboard is empty&quot; Else MsgBox &quot;Clipboard is not empty&quot; End If End Sub </code></pre>
9,279,441
The simplest way to deploy to production with builds
<p>I must confess I'm new to maven world after years of living in the world of monstrous debuild/ant/makefile chimeric constructions. I just don't have yet that very feeling which helps seasoned developer to choose right decisions, and it's looks like there are plenty different ways in maven.</p> <p>So, I have a simple project containing of web-app. I want basically following:</p> <ul> <li>deploy to development Tomcat (I'm using tomcat:deploy), then do nothing.</li> <li>deploy to production Tomcat, but <strong>before deployment</strong> update git repo, add tagged commit and upgrade build version. </li> </ul> <p>For distinguishing between development and production I've created profiles, <code>dev</code> and <code>prod</code>. The <code>dev</code> profile is activated by default. When I want to deploy something to production, I just type <code>mvn -P prod tomcat:deploy</code></p> <p>I've read about release plugin, as well as about buildnumber plugin. But I'm just not sure I'm going the right way. </p> <p>So, the question is - what is the most succint, self-contained and "mavenish" way to resolve the task I'm asking about.</p>
10,964,696
6
0
null
2012-02-14 15:20:43.3 UTC
13
2012-06-20 08:15:06.943 UTC
null
null
null
null
360,811
null
1
22
tomcat|deployment|maven
14,390
<p>Shabunk, as I was commented out, Maven is driving you on the best way to do what you want, inheriting from years of developpers experience.</p> <p>I would explain what I would (and what I myself really) do.</p> <p>So you're right to use Maven Release Plugin, plus another one (cargo for instance) You're trying to do two differents things : </p> <ul> <li>Identifying a unique version, which means tagging it, and updating pom for a new version</li> <li>Deploying your app (no matter which environnement it is)</li> </ul> <hr> <p><strong><em>Maven Release Plugin</em></strong></p> <p>Consider that your own process is maybe ligher than other dev teams are used to. I mean that there is more steps between unit testing and production deployment in larger teams (Q&amp;A, user acceptance, non regression campains). It seems that you make a shortcut linking tag and production deployement. If you want to deploy your webapp on different environnements (integration, user acceptannce, performance, preprod, and so on) you had to identify your version and had to be able to build it again (sure and "repeatable").</p> <p>That what maven-release-plugin is intended to. It helps you to verify that your source code is clean (all files under source control, with no modification), can compile and pass all tests phases. Then, it deals with pom version and tagging, and finish by storing it for later use in you Maven enterprise repository.</p> <p>You have many configurations to set up (ditributionManagement, SCM, maven plugin release configuration). But once it is in place, releasing version stand in one simple command line : </p> <pre><code>mvn release:prepare release:perform </code></pre> <p>If you want some examples, I can give you some.</p> <pre class="lang-xml prettyprint-override"><code>&lt;scm&gt; &lt;!-- Base URL repository --&gt; &lt;url&gt;scm:svn:http://svn.myorg.corp/svn/repository/&lt;/url&gt; &lt;!-- Developper URL (from trunk or branche) --&gt; &lt;developerConnection&gt;scm:svn:http://svn.myorg.corp/svn/repository/trunk/project1&lt;/developerConnection&gt; &lt;connection&gt;scm:svn:http://svn.myorg.corp/svn/repository/trunk/project1&lt;/connection&gt; &lt;/scm&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-scm-plugin&lt;/artifactId&gt; &lt;version&gt;1.6&lt;/version&gt; &lt;configuration&gt; &lt;username&gt;${from.settings.xml.user}&lt;/username&gt; &lt;password&gt;${from.settings.xml.password}&lt;/password&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-release-plugin&lt;/artifactId&gt; &lt;version&gt;2.2.2&lt;/version&gt; &lt;configuration&gt; &lt;tagBase&gt;http://svn.myorg.corp/svn/repository/tags/&lt;/tagBase&gt; &lt;scmCommentPrefix&gt;[DEV#SCM]&lt;/scmCommentPrefix&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; [...] &lt;/build&gt; &lt;distributionManagement&gt; &lt;repository&gt; &lt;id&gt;enterprise_repo&lt;/id&gt; &lt;name&gt;Enteprise Repository on Artifactory - Stable versions&lt;/name&gt; &lt;url&gt;http://repo.corp:8080/artifactory/prj-xxx-releases&lt;/url&gt; &lt;/repository&gt; &lt;snapshotRepository&gt; &lt;id&gt;enterprise_repo&lt;/id&gt; &lt;name&gt;Enteprise Repository on Artifactory - DEV versions&lt;/name&gt; &lt;url&gt;http://repo.corp:8080/artifactory/prj-xxx-snapshots&lt;/url&gt; &lt;/snapshotRepository&gt; &lt;site&gt; &lt;id&gt;corporate_site&lt;/id&gt; &lt;name&gt;Corporate public site&lt;/name&gt; &lt;!-- must add wagon plugin that support this protocol --&gt; &lt;url&gt;ftp://...&lt;/url&gt; &lt;/site&gt; &lt;/distributionManagement&gt; </code></pre> <hr> <p><strong><em>Deployement</em></strong></p> <p>Once again, you may have multiple environnements on which you want to test your app against. There is many plugins that allow you to send and deploy your war : the general cargo-plugin, or more specific ones tomcat-plugin, glassfish-plugin, ... Plugins are giving you the hability to do what you want. Then, configuration can be performed in many ways.</p> <p><em>Full Maven way :</em> The full integrated way with Maven is to use Profile and maybe Filters. Profiles let describe properites and behaviour, as you seem to know. Filters are kind of .properties grouping a set of variable that will be used to replace patterns in you xml configuration file into the war (for instance, db connection). It's not the one I use because I find it less flexible than externalizing files. But no matter</p> <p><em>Maven with its ecosystem:</em> The way I prefer is to build my apps with Maven and Jenkins (or Continous Integration tool). This is why I'm agree with Aaron when he says that you had to konw limitations of your tools. Using Jenkins, I run every hours/day my application against Unit Tests, generatio Q&amp;A reports, documentation, ... I have a release build that help me to produce all I want to deliver it (to my test team or my customer), and I provide some information to my jobs to deploy it onto different environnements (using maven profiles or jenkins built-in configuration).</p> <p>It works really fine for me, and I'm pretty sure this is the right way to do.</p> <p>[EDIT]</p> <hr> <p><strong><em>Deployment</em></strong></p> <p>Once again, deployment mean different phases of Lifecycle.</p> <p><strong>Local / Dev environnement</strong></p> <p>I'd never use tomcat:deploy until now, but only because I'd prefer using jetty as light web container (and well integrated with maven). But I'm pretty sure that every kinf of configuration would fit your needs here.</p> <p><strong>Continuous Integration Environnement</strong> In an continous integration environnement, I usually copy the war directly with Jenkins (exporting *.war on the desired machine). The way I do depends on many things :</p> <ul> <li>if CI soft is on the same (physical|virtual) server than your app server (Tomcat, Jboss, Weblogic, Glassfish, ...), or distant one => copy time will outstand server refresh time and will produce unsafe deployement (generally corrupted archives)</li> <li>if server is supporting hot reloading (exploded war in web-apps for Tomcat) or at least aware of file system modifications (full war in /deploy for JBoss)</li> <li>if you need to stop your server before, ...</li> </ul> <p>Most of time, it's a simple copy. If I can't, I use some integrated maven plugins (like jahia:deploy plugin for the famous CMS : www.jahia.com), or just cargo plugin : <a href="http://cargo.codehaus.org/Maven2+plugin" rel="noreferrer">http://cargo.codehaus.org/Maven2+plugin</a>. I don't have any example, but it's really easy to find some on internet because this configuration is often recommanded.</p> <p><strong>Q&amp;A / Acceptance / Production environnement</strong></p> <p>For those kind of environnements, which often (as far I as I saw in my job) deals with Service Level Agreement, we (I or admin team) wrote some specific scripts. I'm sure you will be desapointed, but as I mentionned, I don't rely on Maven for everything, and for deployement in particular. IMHO, this is one limit of this tool. You can maybe rely on cargo plugin, or specific ones, but releasing a version, or building one don't match (in time sequence) with real deployement. Even more, I didn't find any plugin that allow me easily to deploy on multiple instances ... and even worth you had to shutdown instances in a specific order (SLA's needs). That said, I didn't mentionned external properties, or SQL scripts, or anything else. They are additional reasons to rely on a dedicated tool.</p> <p>So, generally, we wrote our own ant / sell scripts. If somebody else have better solutions, I'm obviously interrested in !</p> <p>I hope I was clear enough.</p> <p>Regards.</p>
22,885,702
HTML for the Pause symbol in audio and video control
<p>I'm trying to find the Unicode symbol to make a button display the Unicode pause symbol. I was able to find that the Unicode play symbol is <code>&amp;#9658</code> but I'm looking for the equivalent of the Unicode pause symbol.</p>
22,885,848
12
1
null
2014-04-05 19:28:06.7 UTC
37
2021-12-27 00:07:42.343 UTC
2018-05-19 14:28:14.36 UTC
null
6,782,707
null
3,081,307
null
1
111
html|unicode|special-characters|symbols
194,175
<p>There are various symbols which could be considered adequate replacements, including: </p> <ol> <li><p><strong>| |</strong> - two standard (bolded) vertical bars.</p></li> <li><p>&#9611;&#9611; - <code>&amp;#9611;</code> and another<code>&amp;#9611;</code></p></li> <li><p>&#9612;&#9612; - <code>&amp;#9612;</code> and another<code>&amp;#9612;</code></p></li> <li><p>&#9613;&#9613; - <code>&amp;#9613;</code> and another<code>&amp;#9613;</code></p></li> <li><p>&#9614;&#9614; - <code>&amp;#9614;</code> and another<code>&amp;#9614;</code></p></li> <li><p>&#10074;&#10074; - <code>&amp;#10074;</code> and another <code>&amp;#10074;</code></p></li> </ol> <p>I may have missed out one or two, but I think these are the better ones. <a href="http://www.scrollseek.com/wd/html_symbols_complete.html">Here's a list of symbols</a> just in case.</p>
18,976,255
How do I dynamically build an ng-include src?
<p>I have the following code:</p> <pre><code>&lt;div ng-repeat="module in modules" id="{{module.Id}}"&gt; &lt;ng-include ng-init="bootstrapModule(module.Id)" src=""&gt;&lt;/ng-include&gt; &lt;/div&gt; </code></pre> <p>I want to be able to build a string in src like so:</p> <pre><code>/modules/{{module.Name}}/{{module.Name}}.tpl.html </code></pre> <p>But I keep hitting roadblocks. I've tried to use a call back function to build it, </p> <pre><code>$scope.constructTemplateUrl = function(id) { return '/modules/' + id + '/' + id + '.tpl.html'; } </code></pre> <p>But this gets called over &amp; over &amp; over and it doesn't seem to like that. I've also tried to construct it like so:</p> <pre><code>ng-src="/modules/{{module.Id}}/{{module.Id}}.tpl.html" </code></pre> <p>But that isn't working either. Rather than spend hours beating around the bush, I wondered if anyone else has come up against something like this and has any ideas?</p> <p>Also, when I grab the modules from $resource, I am returning them asynchronously with $q, so I can't seem to go through and add it into the modules before in the controller as <code>$scope.modules</code> just equals a <code>then</code> function at that point.</p> <p>Any ideas?</p>
18,976,895
1
1
null
2013-09-24 08:14:16.707 UTC
4
2013-09-24 21:29:57.227 UTC
2013-09-24 21:29:57.227 UTC
null
168,868
null
1,138,620
null
1
27
angularjs|angularjs-ng-repeat|angularjs-ng-include
45,832
<p><code>ngInclude | src</code> directive requires an angular expression, which means you should probably write </p> <p><code>ng-src="'/modules/' + module.Id + '/tpl.html'"</code></p> <p>From <a href="http://docs.angularjs.org/api/ng.directive:ngInclude">http://docs.angularjs.org/api/ng.directive:ngInclude</a></p> <blockquote> <p>ngInclude|src string angular expression evaluating to URL. If the source is a string constant, make sure you wrap it in quotes, e.g. src="'myPartialTemplate.html'".</p> </blockquote> <p>It might be better if you construct the url in model instead of inline HTML</p> <pre><code>&lt;div ng-repeat="module in modules" id="{{module.Id}}"&gt; &lt;ng-include src="module.url"&gt;&lt;/ng-include&gt; &lt;/div&gt; </code></pre>
18,909,273
How to change color of Selected Tab
<p>How to change color of tab when its selected, see below screen shot:</p> <p>i am showing Orange color in ActionBar, in a same way i wanna show orange color in place of light blue.</p> <p>To show Orange color in ActionBar background, i am using below code:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;style name="Theme.MyAppTheme" parent="android:style/Theme.Holo.Light"&gt; &lt;item name="android:actionBarStyle"&gt;@style/Theme.MyAppTheme.ActionBar&lt;/item&gt; &lt;/style&gt; &lt;style name="Theme.MyAppTheme.ActionBar" parent="android:style/Widget.Holo.Light.ActionBar"&gt; &lt;item name="android:background"&gt;#FF4444&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre>
18,909,350
11
1
null
2013-09-20 05:14:15.423 UTC
5
2021-12-16 17:50:32.483 UTC
2013-09-20 11:46:04.45 UTC
null
2,790,257
null
2,790,257
null
1
20
android|android-actionbar
67,303
<p>I really recommend you to use the <a href="http://jgilfelt.github.io/android-actionbarstylegenerator">Actionbar Style Generator</a>.</p> <p>With that tool you can easily theme your graphic elements in your toolbar. </p>
1,677,037
How can I reference my Java Enum without specifying its type
<p>I have a class that defines its own enum like this:</p> <pre><code>public class Test { enum MyEnum{E1, E2}; public static void aTestMethod() { Test2(E1); // &lt;&lt; Gives "E1 cannot be resolved" in eclipse. } public Test2(MyEnum e) {} } </code></pre> <p>If I specify MyEnum.E1 it works fine, but I'd really just like to have it as "E1". Any idea how I can accomplish this, or does it have to be defined in another file for this to work?</p> <p>CONCLUSION: I hadn't been able to get the syntax for the import correct. Since several answers suggested this was possible, I'm going to select the one that gave me the syntax I needed and upvote the others.</p> <p>By the way, a REALLY STRANGE part of this (before I got the static import to work), a switch statement I'd written that used the enum did not allow the enum to be prefixed by its type--all the rest of the code required it. Hurt my head.</p>
1,677,074
3
3
null
2009-11-04 22:13:03.887 UTC
16
2016-11-19 06:11:19.697 UTC
2009-11-04 22:54:39.73 UTC
null
12,943
null
12,943
null
1
92
java|enums
78,249
<p>Actually, you can do a <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.html" rel="noreferrer">static import</a> of a nested enum. The code below compiles fine:</p> <pre><code>package mypackage; import static mypackage.Test.MyEnum.*; public class Test { enum MyEnum{E1, E2}; public static void aTestMethod() { Test2(E1); } public static void Test2(MyEnum e) {} } </code></pre>
51,798,498
Flutter setState to another class?
<p>I have a root class <code>RootPage</code> which is a <code>StatefulWidget</code> which is always in view. I would like to change the <code>body</code> in <code>RootPage</code> which is controlled by <code>RootPage's currentPage Widget</code> from different classes such as my <code>FeedPage</code> class and any other class that I make?</p> <p>Example code</p> <pre><code>import 'package:flutter/material.dart'; class RootPage extends StatefulWidget { @override _RootPageState createState() =&gt; new _RootPageState(); } class _RootPageState extends State&lt;RootPage&gt; { FeedPage feedPage; Widget currentPage; @override void initState() { super.initState(); feedPage = FeedPage(); currentPage = feedPage; } @override Widget build(BuildContext context) { return new Scaffold( //Current page to be changed from other classes too? body: currentPage ); } } class FeedPage extends StatefulWidget { @override _feedPageState createState() =&gt; new _feedPageState(); } class _feedPageState extends State&lt;FeedPage&gt; { @override Widget build(BuildContext context) { return new FlatButton( onPressed: () { setState(() { //change the currentPage in RootPage so it switches FeedPage away and gets a new class that I'll make }); }, child: new Text('Go to a new page but keep root, just replace this feed part'), ); } } </code></pre> <p>I'm sure there's an obvious answer but I can't seem to figure out how to do it efficiently so it'll be easy to integrate future classes and keep my Root always in view.</p>
51,798,698
5
0
null
2018-08-11 09:55:11.36 UTC
11
2021-07-11 09:14:15.64 UTC
null
null
null
null
7,461,028
null
1
50
dart|flutter|setstate
67,449
<p>You can use <strong>callbacks functions</strong> to achieve this. Please refer to the below code.</p> <pre><code>import 'package:flutter/material.dart'; class RootPage extends StatefulWidget { @override _RootPageState createState() =&gt; new _RootPageState(); } class _RootPageState extends State&lt;RootPage&gt; { FeedPage feedPage; Widget currentPage; @override void initState() { super.initState(); feedPage = FeedPage(this.callback); currentPage = feedPage; } void callback(Widget nextPage) { setState(() { this.currentPage = nextPage; }); } @override Widget build(BuildContext context) { return new Scaffold( //Current page to be changed from other classes too? body: currentPage ); } } class FeedPage extends StatefulWidget { Function callback; FeedPage(this.callback); @override _feedPageState createState() =&gt; new _feedPageState(); } class _feedPageState extends State&lt;FeedPage&gt; { @override Widget build(BuildContext context) { return new FlatButton( onPressed: () { this.widget.callback(new NextPage()); // setState(() { // //change the currentPage in RootPage so it switches FeedPage away and gets a new class that I'll make // }); }, child: new Text('Go to a new page but keep root, just replace this feed part'), ); } } </code></pre> <p>This is very similar to this <a href="https://stackoverflow.com/questions/51463906/emit-the-data-to-parent-widget-in-flutter/51468131#51468131">problem</a> and you could refer 3rd point in my answer.</p>
23,231,563
'NoneType' object has no attribute 'config'
<p>What I am trying to do here is add the image to the button I have, then based on click or hover change the image. All the examples I have followed use the <code>.config()</code> method. </p> <p>For the life of me I can't figure out why it doesn't know what the button object is. What is interesting is that if I modify the Button definition line to include the image option, everything is fine. But, with that there it seems I can't modify it using <code>.config()</code></p> <pre><code>PlayUp = PhotoImage(file=currentdir+'\Up_image.gif') PlayDown = PhotoImage(file=currentdir+'\Down_image.gif') #Functions def playButton(): pButton.config(image=PlayDown) pButton = Button(root, text="Play", command="playButton").grid(row=1) pButton.config(image=PlayUp) </code></pre>
23,231,580
4
0
null
2014-04-22 22:38:37.937 UTC
3
2022-03-14 01:32:33.123 UTC
2017-02-19 18:20:17.977 UTC
null
3,329,664
null
2,138,140
null
1
15
python|image|button|nonetype
42,285
<pre><code>pButton = Button(root, text="Play", command="playButton").grid(row=1) </code></pre> <p>Here you are creating an object of type <code>Button</code>, but you are immediately calling the <code>grid</code> method over it, which returns <code>None</code>. Thus, <code>pButton</code> gets assigned <code>None</code>, and that's why the next row fails.</p> <p>You should do instead:</p> <pre><code>pButton = Button(root, text="Play", command="playButton") pButton.grid(row=1) pButton.config(image=PlayUp) </code></pre> <p>i.e. first you create the button and assign it to <code>pButton</code>, <em>then</em> you do stuff over it.</p>
40,036,648
GIT Fatal : refusing to merge unrelated histories
<pre><code>$ git pull origin master From https://bitbucket.org/tecgenome/chl-v2.0-html * branch master -&gt; FETCH_HEAD fatal: refusing to merge unrelated histories </code></pre> <p>How can I avoid or get past that error message?</p>
40,037,123
3
0
null
2016-10-14 06:47:22.347 UTC
6
2021-12-17 10:49:39.283 UTC
2021-12-17 10:49:39.283 UTC
null
6,294,937
null
6,294,937
null
1
28
git|bitbucket
33,042
<p><a href="https://stackoverflow.com/a/36528527/6309">Since Git 2.9 (April 2016)</a>, you can try:</p> <pre><code>git pull --allow-unrelated-histories origin master </code></pre> <p>But check why those branches are no longer common though.<br /> May be there was a force push rewritting <em>all</em> the history of <code>origin/master</code>.</p> <p>In which case, if you don't have local commits of your own, it is best to reset your branch to the new one:</p> <p><strong>Warning</strong>: this will delete any untracked file, and reset your repository to <strong>origin/master</strong><br /> (You can try it in a copy of your current local clone)</p> <pre><code>git fetch # Warning: RESET AHEAD git reset --hard origin/master </code></pre>
42,874,351
Spring Boot enabling CORS by application.properties
<p>I using Spring Boot API RESTful that get up automatically by your Entities Class. I'm consuming this apiRest from a front-end web app but it gives me this error:</p> <blockquote> <p>No 'Access-Control-Allow-Origin' header is present on the requested resource</p> </blockquote> <p>I'm setting the CORS configuration using the applicantion.properties specified <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html" rel="noreferrer">here</a>.</p> <p>My basic configuration is:</p> <pre><code>endpoints.cors.allow-credentials=true endpoints.cors.allowed-origins=* endpoints.cors.allowed-methods=* endpoints.cors.allowed-headers=* </code></pre> <p>I have tried different combinations in those variables but still not working. Any ideas?</p>
42,899,222
12
0
null
2017-03-18 12:22:16.513 UTC
20
2022-08-20 20:47:04.657 UTC
2018-08-15 17:14:27.243 UTC
null
472,495
null
2,992,476
null
1
38
spring-boot|cors
75,685
<p>I got the answer by myself:</p> <p>Just add this to application.java</p> <pre><code> @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000"); } }; } </code></pre>
29,502,255
Is there a way to close a tab in WebDriver or Protractor?
<p>Is there a way to physically close a tab via Protractor or WebDriver? </p> <p>I ask because while I know how to <a href="https://stackoverflow.com/questions/26798020/protractor-switch-to-previous-tab">switch tabs</a> programmatically, but it does not bring the active tab to the foreground. I can't always tell what is going on in my E2E tests that run on SauceLabs because when I view the screen casts it is showing the tab that I navigated away from, not the active one.</p> <p>Am I going about this incorrectly?</p> <pre><code>it('should do something in the previous tab', function(done) { browser.getAllWindowHandles().then(function (handles) { browser.switchTo().window(handles[0]); // do something expect(something).toEqual(thisThing); done(); }); }); </code></pre>
29,505,926
11
0
null
2015-04-07 22:10:10.767 UTC
12
2021-04-27 19:04:24.037 UTC
2017-05-23 12:02:23.447 UTC
null
-1
null
2,058,281
null
1
40
selenium|selenium-webdriver|protractor
129,693
<p>You can try the following:</p> <ol> <li>Switch to the new opened tab. </li> <li>Close the current windows (in this case, the new tab). </li> <li><p>Switch back to the first window.</p> <pre><code>browser.getAllWindowHandles().then(function (handles) { browser.driver.switchTo().window(handles[1]); browser.driver.close(); browser.driver.switchTo().window(handles[0]); }); </code></pre></li> </ol>
274,815
Flash - recording from user's webcam
<p>I've seen a few sites that have a flash app which takes video from the users webcam and manipulates it. One example is the flash barcode reader <a href="http://www.renaun.com/flex2/BarcodeReader/BarcodeReader.html" rel="noreferrer">http://www.renaun.com/flex2/BarcodeReader/BarcodeReader.html</a> .</p> <p>I want users to be able to submit 10-15 second clips which I can save to my server and then play back later via flash again.</p> <p>Can you link to some example projects for this, or tell me what sections of which manuals I should be looking at?</p> <p>-Adam</p>
274,820
4
0
null
2008-11-08 15:14:27.63 UTC
11
2012-10-21 09:33:38.953 UTC
null
null
null
Adam Davis
2,915
null
1
7
apache-flex|flash|flv|webcam
10,040
<p>There are several articles with sample code for this on adobes site. I would recommend you to go through this tutorial as it will guide you through all the necessary steps along with sample code:</p> <p><a href="http://www.adobe.com/devnet/flash/articles/webcam_motion.html" rel="nofollow noreferrer"><a href="http://www.adobe.com/devnet/flash/articles/webcam_motion.html" rel="nofollow noreferrer">http://www.adobe.com/devnet/flash/articles/webcam_motion.html</a></a></p>
162,764
Sql Server 2005 how to change dbo login name
<p>I have a database with user 'dbo' that has a login name "domain\xzy". How do I change it from "domain\xzy" to "domain\abc".</p>
251,742
4
0
null
2008-10-02 14:54:09.967 UTC
9
2021-03-09 23:19:10.18 UTC
2008-10-30 20:56:05.467 UTC
PhantomTypist
24,522
Jason
24,522
null
1
56
sql-server|sql-server-2005|security|active-directory
69,348
<p>I figured it out. Within SQL Management Studio you have to right-click on the database -> Properties -> Files -> Owner field. Change this field to the login name/account that you want associated with the "dbo" username for that database. Please keep in mind that the login name/account you choose must already be setup in the sql server under Security -> Logins</p>
813,822
How to make git merge handle uncommitted changes to my working tree?
<p>A co-worker and I are both working on the master branch at the moment. I have some code in my working tree that I don't want to commit (debugging statements and the like). Now if he commits changes to some of those same files, I can't merge them:</p> <pre><code>$ git merge origin/master Updating 1b8c5c6..eb44c23 error: Entry 'blah.java' not uptodate. Cannot merge. </code></pre> <p>Coming from a subversion background, I'm used to having my working tree automatically merged when I pull changes from the repository and if there are conflicts, I resolve them manually.</p> <p>The quickest way I have found to do this in git is:</p> <pre><code>$ git stash $ git merge origin/master $ git stash pop </code></pre> <p>Essentially, removing my uncommitted changes, doing the merge and then re-applying the changes. How can I tell merge to automatically merge my working tree with the changes I'm trying to pull in?</p>
813,827
4
5
null
2009-05-02 00:33:38.603 UTC
16
2019-03-19 01:50:59.78 UTC
null
null
null
null
99,189
null
1
56
git|git-merge|git-stash
40,774
<p>As far as I can tell, the best you can do is what you already have with <code>git stash</code>. I too find it strange that merge wants to deal only with clean trees.</p>
804,297
When to use `require`, `load` or `autoload` in Ruby?
<p>I understand the subtle differences between <code>require</code>, <code>load</code> and <code>autoload</code> in Ruby, but my question is, how do you know which one to use? </p> <p>Other than being able to "wrap" a <code>load</code> in an anonymous module, <code>require</code> seems to be preferred.</p> <p>But then <code>autoload</code> allows you to lazy load files -- which sounds fantastic but I'm not sure practically what you gain over <code>require</code></p> <p>Is one method preferred over the other? Is there a situation where one method stands out?</p>
804,698
4
0
null
2009-04-29 21:12:38.277 UTC
16
2019-11-17 23:23:00.45 UTC
null
null
null
null
31,377
null
1
65
ruby|module
25,302
<p>Generally, you should use <code>require</code>. <code>load</code> will re-load the code every time, so if you do it from several modules, you will be doing a lot of extra work. The lazyness of <code>autoload</code> sounds nice in theory, but many Ruby modules do things like monkey-patching other classes, which means that the behavior of unrelated parts of your program may depend on whether a given class has been used yet or not.</p> <p>If you want to make your own automatic reloader that loads your code every time it changes or every time someone hits a URL (for development purposes so you don't have to restart your server every time), then using <code>load</code> for that is reasonable.</p>
25,779,184
Explanation of generic <T extends Comparable<? super T>> in collection.sort/ comparable code?
<p>I use comparable interface all the time to provided natural ordering for my class through collection.sort.</p> <p>Basically if I have a person class, I will get it to implement Comparable interface and will provide the implementation of compareTo. However in the definition of Collections.sort in javadocs, I see this signature</p> <pre><code>public static &lt;T extends Comparable&lt;? super T&gt;&gt; void sort(List&lt;T&gt; list) </code></pre> <p>I don't understand this generics definition at all? Shouldn't it just say</p> <pre><code>&lt;T implements Comparable&lt;T&gt;&gt; </code></pre> <p>Can someone help me with this?</p>
25,783,345
2
2
null
2014-09-11 04:37:47.213 UTC
26
2014-09-11 09:05:56.393 UTC
2014-09-11 06:57:44.457 UTC
null
2,057,294
null
1,529,267
null
1
37
java|generics
26,955
<p>Actually, it means that T <em>can</em> implement <code>Comparable&lt;? super T&gt;</code>, not just <code>Comparable&lt;T&gt;</code>.</p> <p>For example, it means that a <code>Student</code> class can implement <code>Comparable&lt;Person&gt;</code>, where <code>Student</code> is a subclass of <code>Person</code>:</p> <pre><code>public class Person {} public class Student extends Person implements Comparable&lt;Person&gt; { @Override public int compareTo(Person that) { // ... } } </code></pre> <p>In this case, a List can be sorted by <code>Collections.sort()</code> but only based on <code>Person</code>'s properties, because you pass the <code>Student</code> instance into <code>compareTo()</code> as a <code>Person</code> (unless you downcast it, of course).</p> <p>In practice however, you'll never see a <code>Student</code> class implement <code>Comparable&lt;Person&gt;</code>. That's because <code>Person</code> will probably have implemented <code>Comparable&lt;Person&gt;</code>, and <code>Student</code> inherits it implementation. The end result is the same however: you can pass a <code>List&lt;Student&gt;</code> to <code>Collections.sort()</code> and have it sorted on <code>Person</code>'s properties.</p> <p>The difference between <code>Comparable&lt;T&gt;</code> and <code>Comparable&lt;? super T&gt;</code> is more obvious in <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-java.util.Comparator-" rel="noreferrer">the overloaded version of Collections.sort()</a> that takes a <code>Comparator&lt;? super T&gt;</code>:</p> <pre><code>class ByAgeAscending implements Comparator&lt;Person&gt; { @Override public int compare(Person a, Person b) { return a.getAge() &lt; b.getAge(); } } List&lt;Student&gt; students = getSomeStudents(); Collections.sort(students, new ByAgeAscending()); </code></pre>
30,429,168
Is a base64 encoded string unique?
<p>I can't find an answer to this. If I encode a string with Base64 will the encoded output be unique based on the string? I ask because I want to create a token which will contain user information so I need make sure the output will be unique depending on the information.</p> <p>For example if I encode "UnqUserId:987654321 Timestamp:01/02/03" will this be unique so no matter what other userid I put it in there will never be a collision?</p>
46,597,409
1
1
null
2015-05-24 22:51:15.413 UTC
13
2022-02-12 21:14:47.937 UTC
2015-05-24 23:14:40.777 UTC
null
1,816,580
null
2,924,127
null
1
40
encoding|base64
21,877
<p>Two years late, but here we go:</p> <p>The short answer is <strong>yes, unique binary/hex values will <em>always</em> encode to a unique base64 encoded string.</strong></p> <p><strong>BUT, multiple base64 encoded strings may represent a single binary/hex value.</strong> </p> <p>This is because hex bytes are not aligned with base64 'digits'. A single hex byte is represented by 8 bits while a single base64 digit is represented by 6 bits. Therefore, any hex value that is not 6-bit aligned <em>can</em> have multiple base64 representations (though correctly implemented base64 encoders <em>should</em> encode to the same base64 representation).</p> <p>An example of this misalignment is the hex value '0x433356c1'. This value is represented by 32-bits and base64 encodes into 'QzNWwQ=='. This 32-bit value, however, is not 6-bit aligned. So what happens? The base64 encoder pads four zero bits onto the end of the binary representation in this case to make the sequence 36-bits and consequently 6-bit aligned. </p> <p>When decoding, the base64 decoder now has to decode into an 8-bit aligned value. It truncates the padded bits and decodes the first 32 bits into a hex value. For example, 'QzNWwc==' and 'QzNWwQ==' are different base64 encoded strings, but decode to the same hex value, 0x433356c1. If we look carefully, we notice that the first 32 bits are the same for both of these encoded strings:</p> <pre><code>'QzNWwc==': 010000 110011 001101 010110 110000 011100 'QzNWwQ==': 010000 110011 001101 010110 110000 010000 </code></pre> <p>The only difference is the last four bits, which are ignored. Keep in mind that no base64 encoder <em>should</em> ever generate 'QzNWwc==' or any other base64 value for 0x433356c1 other than 'QzNWwQ==' since added padding bytes should always be zeros.</p> <p>In conclusion, it is safe to assume that a unique binary/hex value will always encode to a unique base64 representation using correctly implemented base64 encoders. A 'collision' will only occur during decoding if base64 strings are generated without zeroing padding/alignment bytes.</p>
53,748,675
Strongly typed Guid as generic struct
<p>I already make twice same bug in code like following:</p> <pre><code>void Foo(Guid appId, Guid accountId, Guid paymentId, Guid whateverId) { ... } Guid appId = ....; Guid accountId = ...; Guid paymentId = ...; Guid whateverId =....; //BUG - parameters are swapped - but compiler compiles it Foo(appId, paymentId, accountId, whateverId); </code></pre> <p>OK, I want to prevent these bugs, so I created strongly typed GUIDs:</p> <pre><code>[ImmutableObject(true)] public struct AppId { private readonly Guid _value; public AppId(string value) { var val = Guid.Parse(value); CheckValue(val); _value = val; } public AppId(Guid value) { CheckValue(value); _value = value; } private static void CheckValue(Guid value) { if(value == Guid.Empty) throw new ArgumentException("Guid value cannot be empty", nameof(value)); } public override string ToString() { return _value.ToString(); } } </code></pre> <p>And another one for PaymentId:</p> <pre><code>[ImmutableObject(true)] public struct PaymentId { private readonly Guid _value; public PaymentId(string value) { var val = Guid.Parse(value); CheckValue(val); _value = val; } public PaymentId(Guid value) { CheckValue(value); _value = value; } private static void CheckValue(Guid value) { if(value == Guid.Empty) throw new ArgumentException("Guid value cannot be empty", nameof(value)); } public override string ToString() { return _value.ToString(); } } </code></pre> <p>These structs are almost same, there is a lot of duplication of code. Isn't is?</p> <p>I cannot figure out any elegant way to solve it except using class instead of struct. I would rather use struct, because of null checks, less memory footprint, no garbage collector overhead etc...</p> <p>Do you have some idea how to use struct without duplicating code?</p>
53,748,965
5
5
null
2018-12-12 17:50:04.49 UTC
4
2022-06-22 13:54:39.983 UTC
2018-12-12 18:01:46.343 UTC
null
518,530
null
518,530
null
1
40
c#|generics|struct|guid
1,799
<p>First off, this is a really good idea. A brief aside:</p> <p>I wish C# made it easier to create cheap typed wrappers around integers, strings, ids, and so on. We are very "string happy" and "integer happy" as programmers; lots of things are represented as strings and integers which could have more information tracked in the type system; we don't want to be assigning customer names to customer addresses. A while back I wrote a series of blog posts (never finished!) about writing a virtual machine in OCaml, and one of the best things I did was wrapped every integer in the virtual machine with a type that indicates its purpose. That prevented so many bugs! OCaml makes it very easy to create little wrapper types; C# does not.</p> <p>Second, I would not worry too much about duplicating the code. It's mostly an easy copy-paste, and you are unlikely to edit the code much or make mistakes. <strong>Spend your time solving real problems.</strong> A little copy-pasted code is not a big deal.</p> <p>If you do want to avoid the copy-pasted code, then I would suggest using generics like this:</p> <pre><code>struct App {} struct Payment {} public struct Id&lt;T&gt; { private readonly Guid _value; public Id(string value) { var val = Guid.Parse(value); CheckValue(val); _value = val; } public Id(Guid value) { CheckValue(value); _value = value; } private static void CheckValue(Guid value) { if(value == Guid.Empty) throw new ArgumentException("Guid value cannot be empty", nameof(value)); } public override string ToString() { return _value.ToString(); } } </code></pre> <p>And now you're done. You have types <code>Id&lt;App&gt;</code> and <code>Id&lt;Payment&gt;</code> instead of <code>AppId</code> and <code>PaymentId</code>, but you still cannot assign an <code>Id&lt;App&gt;</code> to <code>Id&lt;Payment&gt;</code> or <code>Guid</code>.</p> <p>Also, if you like using <code>AppId</code> and <code>PaymentId</code> then at the top of your file you can say</p> <pre><code>using AppId = MyNamespace.Whatever.Id&lt;MyNamespace.Whatever.App&gt; </code></pre> <p>and so on.</p> <p>Third, you will probably need a few more features in your type; I assume this is not done yet. For example, you'll probably need equality, so that you can check to see if two ids are the same.</p> <p>Fourth, be aware that <code>default(Id&lt;App&gt;)</code> still gives you an "empty guid" identifier, so your attempt to prevent that does not actually work; it will still be possible to create one. There is not really a good way around that.</p>
20,563,639
Ansible playbook shell output
<p>I would like to quickly monitor some hosts using commands like ps,dstat etc using ansible-playbook. The <code>ansible</code> command itself perfectly does what I want, for instance I'd use:</p> <pre><code>ansible -m shell -a "ps -eo pcpu,user,args | sort -r -k1 | head -n5" </code></pre> <p>and it nicely prints all std output for every host like this:</p> <pre><code>localhost | success | rc=0 &gt;&gt; 0.0 root /sbin/init 0.0 root [kthreadd] 0.0 root [ksoftirqd/0] 0.0 root [migration/0] otherhost | success | rc=0 &gt;&gt; 0.0 root /sbin/init 0.0 root [kthreadd] 0.0 root [ksoftirqd/0] 0.0 root [migration/0] </code></pre> <p>However this requires me to keep a bunch of shell scripts around for every task which is not very 'ansible' so I put this in a playbook:</p> <pre><code>--- - hosts: all gather_facts: no tasks: - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5 </code></pre> <p>and run it with <code>-vv</code>, but the output baiscally shows the dictionary content and newlines are not printed as such so this results in an unreadable mess like this:</p> <pre><code>changed: [localhost] =&gt; {"changed": true, "cmd": "ps -eo pcpu,user,args | sort -r -k1 head -n5 ", "delta": "0:00:00.015337", "end": "2013-12-13 10:57:25.680708", "rc": 0, "start": "2013-12-13 10:57:25.665371", "stderr": "", "stdout": "47.3 xxx Xvnc4 :24 -desktop xxx:24 (xxx) -auth /home/xxx/.Xauthority -geometry 1920x1200\n .... </code></pre> <p>I also tried adding <code>register: var</code> and the a 'debug' task to show <code>{{ var.stdout }}</code> but the result is of course the same.</p> <p>Is there a way to get nicely formatted output from a command's stdout/stderr when run via a playbook? I can think of a number of possible ways (format output using sed? redirect output to file on the host then get that file back and echo it to the screen?), but with my limited knowledge of the shell/ansible it would take me a day to just try it out.</p>
24,834,231
8
1
null
2013-12-13 10:01:05.623 UTC
18
2022-07-06 22:29:07.44 UTC
2013-12-13 11:52:13.227 UTC
null
128,384
null
128,384
null
1
73
shell|sed|ansible
219,100
<p>The <code>debug</code> module could really use some love, but at the moment the best you can do is use this:</p> <pre><code>- hosts: all gather_facts: no tasks: - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5 register: ps - debug: var=ps.stdout_lines </code></pre> <p>It gives an output like this:</p> <pre><code>ok: [host1] =&gt; { "ps.stdout_lines": [ "%CPU USER COMMAND", " 1.0 root /usr/bin/python", " 0.6 root sshd: root@notty ", " 0.2 root java", " 0.0 root sort -r -k1" ] } ok: [host2] =&gt; { "ps.stdout_lines": [ "%CPU USER COMMAND", " 4.0 root /usr/bin/python", " 0.6 root sshd: root@notty ", " 0.1 root java", " 0.0 root sort -r -k1" ] } </code></pre>
20,366,189
LINQ where condition filtering
<pre><code>String Sex = getSex(); // return M or F String[] members = getMembers(); // return member codes in array or null //if members array is null, no filtering for member codes var query = from tb in MemberTable where tb.sex.Equals(Sex) &amp;&amp; (members != null ? members.Contains(tb.membercode) : true) select tb; </code></pre> <p>The code doesn't return correct result. It returns all members no matter what <code>members[]</code> is.</p> <p>Actually the original LINQ is complex so if there are any other possible solutions, I do not want to write the following:</p> <pre><code>if (members == null){ /*LINQ1*/ } else { /*LINQ2*/ } </code></pre> <p>which is not a good coding style. Any suggestion for solving this problem?</p>
20,366,227
3
1
null
2013-12-04 03:23:03.24 UTC
4
2019-03-12 10:24:52.3 UTC
2013-12-06 02:21:49.82 UTC
null
1,984,610
null
1,984,610
null
1
7
c#|linq
95,215
<pre><code>var query = MemberTable.Where(x=&gt;x.sex.Equals(Sex)) if (members != null) query = query.Where(x=&gt;members.Contains(x.membercode)) //use your query query.ToList(); </code></pre> <p>OR</p> <pre><code>var query = from tb in MemberTable where tb.sex.Equals(Sex) &amp;&amp; (members == null || members.Contains(tb.membercode)) select tb; </code></pre> <p>I prefer the first.</p>
51,875,158
Check if JSON response data is empty
<p>The JSON response looks like this when it is empty when viewed in the browser console:</p> <pre><code>{"data":{},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://url/form/BN217473","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"","xhrStatus":"complete"} </code></pre> <p>In angular script I am checking if the response is empty but the check is not catching the empty response as the logic block is never executed</p> <pre><code>if (response.data == '') { console.log("no data found"); } </code></pre> <p>How can I check that my response is not empty?</p>
51,875,192
3
1
null
2018-08-16 10:44:13.843 UTC
2
2018-08-16 10:50:03.487 UTC
2018-08-16 10:48:14.65 UTC
null
1,108,098
null
9,841,828
null
1
8
javascript|angularjs
56,823
<p>Try below code snippet:-</p> <pre><code>if(!Object.keys(response.data).length){ console.log("no data found"); } </code></pre> <p>If you are getting data as empty object like data: {}, then you should check if there is any key inside the object or not.</p>
4,814,432
Publishing To User's Wall Without Being Online/Logged-in - Facebook Sharing Using Graph API
<p>Hi i'm new to facebook sharing. I want to make a user log in using his uid and then store these for further uses</p> <p>The primary purpose is to share links in the user's wall</p> <p>next time onwards without showing the facebook window i want to post in to his wall through ajax.</p> <p>How is it possible any help regarding this will be appreciated!</p> <p><strong>EDIT</strong></p> <p>I used the example given and then tried curl function</p> <p>got this error</p> <pre><code>HTTP/1.1 403 Forbidden Cache-Control: no-store Content-Type: text/javascript; charset=UTF-8 Expires: Sat, 01 Jan 2000 00:00:00 GMT P3P: CP="Facebook does not have a P3P policy. Learn why here: http://fb.me/p3p" Pragma: no-cache WWW-Authenticate: OAuth "Facebook Platform" "insufficient_scope" "(#200) This API call requires a valid app_id." Set-Cookie: datr=g4JBTb4OsRZxBAztV7iIkpWg; expires=Sat, 26-Jan-2013 14:34:43 GMT; path=/; domain=.facebook.com; httponly X-Cnection: close Date: Thu, 27 Jan 2011 14:34:43 GMT Content-Length: 93 {"error":{"type":"OAuthException","message":"(#200) This API call requires a valid app_id."}} </code></pre> <p><strong>EDIT SO THAT SOMEONE MAY FIND USEFUL</strong></p> <p>FACEBOOK CONNECTION</p> <pre><code>$facebook_connect = array( 'appId' =&gt; 'YOUR APP_ID', 'secret' =&gt; 'YOUR SEC KEY', 'access_token'=&gt;"USER'S ACCESS TOKEN", 'cookie' =&gt; true ); </code></pre> <p>POST TO USER WALL</p> <pre><code>$facebook-&gt;api("/PROFILE_ID/feed", "post", array( "message"=&gt;"Hi Friends Join ****", "name"=&gt;"You're invited to join ****!", "link"=&gt;"www.****.com", "description"=&gt;"Great site", "picture"=&gt;"http://www.****.com/logo.jpg", "caption"=&gt;"Join *****" ) </code></pre>
4,816,134
1
0
null
2011-01-27 09:08:50.093 UTC
13
2012-11-11 20:40:07.01 UTC
2011-08-25 10:02:44.507 UTC
null
337,227
null
538,778
null
1
7
php|facebook|facebook-graph-api|facebook-php-sdk
20,681
<p>I suggest you start learning how Facebook Graph API works first. </p> <ol> <li>Facebook will <strong><em>NEVER</em></strong> share the user password with you!</li> <li>If you just need to give the user the possibility to share link, then just use the <a href="http://developers.facebook.com/docs/reference/plugins/like">like plugin</a>. You may also find more interesting <a href="http://developers.facebook.com/docs/plugins">social plugins</a> to use in your website.</li> <li>If you use the like plugin, it won't open any popups and it would post the link directly to the user's wall.</li> <li>You could always use the <a href="http://developers.facebook.com/docs/reference/dialogs/feed/">Feed Dialog</a></li> <li>Start reading the <a href="http://developers.facebook.com/docs/">Facebook Documentation</a> </li> </ol> <hr> <p>Now to post on the user's wall (on his behalf) <strong><em>without</em></strong> him being logged-in, you need the following: </p> <ol> <li><a href="https://developers.facebook.com/docs/opengraph/using-app-tokens/">app <code>access_token</code></a></li> <li><code>publish_stream</code> permission, <strong>NO NEED</strong> for the long-lived access token: </li> </ol> <blockquote> <p>Enables your app to post content, comments, and likes to a user's stream and to the streams of the user's friends. This is a superset publishing permission which also includes publish_actions. However, please note that Facebook recommends a user-initiated sharing model. Please read the Platform Policies to ensure you understand how to properly use this permission. Note, you do not need to request the publish_stream permission in order to use the Feed Dialog, the Requests Dialog or the Send Dialog.</p> </blockquote> <p><strong>Require the permission:</strong><br> This can be done in multiple of ways:<br> Using the <a href="https://developers.facebook.com/docs/reference/plugins/login/">Login Plugin</a>: </p> <pre><code>&lt;div class="fb-login-button" data-show-faces="true" data-width="200" data-scope="publish_stream" data-max-rows="1"&gt;&lt;/div&gt; </code></pre> <p><a href="https://developers.facebook.com/docs/howtos/login/server-side-login/">Server-side login</a> (Redirect to the OAuth Dialog): </p> <pre><code>https://www.facebook.com/dialog/oauth? client_id=YOUR_APP_ID &amp;redirect_uri=YOUR_URL &amp;scope=publish_stream &amp;state=SOME_ARBITRARY_BUT_UNIQUE_STRING </code></pre> <p><a href="https://github.com/facebook/php-sdk">PHP-SDK</a>: </p> <pre><code>$loginUrl = $facebook-&gt;getLoginUrl(array("scope"=&gt;"publish_stream")); </code></pre> <p>JS-SDK through the <a href="https://developers.facebook.com/docs/reference/javascript/FB.login/">FB.login</a> method: </p> <pre><code> FB.login(function(response) { if (response.authResponse) { console.log('Welcome! Fetching your information.... '); FB.api('/me', function(response) { console.log('Good to see you, ' + response.name + '.'); FB.logout(function(response) { console.log('Logged out.'); }); }); } else { console.log('User cancelled login or did not fully authorize.'); } }, {scope: 'publish_stream'}); </code></pre> <p><strong>Publishing:</strong> </p> <pre><code>$USER_ID = "XXXXXXXX"; // Connected once to your APP and not necessary logged-in at the moment $args = array( 'message' =&gt; 'Hello from app', 'link' =&gt; 'http://www.masteringapi.com/', 'caption' =&gt; 'Visit MasteringAPI.com For Facebook API Tutorials!' ); $post_id = $facebook-&gt;api("/$USER_ID/feed", "post", $args); </code></pre> <p><strong>Note:</strong><br> While it's possible to post without the user's presence always remember Facebook recommends a user-initiated sharing model</p>
4,716,092
WinForms DataGridView - databind to an object with a list property (variable number of columns)
<p>I have a .NET class I'd like to show in a DataGridView, and the default databinding - setting the DGV's DataSource to the object - produces 90% of my requirements (i.e. it's outputting the public properties correctly and I can add sorting easily).</p> <p>However, one of the properties I need to bind is a List which contains data which needs to be in separate columns after the other databound items. I'm stuck on how best to implement this.</p> <p>My class looks something like this:</p> <pre><code>public class BookDetails { public string Title { get; set; } public int TotalRating { get; set; } public int Occurrence { get; set; } public List&lt;int&gt; Rating { get; set; } } </code></pre> <p>Ideally, I'd be able to expand that Rating property into a number of numeric columns to give an output like this at runtime:</p> <p>Title | Total Rating | Occurrence | R1 | R2 | R3 ... RN</p> <p>It would also be useful to have Total Rating be calculated as the sum of all the individual ratings, but I'm updating that manually at the moment without issue.</p>
4,717,268
1
7
null
2011-01-17 17:42:36.417 UTC
9
2022-08-22 03:46:57.86 UTC
2011-01-26 15:41:25.107 UTC
null
42,841
null
42,841
null
1
11
c#|.net|winforms|data-binding|datagridview
9,299
<p>Like this?</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows.Forms; public class BookDetails { public string Title { get; set; } public int TotalRating { get; set; } public int Occurrence { get; set; } public List&lt;int&gt; Rating { get; set; } } class BookList : List&lt;BookDetails&gt;, ITypedList { public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) { var origProps = TypeDescriptor.GetProperties(typeof(BookDetails)); List&lt;PropertyDescriptor&gt; newProps = new List&lt;PropertyDescriptor&gt;(origProps.Count); PropertyDescriptor doThisLast = null; foreach (PropertyDescriptor prop in origProps) { if (prop.Name == &quot;Rating&quot;) doThisLast = prop; else newProps.Add(prop); } if (doThisLast != null) { var max = (from book in this let rating = book.Rating where rating != null select (int?)rating.Count).Max() ?? 0; if (max &gt; 0) { // want it nullable to account for jagged arrays Type propType = typeof(int?); // could also figure this out from List&lt;T&gt; in // the general case, but make it nullable for (int i = 0; i &lt; max; i++) { newProps.Add(new ListItemDescriptor(doThisLast, i, propType)); } } } return new PropertyDescriptorCollection(newProps.ToArray()); } public string GetListName(PropertyDescriptor[] listAccessors) { return &quot;&quot;; } } class ListItemDescriptor : PropertyDescriptor { private static readonly Attribute[] nix = new Attribute[0]; private readonly PropertyDescriptor tail; private readonly Type type; private readonly int index; public ListItemDescriptor(PropertyDescriptor tail, int index, Type type) : base(tail.Name + &quot;[&quot; + index + &quot;]&quot;, nix) { this.tail = tail; this.type = type; this.index = index; } public override object GetValue(object component) { IList list = tail.GetValue(component) as IList; return (list == null || list.Count &lt;= index) ? null : list[index]; } public override Type PropertyType { get { return type; } } public override bool IsReadOnly { get { return true; } } public override void SetValue(object component, object value) { throw new NotSupportedException(); } public override void ResetValue(object component) { throw new NotSupportedException(); } public override bool CanResetValue(object component) { return false; } public override Type ComponentType { get { return tail.ComponentType; } } public override bool ShouldSerializeValue(object component) { return false; } } static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); var data = new BookList { new BookDetails { Title = &quot;abc&quot;, TotalRating = 3, Occurrence = 2, Rating = new List&lt;int&gt; {1,2,1}}, new BookDetails { Title = &quot;def&quot;, TotalRating = 3, Occurrence = 2, Rating = null }, new BookDetails { Title = &quot;ghi&quot;, TotalRating = 3, Occurrence = 2, Rating = new List&lt;int&gt; {3, 2}}, new BookDetails { Title = &quot;jkl&quot;, TotalRating = 3, Occurrence = 2, Rating = new List&lt;int&gt;()}, }; Application.Run(new Form { Controls = { new DataGridView { Dock = DockStyle.Fill, DataSource = data } } }); } } </code></pre>
4,205,662
Draw an Inset NSShadow and Inset Stroke
<p>I have an <code>NSBezierPath</code> and I want to draw in inset shadow (similar to Photoshop) inside the path.</p> <p>Is there anyway to do this? Also, I know you can <code>-stroke</code> paths, but can you stroke inside a path (similar to Stroke Inside in Photoshop)?</p> <h2>Update 3</h2> <pre><code>static NSImage * graydient = nil; if (!graydient) { graydient = [[NSImage alloc] initWithSize: NSMakeSize(22, 22)]; [graydient lockFocus]; NSGradient * gradient = [[NSGradient alloc] initWithColorsAndLocations: clr(@"#262729"), 0.0f, clr(@"#37383a"), 0.43f, clr(@"#37383a"), 1.0f, nil]; [gradient drawInRect: NSMakeRect(0, 4.179, 22, 13.578) angle: 90.0f]; [gradient release]; [graydient unlockFocus]; } NSColor * gcolor = [NSColor colorWithPatternImage: graydient]; [gcolor set]; NSShadow * shadow = [NSShadow new]; [shadow setShadowColor: [NSColor colorWithDeviceWhite: 1.0f alpha: 1.0f]]; [shadow setShadowBlurRadius: 0.0f]; [shadow setShadowOffset: NSMakeSize(0, 1)]; [shadow set]; [path fill]; [NSGraphicsContext saveGraphicsState]; [[path pathFromIntersectionWithPath: [NSBezierPath bezierPathWithRect: NSInsetRect([path bounds], 0.6, 0)]] setClip]; [gcolor set]; [shadow setShadowOffset: NSMakeSize(0, 1)]; [shadow setShadowColor: [NSColor blackColor]]; [shadow set]; [outer stroke]; [NSGraphicsContext restoreGraphicsState]; [NSGraphicsContext saveGraphicsState]; [[NSGraphicsContext currentContext] setCompositingOperation: NSCompositeSourceOut]; [shadow set]; [[NSColor whiteColor] set]; [inner fill]; [shadow set]; [inner fill]; [NSGraphicsContext restoreGraphicsState]; </code></pre> <p><img src="https://i.stack.imgur.com/lyn2J.png" alt="Final Result"> This is my final result. It looks pretty good. I had to change the shadow to White @ 1.0 Alpha to make it work. Even though the shadow alpha norm for menu bar items is 0.5, it doesn't look half bad.</p> <p>Many thanks go out to <a href="https://stackoverflow.com/users/201199/joshua-nozzi">Joshua Nozzi</a>.</p>
4,206,726
1
1
null
2010-11-17 14:59:50.12 UTC
11
2014-02-24 06:52:48.417 UTC
2017-05-23 12:24:43.06 UTC
null
-1
null
205,895
null
1
13
cocoa|drawing|photoshop|shadow|bezier
9,418
<p>I think you can do this by setting clip on the bezier path to use it as a mask and stroking the shadow, then adding a normal stroke if desired.</p> <p><strong>Update based on updated code:</strong></p> <p>Here you go. I'm feeling procrastinate-y tonight. :-)</p> <pre><code>// Describe an inset rect (adjust for pixel border) NSRect whiteRect = NSInsetRect([self bounds], 20, 20); whiteRect.origin.x += 0.5; whiteRect.origin.y += 0.5; // Create and fill the shown path NSBezierPath * path = [NSBezierPath bezierPathWithRect:whiteRect]; [[NSColor whiteColor] set]; [path fill]; // Save the graphics state for shadow [NSGraphicsContext saveGraphicsState]; // Set the shown path as the clip [path setClip]; // Create and stroke the shadow NSShadow * shadow = [[[NSShadow alloc] init] autorelease]; [shadow setShadowColor:[NSColor redColor]]; [shadow setShadowBlurRadius:10.0]; [shadow set]; [path stroke]; // Restore the graphics state [NSGraphicsContext restoreGraphicsState]; // Add a nice stroke for a border [path setLineWidth:1.0]; [[NSColor grayColor] set]; [path stroke]; </code></pre>
34,752,200
Gson: @Expose vs @SerializedName
<p>With respect to Gson what is the difference between <code>@Expose</code> and <code>@SerializedName("stringValue")</code>?</p>
52,221,102
4
3
null
2016-01-12 19:28:01.023 UTC
19
2019-02-19 07:23:18.04 UTC
2019-01-29 23:04:05.93 UTC
null
1,709,587
null
867,591
null
1
95
java|android|json|gson
73,700
<p>Even if it's late I wanted to answer this question. To explain it we must know what is <code>serialization</code> and <code>deserialization</code>. <code>serialization</code> is converting <code>object</code> into <code>json string</code> and <code>deserialization</code> is converting <code>json string</code> into <code>object</code>.</p> <p>Let's say we've <code>User</code> class with no annotations.</p> <pre><code>public class User{ private String userName; private Integer userAge; public User(String name, Integer age){ userName = name; userAge = age; } } </code></pre> <p>And we <code>serialize</code> this <code>object</code> as below</p> <pre><code>User user = new User("Ahmed", 30); Gson gson = new Gson(); String jsonString = gson.toJson(user); </code></pre> <p>Json string will be like this</p> <pre><code>{ "userName":"Ahmed", "userAge":30 } </code></pre> <p>If we add annotation <code>@SerializedName</code></p> <pre><code>public class User{ @SerializedName("name") private String userName; @SerializedName("age") private Integer userAge; public User(String name, Integer age){ userName = name; userAge = age; } } </code></pre> <p>Json string will be like this</p> <pre><code>{ "name":"Ahmed", "age":30 } </code></pre> <p><code>@Expose</code> is used to allow or disallow <code>serialization</code> and <code>deserialization</code>. <code>@Expose</code> is optional and it has two configuration parameters: <code>serialize</code> and <code>deserialize</code>. By default they're set to true. To <code>serialize</code> and <code>deserialize</code> with <code>@Expose</code> we create gson object like this</p> <pre><code>Gson gsonBuilder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); </code></pre> <p>Below <code>userName</code> won't be deserialized. userName's value will be <code>null</code>.</p> <pre><code>@SerializedName("name") @Expose(deserialize = false) private String userName; </code></pre> <p>Below <code>userName</code> won't be serialized.</p> <pre><code>@SerializedName("name") @Expose(serialize = false) private String userName; </code></pre> <p>Json string will be like this. Only <code>userAge</code> will be deserialized.</p> <pre><code>{ "age":30 } </code></pre>
39,436,018
How to drop null values in Pandas?
<p>I try to drop null values of column 'Age' in dataframe, which consists of float values, but it doesn't work. I tried</p> <pre><code>data.dropna(subset=['Age'], how='all') data['Age'] = data['Age'].dropna() data=data.dropna(axis=1,how='all') </code></pre> <p>It works for other columns but not for 'Age'</p> <pre><code> Pclass Fare Age Sex 0 3 7.2500 22.0 1 1 1 71.2833 38.0 0 2 3 7.9250 26.0 0 3 1 53.1000 35.0 0 4 3 8.0500 35.0 1 5 3 8.4583 NaN 1 6 1 51.8625 54.0 1 7 3 21.0750 2.0 1 </code></pre>
39,436,068
1
1
null
2016-09-11 12:20:45.267 UTC
2
2016-09-11 12:26:47.637 UTC
null
null
null
null
6,646,671
null
1
7
python|pandas
49,370
<p><code>data.dropna(subset=['Age'])</code> would work, but you should either set <code>inplace=True</code> or assign it back to <code>data</code>:</p> <pre><code>data = data.dropna(subset=['Age']) </code></pre> <p>or </p> <pre><code>data.dropna(subset=['Age'], inplace=True) </code></pre>
31,318,107
Spring Boot: Cannot access REST Controller on localhost (404)
<p>I am trying to adapt the REST Controller example on the Spring Boot website. Unfortunately I've got the following error when I am trying to access the <code>localhost:8080/item</code> URL. </p> <pre><code>{ "timestamp": 1436442596410, "status": 404, "error": "Not Found", "message": "No message available", "path": "/item" } </code></pre> <p>POM:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;SpringBootTest&lt;/groupId&gt; &lt;artifactId&gt;SpringBootTest&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;properties&gt; &lt;javaVersion&gt;1.8&lt;/javaVersion&gt; &lt;mainClassPackage&gt;com.nice.application&lt;/mainClassPackage&gt; &lt;mainClass&gt;${mainClassPackage}.InventoryApp&lt;/mainClass&gt; &lt;/properties&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.3&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;${javaVersion}&lt;/source&gt; &lt;target&gt;${javaVersion}&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;!-- Makes the Spring Boot app executable for a jar file. The additional configuration is needed for the cmd: mvn spring-boot:repackage OR mvn spring-boot:run --&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;mainClass&gt;${mainClass}&lt;/mainClass&gt; &lt;layout&gt;ZIP&lt;/layout&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;repackage&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;!-- Create a jar with a manifest --&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;version&gt;2.4&lt;/version&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifest&gt; &lt;mainClass&gt;${mainClass}&lt;/mainClass&gt; &lt;/manifest&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;!-- Import dependency management from Spring Boot. This replaces the usage of the Spring Boot parent POM file. --&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt; &lt;version&gt;1.2.5.RELEASE&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- more comfortable usage of several features when developing in an IDE. Developer tools are automatically disabled when running a fully packaged application. If your application is launched using java -jar or if it’s started using a special classloader, then it is considered a 'production application'. Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.guava&lt;/groupId&gt; &lt;artifactId&gt;guava&lt;/artifactId&gt; &lt;version&gt;15.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre> <p>Starter-Application:</p> <pre><code>package com.nice.application; @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class InventoryApp { public static void main( String[] args ) { SpringApplication.run( InventoryApp.class, args ); } } </code></pre> <p>REST-Controller:</p> <pre><code>package com.nice.controller; @RestController // shorthand for @Controller and @ResponseBody rolled together public class ItemInventoryController { public ItemInventoryController() { } @RequestMapping( "/item" ) public String getStockItem() { return "It's working...!"; } } </code></pre> <p>I am building this project with Maven. Started it as jar (spring-boot:run) and as well inside the IDE (Eclipse).</p> <p>Console Log:</p> <pre><code>2015-07-09 14:21:52.132 INFO 1204 --- [ main] c.b.i.p.s.e.i.a.InventoryApp : Starting InventoryApp on 101010002016M with PID 1204 (C:\eclipse_workspace\SpringBootTest\target\classes started by MFE in C:\eclipse_workspace\SpringBootTest) 2015-07-09 14:21:52.165 INFO 1204 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7a3d45bd: startup date [Thu Jul 09 14:21:52 CEST 2015]; root of context hierarchy 2015-07-09 14:21:52.661 INFO 1204 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]] 2015-07-09 14:21:53.430 INFO 1204 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2015-07-09 14:21:53.624 INFO 1204 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat 2015-07-09 14:21:53.625 INFO 1204 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.23 2015-07-09 14:21:53.731 INFO 1204 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2015-07-09 14:21:53.731 INFO 1204 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1569 ms 2015-07-09 14:21:54.281 INFO 1204 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2015-07-09 14:21:54.285 INFO 1204 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2015-07-09 14:21:54.285 INFO 1204 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2015-07-09 14:21:54.508 INFO 1204 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7a3d45bd: startup date [Thu Jul 09 14:21:52 CEST 2015]; root of context hierarchy 2015-07-09 14:21:54.573 INFO 1204 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity&lt;java.util.Map&lt;java.lang.String, java.lang.Object&gt;&gt; org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2015-07-09 14:21:54.573 INFO 1204 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest) 2015-07-09 14:21:54.594 INFO 1204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2015-07-09 14:21:54.594 INFO 1204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2015-07-09 14:21:54.633 INFO 1204 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2015-07-09 14:21:54.710 INFO 1204 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2015-07-09 14:21:54.793 INFO 1204 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2015-07-09 14:21:54.795 INFO 1204 --- [ main] c.b.i.p.s.e.i.a.InventoryApp : Started InventoryApp in 2.885 seconds (JVM running for 3.227) 2015-07-09 14:22:10.911 INFO 1204 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet' 2015-07-09 14:22:10.911 INFO 1204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started 2015-07-09 14:22:10.926 INFO 1204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 15 ms </code></pre> <p>What I've tried so far: </p> <ul> <li>Accessing the URL with the application name (InventoryApp)</li> <li>Put another <code>@RequestMapping("/")</code> at class level of the <code>ItemInventoryController</code></li> </ul> <p>As far as I understood, I won't need an application-context when using Spring Boot. Am I right?</p> <p>What else can I do to access the method via URL?</p>
31,318,789
25
6
null
2015-07-09 12:52:32.997 UTC
33
2022-07-13 09:20:09.383 UTC
2015-07-09 13:29:40.813 UTC
null
1,654,284
null
1,654,284
null
1
151
java|rest|spring-boot
336,108
<p>Try adding the following to your InventoryApp class</p> <pre><code>@SpringBootApplication @ComponentScan(basePackageClasses = ItemInventoryController.class) public class InventoryApp { ... </code></pre> <p>spring-boot will scan for components in packages below <code>com.nice.application</code>, so if your controller is in <code>com.nice.controller</code> you need to scan for it explicitly.</p>
6,856,878
C# - Why are DateTime.MinValue and MaxValue not compile-time constants?
<p>I wanted to have an optional date parameter for a method (defaulted to MinValue), in order to check if the user had actually supplied a value or not (supplying MinValue was invalid), but I'm not allowed as apparently it's not a compile-time constant. </p> <p>According to <a href="http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx" rel="noreferrer">the MSDN page</a>, "The value of this constant is equivalent to 00:00:00.0000000, January 1, 0001." </p> <p>So why is that not compile-time constant? And why is it different from passing in Int32.MinValue, which is allowed?</p>
6,856,893
2
1
null
2011-07-28 09:37:03.44 UTC
2
2011-07-28 09:46:19.497 UTC
null
null
null
null
546,004
null
1
28
c#|datetime|compile-time-constant
5,821
<p>You cannot define a DateTime constant (or structs). From MSDN allowed types for const are:</p> <blockquote> <p>One of the types: byte, char, short, int, long, float, double, decimal, bool, string, an enum type, or a reference type.</p> </blockquote>
7,242,006
html5: copy a canvas to image and back
<p>I implemented a zoom in and out function on a canvas element. it works by scaling the canvas, translating it, and then redraw the whole scene again. the problem is that it takes a lot of time to redraw everything because i got a lot of things on my canvas.</p> <p>I need a way to copy the canvas to an image object and than copy the image back to the canvas without loosing quality. what are the specific methods to copy canvas to a javascript variable, and to to copy this variable back to the canvas later?</p> <p>I'll be glad if you write down the code because I couldn't find any good explanation over the internet.</p> <p>thanks,</p>
7,243,407
3
3
null
2011-08-30 10:47:12.973 UTC
11
2016-07-17 21:17:54.093 UTC
null
null
null
null
774,190
null
1
26
image|html|canvas
51,581
<p>The drawImage() method can draw to a canvas using another canvas instead of an image.</p> <p>You could create a 'backup' canvas, of the same size as your original, draw the first one to there and then draw that one back to the original when you need it.</p> <p>e.g.</p> <pre><code>// Assume we have a main canvas // canvas = &lt;main canvas&gt; ctx = canvas.getContext('2d'); .. // create backing canvas var backCanvas = document.createElement('canvas'); backCanvas.width = canvas.width; backCanvas.height = canvas.height; var backCtx = backCanvas.getContext('2d'); // save main canvas contents backCtx.drawImage(canvas, 0,0); .. // restore main canvas ctx.drawImage(backCanvas, 0,0); </code></pre>
7,222,533
Polymorphic model binding
<p>This question has been <a href="https://stackoverflow.com/questions/4012217/asp-net-mvc-2-binding-to-abstract-model">asked before</a> in earlier versions of MVC. There is also <a href="http://blog.abodit.com/2010/02/asp-net-mvc-ambiguous-match/" rel="noreferrer">this blog entry</a> about a way to work around the problem. I'm wondering if MVC3 has introduced anything that might help, or if there are any other options.</p> <p>In a nutshell. Here's the situation. I have an abstract base model, and 2 concrete subclasses. I have a strongly typed view that renders the models with <code>EditorForModel()</code>. Then I have custom templates to render each concrete type.</p> <p>The problem comes at post time. If I make the post action method take the base class as the parameter, then MVC can't create an abstract version of it (which i would not want anyways, i'd want it to create the actual concrete type). If I create multiple post action methods that vary only by parameter signature, then MVC complains that it's ambiguous.</p> <p>So as far as I can tell, I have a few choices on how to solve this proble. I don't like any of them for various reasons, but i will list them here:</p> <ol> <li>Create a custom model binder as Darin suggests in the first post I linked to.</li> <li>Create a discriminator attribute as the second post I linked to suggests.</li> <li>Post to different action methods based on type</li> <li>???</li> </ol> <p>I don't like 1, because it is basically configuration that is hidden. Some other developer working on the code may not know about it and waste a lot of time trying to figure out why things break when changes things.</p> <p>I don't like 2, because it seems kind of hacky. But, i'm leaning towards this approach.</p> <p>I don't like 3, because that means violating DRY. </p> <p>Any other suggestions?</p> <p>Edit: </p> <p>I decided to go with Darin's method, but made a slight change. I added this to my abstract model:</p> <pre><code>[HiddenInput(DisplayValue = false)] public string ConcreteModelType { get { return this.GetType().ToString(); }} </code></pre> <p>Then a hidden automatically gets generated in my <code>DisplayForModel()</code>. The only thing you have to remember is that if you're not using <code>DisplayForModel()</code>, you'll have to add it yourself.</p>
7,222,639
4
0
null
2011-08-28 17:18:20.137 UTC
46
2021-11-19 11:29:26.437 UTC
2017-05-23 12:17:45.993 UTC
null
-1
null
61,164
null
1
59
asp.net-mvc|asp.net-mvc-3|polymorphism|model-binding
28,427
<p>Since I obviously opt for option 1 (:-)) let me try to elaborate it a little more so that it is less <em>breakable</em> and avoid hardcoding concrete instances into the model binder. The idea is to pass the concrete type into a hidden field and use reflection to instantiate the concrete type.</p> <p>Suppose that you have the following view models:</p> <pre><code>public abstract class BaseViewModel { public int Id { get; set; } } public class FooViewModel : BaseViewModel { public string Foo { get; set; } } </code></pre> <p>the following controller:</p> <pre><code>public class HomeController : Controller { public ActionResult Index() { var model = new FooViewModel { Id = 1, Foo = "foo" }; return View(model); } [HttpPost] public ActionResult Index(BaseViewModel model) { return View(model); } } </code></pre> <p>the corresponding <code>Index</code> view:</p> <pre><code>@model BaseViewModel @using (Html.BeginForm()) { @Html.Hidden("ModelType", Model.GetType()) @Html.EditorForModel() &lt;input type="submit" value="OK" /&gt; } </code></pre> <p>and the <code>~/Views/Home/EditorTemplates/FooViewModel.cshtml</code> editor template:</p> <pre><code>@model FooViewModel @Html.EditorFor(x =&gt; x.Id) @Html.EditorFor(x =&gt; x.Foo) </code></pre> <p>Now we could have the following custom model binder:</p> <pre><code>public class BaseViewModelBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var typeValue = bindingContext.ValueProvider.GetValue("ModelType"); var type = Type.GetType( (string)typeValue.ConvertTo(typeof(string)), true ); if (!typeof(BaseViewModel).IsAssignableFrom(type)) { throw new InvalidOperationException("Bad Type"); } var model = Activator.CreateInstance(type); bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() =&gt; model, type); return model; } } </code></pre> <p>The actual type is inferred from the value of the <code>ModelType</code> hidden field. It is not hardcoded, meaning that you could add other child types later without having to ever touch this model binder. </p> <p>This same technique could be <a href="https://stackoverflow.com/questions/6484972/viewmodel-with-listbaseclass-and-editor-templates/6485552#6485552">easily be applied</a> to collections of base view models.</p>
24,172,814
How to change publisher name in Google Play
<p>I just recently posted my first app to Google Play. When I search for my app, I would see my app name, and underneath the app name it says who published it. In my case, my app says it is published under my full legal name. I would like to change it so that my app says it is published by my company name. How can I go about changing this? I don't mind removing my app from Google Play and uploading a new app if I have to.</p>
24,172,911
3
2
null
2014-06-11 21:23:09.38 UTC
9
2022-01-18 14:29:55.843 UTC
2019-07-03 22:13:45.387 UTC
null
6,214,491
null
2,969,777
null
1
63
android|publisher
56,106
<p>In the Developer Console, go to Settings, and change the 'Developer Name'.</p> <p>Note that this name is the same for <em>all</em> of your apps. If you want to keep your name for other apps, you need a separate developer account and file for an app transfer.</p>
1,994,945
How to do window.open with no scrollbars in Google Chrome
<p>The following code opens the <strong>new window without scrollbars</strong> in Firefox, IE and Opera. </p> <pre><code> var options = { height: 300, // sets the height in pixels of the window. width: 300, // sets the width in pixels of the window. toolbar: 0, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}. scrollbars: 0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}. status: 0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}. resizable: 1, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable. left: 0, // left position when the window appears. top: 0, // top position when the window appears. center: 0, // should we center the window? {1 (YES) or 0 (NO)}. overrides top and left createnew: 0, // should we create a new window for each occurance {1 (YES) or 0 (NO)}. location: 0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}. menubar: 0 // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}. }; var parameters = "location=" + options.location + ",menubar=" + options.menubar + ",height=" + options.height + ",width=" + options.width + ",toolbar=" + options.toolbar + ",scrollbars=" + options.scrollbars + ",status=" + options.status + ",resizable=" + options.resizable + ",left=" + options.left + ",screenX=" + options.left + ",top=" + options.top + ",screenY=" + options.top; // target url var target = 'some url' popup = window.open(target, 'popup', parameters); </code></pre> <p>In <strong>Google Chrome</strong> the new window still has the scrollbars. Any ideas to make it work?</p>
1,995,823
4
0
null
2010-01-03 13:27:36.027 UTC
10
2014-01-12 09:21:56.07 UTC
2010-01-03 14:46:38.817 UTC
null
96,656
null
221,315
null
1
15
javascript|google-chrome|popup
56,902
<p>This style should do the trick, add it to the opened window document:</p> <pre><code> body{ overflow-x:hidden;overflow-y:hidden; } </code></pre>
1,853,450
Install Eclipse JDT on top of CDT
<p>I have the eclipse CDT installed, and I would like to install Java development functionality (JDT) on top of my CDT installation. I've been Googling from an hour but I can't figure out how to do this. </p> <p>What plugin do I need to install? What update site do I need to use?</p>
1,853,603
4
0
null
2009-12-05 21:01:05.5 UTC
17
2021-05-31 09:23:27.493 UTC
2016-10-26 09:52:34.98 UTC
null
452,775
null
141,719
null
1
72
eclipse|eclipse-cdt|eclipse-jdt
49,086
<p>All versions of Eclipse have a standard base, then a specific set of plugins, depending on the version. All you have to do is go to the <em>Help > Install New Software</em> menu, select the Eclipse update site (e.g. "Galileo - <a href="http://download.eclipse.org/releases/galileo" rel="noreferrer">http://download.eclipse.org/releases/galileo</a>"), and under the <em>Programming Languages</em> section, select <em>Eclipse Java Development Tools</em>.</p> <p>If you don't see the Java Development Tools in the list, click on the "already installed" link on the install page--you may already have the Java tools installed.</p>
26,099,111
Swift Compiler Error: Use of unresolved identifier 'name'
<p>I tried to include a class called 'name' and I got an error:</p> <pre><code>Swift Compiler Error: Use of unresolved identifier 'name' </code></pre> <p>The class exists and doesn't contain any compile errors.</p>
26,099,112
5
1
null
2014-09-29 11:43:28.26 UTC
null
2017-05-10 11:27:16.553 UTC
2015-12-01 09:15:44.047 UTC
null
1,121,716
null
1,121,716
null
1
20
ios|xcode|swift|compiler-errors|ios9
46,036
<p>There could be a few possible issues.</p> <ol> <li><p>One of the classes has a <strong>Testing target</strong> and other one doesn't. You have to even include all of your classes in the testing target or none of them.</p></li> <li><p>If it's Objective C class, check that the class is in ObjectiveC bridging header file.</p></li> <li><p>If it's NSManagedObject subclass. Add <code>@objc(className)</code> before the class declaration.</p></li> <li><p>If it's part of a different framework, make sure that the class or function is <code>public</code></p></li> </ol>
7,291,065
Any library for face recognition in JavaScript?
<p>I would like to know if someone know how to recognize a face using just JavaScript. I've heard of OpenCV and relatives but I want to process the face recognition at the client side (web app).</p> <p>Any ideas?</p>
7,291,105
5
5
null
2011-09-03 03:54:02.807 UTC
24
2016-08-25 16:10:22.877 UTC
null
null
null
null
114,747
null
1
37
javascript|face-recognition
43,067
<p>If you are looking to recognize where a face is in an image, as opposed to matching faces across multiple images, there is actually a library that does this in conjunction with HTML canvass.</p> <p>There is a demo on the developers site <a href="http://liuliu.me/detect/detect.html" rel="noreferrer">here</a>. You can also download the source on <a href="https://github.com/liuliu/ccv" rel="noreferrer">github</a>.</p> <p>In my test's the performance was decent - but not blazing.</p>
7,229,070
How to set value to variable using 'execute' in t-sql?
<pre><code>DECLARE @dbName nvarchar(128) = 'myDb' DECLARE @siteId int exec ('SELECT TOP 1 @siteId = Id FROM ' + @dbName + '..myTbl') select @siteId </code></pre> <p>When I run the script above I get the following error</p> <pre><code>Msg 137, Level 15, State 1, Line 1 Must declare the scalar variable "@siteId". (1 row(s) affected) </code></pre> <p>Why and how to fix it?</p> <p>Thank you</p>
7,229,151
5
0
null
2011-08-29 10:46:32.757 UTC
13
2021-12-09 14:11:17.313 UTC
null
null
null
null
573,082
null
1
69
sql-server|tsql
203,924
<p>You can use output parameters with sp_executesql.</p> <pre><code>DECLARE @dbName nvarchar(128) = 'myDb' DECLARE @siteId int DECLARE @SQL nvarchar(max) = N'SELECT TOP 1 @outputFromExec = Id FROM ' + quotename(@dbName) + N'..myTbl' exec sp_executesql @SQL, N'@outputFromExec int out', @siteId out select @siteId </code></pre>
7,114,990
Pseudo-terminal will not be allocated because stdin is not a terminal
<p>I am trying to write a shell script that creates some directories on a remote server and then uses scp to copy files from my local machine onto the remote. Here's what I have so far:</p> <pre><code>ssh -t user@server&lt;&lt;EOT DEP_ROOT='/home/matthewr/releases' datestamp=$(date +%Y%m%d%H%M%S) REL_DIR=$DEP_ROOT"/"$datestamp if [ ! -d "$DEP_ROOT" ]; then echo "creating the root directory" mkdir $DEP_ROOT fi mkdir $REL_DIR exit EOT scp ./dir1 user@server:$REL_DIR scp ./dir2 user@server:$REL_DIR </code></pre> <p>Whenever I run it I get this message:</p> <pre><code>Pseudo-terminal will not be allocated because stdin is not a terminal. </code></pre> <p>And the script just hangs forever.</p> <p>My public key is trusted on the server and I can run all the commands outside of the script just fine. Any ideas?</p>
7,122,115
9
4
null
2011-08-18 22:38:40.413 UTC
137
2021-08-01 01:38:08.343 UTC
2015-12-14 15:27:42.82 UTC
null
2,214,693
null
818,091
null
1
437
linux|bash|shell|ssh
608,415
<p>Try <code>ssh -t -t</code>(or <code>ssh -tt</code> for short) to force pseudo-tty allocation even if stdin isn't a terminal.</p> <p>See also: <a href="https://stackoverflow.com/questions/7085429/terminating-ssh-session-executed-by-bash-script">Terminating SSH session executed by bash script</a></p> <p>From ssh manpage:</p> <pre><code>-T Disable pseudo-tty allocation. -t Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty. </code></pre>
7,161,638
How do I use a custom Serializer with Jackson?
<p>I have two Java classes that I want to serialize to JSON using Jackson:</p> <pre><code>public class User { public final int id; public final String name; public User(int id, String name) { this.id = id; this.name = name; } } public class Item { public final int id; public final String itemNr; public final User createdBy; public Item(int id, String itemNr, User createdBy) { this.id = id; this.itemNr = itemNr; this.createdBy = createdBy; } } </code></pre> <p>I want to serialize an Item to this JSON:</p> <pre><code>{"id":7, "itemNr":"TEST", "createdBy":3} </code></pre> <p>with User serialized to only include the <code>id</code>. I will also be able to serilize all user objects to JSON like:</p> <pre><code>{"id":3, "name": "Jonas", "email": "[email protected]"} </code></pre> <p>So I guess that I need to write a custom serializer for <code>Item</code> and tried with this:</p> <pre><code>public class ItemSerializer extends JsonSerializer&lt;Item&gt; { @Override public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeNumberField("id", value.id); jgen.writeNumberField("itemNr", value.itemNr); jgen.writeNumberField("createdBy", value.user.id); jgen.writeEndObject(); } } </code></pre> <p>I serialize the JSON with this code from <a href="https://github.com/FasterXML/jackson-docs/wiki/JacksonHowToCustomSerializers" rel="noreferrer">Jackson How-to: Custom Serializers</a>:</p> <pre><code>ObjectMapper mapper = new ObjectMapper(); SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1,0,0,null)); simpleModule.addSerializer(new ItemSerializer()); mapper.registerModule(simpleModule); StringWriter writer = new StringWriter(); try { mapper.writeValue(writer, myItem); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } </code></pre> <p>But I get this error:</p> <pre><code>Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType() (use alternative registration method?) at org.codehaus.jackson.map.module.SimpleSerializers.addSerializer(SimpleSerializers.java:62) at org.codehaus.jackson.map.module.SimpleModule.addSerializer(SimpleModule.java:54) at com.example.JsonTest.main(JsonTest.java:54) </code></pre> <p><strong>How can I use a custom Serializer with Jackson?</strong></p> <hr> <p>This is how I would do it with Gson:</p> <pre><code>public class UserAdapter implements JsonSerializer&lt;User&gt; { @Override public JsonElement serialize(User src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.id); } } GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(User.class, new UserAdapter()); Gson gson = builder.create(); String json = gson.toJson(myItem); System.out.println("JSON: "+json); </code></pre> <p>But I need to do it with Jackson now, since Gson doesn't have support for interfaces.</p>
7,168,386
11
2
null
2011-08-23 13:19:18.343 UTC
31
2022-01-08 07:16:34.367 UTC
2018-12-04 10:31:48.17 UTC
null
90,033
null
213,269
null
1
125
java|json|serialization|jackson
289,896
<p>As mentioned, @JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:</p> <pre><code>public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeNumber(id); } </code></pre> <p>Yet another possibility is to implement <code>JsonSerializable</code>, in which case no registration is needed.</p> <p>As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend <code>org.codehaus.jackson.map.ser.SerializerBase</code> as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).</p>
14,269,541
XSD Restriction on Attribute
<p>I think I have searched a lot about this but still no go.</p> <p>Will appreciate any help.</p> <p>I am trying to restrict an attribute for an element with empty content. "color" should have a restriction to only hold 3 digit or minLength=3 and maxLength=3. It should not have any content.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation=""&gt; &lt;product id="" name=""&gt; &lt;article id="1001"&gt; &lt;umbrella color="100"/&gt; &lt;umbrella color="101"/&gt; &lt;/article&gt; &lt;article id="1002"&gt; &lt;umbrella color="110"/&gt; &lt;/article&gt; &lt;/product&gt; &lt;/items&gt; </code></pre> <p>EDIT: I know how to do a XSD Restriction on a simpleType. But I don't how to combine it to one entity with a ComplexType.</p> <p>If you could provide a more detailed (or full) solution I would be happy.</p> <p>Btw, "color" is not limited to xs:integer. It is actually a xs:string.</p>
14,269,749
2
0
null
2013-01-11 00:05:18.54 UTC
7
2013-01-11 21:09:57.797 UTC
2013-01-11 07:05:34.527 UTC
null
1,888,562
null
1,888,562
null
1
26
attributes|xsd|restriction
46,017
<p>You can define your attribute similar to the following. This example uses a pattern to restrict the value, but you could also use min and max if that's more appropriate.</p> <pre><code>&lt;xs:attribute name="color"&gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:integer"&gt; &lt;xs:pattern value="[0-9][0-9][0-9]"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:attribute&gt; </code></pre> <p>Then in your element definition, you just use a <code>ref</code> to reference the defined attribute:</p> <pre><code>&lt;xs:attribute ref="color"/&gt; </code></pre> <p>UPDATE (in response to comment from OP):</p> <p>Here's what the entire schema might look like:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:attribute name="color"&gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:integer"&gt; &lt;xs:pattern value="[0-9][0-9][0-9]"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:attribute&gt; &lt;xs:attribute name="id"&gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:integer"&gt; &lt;xs:pattern value="[0-9][0-9][0-9][0-9]"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:attribute&gt; &lt;xs:attribute name="name" type="xs:string"/&gt; &lt;xs:complexType name="article_type"&gt; &lt;xs:attribute ref="color" use="required"/&gt; &lt;/xs:complexType&gt; &lt;xs:element name="article"&gt; &lt;xs:complexType&gt; &lt;xs:choice maxOccurs="unbounded" minOccurs="0"&gt; &lt;xs:element name="umbrella" type="article_type"/&gt; &lt;/xs:choice&gt; &lt;xs:attribute ref="id" use="required"/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="product"&gt; &lt;xs:complexType&gt; &lt;xs:choice maxOccurs="unbounded" minOccurs="0"&gt; &lt;xs:element ref="article"/&gt; &lt;/xs:choice&gt; &lt;xs:attribute ref="id" use="required"/&gt; &lt;xs:attribute ref="name"/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="items"&gt; &lt;xs:complexType&gt; &lt;xs:choice maxOccurs="unbounded" minOccurs="0"&gt; &lt;xs:element ref="product"/&gt; &lt;/xs:choice&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre>
14,343,812
Redirecting to URL in Flask
<p>I'm new to Python and Flask and I'm trying to do the equivalent of <code>Response.redirect</code> as in C# - ie: redirect to a specific URL - how do I go about this?</p> <p>Here is my code:</p> <pre><code>import os from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello World!' if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) </code></pre>
14,343,957
11
0
null
2013-01-15 17:55:45.957 UTC
55
2021-12-25 06:42:36.96 UTC
2019-05-14 13:24:01.597 UTC
null
1,709,587
null
1,426,157
null
1
325
python|redirect|flask
592,648
<p>You have to return a redirect:</p> <pre><code>import os from flask import Flask,redirect app = Flask(__name__) @app.route('/') def hello(): return redirect(&quot;http://www.example.com&quot;, code=302) if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) </code></pre> <p>See <a href="https://flask.palletsprojects.com/api/#flask.redirect" rel="noreferrer">the documentation on flask docs.</a> The default value for code is 302 so <code>code=302</code> can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).</p>
29,896,938
Unable to load the requested language file: language/en/form_validation_lang.php
<p>I am using codeigniter 2.1.4</p> <p>In that I am using <code>form_validation</code> library for form validation.</p> <p>When I try to run that function I get following error</p> <blockquote> <p>Unable to load the requested language file: language/en/form_validation_lang.php</p> </blockquote> <p>I have scanned all of the files. I am not using or calling this language file in any file still and I am getting this error.</p> <pre><code>function insert(){ $this-&gt;load-&gt;library('form_validation'); $this-&gt;form_validation-&gt;set_rules('username_field', 'username', 'required'); $this-&gt;form_validation-&gt;set_rules('firstname_field', 'firstname', 'required'); $this-&gt;form_validation-&gt;set_rules('lastname_field', 'lastname', 'required'); $this-&gt;form_validation-&gt;set_rules('email_field', 'email', 'required|valid_email|callback_isEmailExist'); if ($this-&gt;form_validation-&gt;run() == FALSE) { $this-&gt;create(); } } function isEmailExist($email) { $this-&gt;load-&gt;library('form_validation'); $is_exist = $this-&gt;users-&gt;isEmailExist($email); if ($is_exist) { $this-&gt;form_validation-&gt;set_message( 'isEmailExist', 'Email address is already exist.' ); return false; } else { return true; } } </code></pre> <p>What is the solution for this?</p>
29,948,588
3
10
null
2015-04-27 13:17:13.483 UTC
2
2016-04-03 16:08:25.31 UTC
2015-04-30 05:31:10.847 UTC
null
542,270
user3232286
null
null
1
12
php|codeigniter
44,288
<p>CI <code>form_validation</code> library uses language file for display error message.You are using <code>required</code> <code>valid_email</code> those error message is written inside <code>form_validation_lang.php</code>.</p> <p><code>form_validation</code> library loads the language file(<code>form_validation_lang.php</code>) itself whether you load or not.You can open the library file and look at the run function you will see a line <code>$this-&gt;CI-&gt;lang-&gt;load('form_validation');</code></p> <p>This file located either inside your <code>system/language/your_language/</code> or <code>application/language/your_language/</code>.</p> <p>That error message says you missed the file inside any of the folder.If you download the original CI files it should be inside <code>system/language/english/</code> folder.If you don't see the file <a href="http://www.codeigniter.com/download" rel="noreferrer">download</a> CI and restore the file there.</p>
44,734,028
member access within null pointer of type 'struct ListNode'
<pre><code>struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool hasCycle(ListNode *head) { if(head == NULL) return false; ListNode* walker = head; ListNode* runner = head; while(runner-&gt;next != NULL &amp;&amp; walker-&gt;next != NULL){ walker = walker-&gt;next; runner = runner-&gt;next-&gt;next; if(walker == runner) return true; } return false; } }; </code></pre> <p>I was practicing an interview code which seemed to be pretty simple. I have to return a bool that determines whether or not the singly-linked list has a cycle. I made two pointers walker which moves 1 step and runner which moves 2 steps every iteration. </p> <p>But then this code gave me an error:</p> <pre class="lang-none prettyprint-override"><code>Line 15: member access within null pointer of type 'struct ListNode' </code></pre> <p>What causes that error?</p>
44,734,070
5
4
null
2017-06-24 07:31:12.05 UTC
5
2021-07-25 13:27:31.503 UTC
2017-06-24 07:34:17.127 UTC
null
7,076,153
null
7,677,413
null
1
23
c++|data-structures|linked-list
64,926
<p>You only make sure that <code>runner-&gt;next</code> is not null, however after assignment</p> <p><code>runner = runner-&gt;next-&gt;next;</code></p> <p><code>runner</code> can become null.</p>
19,429,152
Check mysql connection in sequelize
<p>I have a very simple program in where I create a Sequelize instance and then I perform a raw query on a mysql database. The case is that when MySql is up and running there is no problem, I can perform the query with no problems. But when MySql is not running then the query doesn't emmit any error until the query timeout has reached and then it emmits a ETIMEOUT error. But that's not really what's happening. I expect the query to emit ENOTFOUND error or something like that if mysql is not running so I can manage the error and perform different actions if Mysql has gone down or Mysql is very busy and has a very large response time. What shoul'd I do to check if Mysql is up and running without having to wait the timeout exception.</p> <pre><code>sequelize = new Sequelize(db_name, db_user, db_pass, opts); sequelize.query('SELECT * FROM some_table').success(function(result) { console.log(result); }).error(function(err) { console.log(err); }); </code></pre>
31,115,934
4
2
null
2013-10-17 14:14:30.777 UTC
2
2020-10-20 08:38:36.993 UTC
null
null
null
null
2,588,593
null
1
31
mysql|node.js|sequelize.js
41,588
<p>As of latest version of <a href="https://www.npmjs.com/package/sequelize" rel="noreferrer">Sequelize</a> (i.e. <code>3.3.2</code>), <a href="http://docs.sequelizejs.com/en/latest/api/sequelize/#authenticate-promise" rel="noreferrer"><code>authenticate</code></a> can be used to check the connection:</p> <pre class="lang-js prettyprint-override"><code>var sequelize = new Sequelize(&quot;db&quot;, &quot;user&quot;, &quot;pass&quot;); sequelize.authenticate().then(function(errors) { console.log(errors) }); </code></pre> <p><code>authenticate</code> simply runs <code>SELECT 1+1 AS result</code> query to check the db connection.</p> <p><strong>UPDATE</strong>:</p> <p>Errors by the <a href="http://docs.sequelizejs.com/manual/installation/getting-started.html#test-the-connection" rel="noreferrer">newest API</a> need to be handled in <code>catch</code>:</p> <pre class="lang-js prettyprint-override"><code>sequelize .authenticate() .then(() =&gt; { console.log('Connection has been established successfully.'); }) .catch(err =&gt; { console.error('Unable to connect to the database:', err); }); </code></pre> <p><strong>UPDATE 2</strong>:</p> <p>I haven't tested this, but its only logical that the same thing can be reached with <code>async/await</code>:</p> <pre class="lang-js prettyprint-override"><code>try { await sequelize.authenticate() } catch (err) { console.error('Unable to connect to the database:', err) } </code></pre>
192,398
Select XML nodes as rows
<p>I am selecting from a table that has an XML column using T-SQL. I would like to select a certain type of node and have a row created for each one.</p> <p>For instance, suppose I am selecting from a <em>people</em> table. This table has an XML column for <em>addresses</em>. The XML is formated similar to the following:</p> <pre><code>&lt;address&gt; &lt;street&gt;Street 1&lt;/street&gt; &lt;city&gt;City 1&lt;/city&gt; &lt;state&gt;State 1&lt;/state&gt; &lt;zipcode&gt;Zip Code 1&lt;/zipcode&gt; &lt;/address&gt; &lt;address&gt; &lt;street&gt;Street 2&lt;/street&gt; &lt;city&gt;City 2&lt;/city&gt; &lt;state&gt;State 2&lt;/state&gt; &lt;zipcode&gt;Zip Code 2&lt;/zipcode&gt; &lt;/address&gt; </code></pre> <p>How can I get results like this:</p> <p><strong>Name</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>City</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>State</strong></p> <p>Joe Baker&nbsp;&nbsp;&nbsp;Seattle&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WA</p> <p>Joe Baker&nbsp;&nbsp;&nbsp;Tacoma&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WA</p> <p>Fred Jones&nbsp;&nbsp;Vancouver&nbsp;BC</p>
193,625
5
0
null
2008-10-10 17:37:03.25 UTC
6
2015-10-26 20:46:10.35 UTC
null
null
null
Bj&#248;rn
3,645
null
1
15
sql|xml|tsql|xpath
61,308
<p>Here is your solution: </p> <pre><code>/* TEST TABLE */ DECLARE @PEOPLE AS TABLE ([Name] VARCHAR(20), [Address] XML ) INSERT INTO @PEOPLE SELECT 'Joel', '&lt;address&gt; &lt;street&gt;Street 1&lt;/street&gt; &lt;city&gt;City 1&lt;/city&gt; &lt;state&gt;State 1&lt;/state&gt; &lt;zipcode&gt;Zip Code 1&lt;/zipcode&gt; &lt;/address&gt; &lt;address&gt; &lt;street&gt;Street 2&lt;/street&gt; &lt;city&gt;City 2&lt;/city&gt; &lt;state&gt;State 2&lt;/state&gt; &lt;zipcode&gt;Zip Code 2&lt;/zipcode&gt; &lt;/address&gt;' UNION ALL SELECT 'Kim', '&lt;address&gt; &lt;street&gt;Street 3&lt;/street&gt; &lt;city&gt;City 3&lt;/city&gt; &lt;state&gt;State 3&lt;/state&gt; &lt;zipcode&gt;Zip Code 3&lt;/zipcode&gt; &lt;/address&gt;' SELECT * FROM @PEOPLE -- BUILD XML DECLARE @x XML SELECT @x = ( SELECT [Name] , [Address].query(' for $a in //address return &lt;address street="{$a/street}" city="{$a/city}" state="{$a/state}" zipcode="{$a/zipcode}" /&gt; ') FROM @PEOPLE AS people FOR XML AUTO ) -- RESULTS SELECT [Name] = T.Item.value('../@Name', 'varchar(20)'), street = T.Item.value('@street' , 'varchar(20)'), city = T.Item.value('@city' , 'varchar(20)'), state = T.Item.value('@state' , 'varchar(20)'), zipcode = T.Item.value('@zipcode', 'varchar(20)') FROM @x.nodes('//people/address') AS T(Item) /* OUTPUT*/ Name | street | city | state | zipcode ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Joel | Street 1 | City 1 | State 1 | Zip Code 1 Joel | Street 2 | City 2 | State 2 | Zip Code 2 Kim | Street 3 | City 3 | State 3 | Zip Code 3 </code></pre>
817,801
time since JVM started
<p>Is there a way to find out the time since the JVM started?</p> <p>Of course, other than starting a timer somewhere near the beginning of <code>main</code>, because in my scenario I am writing library code and the requirement that something be called immediately after startup is a too burdensome.</p>
817,835
5
0
null
2009-05-03 19:32:07.267 UTC
14
2021-03-05 13:19:08.243 UTC
2012-03-12 05:12:59.023 UTC
null
538,613
null
63,051
null
1
65
java|time|jvm
24,965
<p>Use this snippet:</p> <pre><code>long jvmUpTime = ManagementFactory.getRuntimeMXBean().getUptime(); </code></pre> <p>or:</p> <pre><code>long jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime(); </code></pre> <p>This is the <strong>correct</strong> way of retrieving JVM up-time.</p> <p>For more info see <a href="https://docs.oracle.com/en/java/javase/15/docs/api/java.management/java/lang/management/RuntimeMXBean.html" rel="noreferrer">RuntimeMXBean</a></p>
144,167
How to format Oracle SQL text-only select output
<p>I am using Oracle SQL (in SQLDeveloper, so I don't have access to SQLPLUS commands such as COLUMN) to execute a query that looks something like this:</p> <pre><code>select assigner_staff_id as staff_id, active_flag, assign_date, complete_date, mod_date from work where assigner_staff_id = '2096'; </code></pre> <p>The results it give me look something like this:</p> <pre> STAFF_ID ACTIVE_FLAG ASSIGN_DATE COMPLETE_DATE MOD_DATE ---------------------- ----------- ------------------------- ------------------------- ------------------------- 2096 F 25-SEP-08 27-SEP-08 27-SEP-08 02.27.30.642959000 PM 2096 F 25-SEP-08 25-SEP-08 25-SEP-08 01.41.02.517321000 AM 2 rows selected </pre> <p>This can very easily produce a very wide and unwieldy textual report when I'm trying to paste the results as a nicely formatted quick-n-dirty text block into an e-mail or problem report, etc. What's the best way to get rid of all tha extra white space in the output columns when I'm using just plain-vanilla Oracle SQL? So far all my web searches haven't turned up much, as all the web search results are showing me how to do it using formatting commands like COLUMN in SQLPLUS (which I don't have).</p>
144,187
6
0
null
2008-09-27 18:07:54.35 UTC
2
2013-11-20 14:43:52.113 UTC
null
null
null
Ogre Psalm33
13,140
null
1
5
sql|oracle|formatting
56,138
<p>What are you using to get the results? The output you pasted looks like it's coming from SQL*PLUS. It may be that whatever tool you are using to generate the results has some method of modifying the output. </p> <p>By default Oracle outputs columns based upon the width of the title or the width of the column data which ever is wider. </p> <p>If you want make columns smaller you will need to either rename them or convert them to text and use substr() to make the defaults smaller. </p> <pre><code>select substr(assigner_staff_id, 8) as staff_id, active_flag as Flag, to_char(assign_date, 'DD/MM/YY'), to_char(complete_date, 'DD/MM/YY'), mod_date from work where assigner_staff_id = '2096'; </code></pre>
447,408
Why do nullable bools not allow if(nullable) but do allow if(nullable == true)?
<p>This code compiles:</p> <pre><code>private static void Main(string[] args) { bool? fred = true; if (fred == true) Console.WriteLine("fred is true"); else if (fred == false) Console.WriteLine("fred is false"); else Console.WriteLine("fred is null"); } </code></pre> <p>This code does <em>not</em> compile.</p> <pre><code>private static void Main(string[] args) { bool? fred = true; if (fred) Console.WriteLine("fred is true"); else if (!fred) Console.WriteLine("fred is false"); else Console.WriteLine("fred is null"); } </code></pre> <p>I thought <code>if(booleanExpression == true)</code> was supposed to be a redundancy. Why isn't it in this case?</p>
447,429
6
0
null
2009-01-15 16:17:33.653 UTC
10
2019-08-11 09:33:18.23 UTC
2019-08-11 09:33:18.23 UTC
null
3,800,096
Quarrelsome
1,143
null
1
36
c#|.net|nullable
6,593
<p>There's no implicit conversion from <code>Nullable&lt;bool&gt;</code> to <code>bool</code>. There <em>is</em> an implicit conversion from <code>bool</code> to <code>Nullable&lt;bool&gt;</code> and that's what happens (in language terms) to each of the bool constants in the first version. The <code>bool operator==(Nullable&lt;bool&gt;, Nullable&lt;bool&gt;</code> operator is then applied. (This isn't quite the same as other lifted operators - the result is just <code>bool</code>, not <code>Nullable&lt;bool&gt;</code>.)</p> <p>In other words, the expression 'fred == false' is of type <code>bool</code>, whereas the expression 'fred' is of type <code>Nullable&lt;bool&gt;</code> hence you can't use it as the "if" expression.</p> <p>EDIT: To answer the comments, there's never an implicit conversion from <code>Nullable&lt;T&gt;</code> to <code>T</code> and for good reason - implicit conversions shouldn't throw exceptions, and unless you want <code>null</code> to be implicitly converted to <code>default(T)</code> there's not a lot else that could be done.</p> <p>Also, if there <em>were</em> implicit conversions both ways round, an expression like "nullable + nonNullable" would be very confusing (for types that support +, like <code>int</code>). Both +(T?, T?) and +(T, T) would be available, depending on which operand were converted - but the results could be very different!</p> <p>I'm 100% behind the decision to only have an explicit conversion from <code>Nullable&lt;T&gt;</code> to <code>T</code>.</p>
124,880
Is it possible to prevent stack allocation of an object and only allow it to be instantiated with 'new'?
<p>Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?</p>
124,904
6
1
null
2008-09-24 01:27:01.263 UTC
12
2018-08-22 17:14:07.45 UTC
2014-08-25 13:59:17.39 UTC
Kevin
1,556,198
Joseph
null
null
1
55
c++|c++-faq
13,632
<p>One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:</p> <pre><code>class Foo { public: ~Foo(); static Foo* createFoo() { return new Foo(); } private: Foo(); Foo(const Foo&amp;); Foo&amp; operator=(const Foo&amp;); }; </code></pre>
52,759,608
What is Task.RunSynchronously for?
<p>I just wonder what's the method for? In what kind of scenario I can use this method. </p> <p>My initial thought is <code>RunSynchronously</code> is for calling an async method and running that synchronously without causing a deadlock issue like what <code>.wait()</code> does.</p> <p>However, according to <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.runsynchronously" rel="noreferrer">MSDN</a>, </p> <blockquote> <p>Ordinarily, tasks are executed asynchronously on a thread pool thread and do not block the calling thread. Tasks executed by calling the RunSynchronously() method are associated with the current TaskScheduler and are run on the calling thread. If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the schedule, and the calling thread will block until the task has completed execution</p> </blockquote> <p>Why need a TaskScheduler here, if the task going to run on the calling thread? </p>
52,760,220
2
8
null
2018-10-11 12:02:22.9 UTC
8
2021-06-01 07:55:59.547 UTC
2018-10-11 12:16:11.367 UTC
user10489223
null
null
407,183
null
1
36
c#|multithreading|asynchronous
21,959
<p><code>RunSynchronously</code> delegates the decision of when to start the task to the current task scheduler (or the one passed as argument).</p> <p>I am not sure why it is there (maybe for internal or legacy use), but it is hard to think of a useful use case in the current versions of <strong>.NET</strong>. <a href="https://stackoverflow.com/questions/52759608/what-is-task-runsynchronously-for#comment92443509_52759608">@Fabjan has a possible explanation in his comment</a> to the question.</p> <p><code>RunSynchronously</code> asks the scheduler to run it synchronously but then the scheduler could very well ignore the hint and run it in a thread pool thread and your current thread will synchronously block until it is completed.</p> <p>The scheduler does not have to run it on the current thread and does not have to run it immediately although I think it is what will happen on common schedulers (ThreadPoolTaskScheduler and common UI schedulers).</p> <p><code>RunSynchronously</code> will also throw an exception if the task has already been started or is completed/faulted (this means you will not be able to use it on async methods).</p> <p>This code may clarify the different behaviour:</p> <p><code>Wait</code> and <code>Result</code> don't run the task at all, they just wait for the task completion on the current thread and block it until the completion so if we want to compare, we can compare <code>Start</code> and <code>Wait</code> to <code>RunSynchronously</code>:</p> <pre><code>class Scheduler : TaskScheduler { protected override void QueueTask(Task task) =&gt; Console.WriteLine("QueueTask"); protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Console.WriteLine("TryExecuteTaskInline"); return false; } protected override IEnumerable&lt;Task&gt; GetScheduledTasks() =&gt; throw new NotImplementedException(); } static class Program { static void Main() { var taskToStart = new Task(() =&gt; { }); var taskToRunSynchronously = new Task(() =&gt; { }); taskToStart.Start(new Scheduler()); taskToRunSynchronously.RunSynchronously(new Scheduler()); } } </code></pre> <p>If you try and comment Start or <code>RunSynchronously</code> and run the code, you will see that <code>Start</code> tries and queue the task to the scheduler while <code>RunSynchronously</code> will try and execute it inline and if failing (return false), it will just queue it.</p>
21,092,415
Force C++ structure to pack tightly
<p>I am attempting to read in a binary file. The problem is that the creator of the file took no time to properly align data structures to their natural boundaries and everything is packed tight. This makes it difficult to read the data using C++ structs.</p> <p>Is there a way to force a <code>struct</code> to be packed tight?</p> <p>Example:</p> <pre><code>struct { short a; int b; } </code></pre> <p>The above structure is 8 bytes: 2 for <code>short a</code>, 2 for padding, 4 for <code>int b</code>. However, on disk, the data is only 6 bytes (not having the 2 bytes of padding for alignment)</p> <p>Please be aware the actual data structures are thousands of bytes and many fields, including a couple arrays, so I would prefer not to read each field individually.</p>
21,092,552
2
7
null
2014-01-13 13:23:42.053 UTC
17
2016-09-08 16:55:09.277 UTC
2016-09-08 16:55:09.277 UTC
null
562,697
null
562,697
null
1
49
c++|struct
65,237
<p>If you're using GCC, you can do <code>struct __attribute__ ((packed)) { short a; int b; }</code></p> <p>On VC++ you can do <code>#pragma pack(1)</code>. This option is <a href="https://gcc.gnu.org/onlinedocs/gcc/Structure-Layout-Pragmas.html" rel="noreferrer">also supported by GCC</a>.</p> <pre><code>#pragma pack(push, 1) struct { short a; int b; } #pragma pack(pop) </code></pre> <p>Other compilers may have options to do a tight packing of the structure with no padding.</p>
17,891,113
How to export complete Google Analytics historical data?
<p>I was given a few days to export all the historical data from a Google Analytics account before access will be shutoff. Important to note that you cannot migrate historical data (at the time of this post) from one Google Analytics account to another. I would specifically like to program this for Excel or better yet get guidance on what others have used.</p> <p>I have never done this before so wanted to reach out and see what others have used? Wanted to avoid the Google Analytics Data Export API unless there was no other option. There is about 5 years of data for a very active site.</p> <h2>Update</h2> <p>I decided moving the information manually was the best route to go at that time. There may be new solutions, see links below.</p> <p>Related references that may be helpful to others:</p> <p><a href="https://support.google.com/accounts/answer/1109839?hl=en" rel="noreferrer">Account merge and data move options</a><br> <a href="https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts?csw=1#organization" rel="noreferrer">Developers.Google.Com</a> - Google Dev Guide<br> <a href="https://stackoverflow.com/questions/6278914/can-we-move-google-analytics-data-to-other-account">Can we move Google Analytics data to other account?</a><br> <a href="https://stackoverflow.com/questions/6859777/exporting-data-from-google-analytics">Exporting Data from Google Analytics</a> - Trying to avoid the API<br> <a href="http://www.google.com/analytics/apps/" rel="noreferrer">Google Analytics Application Gallery</a> - Apps list, anyone use these?</p>
17,911,199
3
0
null
2013-07-26 21:12:51.307 UTC
8
2019-04-08 21:47:49.047 UTC
2019-04-08 21:47:49.047 UTC
null
472,495
null
337,529
null
1
35
google-analytics|export-to-excel|export-to-csv
62,846
<p>You can't (not with the free version of GA in any case). You can export aggregated reports (with up to 50 000 rows for standard reports or 200 000 rows for ad-hoc (not pre-calculated) reports via the API either by scripting yourself or using a tool like Next Analytics (the only programm from the Application Gallery I have used myself). But with 5 years of data you will at some point hit the courtesy limits for the Google API. And I'm not sure how helpful the exports are when you cannot get at the raw data.</p> <p>Data Liberation from google may contanin updated info about this topic <a href="https://sites.google.com/a/dataliberation.org/www/google/analytics" rel="noreferrer">https://sites.google.com/a/dataliberation.org/www/google/analytics</a></p>
23,438,918
How to have a common header shared by all webpages in AngularJS?
<p>I would like to have a header.html which defines how the header for all my web pages will look like. How can I insert this header.html into the other web pages at the top? </p> <p>There may be better methods around to achieve a common header to be shared around. As I still consider myself a newbie to html (but not to programming), I am open to better suggestions.</p> <p>Thank you.</p> <p>EDIT: Helpful replies have mentioned using PHP. However, I am using AngularJS as front-end and my PHP backend is simply a pure REST server. My preference is to do it the AngularJS way and not the PHP way.</p>
23,438,974
3
3
null
2014-05-03 00:37:49.27 UTC
9
2017-11-26 11:07:27.647 UTC
2014-05-03 00:53:17.97 UTC
null
1,709,088
null
1,709,088
null
1
18
html|angularjs
42,487
<p>An AngularJS solution would look like this:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en" ng-app="myApp"&gt; &lt;head&gt; &lt;script src='angular.js'&gt;&lt;/script&gt; &lt;script src='main.js'&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div ng-controller="HeaderCtrl"&gt; &lt;div ng-include src="header.url"&gt;&lt;/div&gt; &lt;script type="text/ng-template" id="header.html"&gt;&lt;/script&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>main.js:</p> <pre><code>var myApp = angular.module('myApp', []); function HeaderCtrl($scope) { $scope.header = {name: "header.html", url: "header.html"}; } </code></pre> <p>header.html:</p> <pre><code>&lt;p&gt; Header content goes here &lt;/p&gt; </code></pre> <p>The reason I did not simply advise a solution such as: <code>&lt;div ng-include="'header.html'"&gt;</code> is to avoid any delay in loading the header. For more information have a look at <a href="https://stackoverflow.com/questions/20555136/angularjs-point-ng-include-to-a-partial-that-contains-a-script-directive">angularjs - Point ng-include to a partial that contains a script directive</a>. </p> <p>Alternatively a jQuery would like this.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="jquery.js"&gt;&lt;/script&gt; &lt;script&gt; $(function(){ $("#headerContent").load("header.html"); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="headerContent"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Finally a PHP solution would look like this:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include('header.html'); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Best of luck learning!</p>
1,399,395
How do the new string types work in Delphi 2009/2010?
<p>I have to convert a large legacy application to Delphi 2009 which uses strings, AnsiStrings, WideStrings and UTF8 data all over the place and I have a hard time to understand how the new string types work and how they should be used.</p> <p>The application fully supported Unicode using TntUnicodeControls and there are 3rd party DLLs which require strings in specific encodings, mostly UTF8 and UTF16, making the conversion task not as trivial as one would suspect.</p> <p>I especially have problems with the C DLL calls and choosing the right type. I also get the impression that there are many implicit string conversions happening, because one of the DLL seems to always receive UTF-8 encoded strings, no matter how the Delphi string is encoded.</p> <p>Can someone please provide a short overview about the new Delphi 2009 string types UnicodeString and RawByteString, perhaps some usage hints and possible pitfalls when converting a pre 2009 application?</p>
1,400,413
5
1
null
2009-09-09 12:27:44.707 UTC
11
2011-02-28 10:48:34.387 UTC
2009-09-09 12:52:25.423 UTC
null
23,368
null
23,368
null
1
7
delphi|unicode|string|delphi-2009
7,692
<p>Watch my <a href="http://conferences.embarcadero.com/coderage/sessions" rel="noreferrer">CodeRage 4</a> talk on "Using Unicode and Other Encodings in your Programs" this friday, or wait until the replay of it is available online.</p> <p>I'm going to cover some encodings and explain about the string format.</p> <p>The slides will be available shortly (I'll try to get them online today) and contain a lot of references to stuff you should read on the internet (but I must admit I forgot the link to Joel on Unicode that eed3si9n posted).</p> <p>Will edit this answer today with the uploads and the links.</p> <hr> <p><em>Edit:</em></p> <p>If you have a small sample where you can show that your C/C++ DLL receives the strings UTF8 encoded, but thought they should be encoded otherwise, please post it (mail me; almost anything at the pluimers dot com gets to me, especially if you use my first name before the at sign).</p> <p>Session materials can be <a href="http://wiert.wordpress.com/2009/09/09/coderage-4-session-materials-available-for-download/" rel="noreferrer">downloaded</a> now, including the "Using Unicode and Other Encodings in your Programs" session.</p> <p>These are links from that session:</p> <p>Read these:</p> <ol> <li>Marco Cantu, Whitepaper “<a href="http://etnaweb04.embarcadero.com/resources/technical_papers/Delphi-and-Unicode_Marco-Cantu.pdf" rel="noreferrer">Delphi and Unicode</a>”</li> <li>Marco Cantu, Presentation “<a href="http://it-republik.de/konferenzen/delphi_live/material/DelpiLive09_Cantu_Unicode.pdf" rel="noreferrer">Delphi and Unicode</a>”</li> <li>Nick Hodges, Whitepaper “<a href="http://etnaweb04.embarcadero.com/resources/technical_papers/Delphi%20in%20a%20Unicode%20World_updated.pdf" rel="noreferrer">Delphi in a Unicode World</a>”</li> </ol> <p>Relevant on-line help topics:</p> <ol> <li><a href="http://edn.embarcadero.com/article/38869" rel="noreferrer">What's New in Delphi and C++Builder 2009</a></li> <li>String Types: <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/stringtypes_xml.html" rel="noreferrer">Base: ShortString, AnsiString, WideString, UnicodeString</a></li> <li>String Types: <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/unicodeinide_xml.html" rel="noreferrer">Unicode (including internal memory layouts of the string types)</a></li> <li>String Types: <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/enablingunicode_xml.html" rel="noreferrer">Enabling for Unicode</a></li> <li>String Types: <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/System_RawByteString.html" rel="noreferrer">RawByteString (AnsiString with CodePage $ffff)</a></li> <li>String Types: <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/System_UTF8String.html" rel="noreferrer">UTF8String (AnsiString with CodePage 65001)</a></li> <li>String &lt;-> PChar conversions: <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/stringdependencies_xml.html" rel="noreferrer">PChar fundamentals</a></li> <li>String &lt;-> PChar conversions: <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/passingalocalvariableasapchar_xml.html" rel="noreferrer">Returning a PChar Local Variable</a></li> <li>String &lt;-> PChar conversions: <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/returningapcharlocalvariable_xml.html" rel="noreferrer">Passing a Local Variable as a PChar</a></li> </ol> <p>Hope this gets you going. If not, mail me and I'll try to extend the answer here.</p>
2,180,326
JQuery event model and preventing duplicate handlers
<p>Once again I want to load a page which contains its own script into a div using $("divid").load(...). The problem I face is related to events. Let's say we trigger("monkey") from the parent page and on the loaded page we bind("monkey") and just do an alert("monkey bound"). If the same load method is called multiple times, the bind is called multiple times. Now I could just unbind it before I bind it, or check the number of handlers before the bind and then not bind it to prevent this. Neither option is scalable as what if I later want to bind to that trigger in another "sub page" (a page loaded into a div).</p> <p>What I ideally want to do then is check if the handler I am about to add already exists, but I still WANT to use anonymous handlers... (asking a bit much with that last request I think). Currently I have a workaround by using pre-defined/named methods and then checking this before the bind.</p> <pre><code>// Found this on StackOverflow function getFunctionName(fn) { var rgx = /^function\s+([^\(\s]+)/ var matches = rgx.exec(fn.toString()); return matches ? matches[1] : "(anonymous)" } function HandlerExists(triggerName, handlerName) { exists = false; if ($(document).data('events') !== undefined) { var event = $(document).data('events')[triggerName]; if(event !== undefined) { $.each(event, function(i, handler) { alert(handlerName); if (getFunctionName(handler) == handlerName) { exists = true; } }); } } return exists; } </code></pre> <p>This is a pretty crude way of going about it I feel, but appears to work. I just do the following before the bind as follows:</p> <pre><code>if (!HandlerExists("test", "theMethod")) { $(document).bind("test", theMethod); } </code></pre> <p>Does anyone have a more elegant solution? for instance, is there any way to check a particular script is loaded? so I could use getScript() to load the js from the child page on first load, and then simply not load it on subsequent loads (and just fire a trigger which would be handled by he preexisting js)..</p>
13,475,122
5
1
null
2010-02-01 21:49:49.233 UTC
10
2015-03-11 16:52:58.917 UTC
null
null
null
null
228,665
null
1
35
jquery|events|triggers|bind|javascript
46,356
<p><strong>Prevent duplicate binding using jQuery's event namespace</strong></p> <p>There are actually a couple different ways of preventing duplicate. One is just passing the original handler in the unbind, BUT if it is a copy and not in the same space in memory it will not unbind, the other popular way (using namespaces) is a more certain way of achieving this.</p> <p>This is a common issue with events. So I'll explain a little on the jQuery events and using namespace to prevent duplicate bindings. </p> <p><br/><br/> <strong>ANSWER:</strong> (Short and straight to the point)</p> <hr> <pre><code>// bind handler normally $('#myElement').bind('myEvent', myMainHandler); // bind another using namespace $('#myElement').bind('myEvent.myNamespace', myUniqueHandler); // unbind the unique and rebind the unique $('#myElement').unbind('myEvent.myNamespace').bind('myEvent.myNamespace', myUniqueHandler); $('#myElement').bind('myEvent.myNamespace', myUniqueHandler); // trigger event $('#myElement').trigger('myEvent'); // output myMainHandler() // fires once! myUniqueHandler() // fires once! </code></pre> <p><br/><br/> <strong>EXAMPLE OF ANSWER:</strong> (Full detailed explanation)</p> <hr> <p>First let's create an example element to bind to. We will use a button with the id of #button. Then make 3 functions that can and will be used as the handlers to get bound to the event:</p> <p>function exampleOne() we will bind with a click. function exampleTwo() we will bind to a namespace of the click. function exampleThree() we will bind to a namepsace of the click, but unbind and bind multiple times without ever removing the other binds which prevents duplicating binding while not removing any other of the bound methods.</p> <p><strong>Example Start:</strong> (Create element to bind to and some methods to be our handlers)</p> <pre><code>&lt;button id="button"&gt;click me!&lt;/button&gt; // create the example methods for our handlers function exampleOne(){ alert('One fired!'); } function exampleTwo(){ alert('Two fired!'); } function exampleThree(){ alert('Three fired!'); } </code></pre> <p><strong>Bind exampleOne to click:</strong></p> <pre><code>$('#button').bind('click', exampleOne); // bind example one to "click" </code></pre> <p>Now if user clicks the button or call $('#button').trigger('click') you will get the alert "One Fired!";</p> <p><strong>Bind exampleTwo to a namespace of click:</strong> "name is arbitrary, we will use myNamespace2"</p> <pre><code>$('#button').bind('click.myNamespace2', exampleTwo); </code></pre> <p>The cool thing about this is, we can trigger the "click" which will fire exampleOne() AND exampleTwo(), or we can trigger "click.myNamespace2" which will only fire exampleTwo()</p> <p><strong>Bind exampleThree to a namespace of click:</strong> "again, name is arbitrary as long as it's different from exampleTwo's namespace, we will use myNamespace3"</p> <pre><code>$('#button').bind('click.myNamespace3', exampleThree); </code></pre> <p>Now if 'click' get's triggered ALL three example methods will get fired, or we can target a specific namespace.</p> <p><strong>PUT IT ALL TOGETHER TO PREVENT DUPLICATE</strong></p> <p>If we were to continue to bind exampleThree() like so:</p> <pre><code>$('#button').bind('click.myNamespace3', exampleThree); $('#button').bind('click.myNamespace3', exampleThree); $('#button').bind('click.myNamespace3', exampleThree); </code></pre> <p>They would get fired three times because each time you call bind you add it to the event array. So, really simple. Just unbind for that namespace prior to binding, like so:</p> <pre><code>$('#button').unbind('click.myNamespace3').bind('click.myNamespace3', exampleThree); $('#button').bind('click.myNamespace3', exampleThree); $('#button').unbind('click.myNamespace3').bind('click.myNamespace3', exampleThree); $('#button').bind('click.myNamespace3', exampleThree); $('#button').unbind('click.myNamespace3').bind('click.myNamespace3', exampleThree); $('#button').bind('click.myNamespace3', exampleThree); </code></pre> <p>If the click function is triggered, exampleOne(), exampleTwo(), and exampleThree() only get fired once.</p> <p><strong>To wrap it all together in a simple function:</strong></p> <pre><code>var myClickBinding = function(jqEle, handler, namespace){ if(namespace == undefined){ jqEle.bind('click', handler); }else{ jqEle.unbind('click.'+namespace).bind('click.'+namespace, handler); } } </code></pre> <p><strong>Summary:</strong></p> <p>jQuery event namespaces allow for binding to main event but also allow child namespaces to be created and cleared without effecting sibling namespaces or parent ones which with very minimal creative thinking allows prevention of duplicate bindings. </p> <p>For further explanation: <a href="http://api.jquery.com/event.namespace/" rel="noreferrer">http://api.jquery.com/event.namespace/</a></p>
1,977,475
How do I get the About box to appear in C#?
<p>I have an About box in my C# project using Microsoft's Visual C# 2008 Express Edition named AboutBox1. I have made it look how I want it in the design view, but how do I make it appear when the About link in the Help menu is clicked?</p> <p>This codes makes an About box appear, but it looks blank. It's not the one I designed.</p> <pre><code> private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutBox1 box = new AboutBox1(); box.ShowDialog(); } </code></pre> <p>Any thoughts or suggestions would be appreciated. Thanks.</p>
1,977,534
6
1
null
2009-12-29 23:03:24.913 UTC
4
2020-04-20 04:36:10.703 UTC
null
null
null
null
214,296
null
1
13
c#|about-box
42,682
<p>Got it.</p> <p>The about box is driven off of assembly properties for your project.</p> <p>Go to Project -> 'ProjectName' Properties -> Assembly Information.</p> <p>You set all of the information there.</p> <p>If you try to set the information in the Property Explorer it will simply be over written at run time by what ever is in this window.</p> <p>Cheers, Mike</p>
1,530,284
Multiple SQL Server connection strings in app.config file
<p>I'm interested in displaying in a Windows Forms app a list of N radio buttons for the user to choose a target database server. I would like to add the SQL Server connection strings in the app.config file, so they are read by the app at runtime and rendered in the windows form as radio buttons. </p> <p>At first I thought of using a delimiter to separate the connections</p> <pre><code> &lt;appSettings&gt; &lt;add key="ConnectionString" value="connection1|user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30|connection2|user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/&gt; &lt;/appSettings&gt; </code></pre> <p>And then split the key value pairs.</p> <p>Is it possible to do this in a different way?</p>
1,530,361
6
0
null
2009-10-07 08:31:51.75 UTC
3
2017-11-15 16:18:31.6 UTC
2009-10-07 08:41:30.92 UTC
null
13,302
null
71,560
null
1
15
c#|sql-server|connection-string|app-config
52,993
<p>To find all defined connection strings from your app.config, use the <code>ConfigurationManager</code> (from System.Configuration).</p> <p>It has an enumeration: <code>ConfigurationManager.ConnectionStrings</code> which contains all entries in your <code>&lt;connectionStrings&gt;</code>.</p> <p>You can loop over it with this code:</p> <pre><code>foreach(ConnectionStringSettings css in ConfigurationManager.ConnectionStrings) { string name = css.Name; string connString = css.ConnectionString; string provider = css.ProviderName; } </code></pre> <p>The <code>Name</code> is just the symbolic name you give your connection string - it can be anything, really.</p> <p>The <code>ConnectionString</code> is the connection string itself.</p> <p>The <code>ProviderName</code> is the name of the provider for the connection, e.g. <code>System.Data.SqlClient</code> for SQL Server (and others for other database system). If you omit the <code>providerName=</code> attribute from your connection string in config, it defaults to SQL Server (System.Data.SqlClient).</p> <p>Marc</p>
2,277,405
JSON stringify missing from jQuery 1.4.1?
<p>Apparently jQuery has the ability to decode a given object or string into a JSON object. However, I have a JS object that I need to POST back to the server and I find no utility in jQuery that wraps the JSON.stringify() function. That function is found in Chrome, Safari 4, FF3.6, and IE8 but is not found in earlier browsers. I can use it natively in the browsers that support it, but otherwise am forced to fall back to using Crockford's JSON scripts.</p> <p>Is there some built-in with jQuery that handles JSON encoding and decoding that takes the place of the Crockford scripts?</p>
2,277,417
6
2
null
2010-02-17 00:13:11.33 UTC
10
2019-12-31 15:24:59.453 UTC
null
null
null
null
68,788
null
1
74
jquery|json|encode|decode
64,829
<p>You might want to check this out: <a href="http://www.json.org/js.html" rel="noreferrer">http://www.json.org/js.html</a></p>
2,288,814
PHP forums - how to cope with unread discussions / topics / posts
<p>I know this question has been asked here a couple of times, but none of the answers had pleased me. This is because almost all of them involve a huge read / write process related with the database, which I'd like to avoid at all cost. </p> <p>About unread discussions / topics / posts, there's a lot to think of. I don't know how do forum systems like <a href="http://en.wikipedia.org/wiki/MyBB" rel="noreferrer">MyBB</a>, <a href="http://en.wikipedia.org/wiki/VBulletin" rel="noreferrer">vBulletin</a>, <a href="http://en.wikipedia.org/wiki/Invision_Power_Board" rel="noreferrer">Invision Power Board</a>, <a href="http://vanillaforums.org/" rel="noreferrer">Vanilla</a>, <a href="http://en.wikipedia.org/wiki/PhpBB" rel="noreferrer">phpBB</a>, etc., cope with that issue, so I'd like to read from you guys your experience with that. I know that using a database table just for that is the simplest way, but that would involve a huge read / write when the community has over 10,000 members and 1000 new topics every month. It's hard, but there should be a way to avoid the server's overloading.</p> <p>So, what do you find as the best practices for this issue, as well as how other forum systems cope with it?</p>
2,308,500
7
0
null
2010-02-18 13:15:48.66 UTC
18
2015-06-12 19:23:57.56 UTC
2010-12-05 21:24:28.503 UTC
null
63,550
null
168,177
null
1
28
php|mysql|forum
7,650
<p>There isn't a lot of choices.</p> <ol> <li><p>mark every reader thread by each user. </p> <ul> <li>Disadvantages: a lot of rows in very active forums</li> <li>Advantages: Every user knows with post has read or not.</li> </ul></li> <li><p>mark every unread thread by each user. <br /></p> <ul> <li>Disadvantages: a lot of space with "unreaded" rows if there is inactivity of a lot of users</li> <li>Solutions: add a lifetime timestamp and delete old records with a cron</li> <li>Advantages: Every user knows with post has read or not.</li> </ul></li> <li><p>use timestamps to determine if show it as unread or not.</p> <ul> <li>Disadvantages: The users don't know with are the real unread threads, the marks only show the "new trheads" since the last login</li> <li>Advantage: Save space</li> </ul></li> </ol> <p>The other alternative is mixing solutions, that is,</p> <p>1 and 3) show thread as "unread" if they aren't older than X days and there isn't a row marked as readed for the user. The "read" rows can be deleted when they are X day older without affect anything.</p> <p>Advantages</p> <ul> <li>less spaced used to determine unread threads</li> </ul> <p>Disadvantages</p> <ul> <li>create a cron that keeps the system clean</li> <li>Users don't know if they read threads olders than x days.</li> </ul> <p>Advantages</p> <ul> <li>Every user knows which "new posts" has read or not.</li> </ul>
2,024,435
How to pass ctor args in Activator.CreateInstance or use IL?
<p>I need a performance enhanced Activator.CreateInstance() and came across <a href="http://mironabramson.com/blog/post/2008/08/Fast-version-of-the-ActivatorCreateInstance-method-using-IL.aspx" rel="noreferrer">this article</a> by Miron Abramson that uses a factory to create the instance in IL and then cache it. (I've included code below from Miron Abramson's site in case it somehow disappears). I'm new to IL Emit code and anything beyond Activator.CreateInstance() for instantiating a class and any help would be much appreciative.</p> <p>My problem is that I need to create an instance of an object that takes a ctor with a parameter. I see there is a way to pass in the Type of the parameter, but is there a way to pass in the value of the ctor parameter as well?</p> <p>If possible, I would like to use a method similar to <code>CreateObjectFactory&lt;T&gt;(params object[] constructorParams)</code> as some objects I want to instantiate may have more than 1 ctor param.</p> <pre><code> // Source: http://mironabramson.com/blog/post/2008/08/Fast-version-of-the-ActivatorCreateInstance-method-using-IL.aspx public static class FastObjectFactory { private static readonly Hashtable creatorCache = Hashtable.Synchronized(new Hashtable()); private readonly static Type coType = typeof(CreateObject); public delegate object CreateObject(); /// /// Create an object that will used as a 'factory' to the specified type T /// public static CreateObject CreateObjectFactory() where T : class { Type t = typeof(T); FastObjectFactory.CreateObject c = creatorCache[t] as FastObjectFactory.CreateObject; if (c == null) { lock (creatorCache.SyncRoot) { c = creatorCache[t] as FastObjectFactory.CreateObject; if (c != null) { return c; } DynamicMethod dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + t.Name, typeof(object), null, t); ILGenerator ilGen = dynMethod.GetILGenerator(); ilGen.Emit(OpCodes.Newobj, t.GetConstructor(Type.EmptyTypes)); ilGen.Emit(OpCodes.Ret); c = (CreateObject)dynMethod.CreateDelegate(coType); creatorCache.Add(t, c); } } return c; } } </code></pre> <p><a href="http://mironabramson.com/blog/post/2008/08/Fast-version-of-the-ActivatorCreateInstance-method-using-IL.aspx" rel="noreferrer">Update to Miron's code from commentor on his post 2010-01-11</a></p> <pre><code>public static class FastObjectFactory2&lt;T&gt; where T : class, new() { public static Func&lt;T&gt; CreateObject { get; private set; } static FastObjectFactory2() { Type objType = typeof(T); var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + objType.Name, objType, null, objType); ILGenerator ilGen = dynMethod.GetILGenerator(); ilGen.Emit(OpCodes.Newobj, objType.GetConstructor(Type.EmptyTypes)); ilGen.Emit(OpCodes.Ret); CreateObject = (Func&lt;T&gt;) dynMethod.CreateDelegate(typeof(Func&lt;T&gt;)); } } </code></pre>
2,045,313
8
1
null
2010-01-07 23:20:37.593 UTC
19
2011-07-25 23:55:16.253 UTC
2010-07-21 20:52:02.557 UTC
null
79,057
null
79,057
null
1
12
.net|performance|parameters|il|createinstance
25,295
<p>I'm putting this up as the so far best performant object creation factory so far using the current (2010-01-11) answers, according to my tests. I did notice that using cache works best when iterations are somewhere below 99,999. If you are going to load more than 99,999 it is best to not use cache. Because this could be the case I've created something that would allow you to use cache or not. My current project will sometimes load millions of records and at other times only load one. Anyways, I'm putting this out there to see what your thoughts are. Note that the code below is for ctor's that have 1 arg, one would have to create a similar factory for more than 1 arg ctor.</p> <pre><code> // code updated 2010-06-01 // class that creates comment objects public class CreatesSomeObject { // method that creates a comment object public void CreateComment() { // Method 1 (without cache) Comment comment1 = ObjectFactoryFactory&ltComment, ObjectId&gt .CreateObject.Invoke(new ObjectId()); // Method 2 (with cache) Comment comment2 = ObjectFactoryFactory&ltComment, ObjectId&gt .CreateObjectWithCache.Invoke(new ObjectId()); // Method 3 (without helper factory ObjectFactoryFactory) Comment comment3 = ObjectFactory&ltComment, ObjectId&gt .CreateObject.Invoke(new ObjectId()); } } // This is optional class. Just helps in creating objects when // a cache is needed or not needed. public static class ObjectFactoryFactory&ltT, P1&gt where T : class { static Hashtable cache = Hashtable.Synchronized(new Hashtable()); public static Func&ltP1, T&gt CreateObject { get { return ObjectFactory&ltT, P1&gt.CreateObject; } } public static Func&ltP1, T&gt CreateObjectWithCache { get { return ObjectFactory&ltT, P1&gt.UseCache(cache); } } } // Main object creation factory class. public static class ObjectFactory&ltT, P1&gt where T : class { static Func&ltP1, T&gt _createObject; public static Func&ltP1, T&gt CreateObject { get { if (_createObject != null) return _createObject; _createObject = CreateDelegate(); return _createObject; } } static Func&ltP1, T&gt CreateDelegate() { Type objType = typeof(T); Type[] types = new[] { typeof(P1) }; var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + objType.Name, objType, types, objType); ILGenerator ilGen = dynMethod.GetILGenerator(); // if need more than 1 arg add another Ldarg_x // you'll also need to add proper generics and // CreateDelegate signatures ilGen.Emit(OpCodes.Ldarg_0); ilGen.Emit(OpCodes.Newobj, objType.GetConstructor(types)); ilGen.Emit(OpCodes.Ret); return (Func&ltP1, T&gt)dynMethod.CreateDelegate(typeof(Func&ltP1, T&gt)); } public static Func&ltP1, T&gt UseCache(Hashtable cache) { Type t = typeof(T); Func&ltP1, T&gt c = cache[t] as Func&ltP1, T&gt;; if (c == null) { lock (cache.SyncRoot) { c = cache[t] as Func&ltP1, T&gt;; if (c != null) { return c; } c = CreateDelegate(); cache.Add(t, c); } } return c; } } </code></pre>
2,246,017
Using Google Translate in C#
<p>I have to translate some text with Google's translate service. All code I've found doesn't work. I think because they have changed their service. If someone has working code, I would be very glad.</p>
2,246,032
8
0
null
2010-02-11 16:46:27.607 UTC
28
2018-11-21 06:58:17.867 UTC
2015-08-27 19:07:11.467 UTC
null
64,046
null
87,152
null
1
57
c#|google-translate
149,211
<p>See if this works for you</p> <p><strong>google-language-api-for-dotnet</strong> </p> <p><a href="http://code.google.com/p/google-language-api-for-dotnet/" rel="noreferrer">http://code.google.com/p/google-language-api-for-dotnet/</a></p> <p><strong>Google Translator</strong></p> <p><a href="http://www.codeproject.com/KB/IP/GoogleTranslator.aspx" rel="noreferrer">http://www.codeproject.com/KB/IP/GoogleTranslator.aspx</a></p> <p><strong>Translate your text using Google Api's</strong></p> <p><a href="http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx" rel="noreferrer">http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx</a></p> <p><strong>Calling Google Ajax Language API for Translation and Language Detection from C#</strong></p> <p><a href="http://www.esotericdelights.com/post/2008/11/Calling-Google-Ajax-Language-API-for-Translation-and-Language-Detection-from-C.aspx" rel="noreferrer">http://www.esotericdelights.com/post/2008/11/Calling-Google-Ajax-Language-API-for-Translation-and-Language-Detection-from-C.aspx</a></p> <p><strong>Translation Web Service in C#</strong></p> <p><a href="http://www.codeproject.com/KB/cpp/translation.aspx" rel="noreferrer">http://www.codeproject.com/KB/cpp/translation.aspx</a></p> <p>Using Google's Translation API from .NET</p> <p><a href="http://www.reimers.dk/blogs/jacob_reimers_weblog/archive/2008/06/18/using-google-s-translation-api-from-net.aspx" rel="noreferrer">http://www.reimers.dk/blogs/jacob_reimers_weblog/archive/2008/06/18/using-google-s-translation-api-from-net.aspx</a></p>
2,050,961
Is "argv[0] = name-of-executable" an accepted standard or just a common convention?
<p>When passing argument to <code>main()</code> in a C or C++ application, will <code>argv[0]</code> always be the name of the executable? Or is this just a common convention and not guaranteed to be true 100% of the time? </p>
2,051,031
8
2
null
2010-01-12 17:31:51.22 UTC
33
2018-11-23 16:03:41.307 UTC
2012-02-11 21:57:05.88 UTC
null
168,868
null
203,690
null
1
117
c++|c|standards|argv
79,870
<p>Guesswork (even educated guesswork) is fun but you really need to go to the standards documents to be sure. For example, ISO C11 states (my emphasis):</p> <blockquote> <p>If the value of <code>argc</code> is greater than zero, the string pointed to by <code>argv[0]</code> <strong><em>represents</em></strong> the program name; <code>argv[0][0]</code> shall be the null character if the program name is not available from the host environment.</p> </blockquote> <p>So no, it's only the program name if that name is <em>available.</em> And it <em>"represents"</em> the program name, not necessarily <em>is</em> the program name. The section before that states:</p> <blockquote> <p>If the value of <code>argc</code> is greater than zero, the array members <code>argv[0]</code> through <code>argv[argc-1]</code> inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup.</p> </blockquote> <p>This is unchanged from C99, the previous standard, and means that even the <em>values</em> are not dictated by the standard - it's up to the implementation entirely.</p> <p>This means that the program name can be empty if the host environment <em>doesn't</em> provide it, and anything else if the host environment <em>does</em> provide it, provided that "anything else" somehow represents the program name. In my more sadistic moments, I would consider translating it into Swahili, running it through a substitution cipher then storing it in reverse byte order :-).</p> <p>However, implementation-defined <em>does</em> have a specific meaning in the ISO standards - the implementation must document how it works. So even UNIX, which can put anything it likes into <code>argv[0]</code> with the <code>exec</code> family of calls, has to (and does) document it.</p>
1,691,575
What ORM for .net should I use?
<p>I'm relatively new to .NET and have being using Linq2Sql for a almost a year, but it lacks some of the features I'm looking for now. </p> <p>I'm going to start a new project in which I want to use an ORM with the following characteristics:</p> <ul> <li>It has to be very productive, I don't want to be dealing with the access layer to save or retrieve objects from or to the database, but it should allows me to easily tweak any object before actually commit it to the database; also it should allows me to work easily with a changing database schema</li> <li>It should allows me to extend the objects mapped from the database, for example to add virtual attributes to them (virtual columns to a table)</li> <li>It has to be (at least almost) database agnostic, it should allows me to work with different databases in a transparent way</li> <li>It has to have not so much configuration or must be based on conventions to make it work</li> <li>It should allows me to work with Linq</li> </ul> <p>So, do you know any ORM that I could use? Thank you for your help.</p> <p><strong>EDIT</strong> I know that an option is to use NHibernate. This appears as the facto standard for enterprise level applications, but also it seems that is not very productive because its deep learning curve. In other way, I have read in some other post here in SO that it doesn't integrate well with Linq. Is all of that true?</p>
1,691,638
9
6
null
2009-11-07 01:28:08.043 UTC
11
2017-05-03 14:44:17.457 UTC
2010-05-04 10:41:48.51 UTC
null
32,173
null
32,173
null
1
15
c#|.net|orm
6,017
<p>Perhaps your best bet is using <a href="http://nhibernate.org" rel="noreferrer">NHibernate</a>. It's arguably the best &quot;industry standard&quot; when it comes to both commercial and open source ORMs. It has been around a long while to become really stable, is used in many enterprise companies, is based on the even better known Hibernate (java), but has fully been rewritten to make the best use of .NET features.</p> <h3>NHibernate drawbacks</h3> <p>This sounds like I'm an advocate of NHibernate. Perhaps I am. But NHibernate has a drawback: it has a steep learning curve and getting used to the many possibilities and choosing the right or &quot;best&quot; practice for your situation can be daunting, even for experienced developers. But that's the prize to pay for an enterprise-level ORM that's capable of virtually anything.</p> <h3>NHibernate with FluentNHibernate rocks</h3> <p>Many of these drawbacks and setup problems vaporize the minute you start using <a href="http://fluentnhibernate.org" rel="noreferrer">Fluent Nhibernate</a>, personally, I hardly do without it anymore as it removes all the tediousness of NHibernate at once (almost).</p> <p>It makes working with NHibernate a breeze: just write your entities as POCOs and load them fully automatically to create your database, the associations etc (or don't create the schema if it's there already). Configure your database using the Fluent syntax. A very simple setup can look as basic as this:</p> <pre><code>// part of a default abstract setup class I use public ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database( MsSqlConfiguration.MsSql2008 .ConnectionString(c =&gt; c.Server(this.ServerName) .Database(this.DatabaseName) .Username(this.Username) .Password(this.Password) ) ) .Mappings(m =&gt; m.AutoMappings.Add(AutoMap.AssemblyOf&lt;User&gt;() // loads all POCOse .Where(t =&gt; t.Namespace == this.Namespace)) // here go the associations and constraints, // (or you can annotate them, or add them later) ) .ExposeConfiguration(CreateOrUpdateSchema) .BuildSessionFactory(); } // example of an entity // It _can_ be as simple as this, which generates the schema, the mappings ets // but you still have the flexibility to expand and to map using more complex // scenarios. It is not limited to just tables, you can map views, stored procedures // create triggers, associations, unique keys, constraints etc. // The Fluent docs help you step by step public class User { public virtual int Id { get; private set; } // autogens PK public virtual string Name { get; set; } // augogens Name col public virtual byte[] Picture { get; set; } // autogens Picture BLOB col public virtual List&lt;UserSettings&gt; Settings { get; set; } // autogens to many-to-one } public class UserSettings { public virtual int Id { get; private set: } // PK again public virtual int UserId { get; set; } // autogens FK public virtual User { get; set; } // autogens OO-mapping to User table } </code></pre> <p>which takes all POCO entities and automatically maps them, creates the configuration for the ORM and builds the schema in the database, provided the user has sufficient rights. One very powerful ability of Fluent (and NH to a lesser extend) is to update a database schema when you make any changes.</p> <h3>Other aids to NHibernate</h3> <p>Also on the upside: many auto generation tools exist (including the open source <a href="http://www.mygenerationsoftware.com/" rel="noreferrer">MyGeneration</a>) that can take your DB schema(s) from a simple ODBC or other connection and turn them into the correct entity classes, associations and HBM configuration files. Many of these tools are (partially) graphical design aids.</p> <h3>Use S#arp for enforcing MVC + NH + NUnit best practices</h3> <p>Make sure to read <a href="http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx" rel="noreferrer">NHibernate best practices</a>. It brings generics and DAO to the next level. You can also skip to the chase and dive deep with <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2008/04/21/asp-net-mvc-best-practices-with-nhibernate-and-spring-net.aspx" rel="noreferrer">S#arp</a> (<a href="http://www.codeplex.com/SharpArchitecture" rel="noreferrer">download</a>), which is a framework that imposes all these best practices and adds NUnit to the mixture.</p> <p>Before I start using a new technology I usually want it well covered. NHibernate and Hibernate don't come short here. Many books explain (N)Hibernate from starter to professional, white papers are abundant and tool documentation is meanwhile rather excellent.</p> <h3>About LINQ and NH</h3> <p>LINQ and NHibernate have always gone well together through all types of <code>ICollection&lt;&gt;</code> which are used in the many-to-X mappings and other associations, but requires the data to be retrieved first which requires a good design (the cache helps here), otherwise it'll perform badly. This has been considered a sore point of NH ever since LINQ came about.</p> <p>Luckily, there's now a new kid in town: <a href="http://ayende.com/Blog/archive/2009/07/26/nhibernate-linq-1.0-released.aspx" rel="noreferrer">NHibernate-LINQ</a>, which maps LINQ queries to <code>ICriteria</code> queries prior to submitting. ICriteria queries are well cached and this combination with LINQ is both very powerful and very performant. NH-LINQ is now part of the standard distribution.</p> <h3>Disclaimer</h3> <p>I've used NHibernate for a almost decade (first Java, later .NET). I've flirted with other ORM's both commercial and open source, but in the end always returned to NH (unless company policy demanded different, but that was rare). This story may sound a bit biased but the space here is too short to go into excruciating detail about how NHibernate compares to other technologies.</p> <p>It's very well possible that other ORM's better fit your need, especially if you never plan to use it in complex multi-database, multi-db-server or hard-to-map-to-OO legacy situations. For me, NH shines because it doesn't limit me in any which way and supports full roundtrip engineering, but your choice might turn out different if features of lighter ORM's that are discussed here weigh heavier for you.</p> <p><em><strong>Update:</strong> added code sample<br /> <strong>Update:</strong> expanded code sample, fixed typos and wording<br /> <strong>Update:</strong> little chapters, added LINQ part, added Disclaimer part</em></p>
1,920,059
Maven throws "java.lang.OutOfMemoryError"
<p>I'm compiling an open source project with "mvn install" but ended up with <code>java.lang.OutOfMemoryError: Java heap space</code>. I tried to execute <code>java -Xmx256m</code> but the output was java synopsis which indicated it's an invalid command.</p> <p>I'm using <code>jdk1.5.0_08</code>, any ideas why this is happening?</p> <p>Thanks,</p>
1,920,071
9
1
null
2009-12-17 07:30:33.02 UTC
9
2018-04-27 06:50:10.837 UTC
2009-12-17 07:36:33.777 UTC
null
18,393
null
124,858
null
1
37
java|maven-2|out-of-memory
58,003
<p>Set the environment variable:</p> <pre><code>MAVEN_OPTS="-Xmx512m" </code></pre>
8,580,591
Export SQL to Excel
<p>How can i export my data from SQL server 2008 into Excel 2010 or later ?</p> <p>i have tried on SQL way:</p> <pre><code>sp_configure 'show advanced options', 0; GO RECONFIGURE; GO sp_configure 'Ad Hoc Distributed Queries', 0; GO RECONFIGURE; GO INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\testing.xls;Extended Properties=EXCEL 12.0;HDR=YES', 'SELECT NO_ORDRE, Date FROM [Sheet1$]') SELECT [NO_ORDRE], GETDATE() FROM ORDRE GO </code></pre> <p>Unfortuntely i receive error: The OLE DB provider 'Microsoft.Jet.OLEDB.4.0' can not be used for distributed queries because the provider is configured to run in STA mode.</p> <p>and then i tried on C# way:</p> <pre><code> public class ExportToExcel { private Excel.Application app; private Excel.Workbook workbook; private Excel.Worksheet previousWorksheet; // private Excel.Range workSheet_range; private string folder; public ExportToExcel(string folder) { this.folder = folder; this.app = null; this.workbook = null; this.previousWorksheet = null; // this.workSheet_range = null; createDoc(); } private void createDoc() { try { app = new Excel.Application(); app.Visible = false; workbook = app.Workbooks.Add(1); } catch (Exception excThrown) { throw new Exception(excThrown.Message); } finally { } } public void shutDown() { try { workbook = null; app.Quit(); } catch (Exception excThrown) { throw new Exception(excThrown.Message); } finally { } } public void ExportTable(string query, string sheetName) { SqlDataReader myReader = null; try { using (var connectionWrapper = new Connexion()) { var connectedConnection = connectionWrapper.GetConnected(); Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Excel.XlSheetType.xlWorksheet); worksheet.Name = sheetName; previousWorksheet = worksheet; SqlCommand myCommand = new SqlCommand(query, connectionWrapper.conn); myReader = myCommand.ExecuteReader(); int columnCount = myReader.FieldCount; for (int n = 0; n &lt; columnCount; n++) { //Console.Write(myReader.GetName(n) + "\t"); createHeaders(worksheet, 1, n + 1, myReader.GetName(n)); } int rowCounter = 2; while (myReader.Read()) { for (int n = 0; n &lt; columnCount; n++) { //Console.WriteLine(); //Console.Write(myReader[myReader.GetName(n)].ToString() + "\t"); addData(worksheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString()); } rowCounter++; } } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { if (myReader != null &amp;&amp; !myReader.IsClosed) { myReader.Close(); } myReader = null; } } public void createHeaders(Excel.Worksheet worksheet, int row, int col, string htext) { worksheet.Cells[row, col] = htext; } public void addData(Excel.Worksheet worksheet, int row, int col, string data) { worksheet.Cells[row, col] = data; } public void SaveWorkbook() { String folderPath = "C:\\My Files\\" + this.folder; if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); } string fileNameBase = "db"; String fileName = fileNameBase; string ext = ".xlsx"; int counter = 1; while (System.IO.File.Exists(folderPath + fileName + ext)) { fileName = fileNameBase + counter; counter++; } fileName = fileName + ext; string filePath = folderPath + fileName; try { workbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } </code></pre> <p>unfortunately i got error: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).</p> <p>Any idea how can i export SQL to Excel ?</p>
8,580,650
10
2
null
2011-12-20 19:04:35.207 UTC
6
2020-03-13 15:28:25.01 UTC
2011-12-20 19:25:30.33 UTC
null
351,982
null
609,511
null
1
10
c#|sql-server-2008|excel
74,968
<p>Your best bet might be to just write it out to a CSV. Excel registers itself as the file handler for CSV files, so it will open in excel by default.</p> <p>For example:</p> <pre><code>private void SQLToCSV(string query, string Filename) { SqlConnection conn = new SqlConnection(connection); conn.Open(); SqlCommand cmd = new SqlCommand(query, conn); SqlDataReader dr = cmd.ExecuteReader(); using (System.IO.StreamWriter fs = new System.IO.StreamWriter(Filename)) { // Loop through the fields and add headers for (int i = 0; i &lt; dr.FieldCount; i++) { string name = dr.GetName(i); if (name.Contains(",")) name = "\"" + name + "\""; fs.Write(name + ","); } fs.WriteLine(); // Loop through the rows and output the data while (dr.Read()) { for (int i = 0; i &lt; dr.FieldCount; i++) { string value = dr[i].ToString(); if (value.Contains(",")) value = "\"" + value + "\""; fs.Write(value + ","); } fs.WriteLine(); } fs.Close(); } } </code></pre>
17,717,600
Confusion between C++ and OpenGL matrix order (row-major vs column-major)
<p>I'm getting thoroughly confused over matrix definitions. I have a matrix class, which holds a <code>float[16]</code> which I assumed is row-major, based on the following observations:</p> <pre><code>float matrixA[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; float matrixB[4][4] = { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 }, { 12, 13, 14, 15 } }; </code></pre> <p><code>matrixA</code> and <code>matrixB</code> both have the same linear layout in memory (i.e. all numbers are in order). According to <a href="http://en.wikipedia.org/wiki/Row-major_order">http://en.wikipedia.org/wiki/Row-major_order</a> this indicates a row-major layout.</p> <pre><code>matrixA[0] == matrixB[0][0]; matrixA[3] == matrixB[0][3]; matrixA[4] == matrixB[1][0]; matrixA[7] == matrixB[1][3]; </code></pre> <p>Therefore, <code>matrixB[0]</code> = row 0, <code>matrixB[1]</code> = row 1, etc. Again, this indicates row-major layout.</p> <p>My problem / confusion comes when I create a translation matrix which looks like: </p> <pre><code>1, 0, 0, transX 0, 1, 0, transY 0, 0, 1, transZ 0, 0, 0, 1 </code></pre> <p>Which is laid out in memory as, <code>{ 1, 0, 0, transX, 0, 1, 0, transY, 0, 0, 1, transZ, 0, 0, 0, 1 }</code>.</p> <p>Then when I call <a href="http://www.opengl.org/sdk/docs/man3/xhtml/glUniform.xml">glUniformMatrix4fv</a>, I need to set the transpose flag to GL_FALSE, indicating that it's column-major, else transforms such as translate / scale etc don't get applied correctly:</p> <blockquote> <p>If transpose is GL_FALSE, each matrix is assumed to be supplied in column major order. If transpose is GL_TRUE, each matrix is assumed to be supplied in row major order. </p> </blockquote> <p>Why does my matrix, which appears to be row-major, need to be passed to OpenGL as column-major?</p>
17,718,408
4
5
null
2013-07-18 07:46:54.017 UTC
58
2022-06-17 16:32:12.753 UTC
2013-07-18 08:23:49.39 UTC
null
986
null
986
null
1
92
c++|math|opengl|matrix
69,299
<p><strong>matrix notation used in opengl documentation does not describe in-memory layout for OpenGL matrices</strong></p> <p>If think it'll be easier if you drop/forget about the entire &quot;row/column-major&quot; thing. That's because in addition to row/column major, the programmer can also decide how he would want to lay out the matrix in the memory (whether adjacent elements form rows or columns), in addition to the notation, which adds to confusion.</p> <p>OpenGL matrices have <a href="http://www.opengl.org/archives/resources/faq/technical/transformations.htm" rel="noreferrer">same memory layout as directx matrices</a>.</p> <pre><code>x.x x.y x.z 0 y.x y.y y.z 0 z.x z.y z.z 0 p.x p.y p.z 1 </code></pre> <p>or</p> <pre><code>{ x.x x.y x.z 0 y.x y.y y.z 0 z.x z.y z.z 0 p.x p.y p.z 1 } </code></pre> <ul> <li><p>x, y, z are 3-component vectors describing the matrix coordinate system (local coordinate system within relative to the global coordinate system).</p> </li> <li><p>p is a 3-component vector describing the origin of matrix coordinate system.</p> </li> </ul> <p>Which means that the translation matrix should be laid out in memory like this:</p> <pre><code>{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, transX, transY, transZ, 1 }. </code></pre> <p>Leave it at that, and the rest should be easy.</p> <p>---citation from old opengl faq--</p> <hr /> <blockquote> <p>9.005 Are OpenGL matrices column-major or row-major?</p> <p>For programming purposes, OpenGL matrices are 16-value arrays with base vectors laid out contiguously in memory. The translation components occupy the 13th, 14th, and 15th elements of the 16-element matrix, where indices are numbered from 1 to 16 as described in section 2.11.2 of the OpenGL 2.1 Specification.</p> <p>Column-major versus row-major is purely a notational convention. Note that post-multiplying with column-major matrices produces the same result as pre-multiplying with row-major matrices. The OpenGL Specification and the OpenGL Reference Manual both use column-major notation. You can use any notation, as long as it's clearly stated.</p> <p>Sadly, the use of column-major format in the spec and blue book has resulted in endless confusion in the OpenGL programming community. Column-major notation suggests that matrices are not laid out in memory as a programmer would expect.</p> </blockquote> <hr /> <p><strong>I'm going to update this 9 years old answer.</strong></p> <p>A mathematical matrix is defined as <code>m x n</code> matrix. Where <code>m</code> is a number of <em>rows</em> and <code>n</code> is number of <em>columns</em>. For the sake of completeness, rows are horizontals, columns are vertical. When denoting a matrix element in mathematical notation <code>Mij</code>, the first element (<code>i</code>) is a row index, the second one (<code>j</code>) is a column index. When two matrices are multiplied, i.e. <code>A(m x n) * B(m1 x n1)</code>, the resulting matrix has number of rows from the first argument(<code>A</code>), and number of columns of the second(<code>B</code>), and number of columns of the first argument (<code>A</code>) must match number of rows of the second (<code>B</code>). so <code>n == m1</code>. Clear so far, yes?</p> <p>Now, regarding in-memory layout. You can store matrix two ways. Row-major and column-major. Row-major means that effectively you have rows laid out one after another, linearly. So, elements go from left to right, row after row. Kinda like english text. Column-major means that effectively you have <em>columns</em> laid out one after another, linearly. So elements start at top left, and go from top to bottom.</p> <p>Example:</p> <pre><code>//matrix |a11 a12 a13| |a21 a22 a23| |a31 a32 a33| //row-major [a11 a12 a13 a21 a22 a23 a31 a32 a33] //column-major [a11 a21 a31 a12 a22 a32 a13 a23 a33] </code></pre> <p>Now, here's the fun part!</p> <p>There are two ways to store 3d transformation in a matrix. As I mentioned before, a matrix in 3d essentially stores coordinate system basis vectors and position. So, you can store those vectors in rows or in columns of a matrix. When they're stored as columns, you multiply a matrix with a column vector. Like this.</p> <pre><code>//convention #1 |vx.x vy.x vz.x pos.x| |p.x| |res.x| |vx.y vy.y vz.y pos.y| |p.y| |res.y| |vx.z vy.z vz.z pos.z| x |p.z| = |res.z| | 0 0 0 1| | 1| |res.w| </code></pre> <p>However, you can also store those vectors as rows, and then you'll be multiplying a row vector with a matrix:</p> <pre><code>//convention #2 (uncommon) | vx.x vx.y vx.z 0| | vy.x vy.y vy.z 0| |p.x p.y p.z 1| x | vz.x vz.y vz.z 0| = |res.x res.y res.z res.w| |pos.x pos.y pos.z 1| </code></pre> <p>So. Convention #1 often appears in mathematical texts. Convention #2 appeared in DirectX sdk at some point. Both are valid.</p> <p>And in regards of the question, if you're using convention #1, then your matrices are column-major. And if you're using convention #2, then they're row major. However, memory layout is the same in both cases</p> <pre><code>[vx.x vx.y vx.z 0 vy.x vy.y vy.z 0 vz.x vz.y vz.z 0 pos.x pos.y pos.z 1] </code></pre> <p>Which is why I said it is easier to memorize which element is which, 9 years ago.</p>
17,911,188
Is it possible to define a class constant inside an Enum?
<p>Python 3.4 introduces a new module <a href="http://docs.python.org/3.4/library/enum.html"><code>enum</code></a>, which adds an <a href="http://en.wikipedia.org/wiki/Enumerated_type">enumerated type</a> to the language. The documentation for <code>enum.Enum</code> provides <a href="http://docs.python.org/3.4/library/enum.html#planet">an example</a> to demonstrate how it can be extended:</p> <pre><code>&gt;&gt;&gt; class Planet(Enum): ... MERCURY = (3.303e+23, 2.4397e6) ... VENUS = (4.869e+24, 6.0518e6) ... EARTH = (5.976e+24, 6.37814e6) ... MARS = (6.421e+23, 3.3972e6) ... JUPITER = (1.9e+27, 7.1492e7) ... SATURN = (5.688e+26, 6.0268e7) ... URANUS = (8.686e+25, 2.5559e7) ... NEPTUNE = (1.024e+26, 2.4746e7) ... def __init__(self, mass, radius): ... self.mass = mass # in kilograms ... self.radius = radius # in meters ... @property ... def surface_gravity(self): ... # universal gravitational constant (m3 kg-1 s-2) ... G = 6.67300E-11 ... return G * self.mass / (self.radius * self.radius) ... &gt;&gt;&gt; Planet.EARTH.value (5.976e+24, 6378140.0) &gt;&gt;&gt; Planet.EARTH.surface_gravity 9.802652743337129 </code></pre> <p>This example also demonstrates a problem with <code>Enum</code>: in the <code>surface_gravity()</code> property method, a constant <code>G</code> is defined which would normally be defined at class level - but attempting to do so inside an <code>Enum</code> would simply add it as one of the members of the enum, so instead it's been defined inside the method.</p> <p>If the class wanted to use this constant in other methods, it'd have to be defined there as well, which obviously isn't ideal.</p> <p>Is there any way to define a class constant inside an <code>Enum</code>, or some workaround to achieve the same effect?</p>
18,035,135
6
3
null
2013-07-28 18:05:21.987 UTC
16
2022-09-02 13:41:26.157 UTC
2015-04-28 13:01:24.413 UTC
null
1,014,938
null
1,014,938
null
1
56
python|python-3.x|enums|constants|class-constants
13,723
<p>This is advanced behavior which will not be needed in 90+% of the enumerations created.</p> <p>According to the docs:</p> <blockquote> <p>The rules for what is allowed are as follows: <code>_sunder_</code> names (starting and ending with a single underscore) are reserved by enum and cannot be used; all other attributes defined within an enumeration will become members of this enumeration, with the exception of <code>__dunder__</code> names and <code>descriptors</code> (methods are also descriptors).</p> </blockquote> <p>So if you want a class constant you have several choices:</p> <ul> <li>create it in <code>__init__</code></li> <li>add it after the class has been created</li> <li>use a mixin</li> <li>create your own <code>descriptor</code></li> </ul> <p>Creating the constant in <code>__init__</code> and adding it after the class has been created both suffer from not having all the class info gathered in one place.</p> <p>Mixins can certainly be used when appropriate (<a href="https://stackoverflow.com/a/18075283/1733117">see dnozay's answer for a good example</a>), but that case can also be simplified by having a base <code>Enum</code> class with the actual constants built in.</p> <p>First, the constant that will be used in the examples below:</p> <pre><code>class Constant: # use Constant(object) if in Python 2 def __init__(self, value): self.value = value def __get__(self, *args): return self.value def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.value) </code></pre> <p>And the single-use Enum example:</p> <pre><code>from enum import Enum class Planet(Enum): MERCURY = (3.303e+23, 2.4397e6) VENUS = (4.869e+24, 6.0518e6) EARTH = (5.976e+24, 6.37814e6) MARS = (6.421e+23, 3.3972e6) JUPITER = (1.9e+27, 7.1492e7) SATURN = (5.688e+26, 6.0268e7) URANUS = (8.686e+25, 2.5559e7) NEPTUNE = (1.024e+26, 2.4746e7) # universal gravitational constant G = Constant(6.67300E-11) def __init__(self, mass, radius): self.mass = mass # in kilograms self.radius = radius # in meters @property def surface_gravity(self): return self.G * self.mass / (self.radius * self.radius) print(Planet.__dict__['G']) # Constant(6.673e-11) print(Planet.G) # 6.673e-11 print(Planet.NEPTUNE.G) # 6.673e-11 print(Planet.SATURN.surface_gravity) # 10.44978014597121 </code></pre> <p>And, finally, the multi-use Enum example:</p> <pre><code>from enum import Enum class AstronomicalObject(Enum): # universal gravitational constant G = Constant(6.67300E-11) def __init__(self, mass, radius): self.mass = mass self.radius = radius @property def surface_gravity(self): return self.G * self.mass / (self.radius * self.radius) class Planet(AstronomicalObject): MERCURY = (3.303e+23, 2.4397e6) VENUS = (4.869e+24, 6.0518e6) EARTH = (5.976e+24, 6.37814e6) MARS = (6.421e+23, 3.3972e6) JUPITER = (1.9e+27, 7.1492e7) SATURN = (5.688e+26, 6.0268e7) URANUS = (8.686e+25, 2.5559e7) NEPTUNE = (1.024e+26, 2.4746e7) class Asteroid(AstronomicalObject): CERES = (9.4e+20 , 4.75e+5) PALLAS = (2.068e+20, 2.72e+5) JUNOS = (2.82e+19, 2.29e+5) VESTA = (2.632e+20 ,2.62e+5 Planet.MERCURY.surface_gravity # 3.7030267229659395 Asteroid.CERES.surface_gravity # 0.27801085872576176 </code></pre> <hr> <p><strong>Note</strong>:</p> <p>The <code>Constant</code> <code>G</code> really isn't. One could rebind <code>G</code> to something else:</p> <pre><code>Planet.G = 1 </code></pre> <p>If you really need it to be constant (aka not rebindable), then use the <a href="https://pypi.python.org/pypi/aenum" rel="noreferrer">new aenum library</a> [1] which will block attempts to reassign <code>constant</code>s as well as <code>Enum</code> members.</p> <hr> <p><sup>1</sup> Disclosure: I am the author of the <a href="https://docs.python.org/3/library/enum.html" rel="noreferrer">Python stdlib <code>Enum</code></a>, the <a href="https://pypi.python.org/pypi/enum34" rel="noreferrer"><code>enum34</code> backport</a>, and the <a href="https://pypi.python.org/pypi/aenum" rel="noreferrer">Advanced Enumeration (<code>aenum</code>)</a> library.</p>
6,481,788
Format of timesince filter
<p>Is there a way to use the <code>{{date|timesince}}</code> filter, but instead of having two adjacent units, only display one?</p> <p>For example, my template is currently displaying "18 hours, 16 minutes". How would I get it to display "18 hours"? (Rounding is not a concern here.) Thank you.</p>
6,481,920
4
0
null
2011-06-26 02:29:25.17 UTC
10
2022-06-16 16:21:07.177 UTC
null
null
null
null
651,174
null
1
15
django|django-templates
10,380
<p>I can't think of a simple builtin way to do this. Here's a custom filter I've sometimes found useful:</p> <pre><code>from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def upto(value, delimiter=None): return value.split(delimiter)[0] upto.is_safe = True </code></pre> <p>Then you could just do</p> <pre><code>{{ date|timesince|upto:',' }} </code></pre>
18,392,804
Python logging - determine level number from name
<p>Python logging levels can be registered using <code>logging.addLevelName</code>. Is there a method to obtain the Python logging number from a level name?</p>
18,392,839
2
1
null
2013-08-23 00:21:39.737 UTC
null
2022-01-01 16:29:27.61 UTC
null
null
null
null
165,495
null
1
34
python
8,515
<p>After you call <code>addLevelName</code>, the resulting level is treated exactly the same as all of the standard ones:</p> <pre><code>&gt;&gt;&gt; import logging &gt;&gt;&gt; logging.getLevelName(10) 'DEBUG' &gt;&gt;&gt; logging.getLevelName('DEBUG') 10 &gt;&gt;&gt; logging.addLevelName(15, 'DEBUGGISH') &gt;&gt;&gt; logging.getLevelName(15) 'DEBUGGISH' &gt;&gt;&gt; logging.getLevelName('DEBUGGISH') 15 </code></pre> <p>The fact that <code>getLevelName</code> can map names to numbers as well as numbers to names is not actually documented in Python 2.x, nor does the name give any hint that it should… but a quick look at <a href="http://hg.python.org/cpython/file/2.7/Lib/logging/__init__.py#l137">the source</a> shows why it works.</p>
15,682,199
private String or public static String?
<p>At my internship one of my colleagues gave me a hint. I want to know if this is good practice.</p> <p>What I was doing was creating classes that are used only for the values they contain and don't have any functions that actually do something (apart from having getters, setters and a constructor). I declared my variables like this:</p> <pre><code>public class ObjectIUse{ Private String name; public ObjectIUse(String name){ this.name = name; } public String getName(){ return name; } } </code></pre> <p>So I'm not using a setter because it should always stay the same. My colleague said that I can also do it this way:</p> <pre><code>public class ObjectIUse{ public final String name; public ObjectIUse(String name){ this.name = name; } } </code></pre> <p>Because now we don't need to have any getters or setters because it is public, however it can also never be changed because it is final. </p> <p>Which would be better? Or would it maybe be preferable to still make it private but also final? I mean all of the options work, obviously. I just want to know which is better and why.</p>
15,682,250
8
14
null
2013-03-28 12:46:24.42 UTC
2
2013-03-28 18:15:37.867 UTC
2013-03-28 13:15:08.67 UTC
null
2,208,272
null
2,208,272
null
1
10
java|android|private|public|final
70,921
<p>Make the variable private, because by doing so you'll be <a href="http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29" rel="nofollow noreferrer">encapsulating</a> the variable in your class. This has many benefits, <a href="http://en.wikipedia.org/wiki/Information_hiding" rel="nofollow noreferrer">information hiding</a> is among one, which you'll learn if you go to the above link.</p> <p>If you want it to never change after creation, then make it final too.</p>
18,798,792
Explaining difference between automaticallyAdjustsScrollViewInsets, extendedLayoutIncludesOpaqueBars, edgesForExtendedLayout in iOS7
<p>I have been reading a lot about iOS7 UI transition.</p> <p>I am not able to get what these three properties <code>automaticallyAdjustsScrollViewInsets</code>, <code>extendedLayoutIncludesOpaqueBars</code>, <code>edgesForExtendedLayout</code>??</p> <p>For example I am trying to make my view controllers start below the status bar but I am not able to achieve it.</p>
19,585,104
5
3
null
2013-09-14 05:52:47.65 UTC
247
2019-07-22 21:33:56.907 UTC
2015-07-15 14:42:58.123 UTC
null
1,570,496
null
1,010,819
null
1
253
ios|objective-c|xcode|uiviewcontroller|ios7
83,732
<p>Starting in iOS7, the view controllers use full-screen layout by default. At the same time, you have more control over how it lays out its views, and that's done with those properties:</p> <p><strong>edgesForExtendedLayout</strong></p> <p>Basically, with this property you set which sides of your view can be extended to cover the whole screen. Imagine that you push a <code>UIViewController</code> into a <code>UINavigationController</code>. When the view of that view controller is laid out, it will start where the navigation bar ends, but this property will set which sides of the view (top, left, bottom, right) can be extended to fill the whole screen.</p> <p>Let see it with an example:</p> <pre><code>UIViewController *viewController = [[UIViewController alloc] init]; viewController.view.backgroundColor = [UIColor redColor]; UINavigationController *mainNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; </code></pre> <p>Here you are not setting the value of <code>edgesForExtendedLayout</code>, therefore the default value is taken (<code>UIRectEdgeAll</code>), so the view extends its layout to fill the whole screen.</p> <p>This is the result:</p> <p><img src="https://i.stack.imgur.com/MOB6v.png" alt="without edges for extended layout, the view fills the whole screen"></p> <p>As you can see, the red background extends behind the navigation bar and the status bar.</p> <p>Now, you are going to set that value to <code>UIRectEdgeNone</code>, so you are telling the view controller to not extend the view to cover the screen:</p> <pre><code>UIViewController *viewController = [[UIViewController alloc] init]; viewController.view.backgroundColor = [UIColor redColor]; viewController.edgesForExtendedLayout = UIRectEdgeNone; UINavigationController *mainNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; </code></pre> <p>And the result:</p> <p><img src="https://i.stack.imgur.com/ojAvO.png" alt="with edgesForExtendedLayout set, the view is just under the navigation"></p> <hr> <p><strong>automaticallyAdjustsScrollViewInsets</strong></p> <p>This property is used when your view is a <code>UIScrollView</code> or similar, like a <code>UITableView</code>. You want your table to start where the navigation bar ends, because you wont see the whole content if not, but at the same time you want your table to cover the whole screen when scrolling. In that case, setting <code>edgesForExtendedLayout</code> to None won't work because your table will start scrolling where the navigation bar ends and it wont go behind it.</p> <p>Here is where this property comes in handy, if you let the view controller automatically adjust the insets (setting this property to YES, also the default value) it will add insets to the top of the table, so the table will start where the navigation bar ends, but the scroll will cover the whole screen.</p> <p>This is when is set to NO:</p> <p><img src="https://i.stack.imgur.com/9Iapl.png" alt="the table will scroll over the whole screen, but starts out partially covered"></p> <p>And YES (by default):</p> <p><img src="https://i.stack.imgur.com/VVQHQ.png" alt="the table scrolls over the whole screen, and starts just under the navigation"></p> <p>In both cases, the table scrolls behind the navigation bar, but in the second case (YES), it will start from below the navigation bar.</p> <hr> <p><strong>extendedLayoutIncludesOpaqueBars</strong></p> <p>This value is just an addition to the previous ones. By default, this parameter is set to NO. If the status bar is opaque, the views won't be extended to include the status bar, even if you extend your view to cover it (<code>edgesForExtendedLayout</code> to <code>UIRectEdgeAll</code>).</p> <p>If you set the value to YES, this will allow the view to go underneath the status bar again.</p> <p>If something is not clear, write a comment and I'll answer it.</p> <p><strong>How does iOS know what UIScrollView to use?</strong></p> <p>iOS grabs the first subview in your ViewController's view, the one at index 0, and if it's a subclass of <code>UIScrollView</code> then applies the explained properties to it. </p> <p>Of course, this means that <code>UITableViewController</code> works by default (since the <code>UITableView</code> is the first view).</p>