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
37,477,139
How to debug a gulp task with VSCode
<p>I need to debug a command <code>gulp start</code> with VScode (I got some mapping error with babel during transpilation that I don't understand yet...). The VSCode debug default configuration aims to launch <code>node app.js</code>. How to modify it to trigger the <code>gulp command</code>?</p> <p>Here is the default configuration. If anyone has hint of how can I do that, I'll be in your debt :)</p> <pre><code>{ "version": "0.2.0", "configurations": [ { "name": "Lancer", "type": "node", "request": "launch", "program": "${workspaceRoot}/app.js", "stopOnEntry": false, "args": [], "cwd": "${workspaceRoot}", "preLaunchTask": null, "runtimeExecutable": null, "runtimeArgs": [ "--nolazy" ], "env": { "NODE_ENV": "development" }, "externalConsole": false, "sourceMaps": false, "outDir": null }, { "name": "Attacher", "type": "node", "request": "attach", "port": 5858, "address": "localhost", "restart": false, "sourceMaps": false, "outDir": null, "localRoot": "${workspaceRoot}", "remoteRoot": null } ] } </code></pre>
37,971,644
1
0
null
2016-05-27 07:16:34.617 UTC
9
2016-06-22 14:54:11.967 UTC
null
null
null
null
1,346,701
null
1
20
debugging|gulp|visual-studio-code
11,670
<p>In your "Lancer" configuration, make the following changes.</p> <ul> <li>Change <em>program</em> to <strong>"${workspaceRoot}/node_modules/gulp/bin/gulp.js"</strong></li> <li>Change <em>args</em> to <strong>["start"]</strong></li> </ul> <p>Set a breakpoint in the task you want to debug and launch the debugger. Change 'start' to the desired task name to debug other tasks.</p>
31,512,422
pip install failing with: OSError: [Errno 13] Permission denied on directory
<p><code>pip install -r requirements.txt</code> fails with the exception below <code>OSError: [Errno 13] Permission denied: '/usr/local/lib/...</code>. What's wrong and how do I fix this? (I am trying to setup <a href="https://www.djangoproject.com" rel="noreferrer">Django</a>)</p> <pre><code>Installing collected packages: amqp, anyjson, arrow, beautifulsoup4, billiard, boto, braintree, celery, cffi, cryptography, Django, django-bower, django-braces, django-celery, django-crispy-forms, django-debug-toolbar, django-disqus, django-embed-video, django-filter, django-merchant, django-pagination, django-payments, django-storages, django-vote, django-wysiwyg-redactor, easy-thumbnails, enum34, gnureadline, idna, ipaddress, ipython, kombu, mock, names, ndg-httpsclient, Pillow, pyasn1, pycparser, pycrypto, PyJWT, pyOpenSSL, python-dateutil, pytz, requests, six, sqlparse, stripe, suds-jurko Cleaning up... Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install requirement.install(install_options, global_options, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install self.move_wheel_files(self.source_dir, root=root) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files pycompile=self.pycompile, File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber os.makedirs(destsubdir) File "/usr/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/amqp-1.4.6.dist-info' </code></pre>
31,512,491
8
1
null
2015-07-20 08:58:05.417 UTC
18
2021-05-27 09:25:42.26 UTC
2019-07-02 04:43:19.537 UTC
null
172,131
null
172,131
null
1
148
python|permissions|pip|installation
277,936
<h1>Option a) Create a virtualenv, activate it and install:</h1> <pre><code>virtualenv .venv source .venv/bin/activate pip install -r requirements.txt </code></pre> <h1>Option b) Install in your homedir:</h1> <pre><code>pip install --user -r requirements.txt </code></pre> <p>My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.</p>
28,042,598
How to $state.go()
<p>Is my $stateProvider:</p> <pre><code>$stateProvider .state('home', { url : '/', templateUrl : '/admindesktop/templates/main/', controller : 'AdminDesktopMainController' }).state('company', { url : '/company', templateUrl : '/admindesktop/templates/grid/', controller : 'CompanyGridController' }).state('company.detail', { url : '/{id:\d+}', //id is templateUrl : '/admindesktop/templates/company/detail/', controller : 'CompanyDetailController' }); </code></pre> <p>It's work for 'company' state (I use ui-sref), but this code not work (called from 'company' state):</p> <pre><code>$state.go('.detail', { id: $scope.selectedItem.id //selectedItem and id is defined }); </code></pre> <p>I read official docs and answers from StackOverflow, but I don't found solution. I can't use ui-sref, I use ui-grid, and new state opened after select one row from table for editing.</p> <p>What i do wrong?</p>
28,042,689
3
0
null
2015-01-20 10:07:43.297 UTC
1
2020-07-21 13:12:20.02 UTC
null
null
null
null
2,463,296
null
1
11
angularjs|angular-ui-router
83,854
<p>What would always work is the full state definition:</p> <pre><code>// instead of this // $state.go('.detail', { // use this $state.go('company.detail', { id: $scope.selectedItem.id //selectedItem and id is defined }); </code></pre> <p>In <a href="https://ui-router.github.io/ng1/docs/0.3.1/index.html#/api/ui.router.state.$state#methods_go" rel="noreferrer">doc there are defined these options</a>, but they depend on CURRENT state:</p> <blockquote> <p><strong>to</strong> <em>string</em><br> Absolute state name or relative state path. Some examples:</p> <ul> <li>$state.go('contact.detail') - will go to the contact.detail state</li> <li>$state.go('^') - will go to a parent state</li> <li>$state.go('^.sibling') - will go to a sibling state</li> <li>$state.go('.child.grandchild') - will go to grandchild state</li> </ul> </blockquote>
22,063,191
Why does the lock object have to be readonly?
<p>When implementing a lock, I used to create a private object inside of my class:</p> <p>If I want to be sure that it is locked in the thread that created my class:</p> <pre><code>private object Locker = new object(); </code></pre> <p>If I want to be sure that it will be locked for all threads inside my application:</p> <pre><code>private static object Locker = new object(); </code></pre> <p>But here: <a href="https://stackoverflow.com/questions/5053172/why-does-the-lock-object-have-to-be-static">Why does the lock object have to be static?</a></p> <p>and in a number of other questions, everyone says that the object has to be <code>readonly</code>. I haven't found the reason - not even in MSDN or JavaDoc.</p> <p>As I use this kind of construction quite often, could someone explain to me why should I use <code>readonly</code>? </p> <p>Thanks!</p>
22,063,363
4
1
null
2014-02-27 08:42:10.05 UTC
5
2022-05-26 10:47:56.417 UTC
2017-05-23 12:17:44.127 UTC
null
-1
null
1,875,384
null
1
35
c#|multithreading
15,307
<blockquote> <p>If I want to be sure that it will be locked for all threads inside my application:</p> </blockquote> <p>The lock object has to be static, if it locks access to static state.<br> Otherwise it has to be instance, because there's no need to lock state of one class instance, and prevent other threads to work with another class instance at the same time.</p> <blockquote> <p>everyone says that the object has to be "readonly" I didn't found the reason</p> </blockquote> <p>Well, it doesn't <em>have to</em> be. This is just a best practice, which helps you to avoid errors.</p> <p>Consider this code:</p> <pre><code>class MyClass { private object myLock = new object(); private int state; public void Method1() { lock (myLock) { state = // ... } } public void Method2() { myLock = new object(); lock (myLock) { state = // ... } } } </code></pre> <p>Here Thread1 can acquire lock via <code>Method1</code>, but Thread2, which is going to execute <code>Method2</code>, will ignore this lock, because lock object was changed => the state can be corrupted.</p>
23,746,431
jfxrt.jar not in JDK 1.8?
<p>I just updated my JDK to the JDK 1.8 because i couldnt find the jfxrt.jar needed by java FX in the 1.7 version.</p> <p>I downloaded the JDK from here: <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html">http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html</a></p> <p>Specifically the version: jdk-8u5-linux-i586.rpm</p> <p>I use opensuse 13.1 by the way.</p> <p>Now after the installation my usr/java/jdk1.9_05/lib still does not contain the jfxrt.jar.</p> <p>Has anybody an idea why, I read that this version should actually contain it. Can I fix this problem putting the jar in ther manually?</p>
23,746,605
4
2
null
2014-05-19 20:13:52.337 UTC
3
2020-02-13 09:41:47.933 UTC
null
null
null
null
1,804,317
null
1
20
java|linux|javafx
60,453
<p>For me on OSX it's under <code>jdk1.8.0_05.jdk/Contents/Home/jre/lib/ext/jfxrt.jar</code>. I'd guess it's in an analogous place on your machine. Try <code>/usr/java/jdk1.8.0_05/jre/lib/ext/jfxrt.jar</code></p>
29,616,596
How to use default serialization in a custom JsonConverter
<p>I have a complex object graph that I am serializing/deserializing with Json.NET. Some of the objects derive from an abstract class, so in order for the deserialization to work properly, I needed to create a custom <code>JsonConverter</code>. Its only role is to select the appropriate concrete implementation of the abstract class at deserialization-time and allow Json.NET to continue on its way.</p> <p>My problem comes when I want to serialize. I don't need to do anything custom at all. I want to get exactly the same behavior as I would get using <code>JsonConvert.SerializeObject</code> with no custom <code>JsonConverter</code>.</p> <p>However, since I'm using the custom JsonConverter class for my deserialization needs, I'm forced to supply a <code>WriteJson</code> implementation. Since WriteJson is abstract, I can't just call <code>base.WriteJson</code>, but I want to do essentially that. So my question is, what do I put in that method to get the plain-Jane, default behavior? In other words:</p> <pre><code>public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // What goes here to get default processing? } </code></pre>
29,616,648
1
1
null
2015-04-13 23:14:40.407 UTC
5
2019-03-29 03:55:56.48 UTC
null
null
null
null
912,961
null
1
53
json|json.net
14,489
<p>In your custom <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverter.htm" rel="noreferrer"><code>JsonConverter</code></a>, override <a href="https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonConverter_CanWrite.htm" rel="noreferrer"><code>CanWrite</code></a> and return false:</p> <pre><code>public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } </code></pre> <p>Then you can just throw an exception from <code>WriteJson</code>, since it won't get called.</p> <p>(Similarly, to get default behavior during <strong>de</strong>serialization, override <a href="https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonConverter_CanRead.htm" rel="noreferrer"><code>CanRead</code></a> and return <code>false</code>.)</p> <p>Note that the same approach can be used for <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverter_1.htm" rel="noreferrer"><code>JsonConverter&lt;T&gt;</code></a> (introduced in <a href="https://github.com/JamesNK/Newtonsoft.Json/releases/tag/11.0.1" rel="noreferrer">Json.NET 11.0.1</a>) since it is just a subclass of <code>JsonConverter</code> that introduces type-safe versions of <a href="https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConverter_1_ReadJson_1.htm" rel="noreferrer"><code>ReadJson()</code></a> and <a href="https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConverter_1_WriteJson_1.htm" rel="noreferrer"><code>WriteJson()</code></a>.</p>
32,366,694
adding values to the vector inside for loop in R
<p>I have just started learning R and I wrote this code to learn on functions and loops. </p> <pre><code>squared&lt;-function(x){ m&lt;-c() for(i in 1:x){ y&lt;-i*i c(m,y) } return (m) } squared(5) NULL </code></pre> <p>Why does this return NULL. I want <code>i*i</code> values to append to the end of <code>m</code>and return a vector. Can someone please point out whats wrong with this code.</p>
32,366,752
2
2
null
2015-09-03 03:56:18.557 UTC
null
2022-01-05 22:51:18.303 UTC
2015-09-03 04:01:00.8 UTC
user3710546
null
null
3,577,754
null
1
5
r|function|for-loop
43,725
<p>You haven't put anything inside <code>m &lt;- c()</code> in your loop since you did not use an assignment. You are getting the following -</p> <pre><code>m &lt;- c() m # NULL </code></pre> <p>You can change the function to return the desired values by assigning <code>m</code> in the loop.</p> <pre><code>squared &lt;- function(x) { m &lt;- c() for(i in 1:x) { y &lt;- i * i m &lt;- c(m, y) } return(m) } squared(5) # [1] 1 4 9 16 25 </code></pre> <p>But this is inefficient because we know the length of the resulting vector will be 5 (or <code>x</code>). So we want to allocate the memory first before looping. This will be the better way to use the <code>for()</code> loop.</p> <pre><code>squared &lt;- function(x) { m &lt;- vector("integer", x) for(i in seq_len(x)) { m[i] &lt;- i * i } m } squared(5) # [1] 1 4 9 16 25 </code></pre> <p>Also notice that I have removed <code>return()</code> from the second function. It is not necessary there, so it can be removed. It's a matter of personal preference to leave it in this situation. Sometimes it will be necessary, like in <code>if()</code> statements for example.</p> <p>I know the question is about looping, but I also must mention that this can be done more efficiently with seven characters using the primitive <code>^</code>, like this</p> <pre><code>(1:5)^2 # [1] 1 4 9 16 25 </code></pre> <p><code>^</code> is a primitive function, which means the code is written entirely in C and will be the most efficient of these three methods</p> <pre><code>`^` # function (e1, e2) .Primitive("^") </code></pre>
4,322,661
Warning: calling polyEqual
<p>Can somebody please explain, what does this warning means?</p> <pre><code>stdIn:18.35 Warning: calling polyEqual </code></pre> <p>and why do I have &quot;a and not 'a in the following statement:</p> <pre><code>val alreadyVisited = fn : ''a * ''a list -&gt; bool </code></pre> <p>this is my function:</p> <pre><code>fun alreadyVisited(v, []) = false | alreadyVisited(v, x::xs) = if(x=v) then true else alreadyVisited(v, xs); </code></pre>
4,328,111
1
0
null
2010-12-01 09:00:42.223 UTC
6
2021-02-11 10:51:05.987 UTC
2021-02-11 10:51:05.987 UTC
null
9,926,721
null
457,445
null
1
38
sml|smlnj
15,221
<p><code>'a</code> means "any type", while <code>''a</code> means "any type that can be compared for equality". Since your <code>alreadyVisited</code> function compared <code>x</code> and <code>v</code> using <code>=</code>, <code>x</code> and <code>v</code> need to have a type that supports comparing them for equality, so you get the type <code>''a</code>.</p> <p>The warning means that you're comparing two values with polymorphic type for equality.</p> <p>Why does this produce a warning? Because it's less efficient than comparing two values of known types for equality.</p> <p>How do you get rid of the warning? By changing your function to only work with a specific type instead of any type.</p> <p>Should you care about the warning? Probably not. In most cases I would argue that having a function that can work for any type is more important than having the most efficient code possible, so I'd just ignore the warning.</p>
39,643,424
NoClassDefFoundError: org/testng/TestNG
<p>This error</p> <blockquote> <p>NoClassDefFoundError: org/testng/TestNG</p> </blockquote> <p>appears when I'm trying to run my test from Testng.xml file using IntelliJ IDEA. Running my test one by one works perfectly as well as running whole gradle project which points to <code>testng.xml</code>, like <code>grade core-test:test</code></p> <p>( On my project I'm using Appium + IntelliJ + TestNG ) </p> <p>But when I'm running testng.xml using IntelliJ I'm immediately getting this message after pressing Run:</p> <pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/testng/TestNG at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:763) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:120) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) Caused by: java.lang.ClassNotFoundException: org.testng.TestNG at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 18 more </code></pre>
41,252,617
8
1
null
2016-09-22 15:43:10.947 UTC
3
2021-05-08 10:08:13.483 UTC
2016-09-26 12:56:24.913 UTC
null
1,905,949
null
6,865,465
null
1
19
java|ide|testng
58,959
<p>I found a solution posted here: <a href="https://intellij-support.jetbrains.com/hc/en-us/community/posts/206597869-Cannot-launch-NGTest-runner-in-IntelliJ-IDEA-2016-1" rel="noreferrer">https://intellij-support.jetbrains.com/hc/en-us/community/posts/206597869-Cannot-launch-NGTest-runner-in-IntelliJ-IDEA-2016-1</a></p> <blockquote> <p>I got it to work by selecting "In whole project" (I had "In single module" selected) under the Configuration tab in the TestNG "Run/Debug Configurations." </p> <p>However, the prior configuration worked in IntelliJ IDEA 15, so to me, it seems that it may have come from a breaking change with newer IDE.</p> </blockquote> <p>It worked for me.</p>
39,607,999
css difference between background: and background-image:
<p>quick simple question In the following example of an external CSS page; </p> <pre><code>body { background-image: url(background.jpg); } header { background: url(background.jpg); } </code></pre> <p>I understand they are effecting different element selectors, my question is what is the difference between using background vs background-image? Does one have access to specific attributes to the other? Please and thank you. </p>
39,608,030
2
1
null
2016-09-21 05:09:52.377 UTC
8
2019-09-09 23:28:42.067 UTC
2016-09-21 05:22:54.273 UTC
null
4,377,017
null
5,613,879
null
1
31
css|background|background-image|between|difference
24,470
<p>In a background property you can add <code>background-color</code>, <code>repeat</code>, <code>no-repeat</code> and other image attributes, but in the <code>background-image</code> property you are only allowed to add image.</p> <pre><code>background-image: url("img_tree.png"); background-repeat: no-repeat; background-position: right top; background-attachment: fixed; </code></pre> <p>and in background property you can do in one line all these</p> <pre><code>background: #ccc url(paper.gif) no-repeat; </code></pre>
26,721,403
Android How to implement Bottom Sheet from Material Design docs
<p>How do you implement the bottom sheet specficiation? <a href="http://www.google.com/design/spec/components/bottom-sheets.html" rel="noreferrer">http://www.google.com/design/spec/components/bottom-sheets.html</a></p> <p>The new update to Google Drive shows this with the Floating Action Button press -></p> <p><img src="https://i.stack.imgur.com/XRiy0.png" alt="enter image description here"></p> <p>Granted the specs never say anything about rounded corners, regardless it is possible to do, just unsure of how to go about it. Currently using the AppCompat library and target set to 21.</p> <p>Thanks</p>
35,615,022
9
1
null
2014-11-03 19:19:08.297 UTC
46
2022-08-29 19:13:46.06 UTC
null
null
null
null
1,784,299
null
1
81
android|android-5.0-lollipop|material-design|floating-action-button
79,225
<p>Answering my own question so developers know that the new support library provides this finally! All hail the all powerful Google!</p> <p>An example from the <a href="http://android-developers.blogspot.com/2016/02/android-support-library-232.html" rel="noreferrer">Android Developer's Blog</a>:</p> <blockquote> <pre><code>// The View with the BottomSheetBehavior View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet); BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet); behavior.setBottomSheetCallback(new BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { // React to state change } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { // React to dragging events } }); </code></pre> </blockquote> <p>@reVerse's <a href="https://stackoverflow.com/a/26723695/1784299">answer above</a> is still a valid option but its nice to know that there is a standard that Google supports too.</p>
20,028,079
Hex String To Byte Array C#
<p><em>This is a duplicate question, my apologies everyone!</em></p> <p>Firstly, I apologize if this is a simple question, I have been searching for a very long time, and either an answer about this does not exist, the answer I am looking for has been buried under answers to questions about how to convert a string to a byte array, or I'm not searching with the right terminology. I have also found a few answers on converting a single hex value into a byte but applying those methods to work with what I want to do doesn't really seem to work very well.</p> <p>What I am looking for is not how to convert "string" to a byte array, rather, I am trying to convert an already in bytes value from a textbox, into something my application will recognize as a byte array. I'll try to explain better with an example:</p> <pre><code>textBox.Text = 019F314A I want byte[] bytes to equal { 0x01, 0x9F, 0x31, 0x4A } </code></pre> <p>Hopefully that makes sense. Thanks to anyone who can offer any assistance!</p>
20,028,150
1
1
null
2013-11-17 06:54:06.92 UTC
null
2013-11-17 07:11:46.923 UTC
2013-11-17 07:11:46.923 UTC
null
1,641,365
null
1,641,365
null
1
3
c#|arrays|string|hex|byte
94,835
<p>I believe you can use Convert.ToByte(), you might have to slice your string in pairs and loop through it.</p> <p>If you do a quick search there are many topics on this already on stackoverflow</p> <p><a href="https://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa">How do you convert Byte Array to Hexadecimal String, and vice versa?</a></p> <p>You can also look at this MS example, it is to convert to int, but the idea is the same. <a href="http://msdn.microsoft.com/en-us/library/bb311038.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb311038.aspx</a></p>
6,831,194
How can I remove all images/drawings from a PDF file and leave text only in Java?
<p>I have a PDF file that's an output from an OCR processor, this OCR processor recognizes the image, adds the text to the pdf but at the end places a low quality image instead of the original one (I have no idea why anyone would do that, but they do).</p> <p>So, I would like to get this PDF, remove the image stream and leave the text alone, so that I could get it and import (using iText page importing feature) to a PDF I'm creating myself with the real image.</p> <p>And before someone asks, I have already tried to use another tool to extract text coordinates (JPedal) but when I draw the text on my PDF it isn't at the same position as the original one.</p> <p>I'd rather have this done in Java, but if another tool can do it better, just let me know. And it could be image removal only, I can live with a PDF with the drawings in there.</p>
6,892,418
2
2
null
2011-07-26 14:00:23.457 UTC
10
2019-08-12 03:05:58.98 UTC
null
null
null
null
293,686
null
1
14
java|pdf|itext
15,001
<p>I used Apache PDFBox in similar situation.</p> <p>To be a little bit more specific, try something like that:</p> <pre><code>import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.exceptions.CryptographyException; import org.apache.pdfbox.exceptions.InvalidPasswordException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDResources; import java.io.IOException; public class Main { public static void main(String[] argv) throws COSVisitorException, InvalidPasswordException, CryptographyException, IOException { PDDocument document = PDDocument.load("input.pdf"); if (document.isEncrypted()) { document.decrypt(""); } PDDocumentCatalog catalog = document.getDocumentCatalog(); for (Object pageObj : catalog.getAllPages()) { PDPage page = (PDPage) pageObj; PDResources resources = page.findResources(); resources.getImages().clear(); } document.save("strippedOfImages.pdf"); } } </code></pre> <p>It's supposed to remove all types of images (png, jpeg, ...). It should work like that:</p> <p><a href="https://i.stack.imgur.com/mqtrs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mqtrs.jpg" alt="Sample article"></a> .</p>
55,184,945
Adding Two Decimal Place to Number TypeScript Angular
<p>Cant seem to figure this out. I have tried many different variations. This is on an Angular project.</p> <p>I want a percent number to always be shown with two decimal places even if the user only types a whole number.</p> <p>I cant switch the data type around as a lot of other code has been written around it being a number.</p> <p>The problem is that TypeScript does not allow var and I am having trouble getting to add the extra zeros or round said number to two decimals. It always seems to strip them.</p> <p>Declaration:</p> <pre><code> percent: number; </code></pre> <p>Some things I have tried.</p> <pre><code>1: this.percent = Math.round(this.percent * 1e2) / 1e2; 2: this.percent = this.percent.toFixed(2); // Throws error cant assign string to num because to fixed returns string 3: const percentString = this.percent.toString() + '.00'; this.percent = parseFloat(percentString) // Strips 00 (Tried this to just add zeros to whole number as test [will be making it more dynamic]) 4: this.percent = Math.round(this.percent * 100) / 100; 5: (This whole function from another SOF) addZeroes(num) { // Convert input string to a number and store as a variable. let value = Number(num).toString(); // Split the input string into two arrays containing integers/decimals const res = num.split('.'); // If there is no decimal point or only one decimal place found. if (res.length === 1 || res[1].length &lt; 3) { // Set the number to two decimal places value = parseFloat(value).toFixed(2); } // Return updated or original number. return value; } and then this.percent = parseFloat(this.addZeroes(this.percent)); 6: this.percent = parseFloat(this.percent).toFixed(2); // Error inside parseFloat: TS2345: Argument of type 'number' is not assignable to parameter of type 'string' 7: this.percent = parseFloat(this.percent.toString()).toFixed(2); // Throws error on this.percent assignment: TS2322: Type 'string' is not assignable to type 'number' 8: this.percent = Number(this.percent).toFixed(2); // Error on assignment: TS2322: Type 'string' is not assignable to type 'number'. </code></pre> <p>HTML:</p> <pre><code> &lt;mat-form-field&gt; &lt;input matInput [numbers]="'.'" type="text" maxlength="5" [placeholder]="'Percent'" [(ngModel)]="percent" (change)="updateDollarAmountNew()" numbers name="percent"&gt; &lt;/mat-form-field&gt; </code></pre> <p>I have also tried piping on front end but have problems with that as well.</p> <pre><code>[(ngModel)]="p.percent | number : '1.2-2'" // Error: ng: The pipe '' could not be found [(ngModel)]="{{percent | number : '1.2-2'}}" // Error: unexpected token '}}' [(ngModel)]={{percent | number : '1.2-2'}} // Error: Attribute number is not allowed here [(ngModel)]={{percent | number : 2}} // Error: : expected // And so on... </code></pre> <p>Thanks for your tips and help!</p>
55,185,043
2
1
null
2019-03-15 14:34:06.893 UTC
2
2019-03-15 20:31:37.793 UTC
2019-03-15 20:31:37.793 UTC
null
10,736,342
null
10,736,342
null
1
7
angular|typescript|decimal
42,119
<p>You've done all the work, but just haven't put the right bits together. Parsing the float works, and <code>toFixed(2)</code> was correctly returning a string with 2 decimal places, you just need to use them together:</p> <p><code>parseFloat(input).toFixed(2)</code></p>
7,184,341
iOS: Sample code for simultaneous record and playback
<p>I'm designing a simple proof of concept for multitrack recorder.</p> <p>Obvious starting point is to play from file A.caf to headphones while simultaneously recording microphone input into file B.caf</p> <p>This question -- <a href="https://stackoverflow.com/questions/4215180/record-and-play-audio-simultaneously">Record and play audio Simultaneously</a> -- points out that there are three levels at which I can work:</p> <ul> <li>AVFoundation API (AVAudioPlayer + AVAudioRecorder)</li> <li>Audio Queue API</li> <li>Audio Unit API (RemoteIO)</li> </ul> <p>What is the best level to work at? Obviously the generic answer is to work at the highest level that gets the job done, which would be AVFoundation.</p> <p>But I'm taking this job on from someone who gave up due to latency issues (he was getting a 0.3sec delay between the files), so maybe I need to work at a lower level to avoid these issues?</p> <p>Furthermore, what source code is available to springboard from? I have been looking at SpeakHere sample ( <a href="http://developer.apple.com/library/ios/#samplecode/SpeakHere/Introduction/Intro.html" rel="nofollow noreferrer">http://developer.apple.com/library/ios/#samplecode/SpeakHere/Introduction/Intro.html</a> ). if I can't find something simpler I will use this.</p> <p>But can anyone suggest something simpler/else? I would rather not work with C++ code if I can avoid it.</p> <p>Is anyone aware of some public code that uses AVFoundation to do this?</p> <p>EDIT: AVFoundation example here: <a href="http://www.iphoneam.com/blog/index.php?title=using-the-iphone-to-record-audio-a-guide&amp;more=1&amp;c=1&amp;tb=1&amp;pb=1" rel="nofollow noreferrer">http://www.iphoneam.com/blog/index.php?title=using-the-iphone-to-record-audio-a-guide&amp;more=1&amp;c=1&amp;tb=1&amp;pb=1</a></p> <p>EDIT(2): Much nicer looking one here: <a href="http://www.switchonthecode.com/tutorials/create-a-basic-iphone-audio-player-with-av-foundation-framework" rel="nofollow noreferrer">http://www.switchonthecode.com/tutorials/create-a-basic-iphone-audio-player-with-av-foundation-framework</a></p> <p>EDIT(3): <a href="https://stackoverflow.com/questions/1010343/how-do-i-record-audio-on-iphone-with-avaudiorecorder">How do I record audio on iPhone with AVAudioRecorder?</a></p>
7,219,499
3
0
null
2011-08-25 02:03:07.323 UTC
12
2016-07-27 17:52:37.833 UTC
2017-05-23 11:45:33.953 UTC
null
-1
null
435,129
null
1
15
ios|audio|record|playback|simultaneous
18,506
<p>As suggested by Viraj, here is the answer.</p> <p>Yes, you can achieve very good results using AVFoundation. Firstly you need to pay attention to the fact that for both the player and the recorder, activating them is a two step process.</p> <p>First you prime it.</p> <p>Then you play it.</p> <p>So, prime everything. Then play everything.</p> <p>This will get your latency down to about 70ms. I tested by recording a metronome tick, then playing it back through the speakers while holding the iPhone up to the speakers and simultaneously recording.</p> <p>The second recording had a clear echo, which I found to be ~70ms. I could have analysed the signal in Audacity to get an exact offset.</p> <p>So in order to line everything up I just performSelector:x withObject: y afterDelay: 70.0/1000.0</p> <p>There may be hidden snags, for example the delay may differ from device to device. it may even differ depending on device activity. It is even possible the thread could get interrupted/rescheduled in between starting the player and starting the recorder.</p> <p>But it works, and is a lot tidier than messing around with audio queues / units.</p>
7,563,652
Static Final Variable in Java
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1415955/private-final-static-attribute-vs-private-final-attribute">private final static attribute vs private final attribute</a> </p> </blockquote> <p>What's the difference between declaring a variable as</p> <pre><code>static final int x = 5; </code></pre> <p>or</p> <pre><code>final int x = 5; </code></pre> <p>If I only want to the variable to be local, and constant (cannot be changed later)?</p> <p>Thanks</p>
7,563,683
4
3
null
2011-09-27 02:44:33.273 UTC
8
2019-06-11 10:04:17.567 UTC
2017-05-23 12:34:50.797 UTC
null
-1
null
680,441
null
1
39
java|static|final
134,826
<p>Just having <code>final</code> will have the intended effect.</p> <pre><code>final int x = 5; ... x = 10; // this will cause a compilation error because x is final </code></pre> <p>Declaring static is making it a class variable, making it accessible using the class name <code>&lt;ClassName&gt;.x</code></p>
7,045,508
Moq: Setup a mocked method to fail on the first call, succeed on the second
<p>What's the most succinct way to use Moq to mock a method that will throw an exception the first time it is called, then succeed the second time it is called?</p>
7,045,647
4
1
null
2011-08-12 19:44:17.213 UTC
7
2017-08-21 10:14:29.66 UTC
null
null
null
null
64,290
null
1
52
c#|unit-testing|mocking|nunit|moq
19,071
<p>I would make use of <code>Callback</code> and increment a counter to determine whether or not to throw an exception from <code>Callback</code>.</p> <pre><code>[Test] public void TestMe() { var count = 0; var mock = new Mock&lt;IMyClass&gt;(); mock.Setup(a =&gt; a.MyMethod()).Callback(() =&gt; { count++; if(count == 1) throw new ApplicationException(); }); Assert.Throws(typeof(ApplicationException), () =&gt; mock.Object.MyMethod()); Assert.DoesNotThrow(() =&gt; mock.Object.MyMethod()); } public interface IMyClass { void MyMethod(); } </code></pre>
7,591,294
How to create a self resizing grid of buttons in tkinter?
<p>I am trying to create a grid of buttons(in order to achieve the clickable cell effect) with Tkinter. </p> <p>My main problem is that I cannot make the <code>grid</code> and the buttons autoresize and fit the parent window. </p> <p>For example, when I have a high number of buttons on the grid, instead of shrinking the buttons so that the grid fits inside the window, I get a stretched frame that goes off screen.</p> <p>The effect that I am looking for is the grid filling all available space, then resizing its cells to fit within that space. I have read at the documentation, but I still cannot figure out how to make it work. </p> <p>This is the basic code which is my starting point:</p> <pre><code>def __init__(self): root = Tk() frame = Frame(root) frame.grid() #some widgets get added in the first 6 rows of the frame's grid #initialize grid grid = Frame(frame) grid.grid(sticky=N+S+E+W, column=0, row=7, columnspan=2) #example values for x in range(60): for y in range(30): btn = Button(grid) btn.grid(column=x, row=y) root.mainloop() </code></pre>
7,591,453
4
0
null
2011-09-29 00:54:48.947 UTC
29
2021-09-02 14:01:02.677 UTC
2015-03-14 21:33:15.757 UTC
null
3,924,118
null
457,899
null
1
59
python|button|grid|tkinter|autoresize
111,393
<p>You need to configure the rows and columns to have a <strong>non-zero weight</strong> so that they will take up the extra space:</p> <pre><code>grid.columnconfigure(tuple(range(60)), weight=1) grid.rowconfigure(tuple(range(30)), weight=1) </code></pre> <p>You also need to configure your buttons so that they will <strong>expand to fill the cell</strong>:</p> <pre><code>btn.grid(column=x, row=y, sticky=&quot;news&quot;) </code></pre> <p>This has to be done all the way up, so here is a full example:</p> <pre><code>from tkinter import * root = Tk() frame = Frame(root) root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) frame.grid(row=0, column=0, sticky=&quot;news&quot;) grid = Frame(frame) grid.grid(sticky=&quot;news&quot;, column=0, row=7, columnspan=2) frame.rowconfigure(7, weight=1) frame.columnconfigure(0, weight=1) #example values for x in range(10): for y in range(5): btn = Button(frame) btn.grid(column=x, row=y, sticky=&quot;news&quot;) frame.columnconfigure(tuple(range(10)), weight=1) frame.rowconfigure(tuple(range(5)), weight=1) root.mainloop() </code></pre>
21,725,916
Convert Any view into image and save it
<p>can any one please help me to know how to capture contents of a <code>FrameLayout</code> into an image and save it to internal or external storage.</p> <p>how can convert any view to image</p>
21,726,101
2
3
null
2014-02-12 10:56:54.253 UTC
8
2022-08-11 14:12:16.713 UTC
2022-08-11 14:12:16.713 UTC
null
18,877,353
null
3,283,568
null
1
19
android|android-framelayout
21,186
<p>try this to convert a view (framelayout) into a bitmap: </p> <pre><code>public Bitmap viewToBitmap(View view) { Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.draw(canvas); return bitmap; } </code></pre> <p>then, save your bitmap into a file: </p> <pre><code>try { FileOutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png"); bitmap.compress(Bitmap.CompressFormat.PNG, 100, output); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } </code></pre> <p>don't forget to set the permission of writing storage into your AndroidManifest.xml: </p> <pre><code>&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; </code></pre>
2,028,719
Handling RuntimeExceptions in Java
<p>Can anyone explain how to handle the Runtime Exceptions in Java?</p>
2,028,730
4
9
null
2010-01-08 15:50:20.64 UTC
10
2015-11-13 09:22:57.99 UTC
2015-11-13 09:22:57.99 UTC
null
617,450
null
214,131
null
1
20
java|exception-handling|runtimeexception
66,014
<p>It doesn't differ from handling a regular exception:</p> <pre><code>try { someMethodThatThrowsRuntimeException(); } catch (RuntimeException ex) { // do something with the runtime exception } </code></pre>
1,473,486
What is the 302 error code that jQuery AJAX is throwing?
<p>I'm working with ASP.NET MVC and jQuery and I have a UserControl that is repeated on every page. In every page request, an AJAX callback occurs. So far so good.</p> <p>But when I'm in localhost and I publish the site, I notice that this AJAX is throwing a <code>302</code> error. This only occurs on <code>https</code> pages, and only in FF and Chrome. On IE, the AJAX request works fine.</p> <p>What is this 302 error? Why does it only occur on <code>https</code> pages, and only in FF and Chrome?</p>
1,473,521
4
1
null
2009-09-24 18:46:59.06 UTC
1
2016-11-17 17:32:41.843 UTC
2016-11-17 17:32:41.843 UTC
null
3,474,146
null
60,286
null
1
21
jquery|ajax|http-status-code-302
94,640
<p>HTTP 302 is used for redirection. My guess is that there is some sort of server error and you are being redirected to an error page using 302. Check the server logs for errors.</p>
1,509,241
Lambda expression with a void input
<p>Ok, very silly question.</p> <pre><code>x =&gt; x * 2 </code></pre> <p>is a lambda representing the same thing as a delegate for </p> <pre><code>int Foo(x) { return x * 2; } </code></pre> <p>But what is the lambda equivalent of</p> <pre><code>int Bar() { return 2; } </code></pre> <p>??</p> <p>Thanks a lot!</p>
1,509,257
4
0
null
2009-10-02 12:31:16.427 UTC
3
2013-05-28 16:06:59.353 UTC
2009-10-02 12:37:47.443 UTC
null
5,789
null
5,789
null
1
30
c#|c#-3.0|lambda
16,408
<p>The nullary lambda equivalent would be <code>() =&gt; 2</code>.</p>
1,566,602
Is "SET CHARACTER SET utf8" necessary?
<p>I´m rewritting our database class (PDO based), and got stuck at this. I´ve been taught to both use <code>SET NAMES utf8</code> and <code>SET CHARACTER SET utf8</code> when working with UTF-8 in PHP and MySQL.</p> <p>In PDO I now want to use the <code>PDO::MYSQL_ATTR_INIT_COMMAND</code> parameter, but it only supports one query.</p> <p>Is <code>SET CHARACTER SET utf8</code> necessary?</p>
1,566,908
4
0
null
2009-10-14 14:23:22.093 UTC
31
2022-05-27 12:46:15.27 UTC
2010-06-17 07:54:40.363 UTC
null
138,023
null
138,023
null
1
30
php|mysql|utf-8|pdo
38,343
<p>Using <code>SET CHARACTER SET utf8</code> after using <code>SET NAMES utf8</code> will actually reset the <code>character_set_connection</code> and <code>collation_connection</code> to<br/> <code>@@character_set_database</code> and <code>@@collation_database</code> respectively.</p> <p>The <a href="http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html" rel="noreferrer">manual</a> states that</p> <ul> <li><p><code>SET NAMES x</code> is equivalent to </p> <pre><code>SET character_set_client = x; SET character_set_results = x; SET character_set_connection = x; </code></pre></li> <li><p>and <code>SET CHARACTER SET x</code> is equivalent to </p> <pre><code>SET character_set_client = x; SET character_set_results = x; SET collation_connection = @@collation_database; </code></pre></li> </ul> <p>whereas <code>SET collation_connection = x</code> also internally executes <code>SET character_set_connection = &lt;&lt;character_set_of_collation_x&gt;&gt;</code> and <code>SET character_set_connection = x</code> internally also executes <code>SET collation_connection = &lt;&lt;default_collation_of_character_set_x</code>.</p> <p>So essentially you're resetting <code>character_set_connection</code> to <code>@@character_set_database</code> and <code>collation_connection</code> to <code>@@collation_database</code>. The manual explains the usage of these variables:</p> <blockquote> <p><em>What character set should the server translate a statement to after receiving it?</em></p> <p>For this, the server uses the character_set_connection and collation_connection system variables. It converts statements sent by the client from character_set_client to character_set_connection (except for string literals that have an introducer such as _latin1 or _utf8). collation_connection is important for comparisons of literal strings. For comparisons of strings with column values, collation_connection does not matter because columns have their own collation, which has a higher collation precedence.</p> </blockquote> <p>To sum this up, the encoding/transcoding procedure MySQL uses to process the query and its results is a multi-step-thing:</p> <ol> <li>MySQL treats the incoming query as being encoded in <code>character_set_client</code>.</li> <li>MySQL transcodes the statement from <code>character_set_client</code> into <code>character_set_connection</code></li> <li>when comparing string values to column values MySQL transcodes the string value from <code>character_set_connection</code> into the character set of the given database column and uses the column collation to do sorting and comparison.</li> <li>MySQL builds up the result set encoded in <code>character_set_results</code> (this includes result data as well as result metadata such as column names and so on)</li> </ol> <p>So it could be the case that a <code>SET CHARACTER SET utf8</code> would not be sufficient to provide full UTF-8 support. Think of a default database character set of <code>latin1</code> and columns defined with <code>utf8</code>-charset and go through the steps described above. As <code>latin1</code> cannot cover all the characters that UTF-8 can cover you may lose character information in step <em>3</em>. </p> <ul> <li><strong>Step <em>3</em>:</strong> Given that your query is encoded in UTF-8 and contains characters that cannot be represented with <code>latin1</code>, these characters will be lost on transcoding from <code>utf8</code> to <code>latin1</code> (the default database character set) making your query fail.</li> </ul> <p>So I think it's safe to say that <code>SET NAMES ...</code> is the correct way to handle character set issues. Even though I might add that setting up your MySQL server variables correctly (all the required variables can be set statically in your <code>my.cnf</code>) frees you from the performance overhead of the extra query required on every connect.</p>
10,439,724
redirect to index rather than show after save
<p>I want to redirect to the a models index view after saving my model. </p> <pre><code>def create @test = Test.new(params[:test]) respond_to do |format| if @test.save format.html { redirect_to @test, notice: 'test was successfully created.' } else format.html { render action: "new" } end end end </code></pre> <p>I've tried</p> <pre><code> format.html { render action: "index", notice: 'Test was successfully created.' } </code></pre> <p>but I get the following error in /app/views/tests/index.html.erb - </p> <pre><code> undefined method `each' for nil:NilClass </code></pre> <p>Any idea what's going wrong?</p>
10,439,833
4
2
null
2012-05-03 21:42:56.073 UTC
7
2016-03-12 16:40:32.617 UTC
2012-05-03 21:52:06.087 UTC
null
597,264
null
597,264
null
1
44
ruby-on-rails|ruby-on-rails-3
49,765
<pre><code>render action: "index" </code></pre> <p>will not redirect, redirecting and rendering a different, render will just render the view with the current available variables for it. while with a redirect the index function of the controller will run and then the view will be rendered from there.</p> <p>you are getting the error because your index view is expecting some array which you are not giving to it since you are just rendering "index" and you dont have the variables that the view needs.</p> <p>You can do it in 2 ways</p> <p>1- using <code>render action: "index"</code></p> <p>make available to the view all the variables that it needs before you render, for example it may be needing a @posts variable which it uses to show list of posts so you need to get the posts in your create action before you render</p> <pre><code>@posts = Post.find(:all) </code></pre> <p>2- don't render do a <code>redirect_to</code></p> <p>instead of rendering "index" you redirect to the index action which will take care of doing the necessary things that the index view needs</p> <pre><code>redirect_to action: "index" </code></pre>
7,122,742
execute two shell commands in single exec php statement
<p>I want to display all the files that are modified after a specified date </p> <p>the commands are</p> <pre><code>touch --date '2011-09-19 /home/ , find /home/ </code></pre> <p>How i can execute this two commands in single exec statement.Thanks in advance</p>
7,122,994
5
0
null
2011-08-19 14:03:54.95 UTC
6
2019-02-15 09:00:38.72 UTC
null
null
null
null
273,266
null
1
24
php|exec
53,937
<p>You can use either a <code>;</code> or a <code>&amp;&amp;</code> to separate the comands. The <code>;</code> runs both commands unconditionally. If the first one fails, the second one still runs. Using <code>&amp;&amp;</code> makes the second command depend on the first. If the first command fails, the second will NOT run.</p> <pre><code>command1 ; command2 (run both uncondtionally) command1 &amp;&amp; command2 (run command2 only if command1 succeeds) </code></pre>
7,187,877
Math.ceil and Math.floor returning same value
<p>I have a double (23.46)</p> <p>And using the methods Math.ceil and Math.floor and parsing my double to these methods, I get the same value returned to me, which is 23...</p> <p>I want it to be rounded off to 24.. In otherwords, if I have a double that's 15.01, it should still be rounded off to 16... How do I do this?</p>
7,187,922
7
2
null
2011-08-25 09:18:49.727 UTC
4
2022-08-02 10:53:50.13 UTC
null
null
null
user818700
null
null
1
21
java|math
91,414
<p>Unable to reproduce:</p> <pre><code>public class Test { public static void main(String[] args) { System.out.println(Math.ceil(23.46)); // Prints 24 System.out.println(Math.floor(23.46)); // Prints 23 } } </code></pre> <p>I suspect that <em>either</em> you haven't got the input data you think you have <em>or</em> you're not writing out the output data you think you are. <code>Math.floor</code>/<code>ceil</code> themselves work fine. The only time they will return the same value is when the input is already an integer. You talk about <em>parsing</em> your double... my guess is that the error lies there. Please show us a short but complete program which demonstrates the problem.</p> <p>(There may be other scenarios around very large values where the exact target integer can't be represented exactly as a <code>double</code> - I haven't checked - but that's certainly not the case here.)</p>
7,132,514
How to unzip a piped zip file (from "wget -qO-")?
<p>Any ideas on how to unzip a piped zip file like this:</p> <pre><code>wget -qO- http://downloads.wordpress.org/plugin/akismet.2.5.3.zip </code></pre> <p>I wished to unzip the file to a directory, like we used to do with a normal file:</p> <pre><code>wget -qO- http://downloads.wordpress.org/plugin/akismet.2.5.3.zip | unzip -d ~/Desktop </code></pre>
7,142,865
7
2
null
2011-08-20 14:54:50.613 UTC
6
2022-05-13 19:34:12.95 UTC
2022-05-13 19:34:12.95 UTC
null
68,587
null
559,742
null
1
42
bash|wget|unzip
52,875
<pre><code>wget -q -O tmp.zip http://downloads.wordpress.org/plugin/akismet.2.5.3.zip &amp;&amp; unzip tmp.zip &amp;&amp; rm tmp.zip </code></pre>
7,255,649
Capturing window.onbeforeunload
<p>I have a form where the input fields are saved <code>onChange</code>. In Firefox (5) this works even when the window is closed, but for Chrome and IE it doesn't and I need to be sure that I'm saving this data even if they try to close the window after they've typed in a field but an <code>onBlur</code> event hasn't occurred (i.e. they've typed something into a textbox, but haven't tabbed out of it).</p> <p>I have read the following SO articles on using <code>window.onbeforeunload</code>: <a href="https://stackoverflow.com/questions/803887/can-i-pop-up-a-confirmation-dialog-when-the-user-is-closing-the-window-in-safari">article 1</a> <a href="https://stackoverflow.com/questions/1244535/alert-when-browser-window-closed-accidentally">article 2</a></p> <p>if I use the following:</p> <pre><code>window.onbeforeunload = function() { return "onbeforeunload"; } </code></pre> <p>then I get a popup with <code>onbeforeunload</code> in.</p> <p>but if I try:</p> <pre><code>window.onbeforeunload = function() { alert("onbeforeunload"); } </code></pre> <p>then nothing happens in any browser, even Firefox.</p> <p>what I want to achieve is:</p> <pre><code>window.onbeforeunload = function() { saveFormData(); } </code></pre> <p>I'd be grateful if someone could point out where I might be going wrong.</p>
7,256,224
7
2
null
2011-08-31 10:27:35.92 UTC
11
2020-05-12 18:09:32 UTC
2020-05-12 16:40:13.887 UTC
null
4,370,109
null
2,106,959
null
1
57
javascript|dom-events
131,627
<p>You have to <code>return</code> from the <code>onbeforeunload</code>:</p> <pre><code>window.onbeforeunload = function() { saveFormData(); return null; } function saveFormData() { console.log('saved'); } </code></pre> <p><strong>UPDATE</strong></p> <p>as per comments, alert does not seem to be working on newer versions anymore, anything else goes :)</p> <p><em>FROM <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload#Notes" rel="noreferrer">MDN</em></a></p> <blockquote> <p>Since 25 May 2011, the HTML5 specification states that calls to <code>window.showModalDialog()</code>, <code>window.alert()</code>, <code>window.confirm()</code>, and <code>window.prompt()</code> methods may be ignored during this event.</p> </blockquote> <p>It is also suggested to use this through the <code>addEventListener</code> interface:</p> <blockquote> <p>You <em>can</em> and <em>should</em> handle this event through <code>window.addEventListener()</code> and the <code>beforeunload</code> event.</p> </blockquote> <p>The updated code will now look like this:</p> <pre><code>window.addEventListener("beforeunload", function (e) { saveFormData(); (e || window.event).returnValue = null; return null; }); </code></pre>
7,652,928
Launch Finder window with specific files selected
<p>I'm trying to programmatically launch an OS X Finder window from an Xcode project. I need the window to open to a specific folder and have specific files within that folder automatically selected.</p> <p>This is similar to the &quot;Show in Finder&quot; functionality used in Xcode and related apps.</p> <p>Does anyone know how to do this in either Objective-C, Swift, AppleScript, or Finder command-line parameters?</p>
7,658,305
8
4
null
2011-10-04 19:14:27.963 UTC
16
2022-09-09 18:23:50.74 UTC
2020-12-10 07:55:19.107 UTC
null
1,265,393
null
979,133
null
1
44
objective-c|macos|applescript|finder
10,956
<p>Objective-C version: </p> <pre><code>NSArray *fileURLs = [NSArray arrayWithObjects:fileURL1, /* ... */ nil]; [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs]; </code></pre>
7,367,344
Adding a css class to select using @Html.DropDownList()
<p>I'm building my first MVC application after years of doing webforms, and for some reason I am not able to make this work: </p> <pre><code>@Html.DropDownList("PriorityID", String.Empty, new {@class="textbox"} ) </code></pre> <p>Error message:</p> <p><code>System.Web.Mvc.HtmlHelper&lt;SPDR.Models.Bug&gt;</code>' does not contain a definition for <code>DropDownList</code> and the best extension method overload <code>System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable&lt;System.Web.Mvc.SelectListItem&gt;, object)</code> has some invalid arguments</p> <p>Any help greatly appreciated!</p>
7,378,746
10
1
null
2011-09-09 20:55:54.85 UTC
15
2018-01-12 13:24:55.77 UTC
2012-08-05 08:50:45.29 UTC
null
1,573,667
null
782,371
null
1
78
asp.net-mvc|razor
188,854
<p>Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.</p> <p>My view was one of the auto-generated ones, and contained this line of code:</p> <pre><code>@Html.DropDownList("PriorityID", string.Empty) </code></pre> <p>To add html attributes, I needed to do something like this:</p> <pre><code>@Html.DropDownList("PriorityID", (IEnumerable&lt;SelectListItem&gt;)ViewBag.PriorityID, new { @class="dropdown" }) </code></pre> <p>Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...</p> <p><strong>UPDATE:</strong> </p> <p>A better way of doing this would be to use <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlistfor%28v=vs.118%29.aspx" rel="noreferrer">DropDownListFor</a> where possible, that way you don't rely on a magic string for the name attribute</p> <pre><code>@Html.DropDownListFor(x =&gt; x.PriorityID, (IEnumerable&lt;SelectListItem&gt;)ViewBag.PriorityID, new { @class = "dropdown" }) </code></pre>
13,861,416
Android Custom Shape Button
<p>How can i make a custom shaped clickable view or button in Android? </p> <p>When I click , I want to avoid touching on an empty area .</p> <p><img src="https://i.stack.imgur.com/PpkBo.png" alt="enter image description here"></p> <p>please help. Thank you. </p>
13,879,492
8
4
null
2012-12-13 14:00:53.53 UTC
33
2016-01-31 05:35:59.387 UTC
2012-12-14 09:26:58.573 UTC
null
849,123
null
849,123
null
1
45
android|android-layout|android-widget|onclicklistener|android-custom-view
65,641
<p>Interesting question. I tried some solutions and this is what I found that has the same result of what you are trying to achieve. The solution below resolves 2 problems:</p> <ol> <li>Custom shape as you presented it </li> <li>The top right side of the button shouldn't be clickable</li> </ol> <p>So this is the solution in 3 steps:</p> <h2>Step 1</h2> <p>Create two shapes.</p> <ul> <li><p>First simple rectangle shape for the button: <strong>shape_button_beer.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;gradient android:angle="90" android:endColor="#C5D9F4" android:startColor="#DCE5FD" /&gt; &lt;corners android:bottomLeftRadius="5dp" android:bottomRightRadius="5dp" android:topLeftRadius="5dp" &gt; &lt;/corners&gt; &lt;/shape&gt; </code></pre></li> <li><p>Second shape is used as mask for the top right side of the button: <strong>shape_button_beer_mask.xml</strong>. It is simple circle with black solid color.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" &gt; &lt;solid android:color="#000000" /&gt; &lt;/shape&gt; </code></pre></li> </ul> <h2>Step 2</h2> <p>In your main layout add the button by next approach:</p> <ul> <li>RelativeLayout is the container of this custom button</li> <li>First LinearLayout is the blue button with beer icon and text inside</li> <li>Second ImageView is the mask above the blue button. And here comes dirty trick: <ol> <li>Margins are negative to set the mask in the right place</li> <li>We define id to be able override on click (see step 3)</li> <li><code>android:soundEffectsEnabled="false"</code> - such that user will not feel that he pressed on something.</li> </ol></li> </ul> <p>The XML:</p> <pre><code> &lt;!-- Custom Button --&gt; &lt;RelativeLayout android:layout_width="120dp" android:layout_height="80dp" &gt; &lt;LinearLayout android:id="@+id/custom_buttom" android:layout_width="100dp" android:layout_height="100dp" android:background="@drawable/shape_button_beer" &gt; &lt;!-- Beer icon and all other stuff --&gt; &lt;ImageView android:layout_width="40dp" android:layout_height="40dp" android:layout_marginLeft="5dp" android:layout_marginTop="15dp" android:src="@drawable/beer_icon" /&gt; &lt;/LinearLayout&gt; &lt;ImageView android:id="@+id/do_nothing" android:layout_width="120dp" android:layout_height="100dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="-50dp" android:layout_marginTop="-50dp" android:background="@drawable/shape_button_beer_mask" android:soundEffectsEnabled="false" &gt; &lt;/ImageView&gt; &lt;/RelativeLayout&gt; &lt;!-- End Custom Button --&gt; </code></pre> <h2>Step 3</h2> <p>In your main activity you define on click events for both: button and the mask as follow:</p> <pre><code>LinearLayout customButton = (LinearLayout) findViewById(R.id.custom_buttom); customButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show(); } }); // Mask on click will do nothing ImageView doNothing = (ImageView) findViewById(R.id.do_nothing); doNothing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // DO NOTHING } }); </code></pre> <p>That's it. I know that is not a perfect solution but in your described use case it could help. I have tested it on my mobile and this is how it looks when you click on the blue area and nothing will happen on other areas:</p> <ul> <li><img src="https://i.stack.imgur.com/CeZGT.png" alt="enter image description here"></li> </ul> <p>Hope it helped somehow :)</p>
9,073,149
Difference between 'DateTime' and 'DateTimeOffset'
<p>What is difference between a <code>DateTime</code> and a <code>DateTimeOffset</code> object? </p> <p>And when should we use each one? </p> <p>In a web-application that may change the server's area, storing date and time. Which one is better, or is there any other suggestions? </p>
9,073,180
2
1
null
2012-01-31 01:08:33.557 UTC
1
2017-02-15 07:26:17.667 UTC
2014-12-09 07:41:59.863 UTC
null
15,541
null
645,167
null
1
45
c#|datetime|datetimeoffset
24,897
<p>DateTimeOffset Represents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC) it provides a greater degree of time zone awareness than the DateTime structure. See it here- <a href="http://msdn.microsoft.com/en-us/library/bb546101.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb546101.aspx</a>.</p>
9,225,567
How to print a int64_t type in C
<p>C99 standard has integer types with bytes size like int64_t. I am using Windows's <code>%I64d</code> format currently (or unsigned <code>%I64u</code>), like:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; int64_t my_int = 999999999999999999; printf(&quot;This is my_int: %I64d\n&quot;, my_int); </code></pre> <p>and I get this compiler warning:</p> <pre><code>warning: format ‘%I64d’ expects type ‘int’, but argument 2 has type ‘int64_t’ </code></pre> <p>I tried with:</p> <pre><code>printf(&quot;This is my_int: %lld\n&quot;, my_int); // long long decimal </code></pre> <p>But I get the same warning. I am using this compiler:</p> <pre><code>~/dev/c$ cc -v Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5664~89/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1 Thread model: posix gcc version 4.2.1 (Apple Inc. build 5664) </code></pre> <p>Which format should I use to print my_int variable without having a warning?</p>
9,225,648
7
1
null
2012-02-10 09:31:33.553 UTC
81
2022-04-28 02:16:41.157 UTC
2021-09-18 21:37:36.613 UTC
null
8,740,349
null
87,610
null
1
364
c|stdint
570,621
<p>For <code>int64_t</code> type:</p> <pre><code>#include &lt;inttypes.h&gt; int64_t t; printf("%" PRId64 "\n", t); </code></pre> <p>for <code>uint64_t</code> type:</p> <pre><code>#include &lt;inttypes.h&gt; uint64_t t; printf("%" PRIu64 "\n", t); </code></pre> <p>you can also use <code>PRIx64</code> to print in hexadecimal.</p> <p><a href="http://en.cppreference.com/w/cpp/types/integer" rel="noreferrer">cppreference.com has a full listing</a> of available macros for all types including <code>intptr_t</code> (<code>PRIxPTR</code>). There are separate macros for scanf, like <code>SCNd64</code>.</p> <hr> <p>A typical definition of PRIu16 would be <code>"hu"</code>, so implicit string-constant concatenation happens at compile time.</p> <p>For your code to be fully portable, you must use <code>PRId32</code> and so on for printing <code>int32_t</code>, and <code>"%d"</code> or similar for printing <code>int</code>.</p>
32,860,815
How to define dimens.xml for every different screen size in android?
<p>When supporting different screen sizes (densities) in <strong>Android</strong> often the focus is on creating different layouts for every possible screen. I.E.</p> <ul> <li>ldpi</li> <li>mdpi</li> <li>hdpi</li> <li>xhdpi</li> <li>xxhdpi</li> <li>xxxhdpi</li> </ul> <p>I designed a layout for an <strong>xhdpi</strong> screen as a reference, and defined it's <strong>dimensions</strong> in <strong><em>dimens.xml</em></strong>. Now <strong>I want to give support it to every possible screen size. How can I do that?</strong></p> <p>As far as I know, I can use <a href="http://androidpixels.net/" rel="noreferrer">this</a> tool to figure out the proper <strong><em>dimens.xml</em></strong> for other screen sizes and add it to my project. Is this the right way to do it in my situation?</p> <p>Another question, <strong>do I only need to create <em>dimens.xml</em> for above screen dimensions? If yes then what is <em><code>w820dp</code></em>?</strong></p> <p>Thanks for your help. I need to support <strong>phones only</strong> (not tablets or other devices).</p>
32,861,248
10
3
null
2015-09-30 07:57:20.57 UTC
134
2022-08-26 04:52:11.9 UTC
2017-09-05 16:47:20.307 UTC
null
1,105,214
null
834,239
null
1
161
android|android-layout|android-activity|android-screen-support
193,987
<p>You have to create <strong><em>Different values folder for different screens</em></strong> . Like </p> <pre><code>values-sw720dp 10.1” tablet 1280x800 mdpi values-sw600dp 7.0” tablet 1024x600 mdpi values-sw480dp 5.4” 480x854 mdpi values-sw480dp 5.1” 480x800 mdpi values-xxhdpi 5.5" 1080x1920 xxhdpi values-xxxhdpi 5.5" 1440x2560 xxxhdpi values-xhdpi 4.7” 1280x720 xhdpi values-xhdpi 4.65” 720x1280 xhdpi values-hdpi 4.0” 480x800 hdpi values-hdpi 3.7” 480x854 hdpi values-mdpi 3.2” 320x480 mdpi values-ldpi 3.4” 240x432 ldpi values-ldpi 3.3” 240x400 ldpi values-ldpi 2.7” 240x320 ldpi </code></pre> <p><a href="https://i.stack.imgur.com/MsXds.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MsXds.png" alt="enter image description here"></a></p> <p>For more information you may visit here</p> <blockquote> <p><a href="https://stackoverflow.com/questions/21280277/different-values-folders-in-android">Different values folders in android</a></p> <p><a href="http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html" rel="noreferrer">http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html</a></p> </blockquote> <p><strong>Edited</strong> By <strong><a href="https://stackoverflow.com/users/2185582/humblerookie">@humblerookie</a></strong></p> <p>You can make use of Android Studio plugin called <a href="https://plugins.jetbrains.com/androidstudio/plugin/9349-dimenify" rel="noreferrer">Dimenify</a> to auto generate dimension values for other pixel buckets based on custom scale factors. Its still in beta, be sure to notify any issues/suggestions you come across to the developer.</p>
45,955,186
Convert numpy array type and values from Float64 to Float32
<p>I am trying to convert threshold array(pickle file of isolation forest from scikit learn) of type from Float64 to Float32 </p> <pre><code>for i in range(len(tree.tree_.threshold)): tree.tree_.threshold[i] = tree.tree_.threshold[i].astype(np.float32) </code></pre> <p>​ Then Printing it</p> <pre><code>for value in tree.tree_.threshold[:5]: print(type(value)) print(value) </code></pre> <p>the output i am getting is :</p> <pre><code>&lt;class 'numpy.float64'&gt; 526226.0 &lt;class 'numpy.float64'&gt; 91.9514312744 &lt;class 'numpy.float64'&gt; 3.60330319405 &lt;class 'numpy.float64'&gt; -2.0 &lt;class 'numpy.float64'&gt; -2.0 </code></pre> <p>I am not getting a proper conversion to Float32. I want to convert values and their type to Float32, Did anybody have any workaround this ?</p>
47,173,355
3
3
null
2017-08-30 08:09:47.493 UTC
4
2018-04-08 00:04:02.16 UTC
null
null
null
null
6,070,611
null
1
45
python|numpy|scikit-learn|pickle
153,002
<blockquote> <p>Actually i tried hard but not able to do as the 'sklearn.tree._tree.Tree' objects is not writable.</p> <p>It is causing a precision issue while generating a PMML file, so i raised a bug over there and they gave an updated solution for it by not converting it in to the Float64 internally.</p> </blockquote> <p>For more info, you can follow this link: <a href="https://github.com/jpmml/jpmml-converter/issues/6" rel="nofollow noreferrer">Precision Issue</a></p>
45,980,173
React: Axios Network Error
<p>This is my first time using axios and I have encountered an error. </p> <pre><code> axios.get( `http://someurl.com/page1?param1=1&amp;param2=${param2_id}` ) .then(function(response) { alert(); }) .catch(function(error) { console.log(error); }); </code></pre> <p>With the right url and parameters, when I check network requests I indeed get the right answer from my server, but when I open console I see that it didn't call the callback, but instead it caught an error.</p> <blockquote> <p>Error: Network Error Stack trace: createError@<a href="http://localhost:3000/static/js/bundle.js:2188:15" rel="noreferrer">http://localhost:3000/static/js/bundle.js:2188:15</a> handleError@<a href="http://localhost:3000/static/js/bundle.js:1717:14" rel="noreferrer">http://localhost:3000/static/js/bundle.js:1717:14</a></p> </blockquote>
47,317,506
20
6
null
2017-08-31 11:16:03.667 UTC
8
2022-08-11 17:15:46.883 UTC
null
null
null
null
6,008,453
null
1
60
javascript|reactjs|axios
205,722
<h1>If Creating an API Using NodeJS</h1> <p><hr> Your Express app needs to use CORS (Cross-Origin Resource Sharing). Add the following to your server file:</p> <pre class="lang-js prettyprint-override"><code>// This should already be declared in your API file var app = express(); // ADD THIS var cors = require('cors'); app.use(cors()); </code></pre> <p>For fuller understanding of CORS, please read the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" rel="noreferrer">Mozilla Documentation on CORS</a>. </p>
24,480,069
Google In-App billing, IllegalArgumentException: Service Intent must be explicit, after upgrading to Android L Dev Preview
<p>My in-app billing code was working fine until I upgraded to the Android L Dev Preview. Now I get this error when my app starts. Does anyone know what's changed about L that causes this or how I should change my code to fix this?</p> <pre><code>android { compileSdkVersion 'android-L' buildToolsVersion '20' defaultConfig { minSdkVersion 13 targetSdkVersion 'L' ... ... compile 'com.google.android.gms:play-services:5.+' compile 'com.android.support:support-v13:21.+' compile 'com.android.support:appcompat-v7:21.+' ... ... </code></pre> <p>The error when the app starts:</p> <pre><code>06-29 16:22:33.281 5719-5719/com.tbse.wnswfree D/AndroidRuntime﹕ Shutting down VM 06-29 16:22:33.284 5719-5719/com.tbse.wnswfree E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.tbse.wnswfree, PID: 5719 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tbse.wnswfree/com.tbse.wnswfree.InfoPanel}: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.billing.InAppBillingService.BIND } at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2317) at android.app.ActivityThread.access$800(ActivityThread.java:143) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5070) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:836) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631) Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.billing.InAppBillingService.BIND } at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1603) at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1702) at android.app.ContextImpl.bindService(ContextImpl.java:1680) at android.content.ContextWrapper.bindService(ContextWrapper.java:528) at com.tbse.wnswfree.util.IabHelper.startSetup(IabHelper.java:262) at com.tbse.wnswfree.InfoPanel.onStart(InfoPanel.java:709) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1217) at android.app.Activity.performStart( Activity.java:5736) at android.app.ActivityThread.performLaunchActivity( ActivityThread.java:2218) at android.app.ActivityThread.handleLaunchActivity( ActivityThread.java:2317) at android.app.ActivityThread.access$800( ActivityThread.java:143) at android.app.ActivityThread$H.handleMessage( ActivityThread.java:1258) ... </code></pre> <p>           </p> <p>Line 709 in InfoPanel.java:</p> <pre><code> mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { @Override public void onIabSetupFinished(IabResult result) { ... </code></pre>
27,027,371
10
3
null
2014-06-29 20:39:57.56 UTC
26
2017-12-13 20:08:34.437 UTC
2014-07-01 18:39:16.39 UTC
null
1,167,780
null
905,089
null
1
58
android|android-intent|in-app-billing|illegalargumentexception|android-5.0-lollipop
26,546
<p>I had the same problem and explicitly setting the package solved it. Similar to Aleksey's answer, but simpler:</p> <pre><code>Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); // This is the key line that fixed everything for me intent.setPackage("com.android.vending"); getContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); </code></pre>
45,187,785
React Native - How to make image width 100 percent and vertical top?
<p>I am newbie at react-native. What I want to do is that fit an image in device and keep the ratio of image. Simply I want to make <code>width : 100%</code></p> <p>I searched how to make it and seems <code>resizeMode = 'contain'</code> is good for that.</p> <p>However, since I used <code>resizeMode = 'contain'</code>, the image keeps the position vertically centered which I don't want. I want it to be vertically top.</p> <p>I tried to use a plug-in such as <a href="https://www.npmjs.com/package/react-native-fit-image" rel="noreferrer">react-native-fit-image</a> but no luck.</p> <p>And I found <a href="https://facebook.github.io/react-native/docs/images.html#why-not-automatically-size-everything" rel="noreferrer">the reason why the image is not sizing automatically</a>. But still I have no idea how to make it.</p> <p>So, my question is what is the best way to deal with this situation?</p> <p>Do I have to manually put <code>width, height</code> size each images?</p> <p>I want :</p> <ul> <li>Keep image's ratio.</li> <li>Vertically top positioned.</li> </ul> <p>React native test code :</p> <p><a href="https://snack.expo.io/ry3_W53rW" rel="noreferrer">https://snack.expo.io/ry3_W53rW</a></p> <p>Eventually what I want to make :</p> <p><a href="https://jsfiddle.net/hadeath03/mb43awLr/" rel="noreferrer">https://jsfiddle.net/hadeath03/mb43awLr/</a></p> <p>Thanks.</p>
45,188,904
6
1
null
2017-07-19 10:25:46.317 UTC
10
2022-07-20 06:27:39.307 UTC
null
null
null
null
2,805,530
null
1
45
react-native|image-resizing
83,640
<p>The image is vertically centered, because you added <code>flex: 1</code> to the style property. Don't add flex: 1, because that will fill the image to its parent, which is not desired in this case.</p> <p>You should always add a height and width on an image in React Native. In case the image is always the same, you can use <code>Dimensions.get('window').width</code> to calculate the size the image should be. For example, if the ratio is always 16x9, the height is 9/16th of the width of the image. The width equals device width, so:</p> <pre class="lang-js prettyprint-override"><code>const dimensions = Dimensions.get('window'); const imageHeight = Math.round(dimensions.width * 9 / 16); const imageWidth = dimensions.width; return ( &lt;Image style={{ height: imageHeight, width: imageWidth }} /&gt; ); </code></pre> <p><strong>Note: When using an implementation like this, your image will not automatically resize when rotating your device, using split screen, etc. You will have to take care of those actions as well if you support multiple orientations...</strong></p> <p>In case the ratio is not the same, dynamically change the 9 / 16 by the ratio for each different image. If you don't really bother the image is a little bit cropped, you can use cover mode with a fixed height as well: (<a href="https://snack.expo.io/rk_NRnhHb" rel="noreferrer">https://snack.expo.io/rk_NRnhHb</a>)</p> <pre class="lang-js prettyprint-override"><code>&lt;Image resizeMode={'cover'} style={{ width: '100%', height: 200 }} source={{uri: temp}} /&gt; </code></pre>
45,103,775
Hosted VS2017 agent build master.dacpac does not exist
<p>My solution created with VS2017 Professional contains an SQL Server Database Project that references the master database. When using the Hosted VS2017 agent to build my solution in Visual Studio Team Services I'm getting the errors below:</p> <blockquote> <p>2017-07-14T12:44:17.8387743Z ##[error]C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets(559,5): Error SQL72027: File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\SQLDB\Extensions\SqlServer\110\SqlSchemas\master.dacpac" does not exist. 2017-07-14T12:44:17.8397816Z C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets(559,5): Build error SQL72027: File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\SQLDB\Extensions\SqlServer\110\SqlSchemas\master.dacpac" does not exist. [d:\a\3\s\Main\ItAsset.Database\ItAsset.Database.sqlproj]</p> </blockquote> <p>How can I fix this and get my solution to build in VSTS?</p>
46,823,232
5
2
null
2017-07-14 13:04:19.603 UTC
6
2021-10-19 11:20:14.22 UTC
null
null
null
null
1,108,740
null
1
29
visual-studio-2017|sql-server-data-tools|azure-pipelines
12,483
<p>I just got bit by this in a multi-developer situation. It seems to happen in VS2017 SSDT projects where the developer who checked in the code originally had their installation of Visual Studio in a different path than you, or another instance of Visual Studio. For example if developer A installed to defaults on C:\ but developer B installed his VS2017 to E:\ drive, whoever creates the reference to Master will work, the other will not find the dacpac file.</p> <p>Looking in the .sqlproj file, you'll likely find this reference to the Master database:</p> <pre><code> &lt;ArtifactReference Include="C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\SQLDB\Extensions\SqlServer\130\SqlSchemas\master.dacpac"&gt; &lt;HintPath&gt;$(DacPacRootPath)\Extensions\Microsoft\SQLDB\Extensions\SqlServer\130\SqlSchemas\master.dacpac&lt;/HintPath&gt; </code></pre> <p>Note: the <code>&lt;HintPath&gt;</code> is correct, but the <code>Include="</code> is a hard coded path. It seems that the hint path is not followed as it normally should be. To fix your problem, try copying the contents of the HintPath element to the Include attribute. Leave the HintPath as it is.</p> <pre><code>&lt;ArtifactReference Include="$(DacPacRootPath)\Extensions\Microsoft\SQLDB\Extensions\SqlServer\130\SqlSchemas\master.dacpac"&gt; </code></pre>
956,030
How to edit default.aspx on SharePoint site without SharePoint Designer
<p>On several occations, I have faced the situation that the default.aspx page on a Site doesn't work. More specifically, a reference to a WebPart and/or Control is throwing a error because the assembly is not found. Fine, you just fire up the dreaded SharePoint Designer and remove the dependency line. However, if I wanted to use this method when not having SharePoint Designer, how could this be done?</p> <p>EDIT: Removing the web part using the "?contents=1" web part management page didn't help in my case. The &lt;%@Register tag was still there and had to be removed using SharePoint Designer.</p>
961,755
5
1
null
2009-06-05 14:04:55.347 UTC
3
2014-12-19 21:49:55.947 UTC
2009-06-05 14:56:20.207 UTC
null
3,584
null
3,584
null
1
12
sharepoint|sharepoint-designer
108,237
<p>Go to view all content of the site (<a href="http://yourdmain.sharepoint/sitename/_layouts/viewlsts.aspx" rel="noreferrer">http://yourdmain.sharepoint/sitename/_layouts/viewlsts.aspx</a>). Select the document library "Pages" (the "Pages" library are named based on the language you created the site in. I.E. in norwegian the library is named "Sider"). Download the default.aspx to you computer and fix it (remove the web part and the &lt;%Register tag). Save it and upload it back to the library (remember to check in the file).</p> <p><strong>EDIT:</strong></p> <p>ahh.. you are not using a publishing site template. Go to site action -> site settings. Under "site administration" select the menu "content and structure" you should now see your default.aspx page. But you cant do much with it...(delete, copy or move) </p> <p><strong>workaround</strong>: Enable publishing feature to the root web. Add the fixed default.aspx file to the Pages library and change the welcome page to this. Disable the publishing feature (this will delete all other list create from this feature but not the Pages library since one page is in use.). You will now have a new default.aspx page for the root web but the url is changed from sitename/default.aspx to sitename/Pages/default.aspx. </p> <p><strong>workaround II</strong> Use a feature to change the default.aspx file. The solution is explained here: <a href="http://wssguy.com/blogs/dan/archive/2008/10/29/how-to-change-the-default-page-of-a-sharepoint-site-using-a-feature.aspx" rel="noreferrer">http://wssguy.com/blogs/dan/archive/2008/10/29/how-to-change-the-default-page-of-a-sharepoint-site-using-a-feature.aspx</a></p>
1,004,082
Theorem numbering in LaTeX
<p>I have a problem with theorem numbering in LaTeX. I can make it number by subsection, e.g</p> <blockquote> <p>Theorem 1.2.1</p> </blockquote> <p>for the first theorem in the second subsection of the first section. But I need it to show me only the numbers of the subsection and the theorem, but not the section number, like this:</p> <blockquote> <p>Theorem 2.1</p> </blockquote> <p>I use</p> <pre><code>\newtheorem{thm}{Theorem}[subsection] </code></pre> <p>for the numbering.</p>
1,004,231
6
3
null
2009-06-16 21:38:29.697 UTC
5
2018-09-26 16:58:22.663 UTC
null
null
null
null
92,821
null
1
8
latex
58,792
<p>Putting the following code in the preamble seems to have the desired effect:</p> <pre><code>\usepackage{amsthm} \newtheorem{thm}{Theorem}[subsection] \renewcommand{\thethm}{\arabic{subsection}.\arabic{thm}} </code></pre> <p>I don't understand why you want this particular theorem numbering system, but the code does what you want: <img src="https://i.stack.imgur.com/Ebs5x.png" alt="LaTeX output"></p>
316,200
Which C++ Library for CGI Programming?
<p>I'm looking at doing some work (for fun) in a compiled language to run some simple tests and benchmarks against php.</p> <p>Basically I'd like to see what other people use for C++ CGI programming. (Including backend database, like mysql++ or something else)</p>
316,245
6
0
null
2008-11-25 02:38:01.577 UTC
10
2014-08-14 18:02:05.76 UTC
null
null
null
Issac Kelly
144
null
1
20
c++|cgi
20,375
<p>I'm not sure exactly what you're looking for, but there is a C++ web framework called wt (pronounced "witty"). It's been kept pretty much up to date and if you want robust C++ server-side code, this is probably what you're looking for.</p> <p>You can check it out and read more at the <a href="http://www.webtoolkit.eu/wt/" rel="noreferrer">wt homepage</a>.</p> <p>P.S. You may have some trouble installing wt if you don't have experience with *nix or C++ libraries. There are walkthroughs but since frameworks like these are the road less traveled, expect to hit a few bumps.</p>
195,768
In search of JavaScript Month Picker
<p>I'm in search of a JavaScript month selection tool. I'm already using jQuery on the website, so if it were a jQuery plugin, that would fit nicely. I'm open to other options, as well.</p> <p>Basically, I'm after a simplified version of the <a href="http://docs.jquery.com/UI/Datepicker" rel="noreferrer">jQuery UI Date Picker</a>. I don't care about the day of the month, just the month and year. Using the Date Picker control feels like overkill and a kludge. I know I could just use a pair of select boxes, but that feels cluttered, and then I also need a confirmation button.</p> <p>I'm envisioning a grid of either two rows of six columns, or three rows of four columns, for month selection, and current and future years across the top. (Maybe the ability to list a few years? I can't see anyone ever needing to go more than a year or two ahead, so if I could list the current and next two years, that would be swell.)</p> <p>It's really just a dumbed down version of the DatePicker. Does something like this exist?</p>
19,389,060
6
5
null
2008-10-12 17:46:47.58 UTC
12
2016-02-20 13:36:31.213 UTC
2016-02-20 13:36:31.213 UTC
Adam Tuttle
1,709,587
Adam Tuttle
751
null
1
49
javascript|jquery
63,545
<p>To anyone <em>still</em> looking forward into this (as I was), here is an beautiful, easy to use, jQuery UI compatible, well documented, tested alternative:</p> <p><img src="https://i.stack.imgur.com/o8h3F.gif" alt="Month picker example"></p> <p>Its default usage is simple as doing the following:</p> <pre><code>$("input[type='month']").MonthPicker(); </code></pre> <ul> <li><a href="https://github.com/KidSysco/jquery-ui-month-picker">GitHub</a></li> <li><a href="http://jsfiddle.net/kidsysco/JeZap/">Fiddle with Examples and tests</a></li> </ul>
17,637,775
How do I write a toString() method
<p>How would I write a toString() method that prints name and computePay with 2 decimal places for the three employees? The program was working (printing name and weeksPay to command line) before I added the StringBuilder. Any help is appreciated.</p> <pre><code>import javax.swing.JOptionPane; public class TestPayroll { public static void main(String[] args) { Payroll employee1 = new Payroll("Tiny Tim", 100.25, 40); Payroll employee2 = new Payroll("Brad Pitt", 150.50, 10); Payroll employee3 = new Payroll("Madonna", 124.24, 20); StringBuilder sb = new StringBuilder(); String toDisplay=sb.toString(); sb.append(String.format("\n", employee1.getName(), employee1.getComputePay())); sb.append(String.format("\n", employee2.getName(), employee2.getComputePay())); JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE); } } public class Payroll { public static void main(String[] args) { } private String name; private double payRate; private double hrsWorked; private double computePay; //default constructor public Payroll() { this.name = name; this.payRate = payRate; this.hrsWorked = hrsWorked; this.computePay = computePay; } //Payroll constructor public Payroll(String name, double payRate, double hrsWorked) { this.name = name; this.payRate = payRate; this.hrsWorked = hrsWorked; } //return name public String getName() { return name; } //set name public void setName(String name) { this.name = name; } //return pay rate public double getPayRate() { return payRate; } //set pay rate public void setPayRate(double payRate) { this.payRate = payRate; } //return hours worked for the week public double getHrsWorked() { return hrsWorked; } //set hours worked for the week public void setHrsWorked(double hrsWorked) { this.hrsWorked = hrsWorked; } //find week's pay public double getComputePay() { double computePay = payRate * hrsWorked; return computePay; } } </code></pre>
17,637,856
4
6
null
2013-07-14 08:31:02.273 UTC
1
2013-07-14 18:21:39.167 UTC
2013-07-14 08:47:54.333 UTC
null
1,055,034
null
1,055,034
null
1
2
java|tostring
41,791
<p>To formats decimal numbers, you can use <a href="http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html" rel="nofollow"><strong>java.text.DecimalFormat</strong></a>, define it in the class level as a <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html" rel="nofollow"><strong>class member</strong></a> so that it could share it's <em>behavior</em> for all objects of <code>Payroll</code> as @Multithreader mentioned it in the comment, this will be your <code>toString()</code> method:</p> <pre><code> private static DecimalFormat df = new DecimalFormat("#.##"); //...... @Override public String toString(){ return "Name: "+getName()+ "\nCompute Pay: "+df.format(getComputePay())+"\n"; } </code></pre> <p>Call the method like this:</p> <pre><code>System.out.println(employee1.toString()); </code></pre> <p>I prefer to use <a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html" rel="nofollow"><strong>java.util.List</strong></a> as it's reduce a lot of codes:</p> <pre><code>public static void main(String[] args) { List &lt;Payroll&gt; employes = new ArrayList&lt;&gt;(); employes.add( new Payroll("Tiny Tim", 100.2534, 40.87876)); employes.add( new Payroll("Brad Pitt", 150.50, 10)); employes.add( new Payroll("Madonna", 124.24, 20)); for(Payroll p :employes){ System.out.println(p.toString()+"\n"); } } </code></pre>
31,182,486
Unable to load Android APK in ARC Welder
<p>I would like to ask for your assistance in loading my APK on ARCWelder on my Chromebook. I have successfully installed ARC Welder from this <a href="https://chrome.google.com/webstore/detail/arc-welder/emfinbmielocnlhgmfkkmkngdoccbadn" rel="noreferrer">link</a> but when I tried to load my APK, it just keeps on loading like the image below.</p> <p><img src="https://i.stack.imgur.com/KFoHi.png" alt="enter image description here"></p> <p>I tried reinstalling ARC Welder multiple times and encountered the same thing. I tried different APKs and no luck as well.</p> <p>Thanks for your help in advance.</p>
31,981,045
5
2
null
2015-07-02 10:48:54.723 UTC
7
2018-08-15 10:12:57.357 UTC
null
null
null
null
703,252
null
1
19
android|google-chrome-arc
56,766
<p>I filed a <a href="https://code.google.com/p/chromium/issues/detail?id=508795" rel="nofollow">bug report</a> for this and found out that it is a bug on <strong>Chrome OS 43's</strong> time zone. They fixed it on <strong>Chrome OS 44</strong>. So simply update your OS to 44.</p> <p>In case <strong>Chrome OS 43</strong> is the most updated version, try to change your download channel from <strong>stable</strong> to <strong>beta</strong> under <strong>Settings</strong>.</p> <p>Hope this may help somebody in the future. Thanks!</p>
31,133,249
Searchable select option
<p>Is there anyway to make select option as selectable/auto complete/searchable? unfortunately i cannot change the form. so i cannot change the select option into text field. but i be able to access the css and javascript..</p> <p>Below is the select option.</p> <pre><code>&lt;select name="siteID" id="siteID" class="abcd" style="width:100%" /&gt; &lt;option value='0' selected='true'&gt; Not associated to any Circuit ID &lt;/option&gt; &lt;option value='2101' &gt; 1007345136 &lt;/option&gt; &lt;option value='2102' &gt; 1007921321 &lt;/option&gt; &lt;option value='2103' &gt; 1007987235 &lt;/option&gt; &lt;option value='2407' &gt; 132 &lt;/option&gt; &lt;option value='2408' &gt; 141 &lt;/option&gt; &lt;option value='2409' &gt; 142 &lt;/option&gt; &lt;option value='2410' &gt; 145 &lt;/option&gt; &lt;option value='2701' &gt; 225 &lt;/option&gt; &lt;option value='2702' &gt; 248 &lt;/option&gt; &lt;option value='2703' &gt; 251 &lt;/option&gt; &lt;option value='2704' &gt; 254 &lt;/option&gt; &lt;option value='2705' &gt; 264 &lt;/option&gt; &lt;option value='1804' &gt; 27 &lt;/option&gt; &lt;option value='2706' &gt; 274 &lt;/option&gt; &lt;option value='2707' &gt; 310 &lt;/option&gt; &lt;option value='2708' &gt; 311 &lt;/option&gt; &lt;option value='3001' &gt; 333 &lt;/option&gt; &lt;option value='2401' &gt; 38 &lt;/option&gt; &lt;option value='2402' &gt; 64 &lt;/option&gt; &lt;option value='2403' &gt; 68 &lt;/option&gt; &lt;option value='2404' &gt; 69 &lt;/option&gt; &lt;option value='2405' &gt; 76 &lt;/option&gt; &lt;option value='2406' &gt; 81 &lt;/option&gt; &lt;option value='2411' &gt; abc123post &lt;/option&gt; &lt;option value='3301' &gt; circuit id 50 &lt;/option&gt; &lt;option value='2105' &gt; fadhil &lt;/option&gt; &lt;option value='2104' &gt; faisal &lt;/option&gt; &lt;option value='3002' &gt; IPEN - SITE TEST &lt;/option&gt; &lt;option value='3601' &gt; Manual Circuit ID &lt;/option&gt; &lt;option value='3302' &gt; new circuit id fadhil &lt;/option&gt; &lt;option value='1809' &gt; try iframe &lt;/option&gt; &lt;/select&gt; </code></pre> <p>is there any javascript/jquery and css that can transform it as serchable.</p>
31,133,634
7
3
null
2015-06-30 08:28:38.057 UTC
2
2022-05-05 07:38:52.353 UTC
null
null
null
null
2,748,728
null
1
2
javascript|jquery|html|select|drop-down-menu
41,482
<p>You may consider using a jQuery plugin called <a href="https://select2.github.io/" rel="noreferrer">Select2</a>. You <strong>cannot</strong> self-close a <code>&lt;select&gt;</code> tag! You can just use it this way:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function () { $("select").select2(); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"&gt;&lt;/script&gt; &lt;select name="siteID" id="siteID" class="abcd" style="width:100%"&gt; &lt;option value='0' selected='true'&gt; Not associated to any Circuit ID &lt;/option&gt; &lt;option value='2101' &gt; 1007345136 &lt;/option&gt; &lt;option value='2102' &gt; 1007921321 &lt;/option&gt; &lt;option value='2103' &gt; 1007987235 &lt;/option&gt; &lt;option value='2407' &gt; 132 &lt;/option&gt; &lt;option value='2408' &gt; 141 &lt;/option&gt; &lt;option value='2409' &gt; 142 &lt;/option&gt; &lt;option value='2410' &gt; 145 &lt;/option&gt; &lt;option value='2701' &gt; 225 &lt;/option&gt; &lt;option value='2702' &gt; 248 &lt;/option&gt; &lt;option value='2703' &gt; 251 &lt;/option&gt; &lt;option value='2704' &gt; 254 &lt;/option&gt; &lt;option value='2705' &gt; 264 &lt;/option&gt; &lt;option value='1804' &gt; 27 &lt;/option&gt; &lt;option value='2706' &gt; 274 &lt;/option&gt; &lt;option value='2707' &gt; 310 &lt;/option&gt; &lt;option value='2708' &gt; 311 &lt;/option&gt; &lt;option value='3001' &gt; 333 &lt;/option&gt; &lt;option value='2401' &gt; 38 &lt;/option&gt; &lt;option value='2402' &gt; 64 &lt;/option&gt; &lt;option value='2403' &gt; 68 &lt;/option&gt; &lt;option value='2404' &gt; 69 &lt;/option&gt; &lt;option value='2405' &gt; 76 &lt;/option&gt; &lt;option value='2406' &gt; 81 &lt;/option&gt; &lt;option value='2411' &gt; abc123post &lt;/option&gt; &lt;option value='3301' &gt; circuit id 50 &lt;/option&gt; &lt;option value='2105' &gt; fadhil &lt;/option&gt; &lt;option value='2104' &gt; faisal &lt;/option&gt; &lt;option value='3002' &gt; IPEN - SITE TEST &lt;/option&gt; &lt;option value='3601' &gt; Manual Circuit ID &lt;/option&gt; &lt;option value='3302' &gt; new circuit id fadhil &lt;/option&gt; &lt;option value='1809' &gt; try iframe &lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p>
13,291,492
using this.addClass (Jquery)
<p>I am trying this.addclass in jquery to add a class to a DIV, that could be unknown. Can this be solved in this way? </p> <pre><code>&lt;style&gt;.classOne { font-size:24px; color:#009900;}&lt;/style&gt; &lt;script&gt; function hello() { alert(); $(this).addClass('classOne'); } &lt;/script&gt; &lt;div class="something" onclick="hello();"&gt; Test information &lt;/div&gt; </code></pre>
13,291,631
4
1
null
2012-11-08 14:58:41.793 UTC
1
2021-09-23 16:16:16.653 UTC
2012-11-08 15:15:23.23 UTC
null
1,808,839
null
1,809,631
null
1
3
javascript|jquery
56,220
<p>Avoid inline javascript whenever you can, and do something like this instead :</p> <pre><code>&lt;style&gt;.classOne { font-size:24px; color:#009900;}&lt;/style&gt; &lt;script type="text/javascript"&gt; $(function() { $('.something').on('click', function() { alert('hello'); $(this).addClass('classOne'); }); }); &lt;/script&gt; &lt;div class="something"&gt; Test information &lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/H7Eqq/"><strong>FIDDLE</strong></a></p>
49,147,369
Moving from EF6 to EF Core 2.0
<p>I just started moving my MVC5 project with EF6x to MVC Core and EF Core but have a big problem with my entities configuration's. How you can migrate a EF6 Fluent configure to EF core? <br> I need a guide with sample if possible. <br></p> <p>Here is one of my mapping classes and my try</p> <p><strong>EntityMappingConfiguratuin</strong></p> <pre><code>public interface IEntityMappingConfiguration { void Map(ModelBuilder b); } public interface IEntityMappingConfiguration&lt;T&gt; : EntityMappingConfiguration where T : class { void Map(EntityTypeBuilder&lt;T&gt; builder); } public abstract class EntityMappingConfiguration&lt;T&gt; : EntityMappingConfiguration&lt;T&gt; where T : class { public abstract void Map(EntityTypeBuilder&lt;T&gt; b); public void Map(ModelBuilder b) { Map(b.Entity&lt;T&gt;()); } } public static class ModelBuilderExtenions { private static IEnumerable&lt;Type&gt; GetMappingTypes(this Assembly assembly, Type mappingInterface) { return assembly.GetTypes().Where(x =&gt; !x.IsAbstract &amp;&amp; x.GetInterfaces().Any(y =&gt; y.GetTypeInfo().IsGenericType &amp;&amp; y.GetGenericTypeDefinition() == mappingInterface)); } public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly) { var mappingTypes = assembly.GetMappingTypes(typeof(IEntityMappingConfiguration&lt;&gt;)); foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast&lt;IEntityMappingConfiguration&gt;()) { config.Map(modelBuilder); } } } </code></pre> <p><strong>DbContext</strong></p> <pre><code>public class CommerceServiceDbContext : AbpDbContext { public CommerceServiceDbContext(DbContextOptions&lt;CommerceServiceDbContext&gt; options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.AddEntityConfigurationsFromAssembly(GetType().Assembly); } } </code></pre> <p><strong>Simple old configuration</strong></p> <pre><code>public partial class AffiliateMap : EntityMappingConfiguration&lt;Affiliate&gt; { public override void Map(EntityTypeBuilder&lt;Affiliate&gt; b) { b.ToTable("Affiliate"); b.HasKey(a =&gt; a.Id); b.HasRequired(a =&gt; a.Address).WithMany().HasForeignKey(x =&gt; x.AddressId).WillCascadeOnDelete(false); } } </code></pre> <p><strong>My Try</strong></p> <pre><code>public partial class AffiliateMap : EntityMappingConfiguration&lt;Affiliate&gt; { public override void Map(EntityTypeBuilder&lt;Affiliate&gt; b) { b.ToTable("Affiliate"); b.HasKey(a =&gt; a.Id); b.HasOne(a =&gt; a.Address) .WithMany().HasForeignKey(x =&gt; x.AddressId).IsRequired().OnDelete(DeleteBehavior.Restrict); } } </code></pre> <p>I've done this using Google Search and Microsoft Documentation. But I'm not sure of my work. Since I have +100 configure classes, I'll ask you before continuing. I apologize if the contents of my question are not compatible with the terms and conditions of the site.</p>
49,148,553
1
10
null
2018-03-07 08:36:23.083 UTC
8
2018-03-13 18:04:21.373 UTC
2018-03-13 18:04:21.373 UTC
null
475,031
null
6,946,375
null
1
13
c#|entity-framework-core|ef-fluent-api|ef-core-2.0
10,347
<p>I found a good article about moving to EF core. I want share that and keeping this question for starters like me.</p> <p><strong>Code Updates</strong> <br> Namespace <code>System.Data.Entity</code> replaced by <code>Microsoft.EntityFrameworkCore</code><br> <code>HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)</code> replaced by <code>ValueGeneratedNever();</code><br> The base constructor of <code>DbContext</code> doesn't have a single string parameter for the connection string. We now have to inject the <code>DbContextOptions</code><br> <code>OnModelCreating(DbModelBuilder modelBuilder)</code> becomes <code>OnModelCreating(ModelBuilder modelBuilder)</code>. Simple change, but change all the same<br> <code>modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());</code> is no longer available which means that <code>EntityTypeConfiguration</code> is also not available, so I had to move all my entity configuration to <code>OnModelCreating</code><br> <code>((IObjectContextAdapter)context).ObjectContext.ObjectMaterialized</code> is no longer available. I was using that to extend the <code>DbContext</code> to convert all dates in an out to Utc. I haven't found a replacement for that yet.<br> <code>ComplexType</code> is no longer available. I had to change the model structure a bit to accomodate this.<br> <code>MigrateDatabaseToLatestVersion</code> is no longer available so I had to add the below to my startup.cs<br></p> <pre><code>using (var serviceScope = app.ApplicationServices.GetRequiredService&lt;IServiceScopeFactory&gt;().CreateScope()) { serviceScope.ServiceProvider.GetService&lt;SbDbContext&gt;().Database.Migrate(); } </code></pre> <p><code>WillCascadeOnDelete(false)</code> becomes <code>OnDelete(DeleteBehavior.Restrict)</code><br> <code>HasOptional</code> is no longer relevant as per post<br> <code>IDbSet</code> becomes <code>DbSet</code><br> <code>DbSet&lt;T&gt;.Add()</code> no longer returns <code>T</code> but <code>EntityEntry&lt;T&gt;</code></p> <pre><code>var entry = context.LearningAreaCategories.Add(new LearningAreaCategory()); //that's if you need to use the entity afterwards var entity = entry.Entity; </code></pre> <p><code>IQueryable&lt;T&gt;.Include(Func&lt;&gt;)</code> now returns <code>IIncludableQueryable&lt;T,Y&gt;</code> instead of <code>IQueryable&lt;T&gt;</code>, same applies for <code>OrderBy</code>. What I did was moving all the includes and orderbys to the end.</p> <p>Source: <a href="https://passos.com.au/moving-from-ef6-to-ef-core/" rel="noreferrer">Moving from EF6 to EF Core</a></p>
37,622,606
NodeJS - nodemon not restarting my server
<p>I installed NodeJS (4.4.5) and then proceed to install nodemon (1.9.2) as well, I follow all the instrucctions of instalation (npm install -g nodemon)</p> <p>I created a new folder, inside I have my <strong>server.js</strong> with some basic code:</p> <pre><code>var http = require('http'); http.createServer(function (request, response){ response.writeHead( 200, {'Content-Type': 'text/plain'} ); response.write("Hello world"); response.end(); }).listen(3000, 'localhost'); console.log('http://localhost:3000'); </code></pre> <p>So when I run in my console "nodemon server.js" I get this:</p> <pre><code>[nodemon] 1.9.2 [nodemon] to restart at any time, enter `rs` [nodemon] watching: *.* [nodemon] starting `node server.js` http://localhost:3000 </code></pre> <p>(Which means that is running fine)</p> <p>But when I make some changes in my server.js, It doesn't restart the server</p> <p>What could be the issue?</p>
41,567,287
11
3
null
2016-06-03 20:10:47.237 UTC
3
2022-07-23 23:50:10.647 UTC
null
null
null
null
5,701,777
null
1
29
javascript|node.js|npm|nodemon
30,391
<p>In some networked environments (such as a container running nodemon reading across a mounted drive), you will need to use the legacyWatch: true which enabled Chokidar's polling.</p> <p>Via the CLI, use either --legacy-watch or -L for short:</p> <blockquote> <p>nodemon -L</p> </blockquote>
35,590,359
Should paging be zero indexed within an API?
<p>When implementing a Rest API, with parameters for paging, should paging be zero indexed or start at 1. The parameters would be Page, and PageSize. </p> <p>For me, it makes sense to start at 1, since we are talking about pages</p>
35,598,484
1
3
null
2016-02-23 23:29:04.84 UTC
4
2016-06-22 11:59:40.423 UTC
null
null
null
null
1,535,911
null
1
39
api|rest|api-design
9,753
<p>There's no standard for it. Just have a look around: there are hundreds of thousands of APIs using different approaches. </p> <p>Most of APIs I know use one of the following approaches for pagination:</p> <ul> <li><code>offset</code> and <code>limit</code> or</li> <li><code>page</code> and <code>size</code></li> </ul> <p>Both can be <code>0</code> or <code>1</code> indexed. Which is better? That's up to you. </p> <p>Just pick the one that fits your needs and <strong>document it properly</strong>.</p> <hr> <p>Additionally, you could provide some links in the response payload to make the navigation easier between the pages.</p> <p>Consider, for example, you are reading data from page 2. So, provide a link for the previous page (page 1) and for the next page (page 3):</p> <pre class="lang-json prettyprint-override"><code>{ "data": [ ... ], "paging": { "previous": "http://api.example.com/foo?page=1&amp;size=10", "next": "http://api.example.com/foo?page=3&amp;size=10" } } </code></pre> <p>And remember, always make an API <em>you</em> would love to use.</p>
21,338,476
addEventListener on form submit
<p>This is what I have and it's not working.</p> <pre><code>document.getElementById('form1').addEventListener('submit', function(){ document.getElementById('donate').style.display = 'none'; document.getElementById('topMessage').style.display = 'none'; }); </code></pre> <p>The javascript console shows this error:</p> <p>Uncaught TypeError: Cannot set property 'onclick' of undefined </p> <p>Any suggestion is much appreciated.</p>
21,342,556
1
7
null
2014-01-24 17:12:45.963 UTC
6
2014-01-27 15:19:38.813 UTC
null
null
null
null
2,245,331
null
1
38
javascript|javascript-events
126,797
<p>Okay, I figured it out. All I need the preventDefault(); So, here's the solution.</p> <pre><code>document.getElementById('form1').addEventListener('submit', function(evt){ evt.preventDefault(); document.getElementById('donate').style.display = 'none'; document.getElementById('topMessage').style.display = 'none'; }) </code></pre>
18,122,608
SimpleDateFormat parse loses timezone
<p>Code:</p> <pre><code> SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println(new Date()); try { String d = sdf.format(new Date()); System.out.println(d); System.out.println(sdf.parse(d)); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } </code></pre> <p>Output: </p> <pre><code>Thu Aug 08 17:26:32 GMT+08:00 2013 2013.08.08 09:26:32 GMT Thu Aug 08 17:26:32 GMT+08:00 2013 </code></pre> <p>Note that <code>format()</code> formats the <code>Date</code> correctly to GMT, but <code>parse()</code> lost the GMT details. I know I can use <code>substring()</code> and work around this, but what is the reason underlying this phenomenon?</p> <p><a href="https://stackoverflow.com/questions/16107898/simpledateformat-returns-wrong-time-zone-during-parse">Here is a duplicate question</a> which doesn't have any answers.</p> <p>Edit: Let me put the question in another way, what is the way to retrieve a Date object so that its always in GMT? </p>
18,124,407
3
9
null
2013-08-08 09:35:46.74 UTC
10
2019-10-21 10:54:23.96 UTC
2017-05-23 11:47:16.903 UTC
null
-1
null
887,421
null
1
61
java|date|simpledateformat|gmt
121,175
<p>All I needed was this : </p> <pre><code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); try { String d = sdf.format(new Date()); System.out.println(d); System.out.println(sdfLocal.parse(d)); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } </code></pre> <p>Output : slightly dubious, but I want only the date to be consistent</p> <pre><code>2013.08.08 11:01:08 Thu Aug 08 11:01:08 GMT+08:00 2013 </code></pre>
1,447,502
What's the difference/relationship between AVR and Arduino?
<p>I've been interested in hardware programming recently, but I have not started yet.</p> <p>I did some searching working, and have a vague idea:</p> <blockquote> <p>Arduino is a combination of both chip and breadboard.</p> <p>AVR is a single chip, and need to buy a breadboard to get started.</p> </blockquote> <p>Is that statement true or false?</p>
1,447,537
5
0
null
2009-09-19 02:01:04.493 UTC
4
2019-04-24 19:48:54.847 UTC
2012-02-28 20:29:25.063 UTC
null
63,550
null
104,015
null
1
22
hardware|arduino|avr
41,869
<p>AVR is just an integrated circuit microchip, made by Atmel. It looks something like this: <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/ATmega8_01_Pengo.jpg/1599px-ATmega8_01_Pengo.jpg" alt="alt text"></p> <p>Although they can be used by themselves, it takes a bit of hardware experience and some support components. </p> <p>The Arduino is an AVR processor running special code that lets you use the Arduino environment to program and upload code easily. All you need is a USB cable to program and communicate with it. It looks something like this:</p> <p><a href="https://i.stack.imgur.com/fxgSC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fxgSC.jpg" alt="alt text"></a><br> <sub>(source: <a href="http://www.mitchellpage.com.au/research/wp-content/uploads/2006/04/arduino_extreme_480.jpg" rel="nofollow noreferrer">mitchellpage.com.au</a>)</sub> </p> <p>A breadboard technically looks like this, and can be helpful in doing things with an Arduino. It is not necessarily needed for either solution but it is useful.</p> <p><img src="https://www.pjrc.com/store/breadboard.jpg" alt="alt text"></p> <p>If your asking these sorts of questions, you should checkout the Arduino tutorials at <a href="http://www.ladyada.net/learn/arduino/index.html" rel="nofollow noreferrer">adafruit</a>. They're very basic and will teach you what you need to know to get started.</p>
1,974,788
Combine onload and onresize (jQuery)
<p>I want to call the function on load as well as on resize.</p> <p>Is there a better way to rewrite this more compactly?</p> <pre><code>$('.content .right').width($(window).width() - (480)); $(window).resize(function(e) { $('.content .right').width($(window).width() - (480)); }); </code></pre>
1,974,797
5
0
null
2009-12-29 14:04:45.383 UTC
30
2016-09-05 21:30:22.283 UTC
2015-04-15 20:23:11.417 UTC
null
1,571,407
null
172,637
null
1
51
jquery|resize|window
101,720
<p>You can bind to the <code>resize</code> event alone, and trigger this event automatically upon load:</p> <pre class="lang-javascript prettyprint-override"><code>// Bind to the resize event of the window object $(window).on("resize", function () { // Set .right's width to the window width minus 480 pixels $(".content .right").width( $(this).width() - 480 ); // Invoke the resize event immediately }).resize(); </code></pre> <p>The last <code>.resize()</code> call will run this code upon load.</p>
2,053,029
How exactly does __attribute__((constructor)) work?
<p>It seems pretty clear that it is supposed to set things up.</p> <ol> <li>When exactly does it run?</li> <li>Why are there two parentheses?</li> <li>Is <code>__attribute__</code> a function? A macro? Syntax?</li> <li>Does this work in C? C++?</li> <li>Does the function it works with need to be static?</li> <li>When does <code>__attribute__((destructor))</code> run?</li> </ol> <p><a href="https://stackoverflow.com/questions/2046426/initialising-a-static-variable-in-objective-c-category/2046997#2046997">Example in Objective-C</a>:</p> <pre><code>__attribute__((constructor)) static void initialize_navigationBarImages() { navigationBarImages = [[NSMutableDictionary alloc] init]; } __attribute__((destructor)) static void destroy_navigationBarImages() { [navigationBarImages release]; } </code></pre>
2,053,078
5
0
null
2010-01-12 22:43:04.91 UTC
170
2022-07-19 12:13:34.82 UTC
2019-03-04 04:06:56.933 UTC
null
1,033,581
null
165,495
null
1
419
c++|objective-c|c|gcc
165,023
<ol> <li>It runs when a shared library is loaded, typically during program startup.</li> <li>That's how all GCC attributes are; presumably to distinguish them from function calls.</li> <li>GCC-specific syntax.</li> <li>Yes, this works in C and C++.</li> <li>No, the function does not need to be static.</li> <li>The destructor runs when the shared library is unloaded, typically at program exit.</li> </ol> <p>So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.</p> <p>Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.</p>
1,453,073
What is an API key?
<p>I see this word in almost every cross service application these days.</p> <p><strong>What exactly is an API key and what are its uses?</strong></p> <p>Also, what is the difference between public and private API keys.</p>
1,453,082
6
0
null
2009-09-21 06:14:36.03 UTC
47
2018-11-01 12:38:29.463 UTC
2017-04-23 10:52:52.45 UTC
null
3,357,935
null
127,212
null
1
116
api|security|terminology|api-key
164,448
<p>What "exactly" an API key is used for depends very much on who issues it, and what services it's being used for. By and large, however, an API key is the name given to some form of secret token which is submitted alongside web service (or similar) requests in order to identify the origin of the request. The key may be included in some digest of the request content to further verify the origin and to prevent tampering with the values.</p> <p>Typically, if you can identify the source of a request positively, it acts as a form of authentication, which can lead to access control. For example, you can restrict access to certain API actions based on who's performing the request. For companies which make money from selling such services, it's also a way of tracking who's using the thing for billing purposes. Further still, by blocking a key, you can partially prevent abuse in the case of too-high request volumes.</p> <p>In general, if you have both a public and a private API key, then it suggests that the keys are themselves a traditional public/private key pair used in some form of <a href="http://en.wikipedia.org/wiki/Public-key_cryptography" rel="noreferrer">asymmetric cryptography</a>, or related, digital signing. These are more secure techniques for positively identifying the source of a request, and additionally, for protecting the request's content from snooping (in addition to tampering).</p>
2,048,470
git working on two branches simultaneously
<p>I have a project with many branches.</p> <p>I would like to work on <strong>several</strong> branches simultaneously without switching back and forth with <code>git checkout</code>.</p> <p>Is there any way I can do that besides copying the whole repository somewhere else?</p>
30,186,843
6
3
null
2010-01-12 11:22:10.867 UTC
70
2022-08-07 11:51:15.06 UTC
2017-04-15 10:58:08.183 UTC
null
775,954
null
158,263
null
1
223
git|branch
97,462
<p>Git 2.5+ (Q2 2015) supports this feature!</p> <p>If you have a git repo <code>cool-app</code>, cd to root (<code>cd cool-app</code>), run <code>git worktree add ../cool-app-feature-A feature/A</code>. This checks out the branch <code>feature/A</code> in it's own new dedicated directory, <code>cool-app-feature-A</code>.</p> <p>That replaces an older script <code>contrib/workdir/git-new-workdir</code>, with a more robust mechanism where those "linked" working trees are actually recorded in the main repo new <code>$GIT_DIR/worktrees</code> folder (so that work on any OS, including Windows).</p> <p>Again, once you have cloned a repo (in a folder like <code>/path/to/myrepo</code>), you can add worktrees for different branches in <em>different</em> independent paths (<code>/path/to/br1</code>, <code>/path/to/br2</code>), while having those working trees linked to the main repo history (no need to use a <code>--git-dir</code> option anymore)</p> <p>See more at "<strong><a href="https://stackoverflow.com/a/30185564/6309">Multiple working directories with Git?</a></strong>".</p> <p>And once you have created a <a href="https://stackoverflow.com/a/49331132/6309">worktree, you can move or remove it</a> (with Git 2.17+, Q2 2018).</p>
1,384,965
How do I use preg_match to test for spaces?
<p>How would I use the PHP function preg_match() to test a string to see if any spaces exist?</p> <h3>Example</h3> <blockquote> <p>&quot;this sentence would be tested true for spaces&quot;</p> <p>&quot;thisOneWouldTestFalse&quot;</p> </blockquote>
1,384,971
7
0
null
2009-09-06 05:45:47.067 UTC
9
2019-11-20 04:16:00.07 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
36,545
null
1
30
php|regex|preg-match
99,495
<p>If you're interested in any white space (including tabs etc), use <code>\s</code></p> <pre><code>if (preg_match("/\\s/", $myString)) { // there are spaces } </code></pre> <p>if you're just interested in spaces then you don't even need a regex:</p> <pre><code>if (strpos($myString, " ") !== false) </code></pre>
1,661,204
How do you organize your work?
<p>How do you work? More specifically, how do you keep your programming tasks organized.</p> <p>When I do Mac development at home I use software called an outliner to organize, keep notes and prioritize the tasks I need to do. I started out using a program called <a href="http://amarsagoo.info/deepnotes/" rel="nofollow noreferrer">Deep Notes</a> which is a nice simple free tool. But now I use <a href="http://www.potionfactory.com/thehitlist/" rel="nofollow noreferrer">The Hit List</a>.</p> <p>I’ve been looking for an equivalently good program on the Windows platform but so far have not found one. So far I’ve tried <a href="http://www.fusiondesk.com/" rel="nofollow noreferrer">FusionDesk</a> and am not satisfied with it. I’m starting to get the urge to write my own software but thought I would ask around first and see if anyone knows of a good product that I have not been able to find on this vast internet.</p> <p><strong>Updated</strong></p> <p>If you've never used an outliner to organize ideas, here is a brief overview. <a href="http://en.wikipedia.org/wiki/Outliner" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Outliner</a> A good outliner is more complicated than a simple flat hierarchical TODO list but simple enough to be a one trick pony. One of the most important features of an outliner is being able to create a nested hierarchy of tasks. For example:</p> <ul> <li>Implement Feature A</li> <li>--- Add support at the data level</li> <li>--- Create quick interface for Feature A</li> <li>--- Create business logic that connects interface to data layer</li> <li>--- Refine the interface</li> </ul> <p>You can also collapse the nested tasks like a folder structure. If I'm not working on Feature A then I should be able to collapse the tree so it's sub tasks are not viewable. </p>
1,674,100
17
3
2009-11-03 13:30:24.407 UTC
2009-11-02 13:04:55.977 UTC
19
2012-05-17 08:11:45.827 UTC
2012-05-17 08:11:45.827 UTC
null
21,234
null
90,244
null
1
17
project-management
5,234
<p>If you're at all used to Emacs, you might LOVE <strong><a href="http://orgmode.org" rel="noreferrer">org-mode</a></strong>. I was not an emacs user, so it was a pretty steep learning curve for me, but it was so worth it. I now have a super fast plain-text based system with</p> <ul> <li>hierarchical folding</li> <li>search</li> <li>tagging</li> <li>scheduling / clocking</li> <li>RSS fetching</li> <li>email capabilities</li> <li><a href="http://mobileorg.ncogni.to" rel="noreferrer">NEW iPhone addon</a></li> </ul> <p>all with a simple(?) Emacs addon. Frickin' perfect for me (and I'm a confessing productivity porn addict).</p> <hr> <p>Secret tip for free: Combine this with the auto-file-syncing <a href="https://www.getdropbox.com/referrals/NTMyOTg0OQ" rel="noreferrer">Dropbox</a> (2.25 GB cloud space for free) and you'll never want anything else ever again. Well maybe that's a little bit of an overstatement...</p> <hr> <p>Also, check out <a href="http://members.optusnet.com.au/~charles57/GTD/gtd_workflow.html" rel="noreferrer">this article</a> which really helped me get off the ground with a system that works well. He combines GTD and orgmode.</p>
2,283,937
How should I ethically approach user password storage for later plaintext retrieval?
<p>As I continue to build more and more websites and web applications I am often asked to store user's passwords in a way that they can be retrieved if/when the user has an issue (either to email a forgotten password link, walk them through over the phone, etc.) When I can I fight bitterly against this practice and I do a lot of ‘extra’ programming to make password resets and administrative assistance possible without storing their actual password.</p> <p>When I can’t fight it (or can’t win) then I always encode the password in some way so that it, at least, isn’t stored as plaintext in the database—though I am aware that if my DB gets hacked it wouldn't take much for the culprit to crack the passwords, so that makes me uncomfortable.</p> <p>In a perfect world folks would update passwords frequently and not duplicate them across many different sites—unfortunately I know MANY people that have the same work/home/email/bank password, and have even freely given it to me when they need assistance. I don’t want to be the one responsible for their financial demise if my DB security procedures fail for some reason.</p> <p>Morally and ethically I feel responsible for protecting what can be, for some users, their livelihood even if they are treating it with much less respect. I am certain that there are many avenues to approach and arguments to be made for salting hashes and different encoding options, but is there a single ‘best practice’ when you have to store them? In almost all cases I am using PHP and MySQL if that makes any difference in the way I should handle the specifics.</p> <p><strong>Additional Information for Bounty</strong></p> <p>I want to clarify that I know this is not something you want to have to do and that in most cases refusal to do so is best. I am, however, not looking for a lecture on the merits of taking this approach I am looking for the best steps to take if you do take this approach.</p> <p>In a note below I made the point that websites geared largely toward the elderly, mentally challenged, or very young can become confusing for people when they are asked to perform a secure password recovery routine. Though we may find it simple and mundane in those cases some users need the extra assistance of either having a service tech help them into the system or having it emailed/displayed directly to them. </p> <p>In such systems the attrition rate from these demographics could hobble the application if users were not given this level of access assistance, so please answer with such a setup in mind.</p> <p><strong>Thanks to Everyone</strong></p> <p>This has been a fun question with lots of debate and I have enjoyed it. In the end I selected an answer that both retains password security (I will not have to keep plain text or recoverable passwords), but also makes it possible for the user base I specified to log into a system without the major drawbacks I have found from normal password recovery.</p> <p>As always there were about 5 answers that I would like to have marked as correct for different reasons, but I had to choose the best one--all the rest got a +1. Thanks everyone!</p> <p>Also, thanks to everyone in the Stack community who voted for this question and/or marked it as a favorite. I take hitting 100 up votes as a compliment and hope that this discussion has helped someone else with the same concern that I had.</p>
2,350,498
26
16
null
2010-02-17 19:54:40.083 UTC
469
2017-05-04 18:19:38.987 UTC
2017-02-15 10:13:56.21 UTC
null
1,945,990
null
258,497
null
1
1,342
security|password-encryption|password-storage
85,574
<p>How about taking another approach or angle at this problem? Ask why the password is required to be in plaintext: if it's so that the user can retrieve the password, then strictly speaking you don't really need to retrieve the password they set (they don't remember what it is anyway), you need to be able to give them a password they <em>can use</em>.</p> <p>Think about it: if the user needs to retrieve the password, it's because they've forgotten it. In which case a new password is just as good as the old one. But, one of the drawbacks of common password reset mechanisms used today is that the generated passwords produced in a reset operation are generally a bunch of random characters, so they're difficult for the user to simply type in correctly unless they copy-n-paste. That can be a problem for less savvy computer users.</p> <p>One way around that problem is to provide auto-generated passwords that are more or less natural language text. While natural language strings might not have the entropy that a string of random characters of the same length has, there's nothing that says your auto-generated password needs to have only 8 (or 10 or 12) characters. Get a high-entropy auto-generated passphrase by stringing together several random words (leave a space between them, so they're still recognizable and typeable by anyone who can read). Six random words of varying length are probably easier to type correctly and with confidence than 10 random characters, and they can have a higher entropy as well. For example, the entropy of a 10 character password drawn randomly from uppercase, lowercase, digits and 10 punctuation symbols (for a total of 72 valid symbols) would have an entropy of 61.7 bits. Using a dictionary of 7776 words (as Diceware uses) which could be randomly selected for a six word passphrase, the passphrase would have an entropy of 77.4 bits. See the <a href="http://world.std.com/~reinhold/dicewarefaq.html#calculatingentropy" rel="noreferrer">Diceware FAQ</a> for more info.</p> <ul> <li><p>a passphrase with about 77 bits of entropy: "admit prose flare table acute flair"</p></li> <li><p>a password with about 74 bits of entropy: "K:&amp;$R^tt~qkD"</p></li> </ul> <p>I know I'd prefer typing the phrase, and with copy-n-paste, the phrase is no less easy to use that the password either, so no loss there. Of course if your website (or whatever the protected asset is) doesn't need 77 bits of entropy for an auto-generated passphrase, generate fewer words (which I'm sure your users would appreciate).</p> <p>I understand the arguments that there are password protected assets that really don't have a high level of value, so the breach of a password might not be the end of the world. For example, I probably wouldn't care if 80% of the passwords I use on various websites was breached: all that could happen is a someone spamming or posting under my name for a while. That wouldn't be great, but it's not like they'd be breaking into my bank account. However, given the fact that many people use the same password for their web forum sites as they do for their bank accounts (and probably national security databases), I think it would be best to handle even those 'low-value' passwords as non-recoverable.</p>
1,535,631
Static variables in JavaScript
<p>How can I create static variables in Javascript?</p>
1,535,687
43
3
null
2009-10-08 04:31:25.337 UTC
329
2022-08-05 19:22:54.763 UTC
2017-01-20 17:00:14.34 UTC
null
1,016,343
null
111,683
null
1
802
javascript|variables|static|closures
800,477
<p>If you come from a class-based, statically typed object-oriented language <em>(like Java, C++ or C#)</em> I assume that you are trying to create a variable or method associated to a "type" but not to an instance.</p> <p>An example using a "classical" approach, with constructor functions maybe could help you to catch the concepts of basic OO JavaScript:</p> <pre><code>function MyClass () { // constructor function var privateVariable = "foo"; // Private variable this.publicVariable = "bar"; // Public variable this.privilegedMethod = function () { // Public Method alert(privateVariable); }; } // Instance method will be available to all instances but only load once in memory MyClass.prototype.publicMethod = function () { alert(this.publicVariable); }; // Static variable shared by all instances MyClass.staticProperty = "baz"; var myInstance = new MyClass(); </code></pre> <p><code>staticProperty</code> is defined in the MyClass object (which is a function) and has nothing to do with its created instances, JavaScript treats functions as <a href="http://en.wikipedia.org/wiki/First-class_function" rel="noreferrer">first-class objects</a>, so being an object, you can assign properties to a function.</p> <p><strong>UPDATE:</strong> ES6 introduced the ability to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes" rel="noreferrer">declare classes</a> through the <code>class</code> keyword. It is syntax sugar over the existing prototype-based inheritance.</p> <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static" rel="noreferrer"><code>static</code> keyword</a> allows you to easily define static properties or methods in a class.</p> <p>Let's see the above example implemented with ES6 classes:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class MyClass { // class constructor, equivalent to // the function body of a constructor constructor() { const privateVariable = 'private value'; // Private variable at the constructor scope this.publicVariable = 'public value'; // Public property this.privilegedMethod = function() { // Public Method with access to the constructor scope variables console.log(privateVariable); }; } // Prototype methods: publicMethod() { console.log(this.publicVariable); } // Static properties shared by all instances static staticProperty = 'static value'; static staticMethod() { console.log(this.staticProperty); } } // We can add properties to the class prototype MyClass.prototype.additionalMethod = function() { console.log(this.publicVariable); }; var myInstance = new MyClass(); myInstance.publicMethod(); // "public value" myInstance.additionalMethod(); // "public value" myInstance.privilegedMethod(); // "private value" MyClass.staticMethod(); // "static value"</code></pre> </div> </div> </p>
8,903,239
How to calculate time elapsed in bash script?
<p>I print the start and end time using <code>date +"%T"</code>, which results in something like:</p> <pre><code>10:33:56 10:36:10 </code></pre> <p>How could I calculate and print the difference between these two?</p> <p>I would like to get something like:</p> <pre><code>2m 14s </code></pre>
8,903,280
19
2
null
2012-01-17 23:38:54.653 UTC
96
2021-05-14 07:56:27.58 UTC
2019-07-25 16:39:15.163 UTC
null
717,501
null
247,243
null
1
288
bash|date
369,937
<p>Bash has a handy <code>SECONDS</code> builtin variable that tracks the number of seconds that have passed since the shell was started. This variable retains its properties when assigned to, and the value returned after the assignment is the number of seconds since the assignment plus the assigned value.</p> <p>Thus, you can just set <code>SECONDS</code> to 0 before starting the timed event, simply read <code>SECONDS</code> after the event, and do the time arithmetic before displaying.</p> <pre><code>#!/usr/bin/env bash SECONDS=0 # do some work duration=$SECONDS echo &quot;$(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed.&quot; </code></pre> <p>As this solution doesn't depend on <code>date +%s</code> (which is a GNU extension), it's portable to all systems supported by Bash.</p>
17,972,380
Wait for process to finish before proceeding in Java
<p>Essentially, I'm making a small program that's going to install some software, and then run some basic commands afterwards to prep that program. However, what is happening is that the program starts its install, and then immediately moves on to the following lines (registration, updates, etc). Of course, that can't happen until it's fully installed, so I'd like to find a way of waiting on the first process before running the second. For example,</p> <pre><code> Main.say("Installing..."); Process p1 = Runtime.getRuntime().exec(dir + "setup.exe /SILENT"); //Wait here, I need to finish installing first! Main.say("Registering..."); Process p2 = Runtime.getRuntime().exec(installDir + "program.exe /register aaaa-bbbb-cccc"); Main.say("Updating..."); Process p4 = Runtime.getRuntime().exec(installDir + "program.exe /update -silent"); </code></pre>
17,972,450
4
0
null
2013-07-31 13:53:45.497 UTC
3
2018-07-15 16:10:30.77 UTC
null
null
null
null
1,185,576
null
1
20
java|process
52,655
<p>Call <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#waitFor%28%29"><code>Process#waitFor()</code></a>. Its Javadoc says:</p> <blockquote> <p>Causes the current thread to wait, if necessary, until the process represented by this <code>Process</code> object has terminated. </p> </blockquote> <p>Bonus: you get the exit value of the subprocess. So you can check whether it exited successfully with code <code>0</code>, or whether an error occured (non-zero exit code).</p>
17,883,447
How to check database on not rooted android device
<p>I am developing an app where i am using sqllite3 database to store values. I have Nexus S and Nexus 7 both are unrooted devices. How can i get the database for my app for debugging purpose.</p> <p>I have tried (1) I have tried all approach mentioned <a href="http://blog.shvetsov.com/2013/02/access-android-app-data-without-root.html">here</a></p> <pre><code>adb shell run-as app.package.name \ cp /data/data/package.name/databases/application.sqlite /sdcard/ exit adb pull /sdcard/application.sqlite ~/ </code></pre> <p>This says cp not found..</p> <p>(2) <a href="http://developer.android.com/tools/help/adb.html#sqlite">http://developer.android.com/tools/help/adb.html#sqlite</a></p> <pre><code>adb -s emulator-5554 shell # sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db SQLite version 3.3.12 Enter ".help" for instructions .... enter commands, then quit... sqlite&gt; .exit </code></pre>
17,883,556
11
2
null
2013-07-26 14:03:30.023 UTC
19
2018-12-10 15:29:39.227 UTC
null
null
null
null
765,552
null
1
19
android|sqlite|adb|android-contentprovider|android-sqlite
32,032
<p>You can write your database to the external memory with the following:</p> <pre><code>private void writeToSD() throws IOException { File sd = Environment.getExternalStorageDirectory(); if (sd.canWrite()) { String currentDBPath = DB_NAME; String backupDBPath = "backupname.db"; File currentDB = new File(DB_PATH, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } } </code></pre> <p>Where <code>DB_NAME</code> is the name of my database and <code>DB_PATH</code> is defined as follows:</p> <pre><code>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN_MR1) { DB_PATH = context.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator; } else { DB_PATH = context.getFilesDir().getPath() + context.getPackageName() + "/databases/"; } </code></pre> <p>And add the following permission (Thanks to @Sathesh for pointing this out):</p> <pre><code>&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; </code></pre> <p>I call this method anytime I have a database write so that my most current database file is in the external memory and I can view it and debug from there. </p> <p>Then you can use the <a href="https://play.google.com/store/apps/details?id=com.lonelycatgames.Xplore">X-Plore app</a> to view the database from the external memory right on the Android device. </p>
6,506,367
Visual C++ 2010 - fatal error LNK1169: one or more multiply defined symbols found
<p>this is a program :</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { cout &lt;&lt; "Enter a number"; int i; cin &gt;&gt; i; try { if( i == 0 ) throw 0; if( i == 2 ) throw "error"; } catch( int i ) { cout &lt;&lt; "can't divide by 0"; } catch( ... ) { cout &lt;&lt; "catching other exceptions"; } } </code></pre> <p>On compiling (Microsoft visual C++ 2010 express on Windows 7), I get the error which says:</p> <blockquote> <p>fatal error LNK1169: one or more multiply defined symbols found</p> </blockquote>
6,506,550
4
5
null
2011-06-28 12:27:50.21 UTC
1
2017-02-09 18:50:17.653 UTC
2011-06-28 12:39:01.23 UTC
user195488
null
null
648,138
null
1
5
c++|visual-c++|exception|visual-c++-2010-express
48,719
<p><strong>Actually there is no error in this code</strong>.</p> <p>Number of source files could be the problem. Try this code as a new project in the same compiler or try deleting the files from the <code>source files</code> option in the left side of Text Area (i.e where you are writing your code)</p> <p>This should compile then.</p>
6,966,496
NVIDIA Cuda error "all CUDA-capable devices are busy or unavailable" on OSX
<p>Quite often, I get the CUDA library to completely fail and return with an error 46 ("all CUDA-capable devices are busy or unavailable") even for simple calls like cudaMalloc. The code runs successfully if I restart the computer, but this is far from ideal. This problem is apparently <a href="http://forums.nvidia.com/index.php?showtopic=196626">quite</a> <a href="http://forums.nvidia.com/index.php?showtopic=173567">common</a>.</p> <p>My setup is the following:</p> <ul> <li>OSX 10.6.8</li> <li>NVIDIA CUDA drivers : CUDA Driver Version: 4.0.31 (latest)</li> <li>GPU Driver Version: 1.6.36.10 (256.00.35f11)</li> </ul> <p>I tried many solutions from the Nvidia forum, but it didn't work. I don't want to reboot every time it happens. I also tried to unload and reload the driver with a procedure I assume to be correct (may not be)</p> <pre><code>kextunload -b com.nvidia.CUDA kextload -b com.nvidia.CUDA </code></pre> <p>But still it does not work. How can I kick the GPU (or CUDA) back into sanity ?</p> <p>This is the device querying result</p> <pre><code> CUDA Device Query (Runtime API) version (CUDART static linking) Found 1 CUDA Capable device(s) Device 0: "GeForce 9400M" CUDA Driver Version / Runtime Version 4.0 / 4.0 CUDA Capability Major/Minor version number: 1.1 Total amount of global memory: 254 MBytes (265945088 bytes) ( 2) Multiprocessors x ( 8) CUDA Cores/MP: 16 CUDA Cores GPU Clock Speed: 1.10 GHz Memory Clock rate: 1075.00 Mhz Memory Bus Width: 128-bit Max Texture Dimension Size (x,y,z) 1D=(8192), 2D=(65536,32768), 3D=(2048,2048,2048) Max Layered Texture Size (dim) x layers 1D=(8192) x 512, 2D=(8192,8192) x 512 Total amount of constant memory: 65536 bytes Total amount of shared memory per block: 16384 bytes Total number of registers available per block: 8192 Warp size: 32 Maximum number of threads per block: 512 Maximum sizes of each dimension of a block: 512 x 512 x 64 Maximum sizes of each dimension of a grid: 65535 x 65535 x 1 Maximum memory pitch: 2147483647 bytes Texture alignment: 256 bytes Concurrent copy and execution: No with 0 copy engine(s) Run time limit on kernels: Yes Integrated GPU sharing Host Memory: Yes Support host page-locked memory mapping: Yes Concurrent kernel execution: No Alignment requirement for Surfaces: Yes Device has ECC support enabled: No Device is using TCC driver mode: No Device supports Unified Addressing (UVA): No Device PCI Bus ID / PCI location ID: 2 / 0 Compute Mode: &lt; Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) &gt; deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 4.0, CUDA Runtime Version = 4.0, NumDevs = 1, Device = GeForce 9400M [deviceQuery] test results... PASSED </code></pre> <p>This is an example of code that may fail (although in normal conditions it does not)</p> <pre><code>#include &lt;stdio.h&gt; __global__ void add(int a, int b, int *c) { *c = a + b; } int main(void) { int c; int *dev_c; cudaMalloc( (void **) &amp;dev_c, sizeof(int)); // fails here, returning 46 add&lt;&lt;&lt;1,1&gt;&gt;&gt;(2,7,dev_c); cudaMemcpy(&amp;c, dev_c, sizeof(int), cudaMemcpyDeviceToHost); printf("hello world, %d\n",c); cudaFree( dev_c); return 0; } </code></pre> <p>I also found out that occasionally I get to revert back to a sane behavior without a reboot. I still don't know what triggers it.</p>
7,186,910
4
9
null
2011-08-06 11:28:55.46 UTC
3
2021-10-29 16:40:57.973 UTC
2011-08-14 23:22:44.967 UTC
null
78,374
null
78,374
null
1
24
cuda
48,125
<p>I confirm the statement made by the commenters to my post. The GPU may not work if other applications are taking control of it. In my case, the flash player in firefox was apparently occupying all the available resources on the card. I killed the firefox plugin for flash and the card immediately started working again. </p>
15,678,587
List all employee's names and their managers by manager name using an inner join
<p>The following is my CREATE TABLE script:</p> <pre><code>create table EMPLOYEES (EmpID char(4) unique Not null, Ename varchar(10), Job varchar(9), MGR char(4), Hiredate date, Salary decimal(7,2), Comm decimal(7,2), DeptNo char(2) not null, Primary key(EmpID), Foreign key(DeptNo) REFERENCES DEPARTMENTS(DeptNo)); </code></pre> <p>The following is my INSERT script:</p> <pre><code>insert into EMPLOYEES values (7839,'King','President',null,'17-Nov-11',5000,null,10); insert into EMPLOYEES values (7698,'Blake','Manager',7839,'01-May-11',2850,null,30); insert into EMPLOYEES values (7782,'Clark','Manager',7839,'02-Jun-11',2450,null,10); insert into EMPLOYEES values (7566,'Jones','Manager',7839,'02-Apr-11',2975,null,20); insert into EMPLOYEES values (7654,'Martin','Salesman',7698,'28-Feb-12',1250,1400,30); insert into EMPLOYEES values (7499,'Allen','Salesman',7698,'20-Feb-11',1600,300,30); insert into EMPLOYEES values (7844,'Turner','Salesman',7698,'08-Sep-11',1500,0,30); insert into EMPLOYEES values (7900,'James','Clerk',7698,'22-Feb-12',950,null,30); insert into EMPLOYEES values (7521,'Ward','Salesman',7698,'22-Feb-12',1250,500,30); insert into EMPLOYEES values (7902,'Ford','Analyst',7566,'03-Dec-11',3000,null,20); insert into EMPLOYEES values (7369,'Smith','Clerk',7902,'17-Dec-10',800,null,20); insert into EMPLOYEES values (7788,'Scott','Analyst',7566,'09-Dec-12',3000,null,20); insert into EMPLOYEES values (7876,'Adams','Clerk',7788,'12-Jan-10',1100,null,20); insert into EMPLOYEES values (7934,'Miller','Clerk',7782,'23-Jan-12',1300,null,10); </code></pre> <p>The following is my SELECT script:</p> <pre><code>select distinct e.Ename as Employee, m.mgr as reports_to from EMPLOYEES e inner join Employees m on e.mgr = m.mgr; </code></pre> <p>Im getting the employees with their corresponding manager's ID;</p> <pre><code>Ford 7566 Scott 7566 Allen 7698 James 7698 Martin 7698 Turner 7698 Ward 7698 Miller 7782 Adams 7788 Blake 7839 Clark 7839 Jones 7839 Smith 7902 </code></pre> <p><em>How do I list the manager name as well?</em> *Am I doing the right inner join?*</p>
15,678,663
11
0
null
2013-03-28 09:46:29.267 UTC
3
2022-09-18 01:51:20.29 UTC
null
null
null
null
2,197,238
null
1
5
sql|sql-server
156,255
<p>Add <code>m.Ename</code> to your <code>SELECT</code> query:</p> <pre><code>select distinct e.Ename as Employee, m.mgr as reports_to, m.Ename as Manager from EMPLOYEES e inner join Employees m on e.mgr = m.EmpID; </code></pre>
27,599,100
Phpunit tests gives warning no tests found in class
<p>I am trying to learn how to test with phpunit and laravel. When start the test using <code>phpunit</code> command, I am getting a warning :</p> <pre><code>There was 1 failure: 1) Warning No tests found in class "PostsTest". FAILURES! Tests: 2, Assertions: 1, Failures: </code></pre> <p>My test classname and filename matches. I have read other problems about unmatching names. my filename is <code>PostsTest.php</code> and my test file :</p> <pre><code>class PostsTest extends ApiTester { public function it_fetches_posts() { $this-&gt;times(5)-&gt;makePost(); $this-&gt;getJson('api/v1/posts'); $this-&gt;assertResponseOk(); } private function makePost($postFields=[]) { $post = array_merge([ 'title' =&gt; $this-&gt;fake-&gt;sentence, 'content' =&gt; $this-&gt;fake-&gt;paragragraph ], $postFields); while($this-&gt;times --)Post::create($post); } } </code></pre> <p>if necessary my ApiTester :</p> <pre><code>use Faker\Factory as Faker; class ApiTester extends TestCase { protected $fake; protected $times = 1; function __construct($faker) { $this-&gt;fake = Faker::create(); } } </code></pre> <p>I dont have any clue where the error is. Laravel or my local phpunit settings or anything else. Any helps is appreciated.</p> <p>Thanks.</p>
29,949,488
4
2
null
2014-12-22 08:33:30.917 UTC
7
2018-09-04 16:32:46.067 UTC
null
null
null
null
1,388,866
null
1
68
php|laravel|phpunit
42,744
<p><a href="https://phpunit.de/manual/current/en/appendixes.annotations.html#appendixes.annotations.test">Annotations are the answer</a>.</p> <pre><code>/** @test */ public function it_tests_something() { ... } </code></pre> <p>Adding that <code>@test</code> tells phpunit to treat the function as a test, regardless of the name.</p>
27,861,383
How to set corner radius of imageView?
<p>In Objective-C such line</p> <pre><code>self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0f; </code></pre> <p>does its job, I tried it in Swift using analogy</p> <pre><code>self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0 </code></pre> <p>and it doesn't change anything, the corners are the same as before. Moreover, Xcode does not show any syntax errors. Does Swift support any other way to reach this goal? I checked some other threads here and usually it's getting done in Swift in the way showed above. </p>
27,862,259
10
3
null
2015-01-09 13:13:30.647 UTC
18
2020-01-28 05:16:45.713 UTC
2018-06-19 08:47:49.463 UTC
null
2,227,743
null
2,087,608
null
1
75
ios|swift|uiimageview|cornerradius
149,048
<p>Layer draws out of clip region, you need to set it to mask to bounds:</p> <pre><code>self.mainImageView.layer.masksToBounds = true </code></pre> <p>From the <a href="https://developer.apple.com/reference/quartzcore/calayer/1410818-cornerradius" rel="noreferrer">docs</a>:</p> <blockquote> <p>By default, the corner radius does not apply to the image in the layer’s contents property; it applies only to the background color and border of the layer. However, setting the masksToBounds property to true causes the content to be clipped to the rounded corners</p> </blockquote>
51,173,002
How to change start destination of a navigation graph programmatically?
<p>Basically, I have the following navigation graph:</p> <p><a href="https://i.stack.imgur.com/Y3yo0.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Y3yo0.jpg" alt="enter image description here" /></a></p> <p>I want to change my starting point in navigation graph to <code>fragment 2</code> right after reaching it (in order to prevent going back to <code>fragment 1</code> when pressing back button - like with the splash screen).</p> <p>This is my code:</p> <pre><code>navGraph = navController.getGraph(); navGraph.setStartDestination(R.id.fragment2); navController.setGraph(navGraph); </code></pre> <p>But, obviously it's not working and it gets back to <code>fragment 1</code> after pressing back button.</p> <p>Am I doing it wrong? Is there any other solution?</p>
51,174,123
8
6
null
2018-07-04 11:50:38.823 UTC
21
2022-02-10 09:19:39.093 UTC
2022-02-10 09:19:39.093 UTC
null
3,585,796
null
6,600,637
null
1
83
android|android-jetpack|android-navigation|android-architecture-navigation
87,070
<h2><strong>UPDATE:</strong></h2> <p>When you have nav graph like this:</p> <pre><code>&lt;fragment android:id="@+id/firstFragment" android:name="com.appname.package.FirstFragment" &gt; &lt;action android:id="@+id/action_firstFragment_to_secondFragment" app:destination="@id/secondFragment" /&gt; &lt;/fragment&gt; &lt;fragment android:id="@+id/secondFragment" android:name="com.appname.package.SecondFragment"/&gt; </code></pre> <p>And you want to navigate to the second fragment and make it root of your graph, specify the next <code>NavOptions</code>:</p> <pre><code>NavOptions navOptions = new NavOptions.Builder() .setPopUpTo(R.id.firstFragment, true) .build(); </code></pre> <p>And use them for the navigation:</p> <pre><code>Navigation.findNavController(view).navigate(R.id.action_firstFragment_to_secondFragment, bundle, navOptions); </code></pre> <blockquote> <p><code>setPopUpTo(int destinationId, boolean inclusive)</code> - Pop up to a given destination before navigating. This pops all non-matching destinations from the back stack until this destination is found.</p> <p><code>destinationId</code> - The destination to pop up to, clearing all intervening destinations.</p> <p><code>inclusive</code> - true to also pop the given destination from the back stack.</p> </blockquote> <p><br></p> <h2><strong>ALTERNATIVE:</strong></h2> <pre><code>&lt;fragment android:id="@+id/firstFragment" android:name="com.appname.package.FirstFragment" &gt; &lt;action android:id="@+id/action_firstFragment_to_secondFragment" app:destination="@id/secondFragment" app:popUpTo="@+id/firstFragment" app:popUpToInclusive="true" /&gt; &lt;/fragment&gt; &lt;fragment android:id="@+id/secondFragment" android:name="com.appname.package.SecondFragment"/&gt; </code></pre> <p>And then on your code:</p> <pre><code>findNavController(fragment).navigate( FirstFragmentDirections.actionFirstFragmentToSecondFragment()) </code></pre> <h2><strong>Old answer</strong></h2> <p><strong>Deprecated</strong>: <em>The <code>clearTask</code> attribute for actions and the associated API in <code>NavOptions</code> has been deprecated.</em></p> <p>Source: <a href="https://developer.android.com/jetpack/docs/release-notes" rel="noreferrer">https://developer.android.com/jetpack/docs/release-notes</a></p> <p><br></p> <p>If you want to change your root fragment to <code>fragment 2</code> (e.g. after pressing back button on <code>fragment 2</code> you will exit the app), you should put the next attribute to your <code>action</code> or <code>destination</code>:</p> <pre><code>app:clearTask="true" </code></pre> <p>Practically it looks in a next way:</p> <pre><code>&lt;fragment android:id="@+id/firstFragment" android:name="com.appname.package.FirstFragment" android:label="fragment_first" &gt; &lt;action android:id="@+id/action_firstFragment_to_secondFragment" app:destination="@id/secondFragment" app:clearTask="true" /&gt; &lt;/fragment&gt; &lt;fragment android:id="@+id/secondFragment" android:name="com.appname.package.SecondFragment" android:label="fragment_second"/&gt; </code></pre> <p>I've added <code>app:clearTask="true"</code> to action. </p> <p><br> Now when you perform navigation from <code>fragment 1</code> to <code>fragment 2</code> use the next code:</p> <pre><code>Navigation.findNavController(view) .navigate(R.id.action_firstFragment_to_secondFragment); </code></pre>
349,250
how to display xml in javascript?
<p>As the question says, it just escaped my memory how to display xml in javascript, I want to display some source xml within an div on a page, that sits next to the processed result of the xml in another div.</p> <p>Can't remember if there was an equivalent to javascript's escape to convert entities on the client </p> <p><strong>Note</strong>: the xml files are served as is from the server, so I need a client side solution</p> <p><strong>Note</strong>: the main problem is XML doesn't render correctly in most browsers, all the brackets and attributes disappear, leaving you with text that doesn't look like xml</p>
349,295
7
0
null
2008-12-08 11:29:49.36 UTC
6
2014-07-05 11:16:24.577 UTC
2008-12-08 11:46:00.077 UTC
Robert Gould
15,124
Robert Gould
15,124
null
1
6
javascript|xml
66,209
<p>If you want the <em>browser to render</em> your <code>XML</code> as <code>XML</code>, it must be in it's own document, like an <code>iframe</code>, or a <code>frame</code>. <code>DIV</code> won't do the job!</p> <p>Besides, in the <code>HTTP</code> header of the request that serves the <code>iframe</code> you should send <code>Content-Type: text/xml</code>, so the Browser can understand that this content is an <code>XML</code>.</p> <p>But, if you truely need to see it in a DIV you will have to build yourself an <code>XML</code> rendering function <code>XML2HTML</code>. You can use the <code>HTML</code> <a href="http://www.w3schools.com/TAGS/tag_pre.asp" rel="noreferrer"><code>PRE</code></a> tag for that, if your <code>XML</code> string is already formatted (line breaks and tabs). In that case you will have to replace <code>&lt;</code> to <code>&amp;gt;</code> in the <code>XML</code> string.</p> <p><strong>Conclusion:</strong> <code>The browser</code> can't render <code>XML</code> and <code>HTML</code> in the same document. If you need it, you just have to workaround it.</p>
1,216,274
Unable to call the built in mb_internal_encoding method?
<p>I'm trying to install indefero on a CentOS 5.3 VMware 'box' and I ran into a problem. Quite early in the installation I get an error that I've been able to narrow down to this:</p> <pre><code>[root@code /var/www/html]# cat x.php &lt;?php mb_internal_encoding("UTF-8"); ?&gt; [root@code /var/www/html]# php x.php PHP Fatal error: Call to undefined function mb_internal_encoding() in /var/www/html/x.php on line 2 </code></pre> <p>I get the same error when calling this script via http through Apache. Now according to the <a href="http://php.net/manual/en/function.mb-internal-encoding.php" rel="noreferrer">PHP manual the mb_internal_encoding function</a> should be a builtin in PHP 5.</p> <p>I have CentOS 5.3 i386 (Linux code 2.6.18-53.1.21.el5 #1 SMP Tue May 20 09:34:18 EDT 2008 i686 i686 i386 GNU/Linux) and I've installed PHP 5.2.9.</p> <pre><code>[root@code /var/www/html]# php -v PHP 5.2.9 (cli) (built: Jul 8 2009 06:03:36) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies </code></pre> <p>I double checked: selinux has been disabled (for now).</p> <p>How do i fix this?</p>
1,216,284
7
1
null
2009-08-01 09:56:09.013 UTC
3
2021-08-23 14:07:41.41 UTC
2012-12-24 21:20:03.177 UTC
null
168,868
null
114,196
null
1
41
php|mbstring
118,856
<p>mbstring is a "non-default" extension, that is not enabled by default ; see <a href="http://www.php.net/manual/en/mbstring.installation.php" rel="noreferrer">this page</a> of the manual : </p> <blockquote> <p><strong>Installation</strong></p> <p>mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details</p> </blockquote> <p>So, you might have to enable that extension, modifying the php.ini file (and restarting Apache, so your modification is taken into account)</p> <p><br> I don't use CentOS, but you may have to install the extension first, using something like this <em>(see <a href="http://www.electrictoolbox.com/mbstring-php-extension-not-found-phpmyadmin/" rel="noreferrer">this page</a>, for instance, which seems to give a solution)</em> :</p> <pre><code>yum install php-mbstring </code></pre> <p><em>(The package name might be a bit different ; so, use yum search to get it :-) )</em></p>
1,254,787
SQL Server Update Trigger, Get Only modified fields
<p>I am aware of <code>COLUMNS_UPDATED</code>, well I need some quick shortcut (if anyone has made, I am already making one, but if anyone can save my time, I will appriciate it)</p> <p>I need basicaly an XML of only updated column values, I need this for replication purpose.</p> <p>SELECT * FROM inserted gives me each column, but I need only updated ones.</p> <p>something like following...</p> <pre><code>CREATE TRIGGER DBCustomers_Insert ON DBCustomers AFTER UPDATE AS BEGIN DECLARE @sql as NVARCHAR(1024); SET @sql = 'SELECT '; I NEED HELP FOR FOLLOWING LINE ...., I can manually write every column, but I need an automated routin which can work regardless of column specification for each column, if its modified append $sql = ',' + columnname... SET @sql = $sql + ' FROM inserted FOR XML RAW'; DECLARE @x as XML; SET @x = CAST(EXEC(@sql) AS XML); .. use @x END </code></pre>
1,922,260
8
0
null
2009-08-10 13:10:01.533 UTC
13
2019-09-28 06:40:10.93 UTC
2012-05-03 09:51:02.353 UTC
null
1,209,430
null
85,597
null
1
20
sql|sql-server|triggers|sql-update|database-replication
65,748
<p>Inside the trigger, you can use <code>COLUMNS_UPDATED()</code> like this in order to get updated value</p> <pre><code>-- Get the table id of the trigger -- DECLARE @idTable INT SELECT @idTable = T.id FROM sysobjects P JOIN sysobjects T ON P.parent_obj = T.id WHERE P.id = @@procid -- Get COLUMNS_UPDATED if update -- DECLARE @Columns_Updated VARCHAR(50) SELECT @Columns_Updated = ISNULL(@Columns_Updated + ', ', '') + name FROM syscolumns WHERE id = @idTable AND CONVERT(VARBINARY,REVERSE(COLUMNS_UPDATED())) &amp; POWER(CONVERT(BIGINT, 2), colorder - 1) &gt; 0 </code></pre> <p>But this snipet of code fails when you have a table with more than 62 columns.. Arth.Overflow...</p> <p>Here is the final version which handles more than 62 columns but give only the number of the updated columns. It's easy to link with 'syscolumns' to get the name</p> <pre><code>DECLARE @Columns_Updated VARCHAR(100) SET @Columns_Updated = '' DECLARE @maxByteCU INT DECLARE @curByteCU INT SELECT @maxByteCU = DATALENGTH(COLUMNS_UPDATED()), @curByteCU = 1 WHILE @curByteCU &lt;= @maxByteCU BEGIN DECLARE @cByte INT SET @cByte = SUBSTRING(COLUMNS_UPDATED(), @curByteCU, 1) DECLARE @curBit INT DECLARE @maxBit INT SELECT @curBit = 1, @maxBit = 8 WHILE @curBit &lt;= @maxBit BEGIN IF CONVERT(BIT, @cByte &amp; POWER(2,@curBit - 1)) &lt;&gt; 0 SET @Columns_Updated = @Columns_Updated + '[' + CONVERT(VARCHAR, 8 * (@curByteCU - 1) + @curBit) + ']' SET @curBit = @curBit + 1 END SET @curByteCU = @curByteCU + 1 END </code></pre>
16,140
What's the best way to get started with OSGI?
<p>What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module? </p> <p>I'm interested in using <a href="http://en.wikipedia.org/wiki/OSGi" rel="noreferrer">OSGi</a> in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using <a href="http://www.springframework.org/osgi" rel="noreferrer">Spring Dynamic Modules for OSGi(tm) Service Platforms</a>. I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. Has anyone here used this or a similar OSGi technology? Are there any pitfalls? </p> <p>@Nicolas - Thanks, I've seen that one. It's a good tutorial, but I'm looking more for ideas on how to do my first "real" OSGi bundle, as opposed to a Hello World example.</p> <p>@david - Thanks for the link! Ideally, with a greenfield app, I'd design the whole thing to be dynamic. What I'm looking for right now, though, is to introduce it in a small piece of an existing application. Assuming I can pick any piece of the app, what are some factors to consider that would make that piece better or worse as an OSGi guinea pig?</p>
16,817
8
0
null
2008-08-19 13:20:49.01 UTC
28
2018-09-19 21:06:35.393 UTC
2008-08-19 17:00:07.867 UTC
Nicholas Trandem
765
Nicholas Trandem
765
null
1
45
java|spring|osgi
12,033
<p>Well, since you can not have one part OSGi and one part non-OSGi you'll need to make your entire app OSGi. In its simplest form you make a single OSGi bundle out of your entire application. Clearly this is not a best practice but it can be useful to get a feel for deploying a bundle in an OSGi container (Equinox, Felix, Knoplerfish, etc).</p> <p>To take it to the next level you'll want to start splitting your app into components, components should typically have a set of responsibilities that can be isolated from the rest of your application through a set of interfaces and class dependencies. Identifying these purely by hand can range from rather straightforward for a well designed highly cohesive but loosely coupled application to a nightmare for interlocked source code that you are not familiar with.</p> <p>Some help can come from tools like <a href="http://clarkware.com/software/JDepend.html" rel="noreferrer">JDepend</a> which can show you the coupling of Java packages against other packages/classes in your system. A package with low efferent coupling should be easier to extract into an OSGi bundle than one with high efferent coupling. Even more architectural insight can be had with pro tools like <a href="http://www.headwaysoftware.com/products/structure101/index.php" rel="noreferrer">Structure 101</a>.</p> <p>Purely on a technical level, working daily with an application that consists of 160 OSGi bundles and using Spring DM I can confirm that the transition from "normal" Spring to Spring DM is largely pain free. The extra namespace and the fact that you can (and should) isolate your OSGi specific Spring configuration in separate files makes it even easier to have both with and without OSGi deployment scenarios.</p> <p>OSGi is a deep and wide component model, documentation I recommend:</p> <ul> <li><a href="http://www.osgi.org/Release4/Download" rel="noreferrer">OSGi R4 Specification</a>: Get the PDFs of the Core and Compendium specification, they are canonical, authoritative and very readable. Have a shortcut to them handy at all times, you will consult them.</li> <li>Read up on OSGi best practices, there is a large set of things you <strong>can</strong> do but a somewhat smaller set of things you <strong>should</strong> do and there are some things you should <strong>never do</strong> (DynamicImport: * for example). </li> </ul> <p>Some links: </p> <ul> <li><a href="http://felix.apache.org/site/presentations.data/best-practices-apachecon-20060628.pdf" rel="noreferrer">OSGi best practices and using Apache Felix</a></li> <li><a href="http://www.osgi.org/wiki/uploads/CommunityEvent2007/OSGiBestPractices.pdf" rel="noreferrer">Peter Kriens and BJ Hargrave in a Sun presentation on OSGi best practices</a> </li> <li>one key OSGi concept are Services, learn why and how they supplant the Listener pattern with the <a href="http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf" rel="noreferrer">Whiteboard pattern</a></li> <li><strike><a href="http://groups.google.com/group/spring-osgi" rel="noreferrer">The Spring DM Google Group</a> is very responsive and friendly in my experience</strike><br> <a href="http://groups.google.com/group/spring-osgi" rel="noreferrer">The Spring DM Google Group</a> is <a href="https://groups.google.com/forum/#!topic/spring-osgi/e-3gVCgl-_M" rel="noreferrer">no longer active</a> and has moved to Eclipse.org as the Gemini Blueprint project which has a forum <a href="http://www.eclipse.org/forums/index.php?t=thread&amp;frm_id=153" rel="noreferrer">here</a>.</li> </ul>
182,542
Email Address Validation for ASP.NET
<p>What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.</p> <p>This is ASP.NET 1.1</p>
182,582
9
0
null
2008-10-08 12:46:21.07 UTC
7
2021-02-27 10:08:22.38 UTC
2009-07-13 08:30:44.387 UTC
Adam Bellaire
75,500
Brian G
3,208
null
1
69
asp.net|validation|email
252,347
<p>Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.</p> <p>You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed. If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.</p> <p>You can use something like:</p> <pre><code>&lt;asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"&gt;&lt;/asp:RegularExpressionValidator&gt; </code></pre>
875,686
Advice for C++ GUI programming
<p>I have been writing C++ Console/CMD-line applications for about a year now and would like to get into windows GUI apps. For those of you who have taken this road before, what advice/tips can you give me. Ex: good readings, tutorials, approach tactics, etc...</p> <p>I know this is a really broad question, but i really don't know how/where to start, thus not knowing how to ask this question properly.</p>
875,895
12
0
null
2009-05-17 22:53:22.673 UTC
9
2020-02-21 12:43:17.467 UTC
2010-12-18 03:38:14.553 UTC
null
98,204
null
98,204
null
1
17
c++|visual-c++
13,616
<p>I highly recommend the use of the <a href="https://www.qt.io/" rel="nofollow noreferrer">Qt Libraries</a> for several reasons:</p> <ol> <li>The Framework is <strong>freely</strong> available for Windows, Linux, MacOS X, and a couple of mobile systems. Since version 4.5 the license is LGPL, which basically means that you can use Qt even in commercial applications.</li> <li>The <strong>design</strong> of Qt is out-standing, e.g. they use modern design patterns and a very consistent interface design (I don't know many other libraries that use object-oriented ideas in such perfection). Using Qt is the same as using Boost: it will improve your own programming skills, because they use such beautiful concepts!</li> <li>They are bloody fast, for instance in <strong>rendering</strong> (due to the different back-end for OpenGL, DirectX, etc.). Just have a look on <a href="http://www.youtube.com/watch?v=MXS3xKV-UM0&amp;feature=channel_page" rel="nofollow noreferrer">this video</a> and you see what can easily be done with Qt but is hard to achieve with native Windows, Mac, or Linux programming.</li> <li>They have a really <strong>great documentation</strong>, with tons of tutorials and a very good reference. You can start learning Qt easily with the given docs! The documentation is also <a href="https://doc.qt.io/qt-5.7/index.html" rel="nofollow noreferrer">available online</a>, so have a look and see by yourself.</li> <li>As mentioned before, Qt is <strong>cross-platform</strong>; you have one source-base that works on all the important operating systems. Why will you limit yourself to Windows, when you can also have Mac and Linux "for free"?</li> <li>Qt is so <strong>much more</strong> than "just" the user interface; they also offer network and database functionality, OpenGL bindings, a full-working web-browser control (based on WebKit), a multimedia playback library, and much much much more.</li> </ol> <p>Honestly, I wasted a couple of years by developing software <em>natively</em> for Windows, while I could have been so much more productive.</p>
277,208
How should I use Mercurial as a lone developer?
<p>I've decided that I want to use Mercurial for a small, personal project. </p> <p>Most of the help I've read about it talks about merging changes between multiple users. Since I'm solo, that's not going to happen.</p> <p>Should I have multiple repositories? My development computer is already backed up nightly to my Windows Home Server, so it doesn't seem valuable to have a second repository elsewhere just for backup purposes.</p> <p>Should I be branching every day? Or just around releases? Or when?</p> <p>In general, what practices do you recommend for the lone developer using Mercurial?</p>
600,158
13
4
null
2008-11-10 06:34:03.953 UTC
42
2012-05-17 08:10:47.713 UTC
2012-05-17 08:10:47.713 UTC
Paul
21,234
Jay Bazuzi
5,314
null
1
62
version-control|mercurial
6,142
<p>I use Mercurial to develop FsCheck, a unit testing framework hosted in codeplex. I am currently the only developer, but occasionally people send me patches.</p> <p>Concretely, I have one folder in my filesystem called "FsCheck". In that, I have one repository, and thus folder, called main. Typically, I have a few folders next to that where I work on specific features or bug fixes or whatever, say bug-escapingexceptions and feat-statefulchecking and patch-userFoo. These are created using hg clone.</p> <p>When I'm done with a feature or bugfix, I commit everything in that folder and push to main. Possibly merge in main. (hg commit, hg push, hg merge). Then I delete the folder (careful using hg status and hg outgoing that I'm not throwing away something useful).</p> <p>I almost never work in main except right before a release, where I do final cleanup (say documentation). Before release, I tag in main with the release number (hg tag v0.5.1).</p> <p>Codeplex uses svn as sourcecontrol. I only use it as to store releases, for which I use a locally checked out SVN working copy, to which I copy the Mercurial repository using hg archive. Then commit using svn. Primitive, but it works (using Mercurial as an SVN 'super client' on windows isn't very user-friendly yet in my opnion)</p> <p>I haven't had to do maintenance on previous releases yet, but I would do that by cloning the main repository from that release's revision(this is easy, since I tagged it), and work in that separate repository. Merging back to the main trunk would be as easy as pushing the changes to main and merging.</p> <p>In summary:</p> <ul> <li>One folder to store all your project's repositories, with the name of your project</li> <li>In that folder one main repository, and one transient repository per "unit of work", with a descriptive name for the unit of work.</li> </ul> <p>It's nice cause your branches and what you're working on is intuitively visible in the filesystem.</p>
248,222
Method Overloading. Can you overuse it?
<p>What's better practice when defining several methods that return the same shape of data with different filters? Explicit method names or overloaded methods?</p> <p>For example. If I have some Products and I'm pulling from a database</p> <p>explicit way:</p> <pre><code>public List&lt;Product&gt; GetProduct(int productId) { // return a List } public List&lt;Product&gt; GetProductByCategory(Category category) { // return a List } public List&lt;Product&gt; GetProductByName(string Name ) { // return a List } </code></pre> <p>overloaded way:</p> <pre><code>public List&lt;Product&gt; GetProducts() { // return a List of all products } public List&lt;Product&gt; GetProducts(Category category) { // return a List by Category } public List&lt;Product&gt; GetProducts(string searchString ) { // return a List by search string } </code></pre> <p>I realize you may get into a problem with <strong>similar signatures</strong>, but if you're passing objects instead of base types (string, int, char, DateTime, etc) this will be less of an issue. So... is it a good idea to <strong>overload a method</strong> to reduce the number of methods you have and for clarity, <strong>or</strong> should <strong>each method</strong> that filters the data a different way <strong>have a different method name</strong>?</p>
249,624
16
0
null
2008-10-29 20:06:34.303 UTC
15
2012-05-17 11:47:00.967 UTC
null
null
null
null
26,931
null
1
40
c#|java|methods|overloading
5,312
<p>Yes, overloading can easily be overused.</p> <p>I've found that the key to working out whether an overload is warranted or not is to consider the audience - not the compiler, but the maintenance programmer who will be coming along in weeks/months/years and has to understand what the code is trying to achieve.</p> <p>A simple method name like GetProducts() is clear and understandable, but it does leave a lot unsaid. </p> <p>In many cases, if the parameter passed to GetProducts() are well named, the maintenance guy will be able to work out what the overload does - but that's relying on good naming discipline at the point of use, which you can't enforce. What you can enforce is the name of the method they're calling.</p> <p>The guideline that I follow is to only overload methods if they are interchangable - if they do the same thing. That way, I don't mind which version the consumer of my class invokes, as they're equivalent.</p> <p>To illustrate, I'd happily use overloads for a DeleteFile() method:</p> <pre><code>void DeleteFile(string filePath); void DeleteFile(FileInfo file); void DeleteFile(DirectoryInfo directory, string fileName); </code></pre> <p>However, for your examples, I'd use separate names:</p> <pre><code>public IList&lt;Product&gt; GetProductById(int productId) {...} public IList&lt;Product&gt; GetProductByCategory(Category category) {...} public IList&lt;Product&gt; GetProductByName(string Name ) {...} </code></pre> <p>Having the full names makes the code more explicit for the maintenance guy (who might well be me). It avoids issues with having signature collisions:</p> <pre><code>// No collisions, even though both methods take int parameters public IList&lt;Employee&gt; GetEmployeesBySupervisor(int supervisorId); public IList&lt;Employee&gt; GetEmployeesByDepartment(int departmentId); </code></pre> <p>There is also the opportunity to introduce overloading for each purpose:</p> <pre><code>// Examples for GetEmployees public IList&lt;Employee&gt; GetEmployeesBySupervisor(int supervisorId); public IList&lt;Employee&gt; GetEmployeesBySupervisor(Supervisor supervisor); public IList&lt;Employee&gt; GetEmployeesBySupervisor(Person supervisor); public IList&lt;Employee&gt; GetEmployeesByDepartment(int departmentId); public IList&lt;Employee&gt; GetEmployeesByDepartment(Department department); // Examples for GetProduct public IList&lt;Product&gt; GetProductById(int productId) {...} public IList&lt;Product&gt; GetProductById(params int[] productId) {...} public IList&lt;Product&gt; GetProductByCategory(Category category) {...} public IList&lt;Product&gt; GetProductByCategory(IEnumerable&lt;Category&gt; category) {...} public IList&lt;Product&gt; GetProductByCategory(params Category[] category) {...} </code></pre> <p>Code is read a lot more than it is written - even if you never come back to the code after the initial check in to source control, you're still going to be reading that line of code a couple of dozen times while you write the code that follows.</p> <p>Lastly, unless you're writing throwaway code, you need to allow for other people calling your code from other languages. It seems that most business systems end up staying in production well past their use by date. It may be that the code that consumes your class in 2016 ends up being written in VB.NET, C# 6.0, F# or something completely new that's not been invented yet. It may be that the language doesn't support overloads.</p>
1,301,346
What is the meaning of single and double underscore before an object name?
<p>What do single and double leading underscores before an object's name represent in Python?</p>
1,301,369
17
2
2009-10-14 12:08:00.667 UTC
2009-08-19 17:11:57.037 UTC
707
2022-08-01 11:25:04.97 UTC
2022-06-13 01:28:06.317 UTC
null
365,102
null
76,701
null
1
1,681
python|oop|naming-conventions|identifier
634,291
<h2>Single Underscore</h2> <p>In a class, names with a leading underscore indicate to other programmers that the attribute or method is intended to be be used inside that class. However, privacy is not <em>enforced</em> in any way. Using leading underscores for functions in a module indicates it should not be imported from somewhere else.</p> <p>From the <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP-8</a> style guide:</p> <blockquote> <p><code>_single_leading_underscore</code>: weak &quot;internal use&quot; indicator. E.g. <code>from M import *</code> does not import objects whose name starts with an underscore.</p> </blockquote> <h2>Double Underscore (Name Mangling)</h2> <p>From <a href="https://docs.python.org/3/tutorial/classes.html#private-variables" rel="noreferrer">the Python docs</a>:</p> <blockquote> <p>Any identifier of the form <code>__spam</code> (at least two leading underscores, at most one trailing underscore) is textually replaced with <code>_classname__spam</code>, where <code>classname</code> is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.</p> </blockquote> <p>And a warning from the same page:</p> <blockquote> <p>Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; <em>it still is possible for a determined soul to access or modify a variable that is considered private.</em></p> </blockquote> <h2>Example</h2> <pre><code>&gt;&gt;&gt; class MyClass(): ... def __init__(self): ... self.__superprivate = &quot;Hello&quot; ... self._semiprivate = &quot;, world!&quot; ... &gt;&gt;&gt; mc = MyClass() &gt;&gt;&gt; print mc.__superprivate Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: myClass instance has no attribute '__superprivate' &gt;&gt;&gt; print mc._semiprivate , world! &gt;&gt;&gt; print mc.__dict__ {'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'} </code></pre>
834,748
gcc makefile error: "No rule to make target ..."
<p>I'm trying to use GCC (linux) with a makefile to compile my project.</p> <p>I get the following error which is can't seem to decipher in this context: </p> <pre><code>"No rule to make target 'vertex.cpp', needed by 'vertex.o'. Stop." </code></pre> <p>This is the makefile: </p> <pre><code>a.out: vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o g++ vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o main.o: main.cpp main.h g++ -c main.cpp vertex.o: vertex.cpp vertex.h g++ -c vertex.cpp edge.o: edge.cpp edge.h g++ -c num.cpp vlist.o: vlist.cpp vlist.h g++ -c vlist.cpp elist.o: elist.cpp elist.h g++ -c elist.cpp vnode.o: vnode.cpp vnode.h g++ -c vnode.cpp enode.o: enode.cpp enode.h g++ -c node.cpp </code></pre>
834,770
21
1
null
2009-05-07 13:49:54.637 UTC
80
2022-05-16 17:59:49.043 UTC
2015-06-18 18:25:11.213 UTC
null
512,251
null
99,213
null
1
445
gcc|makefile
1,340,272
<p>That's usually because you don't have a file called <code>vertex.cpp</code> available to make. Check that:</p> <ul> <li>that file exists.</li> <li>you're in the right directory when you make.</li> </ul> <p>Other than that, I've not much else to suggest. Perhaps you could give us a directory listing of that directory.</p>
255,202
How do I view 'git diff' output with my preferred diff tool/ viewer?
<p>When I type <code>git diff</code>, I want to view the output with my visual diff tool of choice (SourceGear "diffmerge" on Windows). How do I configure git to do this?</p>
255,212
26
7
null
2008-10-31 22:55:12.493 UTC
314
2021-07-05 08:03:30.637 UTC
2018-02-13 23:12:55.527 UTC
null
202,229
null
3,891
null
1
807
git|diff|difftool|git-difftool|diffmerge
495,257
<p>Since Git1.6.3, you can use the <strong>git difftool script</strong>: see <a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/949242#949242">my answer below</a>.</p> <hr> <p>May be this <a href="https://web.archive.org/web/20170508180316/http://git.net:80/ml/version-control.msysgit/2008-06/msg00200.html" rel="noreferrer">article</a> will help you. Here are the best parts:</p> <p>There are two different ways to specify an external diff tool. </p> <p>The first is the method you used, by setting the GIT_EXTERNAL_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT_EXTERNAL_DIFF will be called with a fixed set of 7 arguments:</p> <pre><code>path old-file old-hex old-mode new-file new-hex new-mode </code></pre> <p>As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.</p> <p>The second method, which I prefer, is to <strong>configure the external diff tool via "git config"</strong>. Here is what I did:</p> <p>1) Create a wrapper script "git-diff-wrapper.sh" which contains something like</p> <pre><code>--&gt;8-(snip)-- #!/bin/sh # diff is called by git with 7 parameters: # path old-file old-hex old-mode new-file new-hex new-mode "&lt;path_to_diff_executable&gt;" "$2" "$5" | cat --8&lt;-(snap)-- </code></pre> <p>As you can see, only the second ("old-file") and fifth ("new-file") arguments will be passed to the diff tool.</p> <p>2) Type</p> <pre><code>$ git config --global diff.external &lt;path_to_wrapper_script&gt; </code></pre> <p>at the command prompt, replacing with the path to "git-diff-wrapper.sh", so your ~/.gitconfig contains</p> <pre><code>--&gt;8-(snip)-- [diff] external = &lt;path_to_wrapper_script&gt; --8&lt;-(snap)-- </code></pre> <p>Be sure to use the correct syntax to specify the paths to the wrapper script and diff tool, i.e. use forward slashed instead of backslashes. In my case, I have</p> <pre><code>[diff] external = \"c:/Documents and Settings/sschuber/git-diff-wrapper.sh\" </code></pre> <p>in .gitconfig and</p> <pre><code>"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat </code></pre> <p>in the wrapper script. Mind the trailing "cat"!</p> <p>(I suppose the '<code>| cat</code>' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)</p> <p>(<a href="https://stackoverflow.com/users/20520/diomidis-spinellis">Diomidis Spinellis</a> adds <a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-my-preferred-diff-tool-viewer/255212#comment96247087_255212">in the comments</a>: </p> <blockquote> <p>The <code>cat</code> command is required, because <a href="http://man7.org/linux/man-pages/man1/diff.1.html" rel="noreferrer"><code>diff(1)</code></a>, by default exits with an error code if the files differ.<br> Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.<br> By piping the output of <code>git</code> to <code>cat</code> the non-zero error code is masked.<br> More efficiently, the program could just run <code>exit</code> with and argument of 0.)</p> </blockquote> <hr> <p>That (the article quoted above) is the theory for external tool <strong>defined through config file</strong> (not through environment variable).<br> In practice (still for config file definition of external tool), you can refer to:</p> <ul> <li><a href="https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667">How do I setup DiffMerge with msysgit / gitk?</a> which illustrates the concrete settings of DiffMerge and WinMerge for MsysGit and gitk</li> <li><a href="https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#773973">How can I set up an editor to work with Git on Windows?</a> for the definition of Notepad++ as an external editor.</li> </ul>
34,571
How do I test a class that has private methods, fields or inner classes?
<p>How do I use JUnit to test a class that has internal private methods, fields or nested classes?</p> <p>It seems bad to change the access modifier for a method just to be able to run a test.</p>
34,658
58
8
2013-04-10 20:46:28.67 UTC
2008-08-29 16:11:09.933 UTC
905
2022-04-23 18:05:12.267 UTC
2021-10-19 20:41:15.027 UTC
Philippe
6,296,561
MattGrommes
3,098
null
1
3,103
java|unit-testing|junit|tdd
1,145,211
<p>If you have somewhat of a legacy <strong>Java</strong> application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use <a href="http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29" rel="noreferrer">reflection</a>.</p> <p>Internally we're using helpers to get/set <code>private</code> and <code>private static</code> variables as well as invoke <code>private</code> and <code>private static</code> methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change <code>private static final</code> variables through reflection.</p> <pre><code>Method method = TargetClass.getDeclaredMethod(methodName, argClasses); method.setAccessible(true); return method.invoke(targetObject, argObjects); </code></pre> <p>And for fields:</p> <pre><code>Field field = TargetClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(object, value); </code></pre> <hr /> <blockquote> <p><strong>Notes:</strong></p> <ol> <li><code>TargetClass.getDeclaredMethod(methodName, argClasses)</code> lets you look into <code>private</code> methods. The same thing applies for <code>getDeclaredField</code>.</li> <li>The <code>setAccessible(true)</code> is required to play around with privates.</li> </ol> </blockquote>
173,400
How to check if PHP array is associative or sequential?
<p>PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array <em>&quot;is a list&quot;</em> (contains only numeric keys starting from 0)?</p> <p>Basically, I want to be able to differentiate between this:</p> <pre><code>$sequentialArray = [ 'apple', 'orange', 'tomato', 'carrot' ]; </code></pre> <p>and this:</p> <pre><code>$assocArray = [ 'fruit1' =&gt; 'apple', 'fruit2' =&gt; 'orange', 'veg1' =&gt; 'tomato', 'veg2' =&gt; 'carrot' ]; </code></pre>
173,479
59
4
2012-11-23 02:51:33.453 UTC
2008-10-06 07:01:13.14 UTC
217
2022-04-03 06:49:42.233 UTC
2022-04-03 06:49:42.233 UTC
PConroy
6,214,210
Wilco
5,291
null
1
881
php|arrays
310,334
<p>You have asked two questions that are not quite equivalent:</p> <ul> <li>Firstly, how to determine whether an array has only numeric keys</li> <li>Secondly, how to determine whether an array has <em>sequential</em> numeric keys, starting from 0</li> </ul> <p>Consider which of these behaviours you actually need. (It may be that either will do for your purposes.)</p> <p>The first question (simply checking that all keys are numeric) is <a href="https://stackoverflow.com/a/4254008/1709587">answered well by Captain kurO</a>.</p> <p>For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:</p> <pre class="lang-php prettyprint-override"><code>function isAssoc(array $arr) { if (array() === $arr) return false; return array_keys($arr) !== range(0, count($arr) - 1); } var_dump(isAssoc(['a', 'b', 'c'])); // false var_dump(isAssoc(["0" =&gt; 'a', "1" =&gt; 'b', "2" =&gt; 'c'])); // false var_dump(isAssoc(["1" =&gt; 'a', "0" =&gt; 'b', "2" =&gt; 'c'])); // true var_dump(isAssoc(["a" =&gt; 'a', "b" =&gt; 'b', "c" =&gt; 'c'])); // true </code></pre>
6,811,549
How can I include a python package with Hadoop streaming job?
<p>I am trying include a python package (NLTK) with a Hadoop streaming job, but am not sure how to do this without including every file manually via the CLI argument, "-file". </p> <p>Edit: One solution would be to install this package on all the slaves, but I don't have that option currently.</p>
6,811,772
5
0
null
2011-07-25 03:33:58.527 UTC
21
2019-04-11 12:20:07.407 UTC
null
null
null
null
318,870
null
1
18
python|hadoop
13,211
<p>I would zip up the package into a <code>.tar.gz</code> or a <code>.zip</code> and pass the entire tarball or archive in a <code>-file</code> option to your hadoop command. I've done this in the past with Perl but not Python.</p> <p>That said, I would think this would still work for you if you use Python's <code>zipimport</code> at <a href="http://docs.python.org/library/zipimport.html" rel="noreferrer">http://docs.python.org/library/zipimport.html</a>, which allows you to import modules directly from a zip.</p>
6,774,201
How to upload a file from the browser to Amazon S3 with node.js, Express, and knox?
<p>I'm trying to find some example code that utilizes node.js, Express, and knox.</p> <p>The docs for Knox only give clear examples of how to upload a file already stored in the file system. <a href="https://github.com/learnboost/knox#readme" rel="noreferrer">https://github.com/learnboost/knox#readme</a></p> <p>Additionally, there a number of simple tutorials (even in Express itself) on how to upload files directly to express and save to the file system.</p> <p>What I'm having trouble finding is an example that lets you upload a client upload to a node server and have the data streamed directly to S3 rather than storing in the local file system first.</p> <p>Can someone point me to a gist or other example that contains this kind of information?</p>
12,021,109
6
3
null
2011-07-21 09:47:29.63 UTC
10
2013-04-06 09:08:48.537 UTC
null
null
null
null
68,788
null
1
21
node.js|upload|amazon-s3|express
18,819
<p>All of the previous answers involve having the upload pass through your node.js server which is inefficient and unnecessary. Your node server does not have to handle the bandwidth or processing of uploaded files whatsoever because Amazon S3 allows uploads <strong>direct from the browser</strong>.</p> <p>Have a look at this blog post: <a href="http://blog.tcs.de/post-file-to-s3-using-node/" rel="noreferrer">http://blog.tcs.de/post-file-to-s3-using-node/</a></p> <p>I have not tried the code listed there, but having looked over it, it appears solid and I will be attempting an implementation of it shortly ad will update this answer with my findings.</p>
6,928,982
How to json_encode array with french accents?
<p>I have an array item with a French accent ([WIPDescription] => Recette Soupe à lOignon Sans Boeuf US). The data is being properly pulled from the database (mysql). </p> <p>However, when I try to encode this as json using the php built in json_encode it produces a null json value (OS X server: php 5.3.4, json 1.2.1 enabled). </p> <p>In a Linux server, the description is cut off after the first accent character. </p> <p>I tried all the json_encode options with no success. Any suggestions?</p> <p>Thank you.</p>
6,929,069
7
0
null
2011-08-03 15:24:34.243 UTC
6
2019-02-18 19:48:09.867 UTC
null
null
null
null
83,719
null
1
32
php|mysql|character-encoding|json
54,962
<p><code>json_encode</code> only wants <code>utf-8</code>. Depending on your character set, you can use <code>iconv</code> or <a href="http://www.php.net/manual/en/function.utf8-encode.php" rel="noreferrer"><code>utf8_encode</code></a> <em>before</em> calling <code>json_encode</code> on your variable. Probably with <code>array_walk_recursive</code>.</p> <p>As requested, an <strong>unfinished</strong> way to alter an array, with the assumptions that (1) it doesn't contain objects, and (2) the array keys are in ascii / lower bounds, so can be left as is:</p> <pre><code>$current_charset = 'ISO-8859-15';//or what it is now array_walk_recursive($array,function(&amp;$value) use ($current_charset){ $value = iconv('UTF-8//TRANSLIT',$current_charset,$value); }); </code></pre>
6,826,564
Remove background drawable programmatically in Android
<p>I want to remove the background drawable <code>@drawable/bg</code> programmatically. Is there a way to do that? </p> <p>Currently, I have the following XML in my layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout android:id="@+id/widget29" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:background="@drawable/bg"&gt; &lt;/RelativeLayout&gt; </code></pre>
6,826,641
11
0
null
2011-07-26 07:18:16.3 UTC
21
2019-11-08 14:33:37.773 UTC
2019-11-08 14:21:35.327 UTC
null
10,096,230
null
827,418
null
1
150
android|layout|background
151,184
<p>Try this </p> <pre><code>RelativeLayout relative = (RelativeLayout) findViewById(R.id.widget29); relative.setBackgroundResource(0); </code></pre> <p>Check the setBackground functions in the <a href="http://developer.android.com/reference/android/widget/RelativeLayout.html" rel="noreferrer">RelativeLayout documentation</a></p>
41,264,525
Hyper-V: Create shared folder between host and guest with internal network
<p>Set up:</p> <ul> <li>Host: Windows 10 Enterprise</li> <li>Guest: Windows 10 Professional</li> <li>Hypervisor: Hyper-V</li> </ul> <p>Aim:</p> <ul> <li>Create a shared folder between Host and Guest via an internal network to exchange files</li> </ul> <p>How can I achieve this?</p>
41,265,072
4
2
null
2016-12-21 13:59:10.38 UTC
34
2022-05-20 12:04:38.707 UTC
null
null
null
null
7,009,990
null
1
102
windows-10|share|hyper-v
248,586
<ul> <li>Open Hyper-V Manager</li> <li>Create a new internal virtual switch (e.g. "Internal Network Connection")</li> <li>Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch</li> <li>Start the VM</li> <li>Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)</li> <li>Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)</li> <li>If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply</li> <li>Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])</li> </ul> <p>There is also an easy way for copying via the clipboard:</p> <ul> <li>If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.</li> </ul> <p><a href="https://i.stack.imgur.com/JAaIH.png" rel="noreferrer">Enhanced Session</a></p>
15,941,732
Start Intent in Adapter
<p>I want to start a new activity from this base adapter. </p> <pre><code>public class EfficientAdapter extends BaseAdapter { private Activity activity; private ArrayList&lt;ComptePost&gt; data; private static LayoutInflater inflater = null; public ImageLoader imageLoader; public Boolean isActusAstuce; public static int flag = 0, counter=0; private Context context; public EfficientAdapter(Context context) { this.context = context; } NVirementEmmeteur main; int num = 0; ViewHolder holder; static String src; public EfficientAdapter(Activity a, ArrayList&lt;ComptePost&gt; d) { activity = a; data = d; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // imageLoader = new ImageLoader(activity.getApplicationContext()); imageLoader=new ImageLoader(activity.getApplicationContext()); } public EfficientAdapter(NVirementEmmeteur m) { main = m; } @Override public int getCount() { return data.toArray().length; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } public static class ViewHolder { public TextView one; public TextView two; public TextView three; public ImageView image; public RelativeLayout relative_layout; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View vi = convertView; holder.relative_layout.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub v.getContext().startActivity(new Intent(context, NVirementEmmeteur.class)); } }); return vi; } } </code></pre> <p>I tried </p> <pre><code>context.startActivity(new Intent(context, NVirementEmmeteur.class)); </code></pre> <p>and </p> <pre><code>v.getContext().startActivity(new Intent(context, NVirementEmmeteur.class)); </code></pre> <p>but it force closes my application.</p> <p>The intent should launch inside an <code>onclicklistener()</code> from the list adapter. Can someone tell me how to launch an intent from my efficientadapter.class please.</p> <p>Here is my logcat output:</p> <blockquote> <p>04-11 10:07:50.878: E/AndroidRuntime(11179): FATAL EXCEPTION: main 04-11 10:07:50.878: E/AndroidRuntime(11179): java.lang.NullPointerException 04-11 10:07:50.878: E/AndroidRuntime(11179): at android.content.ComponentName.(ComponentName.java:75) 04-11 10:07:50.878: E/AndroidRuntime(11179): at android.content.Intent.(Intent.java:2863) 04-11 10:07:50.878: E/AndroidRuntime(11179): at.adapter.EfficientAdapter$1.onClick(EfficientAdapter.java:141) 04-11 10:07:50.878: E/AndroidRuntime(11179): at android.view.View.performClick(View.java:2538) 04-11 10:07:50.878: E/AndroidRuntime(11179): at android.view.View$PerformClick.run(View.java:9152) 04-11 10:07:50.878: E/AndroidRuntime(11179): at android.os.Handler.handleCallback(Handler.java:587) 04-11 10:07:50.878: E/AndroidRuntime(11179): at android.os.Handler.dispatchMessage(Handler.java:92) 04-11 10:07:50.878: E/AndroidRuntime(11179): at android.os.Looper.loop(Looper.java:130) 04-11 10:07:50.878: E/AndroidRuntime(11179): at android.app.ActivityThread.main(ActivityThread.java:3687) 04-11 10:07:50.878: E/AndroidRuntime(11179): at java.lang.reflect.Method.invokeNative(Native Method) 04-11 10:07:50.878: E/AndroidRuntime(11179): at java.lang.reflect.Method.invoke(Method.java:507) 04-11 10:07:50.878: E/AndroidRuntime(11179): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842) 04-11 10:07:50.878: E/AndroidRuntime(11179): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 04-11 10:07:50.878: E/AndroidRuntime(11179): at dalvik.system.NativeStart.main(Native Method)</p> </blockquote>
15,941,755
9
5
null
2013-04-11 06:03:17.623 UTC
9
2021-03-29 13:38:57.75 UTC
2017-07-27 20:34:40.587 UTC
null
5,237,611
null
2,190,256
null
1
20
android
80,573
<p><strong>you have passed context of activity in constructor so you can also use;</strong></p> <pre><code>activity.startActivity(new Intent(activity, NVirementEmmeteur.class)); </code></pre> <hr> <p>check here is sample code you get idea what to do:</p> <p>setadapter like : <code>adapter = new MyArrayAdapter(MainActivity.this, COUNTRIES);</code></p> <p>adapter code:</p> <pre><code>package com.example.testapp; import com.example.main.util.testActivity; import android.content.Context; import android.content.Intent; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; class MyArrayAdapter extends BaseAdapter { private LayoutInflater mInflater; private Context mcon; private String[] COUNTRIES_; public MyArrayAdapter(Context con, String[] countries) { // TODO Auto-generated constructor stub mcon = con; COUNTRIES_ = countries; mInflater = LayoutInflater.from(con); } @Override public int getCount() { // TODO Auto-generated method stub return COUNTRIES_.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub final ListContent holder; View v = convertView; if (v == null) { v = mInflater.inflate(R.layout.my_spinner_style, null); holder = new ListContent(); holder.line = (LinearLayout) v.findViewById(R.id.line_); holder.name = (TextView) v.findViewById(R.id.textView1); holder.name1 = (TextView) v.findViewById(R.id.textView2); holder.name2 = (ImageView) v.findViewById(R.id.imageView1); v.setTag(holder); } else { holder = (ListContent) v.getTag(); } holder.name.setText("" + Html.fromHtml("" + COUNTRIES_[position])); holder.name1.setText("" + Html.fromHtml("" + COUNTRIES_[position])); holder.line.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mcon.startActivity(new Intent(mcon, testActivity.class)); } }); return v; } } class ListContent { TextView name; TextView name1; ImageView name2; LinearLayout line; } </code></pre> <hr> <p><strong>Edited:</strong></p> <p>if your are use this constructor: then <code>list.setadapter(new EfficientAdapter(myactivity.this));</code></p> <pre><code>public EfficientAdapter(Context context) { this.context = context; } </code></pre> <p>then use : <code>context.startActivity(new Intent(context, NVirementEmmeteur.class));</code></p> <hr> <p>if you use this construdtor <code>list.setadapter(new EfficientAdapter(myactivity.this, ComptePostarray));</code></p> <pre><code>public EfficientAdapter(Activity a, ArrayList&lt;ComptePost&gt; d) { activity = a; data = d; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // imageLoader = new ImageLoader(activity.getApplicationContext()); imageLoader=new ImageLoader(activity.getApplicationContext()); } </code></pre> <p>then use <code>activity.startActivity(new Intent(activity, NVirementEmmeteur.class));</code></p> <p><strong>Hope you understud....</strong></p>
15,545,720
How to fix Invalid byte 1 of 1-byte UTF-8 sequence
<p>I am trying to fetch the below xml from db using a java method but I am getting an error</p> <p>Code used to parse the xml</p> <pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new ByteArrayInputStream(cond.getBytes())); Document doc = db.parse(is); Element elem = doc.getDocumentElement(); // here we expect a series of &lt;data&gt;&lt;name&gt;N&lt;/name&gt;&lt;value&gt;V&lt;/value&gt;&lt;/data&gt; NodeList nodes = elem.getElementsByTagName("data"); TableID jobId = new TableID(_processInstanceId); Job myJob = Job.queryByID(_clientContext, jobId, true); if (nodes.getLength() == 0) { log(Level.DEBUG, "No data found on condition XML"); } for (int i = 0; i &lt; nodes.getLength(); i++) { // loop through the &lt;data&gt; in the XML Element dataTags = (Element) nodes.item(i); String name = getChildTagValue(dataTags, "name"); String value = getChildTagValue(dataTags, "value"); log(Level.INFO, "UserData/Value=" + name + "/" + value); myJob.setBulkUserData(name, value); } myJob.save(); </code></pre> <p>The Data</p> <pre><code>&lt;ContactDetails&gt;307896043&lt;/ContactDetails&gt; &lt;ContactName&gt;307896043&lt;/ContactName&gt; &lt;Preferred_Completion_Date&gt; &lt;/Preferred_Completion_Date&gt; &lt;service_address&gt;A-End Address: 1ST HELIERST HELIERJT2 3XP832THE CABLES 1 POONHA LANEST HELIER JE JT2 3XP&lt;/service_address&gt; &lt;ServiceOrderId&gt;315473043&lt;/ServiceOrderId&gt; &lt;ServiceOrderTypeId&gt;50&lt;/ServiceOrderTypeId&gt; &lt;CustDesiredDate&gt;2013-03-20T18:12:04&lt;/CustDesiredDate&gt; &lt;OrderId&gt;307896043&lt;/OrderId&gt; &lt;CreateWho&gt;csmuser&lt;/CreateWho&gt; &lt;AccountInternalId&gt;20100333&lt;/AccountInternalId&gt; &lt;ServiceInternalId&gt;20766093&lt;/ServiceInternalId&gt; &lt;ServiceInternalIdResets&gt;0&lt;/ServiceInternalIdResets&gt; &lt;Primary_Offer_Name action='del'&gt;MyMobile Blue &amp;#163;44.99 [12 month term]&lt;/Primary_Offer_Name&gt; &lt;Disc_Reason action='del'&gt;8&lt;/Disc_Reason&gt; &lt;Sup_Offer action='del'&gt;80000257&lt;/Sup_Offer&gt; &lt;Service_Type action='del'&gt;A-01-00&lt;/Service_Type&gt; &lt;Priority action='del'&gt;4&lt;/Priority&gt; &lt;Account_Number action='del'&gt;0&lt;/Account_Number&gt; &lt;Offer action='del'&gt;80000257&lt;/Offer&gt; &lt;msisdn action='del'&gt;447797142520&lt;/msisdn&gt; &lt;imsi action='del'&gt;234503184&lt;/imsi&gt; &lt;sim action='del'&gt;5535&lt;/sim&gt; &lt;ocb9_ARM action='del'&gt;false&lt;/ocb9_ARM&gt; &lt;port_in_required action='del'&gt; &lt;/port_in_required&gt; &lt;ocb9_mob action='del'&gt;none&lt;/ocb9_mob&gt; &lt;ocb9_mob_BB action='del'&gt; &lt;/ocb9_mob_BB&gt; &lt;ocb9_LandLine action='del'&gt; &lt;/ocb9_LandLine&gt; &lt;ocb9_LandLine_BB action='del'&gt; &lt;/ocb9_LandLine_BB&gt; &lt;Contact_2&gt; &lt;/Contact_2&gt; &lt;Acc_middle_name&gt; &lt;/Acc_middle_name&gt; &lt;MarketCode&gt;7&lt;/MarketCode&gt; &lt;Acc_last_name&gt;Port_OUT&lt;/Acc_last_name&gt; &lt;Contact_1&gt; &lt;/Contact_1&gt; &lt;Acc_first_name&gt;.&lt;/Acc_first_name&gt; &lt;EmaiId&gt; &lt;/EmaiId&gt; </code></pre> <p>The ERROR</p> <pre><code> org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence. </code></pre> <p>I read in some threads it's because of some special characters in the xml. How to fix this issue ?</p>
15,545,863
14
7
null
2013-03-21 11:05:00.583 UTC
3
2021-03-10 23:54:29.577 UTC
2014-04-10 07:25:17.387 UTC
null
2,392,564
null
1,861,033
null
1
34
java|xml|xml-parsing
191,308
<blockquote> <p>How to fix this issue ?</p> </blockquote> <p>Read the data using the correct character encoding. The error message means that you are trying to read the data as UTF-8 (either deliberately or because that is the default encoding for an XML file that does not specify <code>&lt;?xml version="1.0" encoding="somethingelse"?&gt;</code>) but it is actually in a different encoding such as ISO-8859-1 or Windows-1252.</p> <p>To be able to advise on how you should do this I'd have to see the code you're currently using to read the XML.</p>
35,950,385
React intellisense in Visual Studio Code
<p>I'm sure I'm missing something simple, but I simply can't get React.js IntelliSense to work in Visual Studio code.</p> <p>I have done the following:</p> <ul> <li><code>npm install typings</code></li> <li><code>ext install Typings Installer</code> in Visual Studio Code</li> <li><code>ext install Typings</code> in Visual Studio Code</li> <li><code>typings init</code> in the root directory of my &quot;app&quot;</li> <li><code>typings install --ambient react-global</code> in the root of my &quot;app&quot;</li> <li>restarted Visual Studio Code</li> </ul> <p>That's created a <code>typings</code> folder. My app is structured in the following folder structure:</p> <pre><code>├───public │ ├───css │ └───scripts | └───test.js └───typings ├───browser │ └───ambient │ └───react-global └───main └───ambient └───react-global </code></pre> <p>Yet when I'm in <code>test.js</code> and type <code>React.</code> I get no IntelliSense.</p> <p>I presume I'm missing something fundamental?</p>
35,952,951
6
6
null
2016-03-11 21:36:54.087 UTC
11
2022-06-29 11:17:18.91 UTC
2022-06-29 11:17:18.91 UTC
null
9,213,345
null
2,169,215
null
1
27
javascript|reactjs|visual-studio-code|intellisense
61,968
<p>You need to add jsconfig.json to the root of your workspace</p> <p><a href="https://code.visualstudio.com/docs/languages/javascript#_javascript-projects-jsconfigjson" rel="nofollow noreferrer">https://code.visualstudio.com/docs/languages/javascript#_javascript-projects-jsconfigjson</a></p> <p>[Note: you can even leave the <code>jsconfig.json</code> file empty]</p>
25,371,926
How can I respond to the width of an auto-sized DOM element in React?
<p>I have a complex web page using React components, and am trying to convert the page from a static layout to a more responsive, resizable layout. However, I keep running into limitations with React, and am wondering if there's a standard pattern for handling these issues. In my specific case, I have a component that renders as a div with display:table-cell and width:auto.</p> <p>Unfortunately, I cannot query the width of my component, because you can't compute the size of an element unless it's actually placed in the DOM (which has the full context with which to deduce the actual rendered width). Besides using this for things like relative mouse positioning, I also need this to properly set width attributes on SVG elements within the component.</p> <p>In addition, when the window resizes, how do I communicate size changes from one component to another during setup? We're doing all of our 3rd-party SVG rendering in shouldComponentUpdate, but you cannot set state or properties on yourself or other child components within that method.</p> <p>Is there a standard way of dealing with this problem using React?</p>
33,027,426
4
5
null
2014-08-18 20:59:31.817 UTC
33
2020-04-18 19:03:45.343 UTC
2016-06-23 21:05:28.827 UTC
null
200,224
null
566,185
null
1
88
javascript|reactjs|responsive
87,408
<p>The most practical solution is to use a library for this like <a href="https://github.com/souporserious/react-measure" rel="nofollow noreferrer" title="react-measure">react-measure</a>.</p> <p><strong>Update</strong>: there is now a custom hook for resize detection (which I have not tried personally): <a href="https://github.com/FezVrasta/react-resize-aware" rel="nofollow noreferrer">react-resize-aware</a>. Being a custom hook, it looks more convenient to use than <code>react-measure</code>.</p> <pre><code>import * as React from 'react' import Measure from 'react-measure' const MeasuredComp = () =&gt; ( &lt;Measure bounds&gt; {({ measureRef, contentRect: { bounds: { width }} }) =&gt; ( &lt;div ref={measureRef}&gt;My width is {width}&lt;/div&gt; )} &lt;/Measure&gt; ) </code></pre> <p>To communicate size changes between components, you can pass an <code>onResize</code> callback and store the values it receives somewhere (the standard way of sharing state these days is to use <a href="http://redux.js.org/" rel="nofollow noreferrer">Redux</a>):</p> <pre><code>import * as React from 'react' import Measure from 'react-measure' import { useSelector, useDispatch } from 'react-redux' import { setMyCompWidth } from './actions' // some action that stores width in somewhere in redux state export default function MyComp(props) { const width = useSelector(state =&gt; state.myCompWidth) const dispatch = useDispatch() const handleResize = React.useCallback( (({ contentRect })) =&gt; dispatch(setMyCompWidth(contentRect.bounds.width)), [dispatch] ) return ( &lt;Measure bounds onResize={handleResize}&gt; {({ measureRef }) =&gt; ( &lt;div ref={measureRef}&gt;MyComp width is {width}&lt;/div&gt; )} &lt;/Measure&gt; ) } </code></pre> <p><strong>How to roll your own if you really prefer to:</strong></p> <p>Create a wrapper component that handles getting values from the DOM and listening to window resize events (or component resize detection as used by <code>react-measure</code>). You tell it which props to get from the DOM and provide a render function taking those props as a child.</p> <p>What you render has to get mounted before the DOM props can be read; when those props aren't available during the initial render, you might want to use <code>style={{visibility: 'hidden'}}</code> so that the user can't see it before it gets a JS-computed layout.</p> <pre><code>// @flow import React, {Component} from 'react'; import shallowEqual from 'shallowequal'; import throttle from 'lodash.throttle'; type DefaultProps = { component: ReactClass&lt;any&gt;, }; type Props = { domProps?: Array&lt;string&gt;, computedStyleProps?: Array&lt;string&gt;, children: (state: State) =&gt; ?React.Element&lt;any&gt;, component: ReactClass&lt;any&gt;, }; type State = { remeasure: () =&gt; void, computedStyle?: Object, [domProp: string]: any, }; export default class Responsive extends Component&lt;DefaultProps,Props,State&gt; { static defaultProps = { component: 'div', }; remeasure: () =&gt; void = throttle(() =&gt; { const {root} = this; if (!root) return; const {domProps, computedStyleProps} = this.props; const nextState: $Shape&lt;State&gt; = {}; if (domProps) domProps.forEach(prop =&gt; nextState[prop] = root[prop]); if (computedStyleProps) { nextState.computedStyle = {}; const computedStyle = getComputedStyle(root); computedStyleProps.forEach(prop =&gt; nextState.computedStyle[prop] = computedStyle[prop] ); } this.setState(nextState); }, 500); // put remeasure in state just so that it gets passed to child // function along with computedStyle and domProps state: State = {remeasure: this.remeasure}; root: ?Object; componentDidMount() { this.remeasure(); this.remeasure.flush(); window.addEventListener('resize', this.remeasure); } componentWillReceiveProps(nextProps: Props) { if (!shallowEqual(this.props.domProps, nextProps.domProps) || !shallowEqual(this.props.computedStyleProps, nextProps.computedStyleProps)) { this.remeasure(); } } componentWillUnmount() { this.remeasure.cancel(); window.removeEventListener('resize', this.remeasure); } render(): ?React.Element&lt;any&gt; { const {props: {children, component: Comp}, state} = this; return &lt;Comp ref={c =&gt; this.root = c} children={children(state)}/&gt;; } } </code></pre> <p>With this, responding to width changes is very simple:</p> <pre><code>function renderColumns(numColumns: number): React.Element&lt;any&gt; { ... } const responsiveView = ( &lt;Responsive domProps={['offsetWidth']}&gt; {({offsetWidth}: {offsetWidth: number}): ?React.Element&lt;any&gt; =&gt; { if (!offsetWidth) return null; const numColumns = Math.max(1, Math.floor(offsetWidth / 200)); return renderColumns(numColumns); }} &lt;/Responsive&gt; ); </code></pre>
41,060,382
Using Pip to install packages to Anaconda Environment
<p>conda 4.2.13 MacOSX 10.12.1</p> <p>I am trying to install packages from <code>pip</code> to a fresh environment (virtual) created using anaconda. <a href="http://conda.pydata.org/docs/using/pkgs.html#install-non-conda-packages" rel="noreferrer">In the Anaconda docs</a> it says this is perfectly fine. It is done the same way as for virtualenv. </p> <blockquote> <p>Activate the environment where you want to put the program, then pip install a program...</p> </blockquote> <p>I created an empty environment in Ananconda like this:</p> <pre><code>conda create -n shrink_venv </code></pre> <p>Activate it:</p> <pre><code>source activate shrink_venv </code></pre> <p>I then can see in the terminal that I am working in my env <code>(shrink_venv)</code>. Problem is coming up, when I try to install a package using <code>pip</code>:</p> <pre><code>(shrink_venv): pip install Pillow Requirement already satisfied (use --upgrade to upgrade): Pillow in /Library/Python/2.7/site-packages </code></pre> <p>So I can see it thinks the requirement is satisfied from the system-wide package. So it seems the environment is not working correctly, definitely not like it said in the docs. Am I doing something wrong here?</p> <p>Just a note, I know you can use <code>conda install</code> for the packages, but I have had an issue with Pillow from anaconda, so I wanted to get it from <code>pip</code>, and since the docs say that is fine.</p> <p>Output of <code>which -a pip</code>:</p> <pre><code>/usr/local/bin/pip /Users/my_user/anaconda/bin/pip </code></pre> <p>** UPDATE ** I see this is pretty common issue. What I have found is that the conda env doesn't play well with the PYTHONPATH. The system seems to always look in the PYTHONPATH locations even when you're using a conda environment. Now, I always run <code>unset PYTHONPATH</code> when using a conda environment, and it works much better. I'm on a mac.</p>
43,729,857
17
10
null
2016-12-09 12:20:55.413 UTC
194
2022-08-25 17:07:58.043 UTC
2018-10-24 14:02:24.91 UTC
null
959,306
null
959,306
null
1
367
python|pip|anaconda|environment
674,320
<p>For others who run into this situation, I found this to be the most straightforward solution:</p> <ol> <li><p>Run <code>conda create -n venv_name</code> and <code>conda activate venv_name</code>, where <code>venv_name</code> is the name of your virtual environment.</p> </li> <li><p>Run <code>conda install pip</code>. This will install pip to your venv directory.</p> </li> <li><p>Find your anaconda directory, and find the actual venv folder. It should be somewhere like <code>/anaconda/envs/venv_name/</code>.</p> </li> <li><p>Install new packages by doing <code>/anaconda/envs/venv_name/bin/pip install package_name</code>.</p> </li> </ol> <p>This should now successfully install packages using that virtual environment's pip!</p>
13,385,653
Multiple conditions on the same column in the WHERE clause
<p>I have a table something like this - </p> <pre><code>RecordID PropertyID PropertyVal -------------------------------------------------- 3215 7 john doe 3215 11 Chicago 3215 13 Business Development Analyst 3216 7 jane doe 3216 11 Chicago 3216 13 Managing Director 3217 7 mike smith 3217 11 Chicago 3217 13 Business Development Analyst 3218 7 john smith 3218 11 Seattle 3218 13 Managing Director </code></pre> <p>How do I return the names of users where <code>PropertyID = 13 AND PropertyVal='Business Development Analyst'AND PropertyID = 11 AND PropertyVal = 'Chicago'</code>. How do I do multiple where clauses for the same column?</p> <p>Edit: I need the result set to look like this -</p> <pre><code>Name ---- John Doe Mike Smith </code></pre>
13,385,698
5
3
null
2012-11-14 19:13:13.903 UTC
4
2020-06-09 18:07:49.967 UTC
2012-11-14 19:34:29.577 UTC
null
349,308
null
349,308
null
1
8
sql|sql-server-2008
75,034
<pre><code>select PropertyVal from your_table where PropertyID = 7 and RecordID in ( select RecordID from your_table where (PropertyID = 13 AND PropertyVal='Business Development Analyst') or (PropertyID = 11 AND PropertyVal = 'Chicago') group by RecordID having count(distinct PropertyID) = 2 ) </code></pre>
13,482,091
UPDATE syntax in SQLite
<p>I need to know if I can do this in an UPDATE statement:</p> <pre><code>UPDATE users SET ('field1', 'field2', 'field3') VALUES ('value1', 'value2', 'value3'); </code></pre> <p>Or similar syntax. I'm using SQLite.</p> <p><strong>Note:</strong></p> <blockquote> <p>Nobody understands me, I just want to know if it is possible to SET separate fields to separate values. That's all.</p> </blockquote>
13,482,298
6
0
null
2012-11-20 21:03:38.51 UTC
4
2020-07-24 18:16:30.207 UTC
2012-11-20 21:25:17.92 UTC
null
15,168
null
1,599,681
null
1
18
sql|sqlite|sql-update
66,126
<p>There is a (standard SQL) syntax that is similar to what you propose but as far as I know, only Postgres has implemented it:</p> <pre><code>UPDATE users SET (field1, field2, field3) = ('value1', 'value2', 'value3') WHERE some_condition ; </code></pre> <p>Tested (for the infidels) in: <strong><a href="http://sqlfiddle.com/#!1/5678f/1">SQL-Fiddle</a></strong> </p> <hr> <p>This also works in Postgres:</p> <pre><code>UPDATE users AS u SET (field1, field2, field3) = (f1, f2, f3) FROM ( VALUES ('value1', 'value2', 'value3') ) AS x (f1, f2, f3) WHERE condition ; </code></pre> <hr> <p>This works in Postgres and SQL-Server:</p> <pre><code>UPDATE users SET field1 = f1, field2 = f2, field3 = f3 FROM ( VALUES ('value1', 'value2', 'value3') ) AS x (f1, f2, f3) WHERE condition ; </code></pre> <hr> <p>and as @JackDouglas commented, this works in Oracle:</p> <pre><code>UPDATE users SET (field1, field2, field3) = ( SELECT 'value1', 'value2', 'value3' FROM dual ) WHERE condition ; </code></pre>
13,593,420
Countdown Timer Image GIF in Email
<p>I recently received an emailer from Onnit Labs that included a Countdown Module Timer inside the emailer using a gif image. The emailer can be viewed here: <a href="https://www.onnit.com/emails/lastchance-historic/" rel="noreferrer">https://www.onnit.com/emails/lastchance-historic/</a></p> <p>The Image can be seen here:</p> <p><a href="https://www.onnit.com/emails/_modules/timer/?end=2014-11-27+00:00:00&amp;dark=1" rel="noreferrer"><img src="https://i.stack.imgur.com/e6zAd.png" alt="enter image description here"></a></p> <p>I looked into it, and it seems you can keep sending new frames to an animated GIF using gifsockets, as a GIF doesn't specify how many frames it has when loaded in the browser. Here it is on github: <a href="http://github.com/videlalvaro/gifsockets" rel="noreferrer">http://github.com/videlalvaro/gifsockets</a></p> <p>I thought this was pretty interesting and a cool effect indeed. Does anyone have any other insights on how this could be accomplished? It seems as though the one they're using at Onnit seems to change the countdown according to date appended at the end of URL or image.</p> <p><code>onnit.com/emails/_modules/timer/?end=2012-12-27+00:00:00&amp;dark=1</code></p> <p>I'm trying to accomplish the same thing to send in an email, but I am a little stumped.</p>
13,597,274
4
5
null
2012-11-27 21:30:13.6 UTC
27
2019-10-06 16:31:33.877 UTC
2012-11-28 01:44:15.027 UTC
null
75,924
null
1,857,868
null
1
38
sockets|email|timer|gif|countdown
64,624
<p>While maybe <code>gifsockets</code> would work (I haven't tried that before...), there is no network traffic while I am looking at the image other than the initial image load. I am also seeing it it jump from 41 to 42 again. A Reload took it down to 39.</p> <p>It appears to be just a script that generates 60 frames of animation and sends them to the user. This could probably be done in any language.</p> <p>Here is how it is done in php:</p> <p><a href="http://seanja.com/secret/countdown/">http://seanja.com/secret/countdown/</a></p> <p><img src="https://i.stack.imgur.com/KpOtd.gif" alt="enter image description here"></p>
13,406,791
Modules and namespace / name collision in AngularJS
<p>Consider the following jfiddle <a href="http://jsfiddle.net/bchapman26/9uUBU/29/">http://jsfiddle.net/bchapman26/9uUBU/29/</a></p> <pre><code>//angular.js example for factory vs service var app = angular.module('myApp', ['module1', 'module2']); var service1module = angular.module('module1', []); service1module.factory('myService', function() { return { sayHello: function(text) { return "Service1 says \"Hello " + text + "\""; }, sayGoodbye: function(text) { return "Service1 says \"Goodbye " + text + "\""; } }; }); var service2module = angular.module('module2', []); service2module.factory('myService', function() { return { sayHello: function(text) { return "Service2 says \"Hello " + text + "\""; }, sayGoodbye: function(text) { return "Service2 says \"Goodbye " + text + "\""; } }; }); function HelloCtrl($scope, myService) { $scope.fromService1 = myService.sayHello("World"); } function GoodbyeCtrl($scope, myService) { $scope.fromService2 = myService.sayGoodbye("World"); }​ </code></pre> <p>I have 2 modules (module1 and module2). Both module1 and module2 define a service called myService. This appears to create a name clash on myService within Angular when both modules are imported into myApp. It appears AngularJs just uses the second service definition without warning you of the possible issue.</p> <p>Very large projects (or just reusing modules in general) would have a risk of names clashing, which could be difficult to debug.</p> <p>Is there a way to prefix names with the module name so that name clashes don't happen? </p>
19,820,088
4
3
null
2012-11-15 21:46:18.613 UTC
8
2018-06-08 06:00:45.797 UTC
2018-05-02 14:18:42.053 UTC
null
7,873,483
null
935,765
null
1
49
angularjs|namespaces|collision|angularjs-module
18,374
<p>As of today, AngularJS modules do not provide any sort of namespacing that would prevent collisions between objects in different modules. The reason is that an AngularJS app has a single injector that holds names for all objects without respect to module names.</p> <p>The <a href="http://docs.angularjs.org/guide/di">AngularJS Developer Guide</a> says:</p> <blockquote> <p>To manage the responsibility of dependency creation, each Angular application has an injector. The injector is a service locator that is responsible for construction and lookup of dependencies.</p> </blockquote> <p>As you've mentioned, nasty bugs can result when injecting modules into your main/app module. When collisions happen they are silent and the winner is determined by whichever was the last module injected.</p> <p>So no, there's not a built in way of avoiding these collisions. Maybe this will happen in the future. For large apps where this problem becomes more likely, you're right that naming conventions are your best tool. Consider whether objects belonging to a module or function area might use a short prefix. </p>
3,623,129
winsock2.h, no such file or directory
<p>I have this error while compiling my Visual C++ project in Visual Studio 2008 on XP. How to resolve this error :(</p> <pre><code>Error 1 fatal error C1083: Cannot open include file: 'winsock2.h': No such file or directory c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\atlbase.h 68 WOT </code></pre>
3,623,141
2
2
null
2010-09-02 00:55:40.733 UTC
null
2011-06-15 19:10:54.507 UTC
null
null
null
null
359,085
null
1
6
visual-c++
40,212
<p>Your Windows SDK is not configure correctly. The easiest way to fix this is to install <a href="http://msdn.microsoft.com/en-us/windows/bb980924.aspx" rel="noreferrer">Windows 7 SDK</a>. (yes, you can install it on windows xp and develop for xp)</p>
9,347,631
Spying on a constructor using Jasmine
<p>I am using Jasmine to test if certain objects are created and methods are called on them.</p> <p>I have a jQuery widget that creates flipcounter objects and calls the setValue method on them. The code for flipcounter is here: <a href="https://bitbucket.org/cnanney/apple-style-flip-counter/src/13fd00129a41/js/flipcounter.js" rel="noreferrer">https://bitbucket.org/cnanney/apple-style-flip-counter/src/13fd00129a41/js/flipcounter.js</a></p> <p>The flipcounters are created using:</p> <pre><code>var myFlipCounter = new flipCounter("counter", {inc: 23, pace: 500}); </code></pre> <p>I want to test that the flipcounters are created and the setValue method is called on them. My problem is that how do I spy on these objects even before they are created? Do I spy on the constructor and return fake objects? Sample code would really help. Thanks for your help! :)</p> <p><strong>Update:</strong></p> <p>I've tried spying on the flipCounter like this:</p> <pre><code>myStub = jasmine.createSpy('myStub'); spyOn(window, 'flipCounter').andReturn(myStub); //expectation expect(window.flipCounter).toHaveBeenCalled(); </code></pre> <p>Then testing for the setValue call by flipCounter:</p> <pre><code>spyOn(myStub, 'setValue'); //expectation expect(myStub.setValue).toHaveBeenCalled(); </code></pre> <p>the first test for initializing flipCounter is fine, but for testing the setValue call, all I'm getting is a 'setValue() method does not exist' error. Am I doing this the right way? Thanks!</p>
9,348,107
6
2
null
2012-02-19 07:54:07.773 UTC
1
2017-09-20 08:35:38.383 UTC
2012-02-19 15:21:04.69 UTC
null
536,770
null
536,770
null
1
71
javascript|jasmine|spy
76,726
<p><code>flipCounter</code> is just another function, even if it also happens to construct an object. Hence you can do:</p> <pre><code>var cSpy = spyOn(window, 'flipCounter'); </code></pre> <p>to obtain a spy on it, and do all sorts of inspections on it or say:</p> <pre><code>var cSpy = spyOn(window, 'flipCounter').andCallThrough(); var counter = flipCounter('foo', options); expect(cSpy).wasCalled(); </code></pre> <p>However, this seems overkill. It would be enough to do:</p> <pre><code>var myFlipCounter = new flipCounter("counter", options); expect(myFlipCounter).toBeDefined(); expect(myFlipCounter.getValue(foo)).toEqual(bar); </code></pre>
29,510,815
how to pass command-line arguments to a program run with the open command?
<p>Is there a way to pass arguments to a program being run via:</p> <pre><code>open -a /Applications/Utilities/Terminal.app ~/my_executable </code></pre> <p>I have tried:</p> <pre><code>open -a /Applications/Utilities/Terminal.app ~/my_executable arg1 arg2 </code></pre> <p>But this is interpreted as telling the terminal to open <code>~/my_executable ~/arg1 ~/arg2.</code></p> <p>I have tried:</p> <pre><code>open -a /Applications/Utilities/Terminal.app '~/my_executable arg1 arg2' </code></pre> <p>But it picks up arg1 and arg2 as if they were part of the path rather than arguments.</p> <p>I have tried:</p> <pre><code>open -a /Applications/Utilities/Terminal.app ~/my_executable | xargs arg1 arg2 </code></pre> <p>I have also tried:</p> <pre><code>open -a /Applications/Utilities/Terminal.app ~/my_executable --args arg1 arg2 </code></pre> <p>But with that flag, args are passed to the terminal.</p> <h2>NOTE</h2> <p>I am only allowed to change the arguments to Terminal.app (the part within [ ]):</p> <pre><code>open -a /Applications/Utilities/Terminal.app [~/my_executable arg1 arg2] </code></pre>
29,511,052
5
4
null
2015-04-08 09:27:08.35 UTC
12
2022-08-22 21:48:08.15 UTC
2015-04-08 09:28:59.073 UTC
null
179,332
null
1,033,323
null
1
30
macos|bash
35,847
<p>Probably the easiest way is to create a temporary shell script, e.g.</p> <pre><code>$ echo &quot;~/my_executable arg1 arg2&quot; &gt; /tmp/tmp.sh ; chmod +x /tmp/tmp.sh ; open -a Terminal /tmp/tmp.sh ; rm /tmp/tmp.sh </code></pre>