source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 1
8
| prompt
stringlengths 209
40.4k
| gold_standard_solution
stringlengths 0
56.7k
| verification_info
stringclasses 1
value | metadata
stringlengths 138
225
| problem_id
stringlengths 9
10
|
---|---|---|---|---|---|---|---|
stackexchange | llm_judgeable_groundtruth_similarity | 2960304 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given an angle $\theta$ , the formulas for $\sin(\frac{\theta}{2})$ and $\cos(\frac{\theta}{2})$ are either positive or negative, which is why $\pm$ is used in their formulas. So, if $\tan(\frac{\theta}{2})=\frac{\sin(\theta/2)}{\cos(\theta/2)}$ , and both the numerator and denominator are either positive or negative (and unless $\theta$ is defined, we must assume they can be both), shouldn't the formula for $\tan(\frac{\theta}{2})$ also be $\pm$ ? Below are the equations I am referring to. $$\sin \left( \frac{u}{2} \right) = \pm \sqrt{\frac{1-\cos(u)}{2}}$$ $$\cos \left( \frac{u}{2} \right) = \pm \sqrt{\frac{1+\cos(u)}{2}}$$ $$\tan \left( \frac{u}{2} \right)=\frac{1-\cos(u)}{\sin(u)}=\frac{\sin(u)}{1+\cos(u)}$$
Now provide the response and nothing else.
| Basically, your first two equations involve square roots, and the third doesn't.The first requires a $\pm$ as $\sin u/2$ may be positive or negative, but by convention square roots are positive. But (using duplication formulas for sine and cosine) $$\frac{1-\cos u}{\sin u}=\frac{1-(1-2\sin^2(u/2))}{2\sin(u/2)\cos(u/2)}=\frac{2\sin^2(u/2)}{2\sin(u/2)\cos(u/2)}=\frac{\sin(u/2)}{\cos(u/2)}=\tan(u/2)$$ etc. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2960304', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/592365/']} | jdg_84441 |
stackexchange | llm_judgeable_groundtruth_similarity | 42794544 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking for a query which will return the week number from given date. What I've already tried is this: select datepart(wk, '2017-02-01') but this returns 5 instead of 6. (february 1st is the 6th week of the year). (week numbers with red)
Now provide the response and nothing else.
| You probably need to specify the first day of your week with set datefirst : set datefirst 1;select datepart(week, '2017-02-01'); returns 6 Depending on the default language, your datefirst might be set to 7 . set datefirst 7;select datepart(week, '2017-02-01'); returns 5 rextester demo: http://rextester.com/KEPB52852 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42794544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/867703/']} | jdg_84442 |
stackexchange | llm_judgeable_groundtruth_similarity | 3615636 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If i perform a standard query in SQLite: SELECT * FROM my_table I get all records in my table as expected. If i perform following query: SELECT *, 1 FROM my_table I get all records as expected with rightmost column holding '1' in all records. But if i perform the query: SELECT *, COUNT(*) FROM my_table I get only ONE row (with rightmost column is a correct count).Why is such results? I'm not very good in SQL, maybe such behavior is expected? It seems very strange and unlogical to me :(.
Now provide the response and nothing else.
| SELECT *, COUNT(*) FROM my_table is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate. You'd want something like SELECT somecolumn,someothercolumn, COUNT(*) FROM my_table GROUP BY somecolumn,someothercolumn | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3615636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69882/']} | jdg_84443 |
stackexchange | llm_judgeable_groundtruth_similarity | 248274 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Show that $V = \mbox{ker}(f) \oplus \mbox{im}(f)$ for a linear map with $f \circ f = f$ I think I need to use the fact that if $v \in V$, then $v = (v - \pi(v)) + \pi(v)$
Now provide the response and nothing else.
| This is just the Fundamental Theorem of Calculus. A PDF (of a univariate distribution) is a function defined such that it is 1.) everywhere non-negative and 2.) integrates to 1 over $\Bbb R$. If we define $F(x) = \int_{-\infty}^x f(t)\ dt$, then the Fundamental Theorem of Calculus gives you the desired result. This function, $F(x)$, is called the "cumulative distribution function," or CDF. It is defined in this manner, so the relationship between CDF and PDF is not coincidental -- it is by design. Note that your last step is incorrect -- $x$ is the independent variable of the derivative there, and it is also the upper limit of the integral (so the resulting integral will be a function in terms of $x$). You can't move the $d/dx$ inside the integral. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/248274', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50029/']} | jdg_84444 |
stackexchange | llm_judgeable_groundtruth_similarity | 49818305 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm fairly new with TypeScript, could you explain what are the difference between these methods of type assertion: // 1. Using :let myStr: string;// 2. Using aslet strLength = (myStr as string).length;// 3. Using <> on left sidelet strLength = <string>myStr.length;// 4. Using <> on right sidelet myObs: Observable<number> and when to use one over the others?Thanks
Now provide the response and nothing else.
| // 1. Using :let myStr: string; // declaring a variable with its type as string// 2. Using aslet strLength = (myStr as string).length; // casting a variable's type to string type using `as` keyword,but here type of strLength is determine by type assertion as there is no explicit type defined.// 3. Using <> on left sidelet strLength = <string>myStr.length; // same as 2 above but using <>// 4. Using <> on right sidelet myObs: Observable<number> // Observable is a generic type you can specify its type(T) in Observable<T>, here it is `number` type. However there is an ambiguity in the language grammar when using <> style assertions in JSX, hence recommended to use as for consistency. Typescript casting : https://acdcjunior.github.io/typescript-cast-object-to-other-type-or-instanceof.html https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html Typescript generic type : https://www.typescriptlang.org/docs/handbook/2/generics.html | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49818305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1615720/']} | jdg_84445 |
stackexchange | llm_judgeable_groundtruth_similarity | 6844981 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: In javascript how can we identify whether an object is a Hash or an Array? In javascript typeof([]) and typeof({}) both return "object". How can I reliably distinguish between an array and an associative array in Javascript? I have thought of testing the object in question to see if it has the "length" attribute (indicating it would be an array), but what then the following would also be seen as an array: {length:5}
Now provide the response and nothing else.
| Modern browsers have Array.isArray built in. For older browsers, you can test for that function and add it when necessary. if( typeof Array.isArray !== 'function' ) { Array.isArray = function( arr ) { return Object.prototype.toString.call( arr ) === '[object Array]'; };}alert( Array.isArray( [] ) ); EDIT: Array.isArray is part of ECMAScript 5 : 15.4.3.2 Array.isArray ( arg ) The isArray function takes one argument arg, and returns the Boolean value true if the argument is an object whose class internal property is "Array"; otherwise it returns false. The following steps are taken: If Type(arg) is not Object, return false. If the value of the [[Class]] internal property of arg is "Array", then return true. Return false. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6844981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274354/']} | jdg_84446 |
stackexchange | llm_judgeable_groundtruth_similarity | 66742033 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Nowadays everytime I create a new project react-native init ProjectName and after it is created I do npx pod-install and then react-native run-ios it gives me error. It happens with every project that I create new. I'm not sure if there is an update that I have to do but here is the error: CompileC /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/Objects-normal/x86_64/FlipperClient.o /Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/FlipperKit/iOS/FlipperKit/FlipperClient.mm normal x86_64 objective-c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'FlipperKit' from project 'Pods') cd /Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods export LANG\=en_US.US-ASCII /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c++ -target x86_64-apple-ios10.0-simulator -fmessage-length\=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit\=0 -std\=gnu++14 -stdlib\=libc++ -fobjc-arc -fmodules -fmodules-cache-path\=/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/ModuleCache.noindex -fmodules-prune-interval\=86400 -fmodules-prune-after\=345600 -fbuild-session-file\=/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/ModuleCache.noindex/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror\=non-modular-include-in-framework-module -fmodule-name\=FlipperKit -Wno-trigraphs -fpascal-strings -O0 -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror\=return-type -Wdocumentation -Wunreachable-code -Wno-implicit-atomic-properties -Werror\=deprecated-objc-isa-usage -Wno-objc-interface-ivars -Werror\=objc-root-class -Wno-arc-repeated-use-of-weak -Wimplicit-retain-self -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wduplicate-method-match -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wno-float-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wshorten-64-to-32 -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wdeprecated-implementations -Wno-c++11-extensions -DPOD_CONFIGURATION_DEBUG\=1 -DDEBUG\=1 -DCOCOAPODS\=1 -DFB_SONARKIT_ENABLED\=1 -DOBJC_OLD_DISPATCH_PROTOTYPES\=0 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk -fasm-blocks -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -Winvalid-offsetof -g -Wno-sign-conversion -Winfinite-recursion -Wmove -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wrange-loop-analysis -Wno-semicolon-before-method-body -Wunguarded-availability -fobjc-abi-version\=2 -fobjc-legacy-dispatch -index-store-path /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Index/DataStore -I/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Products/Debug-iphonesimulator/FlipperKit/include -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Private -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Private/FlipperKit -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-DoubleConversion -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-Folly -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-Glog -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-PeerTalk -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-RSocket -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/FlipperKit -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Yoga -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/FlipperKit/iOS/FlipperKit -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Private/FlipperKit -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/boost-for-react-native -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/boost-for-react-native -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/libevent/include -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/boost-for-react-native -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Flipper-DoubleConversion -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/FlipperKit/iOS/\*\* -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/libevent/include -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/boost-for-react-native -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Flipper-DoubleConversion -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/libevent/include -IHeaders/Private/FlipperKit -IHeaders/Private/FlipperKit/CppBridge -IHeaders/Private/FlipperKit/FBCxxFollyDynamicConvert -IHeaders/Private/FlipperKit/FBDefines -IHeaders/Private/FlipperKit/FKPortForwarding -IHeaders/Private/FlipperKit/FlipperKitHighlightOverlay -IHeaders/Private/FlipperKit/FlipperKitLayoutPlugin -IHeaders/Private/FlipperKit/FlipperKitLayoutTextSearchable -IHeaders/Private/FlipperKit/FlipperKitNetworkPlugin -IHeaders/Private/FlipperKit/FlipperKitReactPlugin -IHeaders/Private/FlipperKit/FlipperKitUserDefaultsPlugin -IHeaders/Private/FlipperKit/SKIOSNetworkPlugin -I/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/DerivedSources-normal/x86_64 -I/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/DerivedSources/x86_64 -I/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/DerivedSources -F/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Products/Debug-iphonesimulator/FlipperKit -F/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/OpenSSL-Universal/Frameworks -F/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Products/Debug-iphonesimulator/XCFrameworkIntermediates/OpenSSL -fmodule-map-file\=/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Products/Debug-iphonesimulator/YogaKit/YogaKit.modulemap -fmodule-map-file\=/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/yoga/Yoga.modulemap -DDEBUG\=1 -DFLIPPER_OSS\=1 -DFB_SONARKIT_ENABLED\=1 -DFOLLY_NO_CONFIG -DFOLLY_MOBILE\=1 -DFOLLY_USE_LIBCPP\=1 -DFOLLY_HAVE_LIBGFLAGS\=0 -DFOLLY_HAVE_LIBJEMALLOC\=0 -DFOLLY_HAVE_PREADV\=0 -DFOLLY_HAVE_PWRITEV\=0 -DFOLLY_HAVE_TFO\=0 -DFOLLY_USE_SYMBOLIZER\=0 -include /Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Target\ Support\ Files/FlipperKit/FlipperKit-prefix.pch -MMD -MT dependencies -MF /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/Objects-normal/x86_64/FlipperClient.d --serialize-diagnostics /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/Objects-normal/x86_64/FlipperClient.dia -c /Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/FlipperKit/iOS/FlipperKit/FlipperClient.mm -o /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/Objects-normal/x86_64/FlipperClient.oCompileC /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/Objects-normal/x86_64/FlipperCppBridgingConnection.o /Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/FlipperKit/iOS/FlipperKit/CppBridge/FlipperCppBridgingConnection.mm normal x86_64 objective-c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'FlipperKit' from project 'Pods') cd /Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods export LANG\=en_US.US-ASCII /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c++ -target x86_64-apple-ios10.0-simulator -fmessage-length\=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit\=0 -std\=gnu++14 -stdlib\=libc++ -fobjc-arc -fmodules -fmodules-cache-path\=/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/ModuleCache.noindex -fmodules-prune-interval\=86400 -fmodules-prune-after\=345600 -fbuild-session-file\=/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/ModuleCache.noindex/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror\=non-modular-include-in-framework-module -fmodule-name\=FlipperKit -Wno-trigraphs -fpascal-strings -O0 -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror\=return-type -Wdocumentation -Wunreachable-code -Wno-implicit-atomic-properties -Werror\=deprecated-objc-isa-usage -Wno-objc-interface-ivars -Werror\=objc-root-class -Wno-arc-repeated-use-of-weak -Wimplicit-retain-self -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wduplicate-method-match -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wno-float-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wshorten-64-to-32 -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wdeprecated-implementations -Wno-c++11-extensions -DPOD_CONFIGURATION_DEBUG\=1 -DDEBUG\=1 -DCOCOAPODS\=1 -DFB_SONARKIT_ENABLED\=1 -DOBJC_OLD_DISPATCH_PROTOTYPES\=0 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk -fasm-blocks -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -Winvalid-offsetof -g -Wno-sign-conversion -Winfinite-recursion -Wmove -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wrange-loop-analysis -Wno-semicolon-before-method-body -Wunguarded-availability -fobjc-abi-version\=2 -fobjc-legacy-dispatch -index-store-path /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Index/DataStore -I/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Products/Debug-iphonesimulator/FlipperKit/include -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Private -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Private/FlipperKit -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-DoubleConversion -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-Folly -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-Glog -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-PeerTalk -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Flipper-RSocket -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/FlipperKit -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/Yoga -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/FlipperKit/iOS/FlipperKit -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Private/FlipperKit -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/boost-for-react-native -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/boost-for-react-native -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/libevent/include -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/boost-for-react-native -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Flipper-DoubleConversion -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/FlipperKit/iOS/\*\* -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/libevent/include -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/boost-for-react-native -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Flipper-DoubleConversion -I/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/libevent/include -IHeaders/Private/FlipperKit -IHeaders/Private/FlipperKit/CppBridge -IHeaders/Private/FlipperKit/FBCxxFollyDynamicConvert -IHeaders/Private/FlipperKit/FBDefines -IHeaders/Private/FlipperKit/FKPortForwarding -IHeaders/Private/FlipperKit/FlipperKitHighlightOverlay -IHeaders/Private/FlipperKit/FlipperKitLayoutPlugin -IHeaders/Private/FlipperKit/FlipperKitLayoutTextSearchable -IHeaders/Private/FlipperKit/FlipperKitNetworkPlugin -IHeaders/Private/FlipperKit/FlipperKitReactPlugin -IHeaders/Private/FlipperKit/FlipperKitUserDefaultsPlugin -IHeaders/Private/FlipperKit/SKIOSNetworkPlugin -I/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/DerivedSources-normal/x86_64 -I/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/DerivedSources/x86_64 -I/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/DerivedSources -F/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Products/Debug-iphonesimulator/FlipperKit -F/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/OpenSSL-Universal/Frameworks -F/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Products/Debug-iphonesimulator/XCFrameworkIntermediates/OpenSSL -fmodule-map-file\=/Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Products/Debug-iphonesimulator/YogaKit/YogaKit.modulemap -fmodule-map-file\=/Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Headers/Public/yoga/Yoga.modulemap -DDEBUG\=1 -DFLIPPER_OSS\=1 -DFB_SONARKIT_ENABLED\=1 -DFOLLY_NO_CONFIG -DFOLLY_MOBILE\=1 -DFOLLY_USE_LIBCPP\=1 -DFOLLY_HAVE_LIBGFLAGS\=0 -DFOLLY_HAVE_LIBJEMALLOC\=0 -DFOLLY_HAVE_PREADV\=0 -DFOLLY_HAVE_PWRITEV\=0 -DFOLLY_HAVE_TFO\=0 -DFOLLY_USE_SYMBOLIZER\=0 -include /Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/Target\ Support\ Files/FlipperKit/FlipperKit-prefix.pch -MMD -MT dependencies -MF /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/Objects-normal/x86_64/FlipperCppBridgingConnection.d --serialize-diagnostics /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/Objects-normal/x86_64/FlipperCppBridgingConnection.dia -c /Users/chaudhrytalha/Documents/xCodeProjects/Learning\ React\ Native/testapp/ios/Pods/FlipperKit/iOS/FlipperKit/CppBridge/FlipperCppBridgingConnection.mm -o /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FlipperKit.build/Objects-normal/x86_64/FlipperCppBridgingConnection.owarning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'Flipper-Glog' from project 'Pods')warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'YogaKit' from project 'Pods')warning: no rule to process file '/Users/chaudhrytalha/Documents/xCodeProjects/Learning React Native/testapp/ios/Pods/Flipper-RSocket/rsocket/README.md' of type 'net.daringfireball.markdown' for architecture 'x86_64' (in target 'Flipper-RSocket' from project 'Pods')warning: no rule to process file '/Users/chaudhrytalha/Documents/xCodeProjects/Learning React Native/testapp/ios/Pods/Flipper-RSocket/rsocket/benchmarks/CMakeLists.txt' of type 'text' for architecture 'x86_64' (in target 'Flipper-RSocket' from project 'Pods')warning: no rule to process file '/Users/chaudhrytalha/Documents/xCodeProjects/Learning React Native/testapp/ios/Pods/Flipper-RSocket/rsocket/benchmarks/README.md' of type 'net.daringfireball.markdown' for architecture 'x86_64' (in target 'Flipper-RSocket' from project 'Pods')warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'boost-for-react-native' from project 'Pods')warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'Flipper-DoubleConversion' from project 'Pods')warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.4, but the range of supported deployment target versions is 9.0 to 14.4.99. (in target 'Flipper-PeerTalk' from project 'Pods')warning: Skipping duplicate build file in Compile Sources build phase: /Users/chaudhrytalha/Documents/xCodeProjects/Learning React Native/testapp/node_modules/react-native/React/FBReactNativeSpec/Native/testapp/node_modules/react-native/React/FBReactNativeSpec/FBReactNativeSpec/FBReactNativeSpec-generated.mm (in target 'FBReactNativeSpec' from project 'Pods')warning: Skipping duplicate build file in Copy Headers build phase: /Users/chaudhrytalha/Documents/xCodeProjects/Learning React Native/testapp/node_modules/react-native/React/FBReactNativeSpec/Native/testapp/node_modules/react-native/React/FBReactNativeSpec/FBReactNativeSpec/FBReactNativeSpec.h (in target 'FBReactNativeSpec' from project 'Pods')** BUILD FAILED **The following build commands failed: PhaseScriptExecution [CP-User]\ Generate\ Specs /Users/chaudhrytalha/Library/Developer/Xcode/DerivedData/testapp-fdikhqqgempmsagsnliemealffwv/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FBReactNativeSpec.build/Script-6B583FC85C8A2C3CF6842DBACCA71427.sh It's a huge error so I included the last few lines. Before this, I use to run the apps smoothly but this just started recently. If I open XCode and run the app from there then the app runs.
Now provide the response and nothing else.
| I've been trying to solve this problem for days on MacOS M1 Big Sur. Nobody else's exact solution worked for me, so I'm going to describe how I came to my solution . Hopefully the process will help someone else figure out what works for them. Everything (for me) needed to be running in Rosetta. Make sure Xcode is running in Rosetta. Make sure your Terminal is running in Rosetta. Make sure pod , yarn , npm , whatever you use, is running the x86 version, not the arm64 version. Make sure you ran yarn install / npm install / pod install with the x86 versions, not the arm64 versions. To clarify arm64 vs. x86, you should ask your Terminal which yarn , which node , which npm , which pod to see the full path to those executables. This is complicated by there being so many ways to install node. I installed node through Homebrew, so my paths below reflect that. For Homebrew on x86 (running in Rosetta Terminal), you should see: $ which node/usr/local/homebrew/bin/node$ which yarn/usr/local/homebrew/bin/yarn$ which npm/usr/local/homebrew/bin/npm Note the /usr/local/homebrew/bin . If you're not running in Rosetta Terminal, you'll see /opt/homebrew/bin . If you're seeing /opt/homebrew/bin anywhere, it's a red flag. Another trap, easy to fall into... I was in Rosetta Terminal with the x86 node, but I realized that my global yarn installation was /opt/homebrew/bin/yarn . I was doing yarn install with arm64 yarn, which can cause problems with your dependencies. Seriously, run all the commands above as a sanity check. Things still weren't working. Same error in Xcode, a mysterious PhaseScriptExecution error on some FBReactNativeSpec.build/Script-********.sh . I opened up Script-********.sh , and saw that it called node_modules/react-native/scripts/generate-specs.sh , which in turned called another script find-node.sh . find-node.sh led me to my problem. I put "echo" debugging statements all over it, and then I ran find-node.sh directly to see what was printed. Sure enough, this one caught something: elif [[ -x "$(command -v brew)" && -s "$(brew --prefix nvm)/nvm.sh" ]]; then echo "AM I GOING CRAZY?" . "$(brew --prefix nvm)/nvm.sh"fi I have no idea what this script is doing, but back in my Terminal I ran echo $(brew --prefix nvm) , which output /usr/local/homebrew/opt/nvm . Clearly, the react-native script is making some kind of decision based on its finding nvm . I don't want nvm to be part of my equation at all; I'm not using it. So in both Rosetta Terminal and Terminal, I brew uninstall nvm . Back in XCode, clean build folder, rebuild, and it works. This is not going to be a satisfying answer for many, as these exact steps will likely not work for you. No one else's exact steps worked for me. After reading dozens of solutions to this problem, it seems that most of them have causes that are node version/path/architecture related. I hope this answer gives you some tools to investigate that yourself. Namely: Make sure which node/yarn/npm is pointing to the correct x86 path. Make sure you installed your node_modules with the correct x86 executable. Debug your node_modules/react-native/scripts/find-node.sh to see if you're tripping up on any extraneous node things in your environment. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66742033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337240/']} | jdg_84447 |
stackexchange | llm_judgeable_groundtruth_similarity | 10149416 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following code which is attempting to normalize the values of an m x n array (It will be used as input to a neural network, where m is the number of training examples and n is the number of features). However, when I inspect the array in the interpreter after the script runs, I see that the values are not normalized; that is, they still have the original values. I guess this is because the assignment to the array variable inside the function is only seen within the function. How can I do this normalization in place? Or do I have to return a new array from the normalize function? import numpydef normalize(array, imin = -1, imax = 1): """I = Imin + (Imax-Imin)*(D-Dmin)/(Dmax-Dmin)""" dmin = array.min() dmax = array.max() array = imin + (imax - imin)*(array - dmin)/(dmax - dmin) print array[0]def main(): array = numpy.loadtxt('test.csv', delimiter=',', skiprows=1) for column in array.T: normalize(column) return arrayif __name__ == "__main__": a = main()
Now provide the response and nothing else.
| If you want to apply mathematical operations to a numpy array in-place, you can simply use the standard in-place operators += , -= , /= , etc. So for example: >>> def foo(a):... a += 10... >>> a = numpy.arange(10)>>> aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> foo(a)>>> aarray([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) The in-place version of these operations is a tad faster to boot, especially for larger arrays: >>> def normalize_inplace(array, imin=-1, imax=1):... dmin = array.min()... dmax = array.max()... array -= dmin... array *= imax - imin... array /= dmax - dmin... array += imin... >>> def normalize_copy(array, imin=-1, imax=1):... dmin = array.min()... dmax = array.max()... return imin + (imax - imin) * (array - dmin) / (dmax - dmin)... >>> a = numpy.arange(10000, dtype='f')>>> %timeit normalize_inplace(a)10000 loops, best of 3: 144 us per loop>>> %timeit normalize_copy(a)10000 loops, best of 3: 146 us per loop>>> a = numpy.arange(1000000, dtype='f')>>> %timeit normalize_inplace(a)100 loops, best of 3: 12.8 ms per loop>>> %timeit normalize_copy(a)100 loops, best of 3: 16.4 ms per loop | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10149416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155268/']} | jdg_84448 |
stackexchange | llm_judgeable_groundtruth_similarity | 580473 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading about order statistics on Wikipedia [retrieved 29 June 2022]: Apparently, if we have a sample with $k$ elements (e.g., $x_1, x_2, ..., x_k$ ) and assume a probability distribution for each of these $k$ elements - we can also determine the probability distribution for each of these individual $k$ elements. It seems that the very definition of an order statistic is based on some underlying assumption of a probability distribution. My Question: Does this mean that for some sample, it is fundamentally impossible to compute the distribution of the $k$ th order statistics without some some choice of probability distributions (i.e., non-parametrically)?
Now provide the response and nothing else.
| "Hey, Dave, how likely is it that my second-largest measurement is at least five?" "What are you measuring?" "Could be anything!" "If you're measuring the number of meters between planets, then I'd say it's pretty likely. If you're measuring the number number of times one gives birth to triplets before age twenty, then I'd say it's pretty unlikely." "...so how likely is it that my second-largest value is at least five?" If you have no idea what the distribution is, then you shouldn't be able to know much about its statistics. The same argument applies to simple statistics like the sample mean. The mean number of meters between planets is likely to be greater than five, while the mean number of times people give birth to triplets by age twenty is unlikely to be greater than five. The original distribution influences the distribution of the statistic. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/580473', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/77179/']} | jdg_84449 |
stackexchange | llm_judgeable_groundtruth_similarity | 335005 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was trying to find alternatives to the use of global variable in some legacy code. But this question is not about the technical alternatives, I'm mainly concerned about the terminology . The obvious solution is to pass a parameter into the function instead of using a global. In this legacy codebase that would mean that I have to change all functions in the long call chain between the point where the value will eventually be used and the function that receives the parameter first. higherlevel(newParam)->level1(newParam)->level2(newParam)->level3(newParam) where newParam was previously a global variable in my example, but it could have been a previously hardcoded value instead. The point is that now the value of newParam is obtained at higherlevel() and has to "travel" all the way to level3() . I was wondering if there was a name(s) for this kind of situation/pattern where you need to add a parameter to many functions that just "pass" the value unmodified. Hopefully, using the proper terminology will allow me to find more resources about solutions for redesign and describe this situation to colleagues.
Now provide the response and nothing else.
| The data itself is called "tramp data" . It is a "code smell", indicating that one piece of code is communicating with another piece of code at a distance, through intermediaries. Increases rigidity of code, especially in the call chain. You are much more constrained in how you refactor any method in the call chain. Distributes knowledge about data/methods/architecture to places that don't care in the least about it. If you need to declare the data that is just passing through, and the declaration requires a new import, you have polluted the name space. Refactoring to remove global variables is difficult, and tramp data is one method of doing so, and often the cheapest way. It does have its costs. | {} | {'log_upvote_score': 9, 'links': ['https://softwareengineering.stackexchange.com/questions/335005', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/87597/']} | jdg_84450 |
stackexchange | llm_judgeable_groundtruth_similarity | 6161812 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Basically I have this script that I'm trying to replace the literal text \r\n with <br /> for proper formatting. I've tried nl2br() and it didn't replace the \r\n with <br /> . Here's the code. $title = isset($post[0]) ? $post[0] : false;$body = isset($post[1]) ? preg_replace('#(\r|\r\n|\n)#', '<br/>', $post[1]) : false;echo $title."<br/>".$body;
Now provide the response and nothing else.
| $body = isset($post[1]) ? preg_replace('#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $post[1]) : false; You'll need three \\\ . Inside single quotes, \\ translates to \ so \\\r becomes \\r which gets fed to the preg_replace funciton. PREG engine has its own set of escape sequences and \r is one of them which means ASCII character #13. To tell PREG engine to search for the literal \r , you need to pass the string \\r which needs to be escaped once more since you have it inside single quotes. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6161812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/715474/']} | jdg_84451 |
stackexchange | llm_judgeable_groundtruth_similarity | 54923904 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I got this this hierarchy of component. A parent component who got 2 child components. I want the first child component to update a property of the parent component, after that the second child component re render.I got main component with two child components: one with select html input and the second one a table of data, the data is coming from the main component as an input. The idea is when i change the selected value, i want to change the data in the main component so the data table can get the new data from the main component. How can i do that? In the first child: @Output() optionSelected = new EventEmitter<string>(); @Input() data; In the parent: @Input() displayOption: string; @Output() dataToSelect When the displayOption updated , i want the second child re render
Now provide the response and nothing else.
| useEffect from React Hooks is by default executed on every render, but you can use second parameter in function to define when the effect will be executed again. That means that function is always executed on mount. In your situation your second useEffect will be run on start and when detailIndex changes. More info: https://reactjs.org/docs/hooks-effect.html Source: Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render. [...] You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect: [...] | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54923904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10186818/']} | jdg_84452 |
stackexchange | llm_judgeable_groundtruth_similarity | 463560 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $$P(x)=x^{6}-x^{5}-x^{3}-x^{2}-x$$$$Q(x)=x^{4}-x^{3}-x^{2}-1$$ Let $z_{1}, z_{2}, z_{3}, z_{4}$ be the roots of Q(x)Prove that $$P\left (z_{1} \right )+ P\left (z_{2} \right )+ P\left (z_{3} \right )+ P\left (z_{4} \right )=6$$
Now provide the response and nothing else.
| $P(x)=Q(x)(x^2+1)+(x^2-x+1)$, hence $\sum P(z_i)= \sum z_i^2 -\sum z_i +4 $. By Vieta's formulas $\sum z_i=1$ and $\sum z_i^2=(\sum z_i)^2-2\sum z_iz_j=1+2=3$. So $\sum P(z_i)=6$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/463560', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/79120/']} | jdg_84453 |
stackexchange | llm_judgeable_groundtruth_similarity | 21597804 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to determine the OS X keyboard layout (or "input source" as OS X calls it) from the terminal so that I can show it in places like the tmux status bar. So I want to know if the current layout is "U.S." or "Swedish - Pro" for example. Googling turns up nothing for me. Is this possible?
Now provide the response and nothing else.
| Note: @MarkSetchell deserves credit for coming up with the fundamental approach - where to [start to] look and what tools to use.After further investigation and back and forth in the comments I thought I'd summarize the solution (as of OS X 10.9.1): do shell script "defaults read ~/Library/Preferences/com.apple.HIToolbox.plist \\ AppleSelectedInputSources | \\ egrep -w 'KeyboardLayout Name' | sed -E 's/^.+ = \"?([^\"]+)\"?;$/\\1/'" Note how \ is escaped as \\ for the benefit of AppleScript , which ensures that just \ reaches the shell. If you want to execute the same command directly from the shell (as one line), it would be: defaults read ~/Library/Preferences/com.apple.HIToolbox.plist AppleSelectedInputSources | egrep -w 'KeyboardLayout Name' |sed -E 's/^.+ = \"?([^\"]+)\"?;$/\1/' The currently selected keyboard layout is stored in the user-level file ~/Library/Preferences/com.apple.HIToolbox.plist , top-level key AppleSelectedInputSources , subkey KeyboardLayout Name . defaults read ensures that the current settings are read (sadly, as of OSX 10.9, the otherwise superior /usr/libexec/PlistBuddy sees only a cached version, which may be out of sync). Since defaults read cannot return an individual key's value, the value of interest must be extracted via egrep and sed - one caveat there is that defaults read conditionally uses double quotes around key names and string values, depending on whether they are a single word (without punctuation) or not. Update : Turns out that AppleScript itself can parse property lists , but it's a bit like pulling teeth .Also, incredibly, the potentially-not-fully-current-values problem also affects AppleScript's parsing. Below is an AppleScript handler that gets the current keyboard layout; it uses a do shell script -based workaround to ensure that the plist file is current, but otherwise uses AppleScript's property-list features, via the Property List Suite of application System Events . Note: Obviously, the above shell-based approach is much shorter in this case , but the code below demonstrates general techniques for working with property lists . # Example call.set activeKbdLayout to my getActiveKeyboardLayout() # ->, e.g., "U.S."on getActiveKeyboardLayout() # Surprisingly, using POSIX-style paths (even with '~') works with # the `property list file` type. set plistPath to "~/Library/Preferences/com.apple.HIToolbox.plist" # !! First, ensure that the plist cache is flushed and that the # !! *.plist file contains the current value; simply executing # !! `default read` against the file - even with a dummy # !! key - does that. try do shell script "defaults read " & plistPath & " dummy" end try tell application "System Events" repeat with pli in property list items of ¬ property list item "AppleSelectedInputSources" of ¬ property list file plistPath # Look for (first) entry with key "KeyboardLayout Name" and return # its value. # Note: Not all entries may have a 'KeyboardLayout Name' key, # so we must ignore errors. try return value of property list item "KeyboardLayout Name" of pli end try end repeat end tellend getActiveKeyboardLayout | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21597804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6962/']} | jdg_84454 |
stackexchange | llm_judgeable_groundtruth_similarity | 95316 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In a (bounded) domain $\Omega \subset \mathbb{R}^n$ , if we're studying the Laplace equation or heat equation or such PDE's we can impose the Dirichlet $u|_{\partial\Omega} \equiv 0$ ,Neumann $D_{\nu} u|_{\partial\Omega}\equiv 0$ or Robin (for $\alpha \in \mathbb{R}$ ) $(D_{\nu} u + \alpha u)|_{\partial \Omega} \equiv 0$ . I know that, for example for the heat equation, Dirichlet eigenvalues correspond physically to the boundary being in contact with a (large) heat bath at $T=0$ . Or, in the Laplace equation, if we're interested in the modes supported by $\Omega$ (as a drum), Dirichlet boundary conditions can be thought of keeping the boundary from moving. Neumann boundary conditions, for the heat flow, correspond to a perfectly insulated boundary. For the Laplace equation and drum modes, I think this corresponds to allowing the boundary to flap up and down, but not move otherwise. My question is: what sort of physical interpretations are there for the Robin boundary conditions? Wikipedia says that they are related to electromagnetic problems, but gives no details. I'd be happy with answers that are not necessarily physics-related, for example, if there was somewhere that Robin boundary conditions naturally arise in a mathematical context, I'd be interested to know about that as well.
Now provide the response and nothing else.
| Here is an example where $\Omega = \mathbb{R}^3$. One way to establish dispersion for the wave equation involves taking a temporal Fourier transform. In order to do this one has to multiply by a cutoff function supported in $t \in [0,\infty)$. You then get the equation $(\Delta+\omega^2)\psi = F$ where $\psi$ is the temporal Fourier transform of the product of the original solution with the cutoff, $\omega$ is the Fourier variable, and $F$ is a function controllable by initial data via a finite time energy inequality. If this plan of attack is going to work, we need to make sure that $\psi$ is uniquely determined by $F$. This of course requires appropriate boundary conditions at $\infty$. These turn out to be 1) $\psi = O\left(|x|^{-1}\right)$ 2) $\frac{\partial\psi}{\partial r} - i\omega\psi = O\left(|x|^{-2}\right)$ This is a sort of Robin condition at infinity. See http://terrytao.wordpress.com/2011/04/21/the-limiting-absorption-principle/ for more details. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/95316', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1540/']} | jdg_84455 |
stackexchange | llm_judgeable_groundtruth_similarity | 48215 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I have already tried a somewhat exhaustive search of the literature, but couldn't find anything close to the problem that I am working on. My question is: When does Mordell's Equation $$y^2 = x^3 + K$$ have only FINITELY many solutions over the field of rational numbers, if we allow $K$ itself to be a rational number? I've seen a "criterion" (i.e. a set of sufficient conditions) related to the class number of the (real/imaginary) quadratic field $\mathbb{Q}(\sqrt{K})$, but it is limited only to $K$ being either 1 or 2 modulo 4. [The actual "criterion" (as stated in the Japanese[?] paper that I allude to) is: Mordell's equation $y^2 = x^3 + K$ has finitely many solutions in $\mathbb{Q}$ if (1) $-K$ is not of the form $3t^2 + 1$ or $3t^2 - 1$; AND (2) $K \equiv 1 (mod 4)$ or $K \equiv 2 (mod 4)$; AND (3) $3$ does not divide the class number of the (real/imaginary) quadratic field $Q(\sqrt{K})$.] Edit: Please refer to this hyperlink for more information as to the context of the previous "criterion". These have since been refuted by Kevin Buzzard (@Kevin - thank YOU!). Thanks to Kevin for pointing out some of the subtle errors in my original post, particularly in the third condition. I was considering the case $K > 0$ (i.e. for real quadratic fields). Now for the context: Let $$Y = W + Z$$ and $$X = WZ$$ where $W$ and $Z$ are defined as: $$W = I(p^k) = \frac{\sigma_{1}(p^k)}{p^k}$$ $$Z = I(m^2) = \frac{\sigma_{1}(m^2)}{m^2}$$ Let $$N = {p^k}{m^2}$$ be a perfect number. (At this point, we don't have to distinguish between even or odd $N$ because the Euclid-Euler model for perfect numbers fits both cases. For more details regarding this, please refer to this link .) We "know" that the exponent $k$ allows us to distinguish between even and odd $N$ in the sense that: (1) If $k$ = 1, then $N$ is even. (2) If $k$ > 1, then $N$ is odd. (Again, refer to the link for more details. There is also a related MathOverflow post here .) Thus, a (possibly) feasible and modern approach to the OPN problem (i.e. determining nonexistence or otherwise) will be to try establishing a finiteness result first (for particular values of $K$). In other words, checking for finiteness of OPNs amounts to checking for finiteness of solutions for Mordell's equation $$Y^2 = X^3 + K$$ for particular values of $K$. And you will only have to check for values of $K$ in the range $[50, 399]$ (for a total of 350 elliptic curves), per the previous answer to this MathOverflow question. $K$ falls in that range because the sum $$Y = W + Z$$ is known to lie in the open interval $(57/20, 3)$. Of course, the "juicy" implication is that: If you will be able to find a condition (e.g. equation, inequality, etc.) relating $k$ to $K$ and you are also able to FURTHER show that the number of solutions to the corresponding Mordell equation $Y^2 = X^3 + K$ is finite FOR ALL SUCH $K$, then it would follow that there are only finitely many perfect numbers (odd AND even). Disclaimer: This is a "naive" approach based on my current understanding of elliptic curve theory. I am well-aware, of course, that the rationals are dense over the real numbers. [Edit: In addition, the abundancy indices and the abundancy outlaws are both dense over the rationals.] Which is why I was kinda surprised that there is NO need to assume ("strict") rationality (i.e. $K \in \mathbb{Q}$ but not in $\mathbb{Z}$) for $K$ when checking for finiteness of solutions to Mordell's equation.
Now provide the response and nothing else.
| First of all, if you replace $k$ by $d^6k$ you get another equation such that the corresponding sets of rational solutions are in bijection. So, you might as well assume that $k$ is an integer. I don't think there is a simple, crisp criterion for the equation to have finitely many solutions. Birch-Swinnerton-Dyer predicts that this is the case if and only if the $L$-function of the elliptic curve does not vanish at $s=1$ and the "if" part is known (Coates-Wiles). There is no shortage of literature on that. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/48215', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10365/']} | jdg_84456 |
stackexchange | llm_judgeable_groundtruth_similarity | 3642362 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am going through the kathy sierra SCJP 1.5 Chapter 9(threads) and there it is mentioned as: Notice that the sleep() method can throw a checked InterruptedException (you'll usually know if that is a possibility, since another thread has to explicitly do the interrupting), so you must acknowledge the exception with a handle or declare I just need a sample program to know when it happens (which i can run on my machine)? I googled but could not find any sample code to test this functionality.. Thanks in Advance
Now provide the response and nothing else.
| Here's an example: public class Test{ public static void main (String[] args) { final Thread mainThread = Thread.currentThread(); Thread interruptingThread = new Thread(new Runnable() { @Override public void run() { // Let the main thread start to sleep try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } mainThread.interrupt(); } }); interruptingThread.start(); try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("I was interrupted!"); } }} To walk through it: Set up a new thread which will sleep for a short time, then interrupt the main thread Start that new thread Sleep for a long-ish time (in the main thread) Print out a diagnostic method when we're interrupted (again, in the main thread) The sleep in the main thread isn't strictly necessary, but it means that the main thread does get to really start sleeping before it's interrupted. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3642362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/305684/']} | jdg_84457 |
stackexchange | llm_judgeable_groundtruth_similarity | 16190 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There are some other questions on this topic but I could not get an answer from reading them. What I want to do is use Apply on some of the arguments of a function, h , and then Map on another argument. Here is what I attempted: Map[Apply[{h[#, ##]} &, {a, b}] &, {1, 2}](* ===>{{h[a, a, b]}, {h[a, a, b]}} *) The elements I want to Map over never get used.But this is not what I want. I want just {h[1,a,b],h[2,a,b]} I could use Table instead of Map but it's slow (slower than just using Apply twice) and I was hoping Map would be faster. I understand that Apply is using both # and ## but I'm not sure what syntax is correct to force the first Slot to be used by Map instead of Apply . EDIT: This is more like what I actually want to do: Map[Apply[{h1[#, ##],h2[#, ##]} &, {RandomReal[], RandomReal[]}] &, {1, 2}] So I want output as {{h1[1, a1,b1], h2[1, a1,b1]},{h1[2, a2,b2], h2[2, a2,b2]}} where I a 's and b 's are the random numbers. So to get this, I think the order of Apply and Map is important.
Now provide the response and nothing else.
| One option is to separate the slots by using an explicit Function for the second argument Map[Function[arg, Apply[{h[arg, ##]} &, {a, b}]], {1, 2}] Regarding your updated question. The approach is the same Map[Function[arg, Apply[{h1[arg, ##], h2[arg, ##]} &, {RandomReal[], RandomReal[]}]], {1, 2}] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/16190', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/377/']} | jdg_84458 |
stackexchange | llm_judgeable_groundtruth_similarity | 103158 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Since the Cantor set is uncountable, it must contain irrationals. I am aware that they can't be normal, so the irrationals in the Cantor set are transcendental. Are there any explicit constructions of such numbers, or can we only indirectly show their existence? Could you please provide the construction for the base $10$ ?
Now provide the response and nothing else.
| Certainly there are irrationals in the Cantor set that can be described simply and explicitly, such as the number that has base $3$ expansion$$0.200200020000200000200000020\dots.$$If the number were rational, its base $3$ representation(s) would be ultimately periodic. But it isn't, because of the increasing number of $0$'s between consecutive $2$'s. Added: An interesting related question is whether there is a closed form irrational number in the Cantor set. The meaning of that question is not clear since we have not defined closed form . However, let $$\alpha=\sum_0^\infty \frac{2}{3^{n(n+1)/2}}.$$Then $\alpha -2$ is an irrational number in the Cantor set, for basically the same reason as the example we gave in the main post. But$$\alpha=\sqrt[8]{3}\; \vartheta(0, 1/\sqrt{3}),$$where $\vartheta$ is the Jacobi $\vartheta$-function. Unfortunately, $\vartheta$ is a pretty exotic function. If we define closed form more narrowly, I do not know what the answer would be. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/103158', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23869/']} | jdg_84459 |
stackexchange | llm_judgeable_groundtruth_similarity | 1608280 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $G$ be a non-trivial group with no non-trivial proper subgroup. Prove that $G$ cannot be infinite group. A hints is given as order of G is not infinite since $a$ and $a^{-1}$ are only generators. I know that infinite cyclic group has only two generators. But don't know how to prove the problem.
Now provide the response and nothing else.
| Take an example where the probability of Robin and Tuck hitting a target respectively are $0.9$ and $1.0$. Your method would give the probability of Robin winning being $\dfrac{0.9}{0.9+1.0}$ when the true probability is $0$. Going back to your original probabilities of hitting of $0.45$ and $0.38$, you would do better saying the probability of Robin winning overall might be $\dfrac{0.45\times(1-0.38)}{ 0.45\times(1-0.38) + 0.38\times(1-0.45)}$ by looking at the decisive and mutually exclusive events of one hitting and the other not. This gives your $0.5717\ldots$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1608280', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211463/']} | jdg_84460 |
stackexchange | llm_judgeable_groundtruth_similarity | 29755000 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am currently using Laravel 5 but any suggestions would be appreciated. I am currently using laravel's form builder and I keep getting this html entity error. I have tried even changing the textarea to a text field and much more to no avail. Below is my full stack trace. STACK TRACE ErrorException in helpers.php line 455:htmlentities() expects parameter 1 to be string, object given (View: /home/fujita/resources/views/emails/contact.blade.php)in helpers.php line 455at CompilerEngine->handleViewException(object(ErrorException), '1') in PhpEngine.php line 43at PhpEngine->evaluatePath('/home/fujita/storage/framework/views/e0d450cfe03e94c1d8bac332b837ce79', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'name' => 'jkj', 'email' => '[email protected]', 'phone' => 'jkjkjk', 'message' => object(Message))) in CompilerEngine.php line 57at CompilerEngine->get('/home/fujita/resources/views/emails/contact.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'name' => 'jkj', 'email' => '[email protected]', 'phone' => 'jkjkjk', 'message' => object(Message))) in View.php line 136at View->getContents() in View.php line 104at View->renderContents() in View.php line 78at View->render() in Mailer.php line 425at Mailer->getView('emails.contact', array('name' => 'jkj', 'email' => '[email protected]', 'phone' => 'jkjkjk', 'message' => object(Message))) in Mailer.php line 288at Mailer->addContent(object(Message), 'emails.contact', null, null, array('name' => 'jkj', 'email' => '[email protected]', 'phone' => 'jkjkjk', 'message' => object(Message))) in Mailer.php line 162at Mailer->send('emails.contact', array('name' => 'jkj', 'email' => '[email protected]', 'phone' => 'jkjkjk', 'message' => 'jkjkj'), object(Closure)) in Facade.php line 216at Facade::__callStatic('send', array('emails.contact', array('name' => 'jkj', 'email' => '[email protected]', 'phone' => 'jkjkjk', 'message' => 'jkjkj'), object(Closure))) in PagesController.php line 37at Mail::send('emails.contact', array('name' => 'jkj', 'email' => '[email protected]', 'phone' => 'jkjkjk', 'message' => 'jkjkj'), object(Closure)) in PagesController.php line 37at PagesController->store(object(ContactFormRequest))at call_user_func_array(array(object(PagesController), 'store'), array(object(ContactFormRequest))) in Controller.php line 246at Controller->callAction('store', array(object(ContactFormRequest))) in ControllerDispatcher.php line 162at ControllerDispatcher->call(object(PagesController), object(Route), 'store') in ControllerDispatcher.php line 107at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141at Pipeline->Illuminate\Pipeline\{closure}(object(Request))at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 108at ControllerDispatcher->callWithinStack(object(PagesController), object(Route), object(Request), 'store') in ControllerDispatcher.php line 67at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\PagesController', 'store') in Route.php line 198at Route->runWithCustomDispatcher(object(Request)) in Route.php line 131at Route->run(object(Request)) in Router.php line 691at Router->Illuminate\Routing\{closure}(object(Request))at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141at Pipeline->Illuminate\Pipeline\{closure}(object(Request))at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101at Pipeline->then(object(Closure)) in Router.php line 693at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 660at Router->dispatchToRoute(object(Request)) in Router.php line 618at Router->dispatch(object(Request)) in Kernel.php line 210at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 43at VerifyCsrfToken->handle(object(Request), object(Closure)) in VerifyCsrfToken.php line 17at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 125at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 55at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 125at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 125at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 36at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 125at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 40at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 125at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 125at Pipeline->Illuminate\Pipeline\{closure}(object(Request))at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101at Pipeline->then(object(Closure)) in Kernel.php line 111at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 84at Kernel->handle(object(Request)) in index.php line 53 contact.blade.php <p>Name: {{ $name }}</p><p>{{ $email }}</p><p>{{ $phone }}</p><p>{{ $message }}</p> ContactFormRequest.php <?php namespace App\Http\Requests;use App\Http\Requests\Request;class ContactFormRequest extends Request { public function authorize() { return true; } public function rules() { return [ 'name' => 'required', 'email' => 'required|email', 'phone' => 'required', 'message' => 'required', ]; }} Form on index.blade.php {!! Form::open(array('route' => 'contact_store', 'class' => 'form')) !!} <div class="form-group"> {!! Form::text('name', null, array('required', 'class'=>'form-control', 'placeholder'=>'Name*')) !!} </div> <div class="form-group"> {!! Form::text('email', null, array('required', 'class'=>'form-control', 'placeholder'=>'Email Address*')) !!} </div> <div class="form-group"> {!! Form::text('phone', null, array('required', 'class'=>'form-control', 'placeholder'=>'Phone')) !!} </div> <div class="form-group"> {!! Form::textarea('message', null, array('required', 'class'=>'form-control', 'placeholder'=>'Message')) !!} </div> <div class="form-group"> {!! Form::submit('Submit', array('class'=>'btn btn-primary')) !!} </div> {!! Form::close() !!} <ul> @foreach($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> PagesController <?php namespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Controllers\Controller;use App\Http\Requests\ContactFormRequest;class PagesController extends Controller { public function home() { // Mail::send('emails.contact', array('name' => 'Justin' ), function($message){ // $message->to('[email protected]', 'Justin')->subject('Test'); // }); return view('pages.index'); } public function store(ContactFormRequest $request){ \Mail::send('emails.contact', array( 'name' => $request->get('name'), 'email' => $request->get('email'), 'phone' => $request->get('phone'), 'message' => $request->get('message') ), function($message) { $message->from('[email protected]'); $message->to('[email protected]', 'Admin')->subject('Chyall Pharma Contact'); }); return \Redirect::route('/')->with('message', 'Thanks for contacting us!');}}
Now provide the response and nothing else.
| The problem is in PagesController inside the Mail::send . 'message' => $request->get('message'); You are using the variable name 'message' and it should be avoided. Note: A $message variable is always passed to e-mail views, and allows the inline embedding of attachments. So, it is best to avoid passing a message variable in your view payload. source: http://laravel.com/docs/5.0/mail#basic-usage in the first note. You might need to change the variable name to be something else. 'bodyMessage' => $request->get('message'); And don't forget the change the variable name in your contact.blade.php as well <p>Name: {{ $name }}</p><p>{{ $email }}</p><p>{{ $phone }}</p><p>{{ $bodyMessage }} // This line.</p> | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29755000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3732124/']} | jdg_84461 |
stackexchange | llm_judgeable_groundtruth_similarity | 1945360 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given $n$ a positive integer, how would you prove from scratch that there exists a rational number $q$ such that $n<q^2<n+1$? By "from scratch" I mean by not using any "advanced" tools like the density of the rational numbers in the real numbers. Just using the definition of rational numbers, how to prove that? I faced this problem while trying to verify that the Dedekind cut $(A,B)$ cannot be determined by a rational number, where: $B=\{x \in Q^+: x^2>2\}$ $A=Q\setminus B$ where $Q^+$ denotes the positive rationals. So, for the purposes of the problem, I still don't even know what the real numbers are.
Now provide the response and nothing else.
| As $1<(\frac54 )^2<2<(\frac32 )^2<3$, we may assume wlog. that $n\ge 3$. With $q=\frac ab$, our task is to find $a,b$ such that $nb^2<a^2<(n+1)b^2$.Pick $b=2n^2$; so we want $4n^5<a^2<4n^5+4n^4$.The set $\{\,k\in\Bbb N\mid k^2>4n^5\,\}$ is a non-empty (contains $3n^3$) subset of $\Bbb N$, hence has a minimal element $a$. Clearly, $a>2n^2>1$.Then $$(a-1)^2=a^2-2a+1>a^2\left(1-\frac 2a\right)>a^2\left(1-\frac 1{n^2}\right) $$If we assume $a^2\ge 4n^5+4n^4$, this leads to $$ (a-1)^2>4n^5+4n^4-4n^3-4n^2=4n^5+4n^2((n-1)^2-2)>4n^5$$contradicting minimality of $a$.Hence $a^2<4n^5+4n^4$, as desired. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1945360', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/360858/']} | jdg_84462 |
stackexchange | llm_judgeable_groundtruth_similarity | 31796798 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I convert 'Jan' to an integer using Datetime? When I try strptime, I get an error time data 'Jan' does not match format '%m'
Now provide the response and nothing else.
| You have an abbreviated month name, so use %b : >>> from datetime import datetime>>> datetime.strptime('Jan', '%b')datetime.datetime(1900, 1, 1, 0, 0)>>> datetime.strptime('Aug', '%b')datetime.datetime(1900, 8, 1, 0, 0)>>> datetime.strptime('Jan 15 2015', '%b %d %Y')datetime.datetime(2015, 1, 15, 0, 0) %m is for a numeric month. However, if all you wanted to do was map an abbreviated month to a number, just use a dictionary. You can build one from calendar.month_abbr : import calendarabbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num} Demo: >>> import calendar>>> abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}>>> abbr_to_num['Jan']1>>> abbr_to_num['Aug']8 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31796798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5100197/']} | jdg_84463 |
stackexchange | llm_judgeable_groundtruth_similarity | 4933958 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I create a new project, I get a strange behavior for unhandled exceptions. This is how I can reproduce the problem: 1) create a new Windows Forms Application (C#, .NET Framework 4, VS2010) 2) add the following code to the Form1_Load handler: int vara = 5, varb = 0;int varc = vara / varb;int vard = 7; I would expect that VS breaks and shows an unhandled exception message at the second line. However, what happens is that the third line is just skipped without any message and the application keeps running. I don't have this problem with my existing C# projects. So I guess that my new projects are created with some strange default settings. Does anyone have an idea what's wrong with my project??? I tried checking the boxes in Debug->Exceptions. But then executions breaks even if I handle the exception in a try-catch block; which is also not what I want. If I remember correctly, there was a column called "unhandled exceptions" or something like this in this dialog box, which would do excatly what I want. But in my projects there is only one column ("Thrown").
Now provide the response and nothing else.
| This is a nasty problem induced by the wow64 emulation layer that allows 32-bit code to run on the 64-bit version of Windows 7. It swallows exceptions in the code that runs in response to a notification generated by the 64-bit window manager, like the Load event. Preventing the debugger from seeing it and stepping in. This problem is hard to fix, the Windows and DevDiv groups at Microsoft are pointing fingers back and forth. DevDiv can't do anything about it, Windows thinks it is the correct and documented behavior, mysterious as that sounds. It is certainly documented but just about nobody understands the consequences or thinks it is reasonable behavior. Especially not when the window procedure is hidden from view of course, like it is in any project that uses wrapper classes to hide the window plumbing. Like any Winforms, WPF or MFC app. Underlying issue is Microsoft could not figure out how to flow exceptions from 32-bit code back to the 64-bit code that triggered the notification back to 32-bit code that tries to handle or debug the exception. It is only a problem with a debugger attached, your code will bomb as usual without one. Project > Properties > Build tab > Platform target = AnyCPU and untick Prefer 32-bit. Your app will now run as a 64-bit process, eliminating the wow64 failure mode. Some consequences, it disables Edit + Continue for VS versions prior to VS2013 and might not always be possible when you have a dependency on 32-bit code. Other possible workarounds: Debug > Exceptions > tick the Thrown box for CLR exceptions to force the debugger to stop at the line of code that throws the exception. Write try/catch in the Load event handler and failfast in the catch block. Use Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) in the Main() method so that the exception trap in the message loop isn't disabled in debug mode. This however makes all unhandled exceptions hard to debug, the ThreadException event is pretty useless. Consider if your code really belongs in the Load event handler. It is very rare to need it, it is however very popular in VB.NET and a swan song because it is the default event and a double-click trivially adds the event handler. You only ever really need Load when you are interested in the actual window size after user preferences and autoscaling is applied. Everything else belongs in the constructor. Update to Windows 8 or later, they have this wow64 problem solved. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4933958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/487356/']} | jdg_84464 |
stackexchange | llm_judgeable_groundtruth_similarity | 33660648 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to be able to modify the filter inside the controller and then return the data based on the altered filter. So for I have an ODataQueryOptions parameter on the server side that I can use to look at the FilterQueryOption. Let's assume the filter is something like this "$filter=ID eq -1" but on the server side if I see "-1" for an ID this tells me that the user wants to select all records. I tried to change the "$filter=ID eq -1" to "$filter=ID ne -1" which would give me all by setting the Filter.RawValue but this is read only. I tried to create a new FilterQueryOption but this requires a ODataQueryContext and a ODataQueryOptionParser which I can't figure out how to create. I then tried to set the Filter = Null and then us the ApplyTo which seems to work when I set a break point in the controller and check this on the immediate window but once it leaves the GET method on the controller then it "reverts" back to what was passed in the URL. This article talks about doing something very similar " The best way to modify a WebAPI OData QueryOptions.Filter " but once it leaves the controller GET method then it reverts back to the URL query filter. UPDATE WITH SAMPLE CODE [EnableQuery][HttpGet]public IQueryable<Product> GetProducts(ODataQueryOptions<Product> queryOptions){ if (queryOptions.Filter != null) { var url = queryOptions.Request.RequestUri.AbsoluteUri; string filter = queryOptions.Filter.RawValue; url = url.Replace("$filter=ID%20eq%201", "$filter=ID%20eq%202"); var req = new HttpRequestMessage(HttpMethod.Get, url); queryOptions = new ODataQueryOptions<Product>(queryOptions.Context, req); } IQueryable query = queryOptions.ApplyTo(db.Products.AsQueryable()); return query as IQueryable<Product>;} Running this code will not return any product this is because the original query in the URL wanted product 1 and I swapped the ID filter of product 1 with product 2. Now if I run SQL Profiler, I can see that it added something like "Select * from Product WHERE ID = 1 AND ID = 2". BUT if I try the same thing by replacing the $top then it works fine. [EnableQuery][HttpGet]public IQueryable<Product> GetProducts(ODataQueryOptions<Product> queryOptions){ if (queryOptions.Top != null) { var url = queryOptions.Request.RequestUri.AbsoluteUri; string filter = queryOptions.Top.RawValue; url = url.Replace("$top=2", "$top=1"); var req = new HttpRequestMessage(HttpMethod.Get, url); queryOptions = new ODataQueryOptions<Product>(queryOptions.Context, req); } IQueryable query = queryOptions.ApplyTo(db.Products.AsQueryable()); return query as IQueryable<Product>;} END RESULT With Microsoft's help. Here is the final output that supports filter, count, and paging. using System.Net.Http;using System.Web.OData;using System.Web.OData.Extensions;using System.Web.OData.Query;/// <summary>/// Used to create custom filters, selects, groupings, ordering, etc.../// </summary>public class CustomEnableQueryAttribute : EnableQueryAttribute{ public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions) { IQueryable result = default(IQueryable); // get the original request before the alterations HttpRequestMessage originalRequest = queryOptions.Request; // get the original URL before the alterations string url = originalRequest.RequestUri.AbsoluteUri; // rebuild the URL if it contains a specific filter for "ID = 0" to select all records if (queryOptions.Filter != null && url.Contains("$filter=ID%20eq%200")) { // apply the new filter url = url.Replace("$filter=ID%20eq%200", "$filter=ID%20ne%200"); // build a new request for the filter HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, url); // reset the query options with the new request queryOptions = new ODataQueryOptions(queryOptions.Context, req); } // set a top filter if one was not supplied if (queryOptions.Top == null) { // apply the query options with the new top filter result = queryOptions.ApplyTo(queryable, new ODataQuerySettings { PageSize = 100 }); } else { // apply any pending information that was not previously applied result = queryOptions.ApplyTo(queryable); } // add the NextLink if one exists if (queryOptions.Request.ODataProperties().NextLink != null) { originalRequest.ODataProperties().NextLink = queryOptions.Request.ODataProperties().NextLink; } // add the TotalCount if one exists if (queryOptions.Request.ODataProperties().TotalCount != null) { originalRequest.ODataProperties().TotalCount = queryOptions.Request.ODataProperties().TotalCount; } // return all results return result; }}
Now provide the response and nothing else.
| Remove [EnableQuery] attribute, your scenario should work, because after using this attribute, OData/WebApi will apply your original query option after you return data in controller, if you already apply in your controller method, then you shouldn't use that attribute. But if your query option contains $select, those code are not working because the result's type is not Product, we use a wrapper to represent the result of $select, so I suggest you use try this: Make a customized EnableQueryAttribute public class MyEnableQueryAttribute : EnableQueryAttribute{ public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions) { if (queryOptions.Filter != null) { queryOptions.ApplyTo(queryable); var url = queryOptions.Request.RequestUri.AbsoluteUri; url = url.Replace("$filter=Id%20eq%201", "$filter=Id%20eq%202"); var req = new HttpRequestMessage(HttpMethod.Get, url); queryOptions = new ODataQueryOptions(queryOptions.Context, req); } return queryOptions.ApplyTo(queryable); }} Use this attribute in your controller method [MyEnableQueryAttribute]public IHttpActionResult Get(){ return Ok(_products);} Hope this can solve your problem, thanks! Fan. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33660648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2022360/']} | jdg_84465 |
stackexchange | llm_judgeable_groundtruth_similarity | 1013336 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I came across with the infinite series$$\sum_{n=1,3,5,\ldots}^{\infty} \frac{1}{n^4}= \frac{\pi^4}{96}$$when calculating a problem about an infinite deep square well in quantum mechanics. Mathematica gives the result in the title, which is enough for a physics problem. But I just want to find how to evaluate the series. I think this sum should be connected to $\zeta(4)=\pi^4/90$, but can't figure out their relation.
Now provide the response and nothing else.
| $$\frac{\pi^4}{90}=\sum_{n=1}^\infty\frac1{n^4}=\sum_{n=1}^\infty\frac1{(2n)^4}+\sum_{n=1}^\infty\frac1{(2n-1)^4}=\frac1{16}\sum_{n=1}^\infty\frac1{n^4}+\sum_{n=1}^\infty\frac1{(2n-1)^4}\implies$$ $$\implies\sum_{n=1}^\infty\frac1{(2n-1)^4}=\left(1-\frac1{16}\right)\frac{\pi^4}{90}=\frac{\pi^4}{96} $$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1013336', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/129973/']} | jdg_84466 |
stackexchange | llm_judgeable_groundtruth_similarity | 2293854 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm parsing a xml file and inserting it into database.However since some text containes double or single quotation I'm having problem with insertion. Currently I'm using the code shown below. But it seems it's inefficient. s = s.replace('"', ' ')s = s.replace("'", ' ') Is there any way I can insert text without replacing these quotations? OR Is there any efficient way to substitute them efficiently ? Thanks !
Now provide the response and nothing else.
| Why can't you insert strings containing quote marks into your database? Is there some weird data type that permits any character except a quote mark? Or are you building an insert statement with literal strings, rather than binding your strings to query parameters as you should be doing? If you're doing cursor.execute('insert into mytable (somefield) values ("%s")' % (mystring)) then that's unsafe and wrong. Instead, you should be doing cursor.execute('insert into mytable (somefield) values (%(myparam)s)', dict(myparam=mystring)) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2293854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127450/']} | jdg_84467 |
stackexchange | llm_judgeable_groundtruth_similarity | 103218 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The default configuration of rsyslogd writes log entries in the traditional format, which looks like this: Nov 30 10:40:01 localhost CRON[30786]: pam_unix(cron:session): session closed for user list There is no year, which is inconvenient for tools that process logs and that require an exact time stamp for each entry, have to implement hacks which guess the year. We can switch rsyslogd to a built-in template called RSYSLOG_FileFormat which changes to a high-precision timestamp. While this is RFC timestamp format is fine for processing, it is verbose gibberish with no whitespace that is hard on the human eyes. 2013-11-30T10:50:01.478204-08:00 localhost CRON[31200]: ... Unfortunately, the template system of rsyslogd is very unfriendly and the documentation is poor. Incredibly, for all the unnecessary complexity in this template system, the value of dateformat is evidently linked to a hard coded C enum of choices! There are parameters like $YEAR but these just pull out the current time, not the one from the message timestamp, so that is a hack. I just want to concentrate on writing the program program which processes the entries. What is the right blurb I can put into a rsyslogd.conf file to get this exact output: Nov 30 2013 10:40:01 localhost CRON[31200]: ... Just the traditional template, plus year.
Now provide the response and nothing else.
| Well, I pulled out rsyslog from its git, made a branch from the closest line to what my system is running and patched it : 2013-11-30 13:39:59 localhost sshd[17331]: Accepted publickey for kaz from 192.1... The above is now produced thanks to these rsyslog.conf lines: $template CustomFormat,"%timegenerated:::date-strftime(%Y-%m-%d %H:%M:%S)% %HOSTNAME% %syslogtag%%msg%0\n"$ActionFileDefaultTemplate CustomFormat The format given in the question is just %b %d %Y %H:%M:%S . The new thing is date-strftime(...) which specifies a date property that is based on strftime formatting. This is applied to the time in the log message (either received time or generated time). Having come into contact with this codebase, I'm now going to shower and soak in bathtub. Feb 2016 update: Looks like this topic came up in a rsyslogd mailing list in 2014, with a reference to this Unix Stackexchange question (the original poster complains that date-strftime isn't working in the version of rsyslogd he's using. No kidding!) This resulted in issue 65 which completely ignores the existence of my strftime -based patch and goes with a clumsy approach with custom replacement items for day of week, hour, year and so on. For instance, to get the year, you have to use %timestamp:::date-year% . This %timestamp:::xxx verbosity has to be repeated for every element of the date! Thus %timestamp:::date-strftime(%Y-%m-%d %H:%M:%S) turns into: %timestamp:::date-year%-%timestamp:::date-month%-%timestamp:::date-day% %timestamp:::date-hour%:%timestamp:::date-minute%:%timestamp:::date-second% Good grief! | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/103218', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/16369/']} | jdg_84468 |
stackexchange | llm_judgeable_groundtruth_similarity | 5383401 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create an application that will have a service running in the background that will be capable of injecting touch screen events into whatever activity is running. I am able to inject events into an Activity that is part of my application by calling Instrumentation.sendPointerSync(motionEvent); However if I try to do this without an activity from my application running I get a permission error saying that I don't have the INJECT_EVENTS permission. I've added this permission to my manifest like this: <uses-permission android:name="android.permission.INJECT_EVENTS"></uses-permission> Its still throwing the same permission exception though. After a bit of searching I've gotten the answer that in order to receive the INJECT_EVENTS permission your app must be signed by the same signature that the system is signed with. I am unclear however what exactly this means. I am going to have to find a custom rom build it and sign it with the same signature that the application is signed with. Then install the custom rom on my device, then install my app and I'll be able to inject the touch events correctly? If this is the case am I better off starting with a custom rom that is already put together, like one from this page Or is it a situation where I am going to need to grab a git copy of the android project and build the whole thing myslef? And either way does anyone know of a place you could point me that would get me working in the right direction to make this happen?
Now provide the response and nothing else.
| Actually, this is pretty simple on a rooted device. I think any app that is running off /system will get access to whatever permissions it requires. So simply manually install your App to /system (as described here http://androidforums.com/droid-all-things-root/64603-installing-apk-system-app-directory.html ): Execute the following commands in the terminal emulator to remount the /system directory as read/write and to install the application into the /system/app directory from the SDCARD: sumount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /systemcp /sdcard/APP.apk /system/app If you prefer to use adb from your computer, execute these commands: adb remountadb shell cp /sdcard/APP.apk /system/app Several users have utilized root explorer from the Google marketplace to simplify this process. Alternatively, check this out: How to compile Android Application with system permissions | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5383401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/507810/']} | jdg_84469 |
stackexchange | llm_judgeable_groundtruth_similarity | 24551816 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I encode a string like this: var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) it doesn't escape the slashes / . I've searched and found this Objective C code: NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)unencodedString, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 ); Is there an easier way to encode an URL and if not, how do I write this in Swift?
Now provide the response and nothing else.
| Swift 3 In Swift 3 there is addingPercentEncoding let originalString = "test/test"let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)print(escapedString!) Output: test%2Ftest Swift 1 In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters var originalString = "test/test"var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())println("escapedString: \(escapedString)") Output: test%2Ftest The following are useful (inverted) character sets: URLFragmentAllowedCharacterSet "#%<>[\]^`{|}URLHostAllowedCharacterSet "#%/<>?@\^`{|}URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}URLPathAllowedCharacterSet "#%;<>?[\]^`{|}URLQueryAllowedCharacterSet "#%<>[\]^`{|}URLUserAllowedCharacterSet "#%/:<>?@[\]^` If you want a different set of characters to be escaped create a set: Example with added "=" character: var originalString = "test/test=42"var customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSetvar escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)println("escapedString: \(escapedString)") Output: test%2Ftest%3D42 Example to verify ascii characters not in the set: func printCharactersInSet(set: NSCharacterSet) { var characters = "" let iSet = set.invertedSet for i: UInt32 in 32..<127 { let c = Character(UnicodeScalar(i)) if iSet.longCharacterIsMember(i) { characters = characters + String(c) } } print("characters not in set: \'\(characters)\'")} | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/24551816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3801276/']} | jdg_84470 |
stackexchange | llm_judgeable_groundtruth_similarity | 130028 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I often want to have the same code at the beginning of every new notebook. Is it possible to configure Mathematica, such that whenever you create a new notebook some user-defined code will always be created with the new document. E.g. commonly used plot configurations, packages, directory setting etc. Needs["PolygonPlotMarkers"]Needs["TwoAxisListPlot"]fm[name_, size_: 7] := Graphics[{EdgeForm[], PolygonMarker[name, Offset[size]]}]PlotStyles = {Frame -> True, FrameStyle -> Directive[Black, Thin], Axes -> False, ImageSize -> 350, AspectRatio -> 1.0}; At the begining of every new notebook.
Now provide the response and nothing else.
| I recommend creating a palette with a button that can insert the code for you. Then save the palette and make it easy to access through the palettes menu. Create palette Suppose your code is (for sake of simplicity), code1 = HoldComplete[1+1]; The create the palette: CreatePalette[ Column[{ PasteButton["Template1", Defer @@ code1] }], WindowTitle -> "Templates" ] I put in a column in case you want multiple buttons that insert different pieces of code. Install palette for permanent use Now go to File → Install..., and in the dialog that comes up select Palettes, then the palette you just created. For Install Name, type a filename, e.g. Templates.nb , then press OK. Now close the palette. From now on the palette will be permanently present in the Palettes menu. If you want to remove it, the file is located at SystemOpen@FileNameJoin[{$UserBaseDirectory, "SystemFiles", "FrontEnd", "Palettes"}] Simply remove it. It is my personal opinion that inserting code in every single notebook you open will eventully be both annoying and counterproductive. I recommend the palette solution instead, which just takes a single mouseclick, so it's simple and quick. It lets you keep several code snippets and insert whichever you want. If you're feeling up to it, you can even create a whole snippet system where the snippets are stored in a file (perhaps notebook) and can be selected and inserted with a simple GUI (e.g. dropdown boxes). Many text editors have such a thing. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/130028', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/27119/']} | jdg_84471 |
stackexchange | llm_judgeable_groundtruth_similarity | 96192 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the book Daemon by Daniel Suarez a technique gets described , that enables a device to create an acoustical illusion of a moving person inside a house. Just then a voice called out clearly from the end of the hallway upstairs. ‘Who’s there?’ […] No reply. But they heard walking again. The footsteps came down the marble stairs to their right, some distance away from them. They could clearly see the staircase, but no one was there. They could hear the sound of a hand sliding down the metal railing. […] The footsteps were moving across the floor to them now. […] Then, in midair not five feet in front of them , a man’s voice shouted, ‘You don’t belong here!’ (page 94) As I searched the internet for more information on the mind-shaking technology described by Suarez, I just encountered papers (and videos) on the use of a single hypersonic sound beam, that creates audible sound where it hits a surface. This leads to an effect that most people describe as a 'god voice' similar to the experience of the use of bone conducting speakers. However what I am searching for is an answer to the question, if it is possible to create sound in mid air (at a chosen position in 3D space) as the author is shaping the picture of the technology, cited below. A HyperSonic Sound system – or HSS – does not use physical speakers. HSS pulsates quartz crystals at a frequency thousands of times faster than the vibrations in a normal speaker – creating ultrasonic waves at frequencies far beyond human hearing. Unlike lower-frequency sound, these waves travel in a tight path – a beam. Two beams can be focused to intersect each other, and where they interact they produce a third sonic wave whose frequency is exactly the difference between the two original sounds. In HSS that difference will fall within the range of human hearing – and will appear to come from thin air . This is known as a Tartini Tone – in honor of Giuseppe Tartini, the eighteenth-century Italian composer who first discovered this principle. PS: The reason why I even bother to search for information about a technology mentioned in a novel, is the author's concern, to just describe technology, that is in development in some lab and not placed in science fiction. He has a website for the description of some technology used in his book.
Now provide the response and nothing else.
| It isn't possible to create an audio source in mid-air using the method you've described. This is because the two ultrasonic waves would create an audible source if the listener were standing at that spot, but those waves would continue to propagate in the same direction afterwards. You would need, as I point out below, some sort of medium which scattered the waves in all directions to make it seem as if the sound were coming from the point at which you interfered the two waves. It is possible, however, to make the user percieve the sound as coming from a specific location, but it isn't as easy as the author makes it seem. I can think of two different ways. First of all, as described by @reirab, you can get audio frequencies by interfering two sound waves of high frequency. When they interfere they will generate a beat note which has the frequency of the difference between the two frequencies. I.E. if you send a sound beam with frequency $f_1=200\ \text{kHz}$ and another beam with $f_2=210\ \text{kHz}$, the frequency heard in the region where they combine will be $\Delta f-=f_2-f_1=10\ \text{kHz}$ which is in the audio band of humans. There is an additional difficulty. You will need the sound to come out in a well-defined, narrow (collimated) beam, and this is not terribly easy to do. A typical speaker emits sound in all directions. There are many techniques for generating such beams, but one is to use a phased array . How can you use this to make a person perceive the sound as coming from a specific point? Sending Two Different Volumes to the Two Ears What does it mean to perceive sound as coming from a specific location? Our ears are just microphones with cones which accept sound mostly from one direction (excepting low frequencies). A large part of the way we determine where the sound came from is just the relative volume in our two ears. So, you could use the interference effect described above with beams which are narrow enough that you can target each ear. By using two separate sets of beams targeting each ear with different volumes, you could make the person perceive the sound as coming from a specific location; at least as well as a 3D movie makes a person perceive images in 3D. Hitting a Material Which Scattered the Sound Isotropically The second method is to use the same interference effect, but this time combining the two beams at a point where a material scattered the sound waves in all directions. I'm going to be honest, I'm not sure how realistic such materials are, but lets assume they exist for now. If you did so, the two sound beams would be scattered with equal amplitude in all directions and the person you are trying to fool would percieve the sound as coming from this point. This method has the advantage of truly sounding to the person as if the sound came from that direction in all respects including reflections, phasing, etc. In summary, the idea is definitely possible (maybe there are more ways than I've given), but it isn't as simple as the passage in the book makes it out to be. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/96192', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/38681/']} | jdg_84472 |
stackexchange | llm_judgeable_groundtruth_similarity | 1149963 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two equations that I have been trying to prove. The first of which is: F(n + 3) = 2F(n + 1) + F(n) for n ≥ 1. For this equation the answer is in the back of my book and the proof is as follows: 1) n = 1: F(4) = 2F(2) + F(1) or 3 = 2(1) + 1, true. 2) n = 2: F(5) = 2F(3) + F(2) or 5 = 2(2) + 1, true. 3) Assume for all r, 1 ≤ r ≤ k: F(r + 3) = 2F(r + 1) + F(r) 4) Then F(k + 4) = F(k + 2) + F(k + 3) = 5) 2F(k) + F(k - 1) + 2F(k + 1) + F(k) = 6) 2[F(k) + F(k + 1)] + [F(k - 1) + F(k)] = 7) 2F(k + 2) + F(k + 1) My first question here is how do I know how many values of n to test for? Here they chose two. My next question is how did they get from line 3 to line 4? I understand how the statement is correct but why is this chosen? I also understand that I need to prove it's true for all values of r because if I do that it implies that it is true for k + 1. Is it just to find a relation to F(r + 3) on line 3? If that was the case why not just have F(k + 3) = F(k + 2) + F(k + 1)? My final question about this is how did they get from line 4 to 5? The second equation I want to prove is: F(n + 6) = 4F(n + 3) + F(n) for n ≥ 1 I'm able to prove n = 1 and n = 2 is true but I get stuck on going from what would be line 3 - 4 on this problem. As this is my problem for homework the answer is not in the back of the book. Now that I've gotten the help I just want to update this with the proof for my second equation (I haven't gotten the formatting down yet so bear with me): F(n + 6) = 4F(n + 3) + F(n) 1) n = 1: F(7) = 4F(4) + F(1) or 13 = 12 + 1, true. 2) n = 2: F(8) = 4F(5) + F(2) or 21 = 20 + 1, true. 3) Assume for all r, 1 ≤ r ≤ k: F(r + 6) = 4F(r + 3) + F(r) 4) Then F(k + 7) = 4F(k + 4) + F(k + 1) = 5) F(k + 4) + F(k + 4) + F(k + 4) + F(k + 4) + F(k + 1) = 6) F(k + 4) + F(k + 4) + F(k + 4) + F(k + 3) + F(k + 2) F(k + 1) = 7) F(k + 4) + F(k + 4) + F(k + 4) +F(k + 3) + F(k + 3) = 8) F(k + 5) + F(k + 5) + F(k + 4) = 9) F(k + 6) + F(k + 5) = 10) F(k + 7)
Now provide the response and nothing else.
| For each $n\geq 0$, let $S(n)$ denote the statement$$S(n) : F_n+2F_{n+1}=F_{n+3}.$$First note that $S(n)$ has a rather trivial direct proof:$$F_{n+3} = F_{n+1}+F_{n+2} = F_{n+1}+(F_n+F_{n+1})=F_n+2F_{n+1}.$$Thus, it is really not necessary to prove your statement by using induction, but let's do it anyway since we're on the topic. Base step: $S(0)$ says $F_0+2F_1=F_3$, which is true since $F_0=0, F_1=1$, and $F_3=2$. Inductive step: For some fixed $k\geq 0$, assume that $S(k)$ is true. To be shown is that$$S(k+1) : F_{k+1}+2F_{k+2} = F_{k+4}$$follows from $S(k)$. Note that $S(k+1)$ can be proved without the inductive hypothesis; however, to formulate the proof as an inductive proof, following sequence of equalities uses the inductive hypothesis:\begin{align}F_{k+1}+2F_{k+2} &= F_{k+1}+2(F_k+F_{k+1})\\[0.5em] &= (F_{k+1}+F_k)+(F_k+2F_{k+1})\\[0.5em] &= F_{k+2}+(F_k+2F_{k+1})\\[0.5em] &= F_{k+2}+F_{k+3}\qquad\text{by $S(k)$}\\[0.5em] &= F_{k+4}.\end{align}This completes the inductive step $S(k)\to S(k+1)$. Thus, by mathematical induction, $S(n)$ is true for every $n\geq 0$. $\Box$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1149963', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/215745/']} | jdg_84473 |
stackexchange | llm_judgeable_groundtruth_similarity | 7534411 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am just wondering whether the below code is valid? <c:choose> <c:when test="${empty example1}"> </c:when> <c:when test="${empty example2}"> </c:when> <c:otherwise> </c:otherwise> </c:choose>
Now provide the response and nothing else.
| In a c:choose ,the first when for which the test is true is the winner.In the c:choose below,if "first test" and "second test" are both true,then the "Kpow" h2 will be added to the html page and the "Blammy" will not. <c:choose> <c:when test="first test"> <h2>Kpow</h2> </c:when> <c:when test="second test"> <h2>Blammy</h2> </c:when></c:choose> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7534411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/920504/']} | jdg_84474 |
stackexchange | llm_judgeable_groundtruth_similarity | 516419 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My physics textbook states that in measuring the time period of a pendulum it is advised to measure the time between consecutive passage though the mean position in the same direction. This results in better accuracy than measuring time between consecutive passage through an extreme position. Why is one method of finding the time period better than the other? How can this affect the accuracy of the final result? I think it shouldn't make any difference, as the time taken for one full oscillation is independent of the choice of the start/end point. Is the statement in the book really correct?
Now provide the response and nothing else.
| To measure the time period it is useful to use a fiducial (reference) mark which in this case could be a vertical line drawn on a piece of card and placed “behind” the pendulum bob/string. It is assumed that the time for a number of complete oscillations will be measured to enable one to find a more accurate value of the period than just measuring the time of just one complete oscillation. If the fiducial mark is placed at an extreme of the motion of the bob then one can estimate when the bob reaches that mark to start and stop the timer. However because the amplitude of motion of the bob will decrease with time the estimation of exactly when the bob stops will become progressively more difficult as the position at which this happens can only be guessed. Even a small error in the location of the position of the bob will result in a relatively large error in the timing because the bob/string would be moving slowly. Putting the fiducial mark at or near the centre of an oscillation does not require any estimate of when the bob (or string) passes across the fiducial mark as the bob/string will always pass the fiducial mark.Also because the speed of the bob/string is a maximum at this position the error in taking a reading when the bob/string is not quite passing the fiducial mark is going to be relatively small. An order of magnitude calculation to estimate the possible error in the measurement of a time interval when the bob has not quite reached the fiducial mark by $1\,\rm mm$ at the centre and extreme of a swing.. A simple pendulum of length of $1$ metre has a period of approximately $2$ seconds so $\omega \approx 3 \,\rm s^{-1}$ . For an angular swing of about $5^\circ$ the amplitude of motion is approximately $160$ mm. Approximating the motion of the bob to a straight line gives an equation for the displacement in millimetres $x = 100\sin (3\,t)$ where the displacement is zero when time $t=0$ . For the bob to move from $x=0\,\rm mm$ to $x=1\,\rm mm$ takes approximately $0.003\,\rm s$ and to move from $x=99\,\rm mm$ to $x=100\,\rm mm$ takes approximately $0.05\,\rm s$ . | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/516419', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/238167/']} | jdg_84475 |
stackexchange | llm_judgeable_groundtruth_similarity | 1422107 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm not sure if it is a error typing in the book or just something I can't solve hope you could help me, so here it is: $$z \bar z+z^2 = \bar {\bar z} - z +2$$ This is the same way they write it in the book, Thanks :)
Now provide the response and nothing else.
| Let $z=a+bi$ where $a,b\in\mathbb R$. Now noting that $\bar{\bar z}=z$,$$z\bar z+z^2=\bar{\bar z}-z+2$$$$\iff z(\bar z+z)=2$$$$\iff (a+bi)\cdot 2a=2$$$$\iff 2a^2=2\quad\text{and}\quad 2ab=0$$$$\iff a=\pm 1,b=0$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1422107', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/262321/']} | jdg_84476 |
stackexchange | llm_judgeable_groundtruth_similarity | 231292 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Decision stump is a decision tree with only one split. It can also be written as a piecewise function. For example, assume $x$ is a vector, and $x_1$ is the first component of $x$, in regression setting, some decision stump can be $f(x)= \begin{cases} 3& x_1\leq 2 \\ 5 & x_1 > 2 \\ \end{cases}$ But is it a linear model? where can be written as $f(x)=\beta^T x$? This Question may sound strange, because as mentioned in the answers and comments, if we plot the piecewise function it is not a line. Please see next section for why I am asking this question. EDIT: The reason I ask this question is logistic regression is a (generalized) linear model and the decision boundary is a line, also for decision stump. Note, we also have this question: Why is logistic regression a linear model? . On the other hand, it seems not true that decision stump is a linear model. Another reason I asked this is because of this question: In boosting, if the base learner is a linear model, does the final model is just a simple linear model? where, if we use a linear model as a base learner, we get nothing more than linear regression. But if we select base learner as a decision stump, we are getting very interesting model. Here is one example of decision stump boosting on regression with 2 features and 1 continuous response.
Now provide the response and nothing else.
| No, unless you transform the data. It is a linear model if you transform $x$ using indicator function:$$x' = \mathbb I \left(\{x>2\}\right) = \begin{cases}\begin{align} 0 \quad &x\leq 2\\ 1 \quad &x>2 \end{align}\end{cases}$$ Then $f(x) = 2x' + 3 = \left(\matrix{3 \\2}\right)^T \left(\matrix{1 \\x'}\right)$ Edit: this was mentioned in the comments but I want to emphasize it here as well. Any function that partitions the data into two pieces can be transformed into a linear model of this form, with an intercept and a single input (an indicator of which "side" of the partition the data point is on). It is important to take note of the difference between a decision function and a decision boundary . | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/231292', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/113777/']} | jdg_84477 |
stackexchange | llm_judgeable_groundtruth_similarity | 654 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In real world applications is there a concrete benefit when using $\mathcal{O}(\log(\log(n))$ instead of $\mathcal{O}(\log(n))$ algorithms ? This is the case when one use for instance van Emde Boas trees instead of more conventional binary search tree implementations. But for example, if we take $n < 10^6$ then in the best case the double logarithmic algorithm outperforms the logarithmic one by (approximately) a factor of $5$. And also in general the implementation is more tricky and complex. Given that I personally prefer BST over VEB-trees, what do you think ? One could easily demonstrate that : $\qquad \displaystyle \forall n < 10^6.\ \frac{\log n}{\log(\log(n))} < 5.26146$
Now provide the response and nothing else.
| Do not forget that $\log n$ still grows exponentially (in $\log(n)$) faster than $\log(\log n)$! Indeed, if you look at the quotient of $\log(n)$ and $\log(\log(n))$, there is not much impressive to see: [ source ] But still, you get a factor five to six for sizes up to $100000$. Note that larger sizes are not uncommon in practice, and a speedup by that factor is awesome ! It may make the difference between having results after lunch or only tomorrow. Be aware that part of the speedup may be eaten away by higher constants of the tree implementation; you would have to plot (or analyse) $c\cdot \log(n)$ and $d\cdot \log(\log(n))$ with $c,d$ the actual runtime constants to get a real picture. Additionally, what Dave mentions is important: if the operation sped up thusly is executed, say, linearly often, constant speedups become linear speedups, i.e. you may decrease the leading constant of your entire algorithm! As I said above, that is awesome. Just look at what happens if you run the operation $n$ times: [ source ] Now if that's not worth the trouble I don't know what. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/654', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/652/']} | jdg_84478 |
stackexchange | llm_judgeable_groundtruth_similarity | 620626 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a query that is taking a long time in the middle of a transaction. When I get the wait_type of the process it is PAGEIOLATCH_SH . What does this wait type mean and how can this be resolved?
Now provide the response and nothing else.
| From Microsoft documentation : PAGEIOLATCH_SH Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem. In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently. If your query is like this: Select * from <table> where <col1> = <value> order by <PrimaryKey> , check that you have a composite index on (col1, col_primary_key) . If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen. Both of them are very disk I/O consuming operations on large tables. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/620626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1545/']} | jdg_84479 |
stackexchange | llm_judgeable_groundtruth_similarity | 34344 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently, there is a lot of research focused on solving the folding patterns of proteins using computers (Folding@Home, https://fold.it/portal/ , etc.). The question that I have is: How do you know when you get it right? Is there some way of verifying, in silico , that you have found a legitimate/correct structure for a protein?
Now provide the response and nothing else.
| Overview Modelling has come on leaps and bounds over the last decade or so and in many cases has acted as a sometimes viable, and inexpensive substitute for experimental structures. How do you know when you get it right? Ultimately, one still needs experimental evidence to know when a model generated in silico is right. But there are ways of scoring a model for how likely it is to be right. Is there some way of verifying, in silico, that you have found a legitimate/correct structure for a protein? There are lots of ways to score and verify your models. Each method tells you something slightly different about the merits, or lack thereof, of your structural model. Some are designed to weed out the obviously awful models and some allow you to detect exactly where your model looks to be accurate or inaccurate. MODELLER Homology modelling output verification on the fly. I am most familiar with modeller for homology modelling. Other softwares are available and they are each evaluated by CASP every two years since 1994. In homology modelling there are 3 common scoring systems that can be used to assess the biochemical viability of a model. This email covers when to use each one. My answer expands and explains a bit more. molpdf is the Modeller objective function. GA341 , discussed here is derived from Z-score (calculated with a statistical potentialfunction), which is a target-template sequence identity, and ameasure of structural compactness. DOPE is a more up to date method, first published in 2006, and is more true to "biological viability". From the publication : DOPE is based on an improved reference state that corresponds to noninteracting atoms in a homogeneous sphere with the radius dependent on a sample native structure; it thus accounts for the finite and spherical shape of the native structures. Which to use depends on what you want to do with the model, but of those three scores, DOPE is the most reliable at separating native-like models from "decoys". DOPE is usually the starting place for figuring out which models might be right and which models are just plain rubbish. Note: If you use Rosetta then there will be equivalents to these, or you can run your generated models through these techniques. If you are using SWISS MODEL that comes with it's own somewhat black box verification techniques but you can still export the model for further verification. General model check against experimental data. A further validation of homology modelling methods or other structural models is ProSA . ProSA provides a great visual representation of where the z-score lies amongst actual crystal and NMR structures. There are probably others that do similar functions, but this is my personal go-to to get an idea of where my structure lies among experimentally gathered structures. Sensitive residue by residue verification. Although the aforementioned methods examine each residue, they usually output an overall score. Residue by residue scores are also available and require a lot of careful interpretation. For example, if you are analysing catalytic activity, a surface looping region that scores poorly might not be an issue, but a core catalytic residue that scores poorly renders the model useless. This means that just because your model has a good (lower) overall DOPE score than another model, doesn't mean it is necessarily a more accurate model for what you are interested in. There are plenty of sensitive modelling scoring systems. Some of which are XdVal, MTZdump , the famous albeit old-school Ramachandran Plotting method, pdbU , pdbSNAFU , PROCHECK , Verify3D , and ERRAT to name a few. Each has a place when checking how correct your model is. | {} | {'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/34344', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/15796/']} | jdg_84480 |
stackexchange | llm_judgeable_groundtruth_similarity | 3540243 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's define a decibinary number system, where each bit (or digit) can range from $0$ to $9$ , but it's place value corresponds to the one in the binary system. For example: $$(2020)_{decibinary} = 2 \times 2^3 + 0 \times 2^2 + 2 \times 2^1 + 0 \times 2^0 = 16 + 2 = (18)_{10}$$ Note, that many decibinary numbers can evaluate to the same decimal value, e.g. $$(1220)_{decibinary} = 1 \times 2^3 + 2 \times 2^2 + 2 \times 2^1 + 0 \times 2^0 = 8 + 8 + 2 = (18)_{10}$$ I am looking for an expression (say function $f$ ) or an efficient algorithm, that, given a decimal number $n$ , gives me a number of decibinary numbers that evaluate to $n$ . Of course I am treating e.g. $(05)_{decibinary}$ the same as $(5)_{decibinary}$ (leading zeros do not matter). As an aside, I found the concept of decibinary numbers in this HackerRank question , where I thought it might actually be useful to be able to quickly compute $f(n)$ to solve the problem efficiently. $$\\$$ Below are my thoughts and approaches to tackle the problem. What I tried was to first see if there is a pattern: $$f(0) = 1 \\ f(1) = 1 \\ f(2) = 2 \\ f(3) = 2 \\ f(4) = 4 \\ f(5) = 4 \\ f(6) = 6 \\ f(7) = 6 \\ f(8) = 10 \\ f(9) = 10 \\ f(10) = 13$$ but $10$ seems to break the pattern, as there are (if I didn't skip anything) $13$ decibinary numbers that evaluate to $(10)_{10}$ : $18, 26, 34, 42, 50, 106, 114, 122, 130, 202, 210, 1002, 1010$ (if it was $14$ I could see some pattern, but unfortunately $10$ cannot be encoded using one digit in decibinary ). What I spotted, however, is that I could recursively calculate $f$ (or use dynamic programming to build up a lookup table bottom-up in order to be able to reuse the computations). For instance, I know that the decibinary number evaluating to $10$ will have at max. $4$ digits (because $(10000)_{decibinary}$ already evaluates to $16$ ). So I can represent $f(10)$ as a sum of the number of ways I can encode $10$ using $4, 3, 2$ and $1$ digit (the latter being $0$ as there is no way I can represent $10$ using 1 digit). Let's try to compute the number of ways to represent $(10)_{10}$ using $b=4$ digits: The first leading digit can only be $1$ ( $1 \times 2^3$ ), and then, the remaining digits need to evaluate to $10 - 8 = 2$ and we can use the lookup : $f(2) = 2$ . Using $b=3$ digits we can use $1$ and $2$ as non-zero leading digits: $1$ will require a lookup $f(6)$ and $2$ will require a lookup of $f(2)$ , giving a sum of $6 + 2 = 8$ which is false (there are only $6$ ways to encode $10$ using $b=3$ bits) because $6$ itself can be encoded using $b=3$ bits and here I am considering two representations two times instead of one (if this makes sense). It seems to me like the lookup needs to be built such that it does not store $f(n)$ but $f(n, b)$ , i.e. the number of ways to encode $(n)_{10}$ in decibinary using $b$ bits (without a leading zero), which already seems like quite a complex (and inefficient) approach to me. Also each time I'd need to perform a check for a minimum number of bits needed to encode a number (e.g. $10$ cannot be encoded using $b=1$ ). What are your thoughts? Is there a neat and a simple way to find $f(n)$ ?
Now provide the response and nothing else.
| You can use generating functions for this. The generating function for decibinary numbers is \begin{eqnarray}\prod_{k=0}^\infty\sum_{j=0}^9x^{2^kj}=\prod_{k=0}^\infty\frac{1-x^{10\cdot2^k}}{1-x^{2^k}}\;.\end{eqnarray} The number of ways to represent $n$ as a decibinary number is the coefficient of $x^n$ in this generating function. For instance, for decibinary numbers with up to $4$ digits, we can truncate the product at $k=3$ and let Wolfram|Alpha compute the expansion: $$1 + x + 2 x^2 + 2 x^3 + 4 x^4 + 4 x^5 + 6 x^6 + 6 x^7 + 10 x^8 + 10 x^9 + 13 x^{10} + \cdots\;,$$ in agreement with your counts. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3540243', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/581561/']} | jdg_84481 |
stackexchange | llm_judgeable_groundtruth_similarity | 40656871 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a vector of the following data structure struct Rule { int m_id = -1; std::wstring name; double angle; };std::vector<Rule>& topPriorityRules; and I am erasing the first element of the vector using topPriorityRules.erase(topPriorityRules.begin()); Is there any other good alternative for removing elements from the front of a std::vecor ?
Now provide the response and nothing else.
| Given std::vector<Rule>& topPriorityRules; The correct way to remove the first element of the referenced vector is topPriorityRules.erase(topPriorityRules.begin()); which is exactly what you suggested. Looks like i need to do iterator overloading. There is no need to overload an iterator in order to erase first element of std::vector . P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40656871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/696219/']} | jdg_84482 |
stackexchange | llm_judgeable_groundtruth_similarity | 14807746 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to PHP and am currently still learning. I'm having issues with my registration form I think. username , password , email all insert into MySQL successfully. registered and last_seen do not. I thought I was using getTimestamp() wrong, but it echos what I need. However when I try to insert both timestamp fields into MySql, I see 0000-00-00 00:00:00 in those fields instead of what it echoed before the sql query. What am I doing wrong here? Any help is much appreciated. $date = new DateTime(); $time = $date->getTimestamp(); echo '<div class="box_grey">' . $time . '</div>'; $sql = ' INSERT INTO users (username, password, email, registered, last_seen) VALUES (:username, :password, :email, :registered, :last_seen)'; $stmt = $pdo->prepare($sql); $stmt->bindParam(':username', $username); $stmt->bindParam(':password', $password); $stmt->bindParam(':email', $email); $stmt->bindParam(':registered', $time); $stmt->bindParam(':last_seen', $time); $stmt->execute(); print '<div class="box_grey">errorCode() ' . $stmt->errorCode() . '<br /><br />'; print_r($stmt->errorInfo()); echo '</div>'; echo '<div class="box_grey">Registered successfully!</div>'; Here's what SHOW CREATE TABLE users; shows me. CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'User''s unique ID number', `username` varchar(16) NOT NULL, `password` varchar(100) NOT NULL, `email` varchar(254) NOT NULL, `registered` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `last_seen` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
Now provide the response and nothing else.
| That occurs pretty often. You're confusing mysql timestamp which is actually a DATETIME like value with UNIX timestamp, which is number of seconds passed since 1970-01-01. You need to either change field format or the inserting value. Also you can find some mysql functions handy - CURDATE() or NOW () for example $sql = 'INSERT INTO users VALUES (NULL,:username,:password,:email,NOW(),NOW())';$stmt = $pdo->prepare($sql);$stmt->execute(array($username, $password, $email)); But personally I'd avoid mysql timestamps. they can be changed unexpectedly, ruining all your data. I'd use DATETIME and set all values manually. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14807746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2060336/']} | jdg_84483 |
stackexchange | llm_judgeable_groundtruth_similarity | 2113399 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Problem: If $\lim_{n\to\infty} \frac{a_{n+1}}{a_n} = 0$, show that $\lim_{n\to\infty}a_n = 0$. Attempted Proof: Let $\epsilon > 0$. From the hypothesis, $\exists \ N \in \mathbb{P}$ such that if $n \geq N$, then $$\left|\ \frac{a_{n+1}}{a_n} - 0 \ \right| < \epsilon.$$ This implies $$\left| {a_{n+1}} \right| < \epsilon \left| a_n \right|.$$ Thus, let $n\geq N'$ such that $$\left|\ \frac{a_{n+1}}{a_n} - 0 \ \right| < \epsilon\left|a_n\right|.$$ Then we have $\left|a_{n+1}\right| < \epsilon,$ which implies $\lim_{n\to\infty}a_n = 0$. My main concern with my proof is that $\epsilon$ depends on $a_n$. Is this an issue?
Now provide the response and nothing else.
| Since $\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=0$, then for $\epsilon=\frac12$, there is $N\in\mathbb{N}$ such that when $n\ge N$,$$ \bigg|\frac{a_{n+1}}{a_n}\bigg|<\epsilon. $$Thus for $n>N$, one has$$ \bigg|\frac{a_{N+1}}{a_N}\bigg|<\epsilon, \bigg|\frac{a_{N+2}}{a_{N+1}}\bigg|<\epsilon,\cdots,\bigg|\frac{a_{n}}{a_{n-1}}\bigg|<\epsilon$$and hence$$ \bigg|\frac{a_{n}}{a_N}\bigg|<\epsilon^{n-N}$$or$$ |a_n|<\epsilon^{n-N}|a_N|. $$So$$ \lim_{n\to\infty}a_n=0.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2113399', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/215976/']} | jdg_84484 |
stackexchange | llm_judgeable_groundtruth_similarity | 24025 |
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is meant by maximally mixed states? Does this mean that there are partially mixed states?For example, consider $\rho_{GHZ} = \left| {GHZ} \right\rangle \left\langle {GHZ} \right|$ and $\rho_W = \left| {W} \right\rangle \left\langle {W} \right|$ , where $$\left| {GHZ} \right\rangle = {1 \over {\sqrt 2 }}\left( {\left| {000} \right\rangle + \left| {111} \right\rangle } \right)$$ $$\left| W \right\rangle = {1 \over {\sqrt 3 }}\left( {\left| {100} \right\rangle + \left| {010} \right\rangle + \left| {001} \right\rangle } \right).$$ Are they maximally mixed?
Now provide the response and nothing else.
| The maximally mixed state is a quantum state whose density matrix is proportional to the identity matrix. Physically, it may be interpreted as a uniform mixture of states in an orthonormal basis. The density matrix of a maximally mixed state is full rank. On the other hand, the density matrix of a pure state, such as $|GHZ\rangle$ or $|W\rangle$ , is rank one. Therefore, no pure state is maximally mixed. That said, tracing out two subsystems of $|GHZ\rangle$ does leave the other one in the maximally mixed state since $$\mathrm{tr}_{23}|GHZ\rangle\langle GHZ|=\frac{|0\rangle\langle 0|}2+\frac{|1\rangle\langle 1|}2 = \frac{I}{2}.$$ However, this is not the case for $|W\rangle$ , because $$\mathrm{tr}_{23}|W\rangle\langle W|=\frac{2|0\rangle\langle 0|}3+\frac{|1\rangle\langle 1|}3$$ is not a multiple of the identity matrix. | {} | {'log_upvote_score': 5, 'links': ['https://quantumcomputing.stackexchange.com/questions/24025', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/16700/']} | jdg_84485 |
stackexchange | llm_judgeable_groundtruth_similarity | 21955088 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering if anyone could explain how I can get 7 equal columns in bootstrap? I am trying to make a calendar. This code seems to do 5: div class="row"> <div class="col-md-2 col-md-offset-1"></div> <div class="col-md-2"></div> <div class="col-md-2"></div> <div class="col-md-2"></div> <div class="col-md-2"></div></div> My main content has the following class, so I would like the 7 columns to sit within this: col-lg-12 Can anyone explain if this is possible, or if I have to stick to even numbers instead?
Now provide the response and nothing else.
| Well, IMO you probably need to override the width of the columns by using CSS3 @media query. Here is my attempt to create a 7-col grid system: <div class="container"> <div class="row seven-cols"> <div class="col-md-1">Col 1</div> <div class="col-md-1">Col 2</div> <div class="col-md-1">Col 3</div> <div class="col-md-1">Col 4</div> <div class="col-md-1">Col 5</div> <div class="col-md-1">Col 6</div> <div class="col-md-1">Col 7</div> </div></div> @media (min-width: 768px){ .seven-cols .col-md-1, .seven-cols .col-sm-1, .seven-cols .col-lg-1 { width: 100%; *width: 100%; }}@media (min-width: 992px) { .seven-cols .col-md-1, .seven-cols .col-sm-1, .seven-cols .col-lg-1 { width: 14.285714285714285714285714285714%; *width: 14.285714285714285714285714285714%; }}/** * The following is not really needed in this case * Only to demonstrate the usage of @media for large screens */ @media (min-width: 1200px) { .seven-cols .col-md-1, .seven-cols .col-sm-1, .seven-cols .col-lg-1 { width: 14.285714285714285714285714285714%; *width: 14.285714285714285714285714285714%; }} The value of width comes from: width = 100% / 7 column-number = 14.285714285714285714285714285714% WORKING DEMO - ( jsbin ) Run the code snippet and click on the "Full page". .col-md-1 { background-color: gold;}@media (min-width: 768px){ .seven-cols .col-md-1, .seven-cols .col-sm-1, .seven-cols .col-lg-1 { width: 100%; *width: 100%; }}@media (min-width: 992px) { .seven-cols .col-md-1, .seven-cols .col-sm-1, .seven-cols .col-lg-1 { width: 14.285714285714285714285714285714%; *width: 14.285714285714285714285714285714%; }}@media (min-width: 1200px) { .seven-cols .col-md-1, .seven-cols .col-sm-1, .seven-cols .col-lg-1 { width: 14.285714285714285714285714285714%; *width: 14.285714285714285714285714285714%; }} <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/><div class="container"> <div class="row seven-cols"> <div class="col-md-1">Col 1</div> <div class="col-md-1">Col 2</div> <div class="col-md-1">Col 3</div> <div class="col-md-1">Col 4</div> <div class="col-md-1">Col 5</div> <div class="col-md-1">Col 6</div> <div class="col-md-1">Col 7</div> </div></div> Other options Also, you could build your own 7-columns version of Twitter Bootstrap by using the Custom Builder (Changing the @grid-columns , ...). If you are using less compiler, you could download the less version of Twitter Bootstrap (from Github ) and edit the variables.less file instead. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21955088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1738522/']} | jdg_84486 |
stackexchange | llm_judgeable_groundtruth_similarity | 5183730 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing a servlet, and need to get all parameters from the request. I found request.getParameterNames returns a java.util.Enumeration , so I have to write code as: val names = request.getParameterNameswhile(names.hasMoreElements) { val name = names.nextElement} I wanna know is there any way to convert a Enumeration to a Seq/List , then I can use the map method?
Now provide the response and nothing else.
| Use JavaConverters See https://stackoverflow.com/a/5184386/133106 Use a wrapper Iterator You could build up a wrapper: val nameIterator = new Iterator[SomeType] { def hasNext = names.hasMoreElements; def next = names.nextElement } Use JavaConversions wrapper val nameIterator = new scala.collection.JavaConversions.JEnumerationWrapper(names) Using JavaConversions implicits If you import import scala.collection.JavaConversions._ you can do it implicitly (and you’ll also get implicit conversions for other Java collecitons) request.getParameterNames.map(println) Use Iterator.continually You might be tempted to build an iterator using Iterator.continually like an earlier version of this answer proposed: val nameIterator = Iterator.continually((names, names.nextElement)).takeWhile(_._1.hasMoreElements).map(_._2) but it's incorrect as the last element of the enumerator will be discarded.The reason is that the hasMoreElement call in the takeWhile is executed after calling nextElement in the continually , thus discarding the last value. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5183730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']} | jdg_84487 |
stackexchange | llm_judgeable_groundtruth_similarity | 19496907 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to set the date/time using the ADB shell but the shell only returns the current time. I've tried: adb shell date -s YYYYMMDD.HHmmss and unix time like: adb shell date 1318349236 any ideas?
Now provide the response and nothing else.
| To save storage space Android like many other embedded systems uses multi-call binaries to implement its basic command line tools like date . Android device may include either toolbox or toybox (or both) binary depending on the version. You can check which implementation of the date tool available on your device by running toolbox date and toybox date commands. Then you can use the one which prints out the current date. For example for an Android 6.0+ device it might look like: $ adb shell toybox dateMon Jul 31 21:09:28 CDT 2017$ adb shell toolbox datedate: no such tool To set date and time using toolbox date use YYYYMMDD.HHmmss format: adb shell "su 0 toolbox date -s 20161231.235959" In case of toybox date use MMDDhhmm[[CC]YY][.ss] format: adb shell "su 0 toybox date 123123592016.59" | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19496907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2903429/']} | jdg_84488 |
stackexchange | llm_judgeable_groundtruth_similarity | 3286614 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been wrote for two interface of .xib file. How to make connection between these two files? When I run the file, the first .xib will appear then after i click the button, the second .xib file will appear and on the top of first .xib file. Thus, i want use the second .xib function to make control of the first .xib file. Thus, there is two .xib file at the end. How to do it? Thank you.
Now provide the response and nothing else.
| Here is a pair of functions that get and set the selection/caret position in a text area in all major browsers. Note: if you don't need to support IE <= 8, just use the selectionStart and selectionEnd properties ( MDN ). All of the complicated code below is just there to support old versions of IE. function getInputSelection(el) { var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { start = el.selectionStart; end = el.selectionEnd; } else { range = document.selection.createRange(); if (range && range.parentElement() == el) { len = el.value.length; normalizedValue = el.value.replace(/\r\n/g, "\n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { start = end = len; } else { start = -textInputRange.moveStart("character", -len); start += normalizedValue.slice(0, start).split("\n").length - 1; if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) { end = len; } else { end = -textInputRange.moveEnd("character", -len); end += normalizedValue.slice(0, end).split("\n").length - 1; } } } } return { start: start, end: end };}function offsetToRangeCharacterMove(el, offset) { return offset - (el.value.slice(0, offset).split("\r\n").length - 1);}function setInputSelection(el, startOffset, endOffset) { if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { el.selectionStart = startOffset; el.selectionEnd = endOffset; } else { var range = el.createTextRange(); var startCharMove = offsetToRangeCharacterMove(el, startOffset); range.collapse(true); if (startOffset == endOffset) { range.move("character", startCharMove); } else { range.moveEnd("character", offsetToRangeCharacterMove(el, endOffset)); range.moveStart("character", startCharMove); } range.select(); }} When you change the textarea's value, first save the selection, then restore it afterwards: var t = document.getElementById("textarea");var sel = getInputSelection(t);t.value = some_new_value;setInputSelection(t, sel.start, sel.end); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3286614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389315/']} | jdg_84489 |
stackexchange | llm_judgeable_groundtruth_similarity | 294019 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
For a locally compact group $G$, we define the Pontryagin dual as $\hat G = Hom(G,\mathbb T)$ where $\mathbb T$ is the circle group and the homomorphisms are continuous group maps. This duality has a lot of nice properties and shows up all over the place so it is probably the right definition. However, without the benefit of hindsight, why would one choose to define the dual of a group with respect to $\mathbb T$ (instead of some other locally compact group, say). Is there a reason to promote $\mathbb T$ to a special place among all locally compact groups? A little more broadly, are there other groups $H$ that also lead to a good theory of duality if we define $\hat G_H = Hom(G,H)$? One possible answer would be to explin the historical context/necessity which led to the definition. But there can also be other motivations and I would be open to both kinds of answers. On a closely related note, one can also ask a similar question for the Cartier duality in algebraic geometry. Probably, the two will have similar answers.
Now provide the response and nothing else.
| You are looking for realizability toposes and related categories, as was already pointed out in the comments. Let me make a quick summary of how things work and why we can completely circumvent the dilemmas involving arbitrary codings of objects with strings. To understand what is going on we do not need realizability toposes, as these are quite technically involved. We can use the much simpler assemblies . First we fix a model of computation $A$. Formally, $A$ should be a partial combinatory algebra , but informally you can just imagine Turing machines, or programs in a general-purpose programming language. An assembly $(S, \Vdash_S)$ is a set $S$ together with a realizability relation ${\Vdash_S} \subseteq A \times S$. We read $p \Vdash_S x$ as "program $p$ is a code of element $x \in S$". We require that $\Vdash_S$ have the property $\forall x \in S . \exists p \in A . p \Vdash_S x$, i.e., every element has to have at least one code. (But the same code may be shared between elements.) The notion of an assembly is very natural and it precisely captures the idea the the elements of an abstract set are encoded in some way by programs. A morphism of assemblies $f : (S, \Vdash_S) \to (T, \Vdash_T)$ is map $f : S \to T$ which is realized , by which we mean that there is a program $q \in A$ such that$$p \Vdash_S x \implies q \cdot p \Vdash_T f(x).$$This again is a completely natural idea which captures precisely the fact that the program $q$ operates on codes the way $f$ operates on the corresponding elements. It is what programmers do when you ask them to implement a mathematical function. The category of assemblies is not a topos, but it is good enough to allow interpretation of lots of constructions and of intuitionistic first-order logic. The interpretation is completely standard (predicates are interpreted as subobjects, and everything else follows from that). Here is the punch line: take an object of interest, say the real numbers. Characterize the real numbers in the language of first-order logic (or higher-order logic if needed, but then we have to use the topos), for instance "the Cauchy-complete archimedean ordered field". Up to isomorphism there is at most one assembly which satisfies this characterization. Therefore, there is no question about how real numbers should be represented! As soon as we say precisely what structure we expect of the reals, the encoding is imposed by the ambient category of assemblies (or the topos). This trick works over and over again. You can start with the natural numbers, for example take $\mathbb{N}$ to be the free algebra for the signature $(0, 1)$, i.e., the free structure with one constant and one unary operation. Since initial algebras are unique up to unique isomorphisms, the assembly of natural numbers is determined. We can go on: interegers are the free commutative unital ring raitonals are the field of fractions of the integers complex numbers are the algebraic closure of the reals Eventually it gets a bit tricky, for instance $L^p[0,1]$ is doable for $p < \infty$, it is not really doable for $L^\infty[0,1]$ (because this space is intuitionistically problematic anyhow), and I don't know whether spaces of distributions have been handled properly. As a rule of thumb, anything that constructive mathematicians can do, you can interpret in realizaiblity to obtain a computable version. So your hunch was correct: categorical logic (which is just model theory in categories instead of sets) and realizaibility provide the answer. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/294019', 'https://mathoverflow.net', 'https://mathoverflow.net/users/58001/']} | jdg_84490 |
stackexchange | llm_judgeable_groundtruth_similarity | 27163 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
It's well known that the nilradical of a commutative ring with identity $A$ is the intersection of all the prime ideals of $A$. Every proof I found (e.g. in the classical "Commutative Algebra" by Atiyah and Macdonald) uses Zorn's lemma to prove that $x \notin Nil(A) \Rightarrow x \notin \cap_{\mathfrak{p}\in Spec(A)} \mathfrak{p}$ (the other way is immediate).Does anybody know a proof that doesn't involve it?
Now provide the response and nothing else.
| Since you asked for a proof, let me complement Chris Phan's answer by outlining a proof that relies only on the Compactness Theorem for propositional logic, which is yet another equivalent to the Ultrafilter Theorem over ZF. Let A be a commutative ring and let x ∉ Nil(A). To each element a ∈ A associate a propositional variable p a and let T be the theory whose axioms are p 0 , ¬p 1 , ¬p x , ¬p x 2 , ¬p x 3 ,... p a ∧ p b → p a+b for all a, b ∈ A. p a → p ab for all a, b ∈ A. p ab → p a ∨ p b for all a, b ∈ A. Models of T correspond precisely to prime ideals that do not contain x. Indeed, if P is such an ideal, then setting p a to be true iff a ∈ P satisfies all of the above axioms, and conversely. So it suffices to show that T has a model. Since x n ≠ 0 for all n, one can verify using ideals over finitely generated subrings of A that the theory T is finitely consistent, i.e. any finite subset of T has a model. (What I just swept under the rug here is a constructive proof of the theorem for quotients of Z[v 1 ,...,v n ].) The Compactness Theorem for propositional logic then ensures that T has a model. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/27163', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6382/']} | jdg_84491 |
stackexchange | llm_judgeable_groundtruth_similarity | 16751401 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
is there a way to check if twig template exists before calling to render? A try catch block seems not to work, at least in dev environment, and plus, I prefer a check than the cost of an exception. This class TwigEngine has an exists() method, but didn't find examples on use.
Now provide the response and nothing else.
| The service holding the twig engine if configured as default is 'templating'. Inside your Controller do the following: if ( $this->get('templating')->exists('AcmeDemoBundle:Foo:bar.html.twig') ) { // ...} The alternative would be catching exception the render() method throws like this: try { $this->get('templating')->render('AcmeDemoBundle:Foo:bar.html.twig') } catch (\Exception $ex) { // your conditional code here. } In a normal controller ... $this->render('...') is only an alias for ... $this->container->get('templating')->renderResponse($view, $parameters, $response); ... while ... $this->get('...') ... is an alias for $this->container->get('...') Have a look at Symfony\FrameworkBundle\Controller\Controller . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16751401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/761076/']} | jdg_84492 |
stackexchange | llm_judgeable_groundtruth_similarity | 7772409 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working with PhoneGap and Android and have my .html and js files on an external server. When I use the following code, the app loads my external .html files and everything works fine: this.setIntegerProperty("loadUrlTimeoutValue", 60000);this.loadUrl("http://www.myserver.com"); However, when work via a WebView I can't seem to set the loadURLTimeoutValue for a WebView : private WebView webView;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); try { webView = (WebView) findViewById(R.id.webview); webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webView.loadUrl("http://www.myserver.com"); } This doesn't work. How can I set the timeout value on the WebView ?
Now provide the response and nothing else.
| This is a workaround to simulate the described behavior. You can use a WebViewClient , and override the onPageStarted method: public class MyWebViewClient extends WebViewClient { boolean timeout; public MyWebViewClient() { timeout = true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { new Thread(new Runnable() { @Override public void run() { timeout = true; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if(timeout) { // do what you want } } }).start(); } @Override public void onPageFinished(WebView view, String url) { timeout = false; }} If timeout, you can load, for example, an error page... To add the WebViewClient to you WebView , just do this: webView.setWebViewClient(new MyWebViewClient()); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7772409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989557/']} | jdg_84493 |
stackexchange | llm_judgeable_groundtruth_similarity | 22273119 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question about the beam search algorithm . Let's say that n = 2 (the number of nodes we are going to expand from every node). So, at the beginning, we only have the root, with 2 nodes that we expand from it. Now, from those two nodes, we expand two more. So, at the moment, we have 4 leafs. We will continue like this till we find the answer. Is this how beam search works? Does it expand only n = 2 of every node, or it keeps 2 leaf nodes at all the times? I used to think that n = 2 means that we should have 2 active nodes at most from each node, not two for the whole tree.
Now provide the response and nothing else.
| In the "standard" beam search algorithm , at every step, the total number of the nodes you currently "know about" is limited - and NOT the number of nodes you will follow from each node. Concretely, if n = 2 , it means that the "beam" will be of size at most 2, at all times. So, initially, you start from one node, then you discover all nodes that are reachable from it, but discard all of them but two, and finish step 1 with 2 nodes. At step 2, you have two nodes, and you will expand both, and discard all nodes again, except exactly 2 nodes (total, not from each!). In the next steps, similarly, you will keep 2 nodes after each step. Choosing which node to keep is usually done by some heuristic function that evaluates which node is closest to the target. Note that the beam search algorithm is not complete (i.e., it may not find a solution if one exists) nor optimal (i.e. it may not find the best solution). The best way to see this is witnessing that when n = 1 , it basically reduces to best-first-search . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22273119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2486753/']} | jdg_84494 |
stackexchange | llm_judgeable_groundtruth_similarity | 4571660 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This problem is from a math competition, but I think is wrong: Find the value of $x+y$ if: $$\begin{align}xy &= 1 \\ x^2 + y^2 &= 5 \\ x^3+y^3 &= 8\end{align}$$ Solution (I think is wrong): $x^3 + y^3 = (x + y)(x^2-xy+y^2) = (x+y)(5-1) = 4(x+y)$ So we have: $x^3+y^3 = 4(x+y)$ $x^3+y^3 = 8$ Then: $8 = 4(x+y)$ $x+y = 2$ However if we replace that value in $(x+y)^2$ we have: $(x+y)^2 = 2^2 =4$ $(x+y)^2 = x^2+y^2+2xy = 5 + 2 = 7$ As you can see $4 \neq 7$ , what is happening?
Now provide the response and nothing else.
| Let us call $a := x + y$ and $b := xy$ . Then the proposed system of equations is equivalent to \begin{align*}\begin{cases}b = 1\\\\a^{2} - 2b = 5\\\\a^{3} - 3ab = 8\end{cases} \Longleftrightarrow\begin{cases}b = 1\\\\a^{2} = 7\\\\a^{3} - 3a = 8\end{cases} & \Longleftrightarrow\begin{cases}b = 1\\\\a = \pm\sqrt{7}\\\\a = 2\end{cases}\end{align*} which clearly has no solutions. I think this answers your question about what is happening. Hopefully this helps! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4571660', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1094924/']} | jdg_84495 |
stackexchange | llm_judgeable_groundtruth_similarity | 11684454 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a chrome extension. I need to analyse from the HTML source of the current page. I found here all kinds of solutions with background pages and content scripts but none helped me. here is what I have so far: manifest.json { "name": "Extension", "version": "1.0", "description": "Extension", "browser_action": { "default_icon": "bmarkred.ico", "popup": "Test.html" }, "content_scripts": [ { "matches": ["http://*/*"], "js": ["content.js"] } ], "background": { "page": "backgroundPage.html" }, "permissions": [ "cookies", "tabs", "http://*/*", "https://*/*" ]} background.html <html><head><script type="text/javascript"> try { chrome.tabs.getSelected(null, function (tab) { chrome.tabs.sendRequest(tab.id, {action: "getSource"}, function(source) { alert(source); }); }); } catch (ex) { alert(ex); }</script></head></html> content.js chrome.extension.onRequest.addListener(function(request, sender, callback) { if (request.action == "getSource") { callback(document.getElementsByTagName('html')[0].innerHTML); }}); The alert always alerts undefined. even if i change in the content.js file the callback function to: callback('hello'); still the same result. What am I doing wrong? maybe I'm going at this the wrong way. What I really need is this: When the user opens the extension popup (and only then), I need HTML of the current page so I can analyse it.
Now provide the response and nothing else.
| Inject a script into the page you want to get the source from and message it back to the popup.... manifest.json { "name": "Get pages source", "version": "1.0", "manifest_version": 2, "description": "Get pages source from a popup", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "permissions": ["tabs", "<all_urls>"]} popup.html <!DOCTYPE html><html style=''><head><script src='popup.js'></script></head><body style="width:400px;"><div id='message'>Injecting Script....</div></body></html> popup.js chrome.runtime.onMessage.addListener(function(request, sender) { if (request.action == "getSource") { message.innerText = request.source; }});function onWindowLoad() { var message = document.querySelector('#message'); chrome.tabs.executeScript(null, { file: "getPagesSource.js" }, function() { // If you try and inject into an extensions page or the webstore/NTP you'll get an error if (chrome.runtime.lastError) { message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message; } });}window.onload = onWindowLoad; getPagesSource.js // @author Rob W <http://stackoverflow.com/users/938089/rob-w>// Demo: var serialized_html = DOMtoString(document);function DOMtoString(document_root) { var html = '', node = document_root.firstChild; while (node) { switch (node.nodeType) { case Node.ELEMENT_NODE: html += node.outerHTML; break; case Node.TEXT_NODE: html += node.nodeValue; break; case Node.CDATA_SECTION_NODE: html += '<![CDATA[' + node.nodeValue + ']]>'; break; case Node.COMMENT_NODE: html += '<!--' + node.nodeValue + '-->'; break; case Node.DOCUMENT_TYPE_NODE: // (X)HTML documents are identified by public identifiers html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n'; break; } node = node.nextSibling; } return html;}chrome.runtime.sendMessage({ action: "getSource", source: DOMtoString(document)}); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11684454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/785736/']} | jdg_84496 |
stackexchange | llm_judgeable_groundtruth_similarity | 17104209 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does std::make_shared<POD>() value initialize my POD? If yes, is this a guaranteed by the standard? If no (as I suspect), is there a way to do this? I guess std::make_shared<POD>(POD()) would do but is that what I should be doing?
Now provide the response and nothing else.
| Yes, it's value intialized, and this is guaranteed by the standard: §20.7.2.2.6,2: (about make_shared ) Effects: Allocates memory suitable for an object of type T and constructs an object in that memory via the placement new expression ::new (pv) T(std::forward<Args>(args)...) . And §5.3.4,15: A new-expression that creates an object of type T initializes that object as follows: — If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value. — Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for directinitialization. So it's direct-initialized as in new POD() . §8.5,16: The semantics of initializers are as follows. [...] — If the initializer is (), the object is value-initialized. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17104209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1171013/']} | jdg_84497 |
stackexchange | llm_judgeable_groundtruth_similarity | 710111 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Use $\epsilon$-$\delta$ definition to show $\displaystyle\lim_{x\to0}\frac{x^2+3}{x^2+1}=3$. Given $\epsilon>0$, there exists $\delta>0$ such that $\displaystyle\left|\frac{x^2+3}{x^2+1}-3\right|<\epsilon$ for all x satisfying $0<|x|<\delta$. So, if $|x|<\delta$, then:$$\left|\frac{x^2+3}{x^2+1}-3\right| = \left|\frac{-2x^2}{x^2+1}\right| =\frac{|-2||x^2|}{\left|x^2+1\right|}=\frac{2|x^2|}{\left|x^2+1\right|}$$ This is where I'm stumped. How can I manipulate $|x|<\delta$ to look like $\left|x^2+1\right|$?
Now provide the response and nothing else.
| $$\sum_{k=1}^{m}k!k \\\sum_{k=1}^{m}k!(k+1-1) \\\sum_{k=1}^{m}k!(k+1)-k! \\\sum_{k=1}^{m}(k+1)!-k! \\= 2!-1!+3!-2!+4!-3!+\cdots + (m+1)!-m! \\=(m+1)!-1$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/710111', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/135045/']} | jdg_84498 |
stackexchange | llm_judgeable_groundtruth_similarity | 48258686 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I write custom datepicker input component imlements ControlValueAccessor in Angular5 using mat-datepicker. date-picker.component.html: <mat-form-field> <input matInput [matDatepicker]="picker" [(ngModel)]="value" (blur)="onBlur()"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker (selectedChanged)="onChange($event)" #picker></mat-datepicker></mat-form-field> date-picker.component.ts : import { Component, OnInit, Input, Output, forwardRef, EventEmitter } from '@angular/core';import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';import { MAT_MOMENT_DATE_FORMATS, MomentDateAdapter } from '@angular/material-moment-adapter';import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';const noop = () => {};export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DatePickerComponent), multi: true};@Component({ selector: 'app-date-picker', templateUrl: './date-picker.component.html', styleUrls: ['./date-picker.component.css'], providers: [ { provide: MAT_DATE_LOCALE, useValue: 'he-IL' }, { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }, CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR ],})export class DatePickerComponent implements OnInit, ControlValueAccessor { @Input() required: boolean; @Output() change: EventEmitter<Date> = new EventEmitter<Date>(); innerValue: Date = new Date(); //Placeholders for the callbacks which are later provided //by the Control Value Accessor private onTouchedCallback: () => void = noop; private onChangeCallback: (_: any) => void = noop; //get accessor get value(): Date { return this.innerValue; }; //set accessor including call the onchange callback set value(v: Date) { if (v !== this.innerValue) { this.innerValue = v; } } constructor(private adapter: DateAdapter<any>) { } ngOnInit() { this.adapter.setLocale('he'); } //Occured value changed from module writeValue(value: any): void { if (value !== this.innerValue) { this.innerValue = value; //invoke value change event this.change.emit(this.innerValue); } } registerOnChange(fn: any): void { this.onChangeCallback = fn; } registerOnTouched(fn: any): void { this.onTouchedCallback = fn; } onChange(event) { this.value = event; this.onBlur(); } onBlur() { this.onChangeCallback(this.innerValue); //invoke value change event this.change.emit(new Date(this.innerValue)); //this.onTouchedCallback(); }} I want to add ability to enforce date mask like 'dd/MM/yyyy' I found matching example, but it written in angularJS and md datepicker: Angular Material Datepicker and ngMask Any idea for implementation in Angular? Edit: Attached live demo, Based on Vivek Doshi nice answer, This demo not work due to [textMask] attribute. Live Demo
Now provide the response and nothing else.
| You can achieve that with the help of angular2-text-mask Component side : public mask = { guide: true, showMask : true, mask: [/\d/, /\d/, '/', /\d/, /\d/, '/',/\d/, /\d/,/\d/, /\d/] }; Template Side : <mat-form-field> <input matInput [textMask]="mask" [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker></mat-form-field> WORKING DEMO Now all you need to do is bind the logic and validations , Here is the WORKING DEMO with the solution of ControlValueAccessor . 3rd Demo , with your code WORKING DEMO | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48258686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4369793/']} | jdg_84499 |
stackexchange | llm_judgeable_groundtruth_similarity | 35751420 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to parallelise a certain task over a number of workers.To that purpose I need all workers to have access to a matrix that stores the data. I thought that the data matrix could be implemented as a Shared Array in order to minimise data movement. In order to get me started with Shared Arrays, I am trying the following very simple example which gives me, what I think is, unexpected behaviour: julia -p 2# the data matrixD = SharedArray(Float64, 2, 3)# initialise the data matrix with dummy valuesfor ii=1:length(D) D[ii] = rand()end# Define some kind of dummy computation involving the shared array f = x -> x + sum(D)# call function on worker@time fetch(@spawnat 2 f(1.0)) The last command gives me the following error: ERROR: On worker 2: UndefVarError: D not defined in anonymous at none:1 in anonymous at multi.jl:1358 in anonymous at multi.jl:904 in run_work_thunk at multi.jl:645 in run_work_thunk at multi.jl:654 in anonymous at task.jl:58 in remotecall_fetch at multi.jl:731 in call_on_owner at multi.jl:777 in fetch at multi.jl:795 I thought that the Shared Array D should be visible to all workers?I am clearly missing something basic. Thanks in advance.
Now provide the response and nothing else.
| Although the underlying data is shared to all workers, the declaration of D is not. You will still need to pass in the reference to D, so something like f = (x,SA) -> x + sum(SA)@time fetch(@spawnat 2 f(1.0,D)) should work. You can change D on the main process and see that it is infact using the same data: julia> # call function on worker @time fetch(@spawnat 2 f(1.0,D)) 0.325254 seconds (225.62 k allocations: 9.701 MB, 5.88% gc time)4.405613684678047julia> D[1] += 11.2005544517241717julia> # call function on worker @time fetch(@spawnat 2 f(1.0,D)) 0.004548 seconds (637 allocations: 45.490 KB)5.405613684678047 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35751420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1438310/']} | jdg_84500 |
stackexchange | llm_judgeable_groundtruth_similarity | 90711 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Inspired by this question, titled: When are the built-in commands loaded to memory , while attempting to answer this I tried the following command and was a bit surprised that I couldn't run it: $ strace cd $HOME Is there a method I can make use of to run strace for the builtin commands to Bash?
Now provide the response and nothing else.
| If you think about how strace works then it makes total sense that none of the builtins to Bash would be traceable. strace can only trace actual executables, whereas the builtins are not. For example, my cd command: $ type cdcd is a functioncd () { builtin cd "$@"; local result=$?; __rvm_project_rvmrc; __rvm_after_cd; return $result} Trick for strace'ing cd? I came across this technique where you could invoke strace on the actual bash process and in so doing, indirectly trace cd that way. Example $ stty -echo$ cat | strace bash > /dev/null Which results in me being able to strace the bash process as follows: ....getegid() = 501getuid() = 500getgid() = 501access("/bin/bash", X_OK) = 0stat("/bin/bash", {st_mode=S_IFREG|0755, st_size=940312, ...}) = 0geteuid() = 500getegid() = 501getuid() = 500getgid() = 501access("/bin/bash", R_OK) = 0getpgrp() = 32438rt_sigaction(SIGCHLD, {0x43e360, [], SA_RESTORER, 0x34e7233140}, {SIG_DFL, [], SA_RESTORER, 0x34e7233140}, 8) = 0getrlimit(RLIMIT_NPROC, {rlim_cur=1024, rlim_max=62265}) = 0rt_sigprocmask(SIG_BLOCK, NULL, [], 8) = 0fcntl(0, F_GETFL) = 0 (flags O_RDONLY)fstat(0, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0lseek(0, 0, SEEK_CUR) = -1 ESPIPE (Illegal seek)rt_sigprocmask(SIG_BLOCK, NULL, [], 8) = 0read(0, This is the Bash prompt, where it's sitting there, waiting for some input. So let's give it the command cd .. : read(0, "c", 1) = 1read(0, "d", 1) = 1read(0, " ", 1) = 1read(0, ".", 1) = 1read(0, ".", 1) = 1read(0, "\n", 1) = 1stat("/home", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0stat("/home/saml", {st_mode=S_IFDIR|0700, st_size=32768, ...}) = 0stat("/home/saml/tst", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0stat("/home/saml/tst/90609", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0stat("/home/saml/tst/90609", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0chdir("/home/saml/tst") = 0rt_sigprocmask(SIG_BLOCK, NULL, [], 8) = 0read(0, From the above output, you can see where I typed the command, cd .. and hit enter, ( \n ). From there you can see that the stat() function was called, and that afterwards Bash is sitting at another read(0.. prompt, waiting for another command. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/90711', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/7453/']} | jdg_84501 |
stackexchange | llm_judgeable_groundtruth_similarity | 59632 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In 2004, France banned wearing conspicuous religious symbols in schools . In particular, this bans the Muslim headscarf, the Jewish kippah, and the Sikh turban. The turban has now been exempted as Sikhs have argued that it is cultural rather than religious; the same argument therefore applies to the headscarf (which need not be an actual scarf, a hat would do) but this has not happened. In 2010, France banned covering the face in public . In particular, this bans the niqab (although the vast majority of Muslims see the niqab as optional, some consider it to be recommended, and many observe it). In 2016, many municipalities banned the burkini , although this was then suspended by the highest French administrative court. Although these bans were all worded in religiously neutral ways, an argument could be made that they mostly affect Muslim women, and in fact the justifications for some of these (such as the Burkiki) explicitly mention combating what is perceived by some French politicians as the oppression of women. Is there evidence that these bans were intended to specifically target Muslims?
Now provide the response and nothing else.
| Yes, there is a plenty of evidence this is specifically about Muslim religious practices. The clearest of which is to be found in the legislative process leading to the 2010 niqab ban. Before being put to a vote, a bill is typically examined by the commission des lois of the relevant chamber. A member of the committee will draft a report on the bill and the whole committee will vote on it. In that case, the report from the Senate's committee is public and available on its official website . That report explains that the bill results from another report presented to the national assembly regarding the “ voile intégral ” (litterally “full veil”, which is the usual name for what the media calls the “burka”). Beside the rapporteur , the senate report also includes the opinion of Christiane Hummel, who was consulted as the head of the committee on women's rights and equal opportunity between men and women. In other words, this was specifically about the niqab and women's rights and not about religious symbols in general or making it possible to identify people (as the law as sometimes been reinterpreted, including by the courts, to sidestep discussion of its original intent). In fact, the report explains that the law was couched as a ban on covering one's face precisely to overcome objections from the Conseil d'État (one of France's supreme courts, which also advises the government and parliament during the legislative process) and heed the need to “deconfessionalize” the debate. While it argues that the “Islamic veil” was “a” reason to start the process and merely “revealed how important the face is in social life”, the connection with earlier efforts to ban the niqab are fully acknowledged and no other practice (religious or otherwise) is mentioned. I don't have evidence as specific as this at hand regarding the 2004 law but the intent was just as unambiguous. | {} | {'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/59632', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/34863/']} | jdg_84502 |
stackexchange | llm_judgeable_groundtruth_similarity | 107700 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As light enters the eye, it reaches the photoreceptors at the "base" of the retina , which then pass that signal to the bipolar and ganglionic neurons -- the latter of which send the signal outside of the eye via their axons (collectively forming the optic nerve ). The exit point of the optic nerve is sometimes referred to as the " blind spot " because there are no photoreceptors present there and therefore no sensory information is gathered. Now, I know photoreceptors exist everywhere else along the retina, so it's not surprising that we perceive vision from the otherwise broadly distributed photoreceptors. However, my question: why do the blood vessels associated with the superficial vascular plexus (which exist between incoming light and the rest of the retina) not obstruct our vision? More broadly, I guess of interest is: why none of the vascular plexuses (or cell structures of the bipolar and ganglionic neurons for that matter) obstruct our vision despite existing between the photoreceptors and incoming light? Sources: LEFT: Figure 1 from Zhongjie et al (2020) ; RIGHT: Figure 5 from Selvam et al (2018) Fu, Z., Sun, Y., Cakir, B., Tomita, Y., Huang, S., Wang, Z., Liu, C.H., S Cho, S., Britton, W., S Kern, T. and Antonetti, D.A., 2020. Targeting neurovascular interaction in retinal disorders. International journal of molecular sciences, 21(4), p1503 Selvam, S., Kumar, T. and Fruttiger, M., 2018. Retinal vasculature development in health and disease. Progress in retinal and eye research, 63, pp.1-19.
Now provide the response and nothing else.
| Avoid the fovea Figure 2 from the same paper shows the distribution relative to the fovea : As you can see, it's pretty much devoid of this superficial vasculature, so anything you are directly focusing on , say, text you read on a computer screen (or even a book!) is not impacted. Receptive fields might be bigger than you think Receptive field sizes for retinal ganglion cells in the primate retina are about 50-300 um, depending on eccentricity (distance from the fovea). Capillaries are going to be around the size of a red blood cell in diameter, so about 10 um; it seems like by the time you get to the far periphery, these vessels are mostly going to be quite small relative to receptive field size, and they are even a bit small in the vicinity of the fovea. Tissue isn't that opaque I'm mostly focusing on the RBC size themselves, because RBCs have a bit of pigment in them, but otherwise, tissue is overall quite transparent. If you've ever looked at an unstained tissue section less than 100 microns thick, you know that it doesn't look like much at all. If you've lost track of one in any volume of water, good luck finding it. For the same reason that RGCs being on the "wrong side" of the inverted vertebrate eye, this thickness of tissue just doesn't seem to be that big of a problem, and it doesn't seem that any affordances for this issue have evolved outside of the fovea in primates (whereas you can see in the figure above that there is a clear exclusion of these vessels from the fovea). We perceive with our brain, not our eyes The general idea of predictive coding models of the brain is that you have some generative model of the world that is constantly making predictions, and sensory organs merely provide evidence to update those models which is propagated as an error signal with respect to the original model; if everything is static and as predicted, nothing needs to be propagated in the brain to alter the perception. Much of what you think you are "seeing" at a given moment you aren't seeing at that moment at all, but merely "remembering" what you saw previously, and having not seen any evidence to the contrary, continue to "see" it there. When a person looks at an object, they do not typically look at one spot, but quickly saccade around to scan different parts of it and form a complete model of the object. It will escape attention until it moves or changes in some way. These blood vessels are going to be quite static, and not provide much of a changing visual image, so there's nothing there for the brain to be interested in. | {} | {'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/107700', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/16866/']} | jdg_84503 |
stackexchange | llm_judgeable_groundtruth_similarity | 197053 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am doing a t-test and I am a little bit confused with x1 and x2: For example: If the mean of dataset A is 1 and the mean of dataset B is 0.5, the t value is going to be negative or positive depending on which dataset I use as x1 and x2. If x1 = 1 and x2 = 0.5 the t value is going to be positive. If x1 = 0.5 and x2= 1 the t value will be negative. I know that I am wrong with something, but I can't figure out what is it. Thank's!
Now provide the response and nothing else.
| Here is Cheng & Feast Gamma generator code, on which R rbeta and rgamma functions are based: function x=gamrnd_cheng(alpha)% Gamma(alpha,1) generator using Cheng--Feast method% Algorithm 4.35c1=alpha-1; c2=(alpha-1/(6*alpha))/c1; c3=2/c1; c4=1+c3;c5=1/sqrt(alpha);flag=0;while flag==0; U1=rand; U2=rand; if alpha>2.5 U1=U2+c5*(1-1.86*U1); end W=c2*U2/U1; flag=(U1<1)&&(U1>0)&&(((c3*U1+W+1/W)<c4)||((c3*log(U1)-log(W)+W)<1));endx=c1*W; which can be recycled into a Beta generator at about the same cost. It uses two uniforms, plus a rejection condition, so for the values of $(\alpha,\beta)$ that you picked, i.e., for a rejection probability of $1/3$, the accept-reject algorithm may be equally efficient. However, you should also run the comparison for larger non-integer values of $(\alpha,\beta)$ to check whether or not the Cheng & Feast Gamma generator remains efficient. For instance, Joe Whittaker's Beta $\mathfrak{B}(\alpha,\beta)$ generator has a rejection condition of the form$$U_1^{1/\alpha}+U_2^{1/\beta}>1$$which occurs with increasing frequency as $\alpha$ and $\beta$ increase. I remember Luc Devroye mentioning that, for $\mathfrak{G}(\alpha,1)$ distributions, it is not possible to find a bound on the computing time that is independent of $\alpha$... | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/197053', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/105489/']} | jdg_84504 |
stackexchange | llm_judgeable_groundtruth_similarity | 21292625 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I get a null response from a $resource? I am running this: angular.module("services").factory('Member', function($resource) { var Member = $resource('/api/v1/member.json'); Member.current = Member.get(); return Member;}); But the server is responding with: null Because the user is not logged in. But when I log the result I get this: Resource 0: "n" 1: "u" 2: "l" 3: "l" $promise: Object $resolved: true __proto__: Resource Where as I would have expected literally null .
Now provide the response and nothing else.
| $resource.get method, by default, expects the JSON response to be an object (when parsed).When calling $resource.get() , the result is going to be an instance of the $resource. In your example, calling Member.get({id:1}) will produce a $resource instance that is created by calling new Member() source and then populated source (when XHR is completed) with properties of the parsed JSON response: shallowClearAndCopy(data, value); The signature of the function with which your Member instance is populated is as follows: function shallowClearAndCopy(src, dst) { dst = dst || {}; angular.forEach(dst, function(value, key){ delete dst[key]; }); for (var key in src) { if (src.hasOwnProperty(key) && key.charAt(0) !== '$' && key.charAt(1) !== '$') { dst[key] = src[key]; } } return dst;} Glancing the function body you will realise that the function does not expect src parameter to be anything else but object ( for (var key in src) { ... ). So, if you provide it with string "null" the result will be: {1: "n", 2: "u", 3: "l", ...} ngResource is built to support a RESTfull API with JSON as an implied data transfer format, hence you won't be able to use responses such as "null" or anything else which isn't a valid JSON. Unless. Unless you make use of transformResponse to convert "null" to something like {'null': true} on the fly: app.factory('Member', function($resource) { var Member = $resource('member.txt', {}, { get: { method: 'GET', isArray: false, transformResponse: function(data, headersGetter){ if(data === 'null'){ return {null: true}; } return angular.fromJson(data); } } }); return Member;});$scope.member = Member.get({id: 1});console.log($scope.member); // --> {null: true} DEMO | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21292625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/268074/']} | jdg_84505 |
stackexchange | llm_judgeable_groundtruth_similarity | 31190 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
K-fold cross-validation can be used to estimate the generalization capability of a given classifier. Can I (or should I) also compute a pooled variance from all validation runs in order to obtain a better estimate of its variance? If not, why? I have found papers which do use the pooled standard deviation across cross-validation runs . I have also found papers explicitly stating there is no universal estimator for the validation variance . However, I have also found papers showing some variance estimators for the generalization error (I am still reading and trying to comprehend this one). What do people really do (or report) in practice? EDIT: When CV is used to measure the crude classification error (i.e. either a sample has been labeled correctly or it hasn't; e.g. true or false) then it may not make sense to talk about a pooled variance. However, I am talking about the case in which the statistic we are estimating does have a variance defined. So, for a given fold, we can end up with both a value for the statistic and a variance estimate. It does not seems right to discard this information and consider only the average statistic. And while I am aware I could build a variance estimate using bootstrap methods, (if I am not very wrong) doing so would still ignore the fold variances and take only the statistic estimates into consideration (plus requiring much more computation power).
Now provide the response and nothing else.
| Very interesting question, I'll have to read the papers you give... But maybe this will start us in direction of an answer: I usually tackle this problem in a very pragmatic way: I iterate the k-fold cross validation with new random splits and calculate performance just as usual for each iteration. The overall test samples are then the same for each iteration, and the differences come from different splits of the data. This I report e.g. as the 5th to 95th percentile of observed performance wrt. exchanging up to $\frac{n}{k} - 1$ samples for new samples and discuss it as a measure for model instability. Side note: I anyways cannot use formulas that need the sample size. As my data are clustered or hierarchical in structure (many similar but not repeated measurements of the same case, usually several [hundred] different locations of the same specimen) I don't know the effective sample size. comparison to bootstrapping: iterations use new random splits. the main difference is resampling with (bootstrap) or without (cv) replacement. computational cost is about the same, as I'd choose no of iterations of cv $\approx$ no of bootstrap iterations / k, i.e. calculate the same total no of models. bootstrap has advantages over cv in terms of some statistical properties (asymptotically correct, possibly you need less iterations to obtain a good estimate) however, with cv you have the advantage that you are guaranteed that the number of distinct training samples is the same for all models (important if you want to calculate learning curves) each sample is tested exactly once in each iteration some classification methods will discard repeated samples, so bootstrapping does not make sense Variance for the performance short answer: yes it does make sense to speak of variance in situation where only {0,1} outcomes exist. Have a look at the binomial distribution (k = successes, n = tests, p = true probability for success = average k / n): $\sigma^2 (k) = np(1-p)$ The variance of proportions (such as hit rate, error rate, sensitivity, TPR,..., I'll use $p$ from now on and $\hat p$ for the observed value in a test) is a topic that fills whole books... Fleiss: Statistical Methods for Rates and Proportions Forthofer and Lee: Biostatistics has a nice introduction. Now, $\hat p = \frac{k}{n}$ and therefore: $\sigma^2 (\hat p) = \frac{p (1-p)}{n}$ This means that the uncertainty for measuring classifier performance depends only on the true performance p of the tested model and the number of test samples. In cross validation you assume that the k "surrogate" models have the same true performance as the "real" model you usually build from all samples. (The breakdown of this assumption is the well-known pessimistic bias). that the k "surrogate" models have the same true performance (are equivalent, have stable predictions), so you are allowed to pool the results of the k tests. Of course then not only the k "surrogate" models of one iteration of cv can be pooled but the ki models of i iterations of k-fold cv. Why iterate? The main thing the iterations tell you is the model (prediction) instability, i.e. variance of the predictions of different models for the same sample. You can directly report instability as e.g. the variance in prediction of a given test case regardless whether the prediction is correct or a bit more indirectly as the variance of $\hat p$ for different cv iterations. And yes, this is important information. Now, if your models are perfectly stable, all $n_{bootstrap}$ or $k \cdot n_{iter.~cv}$ would produce exactly the same prediction for a given sample. In other words, all iterations would have the same outcome. The variance of the estimate would not be reduced by the iteration (assuming $n - 1 \approx n$). In that case, assumption 2 from above is met and you are subject only to $\sigma^2 (\hat p) = \frac{p (1-p)}{n}$ with n being the total number of samples tested in all k folds of the cv. In that case, iterations are not needed (other than for demonstrating stability). You can then construct confidence intervals for the true performance $p$ from the observed no of successes $k$ in the $n$ tests. So, strictly, there is no need to report the variance uncertainty if $\hat p$ and $n$ are reported. However, in my field, not many people are aware of that or even have an intuitive grip on how large the uncertainty is with what sample size. So I'd recommend to report it anyways. If you observe model instability, the pooled average is a better estimate of the true performance. The variance between the iterations is an important information, and you could compare it to the expected minimal variance for a test set of size n with true performance average performance over all iterations. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/31190', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/1538/']} | jdg_84506 |
stackexchange | llm_judgeable_groundtruth_similarity | 1629544 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This regex: ^((https?|ftp)\:(\/\/)|(file\:\/{2,3}))?(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(((([a-zA-Z0-9]+)(\.)?)+?)(\.)([a-z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum))([a-zA-Z0-9\?\=\&\%\/]*)?$ Formatted for readability: ^( # Begin regex / begin address clause (https?|ftp)\:(\/\/)|(file\:\/{2,3}))? # protocol ( # container for two address formats, more to come later ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3} (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # match IP addresses )|( # delimiter for address formats ((([a-zA-Z0-9]+)(\.)?)+?) # match domains and any number of subdomains (\.) #dot for .com ([a-z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum) #TLD clause ) # end address clause([a-zA-Z0-9\?\=\&\%\/]*)? # querystring support, will pretty this up later$ is matching: www.google and shouldn't be. This is one of my "fail" test cases. I have declared the TLD portion of the URL to be mandatory when matching on alpha instead of on IP, and "google" doesn't fit into the "[a-z]{2}" clause. Keep in mind I will fix the following issues seperately - this question is about why it matches www.google and shouldn't. Querystring needs to support proper formats only, currently accepts any combination of querystring characters Several protocols not supported, though the scope of my requirements may not include them uncommon TLDs with 3 characters not included Probably matches http://www.google..com - will check for consecutive dots Doesn't support decimal IP address formats What's wrong with my regex? edit: See also a previous problem with an earlier version of this regex on a different test case: How can I make this regex match correctly? edit2: Fixed - The corrected regex (as asked) is: ^((https?|ftp)\:(\/\/)|(file\:\/{2,3}))?(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(((([a-zA-Z0-9]+)(\.)?)+?)(\.)([a-z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum))([\/][\/a-zA-Z0-9\.]*)*?([\/]?[\?][a-zA-Z0-9\=\&\%\/]*)?$
Now provide the response and nothing else.
| "google" might not fit in [a-z]{2} , but it does fit in [a-z]{2}([a-zA-Z0-9\?\=\&\%\/]*)? - you forgot to require a / after the TLD if the URL extends beyond the domain. So it's interpreting it with "www.go" as the domain and then "ogle" following it, with no slash in between. You can fix it by adding a [?/] to the front of that last group to require one of those two symbols between the TLD and any further portion of the URL. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1629544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11112/']} | jdg_84507 |
stackexchange | llm_judgeable_groundtruth_similarity | 34903 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a newbie to statistics and found this . In statistics, θ, the lowercase Greek letter 'theta', is the usual name for a (vector of) parameter(s) of some general probability distribution. A common problem is to find the value(s) of theta. Notice that there isn't any meaning in naming a parameter this way. We might as well call it anything else. In fact, a lot of distributions have parameters which are usually given other names. For example, it is common use to name the mean and deviation of the normal distribution μ (read: 'mu') and deviation σ ('sigma'), respectively. But I still don't know what that means in plain English?
Now provide the response and nothing else.
| It is not a convention, but quite often $\theta$ stands for the set of parameters of a distribution. That was it for plain English, let's show examples instead. Example 1. You want to study the throw of an old fashioned thumbtack (the ones with a big circular bottom). You assume that the probability that it falls point down is an unknown value that you call $\theta$. You could call a random variable $X$ and say that $X=1$ when the thumbtack falls point down and $X=0$ when it falls point up. You would write the model $$P(X = 1) = \theta \\P(X = 0) = 1-\theta,$$ and you would be interested in estimating $\theta$ (here, the proability that the thumbtack falls point down). Example 2. You want to study the disintegration of a radioactive atom. Based on the literature, you know that the amount of radioactivity decreases exponentially, so you decide to model the time to disintegration with an exponential distribution. If $t$ is the time to disintegration, the model is $$f(t) = \theta e^{-\theta t}.$$ Here $f(t)$ is a probability density, which means that the probability that the atom disintegrates in the time interval $(t, t+dt)$ is $f(t)dt$. Again, you will be interested in estimating $\theta$ (here, the disintegration rate). Example 3. You want to study the precision of a weighing instrument. Based on the literature, you know that the measurement are Gaussian so you decide to model the weighing of a standard 1 kg object as $$f(x) = \frac{1}{\sigma \sqrt{2\pi}} \exp \left\{ -\left( \frac{x-\mu}{2\sigma} \right)^2\right\}.$$ Here $x$ is the measure given by the scale, $f(x)$ is the density of probability, and the parameters are $\mu$ and $\sigma$, so $\theta = (\mu, \sigma)$. The paramter $\mu$ is the target weight (the scale is biased if $\mu \neq 1$), and $\sigma$ is the standard deviation of the measure every time you weigh the object. Again, you will be interested in estimating $\theta$ (here, the bias and the imprecision of the scale). | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/34903', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/11799/']} | jdg_84508 |
stackexchange | llm_judgeable_groundtruth_similarity | 23010 |
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to run a windows xp OS on my raspberry.If I try to install it with Win32DiskImager would be able to use?Which version should I try?
Now provide the response and nothing else.
| TL;DR Yes it is possible to virtualize Windows XP on an ARM device such as Raspberry Pi. For anyone saying that this isn't possible needs to re-evaluate what "possible" means. Just because it hasn't been done yet (which it has), it's not appropriate to say it's impossible. In fact, it's generally never a good idea to claim something as impossible. That said, it IS entirely possible to run x86 systems on an ARM device if it meets the standard requirements. I have first hand experience with getting Mac OS X Mavericks running on an ARM HDMI stick, primarily aimed at running Android on a TV. This setup requires that QEMU be compiled and running with a specific configuration. There are also guides that have ported Windows 95 , 98 , XP and other x86 system to run on many ARM devices. One such guide can be found here From the guide: Now you can run x86 based operating systems on your ARM device. Now you can have full desktop windows/linux experience on your Android smartphones. It should be noted that this guide was primarily written with an Android operating system in mind, however one with enough experience can get a minimal Linux OS running on the rPI, say Debian , Linux Mint or lubuntu and then attempt to get QEMU compiled. Looking at the minimum system requirements of Windows XP and then comparing those to Raspberry Pi's specifications, at a glance I would say it's possible to virtualize XP. I don't know what kind of performance you could get and it might even prove to be unusable. However, it would be an interesting experiment to try. To give you an idea of the steps that would be required, it would look something like this. Get a linux distribution of your choice to run on RPI, like Debian, Ubuntu, etc. Compile QEMU with whatever requirements that Windows XP needs to emulate. This step requires research on your part. Virtualize Windows XP with a running version of QEMU and attach the video to the QEMU instance. Most things in the OS should operate normally, however you may run into compatibility problems with hardware due to emulated conditions. Note the limitations of running Windows XP, which is a very dated piece of software that has reached it's end of life. This means that newer modern web browsers, firewalls, anti-virus solutions and many more key pieces of software probably won't run properly, if it all. Extras: Here is a video tutorial of how to get QEMU running on the Pi. Here are some reasons of why I think it could be possible. A YouTube video in German that displays Windows XP booting up in 20-some minutes on a Raspberry Pi. Eye witness accounts of running OSX Mavericks on an Android HDMI stick Several tutorials of running past OS's with QEMU virtualization (x86 to ARM) | {} | {'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/23010', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/19605/']} | jdg_84509 |
stackexchange | llm_judgeable_groundtruth_similarity | 274623 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would appreciate it if somebody could help me with the following problem: Q: To find the number of ordered pairs of natural numbers in the following equation $$a+b+c+d=13$$ we want to add the condition that $\frac{a+b+c}{d}$ is an integer. What should I do? Please advise. My Try: {a,b,c,d} /. Solve[ a+b+c+d==13 &&1<={a,b,c,d}<=12, IntegerQ[(a+b+c)/d]==True, {a,b,c,d}, Integers]
Now provide the response and nothing else.
| The approach with Solve in the original question is syntactically incorrect and mathematically not quite correct . The natural numbers start with zero not one. This might be reformulated as e.g. {a, b, c, d} /. Normal @ Solve[ a + b + c + d == 13 && 0 <= {a, b, c, d} && (a + b + c)/d == k, {a, b, c, d, k}, Integers] However this solution is not especially elegant and efficient. Since $a+b+c= k\;d$ we have $13=a+b+c+d = k\; d+ d=(k+1)\; d$ , and since $13$ is a prime number this means that $k =12$ and $d=1$ or $k=0$ and $d=13$ . The second case is trivial $\{a,b,c\}=\{0,0,0\}$ .Possible solutions in the first case one can find with FrobeniusSolve , e.g. FrobeniusSolve[{1, 1, 1}, 12] and the number of solutions is simiply FrobeniusSolve[{1, 1, 1}, 12] // Length 91 plus $1$ solution of the second case, i.e. $92$ solutions. If we are looking only for positive solutions there are only DeleteCases[FrobeniusSolve[{1, 1, 1}, 12], {___, 0, ___}] // Length 55 solutions. FrobeniusSolve is a better approach than Solve because of it efficiency for such problems, see e.g. Finding the number of solutions to a diophantine equation . | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/274623', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/61953/']} | jdg_84510 |
stackexchange | llm_judgeable_groundtruth_similarity | 8498357 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've learned difference between sessionStorage (persist during session) and localStorage (persist forever if not deleted). I can see that localStorage can be used as better version of cookie. (more size, not traveling to server for each HTTP request like cookie does). But for sessionStorage , I'm thinking when should I use it effectively? I thought about user inputs into text fields in pageA and then moves onto pageB within the same tab or browser window, pageB can look up sessionStorage. I can't really expand my guess more than the scenario above. Could anyone tell me how can sessionStorage be used?
Now provide the response and nothing else.
| With ajax-driven dynamic interfaces, a lot of times there is nothing storing the current state of how the interface looks (like which tab is selected, for example). sessionStorage could be used to store the state of the interface, so when coming back to a page, you can restore the screen the way the user was looking at it. Another use would be if several pages deep you are working on a single object, you could store the id like a global variable: currentInvoiceId . User settings that are needed on every page, like a special layout or template, could be loaded once up front and put into sessionStorage for easy access. Some things you only want the user to see once per login, like a news popup. You could store that they've seen it already in sessionStorage . This would also work for actions that you only want the user to do once per login. It's a good alternative to passing data between pages using viewstate, hidden <input> fields, or URL parameters. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8498357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/355044/']} | jdg_84511 |
stackexchange | llm_judgeable_groundtruth_similarity | 43137275 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Not able to get values of input type using this.refs...how to get that values from input type export class BusinessDetailsForm extends Component { submitForm(data) { console.log(this.refs.googleInput.value) } } reder() { return( <form onSubmit={this.submitForm}> <Field type="text" name="location" component={GoogleAutoComplete} id="addressSearchBoxField" ref="googleInput" /> </form> ) } }
Now provide the response and nothing else.
| You should avoid ref="googleInput" as it is now considered legacy. You should instead declare ref={(googleInput) => { this.googleInput = googleInput }} Inside of your handler, you can use this.googleInput to reference the element. Then inside of your submitForm function, you can obtain the text value with this.googleInput._getText() String refs are legacy https://facebook.github.io/react/docs/refs-and-the-dom.html If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead. Edit From React 16.3 , the format for creating refs are: class Component extends React.Component { constructor() { this.googleInput = React.createRef(); } render() { return ( <div ref={this.googleInput}> {/* Details */} </div> ); } } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43137275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7510657/']} | jdg_84512 |
stackexchange | llm_judgeable_groundtruth_similarity | 18008700 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Sass, I can't quite discern the difference between using @include with a mixin and using @extend with a placeholder class. Don't they amount to the same thing?
Now provide the response and nothing else.
| Extends do not allow customization, but they produce very efficient CSS. %button background-color: lightgrey &:hover, &:active background-color: whitea @extend %buttonbutton @extend %button Result: a, button { background-color: lightgrey;}a:hover, button:hover, a:active, button:active { background-color: white;} With mixins, you get duplicated CSS, but you can use arguments to modify the result for each usage. =button($main-color: lightgrey, $active-color: white) background-color: $main-color border: 1px solid black border-radius: 0.2em &:hover, &:active background-color: $active-colora +buttonbutton +button(pink, red) Results in: a { background-color: lightgrey; border: 1px solid black; border-radius: 0.2em;}a:hover, a:active { background-color: white;}button { background-color: pink; border: 1px solid black; border-radius: 0.2em;}button:hover, button:active { background-color: red;} Please follow this consecutive set of code examples to see how you can make your code cleaner and more maintainable by using extends and mixins effectively: http://thecodingdesigner.com/posts/balancing Note that SASS unfortunately does not allow using extends inside media queries (and corresponding example from the above link is wrong). In the situation where you need to extend based on media queries, use a mixin: =active display: block background-color: pink%active +active#main-menu @extend %active // Active by default#secondary-menu @media (min-width: 20em) +active // Active only on wide screens Result: #main-menu { display: block; background-color: pink;}@media (min-width: 20em) { #secondary-menu { display: block; background-color: pink; }} Duplication is inevitable in this case, but you shouldn't care too much about it because web server's gzip compression will take care of it. PS Note that you can declare placeholder classes within media queries. Update 2014-12-28 : Extends produce more compact CSS than mixins do, but this benefit is diminished when CSS is gzipped. If your server serves gzipped CSS (it really should!), then extends give you almost no benefit. So you can always use mixins ! More on this here: http://www.sitepoint.com/sass-extend-nobody-told-you/ | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18008700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1029146/']} | jdg_84513 |
stackexchange | llm_judgeable_groundtruth_similarity | 135608 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Our team is developing a project using an Agile development process. All of our requirements are converted into product backlog items and task are broken down based on that. One of my team member suggested to maintain the High Level Document (HLD) and Low Level Document (LLD) for the requirement. Do we need to have these documents to follow the Agile process?
Now provide the response and nothing else.
| No, Agile does not call for the need of HLD (or SRS, business requirements) document or LLD (or technical specification) to be associated with User Stories. These documents would be highly encouraged for the Waterfall process however. Simply because Agile does not call for this doesn't mean that it shouldn't exist though. They are not mutually exclusive. One can theoretically manage an Agile project and still demand HLD and LLD documents however the case should be made if these documents bring value to the stakeholders . It is highly encouraged in Agile to only do tasks that bring value to the stakeholder and most would argue these documents do not do this. They may bring value to the architects or to the developer, but the users and other stakeholders likely do not care about such things unless they specifically require them as deliverables. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/135608', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/46506/']} | jdg_84514 |
stackexchange | llm_judgeable_groundtruth_similarity | 19534210 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have implemented In-App billing in my app - and very recently google has updated it,previously i was testing the in-app billing with "android.test.purchased" and it was working fine (Buy full Version and Restore full version). Now i took the changed classes from here https://code.google.com/p/marketbilling/source/detail?r=7bc191a004483a1034b758e1df0bda062088d840 After that i am not able to test the app it gives the following error in the Logcat "IabHelper: In-app billing error: Purchase signature verification FAILED for sku android.test.purchased". I have checked with my key, package name and also app version all is proper, has any one faced this issue? Please help me with this.
Now provide the response and nothing else.
| This is because of the verifyPurchase() method in the Security class that has been change in the new fixes. Let me show you what is the exact problem is: Security class changes OLD CODE public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return false; } boolean verified = false; if (!TextUtils.isEmpty(signature)) { PublicKey key = Security.generatePublicKey(base64PublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return false; } } return true; } New Code public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) { if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) || TextUtils.isEmpty(signature)) { Log.e(TAG, "Purchase verification failed: missing data."); return false; } PublicKey key = Security.generatePublicKey(base64PublicKey); return Security.verify(key, signedData, signature);} According to what I have searched and tested from New code, Why it happens because we will not get any signature while we are using dummy product like "android.test.purchased". So in the old code it is working good because we were return true even if signature is not given and for the New code we are returning false. more information about the signature data null or blank from link1 and link2 So I suggest you just replace old code method verifyPurchase() instead of New Code method. I think may be New Code will work fine for the real product but not in the dummy product. But yet I have not tested for the real product. Let me search more about this, why they changed code and what is the purpose behind that. EDIT: BuildConfig.DEBUG will also give you the solution for the test purchases. In the verifyPurchase I changed return false to: Log.e(TAG, "Purchase verification failed: missing data."); if (BuildConfig.DEBUG) { return true; } return false; but you should be aware to use this only in test scenario's. This will return true, if you have a debug build, and the signature data is missing. Since the BuildConfig.DEBUG will be false in a production build this should be OK. But better is to remove this code after everything is debugged. I have edited some code in the verifyPurchase() method, check it below: public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return false; } if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) || TextUtils.isEmpty(signature)) { Log.e(TAG, "Purchase verification failed: missing data."); if (BuildConfig.DEBUG) { Log.d("DeBUG", ">>>"+BuildConfig.DEBUG); return true; } return false; } PublicKey key = Security.generatePublicKey(base64PublicKey); return Security.verify(key, signedData, signature);} I got this from GvS's answer android in app billing purchase verification failed . hope it is helpful for you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19534210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1187594/']} | jdg_84515 |
stackexchange | llm_judgeable_groundtruth_similarity | 320195 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am developing a RESTful API and I think it is convenient to use DAOs for my resources because although I plan on just using memory to store them, I don't want to close a door to whoever is using my library if they decided to use a database implementation for the DAO. My question is whether the DAO should be a singleton or not. If it is not, the service will have an instance of the DAO and it would look roughly like this: @Path("eventscheduler")public class EventSchedulerService { private IEventSchedulerDao dao = new EventSchedulerDao(); // in case a different implementation is to be used public void setEventSchedulerDao(IEventSchedulerDao dao) { this.dao = dao; } @Path("{uniqueName}") @GET @Produces(MediaType.APPLICATION_JSON) public Tournament getTournament(@PathParam("name") String uniqueName) { return dao.get(uniqueName); } @Path("create") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Tournament createTournament(Tournament tournament) { return dao.create(tournament); }} While if the DAO was a singleton, but I guess there wouldn't be much of a difference, just in the first line: private IEventSchedulerDao dao = EventSchedulerDao.getInstance(); I would still have to use an IEventSchedulerDao instance, but I guess all singletons work like this right? For some reason I always correlate singletons to static methods, so instead of having a singleton instance visible to the user with getInstance() , this would be hidden and he/she would just use EventSchedulerDao.get(name) , etc... in a static fashion. Is this a thing or is this just me? So, should I or should I not have singleton DAOs? And as a side question, is it alright my approach to have open doors for the user to implement their own DAOs?
Now provide the response and nothing else.
| I wouldn't use a singleton. It's a recognised anti-pattern , and makes testing difficult. I would much rather inject in a concrete implementation, and have your service reference a DAO interface (allowing you to inject different implementations in) | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/320195', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/223143/']} | jdg_84516 |
stackexchange | llm_judgeable_groundtruth_similarity | 6977218 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to migrate a database where images were stored in the database to a record in the database pointing at a file on the hard drive. I was trying to use Parallel.ForEach to speed up the process using this method to query out the data. However, I noticed that I was getting an OutOfMemory Exception. I know Parallel.ForEach will query a batch of enumerables to mitigate the cost of overhead if there is one for spacing the queries out (so your source will more likely have the next record cached in memory if you do a bunch of queries at once instead of spacing them out). The issue is due to one of the records that I am returning is a 1-4Mb byte array that caching is causing the entire address space to be used up (The program must run in x86 mode as the target platform will be a 32-bit machine) Is there any way to disable the caching or make is smaller for the TPL? Here is an example program to show the issue. This must be compiled in the x86 mode to show the issue if it is taking to long or is not happening on your machine bump up the size of the array (I found 1 << 20 takes about 30 secs on my machine and 4 << 20 was almost instantaneous) class Program{ static void Main(string[] args) { Parallel.ForEach(CreateData(), (data) => { data[0] = 1; }); } static IEnumerable<byte[]> CreateData() { while (true) { yield return new byte[1 << 20]; //1Mb array } }}
Now provide the response and nothing else.
| The default options for Parallel.ForEach only work well when the task is CPU-bound and scales linearly . When the task is CPU-bound, everything works perfectly. If you have a quad-core and no other processes running, then Parallel.ForEach uses all four processors. If you have a quad-core and some other process on your computer is using one full CPU, then Parallel.ForEach uses roughly three processors. But if the task is not CPU-bound, then Parallel.ForEach keeps starting tasks, trying hard to keep all CPUs busy. Yet no matter how many tasks are running in parallel, there is always more unused CPU horsepower and so it keeps creating tasks. How can you tell if your task is CPU-bound? Hopefully just by inspecting it. If you are factoring prime numbers, it is obvious. But other cases are not so obvious. The empirical way to tell if your task is CPU-bound is to limit the maximum degree of parallelism with ParallelOptions.MaximumDegreeOfParallelism and observe how your program behaves. If your task is CPU-bound then you should see a pattern like this on a quad-core system: ParallelOptions.MaximumDegreeOfParallelism = 1 : use one full CPU or 25% CPU utilization ParallelOptions.MaximumDegreeOfParallelism = 2 : use two CPUs or 50% CPU utilization ParallelOptions.MaximumDegreeOfParallelism = 4 : use all CPUs or 100% CPU utilization If it behaves like this then you can use the default Parallel.ForEach options and get good results. Linear CPU utilization means good task scheduling. But if I run your sample application on my Intel i7, I get about 20% CPU utilization no matter what maximum degree of parallelism I set. Why is this? So much memory is being allocated that the garbage collector is blocking threads. The application is resource-bound and the resource is memory. Likewise an I/O-bound task that performs long running queries against a database server will also never be able to effectively utilize all the CPU resources available on the local computer. And in cases like that the task scheduler is unable to "know when to stop" starting new tasks. If your task is not CPU-bound or the CPU utilization doesn't scale linearly with the maximum degree of parallelism, then you should advise Parallel.ForEach not to start too many tasks at once. The simplest way is to specify a number that permits some parallelism for overlapping I/O-bound tasks, but not so much that you overwhelm the local computer's demand for resources or overtax any remote servers. Trial and error is involved to get the best results: static void Main(string[] args){ Parallel.ForEach(CreateData(), new ParallelOptions { MaxDegreeOfParallelism = 4 }, (data) => { data[0] = 1; });} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6977218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80274/']} | jdg_84517 |
stackexchange | llm_judgeable_groundtruth_similarity | 42621023 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to compare two different lists with one property in common (Name). I have tried things like the .Contains() method, but that does not work because I am dealing with lists of two different objects. I have tried the solutions in questions like: C# Compare Two Lists of Different Objects C#, compare two different type of lists compare different type of list in c# But these solutions do not work because my lists expect a Property or Animal object and not a "string", this is where I get stuck. I have two classes: public class Animal { public string Name = string.Empty; public string XChromosome = string.Empty; public string YChromosome = string.Empty; }public class Properties{ public string Name = string.Empty; public string Prop1 = string.Empty; public string Prop2 = string.Empty;} The two lists look like this: List<Animal> = "name", "xposition", "yposition" "name1", "xposition1", "yposition1" etc..List<Properties> = "name", "prop1","prop2" "name1", "prop3", "prop4" etc.. What I would like to do do is, compare these two lists and if the "Name" matches I would like to get the content of both lists belonging to this name. I also tried using a HashSet or a Dictionary, but this is not what I am looking for.
Now provide the response and nothing else.
| You can join two lists on Name property and get matches as anonymous object: from a in animalsjoin p in properties on a.Name equals p.Nameselect new { a.Name, a.XChromosome, a.YChromosome, p.Prop1, p.Prop2} You can try it yourself in .NET Fiddle . NOTE: If you want to get animal info no matter if there is match in properties, or you can have more than one match for given animal, then you need to use group join ( check this fiddle for details): from a in animals join p in properties on a.Name equals p.Name into g from p in g.DefaultIfEmpty() select new { a.Name, a.XChromosome, a.YChromosome, Prop1 = p?.Prop1, Prop2 = p?.Prop2 } That wil return each pair of animal - property joined by name. If no matching property found, then Prop1 and Prop2 will have null values by default (though you can provide any default value you want). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42621023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7665121/']} | jdg_84518 |
stackexchange | llm_judgeable_groundtruth_similarity | 49491982 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to know if it is possible to create a dynamic HTML table from JSON data. The amount of columns and headers should change according to the keys in the JSON. For example this JSON should create this table: { color: "green", code: "#JSH810" } , { color: "red", code: "#HF59LD" } ... And this JSON should create this table: { id: "1", type: "bus", make: "VW", color: "white"},{ id: "2", type: "taxi", make: "BMW", color: "blue"}... This has to be 100% dynamic though, because I want to display hundreds of different JSON objects, so nothing should be hard coded in the HTML page.
Now provide the response and nothing else.
| If you want to get the key of your object as the head of your table, you should create a custom pipe . import { PipeTransform, Pipe } from '@angular/core';@Pipe({name: 'keys'})export class KeysPipe implements PipeTransform { transform(value, args:string[]) : any { let keys = []; for (let key in value) { keys.push(key); } return keys; }} Update: Or simply return keys using Object.keys() . ( demo ) @Pipe({name: 'keys'})export class KeysPipe implements PipeTransform { transform(value, args:string[]) : any { return Object.keys(value); }} Now into your html template: <table> <thead> <tr> <th *ngFor="let head of items[0] | keys">{{head}}</th> </tr> </thead> <tbody> <tr *ngFor="let item of items"> <td *ngFor="let list of item | keys">{{item[list]}}</td> </tr> </tbody></table> Update : Here is the demo . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49491982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9283107/']} | jdg_84519 |
stackexchange | llm_judgeable_groundtruth_similarity | 41869070 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am developing an Android app that does Human Activity Recognition. It basically works like that - Service constantly reads the accelerator data and stores the recognized activity (i.e. Walking, running) in a database. The user can see all of the recognized activities in an ListView in activity (accesses the database). Every User table in the database has a pa_goal (physical activity goal) field which the Service reads from the database and does some checks. The user, of course, can change this goal from an activity. Since I will be implementing the MVP architectural pattern. I am unsure where to put the Service? It surely isn't View. Any advice?
Now provide the response and nothing else.
| In a clean architecture, which is what I am assuming you are using MVP for, there is the idea of separating the framework from the business logic. This is essentially what a normal presenter allows you to do. In this case its not a view you are dealing with but the principle is similar. You don't want all your business or application logic mixed in the Android code when you can separate them out for nicer, more single responsibility classes. So I would say that while it isn't a view you should still have a presenter type class (probably better to be called controller or manager maybe). This class would be a POJO that controls how your service behaves which is easily testable with standard junit tests and service mocks. This class and the service could then be put into its own feature package and interact with the back end models the same way as your presenters. So, in summary, the role is of another feature of your app that sites alongside the other features (which are usually just views in my experience). Hope that helps | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41869070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3398554/']} | jdg_84520 |
stackexchange | llm_judgeable_groundtruth_similarity | 8683125 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I like the module pattern that returns constructors as described in: http://elegantcode.com/2011/02/15/basic-javascript-part-10-the-module-pattern/ However I am not sure how to inherit from an object that is implemented with this pattern. Suppose I have a parent object implemented thus... namespace('MINE'); MINE.parent = (function() { // private funcs and vars here // Public API - constructor var Parent = function (coords) { // ...do constructor stuff here }; // Public API - prototype Parent.prototype = { constructor: Parent, func1: function () { ... }, func2: function () { ... } } return Parent; }()); How do I define a child object that also uses the module pattern that inherits from parent in such a way that I can selectively override, for example, func2 ?
Now provide the response and nothing else.
| MINE.child = (function () { var Child = function (coords) { Parent.call(this, arguments); } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; Child.prototype.func2 = function () { ... }; return Child;}()); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8683125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_84521 |
stackexchange | llm_judgeable_groundtruth_similarity | 12195382 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been having a hard time googling an answer for this, but....can someone explain to me the difference between putting the ON condition of a JOIN with the the JOIN itself vs putting the ON at the end of all the other JOINs. here is an example http://sqlfiddle.com/#!3/e0a0f/3 CREATE TABLE TableA (Email VARCHAR(100), SomeNameA VARCHAR(100))CREATE TABLE Tableb (Email VARCHAR(100), SomeNameB VARCHAR(100))CREATE TABLE Tablec (Email VARCHAR(100), SomeNameC VARCHAR(100))INSERT INTO TableA SELECT '[email protected]', 'JoeA'INSERT INTO TableA SELECT '[email protected]', 'JaneA'INSERT INTO TableA SELECT '[email protected]', 'DaveA'INSERT INTO TableB SELECT '[email protected]', 'JoeB'INSERT INTO TableB SELECT '[email protected]', 'DaveB'INSERT INTO TableC SELECT '[email protected]', 'JoeC'INSERT INTO TableC SELECT '[email protected]', 'DaveC'SELECT TOP 2 a.*, b.*, c.*FROM TableA a LEFT OUTER JOIN TableB b ON a.email = b.email INNER JOIN TableC c ON c.Email = b.email;SELECT TOP 2 a.*, b.*, c.*FROM TableA a LEFT OUTER JOIN TableB b INNER JOIN TableC c ON c.Email = b.email ON a.email = b.email; I don't understand why these two SELECT statements produce different results.
Now provide the response and nothing else.
| What matters is orders of joins. Treat your expressions as if every join produced temporary "virtual" table. So when you write FROM TableA a LEFT OUTER JOIN TableB b ON a.email = b.emailINNER JOIN TableC c ON c.Email = b.email ; then order is as follows: TableA is left joined to TableB producing temporary relation V1 V1 is inner joined to TableC . Meanhwile when you write: FROM TableA a LEFT OUTER JOIN TableB b INNER JOIN TableC c ON c.Email = b.email ON a.email = b.email; then order is as follows: TableB is inner joined to TableC producing temporary relation V1 . TableA is left joined to V1 . Thus results are different. It is generally recommended to use parenthesis in such situations to improve readability of the query: FROM TableA a LEFT OUTER JOIN (TableB b INNER JOIN TableC c ON c.Email = b.email)ON a.email = b.email; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12195382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139912/']} | jdg_84522 |
stackexchange | llm_judgeable_groundtruth_similarity | 1720678 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created a component and it is automatically shown in toolbox when I open the solution. It can be placed on form, I can change properties etc. When I close the solution and install it in toolbox (choose toolbox item menu), I want this component to be shown in a different group (other than "All Windows Forms" group). How can I do it? EDIT: I want my components to be shown in a custom group such as "My Components".
Now provide the response and nothing else.
| This version uses a bit more PowerShell and handles the case of mulitple items with WorkDir keys: $xml = [xml](Get-Content foo.xml)$xpath = "/sections/section/item[@key='WorkDir']" Microsoft.PowerShell.Utility\Select-Xml $xml -XPath $xpath | Foreach {$_.Node.SetAttribute('value', $pwd)}$xml.Save("$pwd\bar.xml") Note, if you have the PowerShell Community Extensions installed you can use the Format-Xml cmdlet to format the output and save it via Out-File e.g.: $xml | Format-Xml -AttributesOnNewLine | Out-File bar.xml -enc utf8 OTOH $xml.Save() is easier except that you must remember that it probably doesn't have the correct current dir if you were to specify just the filename. That's why I used "$pwd\bar.xml" in the first example. This is not an issue with PowerShell cmdlets like Out-File. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1720678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23671/']} | jdg_84523 |
stackexchange | llm_judgeable_groundtruth_similarity | 31377680 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the book of "function programming in Scala", it gives several example of what is "side-effects", one of them is: Reading from or writing to a file I can understand "writing to a file" is not pure, because it changes the environment. But why "reading a file" is not pure? It doesn't change anything. See my example: val readFile: File => String = file => readingTheContentFromFile(file)
Now provide the response and nothing else.
| A pure function allways returns the same value given the same input. Otherwise it is based on side effects (like changing a file). If you read from a file the results might change without the parameters given to the function changing. The relevant concept is 'referential transparency'. This means you can substitute a function call and a given set of parameters with the result the function would return. Reading from a file is therefore not referentially transparent! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31377680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']} | jdg_84524 |
stackexchange | llm_judgeable_groundtruth_similarity | 7059780 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is an array (of size N) with an element repeated more than N/2 number of time and the rest of the element in the array can also be repeated but only one element is repeated more than N/2 times. Find the number. I could think of few approaches: Naive, keep the count of each number in a hash map. Simplest, sort the array and the number at n/2+1 th index is therequired number. Keep count of only consecutive duplicate values found. Checkseparately for the pattern where the values are stored alternatively. Unable to think of a better solution, there has to be.
Now provide the response and nothing else.
| There is a beautiful algorithm for solving this that works in two passes (total time O(N)) using only constant external space (O(1)). I have an implementation of this algorithm, along with comments including a correctness proof, available here The intuition behind the algorithm is actually quite beautiful. Suppose that you were to have a roomful of people each holding one element of the array. Whenever two people find each other where neither is holding the same array element as the other, the two of them sit down. Eventually, at the very end, if anyone is left standing, there's a chance that they're in the majority, and you can just check that element. As long as one element occurs with frequency at least N/2, you can guarantee that this approach will always find the majority element. To actually implement the algorithm, you make a linear scan over the array and keep track of your current guess as to what the majority element is, along with the number of times that you've seen it so far. Initially, this guess is undefined and the number of repeats is zero. As you walk across the array, if the current element matches your guess, you increment the counter. If the current element doesn't match your guess, you decrement the counter. If the counter ever hits zero, then you reset it to the next element you encounter. You can think about this implementation as a concrete realization of the above "standing around in a room" algorithm. Whenever two people meet with different elements, they cancel out (dropping the counter). Whenever two people have the same element, then they don't interact with each other. For a full correctness proof, citation to the original paper (by Boyer and Moore of the more famous Boyer-Moore string matching algorithm), and an implementation in C++, check out the above link. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7059780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/854075/']} | jdg_84525 |
stackexchange | llm_judgeable_groundtruth_similarity | 522956 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have spent the past few days trying to reverse engineer a capacitive moisture sensor I ordered from eBay a while ago . The particular one I received looks like this: What fascinated me about this sensor was that I could put it in a plastic bag and it would still be able to give accurate moisture readings. In air, the output voltage of the sensor is about 2.3V; in water, I am getting around 0.7V when submerged directly and 1.6V when submerged in a plastic bag. After analysing the circuit, I came up with this schematic (Note: I have left out the voltage regulator and the four corresponding caps, because I am feeding in 3.3V DC from my bench supply directly): I then built a prototype on a breadboard, which gave me this result: Unfortunately, my sensor does not work as well as the one I bought, because the voltage drops seem to be a lot smaller. The output voltage in the air is the same. But when submerging it directly in water, I am getting 1.6V (as opposed to 0.7v for the bought one). When submerging it in a plastic bag, I can only see a voltage drop of 10mv to about 2.29V. I have already re-measured the component values several times and also buzzed out all the traces again to make sure I got the connections right, but I obviously must be missing something. One thing I have noticed while testing is that decreasing the value of C1 from 23nF to something like 470pF causes larger voltage drops, which makes my custom built sensor behave more like the bought one. But I'm still far from what I would like to see. I'm an electronics beginner and this is one of my first reverse engineering projects, so any advice/tip would be greatly appreciated. I suspect that there is something wrong with my 555 timer circuit, but since I don't have access to an oscilloscope, I could not really confirm that idea so far. SOLUTION: I finally managed to get my custom sensor to work like the bought one. To make it work, I did the following: Replace all electrolytic capacitors with ceramic ones Added a 100nF ceramic capacitor between VCC and GND Change the value of C3 from 40nF to 10nF Change the value of C1 from 23nF to 470pF Also, the 555 chip used makes a huge difference. When using a TI NE555DR, I doesn't work as well as when using the original NE555 of the bought sensor.
Now provide the response and nothing else.
| You're using a bipolar 555 and the original obviously has a CMOS TLC555 (marked TL555). There are a number of differences aside from power supply current draw including greater output swing (particularly noticeable on a 5V supply). Diode on the original is probably a 1N4148 or similar. A 1N400x is too slow for this application. I would expect C1 to be more like 470pF. You are using an electrolytic capacitor for the filter, which may be too leaky for the 1M resistor. It may be okay, but you should be aware of the distinction between a ceramic capacitor (10G or 0.5nA max leakage at 5V) and an electrolytic (maybe 3uA leakage after 1 minute maximum) which is 6,000 times worse. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/522956', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/263636/']} | jdg_84526 |
stackexchange | llm_judgeable_groundtruth_similarity | 2003666 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say that I have the following code: SELECT * FROM table where company LIKE '%Auto%' And I receive more results, and I want to have an option to sort the results alphabetically, let's say that the user wants to sort the search results for the ones which start with "C"! Best Regards,
Now provide the response and nothing else.
| Well, it seems that you are talking about two different things. If you are interested in sorting you would need to use the ORDER BY clause: SELECT * FROM table ORDER BY name If you want to filter the results by items that start with the letter 'C' then you would want to add another LIKE clause with that letter: SELECT * FROM table where company LIKE '%Auto%' AND name LIKE 'C%' Additionally you'll notice that the name filter only has the % after the query. This is the syntax for "starts with" | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2003666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58839/']} | jdg_84527 |
stackexchange | llm_judgeable_groundtruth_similarity | 222120 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does plot(ecdf(1:1000)) produce a straight line? Since Fn($x_n$) = $x_1$/(total sum) +$x_2$/(total sum) +...+$x_n$/total sum = ($x_1+x_2+x_3+...+x_n$)/total sum.the fact that Fn(200) roughly being equal to 0.2 and sum(0:200) roughly being equal to 0.4 seems to indicate that sum(1:200) is roughly half of sum(1:400), which isn't true, the two expressions being 20,000 and 80,000 respectively. What am i misunderstanding?
Now provide the response and nothing else.
| The cumulative distribution function of a random variable $X$ has nothing to do with summing the random variable. It is the probability that $X$ will take a value less than or equal to $x$. And of course, the probability that a value randomly sampled from your vector $(1, \dots, 1000)$ is less than or equal to 200 is exactly half the probability that it is less than or equal to 400. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/222120', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/86977/']} | jdg_84528 |
stackexchange | llm_judgeable_groundtruth_similarity | 36591421 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to remove unused resources from my project to reduce the app size. Is there any way to do it by using Android Studio IDE efficiently?
Now provide the response and nothing else.
| The Gradle build system for Android supports Resource Shrinking : the automatic removal of resources that are unused, at build time, in the packaged app. In addition to removing resources in your project that are not actually needed at runtime, this also removes resources from libraries you are depending on if they are not actually needed by your application. For example, your application is using Google Play Services to for example access Google Drive functionality, and you are not currently using Google Sign In, then this would remove the various drawable assets for the Sign In buttons. Note: Resource Shrinking only works in conjunction with code shrinking (such as ProGuard). That's how it can remove unused resources from libraries; normally, all resources in a library are used, and it is only when we remove unused code that it becomes apparent which resources are referenced from the remaining code. To enable resource shrinking, update your build type as follows: android { ... buildTypes { release { minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }} And google recently launched Android Studio 2.0 officially, Now they are giving an option in the IDE itself. Right click on app --> Refactor --> Remove Unused Resources It will prompt Check the box prior confirm action so that you can get rid of unused @id declarations too. In terms of APK optimization consider Selecting a Format fact as well. Use WebP Images provide better compression than either JPEG or PNG. Lossy WebP images are supported in Android 4.0 (API level 14) and higher, and lossless and transparent WebP images are supported in Android 4.3 (API level 18) and higher. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36591421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4817630/']} | jdg_84529 |
stackexchange | llm_judgeable_groundtruth_similarity | 3266666 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to find which one is bigger $100^{300}$ or $300!$ without using a calculator?I have tried it for whole 2 years but could not find it yet.
Now provide the response and nothing else.
| Let $n\in\Bbb N$ . We have $e<3$ and hence $$3^{3n}>e^{3n}=\sum_{k=0}^\infty\frac{(3n)^k}{k!}.$$ As all summands are positive, this implies $$ 3^{3n}>\frac{(3n)^k}{k!}=\frac{3^kn^k}{k!}$$ for all $k$ . In particular, for $k=3n$ , this becomes $3^{3n}>\frac{3^{3n}n^{3n}}{(3n)!}$ , or $$(3n)!>n^{3n}.$$ For $n=100$ , this gives us $$300! > 100^{300}. $$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3266666', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/683129/']} | jdg_84530 |
stackexchange | llm_judgeable_groundtruth_similarity | 22646 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to use the descriptive statistics feature of Mathematica to answer the following question: suppose I have two events, A and B, whose occurrence is described by a normal distribution around time $t_A$ and $t_B$ (with moments $\sigma_A$ and $\sigma_B$). What is the probability that, at a given time $t$, both events have occurred? I have tried to define distributions and then use them in a construct of the form Probability[A && B, …] , but it is clear from the documentation that Probability is not supposed to be used that way. PS: I'm not so much interested in the mathematical solution (I have to read up on that subject, I'm really bad in statistics), rather in the way I can get Mathematica to solve this issue without me doing the maths :)
Now provide the response and nothing else.
| For reasons @wolfies has amply made clear, it's wise to solve probability problems in Mathematica by getting as close to first principles as possible, rather than relying on black-box solutions (which tend to be much slower as well). Assuming (as the O.P. implicitly does) that the events are independent, the axioms of probability assert that the chance both events have occurred is the product of their chances of occurring. By definition, the chance that an event has occurred by time $t$ is the value of its cumulative distribution function at $t$. Therefore, after consulting the help page to make sure about the parameterization of Normal distributions, we can reliably construct a correct answer as f[t_, {tA_, sA_}, {tB_, sB_}] := Evaluate[CDF[NormalDistribution[tA, sA], t] CDF[NormalDistribution[tB, sB], t]]; (I stuck in the Evaluate so we can see what MMA 's final formula might be and compare it to other putative solutions: ? f $f[\text{t$\_$},\{\text{tA$\_$},\text{sA$\_$}\},\{\text{tB$\_$},\text{sB$\_$}\}]\text{:=}\frac{1}{4} \text{erfc}\left(\frac{\text{tA}-t}{\sqrt{2} \text{sA}}\right) \text{erfc}\left(\frac{\text{tB}-t}{\sqrt{2} \text{sB}}\right)$ Notice the lack of square roots over $s_A$ and $s_B$.) To help understand it, let's plot (a) this function against time $t$ and (b) the two probability density functions for the events, allowing manipulation of the four parameters $t_A, \ldots, s_B$. The principal contribution of this code is to determine reasonable ranges for the plots automatically: Manipulate[ range = {t, Min[tA, tB] - 3 Sqrt[sA^2 + sB^2], Max[tA, tB] + 3 Sqrt[sA^2 + sB^2]}; GraphicsRow[{ Plot[f[t, {tA, sA}, {tB, sB}], Evaluate@range, PlotStyle -> Thick, AxesLabel -> {"Time", "Probability"}, ImageSize -> i], Plot[{PDF[NormalDistribution[tA, sA]][t], PDF[NormalDistribution[tB, sB]][t]}, Evaluate@range, Filling -> Axis, PlotRange -> {Full, Full}, AxesLabel -> {"Time", "Density"}, ImageSize -> i] }], {{tA, 0}, -5, 0}, {{tB, 2}, 0, 5}, {{sA, 3}, 0, 3}, {{sB, 1/2}, 0, 3}, {{i, 300, "Image size"}, 50, 500} ] The illustration makes sense: there is essentially no probability of both events occurring before time $t=1$, when the event $B$ (red) first begins to have some visible chance of happening. At that point the chance of both events (left) rises rapidly because it's likely event $A$ (blue) has already occurred and the chance of event $B$ is rapidly increasing (as attested by the height of its density curve). By time $t=4$, the chance is good both events have already occurred, with some residual uncertainty about $A$ due to its wide spread. The righthand density plots appear correctly to represent Normal distributions with the given locations ($0$ and $2$) and spreads ($3$ and $1/2$, respectively) while the foregoing reasoning indicates the lefthand plot--our solution--correctly reflects the intended result. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/22646', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/700/']} | jdg_84531 |
stackexchange | llm_judgeable_groundtruth_similarity | 19073238 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i have modal with button (Save) <button type="button" class="btn btn-success btn-sm" data-dismiss="modal" onclick="do_save()">Save </button> how to prevent closing when do_save() function failed? (for example when some data fails to validate)
Now provide the response and nothing else.
| Don't use the data-dismiss="modal" and let your function close (hide) your modal: <button type="button" class="btn btn-success btn-sm" onclick="do_save()">Save</button> " function do_save() { if(Math.floor(Math.random() * 2)==1) { console.log('success'); $('#myModal').modal('hide'); return; } console.log('failure'); return false; } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19073238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620210/']} | jdg_84532 |
stackexchange | llm_judgeable_groundtruth_similarity | 19516771 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I want to pass the referrer state to another state so I use the toParams of $state.go like so: $state.go('toState', {referer: $state.current.name}); According to the docs , this should populate the $stateParams on the toState controller, but it is undefined . What am I missing? I've created a plunk to demonstrate: http://plnkr.co/edit/ywEcG1
Now provide the response and nothing else.
| If you want to pass non-URL state, then you must not use url when setting up your state . I found the answer on a PR and did some monkeying around to better understand. $stateProvider.state('toState', { templateUrl:'wokka.html', controller:'stateController', params: { 'referer': 'some default', 'param2': 'some default', 'etc': 'some default' }}); Then you can navigate to it like so: $state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' }); Or: var result = { referer:'jimbob', param2:37, etc:'bluebell' };$state.go('toState', result); And in HTML thusly: <a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a> This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19516771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255189/']} | jdg_84533 |
stackexchange | llm_judgeable_groundtruth_similarity | 55124010 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In symfony, I have an entity Program , which has the attribute image . Uploading images, naming them and putting them in the right directory is done with the VichUploaderBundle . The entity looks like this: //.../** * NOTE: This is not a mapped field of entity metadata, just a simple property. * * @Assert\Image( * maxSize="5M", * mimeTypesMessage="The file you tried to upload is not a recognized image file" * ) * @Vich\UploadableField(mapping="program_image", fileNameProperty="imageName") * * @var File */private $image;/** * @ORM\Column(type="string", length=191, nullable=true) */private $imageName; //... Now I wish for images to be processed before they are uploaded, which I have done with some JS that returns a base64 string. I put this string in a hidden input field, base64Image . I then retrieve this string in my controller and try to make it into an image that I can save to my entity like so: if ($form->isSubmitted() && $form->isValid()) { $program = $form->getData(); $base64String = $request->request->get('base64Image'); $decodedImageString = base64_decode($base64String); $program->setImage($decodedImageString);//etc..... The program occurs with the last line. $decodedImageString is actually another string that first needs to be created into a file. I have looked into file_put_contents to create a file as describer here , but with no luck. The filename cannot be empty Is the error I receive. Also I don't know if this would work with the VichUploaderBundle and perhaps the answer in that question is also outdated. Any suggestions on what I could do? Edit: Got the converting and uploading working with the following code: define('UPLOAD_DIR', 'images/');$img = $request->request->get('base64Image');$img = str_replace('data:image/jpeg;base64,', '', $img);$img = str_replace(' ', '+', $img);$data = base64_decode($img);$file = UPLOAD_DIR . uniqid() . '.jpeg';$success = file_put_contents($file, $data);print $success ? $file : 'Unable to save the file.'; Now I just need to load the VichUploaderBundle config somehow, or maybe not use that altogether perhaps.
Now provide the response and nothing else.
| An attempt of solution is to transform first the base64 file into a symfony uploadedFile. You define this service <?php namespace App\Utils; use Symfony\Component\HttpFoundation\File\UploadedFile; class UploadedBase64File extends UploadedFile { public function __construct(string $base64String, string $originalName) { $filePath = tempnam(sys_get_temp_dir(), 'UploadedFile'); $data = base64_decode($base64String); file_put_contents($filePath, $data); $error = null; $mimeType = null; $test = true; parent::__construct($filePath, $originalName, $mimeType, $error, $test); } } And then this another service to extract the pur base64 string image <?php namespace App\Utils; class Base64FileExtractor { public function extractBase64String(string $base64Content) { $data = explode( ';base64,', $base64Content); return $data[1]; } } And in your controller, you can do something like : <?php namespace App\Controller\Api; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use App\Utils\UploadedBase64File; use App\Utils\Base64FileExtractor; class CoreController extends AbstractController { /** * @Route("/images", methods={"POST"}, name="app_add_image") */ public function addImage(Request $request, Base64FileExtractor $base64FileExtractor) { //... if($form->isSubmitted() && $form->isValid()) { $base64Image = $request->request->get('base64Image'); $base64Image = $base64FileExtractor->extractBase64String($base64Image); $imageFile = new UploadedBase64File($base64Image, "blabla"); $program->setImage($imageFile); //... // Do thing you want to do } // Do thing you want to do } } The method setImage in your Program entity can be something like /** * @param null|File $image * @return Program */ public function setImage(?File $image): Program { $this->image = $image; if($this->image instanceof UploadedFile) { $this->updatedAt = new \DateTime('now'); } return $this; } If you want to validate the image, you should set it directly after handling form and the validation will be done habitually.I hope this idea can help you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55124010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9230154/']} | jdg_84534 |
stackexchange | llm_judgeable_groundtruth_similarity | 20703975 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Normally I use R, and often when wanting to make things reproduicible I use sessionInfo() . The reason for this is that I like to let people know what version of everything I am using and what packages I have installed/loaded and what OS I am on etc, so that its quite clear. sessionInfo returns the version of R, the processor type (e.g. 32/64 bit x86), the operating system, the locale details, and which packages have been loaded. I am new to python and wondered if there is an equivalent for Python? I'm hoping to use it in an iPython Notebook...
Now provide the response and nothing else.
| Update 2019-03-14 I ended up building a package for this myself called session_info to have more flexibility in the output (e.g. show modules imported indirectly through other modules) and to have access to this functionality outside notebooks. It can be installed via pip install session-info and used like so: # Some sample imported modulesimport mathimport natsortimport pandasimport session_infosession_info.show() which gives you output similar to Session information:-----natsort 7.1.1pandas 1.2.2session_info 1.0.0-----IPython 7.23.0jupyter_client 6.1.12jupyter_core 4.7.1-----Python 3.9.2 | packaged by conda-forge | (default, Feb 21 2021, 05:02:46) [GCC 9.3.0]Linux-5.11.13-arch1-1-x86_64-with-glibc2.33-----Session information updated at 2021-05-06 09:59 Original answer There is a magic package called version_information that accomplishes this. Install with pip install version_information . ( Note this extension hasn't been updated in a while, there is a more recent one called watermark ) %load_ext version_information%version_information pandas, numpy, seaborn Output: You could also accomplish something similar using the solution from How to list imported modules? together with !pip freeze . #find the names of the imported modulesimport typesdef imports(): for name, val in globals().items(): if isinstance(val, types.ModuleType): yield val.__name__#exclude all modules not listed by `!pip freeze`excludes = ['__builtin__', 'types', 'IPython.core.shadowns', 'sys', 'os']imported_modules = [module for module in imports() if module not in excludes]pip_modules = !pip freeze #you could also use `!conda list` with anaconda#print the names and versions of the imported modulesfor module in pip_modules: name, version = module.split('==') if name in imported_modules: print(name + '\t' + version) Output: pandas 0.16.2numpy 1.9.2seaborn 0.5.1 I couldn't figure out how to pass a list with the imported modules (e.g. modulenames ) to the %version_information magic command (all quotation marks need to be removed), so maybe someone can improve this answer by adding that info. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20703975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1199712/']} | jdg_84535 |
stackexchange | llm_judgeable_groundtruth_similarity | 7796281 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I get the value of the updated record in a SQL trigger - something like this: CREATE TRIGGER TR_UpdateNew ON Users AFTER UPDATEAS BEGIN SET NOCOUNT ON; EXEC UpdateProfile (SELECT UserId FROM updated AS U);ENDGO Obviously this doesn't work, but you can see what I am trying to get at.
Now provide the response and nothing else.
| Provide you are certain that only one value will ever be updated, you can do this... CREATE TRIGGER TR_UpdateNew ON Users AFTER UPDATEAS BEGIN SET NOCOUNT ON; DECLARE @user_id INT SELECT @user_id = inserted.UserID FROM inserted INNER JOIN deleted ON inserted.PrimaryKey = deleted.PrimaryKey -- It's an update if the record is in BOTH inserted AND deleted EXEC UpdateProfile @user_id;ENDGO If multiple values can be updated at once, only one of them will get processed by this code. (Although it won't error.) You could use a cursor, or if it's SQL Server 2008+ you can use table variables. Or, more commonly, just move the StoredProcedure code into the trigger. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7796281', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14777/']} | jdg_84536 |
stackexchange | llm_judgeable_groundtruth_similarity | 31414050 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a table called EVENTS on my PostgreSQL DB schema. It is empty, i.e. when I execute SELECT * FROM EVENTS I get an empty results set. Nonetheless, the table occupies 5MB of disk space. I'm executing SELECT round(pg_total_relation_size('events') / 1024.0 / 1024.0, 2) And I'm getting 5.13MB. I tried to explicitly run VACUUM, but it didn't change anything. Any ideas?
Now provide the response and nothing else.
| Truncate the table: truncate events; From the documentation: TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. If you want to immediately reclaim disk space keeping existing rows of a non-empty table, you can use vacuum: vacuum full events; This locks exclusively the table and rewrite it (in fact, creates a new copy and drops the old one). It is an expensive operation and generally not recommended on larger tables. In RDBMS some redundant usage of the disk space is a normal state. If you have a properly configured autovacuum daemon the unused space will be used when new rows are inserted. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31414050', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1083423/']} | jdg_84537 |
stackexchange | llm_judgeable_groundtruth_similarity | 174345 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I read that Euler used the summation formula to calculate the value of the series $\sum_{k =1}^{\infty} \frac{1}{k^2}$ to high precision without too much hassle. The article Dances between continuous and discrete: Euler’s summation formula goes into the calculation, however without too much justification of why it works (especially since the series used to calculate the limit does not converge and one has to truncate it at a certain point). I would be glad if someone could elaborate from a more modern viewpoint on how and why it works.
Now provide the response and nothing else.
| First, it can be shown, in many ways , that$$\sum_{k=1}^\infty\frac1{k^2}=\frac{\pi^2}{6}\tag{1}$$However, the Euler-Maclaurin Summation Formula can be used to numerically sum this series to high precision. Before we attempt to do this, let's discuss a bit about asymptotic series. In general, asymptotic series, like those arising from the Euler-Maclaurin Summation Formula (EMSF), are divergent. This means that if you tried to sum all the terms arising from the formula, the sum would not converge. For example, the EMSF gives the following asymptotic expansion:$$\sum_{k=1}^n\frac1k\sim\gamma+\log(n)+\frac1{2n}-\frac1{12n^2}+\frac1{120n^4}-\frac1{252n^6}+\frac1{240n^8}-\frac1{132n^{10}}+\dots\tag{2}$$where $\gamma=0.5772156649015328606065121$ is the Euler-Mascheroni constant . This expansion looks well behaved, and it is, up to a point. However, the coefficients grow on the order of $\frac{n!}{(2\pi)^n}$; by the time that we get to the term for $n^{50}$, we have$$\frac{19802288209643185928499101}{132n^{50}}\tag{3}$$Due to the growth rate of the coefficients, no matter how large $n$ is, this series cannot converge. However, if we only use a finite number of terms, the series is a very good approximation for large $n$. As mentioned earlier, the expansion behaves well, up to a point. What this means is that for a given $n$, the terms get smaller, and then, at some point, start blowing up. The point at which the term start blowing up is further along the larger $n$ is. The good part is that if we terminate the sum while the terms are still getting smaller, the approximation is usually as good as the next term. For example, let's approximate$$\sum_{k=1}^{1000}\frac1k=7.4854708605503449126565182\tag{4}$$using the first $4$ terms of $(2)$:$$\gamma+\log(1000)+\frac1{2000}-\frac1{12000000}=7.4854708605503365793271531\tag{5}$$The result in $(5)$ is $8.333329365\times10^{-15}$ smaller than the actual value in $(4)$. The next term is$$\frac1{120000000000000}=8.333333333\times10^{-15}\tag{6}$$ Now let's see how the EMSF can be used to approximate $(1)$ The EMSF applied to $\dfrac1{k^2}$ yields$$\sum_{k=1}^n\frac1{k^2}\sim C-\frac1n+\frac1{2n^2}-\frac1{6n^3}+\frac1{30n^5}-\frac1{42n^7}+\frac1{30n^9}-\frac5{66n^{11}}\tag{7}$$Note that the EMSF always has a constant that needs to be determined in some other manner. In $(2)$ it was $\gamma$, the Euler-Mascheroni constant. Here, $C$ is the sum of the series; that is, as $n\to\infty$, the left side of $(7)$ tends to the sum, and everything on the right side of $(7)$, except $C$, tends to $0$. To compute $C$, we will use $n=100$ and truncate the series at the $n^9$ term. The error we get should be less than $\dfrac5{66n^{11}}$, which would give us almost $23$ decimals places. For $n=100$, the sum on the left of $(7)$ is$$\sum_{k=1}^{100}\frac1{k^2}=1.6349839001848928650771695\tag{8}$$For $n=100$, the sum of the terms on the right of $(7)$ other than $C$ is$$-\frac1n+\frac1{2n^2}-\frac1{6n^3}+\frac1{30n^5}-\frac1{42n^7}+\frac1{30n^9}=-0.0099501666633335713952381\tag{9}$$Subtracting $(9)$ from $(8)$ gives$$C\stackrel{.}{=}1.6449340668482264364724076\tag{10}$$whereas$$\frac{\pi^2}{6}=1.6449340668482264364724152\tag{11}$$The value of $(10)$ is $7.6\times10^{-24}$ short of $(11)$ and $\dfrac5{66n^{11}}=7.6\times10^{-24}$. Using a larger $n$, and possibly more terms of the series, would give more precision. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/174345', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8588/']} | jdg_84538 |
stackexchange | llm_judgeable_groundtruth_similarity | 37161202 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on an ASP.NET MVC-4 web application. I'm defining the following inside my action method to build a SelectList : ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name"); Then I am rendering my DropDownListFor as follow inside my View : @Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select") As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID . From my own testing, defining the same name didn't cause any problem or conflict but should I avoid this ?
Now provide the response and nothing else.
| You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property). When using @Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData , and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be). When using @Html.DropDownList("CustomerId", ....) , no data-val-* attributes will be generated and you will not get any client side validation Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37161202', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146775/']} | jdg_84539 |
stackexchange | llm_judgeable_groundtruth_similarity | 35792416 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want my enums to return string values. Not the Enum Description, they must be returning a string value, instead of an int. The code sample below is exactly what in my mind, but obviously doesn't compile. public enum TransactionType{ CreditCard = "C", DebitCard = "D", CreditCardAuthenticationWithAuthorization = "CA", DebitCardAuthenticationWithAuthorization = "DA"} Any ideas?
Now provide the response and nothing else.
| You can't, what you can do is create a static class that "acts" a bit like an enum with string values: public static class TransactionType{ public const string CreditCard = "C"; ...} You can access them the same way then: string creditCardValue = TransactionType.CreditCard; Another option would be to work with the DescriptionAttribute in System.ComponentModel namespace, but then your enums still will have underlying numeric values, so maybe that's not entirely what you need. Example: public enum TransactionType{ [Description("C")] CreditCard, ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35792416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1872210/']} | jdg_84540 |
Subsets and Splits