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
27702002
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 fighting with NSDocument in a document based Storyboard based Cocoa Application (Objective C). Can anybody tell me how i can access the document in the NSViewController subclass? I've tried to access it the following way - but the document is null: [self.view.window.windowController document]; Thanks for your help! Best regardsMartin Now provide the response and nothing else.
I was just wrestling with this myself. I started with the standard Yosemite template and was trying to use [self.view.window.windowController document] in -viewDidLoad . At that point, self.view.window is nil , so there's no way to get to the document . The trick is to wait until -viewWillAppear . By the time it is called, self.view.window is populated and the document is available. Sequence: -makeWindowControllers invokes -self addWindowController: with the storyboard's - instantiateControllerWithIdentifier: result. -addWindowController: triggers a call to the VC's -viewDidLoad before returning. Then, finally, -viewWillAppear is called (and the document is available).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27702002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384011/']}
jdg_375841
stackexchange
llm_judgeable_groundtruth_similarity
38813906
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 Objective-C it was sometimes useful to use static string constants to define alternate API keys (for example to differentiate between RELEASE and DEBUG keys for analytics packages, like MixPanel, Flurry or Crashlytics): #if DEBUGstatic NSString *const API_KEY = @"KEY_A";#elsestatic NSString *const API_KEY = @"KEY_B";#endif and then... [Analytics startSession:API_KEY]; How does this translate to Swift, since the Swift compiler no longer uses a preprocessor? Now provide the response and nothing else.
Apple included full support for Swift preprocessor flags as of Xcode 8 , so it's no longer necessary to set these values in "Other Swift Flags". The new setting is called "Active Compilation Conditions", which provides top-level support for the Swift equivalent of preprocessor flags. You use it in exactly the same way as you would "Other Swift Flags", except there's no need to prepend the value with a "-D" (so it's just a little cleaner). From the Xcode 8 release notes : Active Compilation Conditions is a new build setting for passing conditional compilation flags to the Swift compiler. Each element of the value of this setting passes to swiftc prefixed with -D , in the same way that elements of Preprocessor Macros pass to clang with the same prefix. (22457329) You use the above setting like so: #if DEBUG let accessToken = "DebugAccessToken"#else let accessToken = "ProductionAccessToken"#endif
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/38813906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/346098/']}
jdg_375842
stackexchange
llm_judgeable_groundtruth_similarity
439674
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: In light of memtest86+ not working with UEFI , is there an open source alternative or something I can use from grub to test memory? Now provide the response and nothing else.
Yes, there is, and it is now Memtest86+ v6 itself. This is a new version of Memtest86+, based on PCMemTest , which is a rewrite of Memtest86+ which can be booted from UEFI. Its authors still label it as not ready for production, but it does work in many configurations. Binaries of Memtest86+ v6 are available on memtest.org . Alternatively, the Linux kernel itself contains a memory test tool: the memtest option will run a memory check with up to 17 patterns (currently). If you add memtest to your kernel boot parameters, it will run all tests at boot, and reserve any failing addresses so that they’re not used. If you want fewer tests, you can specify the number of patterns ( memtest=8 for example). This isn’t as extensive as Memtest86+’s tests, but it still gives pretty good results. Some distribution kernels don’t include this feature; you can check whether it’s available by looking for CONFIG_MEMTEST in your kernel configuration (try /boot/config-$(uname -r) ). The kernel won’t complain if you specify memtest but it doesn’t support it; when it does run, you should see output like [ 0.000000] early_memtest: # of tests: 17[ 0.000000] 0x0000000000010000 - 0x0000000000099000 pattern 4c494e5558726c7a[ 0.000000] 0x0000000000100000 - 0x0000000003800000 pattern 4c494e5558726c7a[ 0.000000] 0x000000000500d000 - 0x0000000007fe0000 pattern 4c494e5558726c7a[ 0.000000] 0x0000000000010000 - 0x0000000000099000 pattern eeeeeeeeeeeeeeee[ 0.000000] 0x0000000000100000 - 0x0000000003800000 pattern eeeeeeeeeeeeeeee[ 0.000000] 0x000000000500d000 - 0x0000000007fe0000 pattern eeeeeeeeeeeeeeee[ 0.000000] 0x0000000000010000 - 0x0000000000099000 pattern dddddddddddddddd[ 0.000000] 0x0000000000100000 - 0x0000000003800000 pattern dddddddddddddddd[ 0.000000] 0x000000000500d000 - 0x0000000007fe0000 pattern dddddddddddddddd[ 0.000000] 0x0000000000010000 - 0x0000000000099000 pattern bbbbbbbbbbbbbbbb[ 0.000000] 0x0000000000100000 - 0x0000000003800000 pattern bbbbbbbbbbbbbbbb... while the kernel boots (or in its boot logs, later). You can use QEMU to get a feel for this: qemu-system-x86_64 -kernel /boot/vmlinuz-$(uname -r) -append "memtest console=ttyS0" -nographic (or whichever qemu-system-... is appropriate for your architecture), and look for “early_memtest”. To exit QEMU after the kernel panics, press Ctrl a , c , q , Enter .
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/439674', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3285/']}
jdg_375843
stackexchange
llm_judgeable_groundtruth_similarity
7295835
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 very confuse with this partial view. I want to load a partial view inside my main view. Here is the simple example. I am loading Index.cshtml of the Homecontroller Index action as a main page. In index.cshtml, I am creating a link via @Html.ActionLink("load partial view","Load","Home") in HomeController I am adding a new Action called public PartialViewResult Load(){ return PartialView("_LoadView");} in _LoadView.cshmtl I am just having a <div> Welcome !!</div> BUT, when run the project, index.cshtml renders first and shows me the link "Load Partial View". when I click on that it goes to new page instade of rendering the welcome message from _LoadView.cshtml into the index.cshtml. What can be wrong? Note: I don't want to load page through AJAX or don't want to use Ajax.ActionLink . Now provide the response and nothing else.
If you want to load the partial view directly inside the main view you could use the Html.Action helper: @Html.Action("Load", "Home") or if you don't want to go through the Load action use the HtmlPartialAsync helper: @await Html.PartialAsync("_LoadView") If you want to use Ajax.ActionLink , replace your Html.ActionLink with: @Ajax.ActionLink( "load partial view", "Load", "Home", new AjaxOptions { UpdateTargetId = "result" }) and of course you need to include a holder in your page where the partial will be displayed: <div id="result"></div> Also don't forget to include: <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script> in your main view in order to enable Ajax.* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default): <add key="UnobtrusiveJavaScriptEnabled" value="true" />
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7295835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/927002/']}
jdg_375844
stackexchange
llm_judgeable_groundtruth_similarity
7337582
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to implement, in Scala, the following Haskell function (from Learn You a Haskell...) so that it works with Int, Double, etc. doubleUs x y = x * 2 + y * 2 Note that this is similar to Scala: How to define "generic" function parameters? Here's my attempt and error. Can someone explain what's happening and offer a solution. Thanks. scala> def doubleUs[A](x:A,y:A)(implicit numeric: Numeric[A]): A = numeric.plus(numeric.times(x,2),numeric.times(y,2)) <console>:34: error: type mismatch; found : Int(2) required: A def doubleUs[A](x:A,y:A)(implicit numeric: Numeric[A]): A = numeric.plus(numeric.times(x,2),numeric.times(y,2)) Now provide the response and nothing else.
You are using the Int literal 2 but scala is expecting the Numeric type A .The Scala Numeric API has a utility function- def fromInt(x:Int): T . This is what you want to use, so replace your usage of 2 with numeric.fromInt(2) def doubleUs[A](x:A,y:A)(implicit numeric: Numeric[A]): A = numeric.plus (numeric.times (x, numeric.fromInt (2)), numeric.times (y, numeric.fromInt (2))) Also, since a Numeric instance defines an implicit conversion to an Ops, you can import numeric._ and then say x * fromInt(2) + y * fromInt(2) .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7337582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/733672/']}
jdg_375845
stackexchange
llm_judgeable_groundtruth_similarity
56359586
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I recently upgraded my app from Angular 7 to Angular 8 and I'm having issues with the node version of the cloud build VM as Angular 8 requires node version 10.9 or greater as shown below: How can I upgrade the node version of the Google cloud VM so I won't get this error again? Thanks. Now provide the response and nothing else.
Ok, so after hours of Googling around it turns out Google cloud platform offers a registry of different npm cloud builders for use with Google cloud build. I could have solved my issue by creating my own docker image but I wanted to avoid this in favour of the default cloud builders docker image. I changed my cloudbuild.yaml file to include the following builder 'gcr.io/cloud-builders/npm:node-10.10.0' instead of 'gcr.io/cloud-builders/npm' this then updated the node version to node 10.10.0 and just like magic Angular 8 can now be built by google cloud build! Specific node versions from the cloud builders repository can be found here: https://console.cloud.google.com/gcr/images/cloud-builders/GLOBAL/npm
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56359586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7727374/']}
jdg_375846
stackexchange
llm_judgeable_groundtruth_similarity
12957492
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 write a python wrapper for some C++ code that make use of OpenCV but I'm having difficulties returning the result, which is a OpenCV C++ Mat object, to the python interpreter. I've looked at OpenCV's source and found the file cv2.cpp which has conversions functions to perform conversions to and fro between PyObject* and OpenCV's Mat. I made use of those conversions functions but got a segmentation fault when I tried to use them. I basically need some suggestions/sample code/online references on how to interface python and C++ code that make use of OpenCV, specifically with the ability to return OpenCV's C++ Mat to the python interpreter or perhaps suggestions on how/where to start investigating the cause of the segmentation fault. Currently I'm using Boost Python to wrap the code. Thanks in advance to any replies. The relevant code: // This is the function that is giving the segmentation fault.PyObject* ABC::doSomething(PyObject* image){ Mat m; pyopencv_to(image, m); // This line gives segmentation fault. // Some code to create cppObj from CPP library that uses OpenCV cv::Mat processedImage = cppObj->align(m); return pyopencv_from(processedImage);} The conversion functions taken from OpenCV's source follows. The conversion code gives segmentation fault at the commented line with "if (!PyArray_Check(o)) ...". static int pyopencv_to(const PyObject* o, Mat& m, const char* name = "<unknown>", bool allowND=true){ if(!o || o == Py_None) { if( !m.data ) m.allocator = &g_numpyAllocator; return true; } if( !PyArray_Check(o) ) // Segmentation fault inside PyArray_Check(o) { failmsg("%s is not a numpy array", name); return false; } int typenum = PyArray_TYPE(o); int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S : typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S : typenum == NPY_INT || typenum == NPY_LONG ? CV_32S : typenum == NPY_FLOAT ? CV_32F : typenum == NPY_DOUBLE ? CV_64F : -1; if( type < 0 ) { failmsg("%s data type = %d is not supported", name, typenum); return false; } int ndims = PyArray_NDIM(o); if(ndims >= CV_MAX_DIM) { failmsg("%s dimensionality (=%d) is too high", name, ndims); return false; } int size[CV_MAX_DIM+1]; size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type); const npy_intp* _sizes = PyArray_DIMS(o); const npy_intp* _strides = PyArray_STRIDES(o); bool transposed = false; for(int i = 0; i < ndims; i++) { size[i] = (int)_sizes[i]; step[i] = (size_t)_strides[i]; } if( ndims == 0 || step[ndims-1] > elemsize ) { size[ndims] = 1; step[ndims] = elemsize; ndims++; } if( ndims >= 2 && step[0] < step[1] ) { std::swap(size[0], size[1]); std::swap(step[0], step[1]); transposed = true; } if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] ) { ndims--; type |= CV_MAKETYPE(0, size[2]); } if( ndims > 2 && !allowND ) { failmsg("%s has more than 2 dimensions", name); return false; } m = Mat(ndims, size, type, PyArray_DATA(o), step); if( m.data ) { m.refcount = refcountFromPyObject(o); m.addref(); // protect the original numpy array from deallocation // (since Mat destructor will decrement the reference counter) }; m.allocator = &g_numpyAllocator; if( transposed ) { Mat tmp; tmp.allocator = &g_numpyAllocator; transpose(m, tmp); m = tmp; } return true;}static PyObject* pyopencv_from(const Mat& m){ if( !m.data ) Py_RETURN_NONE; Mat temp, *p = (Mat*)&m; if(!p->refcount || p->allocator != &g_numpyAllocator) { temp.allocator = &g_numpyAllocator; m.copyTo(temp); p = &temp; } p->addref(); return pyObjectFromRefcount(p->refcount);} My python test program: import pysomemodule # My python wrapped library.import cv2def main(): myobj = pysomemodule.ABC("faces.train") # Create python object. This works. image = cv2.imread('61.jpg') processedImage = myobj.doSomething(image) cv2.imshow("test", processedImage) cv2.waitKey()if __name__ == "__main__": main() Now provide the response and nothing else.
I solved the problem so I thought I'll share it here with others who may have the same problem. Basically, to get rid of the segmentation fault, I need to call numpy's import_array() function. The "high level" view for running C++ code from python is this: Suppose you have a function foo(arg) in python that is a binding for some C++ function. When you call foo(myObj) , there must be some code to convert the python object "myObj" to a form your C++ code can act on. This code is generally semi-automatically created using tools such as SWIG or Boost::Python. (I use Boost::Python in the examples below.) Now, foo(arg) is a python binding for some C++ function. This C++ function will receive a generic PyObject pointer as an argument. You will need to have C++ code to convert this PyObject pointer to an "equivalent" C++ object. In my case, my python code passes a OpenCV numpy array for a OpenCV image as an argument to the function. The "equivalent" form in C++ is a OpenCV C++ Mat object. OpenCV provides some code in cv2.cpp (reproduced below) to convert the PyObject pointer (representing the numpy array) to a C++ Mat. Simpler data types such as int and string do not need the user to write these conversion functions as they are automatically converted by Boost::Python. After the PyObject pointer is converted to a suitable C++ form, C++ code can act on it. When data has to be returned from C++ to python, an analogous situation arises where C++ code is needed to convert the C++ representation of the data to some form of PyObject . Boost::Python will take care of the rest in converting the PyObject to a corresponding python form. When foo(arg) returns the result in python, it is in a form usable by python. That's it. The code below shows how to wrap a C++ class "ABC" and expose its method "doSomething" that takes in a numpy array (for an image) from python, convert it to OpenCV's C++ Mat, do some processing, convert the result to PyObject *, and return it to the python interpreter. You can expose as many functions/method you wish (see comments in the code below). abc.hpp: #ifndef ABC_HPP#define ABC_HPP#include <Python.h>#include <string>class ABC{ // Other declarations ABC(); ABC(const std::string& someConfigFile); virtual ~ABC(); PyObject* doSomething(PyObject* image); // We want our python code to be able to call this function to do some processing using OpenCV and return the result. // Other declarations};#endif abc.cpp: #include "abc.hpp"#include "my_cpp_library.h" // This is what we want to make available in python. It uses OpenCV to perform some processing.#include "numpy/ndarrayobject.h"#include "opencv2/core/core.hpp"// The following conversion functions are taken from OpenCV's cv2.cpp file inside modules/python/src2 folder.static PyObject* opencv_error = 0;static int failmsg(const char *fmt, ...){ char str[1000]; va_list ap; va_start(ap, fmt); vsnprintf(str, sizeof(str), fmt, ap); va_end(ap); PyErr_SetString(PyExc_TypeError, str); return 0;}class PyAllowThreads{public: PyAllowThreads() : _state(PyEval_SaveThread()) {} ~PyAllowThreads() { PyEval_RestoreThread(_state); }private: PyThreadState* _state;};class PyEnsureGIL{public: PyEnsureGIL() : _state(PyGILState_Ensure()) {} ~PyEnsureGIL() { PyGILState_Release(_state); }private: PyGILState_STATE _state;};#define ERRWRAP2(expr) \try \{ \ PyAllowThreads allowThreads; \ expr; \} \catch (const cv::Exception &e) \{ \ PyErr_SetString(opencv_error, e.what()); \ return 0; \}using namespace cv;static PyObject* failmsgp(const char *fmt, ...){ char str[1000]; va_list ap; va_start(ap, fmt); vsnprintf(str, sizeof(str), fmt, ap); va_end(ap); PyErr_SetString(PyExc_TypeError, str); return 0;}static size_t REFCOUNT_OFFSET = (size_t)&(((PyObject*)0)->ob_refcnt) + (0x12345678 != *(const size_t*)"\x78\x56\x34\x12\0\0\0\0\0")*sizeof(int);static inline PyObject* pyObjectFromRefcount(const int* refcount){ return (PyObject*)((size_t)refcount - REFCOUNT_OFFSET);}static inline int* refcountFromPyObject(const PyObject* obj){ return (int*)((size_t)obj + REFCOUNT_OFFSET);}class NumpyAllocator : public MatAllocator{public: NumpyAllocator() {} ~NumpyAllocator() {} void allocate(int dims, const int* sizes, int type, int*& refcount, uchar*& datastart, uchar*& data, size_t* step) { PyEnsureGIL gil; int depth = CV_MAT_DEPTH(type); int cn = CV_MAT_CN(type); const int f = (int)(sizeof(size_t)/8); int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE : depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT : depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT : depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f^1)*NPY_UINT; int i; npy_intp _sizes[CV_MAX_DIM+1]; for( i = 0; i < dims; i++ ) { _sizes[i] = sizes[i]; } if( cn > 1 ) { /*if( _sizes[dims-1] == 1 ) _sizes[dims-1] = cn; else*/ _sizes[dims++] = cn; } PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum); if(!o) { CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims)); } refcount = refcountFromPyObject(o); npy_intp* _strides = PyArray_STRIDES(o); for( i = 0; i < dims - (cn > 1); i++ ) step[i] = (size_t)_strides[i]; datastart = data = (uchar*)PyArray_DATA(o); } void deallocate(int* refcount, uchar*, uchar*) { PyEnsureGIL gil; if( !refcount ) return; PyObject* o = pyObjectFromRefcount(refcount); Py_INCREF(o); Py_DECREF(o); }};NumpyAllocator g_numpyAllocator;enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 };static int pyopencv_to(const PyObject* o, Mat& m, const char* name = "<unknown>", bool allowND=true){ //NumpyAllocator g_numpyAllocator; if(!o || o == Py_None) { if( !m.data ) m.allocator = &g_numpyAllocator; return true; } if( !PyArray_Check(o) ) { failmsg("%s is not a numpy array", name); return false; } int typenum = PyArray_TYPE(o); int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S : typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S : typenum == NPY_INT || typenum == NPY_LONG ? CV_32S : typenum == NPY_FLOAT ? CV_32F : typenum == NPY_DOUBLE ? CV_64F : -1; if( type < 0 ) { failmsg("%s data type = %d is not supported", name, typenum); return false; } int ndims = PyArray_NDIM(o); if(ndims >= CV_MAX_DIM) { failmsg("%s dimensionality (=%d) is too high", name, ndims); return false; } int size[CV_MAX_DIM+1]; size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type); const npy_intp* _sizes = PyArray_DIMS(o); const npy_intp* _strides = PyArray_STRIDES(o); bool transposed = false; for(int i = 0; i < ndims; i++) { size[i] = (int)_sizes[i]; step[i] = (size_t)_strides[i]; } if( ndims == 0 || step[ndims-1] > elemsize ) { size[ndims] = 1; step[ndims] = elemsize; ndims++; } if( ndims >= 2 && step[0] < step[1] ) { std::swap(size[0], size[1]); std::swap(step[0], step[1]); transposed = true; } if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] ) { ndims--; type |= CV_MAKETYPE(0, size[2]); } if( ndims > 2 && !allowND ) { failmsg("%s has more than 2 dimensions", name); return false; } m = Mat(ndims, size, type, PyArray_DATA(o), step); if( m.data ) { m.refcount = refcountFromPyObject(o); m.addref(); // protect the original numpy array from deallocation // (since Mat destructor will decrement the reference counter) }; m.allocator = &g_numpyAllocator; if( transposed ) { Mat tmp; tmp.allocator = &g_numpyAllocator; transpose(m, tmp); m = tmp; } return true;}static PyObject* pyopencv_from(const Mat& m){ if( !m.data ) Py_RETURN_NONE; Mat temp, *p = (Mat*)&m; if(!p->refcount || p->allocator != &g_numpyAllocator) { temp.allocator = &g_numpyAllocator; m.copyTo(temp); p = &temp; } p->addref(); return pyObjectFromRefcount(p->refcount);}ABC::ABC() {}ABC::~ABC() {}// Note the import_array() from NumPy must be called else you will experience segmentation faults.ABC::ABC(const std::string &someConfigFile){ // Initialization code. Possibly store someConfigFile etc. import_array(); // This is a function from NumPy that MUST be called. // Do other stuff}// The conversions functions above are taken from OpenCV. The following function is // what we define to access the C++ code we are interested in.PyObject* ABC::doSomething(PyObject* image){ cv::Mat cvImage; pyopencv_to(image, cvImage); // From OpenCV's source MyCPPClass obj; // Some object from the C++ library. cv::Mat processedImage = obj.process(cvImage); return pyopencv_from(processedImage); // From OpenCV's source} The code to use Boost Python to create the python module. I took this and the following Makefile from http://jayrambhia.wordpress.com/tag/boost/ : pysomemodule.cpp: #include <string> #include<boost/python.hpp>#include "abc.hpp"using namespace boost::python;BOOST_PYTHON_MODULE(pysomemodule){ class_<ABC>("ABC", init<const std::string &>()) .def(init<const std::string &>()) .def("doSomething", &ABC::doSomething) // doSomething is the method in class ABC you wish to expose. One line for each method (or function depending on how you structure your code). Note: You don't have to expose everything in the library, just the ones you wish to make available to python. ;} And finally, the Makefile (successfully compiled on Ubuntu but should work elsewhere possibly with minimal adjustments). PYTHON_VERSION = 2.7PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)# location of the Boost Python include files and libraryBOOST_INC = /usr/local/include/boostBOOST_LIB = /usr/local/libOPENCV_LIB = `pkg-config --libs opencv`OPENCV_CFLAGS = `pkg-config --cflags opencv`MY_CPP_LIB = lib_my_cpp_library.soTARGET = pysomemoduleSRC = pysomemodule.cpp abc.cppOBJ = pysomemodule.o abc.o$(TARGET).so: $(OBJ) g++ -shared $(OBJ) -L$(BOOST_LIB) -lboost_python -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so $(OPENCV_LIB) $(MY_CPP_LIB)$(OBJ): $(SRC) g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) $(OPENCV_CFLAGS) -fPIC -c $(SRC)clean: rm -f $(OBJ) rm -f $(TARGET).so After you have successfully compiled the library, you should have a file "pysomemodule.so" in the directory. Put this lib file in a place accessible by your python interpreter. You can then import this module and create an instance of the class "ABC" above as follows: import pysomemodulefoo = pysomemodule.ABC("config.txt") # This will create an instance of ABC Now, given an OpenCV numpy array image, we can call the C++ function using: processedImage = foo.doSomething(image) # Where the argument "image" is a OpenCV numpy image. Note that you will need Boost Python, Numpy dev, as well as Python dev library to create the bindings. The NumPy docs in the following two links are particularly useful in helping one understand the methods that were used in the conversion code and why import_array() must be called. In particular, the official numpy doc is helpful in making sense of OpenCV's python binding code. http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html http://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html Hope this helps.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12957492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/540259/']}
jdg_375847
stackexchange
llm_judgeable_groundtruth_similarity
17829
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 was reading the question here with some interest, because I am in the end stages of construction on a project that involves 16 solid-state relays. I'm using non-zero crossing type, because that's what I happened to find on a schematic by someone who completed a very similar project to mine. The datasheet for my SSRs mentions that a snubber circuit is recommended, especially when driving inductive loads (which I am, since my loads are AC solenoids). I thought I understood that this is to give somewhere for the energy stored in the inductor somewhere to go if the SSR switches off right as the voltage peaks. When I read about ZC-type SSRs, I thought to myself, "self, that would eliminate the need for a snubber circuit, right?" I then dug up a datasheet for the ZC version of the SSR I'm using, and I found this: Particular attention needs to be paid when utilizing SSRs that incorporate zero crossing circuitry. If the phase difference between the voltage and the current at the output pins is large enough, zero crossing type SSRs cannot be used. As well, the snubber circuit continues to be recommended for the ZC-type SSR. The phrase "phase difference between the voltage and the current" doesn't make sense to me. What does that mean? Now provide the response and nothing else.
An old question, but it's a cool topic for beginners to wrap their minds around, so I'll answer it. To answer the last question first, remember that voltage appears across a load, while current is measured through the load. It may be easier to visualize the phase lag concept if you think of a capacitor rather than an inductor. You're probably familiar with the fact that when you charge a large capacitor, it looks like a short circuit at first. At the instant of connection, current is flowing through the cap, but no voltage appears across it because, hey, it's a short circuit, right? As the cap charges up, the voltage across it rises and the current through it falls. This is all that's meant when people say that "the current leads the voltage" in a capacitor. With an inductor, we say the voltage leads the current because at the instant of connection the inductor looks like an open circuit. A perfect inductor connected to a voltage source at time=0 will have the whole supply voltage across it, with no current flowing through it. During the 'charging' process the inductor stores energy in its surrounding magnetic field, which cannot happen instantaneously any more than a capacitor can be charged instantaneously. So the voltage "leads" the current in this case. What's interesting about an inductor is what happens when the source is disconnected. A capacitor will just sit there at the same voltage, slowly losing its charge over a long period of time if there is no load across it. But with an inductor, the magnetic field collapses as soon as the power supply is removed, and this happens quickly. A recently-disconnected inductor will try to maintain the flow of current through the circuit rather than the voltage across itself.... but wait, there is no circuit anymore, because we just opened it. A perfect inductor would generate an infinite voltage in an attempt to keep the current flowing. Even an imperfect one can turn a few volts into several hundred for a short period of time after disconnection. This is why a zero-crossing switch is not the same thing as a snubber. The snubber's job is to give the inductor a load it can drive when the source is removed altogether -- usually a capacitive one since you don't want it drawing current the rest of the time. It keeps the voltage from rising to levels that could hose semiconductors, burn relay contacts with arcing, or otherwise cause trouble.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/17829', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3240/']}
jdg_375848
stackexchange
llm_judgeable_groundtruth_similarity
21404
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: Bug introduced in 9.0 and fixed in 9.0.1 When I need to plot a 'large' graph with CommunityGraphPlot the output is always sized at the Mathematica default value. The Graph object itself can be resized with ImageSize option. However that doesn't work with Mathematica 9.0.0. The only option is to enlarge the plot by clicking the image and pull it to the wanted size. Then you can export this graph to PDF and print it.Is there a alternative way? g = RandomGraph[{200, 300}, VertexLabels -> "Name",ImagePadding -> 20, ImageSize -> Scaled[0.5]] CommunityGraphPlot[g] UPDATE: I just found out that the CommunityGraphPlot generated can be double clicked and then you can freely drag the vertexes etc while keeping the connections! Can't do that with Graph object by default. Now provide the response and nothing else.
Among the answers linked by Mr. Wizard, there's also my label3D function. Looking at that, I think in your case it would work as a replacement for Text as well. In that answer, I set a HoldFirst attribute, but I think it's not that convenient here. So I would suggest executing the definition for label3D in the linked answer , followed by ClearAttributes[label3D, HoldFirst]imagewrapped = With[{Lx = 10, Ly = 10, Nx = 5, Ny = 5, r0 = 2, ftsz = 12}, Graphics3D[{Table[{Sphere[{ix Lx, iy Ly, 0}, r0]}, {ix, 1, Nx}, {iy, 1, Ny}], Glow[Red], Table[label3D[ Style[ix, ftsz, Red, Bold], {ix Lx, 0, 0}, {-5, 0, 0}, 0], {ix, 1, Nx}], Glow[Cyan], Table[ label3D[Style[iy, ftsz, Cyan, Bold], {0, iy Ly, 0}, {0, 5, 0}, 0], {iy, 1, Ny}]}, Boxed -> False, Lighting -> Automatic, ViewPoint -> {1, 1, 1}, ImageSize -> {Automatic, 100}, Method -> {"ShrinkWrap" -> True}]] This seems to be treated correctly by ShrinkWrap . To make the labels look as much like the Text labels, I gave them a Glow to prevent them to display with shading.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/21404', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/150/']}
jdg_375849
stackexchange
llm_judgeable_groundtruth_similarity
9328143
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 reading source code of xl2tpd , and face lots of problems when reading this code. For example I cannot find where the structure lac is defined. How do I find the definition of this structure? I have used ctags and vim to read this code, but failed to find the structure. I googled and could not find the structure. Is there any method that can make the code reading process more comfortable? That is, I can jump to definition of most variables, functions and structures? Now provide the response and nothing else.
try cscope with vim. follow steps below - 1) run cscope -R in xl2tpd directory . it will create file cscope.out 2) open file with vim where structure lac is used 3) use :cs f g <lac> . now it will show the files where lac is defined . 4) choose file.h . it contain the definition . if you are perticulerly interested in definition of struct lac it is below - struct lac{ struct lac *next; struct host *lns; /* LNS's we can connect to */ struct schedule_entry *rsched; int tun_rws; /* Receive window size (tunnel) */ int call_rws; /* Call rws */ int rxspeed; /* Tunnel rx speed */ int txspeed; /* Tunnel tx speed */ int active; /* Is this connection in active use? */ int hbit; /* Permit hidden AVP's? */ int lbit; /* Use the length field? */ int challenge; /* Challenge authenticate the peer? */ unsigned int localaddr; /* Local IP address */ unsigned int remoteaddr; /* Force remote address to this */ char authname[STRLEN]; /* Who we authenticate as */ char password[STRLEN]; /* Password to authenticate with */ char peername[STRLEN]; /* Force peer name to this */ char hostname[STRLEN]; /* Hostname to report */ char entname[STRLEN]; /* Name of this entry */ int authpeer; /* Authenticate our peer? */ int authself; /* Authenticate ourselves? */ int pap_require; /* Require PAP auth for PPP */ int chap_require; /* Require CHAP auth for PPP */ int pap_refuse; /* Refuse PAP authentication for us */ int chap_refuse; /* Refuse CHAP authentication for us */ int idle; /* Idle timeout in seconds */ int autodial; /* Try to dial immediately? */ int defaultroute; /* Use as default route? */ int redial; /* Redial if disconnected */ int rmax; /* Maximum # of consecutive redials */ int rtries; /* # of tries so far */ int rtimeout; /* Redial every this many # of seconds */ char pppoptfile[STRLEN]; /* File containing PPP options */ int debug; struct tunnel *t; /* Our tunnel */ struct call *c; /* Our call */};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9328143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257527/']}
jdg_375850
stackexchange
llm_judgeable_groundtruth_similarity
84015
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 have a list of 2 by 2 matrices and I want the list of their traces. I have been using Map[Tr,mylistofmatrices] But I wonder if there is a way to make Tr Listable so I can just call Tr[mylistofmatrices] Now provide the response and nothing else.
No, there isn't. There are several reasons for that: Tr operates on tensors of arbitrary rank, not just matrices Listable functions will automatically thread to the deepest level of lists, so if you set Tr to be Listable , it'll individually wrap each deepest element of a nested list, e.g. Tr[{{1,2},{3,4}}] would transform to {{Tr[1], Tr[2]}, {Tr[3], Tr[4]}} . Just use Map , which is unambiguous and takes just one extra character to type ... Tr /@ list vs Tr @ list .
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/84015', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/23255/']}
jdg_375851
stackexchange
llm_judgeable_groundtruth_similarity
39758449
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a list of numbers ranging from x to y that may contain NaN , how can I normalise between 0 and 1, ignoring the NaN values (they stay as NaN ). Typically I would use MinMaxScaler ( ref page ) from sklearn.preprocessing , but this cannot handle NaN and recommends imputing the values based on mean or median etc. it doesn't offer the option to ignore all the NaN values. Now provide the response and nothing else.
consider pd.Series s s = pd.Series(np.random.choice([3, 4, 5, 6, np.nan], 100))s.hist() Option 1 Min Max Scaling new = s.sub(s.min()).div((s.max() - s.min()))new.hist() NOT WHAT OP ASKED FOR I put these in because I wanted to Option 2 sigmoid sigmoid = lambda x: 1 / (1 + np.exp(-x))new = sigmoid(s.sub(s.mean()))new.hist() Option 3 tanh (hyperbolic tangent) new = np.tanh(s.sub(s.mean())).add(1).div(2)new.hist()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39758449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2308132/']}
jdg_375852
stackexchange
llm_judgeable_groundtruth_similarity
10374
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: First do we have anyway to even estimate the mass of the entire observable universe? And then is there any data that shows mass being gained or lost? Would we ever know if someone was playing with the til. Also I want to be clear that I am not talking about small masses on the outskirts of the "universe" or small discrepancies in measurement or anything of the sort. Note: I would like to add that maybe we should define the observable universe as NOW (x-date) so that we aren't calculating a moving target. Now provide the response and nothing else.
Yes, the mass of the observable Universe is always increasing. Matter Even if you're only referring the "ordinary" matter (such as stars, gas, and bicycles) and dark matter , the mass of the observable Universe does increase, not because mass is being created, but because the size of the observable Universe increases. In a billion years from now, we can see stuff that today is too far away for the light to have reached us, so its radius has increased. Since the mass $M$ equals density $\rho_\mathrm{M}$ times volume $V$ , $M$ increases. As called2voyage mentions, we have several ways of measuring the density, and we know it's close to $\rho_\mathrm{M}\simeq 2.7\times10^{-30}\,\mathrm{g}\,\mathrm{cm}^{-3}$ ( Planck Collaboration et al. 2020 ). The radius is $R = 4.4\times10^{28}\,\mathrm{cm}$ , so the mass is $$M = \rho_\mathrm{M} \times V = \rho_\mathrm{M} \times \frac{4\pi}{3}R^3 \simeq 10^{57}\,\mathrm{g},$$ or $5\times10^{23}M_\odot$ (Solar masses). Mass increase of matter Every second, the radius of the observable Universe increases by $dR = c\,dt = 300\,000\,\mathrm{km}$ , in addition to the expansion. Here, $c$ is the speed of light, and $dt$ is the time interval that I choose to be 1 second. That means that its mass (currently) increases by $$\begin{array}{rcl}dM & = & A \times dR \times \rho_\mathrm{M}\\ & = & 4\pi R^2 \times c\,dt \times \rho_\mathrm{M}\\ & \sim & 10^6\,M_\odot\,\text{per second,}\end{array}$$ where $A=4\pi R^2$ is the surface area of the Universe. Dark energy However, another factor contributes to the mass increase, namely the so-called dark energy , which is a form of energy attributed to empty space. And since new space is created as the Universe expands, dark energy is being created all the time. Currently, the energy density of dark energy, expressed as mass density through $E=mc^2$ , is more than twice that of matter ( $\rho_\Lambda \simeq 6\times10^{-30}\,\mathrm{g}\,\mathrm{cm}^{-3}$ ). The rate at which the observable Universe grows due to expansion can be calculated from the Hubble law , which says that objects at a distance $d$ from us recedes at a velocity $$v = H_0 \, d,$$ where $H_0\simeq 70\,\mathrm{km}\,\mathrm{s}^{-1}\,\mathrm{Mpc}^{-1}$ is the Hubble constant. Expansion thus makes the edge of the observable Universe recede at $v=H_0 R = 3.2c$ (yes, more than three times the speed of light), in addition to the factor of $1c$ that comes from more light reaching us (as above). Mass increase of dark energy Hence, every second the "total" radius of the observable Universe (i.e. expansion + more light) increases by $dR = (3.2c + 1c)\times dt$ , such that the increase in mass/energy from dark energy is $$\begin{array}{rcl}dM & = & A \times dR \times \rho_\Lambda\\ & = & 4\pi R^2 \times (3.2c + 1c)dt \times \rho_\Lambda\\ & \sim & 10^7\,M_\odot\,\text{per second,}\end{array}$$ an order of magnitude more than that of regular/dark matter.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/10374', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/2506/']}
jdg_375853
stackexchange
llm_judgeable_groundtruth_similarity
29022377
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 an assignment to count the number of vowels in a file, currently in my class we have only been using code like this to check for the end of a file: vowel=0f=open("filename.txt","r",encoding="utf-8" )line=f.readline().strip()while line!="": for j in range (len(line)): if line[j].isvowel(): vowel+=1 line=f.readline().strip() But this time for our assignment the input file given by our professor is an entire essay, so there are several blank lines throughout the text to separate paragraphs and whatnot, meaning my current code would only count until the first blank line. Is there any way to check if my file has reached its end other than checking for if the line is blank? Preferably in a similar fashion that I have my code in currently, where it checks for something every single iteration of the while loop Thanks in advance Now provide the response and nothing else.
Don't loop through a file this way. Instead use a for loop. for line in f: vowel += sum(ch.isvowel() for ch in line) In fact your whole program is just: VOWELS = {'A','E','I','O','U','a','e','i','o','u'}# I'm assuming this is what isvowel checks, unless you're doing something# fancy to check if 'y' is a vowelwith open('filename.txt') as f: vowel = sum(ch in VOWELS for line in f for ch in line.strip()) That said, if you really want to keep using a while loop for some misguided reason: while True: line = f.readline().strip() if line == '': # either end of file or just a blank line..... # we'll assume EOF, because we don't have a choice with the while loop! break
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29022377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2502019/']}
jdg_375854
stackexchange
llm_judgeable_groundtruth_similarity
19592706
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 dataframe with an NA row: df = data.frame(c("classA", NA, "classB"), t(data.frame(rep("A", 5), rep(NA, 5), rep("B", 5)))) rownames(df) <- c(1,2,3) colnames(df) <- c("class", paste("Year", 1:5, sep = "")) > df class Year1 Year2 Year3 Year4 Year51 classA A A A A A2 <NA> <NA> <NA> <NA> <NA> <NA>3 classB B B B B B I introduced the empty row (NA row) on purpose because I wanted to have some space between classA row and classB row. Now, I would like to substitute the <NA> by blank, so that the second row looks like an empty row. I tried: df[is.na(df)] <- "" and df[df == "NA"] <- "" but it didn't work.. Any ideas? Thanks! Now provide the response and nothing else.
Another alternative: df <- sapply(df, as.character) # since your values are `factor`df[is.na(df)] <- 0 If you want blanks instead of zeroes > df <- sapply(df, as.character)> df[is.na(df)] <- " "> df class Year1 Year2 Year3 Year4 Year5[1,] "classA" "A" "A" "A" "A" "A" [2,] " " " " " " " " " " " " [3,] "classB" "B" "B" "B" "B" "B" If you want a data.frame, then just use as.data.drame > as.data.frame(df) class Year1 Year2 Year3 Year4 Year51 classA A A A A A2 3 classB B B B B B
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19592706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664960/']}
jdg_375855
stackexchange
llm_judgeable_groundtruth_similarity
1242221
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: The first sentence in the Wikipedia article entitled "Cyclic Groups" states that "In algebra, a cyclic group is a group that is generated by a single element". How is this consistent with addition on the set of integers being considered a cyclic group. What would be the single element that generates all the integers.? Please don't tell me it is the element 1 :) Now provide the response and nothing else.
It is the element $-1$. On a more serious note, the definition of "generates" includes allowing the inverse of the generating elements. For any group $G$, and element $g\in G$, the subgroup generated by $g$ is$$\{g^n:n\in\mathbb{Z}\}$$not$$\{g^n:n\in\mathbb{N}\}$$(the latter is not a subgroup unless $g$ has finite order). Observe that $g^{-1}$ is always in $\{g^n:n\in\mathbb{Z}\}$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1242221', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/139257/']}
jdg_375856
stackexchange
llm_judgeable_groundtruth_similarity
68249
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: The question might be asked for any kind of "bound" proteins, but I'd like to restrict it to membrane proteins . Assuming membrane proteins (or their main parts) don't (or aren't) build in situ but at some distance of the membrane, I wonder by which mechanisms they travel from their generation site to their final destination inside the membrane (inner or outer). Proteins that are distributed roughly evenly (or randomly) over the membrane don't pose a big conceptual problem: they could have gone their just by diffusion , possibly from many generation sites, distributed roughly evenly (or randomly) inside the cell. But what about uneven distributions, where some proteins are more densely and non-randomly packed (significant and functional) at some sites of the membrane than at others, e.g. receptors at postsynaptic densities Na + channels at action potential initiation sites like the axon hillock or the axon initial segment Na + channels at nodes of Ranvier ? By which mechanisms (forces, signals or structures) are these proteins led to their targets? Maybe it depends, and there are different mechanisms. These I came up with (by contemplating first principles ): uneven distribution of generation sites inside the cell (due to what?) uneven distribution of origins of attracting signals inside the membrane (due to what?) some "self-attracting" forces or signals (leading to accumulation by positive feedback ) microtubules Which mechanism is — possibly — predominant? Related questions: Life cycle of proteins Pathways of ligand-gated ion channels Distribution of synapses of CA1 neurons Distribution of dendritic spike generating ion channels on the dendritic tree Visual maps of the neuronal membrane Distribution of sodium–potassium pumps Now provide the response and nothing else.
This is a great question. A comprehensive answer would be beyond the scope of an answer on a forum like this. I will summarize the best I can here, but if you are really interested in this you should look at some of the work by Randy Schekman and Tom Rapoport , who have done a lot of pioneering work in this field and have papers from more than two decades ago on their lab websites. I'll talk about membrane proteins generally, but I'm not sure what the state of the field is for Na+ channels specifically, so I can't comment too much on that particular case. Many of the details of the processes I will mention are still areas of active research, so I will try to stick mainly to what has been well-characterized (to the best of my knowledge). To restate the problem, proteins are generally synthesized in the lumen of the endoplasmic reticulum , which is an aqueous environment similar to the cytosol in many (but not all) ways. However, membrane proteins, which are not stable in aqueous environments, must: 1) Find a way from the ER lumen into a membrane. 2) Get from the ER into the correct membrane so they may perform their cellular function. We will start with step 1, but the key to both is a critical but often underappreciated aspect of protein biology called the signal peptide . The signal peptide is simply an N-terminal sequence of amino acids that precedes what we would normally think of as the beginning of a mature protein. It is relatively short, usually only ~30 amino acids in length. It is cleaved off the mature protein by a protease once the protein is folded and in the membrane. Until that time, the signal peptide serves as a molecular marker that indicates where the nascent protein should be heading and how it should be handled. Not surprisingly, there are many different signal peptides that serve multiple functions, and they are not only used for membrane proteins. So let's say we are in the ER lumen, and have some mRNA coding for a membrane protein that is destined for the plasma membrane. The first amino acids that will emerge from the ribosome is the signal sequence, in this case a specific signal sequence indicating that this is to be a plasma membrane protein. Once the signal sequence emerges from the ribosome, it is recognized by a ribonucleoprotein complex (that is, a complex of RNA and protein) called the signal recognition particle . Once the SRP binds to the signal peptide, translation is halted, and the whole complex moves to the ER membrane, where it forms a complex with another large protein complex called the translocon . I can't go into the intricacies of these complexes and their functions in this answer alone, but the simple description is that the translocon contains an ATPase that can insert the membrane protein into the ER membrane as it is translated, with the correct orientation. The hydrolysis of ATP provides energy to move the emerging polypeptide chain into the hydrophobic membrane, where chaperones help it fold. This process is in part driven by the recognition of hydrophobic transmembrane regions of the proteins by the translocon. It can also move soluble, cytosolic proteins across the membrane through a similar mechanism. Now that the protein has been translocated, a peptidase will cleave the signal sequence off the protein. From here, sorting signals will take over. Generally, these are simple sequence motifs in the first transmembrane domain that act similarly to a signal sequence, but they are not cleaved . However, sorting signals can be stretches of peptide throughout the protein too , in some cases. These sequence motifs will be recognized by cell trafficking machinery. Without going into too much detail, the proteins will be gathered into vesicles, and transported to other organelles. Usually, the first stop for proteins is the golgi apparatus , which is typically where many post-translational modifications, such as glycosylation, take place. I am a biochemist and not a cell biologist, so I am not the most qualified to go into the details of subcellular trafficking. Suffice it to say, once the protein is finished being processed in the golgi, it will be trafficked into other organelles, such as the plasma membrane using vesicle transport as before. From my understanding, the protein will be sorted into the proper vesicles based on its sorting signals, as well as other markers (in some cases, certain post-translational modifications on certain proteins can influence its trafficking). The vesicles recognize the proper destination membrane in part by the lipid composition of that membrane. For example, phosphoinositides have extensive influence on membrane trafficking , and many membranes can be differentiated by their phosphoinositide signature. Anyway, that is a very broad overview of the answer to your question. I'm sorry I can't comment too much on the intricacies of cellular trafficking, I don't quite have the expertise to go through that literature quickly enough to answer your question in a reasonable time frame. I hope this is helpful in pointing you in the right direction, and good luck!
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/68249', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/27928/']}
jdg_375857
stackexchange
llm_judgeable_groundtruth_similarity
25680612
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:gravity="center_vertical" android:orientation="horizontal" android:padding="10dp" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/icon" android:paddingBottom="10dp" android:textColor="#505050" android:textSize="16dp" /> <TextView android:id="@+id/desc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:textColor="#202020" android:textSize="14dp" /> <ImageView android:id="@+id/imageView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:src="@drawable/abs__ab_share_pack_holo_light" /> <LinearLayout android:id="@+id/linear2" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="1" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="25dip" android:layout_weight=".5" android:src="@drawable/accepticon" /> <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="25dip" android:layout_weight=".5" android:src="@drawable/rejecticon" /> <ImageView android:id="@+id/runnimage" android:layout_width="wrap_content" android:layout_height="25dip" android:src="@drawable/running" android:visibility="invisible" /> <TextView android:id="@+id/rejectedrequest" android:layout_width="wrap_content" android:layout_height="40dip" android:singleLine="true" android:text="Rejected" android:visibility="invisible" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_below="@+id/linear2" android:orientation="horizontal" > <TextView android:id="@+id/revresetime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Just 5 Minute Ago" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#000000" android:textSize="10dip" /> </LinearLayout> </LinearLayout></LinearLayout> This is My Xml I am able to display item in ListView : But I want to set my adapter Like this : Here is my ListView item : I have tried but am face issue to set margin layout and below one relative layout to linear layout please help me how to set item listview like this there is 2 textview request traveling and D has request for traveling for You Now provide the response and nothing else.
More than one binary may be uploaded to App Store Connect for the same version, if the the Build number is increasing for each build uploaded to iTunesConnect. The build number just has to be unique (and higher) for each binary that is uploaded (select the Target, then Xcode -> General -> Build, see the picture below).For example in the image below the build uploaded has version 3.1.4 (3.75 in the older image) and the build number is 1 . Thus, after uploading this image increase the build to a minimum 2 or higher . Then this binary may also be uploaded to App Store Connect as it's a later build according to the build number . The version notes the release version of the app your releasing to the user. The build number remarks the final build of the binary uploaded to the store, i.e. after many bug fixes. After Xcode 9 you are not able to upload a new build (for the same version), if there is a previous build with the same build number in the store. So, check your build number and increase if not certain. EDIT: It's more correct to use 1 , 2 , 3 , 4 , etc. for the build number, but the version number has to be increasing, 1.0 -> 1.1 -> 1.2 etc. The build number has to be higher than what was submitted previously for the same version number, if not an error is posted. So, if a new binary is submitted that has version 3.75 and a build 1 has already been submitted, then next build shall be 2 or higher, but the version can still remain 3.75. New updated and the recommended way of having the build numbers serial : The older image to match the one below: After a new binary is uploaded and processed (~5-20 min processing time, if it doesn´t show up upload again and wait), then you can select the new binary and submit it for review. In the picture below you may see the old and the new binary listed in App Store Connect in the Build section of the current App version (you click the plus sign). Then the new binary is selected -> Saved -> Submit for Review . (Sometimes an error comes when submitting, then just try after a few mins or upload a new binary). For those inclined to do this automatically with an Xcode script, here is a description of making an automatic script for updating Build numbers Better way of incrementing build number?
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/25680612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3587940/']}
jdg_375858
stackexchange
llm_judgeable_groundtruth_similarity
54133045
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 difference in performance computationally and/or memory-wise between Swift Array / Dictionary primitive functions removeAll and init ? Basically, I am asking, what are the pros and cons to resetting a mutable collection in Swift, and is one considered the recommended way to empty an Array / Dictionary ? // Scenario Avar myArray = ["one", "two", "three"]myArray.removeAll()// Scenario BmyArray = ["one", "two", "three"]myArray = [] Now provide the response and nothing else.
The performance difference should not be significant as they do largely the same thing. Let’s look at the source code : /// Removes all elements from the array.////// - Parameter keepCapacity: Pass `true` to keep the existing capacity of/// the array after removing its elements. The default value is/// `false`.////// - Complexity: O(*n*), where *n* is the length of the array.@inlinablepublic mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) }} There are several other implementations of this method for different types, but the pattern is always the same. If removeAll parameter keepCapacity is false , just reinitialize it, largely equivalent to saying myArray = [] . So, the only question is whether you want to preserve the capacity of the array after removing its elements or not (which you might do if you’re emptying a large array and about to repopulate with another array of the same size). If you want, benchmark it. For example, add "Unit Test” target to your project, bumping up the number of iterations high enough to make the duration observable: class MyAppTests: XCTestCase { func testPerformanceRemoveAll() { var countTotal = 0 var myArray: [Int] = [] self.measure { for _ in 0 ..< 1_000_000 { myArray = Array(repeating: 0, count: 1_000) myArray.removeAll(keepingCapacity: false) countTotal += myArray.count } } XCTAssertEqual(countTotal, 0) } func testPerformanceReinitialize() { var countTotal = 0 var myArray: [Int] = [] self.measure { for _ in 0 ..< 1_000_000 { myArray = Array(repeating: 0, count: 1_000) myArray = [] countTotal += myArray.count } } XCTAssertEqual(countTotal, 0) }} With the following results: Test Case '-[MyAppTests.MyAppTests testPerformanceReinitialize]' started./.../MyApp/MyAppTests/MyAppTests.swift:41: Test Case '-[MyAppTests.MyAppTests testPerformanceReinitialize]' measured [Time, seconds] average: 0.221, relative standard deviation: 6.559%, values: [0.264467, 0.216076, 0.216146, 0.216040, 0.216014, 0.216426, 0.216374, 0.215876, 0.216272, 0.216152], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100Test Case '-[MyAppTests.MyAppTests testPerformanceReinitialize]' passed (2.646 seconds).Test Case '-[MyAppTests.MyAppTests testPerformanceRemoveAll]' started./.../MyApp/MyAppTests/MyAppTests.swift:26: Test Case '-[MyAppTests.MyAppTests testPerformanceRemoveAll]' measured [Time, seconds] average: 0.235, relative standard deviation: 6.712%, values: [0.282223, 0.229732, 0.229601, 0.229624, 0.229584, 0.229652, 0.229695, 0.229729, 0.229702, 0.229659], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100Test Case '-[MyAppTests.MyAppTests testPerformanceRemoveAll]' passed (2.602 seconds). By the way, if you’re wondering about why I’m adding the totals after emptying the array, I’m just trying to make sure that I actually use the array after emptying it to ensure that the optimizer doesn’t optimize out the code doing the emptying. It’s not necessary in this case, but is prudent. I also did the test with Int instead of String , as I’m not curious about the String overhead, but rather trying to focus on the Array behavior. Bottom line, the performance difference was largely indistinguishable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54133045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409958/']}
jdg_375859
stackexchange
llm_judgeable_groundtruth_similarity
42962752
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Instead of using the element type 'card' I needed to separate the elements, In the documentation example they only use 'card' so when they create a token they just pass the card object to the create token parameter. stripe.createToken(card).then(function(result) {}); How can I pass these multiple objects to create a token? var cardNumber = elements.create('cardNumber');cardNumber.mount('#card-number');var cardExpiry = elements.create('cardExpiry');cardExpiry.mount('#card-expiry');var cardCvc = elements.create('cardCvc');cardCvc.mount('#card-cvc');var cardPostalCode = elements.create('postalCode');cardPostalCode.mount('#card-postal-code'); Now provide the response and nothing else.
From the Elements reference. element: the Element you wish to tokenize data from. The Element will pull data from other Elements you’ve created on the same instance of elements to tokenize. https://stripe.com/docs/elements/reference#stripe-create-token So you can initialize elements var elements = stripe.elements(); And then define / mount your fields var cardNumber = elements.create('cardNumber');cardNumber.mount('#card-number');var cardExpiry = elements.create('cardExpiry');cardExpiry.mount('#card-expiry');var cardCvc = elements.create('cardCvc');cardCvc.mount('#card-cvc');// creating a postal code element is deprecated // var cardPostalCode = elements.create('postalCode');// cardPostalCode.mount('#card-postal-code'); Then this should pull them all in as they are part of elements stripe.createToken(cardNumber).then(doSomething); Edit: The postal code element has been deprecated, so I removed it from my example. If you're using separate fields and want to collect the postal code (or other address data), you should do this via an <input> and then pass it into the optional cardData object when calling stripe.createToken https://stripe.com/docs/stripe-js/reference#elements-create // <input id="postal-code" name="postal_code" class="field" placeholder="90210" />var cardData = { address_zip: document.getElementById('postal-code').value}stripe.createToken(cardNumber,cardData).then(doSomething);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42962752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1386644/']}
jdg_375860
stackexchange
llm_judgeable_groundtruth_similarity
300234
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I failed this audit in triage ( screenshot ).The description of why it wasn't "ok" was that it was spam or complete nonsense. I don't think the question was spam or complete nonsense, so does someone here have a better explanation for why I failed this review? On a side note, I was suspended from reviewing as a result of this failure. Now provide the response and nothing else.
I can provide a little context on this question. The reason why this appeared as an audit is because it was flagged as spam and deleted. That validated the spam flag and caused it to be used as an audit case. Why that question was flagged as spam had to do with one of the answers. For a couple of months now, a clever spam ring has been posting spam for "Easy Data Feed" and other related products. They do this by first seeding well-written but completely off topic questions in a series of tags (usually [e-commerce], [scrape], and [web-scraping]), then answering them with their spam. The question will be posted on a different account than the spam answer, with the answer sometimes coming days later. At the request of myself and other moderators, folks in the Tavern have been watching for this and flagging spam seed questions and their answers as they come in. Usually, they use spam flags only on the obvious spam answers and "other" flags on the questions, but occasionally they use spam flags on both. We're usually in a hurry to delete the whole thing, and we appreciate the help, so maybe we're not always as discriminating as to whether the question would appear to be wrong to someone not aware of this and don't dispute spam flags on them. Also, sometimes we'll use a hard moderator spam flag on the question itself (immediately destroying the post), because that can trigger the anti-spam system to immediately stop any new posts from a location for a short duration. I think that might have been used here. This is probably the most borderline of the ones I've seen, so I've cleared the spam flag on this (stopping it from being used as an audit). I've also lifted your review ban, since you couldn't have known all this.
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/300234', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/3960399/']}
jdg_375861
stackexchange
llm_judgeable_groundtruth_similarity
463643
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'm asking the same question as this guy: How to do relative imports in Python? But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as the OP pointed out in his comments to their answers). I know that you can do this by using sys.path, but I would prefer a cleaner method. Example: App__init__.pyPackage_A--__init__.py--Module_A.pyPackage_B--__init__.py--Module_B.py How would I import Module_A into Module_B? Now provide the response and nothing else.
main.pysetup.pyapp/ -> __init__.py package_a/ -> __init__.py module_a.py package_b/ -> __init__.py module_b.py You run python main.py . main.py does: import app.package_a.module_a module_a.py does import app.package_b.module_b Alternatively 2 or 3 could use: from app.package_a import module_a That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then. So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/463643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49018/']}
jdg_375862
stackexchange
llm_judgeable_groundtruth_similarity
1145775
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 hopes of trying to avoid future memory leaks in php programs (drupal modules, etc.) I've been messing around with simple php scripts that leak memory. Could a php expert help me find what about this script causes the memory usage to continually climb? Try running it yourself, changing various parameters. The results are interesting. Here it is: <?phpfunction memstat() { print "current memory usage: ". memory_get_usage() . "\n";}function waste_lots_of_memory($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i} = array("blah blah blha" => 12345); $object->{"membersonly_" . $i} = new StdClass; $object->{"onlymember"} = array("blah blah blha" => 12345); } unset($object);}function waste_a_little_less_memory($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i} = array("blah blah blha" => 12345); $object->{"membersonly_" . $i} = new StdClass; $object->{"onlymember"} = array("blah blah blha" => 12345); unset($object->{"membersonly_". $i}); unset($object->{"member_" . $i}); unset($object->{"onlymember"}); } unset($object);}memstat();waste_a_little_less_memory(1000000);memstat();waste_lots_of_memory(10000);memstat(); For me, the output is: current memory usage: 73308current memory usage: 74996current memory usage: 506676 [edited to unset more object members] Now provide the response and nothing else.
unset() doesn't free the memory used by a variable. The memory is freed when the "garbage collector" (in quotes since PHP didn't have a real garbage collector before version 5.3.0, just a memory free routine which worked mostly on primitives) sees fit. Also, technically, you shouldn't need to call unset() since the $object variable is limited to the scope of your function. Here is a script to demonstrate the difference. I modified your memstat() function to show the memory difference since the last call. <?phpfunction memdiff() { static $int = null; $current = memory_get_usage(); if ($int === null) { $int = $current; } else { print ($current - $int) . "\n"; $int = $current; }}function object_no_unset($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i}= array("blah blah blha" => 12345); $object->{"membersonly_" . $i}= new StdClass; $object->{"onlymember"}= array("blah blah blha" => 12345); }}function object_parent_unset($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i}= array("blah blah blha" => 12345); $object->{"membersonly_" . $i}= new StdClass; $object->{"onlymember"}= array("blah blah blha" => 12345); } unset ($object);}function object_item_unset($iters) { $i = 0; $object = new StdClass; for (;$i < $iters; $i++) { $object->{"member_" . $i}= array("blah blah blha" => 12345); $object->{"membersonly_" . $i}= new StdClass; $object->{"onlymember"}= array("blah blah blha" => 12345); unset ($object->{"membersonly_" . $i}); unset ($object->{"member_" . $i}); unset ($object->{"onlymember"}); } unset ($object);}function array_no_unset($iters) { $i = 0; $object = array(); for (;$i < $iters; $i++) { $object["member_" . $i] = array("blah blah blha" => 12345); $object["membersonly_" . $i] = new StdClass; $object["onlymember"] = array("blah blah blha" => 12345); }}function array_parent_unset($iters) { $i = 0; $object = array(); for (;$i < $iters; $i++) { $object["member_" . $i] = array("blah blah blha" => 12345); $object["membersonly_" . $i] = new StdClass; $object["onlymember"] = array("blah blah blha" => 12345); } unset ($object);}function array_item_unset($iters) { $i = 0; $object = array(); for (;$i < $iters; $i++) { $object["member_" . $i] = array("blah blah blha" => 12345); $object["membersonly_" . $i] = new StdClass; $object["onlymember"] = array("blah blah blha" => 12345); unset ($object["membersonly_" . $i]); unset ($object["member_" . $i]); unset ($object["onlymember"]); } unset ($object);}$iterations = 100000;memdiff(); // Get initial memory usageobject_item_unset ($iterations);memdiff();object_parent_unset ($iterations);memdiff();object_no_unset ($iterations);memdiff();array_item_unset ($iterations);memdiff();array_parent_unset ($iterations);memdiff();array_no_unset ($iterations);memdiff();?> If you are using objects, make sure the classes implements __unset() in order to allow unset() to properly clear resources. Try to avoid as much as possible the use of variable structure classes such as stdClass or assigning values to members which are not located in your class template as memory assigned to those are usually not cleared properly. PHP 5.3.0 and up has a better garbage collector but it is disabled by default. To enable it, you must call gc_enable() once.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1145775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1789888/']}
jdg_375863
stackexchange
llm_judgeable_groundtruth_similarity
68650
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: Richmond's mayor Levar Stoney was quoted as saying (in the context of the removal of a statue of Robert E. Lee) Mr Northam called the statue "a monument to the Confederate insurrection". [...] "There's no other country in the world that erects monuments to those who took up arms against their country," Mayor of Richmond, Levar Stoney, told BBC News. No doubt it's unusual for a country/government to have monuments honoring those that "took up arms against it". But if one considers winning revolutions/insurrections, surely there are plenty of examples of statues for those who overthrew the old regime. In the more autocratic cases, statues even ordered by themselves after taking power, but often enough by later generations if the change/revolution was stable enough in terms of outcome. So, I'm thinking that the claim needs to be more narrowly interpreted as in: no country that hasn't seen a [dramatic/substantial] change in regime or constitutional order has erected such statues to defeated insurrectionists, revolutionaries, or separatists. I.e. given some reasonable level of regime or constitutional continuity, such statues really are non-existent. Is the claim true in this sense, which is probably how it was meant? Or are there some counter-examples even to this? (I could ask this on Skeptics, but given that the claim is not literally true as in the quote, I may get flak there for asking my own question/interpretation.) Now provide the response and nothing else.
There are plenty of counter-examples in the UK; commenters have mentioned Guy Fawkes, who unsuccessfully plotted to assassinate King James I and restore the Catholic monarchy - commemorated with a statue, and carnival , in Bridgwater, Somerset, and Oliver Cromwell, who successfully overthrew King Charles I in the English Civil War and ruled as Lord Protector until his death in 1658 - commemorated with a statue outside of Parliament , as well as others in St Ives, Manchester, Warrington, and Bradford. The monarchy was later restored, so I suppose Cromwell could also be classified as having been unsuccessful. Other examples of statues commemorating participants in an unsuccessful rebellion might be those in memory of the Jacobite Risings of 1745. Charles Edward Stuart, often known as Bonnie Prince Charlie, led the rebellion in an attempt to reclaim the British throne for his father, James Stuart, son of James II and IV. Both the Glenfinnan Monument of the Unknown Highlander , located at the spot where the rising began, as well as the statue of Bonnie Prince Charlie in Derby, England , where the Jacobites retreated back to Scotland, commemorate the participants. Another example might be the statue in St Keverne, Cornwall, of two of the leaders of the Cornish rebellion of 1497 - Thomas Flamank and Michael An Gof. Further examples mentioned by commenters: Many monuments/memorials to the Covenanters , named after a document called the National Covenant, which pledged to resist changes to the Church of Scotland planned by Charles I. Uprisings included the 1679 Rebellion which culminated in the Battle of Bothwell Bridge . Statues of Charles I , defeated by Thomas Fairfax, Oliver Cromwell and the Parliamentarians in the English Civil War. The statue of Mahatma Gandhi which was placed in Parliament Square in 2015. The memorial in Smithfield to Wat Tyler, John Ball and other leaders of the 1381 Peasant's Revolt. The statue of Owain Glyndŵr in Corwen , who led the Welsh Revolt against English rule in 1400-15.
{}
{'log_upvote_score': 7, 'links': ['https://politics.stackexchange.com/questions/68650', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/18373/']}
jdg_375864
stackexchange
llm_judgeable_groundtruth_similarity
28438141
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My code currently takes in a file, and saves it to a preset directory, but is it possible to just use the file (read the file) and not save it? @app.route('/', methods=['GET', 'POST'])def upload_file(): if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return "yatta" else: return "file not allowed" return render_template("index.html") I have tried both file.read() and file.stream.read() but the return value of that is empty. I verify that the file exists in the uploaded directory and see that the file is not empty. Now provide the response and nothing else.
I know that this is very outdated but for the sake of people landing here for similar inquiry, here it is if you want to save AND read your file after wards. Seems like Werkzeug's FileStorage class (which is the class to handle uploaded file in Flask) pointing to end of file after every action (saving or reading). So we have to move the pointer up to the beginning of the file before doing any subsequent action. I am using python's pandas in my answer below because I usually read csv into dataframe. import pandas as pd@app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) ## snippet to read code below file.stream.seek(0) # seek to the beginning of file myfile = file.file # will point to tempfile itself dataframe = pd.read_csv(myfile) ## end snippet return "yatta" else: return "file not allowed" return render_template("index.html")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28438141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1515864/']}
jdg_375865
stackexchange
llm_judgeable_groundtruth_similarity
9605732
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 get this XML from "select * from ANY_TABLE" query? <root> <row> <column name="id" value="321"> <column name="name" value="Book"> </row> <row> <column name="id" value="654"> <column name="name" value="Pen"> </row></root> Now provide the response and nothing else.
Strings in Java are immutable, which makes this somewhat tricky if you are talking about an arbitrary number of things you need to find and replace. Specifically you need to define your replacements in a Map , use a StringBuilder (before Java 9, less performant StringBuffer should have been used) and the appendReplacements() and appendTail() methods from Matcher . The final result will be stored in your StringBuilder (or StringBuffer ). Map<String, String> replacements = new HashMap<String, String>() {{ put("${env1}", "1"); put("${env2}", "2"); put("${env3}", "3");}};String line ="${env1}sojods${env2}${env3}";String rx = "(\\$\\{[^}]+\\})";StringBuilder sb = new StringBuilder(); //use StringBuffer before Java 9Pattern p = Pattern.compile(rx);Matcher m = p.matcher(line);while (m.find()){ // Avoids throwing a NullPointerException in the case that you // Don't have a replacement defined in the map for the match String repString = replacements.get(m.group(1)); if (repString != null) m.appendReplacement(sb, repString);}m.appendTail(sb);System.out.println(sb.toString()); Output: 1sojods23
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9605732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278822/']}
jdg_375866
stackexchange
llm_judgeable_groundtruth_similarity
27759380
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 unable to stop refreshing page after ajax call. I have tried by putting e.preventDefault(); and return false; as well but again my page is refreshing. I dont know what is the problem with the code or something. Please help me to stop refreshing page after ajax call. solving this issue would be a great help for me. Thanks in advance. Here is my code: $(document).ready(function() { $('#loginForm').on('click', function(e) { e.preventDefault(); var formData = { 'uname' : $('#uname').val(), 'pwd' : $('#pwd').val() }; $.ajax({ type : "POST", url : "getresults.php", data : formData }).done(function(data) { alert(data+"This is working"); }).fail(function(data) { alert("This is not working"); }); });}); Now provide the response and nothing else.
Is the id #loginForm pointing to a form? If yes you need to listen to the submit event instead of click. If you really need to listen to the click event, you have to bind the event to the submit button or whatever triggers the form.submit() . Try something like this: $('#loginForm').on('submit', function(e) { e.preventDefault(); e.stopPropagation(); // only neccessary if something above is listening to the (default-)event too [YOUR CODE GOES HERE]}); This should do the trick for you.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27759380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4415708/']}
jdg_375867
stackexchange
llm_judgeable_groundtruth_similarity
3768893
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 to implement a https connection with SSL and ASIHTTPRequest ? Are there some special steps to do? Can it be that this has nothing to do with ASIHTTPRequest ? It has to do only with the server-side I think. Can someone post a link or describe the process of how a https connection can be established? This is what I found out so far: I read somewhere that you need a "real" SSL certificate and not a self signed one. There are also not all provider of SSL certificates supported I think (read this ). You also have to run through the U.S. Government requirement for a CCATS review and approval. (see here ). Now provide the response and nothing else.
So you've got a few questions here: To do SSL with ASIHTTPRequest, you just need to pass a https url instead of a http one. you don't need a real SSL certificate, you can disable validation using: [request setValidatesSecureCertificate:NO];. Disabling certificate validation does mean you lose some of the protection that SSL provides, making you vulnerable to man-in-the-middle attacks etc. Yes, you're limited by what certificate signing authorities are supported by the iPhone. So long as you stick to the big names it shouldn't really be an issue. (And as per 2. you can use a self signed certificate anyway.) It seems CCATS not necessary anymore, you need an ERN instead - the process has changed, as of Summer 2010! See http://tigelane.blogspot.com/2011/01/apple-itunes-export-restrictions-on.html . There are also extra restrictions if you want to distribute on the French app store, see Using SSL in an iPhone App - Export Compliance .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3768893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/426227/']}
jdg_375868
stackexchange
llm_judgeable_groundtruth_similarity
24302
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 made a visualization of Amazon related products. Every link in visualization means two products are often bought together. Now I'm applying various graph analysis techniques and am fascinated by the results. The biggest problem though is translating scientific terms to human language (please pardon me if it sounds snobberish). For example, I calculated indegree centrality of nodes, and I called it "What's popular here". After all the most connected node means it's most often bought with all other products in a given graph. Currently I'm working on betweenness centrality , and it yields quite interesting results, often contradicting degree centrality . But how would you interpret these results? Most important products? For example, books graph of The art of R programming has the following top 3 nodes: Indegree Centrality: The art of R programming - 18 outgoing edges R Cookbook (O'Reilly Cookbooks) - 14 outgoing edges Doing Bayesian Data Analysis: A Tutorial with R and BUGS - 10 outgoing edges Betweenness Centrality: The art of R programming - centrality value of 1210 What is a p-value anyway? - centrality value of 896 Visualize This - centrality value of 784 The graph itself looks like this: Now provide the response and nothing else.
The difference between in-degree centrality and closeness centrality - or really any other centrality measure - the answer is that you're identifying different things. Currently I'm working on betweenness centrality, and it yields quite interesting results, often contradicting degree centrality. But how would you interpret these results? Most important product? I wouldn't necessarily call it the most important product. To my mind, a better description might be "core" products - those that regardless of what you purchase, it's relatively easy to end up at those books. Looking at your figure, the three most popular nodes are all near the center of your graph. They define places where, as soon as you move outside your sub-field, you have a somewhat higher level book that defines several groups. Take Visualize This , as its the clearest illustration of this. Even if people don't jointly buy books about Tufte's theories and infographics about trivia, Visualize This is a common foundational book not very far removed from either group. The same is true with the p-value book. No one jointly buys an "Idiots Guide to a Natural Science" book, a "Popular Statistics" book and a "Biostatistics" book. But all three can and do end up buying What Is a p-value anyway? Its a core book, useful to three different groups of readers.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/24302', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/8717/']}
jdg_375869
stackexchange
llm_judgeable_groundtruth_similarity
562958
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 would like to do a linear regression between my response "weed coverage [%]" and my predictor "soil moisture content[%]". Since the response was not normally distributed and had issues with heteroskedecity, I have decided to transform my response by applying the log. Now, I got diagnostic plots and normality-test results as seen below. My question: Can I do a simple linear regression now? Thanks for your help! EDIT: I forgot to mention that my observations were measured on different lakes and on different dates, e.g I measured soil moisture content at Lake A, Lake B and Lake C on Date A and later on Date B and so on. That means they are dependend.. What do I need to do now? ----------------------------------------------- Test Statistic pvalue -----------------------------------------------Shapiro-Wilk 0.9917 0.0057 Kolmogorov-Smirnov 0.0425 0.3116 Cramer-von Mises 31.7515 0.0000 Anderson-Darling 0.9348 0.0177 ----------------------------------------------- Now provide the response and nothing else.
If you are doing explorative analysis, then you don't care about p-values. What you do is search for any pattern. P-values are used to verify a hypothesis, but you have none. However, if after your explorative analysis you are gonna perform some hypothesis tests with the same data then this gives the erroneous p-values if the hypothesis were created by the same data. If you only have a single data set available then you can split the data into two subsets, one for analysis and another for follow-up research to verify whether the found patterns are much different from statistical variations in the sampling. You seem to be doing a search for patterns by using hypothesis tests and p-values. That is not p-hacking if you regard the p-values only as an aid in pattern recognition (a search for anomalies) instead of a value to report in relation to an experiment to verify a certain effect. You have to be careful though that you do not switch the meaning from a statistic used in pattern recognition to a value that expresses the statistical significance of an experiment to measure an effect.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/562958', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/345827/']}
jdg_375870
stackexchange
llm_judgeable_groundtruth_similarity
7392057
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following program compiles: template <const int * P>class Test{};extern const int var = 42; //extern needed to force external linkageint main(){ Test<&var> test;} This one, however, doesn't, which is a surprise for me: template <const int * P>class Test{};extern const int var = 42; //extern needed to force external linkageextern const int * const ptr = &var; //extern needed to force external linkageint main(){ Test<ptr> test; //FAIL! Expected constant expression.} Alternative example: int main(){ const int size = 42; int ok[*&size]; //OK const int * const pSize = &size; int fail[*pSize]; //FAIL} I have concluded that a pointer just can't be a constant expression regardless of whether it's const and initialized with a constant expression. Questions: Is my conclusion true? If so, why can't a pointer be a constant expression? If not, why don't the above programs compile? Does C++0x(C++11, if you will) change anything? Thanks for any insights! Now provide the response and nothing else.
It's a bit more complicated. In C++03 and C++11, &var is a constant expression if var is a local static / class static or namespace scope variable. This is called an address constant expression. Initializing a class static or namespace scope pointer variable with that constant expression is guaranteed to be done before any code is run (static initialization phase), because of it being a constant expression. However only since C++11, a constexpr pointer variable that stores the address &var can also be used as an address constant expression and only since C++11, you can dereference an address constant expression (actually, you can dereference even more - even local array element addresses, but let's keep it ontopic) and if it refers to a constant integral variable initialized prior to the dereference or a constexpr variable, you again get a constant expression (depending on the type and value category, the kind of constant expression may vary). As such, the following is valid C++11: int const x = 42;constexpr int const *px = &x;// both the value of "px" and the value of "*px" are prvalue constant expressionsint array[*px];int main() { return sizeof(array); } If so, why can't a pointer be a constant expression? If not, why don't the above programs compile? This is a known limitation in the Standard's wording - it currently only allows other template parameters as arguments or & object , for a template parameter of pointer type. Even though the compiler should be capable of doing much more.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7392057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/469935/']}
jdg_375871
stackexchange
llm_judgeable_groundtruth_similarity
9608
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When water is added to a weak acid like ethanoic acid, the number of ethanoic acid molecules that dissociate increases, however, pH increases (less acidic), too. Why is this so? Now provide the response and nothing else.
It's simply due to dilution. If it's true that adding water increases dissociation (Gerard has done a nice effort in Does the number of H+ ions in solution go up on dilution of a weak acid? ), concentration of $\ce{H3O+}$ inevitably decreases. As a consequence, $\mathrm{pH}$ , defined as $-\log[\ce{H3O+}]$ , increases. Start with $\pu{1 L}$ acetic acid concentration $\pu{1 M}$ , $$\ce{[H3O+]} = \sqrt{K_c} = \pu{4.22E-3M},$$ that corresponds to $\pu{4.22E-3mol}$ of $\ce{H3O+}$ .If you double the volume ( $\pu{2 L}$ ), $$\ce{[H3O+]}=\sqrt{K_c/2}=\pu{2.98E-3M},$$ that corresponds to $\pu{5.96E-3mol}$ of $\ce{H3O+}$ . The amount of substance is higher, but concentration is less: dilution does play a role here.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/9608', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/2595/']}
jdg_375872
stackexchange
llm_judgeable_groundtruth_similarity
8485947
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say I run a simple single-threaded process like the one below: public class SirCountALot { public static void main(String[] args) { int count = 0; while (true) { count++; } }} (This is Java because that's what I'm familiar with, but I suspect it doesn't really matter) I have an i7 processor (4 cores, or 8 counting hyperthreading), and I'm running Windows 7 64-bit so I fired up Sysinternals Process Explorer to look at the CPU usage, and as expected I see it is using around 20% of all available CPU. But when I toggle the option to show 1 graph per CPU, I see that instead of 1 of the 4 "cores" being used, the CPU usage is spread all over the cores: Instead what I would expect is 1 core maxed out, but this only happens when I set the affinity for the process to a single core. Why is the workload split over the separate cores? Wouldn't splitting the workload over several cores mess with the caching or incur other performance penalties? Is it for the simple reason of preventing overheating of one core? Or is there some deeper reason? Edit: I'm aware that the operating system is responsible for the scheduling, but I want to know why it "bothers". Surely from a naive viewpoint, sticking a (mostly*) single-threaded process to 1 core is the simpler & more efficient way to go? *I say mostly single-threaded because there's multiple theads here, but only 2 of them are doing anything: Now provide the response and nothing else.
The OS is responsible for scheduling. It is free to stop a thread and start it again on another CPU. It will do this even if there is nothing else the machine is doing. The process is moved around the CPUs because the OS doesn't assume there is any reason to continue running the thread on the same CPU each time. For this reason I have written a library for lock threads to a CPU so it won't move around and won't be interrupted by other threads. This reduces latency and improve throughput but does tire up a CPU for that thread. This works for Linux, perhaps you can adapt it for Windows. https://github.com/peter-lawrey/Java-Thread-Affinity/wiki/Getting-started
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8485947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775982/']}
jdg_375873
stackexchange
llm_judgeable_groundtruth_similarity
70335156
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 just installed react navigation version 6 and i received below error Attempt to invoke interface method boolean com.swmansion.reanimated.layoutReanimation.NativeMethodsHolder.isLayoutAnimationEnabled() on a null object reference below is my code /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */import 'react-native-gesture-handler';import React from 'react';import { SafeAreaView, ScrollView, StatusBar, StyleSheet, Text, useColorScheme, View,} from 'react-native';import { NavigationContainer } from '@react-navigation/native';import { createStackNavigator } from '@react-navigation/stack';import Upload from './Screens/Upload';import Display from './Screens/Display';const Stack = createStackNavigator()function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name='Screen_A' component={Upload} > </Stack.Screen> <Stack.Screen name='Screen_B' component={Display} > </Stack.Screen> </Stack.Navigator> </NavigationContainer> );};export default App; this is first time i am using react-native and react-native navigation wish to build an app Now provide the response and nothing else.
There are two ways to solve it. in your json package there is a package named "react-native-reanimated": "^2.3.0", remove this package and install "react-native-reanimated": "^2.2.4" and restart metro then build again Second way 1° - Turn on Hermes engine by editing android/app/build.gradle project.ext.react = [ enableHermes: true // <- here -- change false for true] 2° - Plug Reanimated in MainApplication.java android\app\src\main\java\com\<yourProjectName>\MainApplication.java import com.facebook.react.bridge.JSIModulePackage; // <- add this import com.swmansion.reanimated.ReanimatedJSIModulePackage; // <- add this ... private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { ... @Override protected String getJSMainModuleName() { return "index"; }// add more this "Override" below <---------------- @Override protected JSIModulePackage getJSIModulePackage() { return new ReanimatedJSIModulePackage(); // <- add } }; ... AFTER ALL PROCESSReact Navigation DocsTo finalize installation of react-native-gesture-handler, add the following at the top (make sure it's at the top and there's nothing else before it) of your entry file, such as index.js or App.js import 'react-native-gesture-handler'; Save all and rebuild( Android is: npx react-native run-android ) My package.json "@react-navigation/drawer": "^6.1.8""@react-navigation/native": "^6.0.6""@react-navigation/native-stack": "^6.2.5""react-native": "0.66.4""react-native-gesture-handler": "^2.1.0" i solved it using first way
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/70335156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8830456/']}
jdg_375874
stackexchange
llm_judgeable_groundtruth_similarity
96562
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: For my research project I need to solve the following integral I = 1/2 Integrate[π Sqrt[r[θ]^2 Sin[θ]^2] Sqrt[r[θ]^2 + Derivative[1][r][θ]^2/ (1 + 1/r[θ]^2 - 3/r[θ] + r[θ]^2)], {θ, 0, 0.005}] where r[θ] is a solution of following differential equation -2 r[θ] + 12 r[θ]^2 - 22 r[θ]^3 + 12 r[θ]^4 - 6 r[θ]^5 + 12 r[θ]^6 - 4 r[θ]^7 - 2 r[θ]^9 + (Cot[θ] r[θ]^2 - 3 Cot[θ] r[θ]^3 + Cot[θ] r[θ]^4 + Cot[θ] r[θ]^6) Derivative[1][r][θ] + (-2 r[θ] + (15 r[θ]^2)/2 - 3 r[θ]^3 - 4 r[θ]^5) Derivative[1][r][θ]^2 + Cot[θ] r[θ]^2 Derivative[1][r][θ]^3 + (r[θ]^2 - 3 r[θ]^3 + r[θ]^4 + r[θ]^6) Derivative[2][r][θ] with initial conditions {r[0] == r0, r'[0] == 0} . It's a second order non-linear differential equation. The independent variable θ runs from θ = {0, 0.005} . There is a singularity at θ = 0 , which can be avoided by taking θ = 10^-10 (some small value). Then initial conditions modify to {r[10^-10] == r0, r'[10^-10] == 0} . I have to choose r0 such that by solving the above equation one should get r[0.005] = 10000 . The initial guess for r0 (depending upon the working precision) can be around r0 = 199.958344 . At the end, integral should gives value I = 76.96884 . I am solving this problem in Mathematica and getting answer like I = 76.9844 . Can you please help me in solving this problem. Now provide the response and nothing else.
J.M.'s answer in comments is what I would have done too. Times @@@ Apply[p, list, {2}] But for completeness, you might be interested in this rule-based method of getting the p elements: Times @@@ (a /. {x_?AtomQ, y_?AtomQ} -> p[x, y]) The test for _AtomQ is important (you could also use _?NumericQ or simple pattern `_Integer, depending on the scope of your actual problem). Otherwise the rule will just match the top level of your nested list and not replace anything else. This being Mathematica, there are many ways to get the same result, but J.M.'s is the most succinct that I can think of.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/96562', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/34703/']}
jdg_375875
stackexchange
llm_judgeable_groundtruth_similarity
13910
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: What's the easiest way to regulate a 12 V battery to a regulated 12 V power source? Preferably, I'd like a ready-made product so that I could avoid having to show my lack of skill with the soldering iron. :-) More complex answers are fine, too, as long as they are insightful. I'm thinking of powering a 12 V / 600 mA stage piano/synth by replacing its AC/DC converter with a small car battery for portable use. Because the device is not designed for in-car use, I understand that regulation is the safest bet. (Of course, I could buy an inverter, but I'd like to "do it right" and get rid of the DC/AC AC/DC conversion.) Now provide the response and nothing else.
What a regulator actually does is to smooth out variations in voltage to make a source look more like a battery. In a case like this, you don't have to worry about the source voltage changing much, so the main advantage of regulation is moot. Often equipment that's designed for low-voltage DC will actually accept a range of voltages. Sometimes it isn't, and really does expect a regulated supply. The problem here is, what's the range that the synth will find acceptable? Admittedly, applying regulation solves that problem by nailing the voltage down to something that's supposed to work, but the thing is, voltage regulation gets complicated when the source and the output voltages are closer than about 2 volts, because regulators need some headroom to work with. Automotive batteries nominally sit around 13.8V; worryingly high if your device wants a regulated 12V input, annoyingly low if you want to regulate it to 12V. If you can measure the voltage from your present AC/DC converter, while it's connected to the synth, with the synth turned on , and that voltage is with say, half a volt of the battery's open-circuit voltage, you would probably be able to directly connect the battery, without a regulator.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/13910', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4122/']}
jdg_375876
stackexchange
llm_judgeable_groundtruth_similarity
3119631
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 know it is true that we have $$\sqrt{1+2\sqrt{1+3\sqrt{1+4\sqrt{1+\cdots}}}}=3$$ The argument is to break the nested radical into something like $$3 = \sqrt{9}=\sqrt{1+2\sqrt{16}}=\sqrt{1+2\sqrt{1+3\sqrt{25}}}=...=\sqrt{1+2\sqrt{1+3\sqrt{1+4\sqrt{1+\cdots}}}}$$ However, I am not convinced. I can do something like $$4 = \sqrt{16}=\sqrt{1+2\sqrt{56.25}}=\sqrt{1+2\sqrt{1+3\sqrt{\frac{48841}{144}}}}=...=\sqrt{1+2\sqrt{1+3\sqrt{1+4\sqrt{1+\cdots}}}}$$ Something must be wrong and the reason behind should be a misunderstanding of how we define infinite nested radical in the form of $$ \sqrt{a_{0}+a_{1}\sqrt{a_{2}+a_{3}\sqrt{a_{4}+a_{5}\sqrt{a_{6}+\cdots}}}} $$ I researched for a while but all I could find was computation tricks but not a strict definition. Really need help here. Thanks. Now provide the response and nothing else.
Introduction: The issue is what "..." really "represents." Typically we use it as a sort of shorthand, as if to say "look, I can't write infinitely many things down, just assume that the obvious pattern holds and goes on infinitely." This idea holds for all sorts of things - nested radicals, infinite sums, continued fractions, infinite sequences, etc. On Infinite Sums: A simple example: the sum of the reciprocals of squares: $$1 + \frac{1}{4} + \frac{1}{9} + \frac{1}{16} + ...$$ This is a well known summation. It is the Riemann zeta function $\zeta(s)$ at $s=2$ , and is known to evaluate to $\pi^2/6$ (proved by Euler and known as the Basel problem ). Another, easier-to-handle summation is the geometric sum $$1 + \frac 1 2 + \frac 1 4 + \frac 1 8 + ...$$ This is a geometric series where the ratio is $1/2$ - each summand is half the previous one. We know, too, that this evaluates to $2$ . Another geometric series you might see in proofs that $0.999... = 1$ is $$9 \left( \frac{1}{10} + \frac{1}{100} + \frac{1}{1,000} + \frac{1}{10,000} + ... \right)$$ which equals $1$ . In fact, any infinite geometric series, with first term $a$ and ratio $|r|<1$ can be evaluated by $$\sum_{n=0}^\infty ar^n = \frac{a}{1-r}$$ So a question arises - ignoring these "obvious" results (depending on your amount of mathematical knowledge), how would we know these converge to the given values? What, exactly, does it mean for a summation to converge to a number or equal a number? For finite sums this is no issue - if nothing else, we could add up each number manually, but we can't just add up every number from a set of infinitely-many numbers. Well, one could argue by common sense that, if the sequence converges to some number, the more and more terms you add up, the closer they'll get to that number. So we obtain one definition for the convergence of an infinite sum. Consider a sequence where the $n^{th}$ term is defined by the sum of the first $n$ terms in the sequence. To introduce some symbols, suppose we're trying to find the sum $$\sum_{k=1}^\infty x_k = x_1 + x_2 + x_3 + x_4 + ...$$ for whatever these $x_i$ 's are. Then define these so-called "partial sums" of this by a function $S(n)$ : $$S(n) = \sum_{k=1}^n x_k = x_1 + x_2 + ... + x_n$$ Then we get a sequence of sums: $$S(1), S(2), S(3), ...$$ or equivalently $$x_1 \;\;,\;\; x_1 + x_2\;\;,\;\; x_1 + x_2 + x_3\;\;,\;\; ...$$ Then we ask: what does $S(n)$ approach as $n$ grows without bound, if anything at all? (In calculus, we call this "the limit of the partial sums $S(n)$ as $n$ approaches infinity.") For the case of our first geometric sum, we immediately see the sequence of partial sums $$1, \frac{3}{2}, \frac{7}{4}, \frac{15}{8},...$$ Clearly, this suggests a pattern - and if you want to, you can go ahead and prove it, I won't do so here for brevity's sake. The pattern is that the $n^{th}$ term of the sequence is $$S(n) = \frac{2^{(n+1)}-1}{2^{n}}$$ We can then easily consider the limit of these partial sums: $$\lim_{n\to\infty} S(n) = \lim_{n\to\infty} \frac{2^{(n+1)}-1}{2^{n}} = \lim_{n\to\infty} \frac{2^{(n+1)}}{2^{n}} - \frac {1}{2^{n}} = \lim_{n\to\infty} 2 - \lim_{n\to\infty} \frac{1}{2^{n}}$$ Obviously, $1/2^{n} \to 0$ as $n$ grows without bound, and $2$ is not affected by $n$ , so we conclude $$\lim_{n\to\infty} S(n) = \lim_{n\to\infty} 2 - \lim_{n\to\infty} \frac{1}{2^n} = 2 - 0 = 2$$ And thus we say $$\sum_{k=0}^\infty \left(\frac 1 2 \right)^k = 1 + \frac 1 2 + \frac 1 4 + \frac 1 8 + ... = 2$$ because the partial sums approach $2$ . On Continued Fractions: That was a simple, "first" sort of example, but mathematicians essentially do the same thing in other contexts. I want to touch on one more such context before we deal with the radical case, just to nail that point home. In this case, it will be with continued fractions . One of the simpler such fractions is the one for $1$ : $$1 = \frac{1}{2-\frac{1}{2-\frac{1}{2-\frac{1}{...}}}}$$ As usual, the "..." denotes that this continues forever. But what it does it mean for this infinite expression to equal $1$ ? For this, we consider a more general analogue of the "partial sum" from before - a "convergent." We cut up the sequence at logical finite points, whatever those points being depending on the context. Then if the sequence of the convergents approaches a limit, we say they're equal. What are the convergents for a continued fraction? By convention, we cut off just before the start of the next fraction. That is, in the continued fraction for $1$ , we cut off at the $n^{th} \; 2$ for the $n^{th}$ convergent, and ignore what follows. So we get the sequence of convergents $$\frac{1}{2} , \frac{1}{2-\frac{1}{2}}, \frac{1}{2-\frac{1}{2-\frac{1}{2}}},...$$ Working out the numbers, we find the sequence to be $$\frac{1}{2},\frac{2}{3},\frac{3}{4},...$$ Again, we see a pattern! The $n^{th}$ term of the sequence is clearly of the form $$\frac{n-1}{n}$$ Let $C(n)$ be a function denoting the $n^{th}$ convergent. Then $C(1)=1/2,$ $C(2) = 2/3,$ $C(n)=(n-1)/n,$ and so on. So like before we consider the infinite limit: $$\lim_{n\to\infty} C(n) = \lim_{n\to\infty} \frac{n-1}{n} = \lim_{n\to\infty} 1 - \frac 1 n = \lim_{n\to\infty} 1 - \lim_{n\to\infty} \frac 1 n = 1 - 0 = 1$$ Thus we can conclude that the continued fraction equals $1$ , because its sequence of convergents equals $1$ ! On Infinite Radicals: So now, we touch on infinite nested radicals. They're messier to deal with but doable. One of the simpler examples of such radicals to contend with is $$2 = \sqrt{2 +\sqrt{2 +\sqrt{2 +\sqrt{2 +\sqrt{2 +...}}}}}$$ As with the previous two cases we see an infinite expression. We instinctively conclude by now: to logically define a limit for this expression - to assign it a value provided it even exists - we need to chop this up at finite points, defining a sequence of convergents $C(n)$ , and then find $C(n)$ as $n\to\infty$ . Nested radicals are a lot messier than the previous, but we manage. So first let the sequence of convergents be given by cutting off everything after the $n^{th} \; 2$ in the expression. Thus we get the sequence $$\sqrt 2 \;\;,\;\; \sqrt{2 + \sqrt{2}}\;\;,\;\; \sqrt{2+\sqrt{2+\sqrt{2}}}\;\;,\;\; \sqrt{2+\sqrt{2+\sqrt{2+\sqrt{2}}}}$$ Okay this isn't particularly nice already, but apparently there does exist, shockingly enough, a closed-form explicit expression for $C(n)$ : (from: S. Zimmerman, C. Ho) $$C(n) = 2\cos\left(\frac{\pi}{2^{n+1}}\right)$$ (I had to find that expression by Googling, I honestly didn't know that offhand. It can be proved by induction, as touched on in this MSE question .) So luckily, then, we can find the limit of $C(n)$ : $$\lim_{n\to\infty} C(n) = \lim_{n\to\infty} 2\cos\left(\frac{\pi}{2^{n+1}}\right)$$ It is probably obvious that the argument of the cosine function approaches $0$ as $n$ grows without bound, and thus $$\lim_{n\to\infty} C(n) = \lim_{n\to\infty} 2\cos\left(\frac{\pi}{2^{n+1}}\right) = 2\cos(0) = 2\cdot 1 = 2$$ Thus, since its convergents approach $2$ , we can conclude that $$2 = \sqrt{2 +\sqrt{2 +\sqrt{2 +\sqrt{2 +\sqrt{2 +...}}}}}$$ A Lengthy Conclusion: So, in short, how do we evaluate an infinite expression, be it radical, continued fraction, sum, or otherwise? We begin by truncating the expression at convenient finite places, creating a series of convergents, generalizations of the "partial sums" introduced in calculus. We then try to get a closed form or some other usable expression for the convergents $C(n)$ , and consider the value as $n\to\infty$ . If it converges to some value, we say that the expression is in fact equal to that value. If it doesn't, then the expression doesn't converge to any value. This doesn't mean each expression is "nice." Radical expressions in particular, in my experience, tend to be nasty as all hell, and I'm lucky I found that one closed form expression for the particularly easy radical I chose. This doesn't mean that other methods cannot be used to find the values, so long as there's some sort of logical justification for said method. For example, there is a justification for the formula for an infinite (and finite) geometric sum. We might have to circumvent the notion of partial sums entirely, or at least it might be convenient to do so. For example, with the Basel problem, Euler's proof focused on Maclaurin series, and none of this "convergent" stuff. (That proof is here plus other proofs of it!) Luckily, at least, this notion of convergents, even if it may not always be the best way to do it, lends itself to an easy way to check a solution to any such problem. Just find a bunch of the convergents - take as many as you need. If you somehow have multiple solutions, as you think with Ramanujan's radical, then you'll see the convergents get closer and closer to the "true" solution. (How many convergents you need to find depends on the situation and how close your proposed solutions are. It might be immediately obvious after $10$ iterations, or might not be until $10,000,000$ . This logic also relies on the assumption that there is only one solution to a given expression that is valid. Depending on the context, you might see cases where multiple solutions are valid but this "approaching by hand" method will only get you some of the solutions. This touches on the notion of "unstable" and "stable" solutions to dynamical systems - which I believe is the main context where such would pop up - but it's a bit overkill to discuss that for this post.) So I will conclude by showing, in this way, that the solution is $3$ to Ramanujan's radical. We begin with the radical itself: $$\sqrt{1+2\sqrt{1+3\sqrt{1+4\sqrt{1+\cdots}}}}=3$$ Let us begin by getting a series of convergents: $$\sqrt{1} \;\;,\;\; \sqrt{1 + 2\sqrt{1}} \;\;,\;\; \sqrt{1 + 2\sqrt{1 + 3\sqrt{1}}} \;\;,\;\;$$ Because the $\sqrt{1}$ isn't necessary, we just let it be $1$ . $$1 \;\;,\;\; \sqrt{1 + 2} \;\;,\;\; \sqrt{1 + 2\sqrt{1 + 3}} \;\;,\;\;$$ Okay so ... where to go from here? Honestly, my initial temptation was to just use a MATLAB script and evaluate it, but I can't think of even a recursive closed form for this that would be nice enough. So in any event, we just have to go by "hand" (and by hand I mean WolframAlpha). Let $C(n)$ be the $n^{th}$ convergent. Then $C(1) = 1$ $C(2) \approx 1.732$ $C(3) \approx 2.236$ $C(4) \approx 2.560$ $C(5) \approx 2.755$ $C(6) \approx 2.867$ $C(7) \approx 2.929$ $C(8) \approx 2.963$ $C(9) \approx 2.981$ $C(10) \approx 2.990$ To skip a few values because at this point the changes get minimal, I used a macro to make a quick code for $C(50)$ so I could put it into Microsoft Excel and got the approximate result $$C(50) \approx 2.999 \; 999 \; 999 \; 999 \; 99$$ So while not the most rigorous result, we can at least on an intuitive level feel like the convergents from Ramanujan's radical converge to $3$ , not $4$ or any other number. Neglecting that this is not an ironclad proof of the convergence, at least intuitively then we can feel like $$3 = \sqrt{1+2\sqrt{1+3\sqrt{1+4\sqrt{1+\cdots}}}}$$ Whew! Hopefully that lengthy post was helpful to you! A late footnote, but Mathologer on YouTube did a video on this very topic, so his video would give a decent summary of all this stuff as well. Here's a link.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/3119631', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/592397/']}
jdg_375877
stackexchange
llm_judgeable_groundtruth_similarity
23691564
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 trying to install Cython for Python 2.7 on my Window 7 system. In particular, I prefer everything in 64 bits. (In case you wonder, I need Cython because Cython is one of the components I need for another package for some specialized numerical analysis. And x64 is potentially an advantage for storage of large data sets.) So I downloaded the x64 Python 2.7 from the official website. Got Cython from Christoph Gohlke . The amd64 version for Python 2.7 of course. Before I installed, I added Python 2.7 into the registry with the .reg file found in Joe DF's answer here . Afterwards, I installed the Visual C++ compiler from here (I don't think it works) and here (but this one should). At this point, I have in my C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin directory all of vcvars32.bat , vcvars64.bat , vcvars86_amd64.bat , vcvarsx86_ia64.bat . I ran vcvars64.bat and there was no error message. Subsequently, I followed this page to create a "hello world" test file. Then, I got this error. ...\Tests>python setup.py build_ext --inplacerunning build_extbuilding 'hello' extensionerror: Unable to find vcvarsall.bat So I thought to myself: Well, Cython can't find that file because it does not exist. (I searched my whole harddrive for it.) So I copied vcvars64.bat from ...\VC\bin to \VC and changed the name to vcvarsall.bat . Now vcvarsall error is gone. And ... naturally, a new error emerges. ...\Tests>python setup.py build_ext --inplacerunning build_extbuilding 'hello' extensionC:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tchello.c /Fobuild\temp.win-amd64-2.7\Release\hello.objhello.cC:\Python27\include\pyconfig.h(227) : fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directoryerror: command '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\cl.exe"' failed with exit status 2 Now I have no idea how to proceed. What should I do? Your help is much appreciated. (For clarity, I did try setting the compiler to Mingw32. But there are other errors. I am focusing on getting VC to work for now.) EDIT: I tried using the SDK build environment CMD following the instructions on this page . I received the same error. Now provide the response and nothing else.
I encountered this problem while trying to install pandas in 'develop' mode. I'm up & running now. My environment: Windows XP Pro x64 SP2 WinPython 64bit 2.7.5.3 (Python 2.7.5.amd64) <-- "registered" as system's python distro using WinPython Control Panel application Problems encountered when running python setup.py develop : Unable to find vcvarsall.bat fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory ... exit code 2 Solution: Download and install Microsoft Visual C++ 2008 Express. Download and install Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1. You will need only: Developer Tools > Windows Headers and Libraries <-- this gives you basetsd.h Developer Tools > Visual C++ Compilers <-- this gives you the 64-bit compilers Copy C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvars64.bat to C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\amd64\vcvarsamd64.bat . Observe the change in file name. Add C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin to PATH . This may not be required (I did so before re-installing the SDK w/ Headers & Libs; therefore, the necessity is unknown). At this point, running python setup.py develop completed successfully and python -c "import pandas; print pandas.__version__" resulted in the git tag I expected. [EDIT] Further reading: error: Unable to find vcvarsall.bat answer if you just want binaries to install answer if you want to compile on x64 machine answer about the file location/name change distutils issue 7511
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23691564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3181104/']}
jdg_375878
stackexchange
llm_judgeable_groundtruth_similarity
29248585
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Signature of isdigit int isdigit(int c); Signature of atoi int atoi(const char *nptr); I just wanted to check whether the command line argument passed was an integer or not.Here is the C Code: #include <stdio.h>#include <stdlib.h>#include <ctype.h>int main(int argc, char *argv[]){ if (argc == 1) return -1; printf ("Hai, you have executed the program : %s\n", argv[0]); if (isdigit(atoi(argv[1]))) printf ("%s is a number\n", argv[1]); else printf ("%s is not a number\n", argv[1]); return 0;} But the output is not as expected, when I am passing a valid number: $ ./a.out 123Hai, you have executed the program : ./a.out123 is not a number$ ./a.out addHai, you have executed the program : ./a.outadd is not a number I couldn't figure out the error. Now provide the response and nothing else.
When you refer argv[1] , it refers to a character array containing value 123 . isdigit function is defined for a single character input. So to handle with this situation, it is better to define a function as follows: bool isNumber(char number[]){ int i = 0; //checking for negative numbers if (number[0] == '-') i = 1; for (; number[i] != 0; i++) { //if (number[i] > '9' || number[i] < '0') if (!isdigit(number[i])) return false; } return true;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29248585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1929187/']}
jdg_375879
stackexchange
llm_judgeable_groundtruth_similarity
28254431
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 started a small Android project to re-learn a bit of Android development, and I'm already stuck... I do not know how to implement the deletetion of an element of my ListView ! Here is the project: https://github.com/gdurelle/Listify Right now it aims at showing a list of lists of elements. I use a custom CursorAdapter to show my list of elements, and I already have a (ugly) destroy button, but I do not know how to make it delete an actual element from the list (and the database). I use ActiveAndroid to manage the database in the ActiveRecord way. Plus: I'm not sure wether or not to use getView() , bindView() , and/or newView() ... I created an issue to remember this and reference this question here: https://github.com/gdurelle/Listify/issues/1 public class ListifyCursorAdapter extends CursorAdapter { public String content; public ListifyCursorAdapter(Context context, Cursor cursor) { super(context, cursor, 0); } // The newView method is used to inflate a new view and return it, you don't bind any data to the view at this point. @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.element_line, parent, false); } // The bindView method is used to bind all data to a given view such as setting the text on a TextView. @Override public void bindView(View view, Context context, Cursor cursor) { // Find fields to populate in inflated template TextView tvBody = (TextView) view.findViewById(R.id.element_content); // Extract properties from cursor content = cursor.getString(cursor.getColumnIndexOrThrow("content")); // Populate fields with extracted properties tvBody.setText(content); }} And in my MainActivity : Cursor cursor = ListifyElement.fetchResultCursor(); adapter = new ListifyCursorAdapter(this, cursor); listView.setAdapter(adapter); I was thinking maybe about a: Button delete_button = (Button) listView.findViewById(R.id.delete_button); with something like ListifyElement.load(ListifyElement.class, the_id_of_the_element).delete(); where the_id_of_the_element would be the DB's id of the element retrieived somehow from the click on it's delete_button in the UI... UPDATE : @Overridepublic void bindView(View view, Context context, final Cursor cursor) { // Find fields to populate in inflated template TextView tvBody = (TextView) view.findViewById(R.id.element_content); // Extract properties from cursor content = cursor.getString(cursor.getColumnIndexOrThrow("content")); // Populate fields with extracted properties tvBody.setText(content); Button delete_button = (Button) view.findViewById(R.id.delete_button); delete_button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ System.out.println(cursor.getColumnName(0)); // Id System.out.println(cursor.getColumnName(1)); // ListifyContainer System.out.println(cursor.getColumnName(2)); // content System.out.println(cursor.getColumnIndexOrThrow("Id")); // 0 ListifyElement.load(ListifyElement.class, cursor.getColumnIndexOrThrow("Id")).delete(); notifyDataSetChanged(); } }); I get this error when I click the delete button: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gdurelle.listify.models.ListifyElement.delete()' on a null object reference Now provide the response and nothing else.
The Schema http://www.springframework.org/schema/util/spring-util.xsd , http://www.springframework.org/schema/util/spring-util-3.1.xsd (and the one with the versions) come with spring-beans-<version>.RELEASE.jar Add this jar to your dependencies: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.1.2.RELEASE</version> </dependency> The problem with maven-assembly-plugin: You wrote: I also use the maven-assembly-plugin to create a executable jar file. Ah... I guess that the maven-assembly-plugin is the cause for that problem. This is because the schema resolution mechanism works this way: Spring provides the XSD files with there jars. Within the jar, in the folder META-INF is a file schema.info . This file contains a listing of all XSD fiels and there locations (in the jar) provided by this jar. example: spring.schema of spring-beans-3.1.1.RELEASE.jar http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsdhttp\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsdhttp\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsdhttp\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsdhttp\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsdhttp\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsdhttp\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsdhttp\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsdhttp\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsdhttp\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsdhttp\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsdhttp\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsdhttp\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsdhttp\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsdhttp\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd So and now you have different jars ( spring-beans , spring-tx , spring-aop , spring-context ...) , that all contains a META-INF/spring.schemas file, with different content. On the other hand you use maven-assembly-plugin to aggregate the content of all the jar files in a single one. I guess you will have this problem with the spring.handlers file too. It looks like you can configure the maven-assembly-plugin to merge this files. see: this answer of How can I merge resource files in a Maven assembly? An alternative solution would using the spring-boot-maven-plugin instead of maven-assembly-plugin <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> <configuration> <mainClass>YOUR.MAIN.CLASS</mainClass> </configuration> </plugin> (or use the maven-shade-pluging )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28254431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/816534/']}
jdg_375880
stackexchange
llm_judgeable_groundtruth_similarity
56939
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $X$ be a linearly ordered topological space with a countable dense subset. Does it necessarily follow that $X$ is metrizable? EDIT: Apollo's comment int he answers implies the answer is negative. Let $X$ be the open unit interval $(0,1)$ and adjoin to every real number $x$ a "ghost number" $x'$ such that $x'$ is the immediate successor of $x$. The "real rationals" are dense in this space. Simply note that sets of the form $(y, x]$ with $x$ and $y$ real and $[x',y)$ with $x'$ ghost and $y$ real form a basis, and these sets all contain a real rational. This space cannot be metrizable, because the subspace topology on the set of all ghost reals is exactly that of the Sorgenfrey line. Now provide the response and nothing else.
You already found a (classical) counterexample: the double arrow ($[0,1] \times \{0,1\}$, ordered lexicographically), which is even compact and separable. There is however a nice metrization theorem for linearly ordered spaces (due to Lutzer ): a linearly ordered space $X$ is metrizable (in the order topology) iff the diagonal $D = \{(x,x) : x \in X\}$ is a countable intersection of open subsets of $X \times X$ (a $G_\delta$). This condition is also necessary and sufficient for countably compact regular spaces as well, not just the ordered ones.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/56939', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4903/']}
jdg_375881
stackexchange
llm_judgeable_groundtruth_similarity
8059065
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 some data in mysql that I load up in php and draw a line chart using the google chart api. Here is part of the code: // ... do a sql query , then loop and create a chart ...while($row=mysql_fetch_array($result)){$values[0][]=$row['v1'];$values[1][]=$row['v2'];}$width=600;$height=500;$scaleMin=0;$scaleMax=99;$chart = new GoogleChart('lc', $width,$height );$chart->setAutoscale(GoogleChart::AUTOSCALE_OFF);// ... other google chart setup code$line = new GoogleChartData($values[0]);$line->setAutoscale(false);$line->setScale($scaleMin,$scaleMax);$line->setLegend('value1');$chart->addData($line);$line = new GoogleChartData($values[1]);$line->setAutoscale(false);$line->setScale($scaleMin,$scaleMax);$line->setLegend('value2');$chart->addData($line);// ... more lines and chart set up ...header('Content-Type: image/png');echo $chart; So that works fine, except that my "value1" or "v1" data will generally range from a minimum of 10 to a maximum of 90. My "value2" or "v2" data will start off at 0, and over time will increment - potentially to 100,000 or more. I am trying to figure out how to either set the google chart up so it will display it somehow, OR potentially alter the data in the array so it displays properly. Currently, it would draw a line, starting a 0, then hour by hour it would climb a little, forming a staircase-like shape. The problem is, it eventually goes past 99, and you have no more line, or similar. Just looking for some thoughts. Now provide the response and nothing else.
Sounds like you want a variant of scanl , which is related to foldl , but creates a list of intermediate results. So while foldl (+) 0 sums a list, scanl (+) 0 creates a list of partial sums. Here, you probably want scanl1 (+) , which doesn't add an extra zero at the beginning. Prelude> scanl1 (+) [0, 2, 5, 9][0,2,7,16]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8059065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/158438/']}
jdg_375882
stackexchange
llm_judgeable_groundtruth_similarity
33106709
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 having a problem getting the POST data from a Facebook action. When you submit a comment on FB it posts to this url: https://www.facebook.com/ufi/add/comment/?__pc=EXP1%3ADEFAULT In the request, the post data for the post exists: Here is an example of the actual comment from the post data: comment_text:test this is a test When I try to access this through a Chrome Extension I can't seem to get this data. I've tried parsing the requestBody, but it is empty. I then tried to see if any of the other requestmethods would work, and I can't seem to find the data anywhere. manifest.json: {"background": { "scripts": [ "background.js" ] },"manifest_version": 2,"name": "Interaction Tracker","description": "Track social interactions by social site and customizable categories.","version": "1.0","browser_action": { "default_icon": "icon.png", "default_popup": "popup.html"},"permissions": [ "webRequest", "webRequestBlocking", "webNavigation", "tabs", "<all_urls>", "debugger" ]} background.js chrome.webRequest.onBeforeRequest.addListener( function(details) { if (details.method == "POST") { var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*"); if ( fb_add_comment_regex.test(details.url) ) { console.log(JSON.stringify(details)); } } }, {urls: ["<all_urls>"]}, ["blocking", "requestBody"] );chrome.webRequest.onBeforeSendHeaders.addListener( function(details) { if (details.method == "POST") { var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*"); if ( fb_add_comment_regex.test(details.url) ) { console.log(JSON.stringify(details)); } } }, {urls: ["<all_urls>"]}, ["blocking", "requestHeaders"] );chrome.webRequest.onSendHeaders.addListener( function(details) { if (details.method == "POST") { var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*"); if ( fb_add_comment_regex.test(details.url) ) { console.log(JSON.stringify(details)); } } }, {urls: ["<all_urls>"]}, ["requestHeaders"] );chrome.webRequest.onHeadersReceived.addListener( function(details) { if (details.method == "POST") { var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*"); if ( fb_add_comment_regex.test(details.url) ) { console.log(JSON.stringify(details)); } } }, {urls: ["<all_urls>"]}, ["blocking", "responseHeaders"] );chrome.webRequest.onAuthRequired.addListener( function(details) { if (details.method == "POST") { var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*"); if ( fb_add_comment_regex.test(details.url) ) { console.log(JSON.stringify(details)); } } }, {urls: ["<all_urls>"]}, ["blocking", "responseHeaders"] );chrome.webRequest.onResponseStarted.addListener( function(details) { if (details.method == "POST") { var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*"); if ( fb_add_comment_regex.test(details.url) ) { console.log(JSON.stringify(details)); } } }, {urls: ["<all_urls>"]}, ["responseHeaders"] );chrome.webRequest.onBeforeRedirect.addListener( function(details) { if (details.method == "POST") { var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*"); if ( fb_add_comment_regex.test(details.url) ) { console.log(JSON.stringify(details)); } } }, {urls: ["<all_urls>"]}, ["responseHeaders"] );chrome.webRequest.onCompleted.addListener( function(details) { if (details.method == "POST") { var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*"); if ( fb_add_comment_regex.test(details.url) ) { console.log(JSON.stringify(details)); } } }, {urls: ["<all_urls>"]}, ["responseHeaders"] ); Below is the output from the console.log statements for each type of request: onBeforeRequest { "frameId": 0, "method": "POST", "parentFrameId": -1, "requestBody": { "raw": [ { "bytes": { } } ] }, "requestId": "6724", "tabId": 93, "timeStamp": 1444749653166.1, "type": "xmlhttprequest", "url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"} onBeforeSendHeaders { "frameId": 0, "method": "POST", "parentFrameId": -1, "requestHeaders": [ { "name": "Origin", "value": "https:\/\/www.facebook.com" }, { "name": "X-DevTools-Emulate-Network-Conditions-Client-Id", "value": "AB63796C-002A-4670-8A56-547F8D13CA8C" }, { "name": "User-Agent", "value": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/45.0.2454.101 Safari\/537.36" }, { "name": "Content-Type", "value": "application\/x-www-form-urlencoded" }, { "name": "Accept", "value": "*\/*" }, { "name": "Referer", "value": "https:\/\/www.facebook.com\/GrauZug?ref=br_rs" }, { "name": "Accept-Encoding", "value": "gzip, deflate" }, { "name": "Accept-Language", "value": "en-US,en;q=0.8" }, { "name": "Cookie", "value": "datr=pvA2VDnTeMjGlWhVYRrnhBtO; lu=gh2TS-IuZkO-Ku-YhAzkiFIw; p=-2; c_user=100000720140344; fr=07LqqXcCamvBIa9Ww.AWU6e_qoHRglPj51gS-CF6uF-r8.BVY1Qk.DT.FYB.0.AWVvgvJA; xs=79%3A403i2b7V6bYSIA%3A2%3A1439311770%3A8344; csm=2; s=Aa4bsJIf94u-JaGr.BVyieb; presence=EDvF3EtimeF1444749507EuserFA21B00720140344A2EstateFDsb2F1444656454966Et2F_5b_5dElm2FnullEuct2F1444743344BEtrFnullEtwF2707054892EatF1444748467285G444749507665CEchFDp_5f1B00720140344F101CC; act=1444749649564%2F26" } ], "requestId": "6724", "tabId": 93, "timeStamp": 1444749653173.2, "type": "xmlhttprequest", "url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"} onSendHeaders { "frameId": 0, "method": "POST", "parentFrameId": -1, "requestHeaders": [ { "name": "Origin", "value": "https:\/\/www.facebook.com" }, { "name": "X-DevTools-Emulate-Network-Conditions-Client-Id", "value": "AB63796C-002A-4670-8A56-547F8D13CA8C" }, { "name": "User-Agent", "value": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/45.0.2454.101 Safari\/537.36" }, { "name": "Content-Type", "value": "application\/x-www-form-urlencoded" }, { "name": "Accept", "value": "*\/*" }, { "name": "Referer", "value": "https:\/\/www.facebook.com\/GrauZug?ref=br_rs" }, { "name": "Accept-Encoding", "value": "gzip, deflate" }, { "name": "Accept-Language", "value": "en-US,en;q=0.8" }, { "name": "Cookie", "value": "datr=pvA2VDnTeMjGlWhVYRrnhBtO; lu=gh2TS-IuZkO-Ku-YhAzkiFIw; p=-2; c_user=100000720140344; fr=07LqqXcCamvBIa9Ww.AWU6e_qoHRglPj51gS-CF6uF-r8.BVY1Qk.DT.FYB.0.AWVvgvJA; xs=79%3A403i2b7V6bYSIA%3A2%3A1439311770%3A8344; csm=2; s=Aa4bsJIf94u-JaGr.BVyieb; presence=EDvF3EtimeF1444749507EuserFA21B00720140344A2EstateFDsb2F1444656454966Et2F_5b_5dElm2FnullEuct2F1444743344BEtrFnullEtwF2707054892EatF1444748467285G444749507665CEchFDp_5f1B00720140344F101CC; act=1444749649564%2F26" } ], "requestId": "6724", "tabId": 93, "timeStamp": 1444749653175.2, "type": "xmlhttprequest", "url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"} onHeadersReceived { "frameId": 0, "method": "POST", "parentFrameId": -1, "requestId": "6724", "responseHeaders": [ { "name": "status", "value": "200" }, { "name": "cache-control", "value": "private, no-cache, no-store, must-revalidate" }, { "name": "content-encoding", "value": "gzip" }, { "name": "content-security-policy", "value": "default-src * data: blob:;script-src *.facebook.com *.fbcdn.net *.facebook.net *.google-analytics.com *.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:* 'unsafe-inline' 'unsafe-eval' *.akamaihd.net *.atlassolutions.com blob: chrome-extension:\/\/lifbcibllhkdhoafpjfnlhfpfgnpldfl;style-src * 'unsafe-inline';connect-src *.facebook.com *.fbcdn.net *.facebook.net *.spotilocal.com:* *.akamaihd.net wss:\/\/*.facebook.com:* https:\/\/fb.scanandcleanlocal.com:* *.atlassolutions.com attachment.fbsbx.com 127.0.0.1:*;" }, { "name": "content-type", "value": "application\/x-javascript; charset=utf-8" }, { "name": "date", "value": "Tue, 13 Oct 2015 15:20:55 GMT" }, { "name": "expires", "value": "Sat, 01 Jan 2000 00:00:00 GMT" }, { "name": "pragma", "value": "no-cache" }, { "name": "public-key-pins-report-only", "value": "max-age=500; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"r\/mIkG3eEpVdm+u\/ko\/cwxzOMo1bk4TyHIlByibiA5E=\"; pin-sha256=\"q4PO2G2cbkZhZ82+JgmRUyGMoAeozA+BSXVXQWB8XWQ=\"; report-uri=\"http:\/\/reports.fb.com\/hpkp\/\"" }, { "name": "strict-transport-security", "value": "max-age=15552000; preload" }, { "name": "vary", "value": "Accept-Encoding" }, { "name": "x-content-type-options", "value": "nosniff" }, { "name": "x-fb-debug", "value": "fd7Bt\/uIX2rLmngndhprmXlX3mTkZboQqcPSaw9kQt0aQUEfX3ikBMT1016i1c2RPbts9Jhbb0+bVGWPqk\/j7Q==" }, { "name": "x-frame-options", "value": "DENY" }, { "name": "x-xss-protection", "value": "0" } ], "statusCode": 200, "statusLine": "HTTP\/1.1 200 OK", "tabId": 93, "timeStamp": 1444749655679.6, "type": "xmlhttprequest", "url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"} onResponseStarted { "frameId": 0, "fromCache": false, "ip": "31.13.93.3", "method": "POST", "parentFrameId": -1, "requestId": "6724", "responseHeaders": [ { "name": "status", "value": "200" }, { "name": "cache-control", "value": "private, no-cache, no-store, must-revalidate" }, { "name": "content-encoding", "value": "gzip" }, { "name": "content-security-policy", "value": "default-src * data: blob:;script-src *.facebook.com *.fbcdn.net *.facebook.net *.google-analytics.com *.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:* 'unsafe-inline' 'unsafe-eval' *.akamaihd.net *.atlassolutions.com blob: chrome-extension:\/\/lifbcibllhkdhoafpjfnlhfpfgnpldfl;style-src * 'unsafe-inline';connect-src *.facebook.com *.fbcdn.net *.facebook.net *.spotilocal.com:* *.akamaihd.net wss:\/\/*.facebook.com:* https:\/\/fb.scanandcleanlocal.com:* *.atlassolutions.com attachment.fbsbx.com 127.0.0.1:*;" }, { "name": "content-type", "value": "application\/x-javascript; charset=utf-8" }, { "name": "date", "value": "Tue, 13 Oct 2015 15:20:55 GMT" }, { "name": "expires", "value": "Sat, 01 Jan 2000 00:00:00 GMT" }, { "name": "pragma", "value": "no-cache" }, { "name": "public-key-pins-report-only", "value": "max-age=500; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"r\/mIkG3eEpVdm+u\/ko\/cwxzOMo1bk4TyHIlByibiA5E=\"; pin-sha256=\"q4PO2G2cbkZhZ82+JgmRUyGMoAeozA+BSXVXQWB8XWQ=\"; report-uri=\"http:\/\/reports.fb.com\/hpkp\/\"" }, { "name": "strict-transport-security", "value": "max-age=15552000; preload" }, { "name": "vary", "value": "Accept-Encoding" }, { "name": "x-content-type-options", "value": "nosniff" }, { "name": "x-fb-debug", "value": "fd7Bt\/uIX2rLmngndhprmXlX3mTkZboQqcPSaw9kQt0aQUEfX3ikBMT1016i1c2RPbts9Jhbb0+bVGWPqk\/j7Q==" }, { "name": "x-frame-options", "value": "DENY" }, { "name": "x-xss-protection", "value": "0" } ], "statusCode": 200, "statusLine": "HTTP\/1.1 200 OK", "tabId": 93, "timeStamp": 1444749655683.3, "type": "xmlhttprequest", "url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"} onCompleted { "frameId": 0, "fromCache": false, "ip": "31.13.93.3", "method": "POST", "parentFrameId": -1, "requestId": "6724", "responseHeaders": [ { "name": "status", "value": "200" }, { "name": "cache-control", "value": "private, no-cache, no-store, must-revalidate" }, { "name": "content-encoding", "value": "gzip" }, { "name": "content-security-policy", "value": "default-src * data: blob:;script-src *.facebook.com *.fbcdn.net *.facebook.net *.google-analytics.com *.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:* 'unsafe-inline' 'unsafe-eval' *.akamaihd.net *.atlassolutions.com blob: chrome-extension:\/\/lifbcibllhkdhoafpjfnlhfpfgnpldfl;style-src * 'unsafe-inline';connect-src *.facebook.com *.fbcdn.net *.facebook.net *.spotilocal.com:* *.akamaihd.net wss:\/\/*.facebook.com:* https:\/\/fb.scanandcleanlocal.com:* *.atlassolutions.com attachment.fbsbx.com 127.0.0.1:*;" }, { "name": "content-type", "value": "application\/x-javascript; charset=utf-8" }, { "name": "date", "value": "Tue, 13 Oct 2015 15:20:55 GMT" }, { "name": "expires", "value": "Sat, 01 Jan 2000 00:00:00 GMT" }, { "name": "pragma", "value": "no-cache" }, { "name": "public-key-pins-report-only", "value": "max-age=500; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"r\/mIkG3eEpVdm+u\/ko\/cwxzOMo1bk4TyHIlByibiA5E=\"; pin-sha256=\"q4PO2G2cbkZhZ82+JgmRUyGMoAeozA+BSXVXQWB8XWQ=\"; report-uri=\"http:\/\/reports.fb.com\/hpkp\/\"" }, { "name": "strict-transport-security", "value": "max-age=15552000; preload" }, { "name": "vary", "value": "Accept-Encoding" }, { "name": "x-content-type-options", "value": "nosniff" }, { "name": "x-fb-debug", "value": "fd7Bt\/uIX2rLmngndhprmXlX3mTkZboQqcPSaw9kQt0aQUEfX3ikBMT1016i1c2RPbts9Jhbb0+bVGWPqk\/j7Q==" }, { "name": "x-frame-options", "value": "DENY" }, { "name": "x-xss-protection", "value": "0" } ], "statusCode": 200, "statusLine": "HTTP\/1.1 200 OK", "tabId": 93, "timeStamp": 1444749655684.2, "type": "xmlhttprequest", "url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"} Any other listener not listed above didn't have output. Anyone have any idea here? Now provide the response and nothing else.
Your console.log shows that requestBody is not empty. You'll just have to parse the raw bytes: If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array. For example if the posted data is a string then you can get its value in onBeforeRequest listener : var postedString = decodeURIComponent(String.fromCharCode.apply(null, new Uint8Array(details.requestBody.raw[0].bytes))); There are many methods to decode the string depending on the encoding used by the site script.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33106709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1742573/']}
jdg_375883
stackexchange
llm_judgeable_groundtruth_similarity
1399275
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 function that essentially reads values in from a vector of doubles, appends these to a string (while ensuring a space between each and setting their precisions) and returns the end result, minus the final whitespace: std::string MultiplePrintProperties::GetHpitchString() { std::string str; vector< double >::iterator it; for ( it = Vals.begin(); it != Vals.end(); it++ ) { ostringstream s; // Set precision to 3 digits after the decimal point // and read into the string boost::format fmt( "%.3f " ); s << fmt % *( it ); str.append( s.str() ); } // Remove last white space and return string return str.substr( 0, str.length() - 1 ); } I would like to find out if this code could be simplified in any way. I have recently been investigating the use of for_each and functors in particular but have not been able to figure out how these techniques could improve this particular example. Now provide the response and nothing else.
Since you're actually transforming doubles into strings, and appending these strings to a stringstream, you can use std::transform for that: // your functor, transforming a double into a stringstruct transform_one_double { std::string operator()( const double& d ) const { boost::format fmt( "%.3f " ); return (fmt % d).str(); }};// iteration code, taking each value and inserting the transformed// value into the stringstream.std::transform( vals.begin(), vals.end() , std::ostream_iterator<std::string>( s, " ") , transform_one_double() );
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1399275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6795/']}
jdg_375884
stackexchange
llm_judgeable_groundtruth_similarity
2726993
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 compiling a c++ program using g++ and ld . I have a .so library I want to be used during linking. However, a library of the same name exists in /usr/local/lib , and ld is choosing that library over the one I'm directly specifying. How can I fix this? For the examples below, my library file is /my/dir/libfoo.so.0 . Things I've tried that don't work: my g++ command is g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp adding /my/dir to the beginning or end of my $PATH en` variable adding /my/dir/libfoo.so.0 as an argument to g++ Now provide the response and nothing else.
Add the path to where your new library is to LD_LIBRARY_PATH (it has slightly different name on Mac ...) Your solution should work with using the -L/my/dir -lfoo options, at runtime use LD_LIBRARY_PATH to point to the location of your library. Careful with using LD_LIBRARY_PATH - in short (from link): ..implications..: Security : Remember that the directories specified in LD_LIBRARY_PATH get searched before(!) the standard locations? In that way, a nasty person could get your application to load a version of a shared library that contains malicious code! That’s one reason why setuid/setgid executables do neglect that variable! Performance : The link loader has to search all the directories specified, until it finds the directory where the shared library resides – for ALL shared libraries the application is linked against! This means a lot of system calls to open(), that will fail with “ENOENT (No such file or directory)”! If the path contains many directories, the number of failed calls will increase linearly, and you can tell that from the start-up time of the application. If some (or all) of the directories are in an NFS environment, the start-up time of your applications can really get long – and it can slow down the whole system! Inconsistency : This is the most common problem. LD_LIBRARY_PATH forces an application to load a shared library it wasn’t linked against, and that is quite likely not compatible with the original version. This can either be very obvious, i.e. the application crashes, or it can lead to wrong results, if the picked up library not quite does what the original version would have done. Especially the latter is sometimes hard to debug. OR Use the rpath option via gcc to linker - runtime library search path, will be usedinstead of looking in standard dir (gcc option): -Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH) This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories. If you don't want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line: LD_LIBRARY_PATH=/some/custom/dir ./fooo You can check what libraries linker knows about using (example): /sbin/ldconfig -p | grep libpthread libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0 And you can check which library your application is using: ldd foo linux-gate.so.1 => (0xffffe000) libpthread.so.0 => /lib/libpthread.so.0 (0xb7f9e000) libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e6e000) librt.so.1 => /lib/librt.so.1 (0xb7e65000) libm.so.6 => /lib/libm.so.6 (0xb7d5b000) libc.so.6 => /lib/libc.so.6 (0xb7c2e000) /lib/ld-linux.so.2 (0xb7fc7000) libdl.so.2 => /lib/libdl.so.2 (0xb7c2a000) libz.so.1 => /lib/libz.so.1 (0xb7c18000)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2726993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218386/']}
jdg_375885
stackexchange
llm_judgeable_groundtruth_similarity
42857897
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As per Docker documentation :There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect. I wish to execute a simple bash script(which processes docker environment variable) before the CMD command(which is init in my case). Is there any way to do this? Now provide the response and nothing else.
Use a custom entrypoint Make a custom entrypoint which does what you want, and then exec's your CMD at the end. NOTE : if your image already defines a custom entrypoint, you may need to extend it rather than replace it, or you may change behavior you need. entrypoint.sh : #!/bin/sh## Do whatever you need with env vars here ...# Hand off to the CMDexec "$@" Dockerfile : COPY entrypoint.sh /entrypoint.shRUN chmod 755 /entrypoint.shENTRYPOINT ["/entrypoint.sh"] Docker will run your entrypoint, using CMD as arguments. If your CMD is init , then: /entrypoint.sh init The exec at the end of the entrypoint script takes care of handing off to CMD when the entrypoint is done with what it needed to do. Why this works The use of ENTRYPOINT and CMD frequently confuses people new to Docker. In comments, you expressed confusion about it. Here is how it works and why. The ENTRYPOINT is the initial thing run inside the container. It takes the CMD as an argument list. Therefore, in this example, what is run in the container is this argument list: # ENTRYPOINT = /entrypoint.sh# CMD = init["/entrypoint.sh", "init"]# or shown in a simpler form:/entrypoint.sh init It is not required that an image have an ENTRYPOINT. If you don't define one, Docker has a default: /bin/sh -c . So with your original situation, no ENTRYPOINT, and using a CMD of init , Docker would have run this: /bin/sh -c 'init'^--------^ ^--^ | \------- CMD \--------------- ENTRYPOINT In the beginning, Docker offered only CMD, and /bin/sh -c was hard-coded as the ENTRYPOINT (you could not change it). At some point along the way, people had use cases where they had to do more custom things, and Docker exposed ENTRYPOINT so you could change it to anything you want. In the example I show above, the ENTRYPOINT is replaced with a custom script. (Though it is still ultimately being run by sh , because it starts with #!/bin/sh .) That ENTRYPOINT takes the CMD as is argument. At the end of the entrypoint.sh script is exec "$@" . Since $@ expands to the list of arguments given to the script, this is turned into exec "init" And therefore, when the script is finished, it goes away and is replaced by init as PID 1. (That's what exec does - it replaces the current process with a different command.) How to include CMD In the comments, you asked about adding CMD in the Dockerfile. Yes, you can do that. Dockerfile : CMD ["init"] Or if there is more to your command, e.g. arguments like init -a -b , would look like this: CMD ["init", "-a", "-b"]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42857897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124330/']}
jdg_375886
stackexchange
llm_judgeable_groundtruth_similarity
1025803
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the follwing class - I would like to know which of the both members is abstract: abstract class Test{ public abstract bool Abstract { get; set; } public bool NonAbstract { get; set; }}var type = typeof( Test );var abs = type.GetProperty( "Abstract" );var nonAbs = type.GetProperty( "NonAbstract" );// now, something like:if( abs.IsAbstract ) ... Unfortunately there is nothing like the IsAbstract -property. I need to select all non-abstract fields/properties/methods of a class - but there are no BindingFlags to narrow the selection, too. Now provide the response and nothing else.
A property is actually some 'syntactic sugar', and is implemented by 2 methods: a getter method and a setter method. So, I think that you should be able to determine if a property is abstract by checking if the getter and/or setter are abstract, like this: PropertyInfo pi = ...if( pi.GetSetMethod().IsAbstract ){} And, AFAIK, a field cannot be abstract. ;)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1025803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52444/']}
jdg_375887
stackexchange
llm_judgeable_groundtruth_similarity
264825
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 a console Java application which is supposed to run until it is stopped by Ctrl + C or closing the console window. How that application can be programmed to execute a clean up code before exit? Now provide the response and nothing else.
You could use a Shutdown Hook . Basically you need to create a Thread which will perform your shutdown actions, and then add it as a shutdown hook . For example: class ShutdownHook extends Thread{ public void run() { // perform shutdown actions }}// Then, somewhere in your codeRuntime.getRuntime().addShutdownHook(new ShutdownHook())
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/264825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31993/']}
jdg_375888
stackexchange
llm_judgeable_groundtruth_similarity
10207416
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I use the same key pair file across all regions? I want to keep the ssh access as simple as possible. I have set up one file for each region. I tried to upload the same file in different region but it did not not work as expected. Now provide the response and nothing else.
This has meanwhile been enabled by means of importing your own keypair(s), see the introductory post New Amazon EC2 Feature: Bring Your Own Keypair : You can now import your own RSA keypair (or the public half, to be precise) for use with your Amazon EC2 instances. Why would you want to do this? Here are a couple of reasons: Trust - By importing your own keypair you can ensure that you have complete control over your keys. Security -You can be confident that your private key has never been transmitted over the wire. Management of Multiple Regions - You can use the same public key across multiple AWS Regions. [emphasis mine] This approach is quite beneficial/convenient indeed - I'm using it for a while already, and it has considerably simplified EC2 usage across multiple regions and accounts. Eric Hammond provides more details and a short tutorial in his article Uploading Personal ssh Keys to Amazon EC2 : Amazon recently launched the ability to upload your own ssh public key to EC2 so that it can be passed to new instances when they are launched. Prior to this you always had to use an ssh keypair that was generated by Amazon. Accordingly, I recommend to follow his article regarding the (few and simple) steps required to achieve this.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10207416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139150/']}
jdg_375889
stackexchange
llm_judgeable_groundtruth_similarity
22759542
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 new to gradle (and so also to groovy) and I am hardly getting behind some concept and don't really know if it is groovy or gradle related and what keywords to google, to get some help. I very often stumble over stuff like: android { [some configuration]} So what is android? A class? A namespace? A collection of properties? But what is more confusing: Sometimes I see configurations that look like: minSdkVersion 19 This seems to be an assignment, but without an equal sign.And sometimes there are assignments with equal signs like source = "folder/file.java" So this is very confusing. Equal sign vs. no equal sign. All these bracket stuff. All the groovy introductions I saw don't cover exactly these topics.So is it some gradle convention or is it real groovy syntax? Now provide the response and nothing else.
In Groovy, parentheses are sometimes optional. The first android is passing a closure to a Method. ie: void android( Closure config ) { println "In Android : ${config()}"}android { 'tim'} prints : In Android : tim it is the same as calling: android( { 'tim'} ) If you put the parens back. The second example with minSdkVersion is the same, but it is passing an Integer to a method. void minSdkVersion( Integer version ) { println "In MinSdkVersion : $version"}minSdkVersion 19// same as minSdkVersion( 19 ) So that prints In MinSdkVersion : 19 The last example is setting a property to a String (as you'd expect)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22759542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1223777/']}
jdg_375890
stackexchange
llm_judgeable_groundtruth_similarity
51851485
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 creating a framework that allows me to use Core Data. In the framework's test target, I have configured a data model named MockModel.xcdatamodeld . It contains a single entity named MockManaged that has a single Date property. So that I can test my logic, I am creating an in-memory store. When I want to validate my saving logic, I create an instance of the in-memory store and use it. However, I keep getting the following output in the console: 2018-08-14 20:35:45.340157-0400 xctest[7529:822360] [error] warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'LocalPersistenceTests.MockManaged' so +entity is unable to disambiguate.CoreData: warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'LocalPersistenceTests.MockManaged' so +entity is unable to disambiguate.2018-08-14 20:35:45.340558-0400 xctest[7529:822360] [error] warning: 'MockManaged' (0x7f986861cae0) from NSManagedObjectModel (0x7f9868604090) claims 'LocalPersistenceTests.MockManaged'.CoreData: warning: 'MockManaged' (0x7f986861cae0) from NSManagedObjectModel (0x7f9868604090) claims 'LocalPersistenceTests.MockManaged'.2018-08-14 20:35:45.340667-0400 xctest[7529:822360] [error] warning: 'MockManaged' (0x7f986acc4d10) from NSManagedObjectModel (0x7f9868418ee0) claims 'LocalPersistenceTests.MockManaged'.CoreData: warning: 'MockManaged' (0x7f986acc4d10) from NSManagedObjectModel (0x7f9868418ee0) claims 'LocalPersistenceTests.MockManaged'.2018-08-14 20:35:45.342938-0400 xctest[7529:822360] [error] error: +[LocalPersistenceTests.MockManaged entity] Failed to find a unique match for an NSEntityDescription to a managed object subclassCoreData: error: +[LocalPersistenceTests.MockManaged entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass Below is the object I use to create my in-memory stores: class MockNSManagedObjectContextCreator { // MARK: - NSManagedObjectContext Creation static func inMemoryContext() -> NSManagedObjectContext { guard let model = NSManagedObjectModel.mergedModel(from: [Bundle(for: self)]) else { fatalError("Could not create model") } let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) do { try coordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) } catch { fatalError("Could not create in-memory store") } let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = coordinator return context }} Below is what makes up my MockManaged entity: class MockManaged: NSManagedObject, Managed { // MARK: - Properties @NSManaged var date: Date} Below is what makes up my XCTestCase : class Tests_NSManagedObjectContext: XCTestCase { // MARK: - Object Insertion func test_NSManagedObjectContext_InsertsManagedObject_WhenObjectConformsToManagedProtocol() { let context = MockNSManagedObjectContextCreator.inMemoryContext() let changeExpectation = expectation(forNotification: .NSManagedObjectContextObjectsDidChange, object: context, handler: nil) let object: MockManaged = context.insertObject() object.date = Date() wait(for: [changeExpectation], timeout: 2) } // MARK: - Saving func test_NSManagedObjectContext_Saves_WhenChangesHaveBeenMade() { let context = MockNSManagedObjectContextCreator.inMemoryContext() let saveExpectation = expectation(forNotification: .NSManagedObjectContextDidSave, object: context, handler: nil) let object: MockManaged = context.insertObject() object.date = Date() do { try context.saveIfHasChanges() } catch { XCTFail("Expected successful save") } wait(for: [saveExpectation], timeout: 2) } func test_NSManagedObjectContext_DoesNotSave_WhenNoChangesHaveBeenMade() { let context = MockNSManagedObjectContextCreator.inMemoryContext() let saveExpectation = expectation(forNotification: .NSManagedObjectContextDidSave, object: context, handler: nil) saveExpectation.isInverted = true do { try context.saveIfHasChanges() } catch { XCTFail("Unexpected error: \(error)") } wait(for: [saveExpectation], timeout: 2) }} What am I doing that is causing the errors in my tests? Now provide the response and nothing else.
Post-automatic-caching This should not happen anymore with NSPersistent[CloudKit]Container(name: String) , since it seems to cache the model automatically now (Swift 5.1, Xcode11, iOS13/MacOS10.15). Pre-automatic-caching NSPersistentContainer/NSPersistentCloudKitContainer does have two constructors: init(name: String) init(name: String,managedObjectModel model: NSManagedObjectModel) The first is just a convenience initializer calling the second with a model loaded from disk. The trouble is that loading the same NSManagedObjectModel twice from disk inside the same app/test invocation results in the errors above, since every loading of the model results in external registration calls, which print errors once called a second time on the same app/test invocation .And init(name: String) was not smart enough to cache the model. So if you want to load a container multiple time you have to load the NSManagedObjectModel once and store it in an attribute you then use on every init(name:managedObjectModel:) call. Example: caching a model import Foundationimport SwiftUIimport CoreDataimport CloudKitclass PersistentContainer { private static var _model: NSManagedObjectModel? private static func model(name: String) throws -> NSManagedObjectModel { if _model == nil { _model = try loadModel(name: name, bundle: Bundle.main) } return _model! } private static func loadModel(name: String, bundle: Bundle) throws -> NSManagedObjectModel { guard let modelURL = bundle.url(forResource: name, withExtension: "momd") else { throw CoreDataError.modelURLNotFound(forResourceName: name) } guard let model = NSManagedObjectModel(contentsOf: modelURL) else { throw CoreDataError.modelLoadingFailed(forURL: modelURL) } return model } enum CoreDataError: Error { case modelURLNotFound(forResourceName: String) case modelLoadingFailed(forURL: URL) } public static func container() throws -> NSPersistentCloudKitContainer { let name = "ItmeStore" return NSPersistentCloudKitContainer(name: name, managedObjectModel: try model(name: name)) }} Old answer Loading Core Data is a little bit of magic, where loading a model from disk and using it means it registers for certain types. A second loading tries to register for the type again, which obviously tells you that something registered for the type already. You can load Core Data only once and cleanup that instance after each test. Cleanup means deleting every object entity and then saving. There is some function which gives you all entities which you can then fetch and delete. Batch delete is not available InMemory though so object-by-managed object it is there. The (probably simpler) alternative is to load the model once, store it somewhere and reuse that model on every NSPersistentContainer call, it has a constructor to use a given model instead of loading it again from disk.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51851485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3720634/']}
jdg_375891
stackexchange
llm_judgeable_groundtruth_similarity
8609307
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 reading through the how to use part of the How to use ASIHTTPRequest notes and would like more clarification on setting up multiple caches. In the notes for the downloadcache it says You aren’t restricted to a single cache - you can create as many caches as you like. When you create a cache yourself, you must set the storage path for the cache - this should be a folder you have write access to: Then shows this peice of code. ASIDownloadCache *cache = [[[ASIDownloadCache alloc] init] autorelease];[cache setStoragePath:@"/Users/ben/Documents/Cached-Downloads"];// Don't forget - you are responsible for retaining your cache![self setMyCache:cache];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];[request setDownloadCache:[self myCache]]; I would like to know where this file is? on the device I suppose? but also how do I make the file and how do I give it write access etc? Now provide the response and nothing else.
Instances of Buffer are also instances of Uint8Array in node.js 4.x and higher. Thus, the most efficient solution is to access the buf.buffer property directly, as per https://stackoverflow.com/a/31394257/1375574 . The Buffer constructor also takes an ArrayBufferView argument if you need to go the other direction. Note that this will not create a copy, which means that writes to any ArrayBufferView will write through to the original Buffer instance. In older versions, node.js has both ArrayBuffer as part of v8, but the Buffer class provides a more flexible API. In order to read or write to an ArrayBuffer, you only need to create a view and copy across. From Buffer to ArrayBuffer: function toArrayBuffer(buf) { const ab = new ArrayBuffer(buf.length); const view = new Uint8Array(ab); for (let i = 0; i < buf.length; ++i) { view[i] = buf[i]; } return ab;} From ArrayBuffer to Buffer: function toBuffer(ab) { const buf = Buffer.alloc(ab.byteLength); const view = new Uint8Array(ab); for (let i = 0; i < buf.length; ++i) { buf[i] = view[i]; } return buf;}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8609307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/807400/']}
jdg_375892
stackexchange
llm_judgeable_groundtruth_similarity
1713819
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Q: I'm trying to update a file in place, by using fopen mode "r+" , reading a certain string, and writing back a modified string, but it's not working. A: Be sure to call fseek before you write, both to seek back to the beginning of the string you're trying to overwrite, and because an fseek or fflush is always required between reading and writing in the read/write "+" modes. My question is why fseek or fflush is always required between reading and writing in the read/write "+" modes? Section 5.2 of Andrew Koenig's C Traps and Pitfalls (1989) mentioned that it is because of a backward compatibility issue. Can anyone explain in detail? Now provide the response and nothing else.
The library buffers input and output operations. Check out setvbuf() and the _IOFBF , _IOLBF parameters to that function. fseek() or fflush() require the library to commit buffered operations. The standard specifies a seek or flush operation (flushing the buffers) as mandatory prior to changing I/O direction to allow the library some shortcuts. Without this restriction, the library would have to check for every I/O operation if the previous operation was the same direction (reading / writing), and trigger a flush by itself if the I/O direction changed. With the restriction as-is, the library may assume the client did the seek / flush before changing I/O direction, and can omit the direction checks.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1713819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115722/']}
jdg_375893
stackexchange
llm_judgeable_groundtruth_similarity
16323571
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I measure the distance between two strings with Ruby? I.e.: compare('Test', 'est') # Returns 1compare('Test', 'Tes') # Returns 1compare('Test', 'Tast') # Returns 1compare('Test', 'Taste') # Returns 2compare('Test', 'tazT') # Returns 5 Now provide the response and nothing else.
I found this for you: def levenshtein_distance(s, t) m = s.length n = t.length return m if n == 0 return n if m == 0 d = Array.new(m+1) {Array.new(n+1)} (0..m).each {|i| d[i][0] = i} (0..n).each {|j| d[0][j] = j} (1..n).each do |j| (1..m).each do |i| d[i][j] = if s[i-1] == t[j-1] # adjust index into string d[i-1][j-1] # no operation required else [ d[i-1][j]+1, # deletion d[i][j-1]+1, # insertion d[i-1][j-1]+1, # substitution ].min end end end d[m][n]end[ ['fire','water'], ['amazing','horse'], ["bamerindos", "giromba"] ].each do |s,t| puts "levenshtein_distance('#{s}', '#{t}') = #{levenshtein_distance(s, t)}"end That's awesome output: =) levenshtein_distance('fire', 'water') = 4levenshtein_distance('amazing', 'horse') = 7levenshtein_distance('bamerindos', 'giromba') = 9 Source: http://rosettacode.org/wiki/Levenshtein_distance#Ruby
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16323571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/977687/']}
jdg_375894
stackexchange
llm_judgeable_groundtruth_similarity
2583892
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 was given the following exercise in an advanced calculus course: Let $f:\mathbb{R}\to\mathbb{R}$ be a continuous function and $a\in\mathbb{R}$. Show that $$\int_{S^{n-1}}f\left(\left< x,a\right>\right)d\mathrm{vol}_{n-1}(x)=\omega_{n-1}\int^1_{-1}f\left(t\left|a\right|\right)\left(1-t^2\right)^\frac{n-3}{2}dt$$ where $\omega_{n-1}$ is the surface area of $S^{n-1}$, the $n-1$ dimensional sphere (embedded in $\mathbb{R}^n$). I initially noticed two things. First, the right hand side seemed to suggest to me that the co-area formula might be useful here. Second, that $\left<x,\frac{a}{\left|a\right|}\right>=\cos\left(\theta\left(x\right)\right)$ when $\theta\left(x\right)$ is the angle between $a$ and $x$. Putting these two together, I thought I might be able to use the co-area formula on the function $\Phi(x)=\cos\left(\theta\left(x\right)\right)$ to work my way from RHS to LHS. I didn't manage it and couldn't come up with an alternative approach. I'd be thankful for any suggestion. Now provide the response and nothing else.
Your idea is a good one. You might have had trouble because the formula is incorrect; the $w_{n-1}$ should in fact be $w_{n-2}$. First of all, both sides are rotationally invariant, so it suffices to assume that $a$ is parallel to $e_n$, i.e. $a=|a| e_n$. Second of all, we can assume $|a|=1$, since if we know the formula holds in this case, then we can deduce it holds for general $a$ by applying the formula to the function $g(x)=f(|a|x)$. Thus, $a=e_n$ without loss of generality. Now, apply the coarea formula to the function $F: S_{n-1}\to [-1,1],F(p)=<p,e_n>$. Before getting into the calculations, let's think geometrically about what's going on. The preimages of $F$ divide the sphere into n-2 dimensional slices at different heights. The value of $F$ is constant on each preimage (by definition). At any point on the sphere, we can either move within the preimage containing that point, or we can move along the line of longitude through that point, thus passing through other preimages. This gives $n-2+1=n-1=Dim(S_{n-1})$ independent directions, which is how we will construct our coordinate system. Now, let's compute $Jac(F)_p$ for any $p\in S_{n-1}$. As discussed above, we can choose an orthonormal system of local coordinates by first taking orthonormal local coordinates $z_1,\dots, z_{n-2}$ for the preimage $F^{-1}(F(p))$, and then letting $z_{n-1}$ correspond to the (downward) line of longitude. Then $\partial F/\partial z_i=0$ for $i\leq n-2$, because $F$ is constant on the preimage. To compute $\partial F/\partial z_{n-1}(p)$, we'll use the fact that $F$ is invariant with respect to rotations about $e_{n}$. Applying such a rotation to $p$, we may assume that $p=(\sqrt{1-q^2},0,..,0, q)$, where $q=F(p)$. The unit vector at p pointing downward along the line of longitude is given by $v=(q,0,...,0,-\sqrt{1-q^2})$ (to get this, just take the orthogonal projection of $-e_n$ onto $p^{\perp}$ and renormalize the result). Now take any path $\gamma:(-\epsilon,\epsilon)\to S^{n-1}$ with $\gamma(0)=p, \gamma’(0)=v$. Then $\partial F/\partial z_{n-1}(p)={\frac d {dt}}_{t=0} F(\gamma(t))={\frac d {dt}}_{t=0} \gamma_n(t)=v_n=-\sqrt{1-q^2}=-\sqrt{1-F(p)^2}$. So, the Jacobian at $p$ $J(F)_{p, z_i}$ with respect to the coordinates $z_i$ is a row vector of length n-1, where the first n-2 entries are 0, and the last is $-\sqrt{1-F(p)^2}$. Since the tangent vectors ${{\partial}{\partial z_i}}$ are orthonormal, the transpose with respect to the Riemannian metric is equal to the regular matrix transpose. Finally, we're ready to apply the formula, which yields $$\int f(F(x))dV_{S_{n-1}}(x)=\int_{-1}^1 \int_{F^{-1}t} {\frac {f(F(p))}{\sqrt{det(J(F)J(F)^T)(p)}}}dV_{F^{-1}t}(p)dt$$ By the discussion above, for $p\in F^{-1}t$, we have $\sqrt{det(J(F)J(F)^T)(p)}=\sqrt{1-t^2}$. Furthermore, by definition of the inverse image, we have $f(F(p))=f(t)$ for any such $p$. Thus the integrand depends only on $t$, so we can pull it out of the inner integral: $$\int_{-1}^1 f(t)(1-t^2)^{-1/2}\int_{F^{-1}t}dV_{F^{-1}t}dt=\int_{-1}^1 f(t)(1-t^2)^{-1/2}Vol(F^{-1}t)dt$$ Now, $F^{-1}t$ is defined by the equations $x_n=t, x_1^2+...+x_{n-1}^2+t^2=1$, so it is an n-2 dimensional sphere of radius $\sqrt{1-t^2}$ embedded in the plane $x_n=t$. Accordingly, $$Vol(F^{-1}t)=(\sqrt{1-t^2})^{n-2}\omega_{n-2}$$ where $\omega_{n-2}$ is the volume of the unit n-2 sphere. This establishes the formula.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2583892', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/266366/']}
jdg_375895
stackexchange
llm_judgeable_groundtruth_similarity
12967
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 a proof technique in search of examples. I'm looking for combinatorially meaningful sequences $\{a_n\}$ so that $a_{n+1}/a_n$ is known or conjectured to be an integer, such that there is a relation between the $n$th case and $n+1$st, but not an obvious $a_{n+1}/a_n\to 1$ map. This means $a_n$ is the $n$th partial product of an infinite sequence of integers, but there isn't an obvious product structure. The prototype was an enumeration ofdomino tilings of an Aztecdiamond of order $n$, $a_n = 2^{n(n+1)/2}$, so $a_{n+1}/a_n = 2^{n+1}$. (There is a nice $2^{n+1}$to 1 map unrelated to my technique,but it isn't obvious.) Another application was a proof that$\det \{B_{i+j}\}_{i,j=0}^n = \prod_{i=1}^n i! $ where $B_n$ isthe $n$th Bell number , equation25 in the linked page. The counts of alternating sign matrices 1, 2, 7, 42, ... are not an example, since $ASM(n+1)/ASM(n) = \frac{ (3n+1)!n!}{2n! (2n+1)!}$ which is not always an integer, e.g, 7/2 is not. What are some other interesting combinatorial families whose ratios $a_{n+1}/a_n$ are known or (preferably) conjectured to be integers? Thanks. Now provide the response and nothing else.
The number of pairs $(P,Q)$ of standard Young tableaux of the same shape and with $n$ squares is $n!$. The number of oscillating tableaux of length $2n$ and empty shape is $1\cdot 3\cdot 5\cdots (2n-1)$. The number of leaf-labeled complete (unordered) binary trees with $n$ leaves is $1\cdot 3\cdot 5\cdots (2n-3)$ (Schröder's third problem). The number of compact-rooted directed animals of size $n$ is $3^n$. See MathSciNet MR0956559 (90c:05009). Let $f(n)$ be the number of $n\times n$ matrices $M=(m_{ij})$ of nonnegative integers with row and column sum vector $(1,3,6,\dots,{n+1\choose 2})$ such that $m_{ij}=0$ if $j>i+1$. Then $f(n)=C_1C_2\cdots C_n$, where $C_i$ is a Catalan number. No combinatorial proof of this result is known. See Exercise 6.C12 on page 38 (solution on page 84) of http://math.mit.edu/~rstan/ec/catadd.pdf
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/12967', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2954/']}
jdg_375896
stackexchange
llm_judgeable_groundtruth_similarity
35823
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: I was solving a practice Physics GRE and there was a question about springs connected in series and parallel. I was too lazy to derive the way the spring constants add in each case. But I knew how capacitances and resistances add when they are connected in series/parallel. So I reasoned that spring constants should behave as capcitances because both springs and capacitors store energy. This line reasoning did give me the correct answer for how spring constants add, but I was just curious if this analogy makes sense, and if it does, how far one can take it. That is, knowing just that two things store energy, what all can you say will be similar for the two things. Now provide the response and nothing else.
Electrical analogies of mechanical elements such as springs, masses, and dash pots provide the answer. The "deep" connection is simply that the differential equations have the same form. In electric circuit theory, the across variable is voltage while the through variable is current. The analogous quantities in mechanics are force and velocity. Note that in both cases, the product of the across and through variables has the unit of power. (An aside, sometimes it is convenient to use force and velocity as the across and through variables respectively while other times, it is more convenient to switch those roles.) Now, assuming velocity is the through variable, velocity and electric current are analogous. Thus, displacement and electric charge are analogous. For a spring, we have $f = kd \rightarrow d = \frac{1}{k}f$ while for a capacitor we have $Q = CV$. For a mass, we have $f = ma = m\dot v $ while for an inductor we have $V = L \dot I$ Finally, for a dashpot, we have $f = Bv$ while for a resistor we have $V = RI$. So, we have $\frac{1}{k} \rightarrow C$ $m \rightarrow L$ $B \rightarrow R$ For a nice summary with examples, see this . UPDATE: In another answer, RubenV questions the answer given above. His reasoning requires an update. Alfred Centauri's answer is not correct. The analogy he mentions is true, but it is irrelevant as it does not tell you anything about components in series or in parallel. In fact, it is relevant and it does tell you everything about components in series or in parallel. Let's review: When two circuit elements are in parallel , the voltage across each is identical. When two circuit elements are in series , the current through each is identical. This is fundamental and must be kept in mind when moving to the mechanical analogy . In the mechanical analogy where a spring is the mechanical analog of a capacitor: force is the analog of voltage velocity is the analog of current . Keeping this in mind, consider two springs connected in mechanical parallel and note that the velocity (rate of change of displacement) for each spring is identical. But recall, in this analogy, velocity is the analog of current. Thus, the equivalent electrical analogy is two capacitors in series (identical current ). In series, capacitance combines as so: $\dfrac{1}{C_{eq}} = \dfrac{1}{C_1} + \dfrac{1}{C_2}$ With the spring analogy, $C \rightarrow \frac{1}{k}$ , this becomes: $k_{eq} = k_1 + k_2$ The key point to take away from this is that mechanical parallel is, in this analogy, circuit series since, in mechanical parallel, the velocity (current) is the same, not the force (voltage). For example, consider dash pots (resistors). Two dash pots in "parallel" combine like two resistors in series, i.e., the resistance to motion of two dash pots in "parallel" is greater then each individually. Now, if the roles of the analogous variables are swapped, if force is like current and velocity is like voltage, then mechanical parallel is like circuit parallel. However, in this analogy, mass is like capacitance.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/35823', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/11471/']}
jdg_375897
stackexchange
llm_judgeable_groundtruth_similarity
77591
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 Phd Student in experimental psychology and I try hard to improve my skills and knowledge about how to analyze my data. Until my 5th year in Psychology, I thought that the regression-like models (e.g., ANOVA) assume the following things: normality of the data variance homogeneity for the dataand so on My undergraduate courses lead me to believe that the assumptions were about the data. However in my 5th year, some of my instructors underlined the fact that the assumptions are about the error (estimated by the residuals) and not the raw data. Recently I was talking about the assumptions question with some of my colleagues who also admited that they discovered the importance of checking the assumptions on the residual only in their last years of university. If I understand well, the regression-like models make assumptions on the error. Thus it makes sense to check the assumptions on the residuals. If so, why some people check the assumptions on the raw data? Is it because such checking procedure approximate what we would obtain by checking the residual? I would be very intersting in a disccussion about this issue with some people who have more accurate knowledge than my colleagues and I. I thank you in advance for your answers. Now provide the response and nothing else.
Basically, you are on the right track. You will find a discussion about the aspect of normality in Normality of dependent variable = normality of residuals? Some assumptions of the classic linear model are indeed about errors (using residuals as realizations of them): Are they uncorrelated? (Relevant for inference and optimality of the OLS-estimators) Do they have equal variance? (Relevant for inference and optimality of the OLS-estimators) Are they centered around 0? (Key assumption to get unbiased estimators and predictions) If the sample is very small: are they normal or at least symmetrically distributed? (Relevant for inference) Other conditions are about "raw data": Are there no gross outliers in regressors? (High leverage observations can destroy the whole model) No perfect multicollinearity? (Would cause computational problems, at least in some software packages) Now, your undergrad teacher might be correct as well: Maybe you were focusing on univariate tests like the one-sample t-test. There, the assumptions are about the raw data. If the $R^2$ is quite low and the response variable looks everything but normal, then the same will most likely also be true for the residuals. How would you check homoscedasticity etc. based on raw data? Maybe you misunderstood him or her.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/77591', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/35227/']}
jdg_375898
stackexchange
llm_judgeable_groundtruth_similarity
18429021
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 some situations, one generally uses a large enough integer value to represent infinity. I usually use the largest representable positive/negative integer. That usually yields more code, since you need to check if one of the operands is infinity before virtually all arithmetic operations in order to avoid overflows. Sometimes it would be desirable to have saturated integer arithmetic. For that reason, some people use smaller values for infinity, that can be added or multiplied several times without overflow. What intrigues me is the fact that it's extremely common to see (specially in programming competitions): const int INF = 0x3f3f3f3f; Why is that number special? It's binary representation is: 00111111001111110011111100111111 I don't see any specially interesting property here. I see it's easy to type, but if that was the reason, almost anything would do (0x3e3e3e3e, 0x2f2f2f2f, etc). It can be added once without overflow, which allows for: a = min(INF, b + c); But all the other constants would do, then. Googling only shows me a lot of code snippets that use that constant, but no explanations or comments. Can anyone spot it? Now provide the response and nothing else.
I found some evidence about this here ( original content in Chinese); the basic idea is that 0x7fffffff is problematic since it's already "the top" of the range of 4-byte signed ints; so, adding anything to it results in negative numbers; 0x3f3f3f3f, instead: is still quite big (same order of magnitude of 0x7fffffff); has a lot of headroom; if you say that the valid range of integers is limited to numbers below it, you can add any "valid positive number" to it and still get an infinite (i.e. something >=INF ). Even INF+INF doesn't overflow. This allows to keep it always "under control": a+=b;if(a>INF) a=INF; is a repetition of equal bytes, which means you can easily memset stuff to INF ; also, as @Jörg W Mittag noticed above, it has a nice ASCII representation, that allows both to spot it on the fly looking at memory dumps, and to write it directly in memory.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18429021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/693716/']}
jdg_375899
stackexchange
llm_judgeable_groundtruth_similarity
922883
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: Having trouble with this question: If $p,q$ are primitive statements, prove that $$(\neg p \vee q)\wedge (p\wedge (p\wedge q))\iff (p\wedge q)$$ Source: Discrete and Combinatorial Mathematics by Ralph P. Grimaldi I'm wondering how I should approach this problem to get to the solution, and also what I should do in the future. Here is my work so far: Now provide the response and nothing else.
Edit: I decided that the previous solution admits a minor but nice generalization, so here goes. Let $$t = \dfrac{x}{\sqrt{x^4+1}}, \quad dt = \frac{1-x^4}{(x^4+1)^{3/2}} \, dx.$$ Then $$\frac{1}{1 \pm 2t^2} = \frac{x^4+1}{x^4 + 1 \pm 2x^2} = \frac{x^4+1}{(1 \pm x^2)^2},$$ so that$$ \begin{align*} \int \frac{x^2 \mp 1}{(x^2 \pm 1)\sqrt{x^4+1}} \, dx &= \int \frac{(x^2 \mp 1)(x^2 \pm 1)(x^4+1)}{(x^2 \pm 1)^2 (x^4+1)^{3/2}} \, dx \\ &= \int \frac{1}{1 \pm 2t^2 } \cdot \frac{x^4-1}{(x^4+1)^{3/2}} \, dx \\ &= - \int \frac{dt}{1 \pm 2t^2}.\end{align*}$$ In the positive case, we get $$- \frac{1}{\sqrt{2}} \tan^{-1} \sqrt{2}t + C = - \frac{1}{\sqrt{2}} \tan^{-1} \frac{x \sqrt{2}}{\sqrt{x^4+1}} + C.$$ In the negative case, we get $$\frac{1}{2\sqrt{2}} \log \left| \frac{1 - \sqrt{2}t}{1 + \sqrt{2}t} \right| + C = \frac{1}{2 \sqrt{2}} \log \left| \frac{\sqrt{x^4+1} - x \sqrt{2}}{\sqrt{x^4+1} + x \sqrt{2}} \right| + C.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/922883', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/159628/']}
jdg_375900
stackexchange
llm_judgeable_groundtruth_similarity
4334753
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 send thousands of different emails to different recipients and would like to open the connection to my SMTP and hold it. I hope this is faster then reopen the connection for ervy mail. I would like to use Apache Commons Email for that, but could fall back to the Java Mail API if necessary. Right now I'am doing this, what opens a closes the connection every time: HtmlEmail email = new HtmlEmail();email.setHostName(server.getHostName());email.setSmtpPort(server.getPort());email.setAuthenticator(new DefaultAuthenticator(server.getUsername(), server.getPassword()));email.setTLS(true);email.setFrom("test@example.com");email.addTo(to);email.setSubject(subject);email.setHtmlMsg(htmlMsg);email.send(); Now provide the response and nothing else.
Here is my performance test class. Sending the mails using one connection is 4 times faster then reopen the connection every time (what happens when you use commons mail). The performance can be pushed further by using multiple threads. Properties properties = System.getProperties(); properties.put("mail.smtp.host", server); properties.put("mail.smtp.port", "" + port); Session session = Session.getInstance(properties); Transport transport = session.getTransport("smtp"); transport.connect(server, username, password); for (int i = 0; i < count; i++) { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); InternetAddress[] address = {new InternetAddress(to)}; message.setRecipients(Message.RecipientType.TO, address); message.setSubject(subject + "JavaMail API"); message.setSentDate(new Date()); setHTMLContent(message); message.saveChanges(); transport.sendMessage(message, address); } transport.close();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4334753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/60518/']}
jdg_375901
stackexchange
llm_judgeable_groundtruth_similarity
69576
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: What is the probability that the sum of squares of n randomly chosen numbers from $Z_p$ is a quadratic residue mod p? That is, let $a_1$,..$a_n$ be chosen at random. Then how often is $\Sigma_i a^2_i$ a quadratic residue? Now provide the response and nothing else.
This probability can be calculated exactly, and indeed it approaches $1/2$ rather quickly — more precisely, for each $p$ it approaches the fraction $(p-1)/(2p)$ of quadratic residues $\bmod p$. This can be proved by elementary means, but perhaps the nicest way to think about it is that if you choose $n$ numbers $a_i$ independently and sum $a_i^2 \bmod p$, the resulting distribution is the $n$-th convolution power of the distribution of a random single square — so its discrete Fourier transform is the $n$-th power of the D.F.T., call it $\gamma$, of the distribution of $a^2 \bmod p$. For this purpose $\gamma$ is normalized so $\gamma(0)=1$. Then for $k \neq 0$ we have $\gamma(k) = (k/p) \gamma(1)$ [where $(\cdot/p)$ is the Legendre symbol], and$$p \gamma(1) = \sum_{a \bmod p} \exp(2\pi i a^2/p),$$which is a Gauss sum and is thus a square root of $\pm p$. It follows that $|\gamma(k)| = p^{-1/2}$, from which we soon see that each value of the convolution approaches $1/p$ at the exponential rate $p^{-n/2}$, and the probability you asked for approaches $(p-1)/(2p)$ at the same rate. As noted above, this result, and indeed the exact probability, can be obtained by elementary means, yielding a (known but not well-known) alternative proof of Quadratic Reciprocity(!). But that's probably too far afield for the present purpose.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/69576', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16203/']}
jdg_375902
stackexchange
llm_judgeable_groundtruth_similarity
32580
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Yesterday I discovered somebody had uploaded this PHP code to my server as a .jpg file via my asp.net MVC application's "Upload your profile picture" form. I believe the attack was unsuccessful for a number of reasons (the images are given random filenames, then resized, and they're stored in a non-execute directory). The file was leftover because I failed to clean up the temporary file if the resizing failed, which I've now fixed. But it worries me that I don't understand what the next step of this attack would be...Say he'd successfully uploaded a .jpg file that had malicious PHP code in it to my Windows/IIS server, and he knew the file's URL. Now what? He would need to get IIS to interpret that .jpg file as PHP code rather than an image, right? What might his plan have been to accomplish that? The only thing I can think of is if it were an apache server and .php files were being filtered out but .htaccess files weren't, he maybe could have managed it. Is there any equivalent approach that might have worked in IIS? Now provide the response and nothing else.
One possible path would be to try and get it to be included somehow. A lot of add-on frameworks can run an arbitrary PHP code file. If the attacker was able to find such an add-on framework, they could give it the path to the file and it would be executed as PHP regardless of the file extension.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/32580', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/21948/']}
jdg_375903
stackexchange
llm_judgeable_groundtruth_similarity
28285830
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Dictionary<int, int> first = new Dictionary<int, int>();first.Add(1, 5);first.Add(2, 4);first.Add(3, 7);Dictionary<int, int> second = new Dictionary<int, int>();second .Add(2, 1);second .Add(3, 2);second .Add(4, 3);var c = first.Where(x => x.Value > 5).Select(x => x.Key).ToList(); // this gives me 3var d = second.Where(x => x.Value >= 2).Select(x => x.Key).ToList(); // this give me 3 and 4 I need to combine result of c and d , which should be 3 and 4 . Can I do this union of these two result in a LINQ query? Now provide the response and nothing else.
If you're using jQuery-UI, you must include the jQuery UI CSS package, otherwise the UI components don't know how to be styled. If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied. Here's an example and some possible fixes. Minimal, Complete, and Verifiable example (i.e. broken) Here's a demo in Stack Snippets without jquery-ui.css (doesn't work) $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags });}); <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><div class="container"> <div class="form-group"> <label>Languages</label> <input class="form-control autocomplete" placeholder="Enter A" /> </div> <div class="form-group"> <label >Another Field</label> <input class="form-control"> </div></div> Fix #1 - jQuery-UI Style Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery. $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags });}); <link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><div class="container"> <div class="form-group"> <label>Languages</label> <input class="form-control autocomplete" placeholder="Enter A" /> </div> <div class="form-group"> <label >Another Field</label> <input class="form-control"> </div></div> Fix #2 - Bootstrap Theme There is a project that created a Bootstrap-esque theme for jQuery-UI components called jquery‑ui‑bootstrap . Just grab the stylesheet from there and you should be all set. $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags });}); <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><div class="container"> <div class="form-group"> <label>Languages</label> <input class="form-control autocomplete" placeholder="Enter A" /> </div> <div class="form-group"> <label >Another Field</label> <input class="form-control"> </div></div> Fix #3 - Manual CSS If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using. After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's autocomplete.css and theme.css to figure out what styles you'll need to manually replace. You can use bootstrap's dropdowns.less for inspiration. Here's a sample CSS that fits pretty well with Bootstrap's default theme: .ui-autocomplete { position: absolute; z-index: 1000; cursor: default; padding: 0; margin-top: 2px; list-style: none; background-color: #ffffff; border: 1px solid #ccc; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);}.ui-autocomplete > li { padding: 3px 20px;}.ui-autocomplete > li.ui-state-focus { background-color: #DDD;}.ui-helper-hidden-accessible { display: none;} $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags });}); .ui-autocomplete { position: absolute; z-index: 1000; cursor: default; padding: 0; margin-top: 2px; list-style: none; background-color: #ffffff; border: 1px solid #ccc -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);}.ui-autocomplete > li { padding: 3px 20px;}.ui-autocomplete > li.ui-state-focus { background-color: #DDD;}.ui-helper-hidden-accessible { display: none;} <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><div class="container"> <div class="form-group ui-widget"> <label>Languages</label> <input class="form-control autocomplete" placeholder="Enter A" /> </div> <div class="form-group ui-widget"> <label >Another Field</label> <input class="form-control" /> </div></div> Tip : Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with .ui-autocomplete and remove display: none; .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28285830', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4187557/']}
jdg_375904
stackexchange
llm_judgeable_groundtruth_similarity
1000037
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: $$\int \sqrt{1-x^2} dx = \int \sqrt{1-\sin^2t} \cdot dt= \int \sqrt {\cos^2 t} \cdot dt= \int \cos t \cdot dt = \sin t +C = x +C$$ The answer is wrong. Why? Now provide the response and nothing else.
Seeing as you intended to substitute $x = \sin t$, then it necessarily follows that $dx = \cos t \,dt$ So $dt \neq dx$, which is what you implicitly assumed in your first transformation. Instead, we have $$\int \sqrt {1-x^2} \,dx = \int \sqrt{1-\sin^2 t}\cos t\,dt = \int \cos^2t \,dt$$ Now, can you finish off, using an appropriate identity?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1000037', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/188391/']}
jdg_375905
stackexchange
llm_judgeable_groundtruth_similarity
34398338
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: gulp-uglify is unable to uglify this piece of code: var alertString = `<?xml version="1.0" encoding="UTF-8" ?> <document> <alertTemplate> <title>${title}</title> <description>${description}</description> </alertTemplate> </document>` it complains at the character: `. The character is valid for the apple's JS framework. I can't see anything inside the uglify package to ignore those characters and the text string inside it. Am i missing something from the documentation? Now provide the response and nothing else.
Gulp-uglify has yet no official support for ECMAScript 2015 (aka ES6, aka Harmony) but with a little modification the on-development repository can be used. How-to: Open Console and enter cd node_modules/gulp-uglify Edit package.json dependencies": { "uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony" }, Console enter: npm update And it is ready to run .pipe(uglify()) again Alternate Solution Download the following via npm : npm install --save-dev gulp-uglify gulp-babel babel-preset-es2015 Add the following requires in the gulpfile.js : var babel = require('gulp-babel'), uglify = require('gulp-uglify'); The gulp task will be as follow: gulp.task('uglify', function(){ gulp.src('*.js') .pipe(babel({ presets: ['es2015'] })) .pipe(uglify().on('error', function(e){ console.log(e); })) .pipe(gulp.dest('js'));}); What this does is transpile all the EcmaScript 2015 JS code to EcmaScript5 and then uglifies it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34398338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3690438/']}
jdg_375906
stackexchange
llm_judgeable_groundtruth_similarity
15785832
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 program like this: ssh -q harigm@8.19.71.238 exitecho "output value -->$?" In the above code, I am trying to SSH to the remote server, and tries to check if I can connect or not.I have few servers, which is password less is activated and few servers for which passwords are still not yet deactivated.So my concern, if there is a password, it will get stuck in the same screen asking for the password and it will be there for infinite time, without Exit logic. Question : How to implement the timers for the above code, and if it stays in the same screen asking for the password. and exit with some error code 2) When I execute the above code, i get the following error codes: 127 -- > I guess its for success225 -- > for any error. are there any other error codes other than above? Now provide the response and nothing else.
You could wrap the call to ssh using the timeout command. The timeout command exits with code 124 if a timeout occurs. timeout 10s ssh -q harigm@8.19.71.238 exitif [ $? -eq 124 ]; then echo "Timeout out"fi Or, as Vorsprung has commented on your question (as I was looking up the man page!): ssh -oPasswordAuthentication=no -q harigm@8.19.71.238 exit which will disallow interactive password authentication. You'd then have to check the exit code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15785832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238052/']}
jdg_375907
stackexchange
llm_judgeable_groundtruth_similarity
159501
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: What is the simplest proof that mutual information is always non-negative? i.e., $I(X;Y)\ge0$ Now provide the response and nothing else.
By definition,$$I(X;Y) = -\sum_{x \in X} \sum_{y \in Y} p(x,y) \log\left(\frac{p(x)p(y)}{p(x,y)}\right)$$Now, negative logarithm is convex and $\sum_{x \in X} \sum_{y \in Y} p(x,y) = 1$, therefore, by applying Jensen Inequality we will get,$$I(X;Y) \geq -\log\left( \sum_{x \in X} \sum_{y \in Y} p(x,y) \frac{p(x)p(y)}{p(x,y)} \right) = -\log\left( \sum_{x \in X} \sum_{y \in Y} p(x)p(y)\right) = 0$$Q.E.D
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/159501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21373/']}
jdg_375908
stackexchange
llm_judgeable_groundtruth_similarity
282959
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: We are trying to configure our Cisco 5505, and it has been done through ASDM. There is one big problem that we're not able to solve, and that's when you go from inside to outside and back in again. Example, we have a server "inside" and we want to be able to reach this server with the same adress if we're on the inside or if we're on the outside. The problem is adding a rule that will allow traffic from inside to outside and then back in again. Now provide the response and nothing else.
The ASA firewall can not route traffic. You need to masq the inside address against the external address. Solution 1: DNS doctoring with static NAT Let's say your external website IP address is 1.2.3.4, wich then again is port-forwarded (or directly NAT'ed) to the internal IP address 192.168.0.10. With DNS doctoring, the following will happen: The client on the inside requests http://www.companyweb.com , wich originally translates to 1.2.3.4 The ASA intercepts the DNS reply packet, and replaces the A-record with 192.168.0.10 The client gets very happy, as it now can open up the company web site :-) For more detailed info on how you enable this: http://www.cisco.com/en/US/products/ps6120/products_configuration_example09186a00807968d1.shtml Solution 2: Internal DNS server This one is useful if you only have one external IP, and you port-forward this IP to many internal services on different servers (Let's say port 80 and 443 goes to 192.168.0.10, port 25 goes to 192.168.0.11 etc). It requires no configuration change on the ASA, but it will require you to duplicate your external domain on a internal DNS server (Active Directory has this built in). You just create the exact same records as you have now, only with internal IP's on the services you have internally. "Solution" 3: DMZ interface with public IP's I'm not going to get into much details on this one, as it requires you to get a subnet of IP adresses from your ISP routed to your ASA. It's very hard these days with the IPv4 starvation.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/282959', 'https://serverfault.com', 'https://serverfault.com/users/85316/']}
jdg_375909
stackexchange
llm_judgeable_groundtruth_similarity
5500139
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 updating an object in AzureTableStorage using the StorageClient library with context.UpdateObject(obj); context.SaveChangesWithRetries(obj); when I do this, is there any way to get hold of the new timestamp for obj without making another request to the server? Thanks Stuart Now provide the response and nothing else.
MSDN page has some guidance on the usage of Timestamp field: Timestamp Property The Timestamp property is a DateTime value that is maintained on the server side to record the time an entity was last modified. The Table service uses the Timestamp property internally to provide optimistic concurrency. You should treat this property as opaque: It should not be read, nor set on insert or update operations (the value will be ignored). This implies that it is really implementation details of the table storage, you should not rely the Timestamp field to represent timestamp of last update. If you want a field which is guaranteed to represent time of last write, create new field and set it on every update operatio. I understand this is more work (and more storage space) to maintain the field, but that would actually automatically resolves your question -- how to get the timestamp back, because you would already know it when calling context.UpdateObject().
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5500139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/373321/']}
jdg_375910
stackexchange
llm_judgeable_groundtruth_similarity
2810545
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 found some places on the web saying that operators in Lua are overloadable but I can't seem to find any example. Can someone provide an example of, say, overloading the + operator to work like the .. operator works for string concatenation? EDIT 1: to Alexander Gladysh and RBerteig : If operator overloading only works when both operands are the same type and changing this behavior wouldn't be easy, then how come the following code works? (I don't mean any offense, I just started learning this language): printf = function(fmt, ...) io.write(string.format(fmt, ...))endSet = {}Set.mt = {} -- metatable for setsfunction Set.new (t) local set = {} setmetatable(set, Set.mt) for _, l in ipairs(t) do set[l] = true end return setendfunction Set.union (a,b) -- THIS IS THE PART THAT MANAGES OPERATOR OVERLOADING WITH OPERANDS OF DIFFERENT TYPES -- if user built new set using: new_set = some_set + some_number if type(a) == "table" and type(b) == "number" then print("building set...") local mixedset = Set.new{} for k in pairs(a) do mixedset[k] = true end mixedset[b] = true return mixedset -- elseif user built new set using: new_set = some_number + some_set elseif type(b) == "table" and type(a) == "number" then print("building set...") local mixedset = Set.new{} for k in pairs(b) do mixedset[k] = true end mixedset[a] = true return mixedset end if getmetatable(a) ~= Set.mt or getmetatable(b) ~= Set.mt then error("attempt to 'add' a set with a non-set value that is also not a number", 2) end local res = Set.new{} for k in pairs(a) do res[k] = true end for k in pairs(b) do res[k] = true end return resendfunction Set.tostring (set) local s = "{" local sep = "" for e in pairs(set) do s = s .. sep .. e sep = ", " end return s .. "}"endfunction Set.print (s) print(Set.tostring(s))ends1 = Set.new{10, 20, 30, 50}s2 = Set.new{30, 1}Set.mt.__add = Set.union-- now try to make a new set by unioning a set plus a number:s3 = s1 + 8Set.print(s3) --> {1, 10, 20, 30, 50} Now provide the response and nothing else.
The metatable function only works on tables, but you can use debug.metatable to set the strings metatable... > mt = {}> debug.setmetatable("",mt)> mt.__add = function (op1, op2) return op1 .. op2 end> ="foo"+"bar"foobar> Another approach is to use debug.getmetatable to augment the built-in string metatable (answering the question in the comment below): ~ e$ luaLua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio> debug.getmetatable("").__add = function (op1, op2) return op1 .. op2 end> ="foo"+"bar"foobar>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2810545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275067/']}
jdg_375911
stackexchange
llm_judgeable_groundtruth_similarity
12219604
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 list the tag name, tag date and tag message for all tags? It seems that git's separation of display logic for commits through git log and tags through git tag makes it difficult to list the tag name, the tag's date and the tag message. I can show the tag date, name and commit message using git log --tags --show-notes --simplify-by-decoration --pretty="format:%ai %d %s" I inspected http://opensource.apple.com/source/Git/Git-26/src/git-htmldocs/pretty-formats.txt but didn't see any option to show tag message. I can show the tag name and 5 lines of tag message using git tag -n5 . But to get all three pieces of info would appear to require gnarly scripting beyond my ability. Now provide the response and nothing else.
You want to use the for-each-ref command. Unfortunately, it's only slightly less user friendly than filter-branch Note that information like tag date and the tagger is only available for annotated tags. Below is a basic prototype. Note that the format= can be an entire shell script of its own, and probably should be depending on how complicated you want the output. They have a couple of examples specifically for tags in the for-each-ref documentation git for-each-ref --format="%(refname:short) %(taggerdate) %(subject) %(body)" refs/tags
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12219604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/709943/']}
jdg_375912
stackexchange
llm_judgeable_groundtruth_similarity
279472
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: In my undergrads, I was taught 8051 and in interrupts my professor had said that on interrupt SP points to the address that is hardcoded and Program goes to excute those instructions. But in between two address space is only where I can write interrupt handling code and I wrote more than than byte available it will overwrite the next interrupt instructions. Now when I look at Atmega or LPC2148 Datasheet it has interrupt vector address and I am assuming that it points to a address where instructions for interrupt handling instructions are written( not exactly on those addresses). Is my assumptions correct? P.S Due to being on low bandwidth net, I am not able to provide links to Datasheet. Would do that when I get back. Now provide the response and nothing else.
The Interrupt Service Routine (ISR) is the program that's to be executed when an interrupt occurs. Some CPU architectures have fixed addresses which the CPU will execute a subroutine call to. This is true of the MCS-51 (8051). The ISR must start at this address. It is not uncommon to just put a Jump instruction at this address that takes the CPU to the rest of the ISR elsewhere in memory. Other CPU architectures use interrupt vectors. The vector is a memory location at which the address of the ISR can be found. The location of the vector is known to the CPU, either by being fixed or in conjunction with a special CPU/hardware register. When the CPU services the interrupt, it reads a vector value from memory and executes a subroutine call to the vector value. This is true of the ARM, 6502 and 68000 family. External hardware may have a hand in specifying the particular vector to use within a table of vectors but the principle still stands. So the handling of interrupts in the 8051 CPU and in the ARM CPU seem different to you because they use fundamentally different schemes for finding the address of the ISR. But these two methods (hard-coded address versus vector in memory) are pretty-much the only schemes you'll come across in all the CPUs you'll see. (There's the occassional oddity, like the Z80 in Interrupt Mode 0 where it expects to read an instruction from external hardware that'll take it to the ISR, but I wouldn't muddy your water with that stuff while you're getting the hang of it all.)
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/279472', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/132000/']}
jdg_375913
stackexchange
llm_judgeable_groundtruth_similarity
695793
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: Can someone explain me what is Normalization in Layman's term ? If we have a vector a, we normalize it by dividing it by |a|. That is $$\frac {a}{|a|} $$ Why we need normalization? Now provide the response and nothing else.
Normalizing a vector is basically the process of preserving the direction of a vector but forgetting its magnitude. Say I have a vector H. and I want to produce a vector in the same direction as H but with a length of 10. What I can do is: Normalize H (meaning set its length to 1) and the multiply that new vector by 10 to create a vector in the same direction with length 10. This of course is not the only nor most useful application but it shows the general idea. Anytime magnitude wants to be forgotten and direction preserved normalization does the trick. Normalization of a vector also appears in probability where you might have a vector describing states. This normalization is difference since instead of dividing by the length of the vector we are dividing by the sum of its entries. Consider for example flipping 2 fair coins in a row: After flipping 2 coins in a row you could end up with two Heads, two tails, Heads first then tails, or tails first then Heads: We can then count the frequency that each state occurs in 4 rounds of flipping two coins: $$[HH, HT, TH, TT] \rightarrow [1, 1, 1, 1]$$ And if we normalize this vector $$Norm([1,1,1,1]) = \left[\frac{1}{4},\frac{1}{4},\frac{1}{4},\frac{1}{4} \right]$$ Our vector now appropriately features the probabilities of each state occurring. Suppose you now had an unfair coin that you flipped twice and you repeated the procedure say 29 times to get the following result $$Frequency([HH, HT, TH, TT]) = [13,11,1,2]$$ To recover our probabilities for ALL the entries we just normalize: $$\text{Probability} = \left[\frac{13}{29},\frac{11}{29},\frac{1}{29},\frac{2}{29} \right] $$ But these two seemingly different definitions of Normalization ACTUALLY HAVE A LOT IN COMMON. They both capture the concept of: I have a vector, I just want a core piece of information (ex: direction, or probability) and I want to lose other data (ex: magnitude, or frequency count). So thats why we use it. To standardize our data. Make it fit a 'norm' such as length = 1 in the first case or: sum of entries = 1 in the second case. Hope that made sense :)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/695793', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131517/']}
jdg_375914
stackexchange
llm_judgeable_groundtruth_similarity
67811355
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 fresh install of Visual Studio Community 2019 on a new computer. I started a web app project, ran it for the first time, and then when prompted to accept the self-signed certificate I somehow managed to click "Do Not Ask Again" and "No". At this point, when running the web app, I get a ERR_CONNECTION_RESET and can't connect to anything. I've tried deleting and recreating the certificate using advice listed here: Re-Installing Visual Studio 2017 Localhost Certificate , as well as reinstalling VS entirely, but neither worked. To be clear, I messed up, not Visual Studio. As far as I can tell, there's nothing particular about my set up or environment, and I've built web apps in Visual Studio before, I just clicked the wrong things this time and am trying to undo that without factory resetting this entire PC. Does anyone have any idea how I can trigger that original prompt in Visual Studio and get a properly signed certificate to run a web application? [SOLVED] Now provide the response and nothing else.
If anyone has this very specific issue again, I'll post what I did to fix it (from this forum thread: https://developercommunity.visualstudio.com/t/cant-debug-aspnet-applications-err-connection-rese/1239592?viewtype=all ) 1. In VS: Tools > Command Line > Developer Command Prompt, run devenv /resetsettings (this will also reset some customization settings) Edit: not needed, thanks lex-li! Remove potentially malformed certificates: In User Certificate Manager (certmgr.msc) AND Computer Certificate Manager (certlm.msc): Personal > Certificates > if a localhost certificate exists there, delete it Trusted Root Certification Authorities > Certificates > if a localhost certificate exists, delete it Repair IIS 10.0 Express: Control Panel > Programs & Features > Right Click IIS Express > Repair It will ask for a file path o a .msi installation file, but VS doesn't store one for IIS Express Look for a hidden file _package.json in the directory C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft.VisualStudio.IISExpress.Msi,version=xx.xx.xxxxx.xxx,chip=x64 Copy the "url" (which should point to the correct .msi file) in _package.json into the file path asked for by the Repair prompt Verify the repair worked by running netsh http show sslcert ipport=0.0.0.0:44390 in the command prompt (ensure the Certificate Hash field is present). Restart Visual Studio, debug your application, you should get the same Trusted Certificate prompt you misclicked the first time.(You can check the User Certificate Manager to see a new localhost certificate has been installed correctly)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67811355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16109601/']}
jdg_375915
stackexchange
llm_judgeable_groundtruth_similarity
30394996
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why does this happens? For the month and day, I think Java is assuming the previous valid month and day, but I don't understand why year is 2. SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");Date result = sdf.parse("0000/00/00");System.out.println(result.toString()); Output is: Sun Nov 30 00:00:00 GMT 2 Now provide the response and nothing else.
The Gregorian calendar does not have year 0. Year 0 corresponds to 1BCE (Before Common Era, also known as BC). Because you supply 0 for the month and 0 for the day, it rolls back to the previous month and previous year. I.e. 30-Nov-0002 BCE. Date#toString does not include BCE / CE suffix. It would be superfluous in the vast majority of cases. If you are going to work with dates that far back then you need to consult with an historian.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30394996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/902782/']}
jdg_375916
stackexchange
llm_judgeable_groundtruth_similarity
75902
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: To keep the overview I like to place multiple commands always in the same order and start them automatically together (gradle, git, database, scala-REPL, jboss...) -H (hold) seems to mean that the terminal isn't closed after termination, but how do I terminate such a process willfully? Not at all? In such a way that I can continue to use the terminal. I'm using xubuntu with with xfce4-terminal and bash. Is there a better GUI-solution to startup multiple commands, with the ability to continue working in that window/tab? Update: If you don't know these commands: Jboss and gradle are continously producing output, which you don't want to have intermixed in the same terminal. And sometimes they need to be interrupted with ^C, and restarted. I don't like to reopen an xfce4-term and navigate to the directory I need to act in. Database and scala-REPL are interactive so there is no sense in starting them in the background. My current startup-script just navigates to the desired directories, and opens all tabs in the right order to find them always at the same position, naming every tab for its purpose: xfce4-terminal -T eclipse --working-directory=/home/stefan/oximity -e "/opt/eclipse/eclipse" \ --tab -T arandr --working-directory=/home/stefan/oximity -e "arandr /home/stefan/.screenlayout/oximity.sh" \ --tab -T bash --working-directory=/home/stefan/oximity \ --tab -T gradle --working-directory=/home/stefan/oximity/med \ --tab -T git --working-directory=/home/stefan/oximity/med \ --tab -T mysql --working-directory=/opt/mini/mysql \ --tab -T jboss --working-directory=/opt/mini/jboss \ --tab -T jboss-log --working-directory=/opt/mini/jboss/standalone/log \ --tab -T scala-REPL --working-directory=/home/stefan/proj/mini/forum -e /opt/scala/bin/scala Eclipse and arandr are detached from the shell and run in their own window, so there the -e (execute) param works. I think for the scala-REPL it works since it is the last command in the list. Now provide the response and nothing else.
The -H/-hold option is to keep the terminal emulator Window open once the applications started in it (shell or other) has exited. In that state, nothing more can happen. If you want to start a command as a job of an interactive shell in the xfce4-terminal terminal emulator and keep the shell running and use it interactively after the application has exited, with bash , you can make use of the $PROMPT_COMMAND environment variable, to have xfce-terminal start an interactive shell that starts the given command just before the first prompt. xfce4-terminal \ -T eclipse \ --working-directory=/home/stefan/oximity \ -e 'env PROMPT_COMMAND="unset PROMPT_COMMAND; /opt/eclipse/eclipse" bash' \ \ --tab -T arandr \ --working-directory=/home/stefan/oximity \ -e 'env PROMPT_COMMAND="unset PROMPT_COMMAND; arandr /home/stefan/.screenlayout/oximity.sh" bash' \ \ --tab -T bash \ --working-directory=/home/stefan/oximity \ ... That way, the commands are jobs of that shell which means you can suspend them with Ctrl-Z and resume them later with fg/bg as if you had entered them at the prompt of that interactive shell. That assumes though that you don't set the $PROMPT_COMMAND in your ~/.bashrc . Also note that the exit status of the command will not be available in $? . To make it even more like the command was entered at the shell prompt you can even add it to the history list. Like: xfce4-terminal -T /etc/motd -e 'env PROMPT_COMMAND=" unset PROMPT_COMMAND history -s vi\ /etc/motd vi /etc/motd" bash' That way, once you exit vi , you can press the Up key to recall that same vi command. An easier way to write it: PROMPT_COMMAND='unset PROMPT_COMMAND; history -s "$CMD"; eval "$CMD"' \ xfce4-terminal --disable-server \ -T /etc/motd -e 'env CMD="vi /etc/motd" bash' \ --tab -T top -e 'env CMD=top bash' The: xfce4-terminal -e 'sh -c "cmd; exec bash"' solution as given in other answers works but has some drawbacks: If you press Ctrl-C while cmd is running, that kills the outer sh since there's only one process group for both sh and cmd . You can't use Ctrl-Z to suspend cmd Like in the $PROMPT_COMMAND approach, the exit status of the command will not be available in $? . You can work around 1 above by doing: xfce4-terminal -e 'sh -c "trap : INT; cmd; exec bash"' Or: xfce4-terminal -e 'sh -ic "cmd; exec bash"' With that latter one, you'll also be able to suspend the process with Ctrl-Z , but you won't be able to use fg/bg on it. You'll be able to continue it in background though by doing a kill -s CONT on the pid of cmd .
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/75902', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4485/']}
jdg_375917
stackexchange
llm_judgeable_groundtruth_similarity
87132
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: In a famous plot, Charles Minard visualised the losses of the French Army in the Russian campaign of Napoleon: (another nice example is this xkcd plot) Is there a canonical name for this type of visualisation? I'm actually looking for an R package to create such plots, but I don't even know how to look for it. EDIT: As I could not find a good package in R do do this type of plots, I have created my own, called "riverplot" -- you can download it from CRAN . Here is a simplified version of the above diagram: And an example of what other diagrams can be created with the package: Now provide the response and nothing else.
It is a map, and so cartographers would likely refer to it as a thematic map (as opposed to a topographical map). The fact that many statistical diagrams have unique names (e.g. a bar chart, a scatterplot, a dotplot) as opposed to just describing their contents can sometime be a hindrance. Both because not everything is named (as is the case here) and the same name can refer to different types of displays ( dotplot is a good example). In the Grammar of Graphics Wilkinson describes a graph as geometric elements displayed in a particular coordinate system. Here he refers to Napoleon's March as a path element whose width represents the number of troops. In this example the path is drawn in a Cartesian coordinate system whose points represent actual locations in Europe. The points are connected as a representation of the journey Napoleon and his army took, although it likely does not exactly trace the journey (nor does the wider element at the start mean the army took up more space on the road!) There are many different software programs that have the capabilities to to draw this type of diagram. Michael Friendly has a whole page of examples . Below is a slightly amended example using the ggplot2 package in R (as you requested an example in R), although it could certainly be replicated in base graphics. mydir <- "your directory here"setwd(mydir)library(ggplot2)troops <- read.table("troops.txt", header=T) #data is from Friendly linkcities <- read.table("cities.txt", header=T) #http://www.datavis.ca/gallery/minard/ggplot2/ggplot2-minard-gallery.ziptemps <- read.table("temps.txt", header=T)temps$date <- as.Date(strptime(temps$date,"%d%b%Y"))xlim <- scale_x_continuous(limits = c(24, 39))p <- ggplot(cities, aes(x = long, y = lat)) + geom_path( aes(size = survivors, colour = direction, group = group), data=troops, linejoin = "round", lineend = "round" ) + geom_point() + geom_text(aes(label = city), hjust=0, vjust=1, size=4) + scale_size(range = c(1, 10)) + scale_colour_manual(values = c("grey50","red")) + xlim + coord_fixed(ratio = 1)pggsave(file = "march.png", width=16, height=4) Here are a few of the things that make this different than the original: I did not display the temperature graph at the bottom of the plot. In ggplot2 you can make a separate graph, you cannot draw lines across the separate graph windows though. Minard's original graph shows the path diminishing in steps between cities. This graph does not interpolate the losses like that, and shows abrupt changes from city to city. (Troop sizes are taken from a diary of a physician who traveled with the army I believe) This graph shows the exact location of the contemporary cities, Minard tended to bend space slightly to make the graph nicer. A more blatant example is the location of England in Minards map of migration flows .
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/87132', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/14803/']}
jdg_375918
stackexchange
llm_judgeable_groundtruth_similarity
34604217
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 compress image taken from camera to 250kb size in Xamarin.Forms. I found ways to do that in dependency service but I want it without dependency service (pure xamarin.forms code). How could it possible. Can anyone suggest me best approaches you have? Thanks in advance Now provide the response and nothing else.
It is a very complicated job since you would need a ton of knowledge about image processing. Most importantly, re-inventing wheel is a bad move. http://www.codeproject.com/Articles/83225/A-Simple-JPEG-Encoder-in-C Take a look of the above code project which only tackles JPEG; not to say TIFF, GIF, BMP etc. Image compression involves many complex mathematics transforms, like DCT and Huffman. You will need a whole university semester to learn those basics. On the other hand, wisely utilizing platform support, you can complete the task within a minute. BitmapEncoder in Windows Phone. FileStream stream = new FileStream("new.jpg", FileMode.Create);JpegBitmapEncoder encoder = new JpegBitmapEncoder();encoder.QualityLevel = 30;encoder.Frames.Add(BitmapFrame.Create(image));encoder.Save(stream); Bitmap in Android using (System.IO.Stream stream = System.IO.File.Create(targetFile)){ bitmap.Compress(Bitmap.CompressFormat.Jpeg, 30, stream);} UIImage in iOS NSData data = image.AsJPEG(0.3); Bitmap in .NET framework ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();ImageCodecInfo codec = codecs.First(t => t.FormatID == ImageFormat.Jpeg.Guid);EncoderParameters parameters = new EncoderParameters(1);parameters.Param[0] = new EncoderParameter(Encoder.Quality, 30L);bitmap.Save("output.jpg", codec, parameters);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34604217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1669601/']}
jdg_375919
stackexchange
llm_judgeable_groundtruth_similarity
42415
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: One of the steps for setting up OpenVPN is running the command openssl dhparam -out dh1024.pem 1024 . The man page tells me this 1024 value refers to the number of bits. Why is the value 1024 suggested by the examples? Should I use a larger value like 4096 ? What value should I use, how many bits are enough, why? RSA 1024 bit keys are now considered weak, and it is often suggested that to use 2048 bit or higher. Does this type of situation apply to this dhparam file as well? The command to generate this file seems takes ~10 hours on the appliance I that I will be using as the OpenVPN server. Is it safe to generate this file on a faster machine machine and transfer it over, or should I treat it like most private keys, and keep it on that host only? How secret should this file be? Now provide the response and nothing else.
Much of this has been addressed before. See my answer and Thomas's answer to a related question for more info about DH and DH parameters. The parameters are just primes, not keys. They don't need to be unique or secret, but they must also not be specially crafted by an attacker. The bit length refers to the size of the prime not a key , so it's not directly comparable to RSA. Note that an RSA key of 2048 bits is composed of a pair of 1024-bit primes, so you're on the same level with respect to factorization with a 1024-bit DH prime versus a 2048 RSA key. As Thomas's answer linked above points out, the number doesn't need to be unique or secret, and in fact your crypto library may provide a DH prime that will work just fine (assuming you trust the source of the library). Or you can generate one yourself. Additional Detail In Light of Recent Discoveries First of all, the advice about prime size is largely still correct -- 512 is too small, and 1024 is probably good enough (some caveats apply) while 2048 is definitely secure. Additionally, though, a precomputation attack was demonstrated such that if you know the primes ahead of time, you can do the majority of the work of cracking a given DH exchange beforehand. It's a ton of calculation and takes a huge amount of time to compute all the possible vectors for a given set of primes, but if a single set of primes is used everywhere, then there's an incentive to spend the time and money because the result will be so widely useful. This means that using the same primes as everyone else is something of a liability, because it's more likely that the precomputation will have been done by your attacker. So you probably will want to generate your own unique primes to keep yourself out of the attack pool. Further, if you, yourself, are such an attractive target that an adversary is willing to spend millions per month to attack you (e.g. Facebook-size targets) then rotating out your primes on a regular basis may be warranted. As for the cost and effort required for doing this precomputation, the work for 512-bit primes can be done by a dedicated individual, for 1024-bit primes by a nation-state, and 2048-bit primes by perhaps an advanced alien civilization.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/42415', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/919/']}
jdg_375920
stackexchange
llm_judgeable_groundtruth_similarity
18081155
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 raised an error using raise(ConfigurationError.new(msg)) I tried to test this with rspec: expect { Base.configuration.username}.to raise_error(ConfigurationError, message) But this doesn't work. How can I test this? The goal is to match message . Now provide the response and nothing else.
You can match error message with regex: it { expect{ Foo.bar }.to raise_error(NoMethodError, /private/) } This will check if NoMethodError raised with private method message not undefined method . Will be useful because NoMethodError.new didn't pass tests even with same error message.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18081155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1291365/']}
jdg_375921
stackexchange
llm_judgeable_groundtruth_similarity
54695534
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 api that should allow multiple params but for three of them I would like to allow only one of them.It easier with values for each key but I am wondering if Joi allows it too or I should add extra validation logic in my server. In short, for keys a , b or c I want to fail any request that has more than one of the three, so: http://myapi.com/?a=value is a valid request. http://myapi.com/?b=value&c=value2 is invalid . Thanks! Now provide the response and nothing else.
You're looking for object.xor(peers) if exactly one of a , b , or c is required. Defines an exclusive relationship between a set of keys where one of them is required but not at the same time where: peers - the exclusive key names that must not appear together but where one of them is required. peers can be a single string value, an array of string values, or each peer provided as an argument. const schema = Joi.object().keys({ a: Joi.any(), b: Joi.any(), c: Joi.any()}).xor('a', 'b', 'c'); Or, object.oxor(peers) if only one of a , b , or c is allowed, but none are required. Defines an exclusive relationship between a set of keys where only one is allowed but none are required where: peers - the exclusive key names that must not appear together but where none are required. const schema = Joi.object().keys({ a: Joi.any(), b: Joi.any(), c: Joi.any()}).oxor('a', 'b', 'c');
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54695534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5751251/']}
jdg_375922
stackexchange
llm_judgeable_groundtruth_similarity
3250241
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: Why are Sobolev spaces useful, and what problems were they developed to overcome? I'm particularly interested in their relation to PDEs, as they are often described as the 'natural space in which to look for PDE solutions' - why is this? How do weak solutions and distributions come into this? There are plenty of books on the subject, but these seem to jump straight into the details and I'm struggling to see the big picture. I know that the Sobolev norm makes the function spaces complete, which would guarantee that infinite linear combinations of solutions do not leave the space, as can be a problem when working with $\mathscr{C}^2$ , for example, but are there any other reasons why this norm is important? I'm also interested in the Sobolev embedding theorems, since I believe that they're important in the problems I'm trying to solve. These are (1) proving the compactness of the integral operator whose kernel is the Green's function for the Laplacian on a bounded domain $\Omega \subset \mathbb{R}^{n}$ with smooth boundary, and (2) understanding why minimising functions of the Rayleigh quotient, $${\arg\min}_{f \in T} \int_{\Omega} \frac{\nabla f \cdot \nabla f}{\left< f , f \right>}$$ always exist, and that they are necessarily smooth ( $\mathscr{C}^\infty(\Omega)$ ) among the set of trial functions $T$ of continuous functions with piecewise continuous first derivatives which vanish at the boundary and are not identically zero. To me, this sounds like the Sobolev space $H_0^1 (\Omega)$ at work, where the smoothness is the result of a Sobolev embedding theorem; however, I'm very new to Sobolev spaces and so don't know much about this. Could anyone provide me with some insight into how results (1) and (2) might be proven? Now provide the response and nothing else.
To motivate Sobolev spaces, let me pose a motivating problem. Let $\Omega$ be a smooth, bounded domain in ${\Bbb R}^n$ and let $f$ be a $C^\infty$ function on $\Omega$ . Prove that there exists a $C^2$ function $u$ satisfying $-\Delta u = f$ in $\Omega$ and $u = 0$ on the boundary of $\Omega$ . As far as PDE's go, this is the tamest of the tame: it's a second-order, constant coefficient elliptic PDE with a smooth right-hand side and a smooth boundary. Should be easy right? It certainly can be done, but you'll find it's harder than you might think. Imagine replacing the PDE with something more complicated like $-\text{div}(A(x)\nabla u) = f$ for some $C^1$ uniformly positive definite matrix-valued function $A$ . Proving even existence of solutions is a nightmare. Such PDE's come up all the time in the natural sciences, for instance representing the equillibrium distribution of heat (or stress, concentration of impurities,...) in a inhomogenous, anisotropic medium. Proving the existence of weak solutions to such PDE's in Sobolev spaces is incredibly simple: once all the relevant theoretical machinery has been worked out, the existence, uniqueness, and other useful things about the solutions to the PDE can be proven in only a couple of lines. The reason Sobolev spaces are so effective for PDEs is that Sobolev spaces are Banach spaces, and thus the powerful tools of functional analysis can be brought to bear. In particular, the existence of weak solutions to many elliptic PDE follows directly from the Lax-Milgram theorem . So what is a weak solution to a PDE? In simple terms, you take the PDE and multiply by a suitably chosen ${}^*$ test function and integrate over the domain. For my problem, for instance, a weak formulation would be to say that $-\int_\Omega v\Delta u \, dx = \int_\Omega fv \, dx$ for all $C^\infty_0$ functions $v$ . We often want to use integration by parts to simplify our weak formulation so that the order of the highest derivative appearing in the expression goes down: you can check that in fact $\int_\Omega \nabla v\cdot \nabla u \, dx = \int_\Omega fv \, dx$ for all $C^\infty_0$ functions $v$ . Note the logic. You begin with a smooth solution to your PDE, which a priori may or may not exist. You then derive from the PDE a certain integral equation which is guaranteed to hold for all suitable test functions $v$ . You then define $u$ to be a weak solution of the PDE if the integral equation holds for all test functions $v$ . By construction, every classical solution to the PDE is a weak solution. Conversely, you can show that if $u$ is a $C^2$ weak solution, then $u$ is a classical solution. ${}^\dagger$ Showing the existence of solutions in a Sobolev space is easy, but proving that they have enough regularity (that is, they are continuous differentiable up to some order— $2$ , in our case) to be classical solutions often requires very length and technical proofs. ${}^\$$ (The Sobolev embedding theorems you mention in your post are one of the key tools--they establish that if you have enough weak derivatives in a Sobolev sense, then you also are guaranteed to have a certain number of classical derivatives. The downside is you have to work in a Sobolev space $W^{k,p}$ where $p$ is larger than the dimension of the space, $n$ . This is a major bummer since we like to work in $W^{k,2}$ since it is a Hilbert space, and thus has much nicer functional analytic tools. Alternatively, if you show that your function is in $W^{k,2}$ for every $k$ , then it is guaranteed to lie in $C^\infty$ .) All of what I've written kind of dances around the central question of why Sobolev spaces are so useful and why all of these functional analytic tools work for Sobolev spaces but not for spaces like $C^2$ . In a sentence, completeness is really, really important . Often, in analysis, when we want to show a solution to something exists, it's much easier to construct a bunch of approximate solutions and then show those approximations converge to a bona fide solution. But without completeness, there might not be a solution ( a priori , at least) for them to converge to. As a much simpler example, think of the intermediate value theorem. $f(x) = x^2-2$ has $f(2) = 2$ and $f(0) = -2$ , so there must exist a zero (namely $\sqrt{2}$ ) in $(0,2)$ . This conclusion fails over the rationals however, since the rationals are not complete, $\sqrt{2} \notin {\Bbb Q}$ . In fact, one way to define the Sobolev spaces is as the completion of $C^\infty$ (or $C^k$ for $k$ large enough) under the Sobolev norms. ${}^\%$ I have not the space in this to answer your questions (1) and (2) directly, as answering these questions in detail really requires spinning out a whole theory. Most graduate textbooks on PDEs should have answers with all the details spelled out. (Evans is the standard reference, although he doesn't include potential theory so he doesn't answer (1), directly at least.) Hopefully this answer at least motivates why Sobolev spaces are the "appropriate space to look for solutions to PDEs". ${}^*$ Depending on the boundary conditions of the PDE's, our test functions may need to be zero on the boundary or not. Additionally, to make the functional analysis nice, we often want our test functions to be taken from the same Sobolev space as we seek solutions in. This usually poses no problem as we may begin by taking our test functions to be $C^\infty$ and use certain approximation arguments to extend to all functions in a suitable Sobolev space. ${}^\dagger$ Apply integration by parts to recover $-\int_\Omega v\Delta u \, dx = \int_\Omega fv \, dx$ for all $C^\infty_0$ functions $v$ and apply the fundamental lemma of calculus of variations . ${}^\$$ Take a look at a regularity proof for elliptic equations in your advanced PDE book of choice. ${}^\%$ You might ask why complete in Sobolev norm, not some simpler norm like $L^p$ ? Unfortunately, the $L^p$ completion of $C^\infty$ is $L^p$ , and there are functions in $L^p$ which you can't define any sensible weak or strong derivative of. Thus, in order to define a complete normed space of differentiable functions, the derivative has to enter the norm (which is why the Sobolev norms are important, and in some sense natural.)
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/3250241', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/201881/']}
jdg_375923
stackexchange
llm_judgeable_groundtruth_similarity
3116330
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 website with articles and sections,each sections can have a parent section, as much as they likefor example: subject 1 -subject 2 --subject 3 -subject 4 --subject 5 --subject 6 ---subject 7subject 8subject 9 etc.. Now, i want to fetch them recursively, what is the most efficient way to do it via php and mysql? Tnx in advanced. Now provide the response and nothing else.
If the tree isn't too large, you can simply build the tree in PHP using some clever references. $nodeList = array();$tree = array();$query = mysql_query("SELECT category_id, name, parent FROM categories ORDER BY parent");while($row = mysql_fetch_assoc($query)){ $nodeList[$row['category_id']] = array_merge($row, array('children' => array()));}mysql_free_result($query);foreach ($nodeList as $nodeId => &$node) { if (!$node['parent'] || !array_key_exists($node['parent'], $nodeList)) { $tree[] = &$node; } else { $nodeList[$node['parent']]['children'][] = &$node; }}unset($node);unset($nodeList); This will give you the tree structure in $tree with the children in the respective children -slot. We've done this with fairly large trees ( >> 1000 items) and it's very stable and a lot faster than doing recursive queries in MySQL.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3116330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364580/']}
jdg_375924
stackexchange
llm_judgeable_groundtruth_similarity
118032
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: I was asked the following question in an interview. Given an array $A$ with $n$ integers and an array $B$ with $m$ integers. For each integer $b \in B$ return and integer $a \in A$ such that $a \otimes b$ is minimum, where $x\otimes y$ for to integers $x$ and $y$ is the bitwise xor operation of $x$ and $y$ . For example: Input: A = [3, 2, 9, 6, 1]B = [4, 8, 5, 9] Output [6, 9, 6, 9] Because when 4 is XORed with any element in A minimum value will occur when A[I] = 6 4 ^ 3 = 74 ^ 2 = 64 ^ 9 = 134 ^ 6 = 24 ^ 1 = 5 Here is my brute force solution in python. def get_min_xor(A, B): ans = [] for val_b in B: min_xor = val_b ^ A[0] for val_a in A: min_xor = min(min_xor, val_b ^ val_a) # print("{} ^ {} = {}".format(val_b, val_a, val_b ^ val_a)) ans.append(min_xor ^ val_b) return ans Any ideas on how this could be solved in sub O(MxN) time complexity? I had the following idea in mind.I would sort the array A in O(NlogN) time then for each element in B. I would try to find it's place in the array A using binary search.Let's say B[X] would fit at ith position in A then I would check the min XOR of B[X] ^ A[i-1] and B[X] ^ A[i+1] . But this approach won't work in all the cases. For example the following input A = [1,2,3]B = [2, 5, 8] Output: [2, 1, 1] Here is the trie based solution class trie(object): head = {} def convert_number(self, number): return format(number, '#032b') def add(self, number): cur_dict = self.head binary_number = self.convert_number(number) for bit in binary_number: if bit not in cur_dict: cur_dict[bit] = {} cur_dict = cur_dict[bit] cur_dict[number] = True def search(self, number): cur_dict = self.head binary_number = self.convert_number(number) for bit in binary_number: if bit not in cur_dict: if bit == "1": cur_dict = cur_dict["0"] else: cur_dict = cur_dict["1"] else: cur_dict = cur_dict[bit] return list(cur_dict.keys())[0]def get_min_xor_with_trie(A,B): number_trie = trie() for val in A: number_trie.add(val) ans = [] for val in B: ans.append(number_trie.search(val)) return ans Now provide the response and nothing else.
Using Trie Data Structure , you can solve this problem in $O(m + n)$ if we know that values are computer integers (e.g. all 32-bit or 64-bit values). Let say we know that all integers in $A$ are 32-bit values. Use the following steps: Create an empty trie. Every node of trie may contains at most two childrenfor 0 and 1 bits. Insert all values in $A$ into the tree in $O(32 \times m) = O(m)$ For each value in $B$ , traverse the tree from the leftmost bit. If a bit doesn't match with child of a middle node, continue the traverse using the existing child until you reach a leaf. Traversing finishes in $O(32 \times n) = O(n)$ Which in total, the complexity is $O(m + n)$ .
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/118032', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/112833/']}
jdg_375925
stackexchange
llm_judgeable_groundtruth_similarity
15695
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: Please consider the following: Split[data, patterns &]patterns=Not[#=="a"]&&Not[#=="b"]&&...&&Not[#=="blabla"]; How can I define patterns without typing &&Not[#=="char"] for every single pattern? Now provide the response and nothing else.
You can add some syntactic sugar to do that relatively easily. For example, define a head for that: ClearAll[SplitPattern];SplitPattern /: Split[expr_, SplitPattern[pt_]] := Split[expr, MatchQ[#, pt] &]; And use this as follows: lst = {"a", "b", "c", "d", "blabla", "e", "f"}Split[lst,SplitPattern[Except["a"|"b"|"blabla"]]](* {{a},{b},{c,d,blabla},{e,f}} *) The performance may not be that great, but I guess the question was more about convenience.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/15695', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/508/']}
jdg_375926
stackexchange
llm_judgeable_groundtruth_similarity
2155553
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 an SQL Table which consists of 1 column only Column NameA AABBBBCDDE I need an SQL Code that returns the cut points. For the table above, it will return this: Column Name 3 7 8 10 11 3 is the end of A's and 7 is the end of B's and 8 is the end of C's and so on... Let's see what can you come up with :=) Now provide the response and nothing else.
Assuming the data can be sorted on your Column , the plan is to generate a row number for each row and do a group by to retrieve your data points. SQL Server 2000 DECLARE @YourTable TABLE (Col VARCHAR(1))CREATE TABLE #TempTable (ID INTEGER IDENTITY(1, 1), Col VARCHAR(1))SET IDENTITY_INSERT #TempTable OFFINSERT INTO @YourTable (Col) VALUES ('A')INSERT INTO @YourTable (Col) VALUES ('A')INSERT INTO @YourTable (Col) VALUES ('A')INSERT INTO @YourTable (Col) VALUES ('B')INSERT INTO @YourTable (Col) VALUES ('B')INSERT INTO @YourTable (Col) VALUES ('B')INSERT INTO @YourTable (Col) VALUES ('B')INSERT INTO @YourTable (Col) VALUES ('C')INSERT INTO @YourTable (Col) VALUES ('D')INSERT INTO @YourTable (Col) VALUES ('D')INSERT INTO @YourTable (Col) VALUES ('E')INSERT INTO #TempTableSELECT *FROM @YourTableORDER BY ColSELECT MAX(ID)FROM #TempTableGROUP BY ColDROP TABLE #TempTable SQL Server 2005 DECLARE @Table TABLE (Col VARCHAR(1))INSERT INTO @Table VALUES ('A')INSERT INTO @Table VALUES ('A')INSERT INTO @Table VALUES ('A')INSERT INTO @Table VALUES ('B')INSERT INTO @Table VALUES ('B')INSERT INTO @Table VALUES ('B')INSERT INTO @Table VALUES ('B')INSERT INTO @Table VALUES ('C')INSERT INTO @Table VALUES ('D')INSERT INTO @Table VALUES ('D')INSERT INTO @Table VALUES ('E')SELECT MAX(RowNumber)FROM (SELECT RowNumber = ROW_NUMBER() OVER (ORDER BY Col), Col FROM @Table) tGROUP BY Col
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2155553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182982/']}
jdg_375927
stackexchange
llm_judgeable_groundtruth_similarity
106333
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: The question derived from @Jason B 's answer .I wanna make it but don't how to do.But we can get some rule about the GIF The change of the total pixel is very small. imagelist = Import["http://i.stack.imgur.com/y9np9.gif"] totalpixel = ImageMeasurements[#, "Total"] & /@ imagelist // Total /@ # &;ListLinePlot[Differences[totalpixel]/Most@totalpixel, Mesh -> All] A frame texture and the next frame roughly is the same. So how to make this GIF by its first frame? Now provide the response and nothing else.
I am delighted by this problem mostly because I was not aware of the underlying physical model of phase separation (the Cahn–Hilliard equation )! Anyway, here is an approximation of a somewhat similar behavior to start the discussion: NestList[ Sharpen@Threshold[GaussianFilter[#, 2], {"Hard", {"BlackFraction", 0.1}}] &, img, 50];ListAnimate[%] I am looking forward to something better from the image processing experts! Here is an alternative method. It is still based on image processing, but it uses CommonestFilter instead of the combination of operations used before. It is interesting to note that these situations almost always reach a steady state in relatively few iterations (hence the use of FixedPointList rather than NestList here. SeedRandom[20160216]img = Image@RandomChoice[{0, 1}, {256, 256}];list = FixedPointList[Binarize[CommonestFilter[#, 3], 0.5] &, img, 2000];
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/106333', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/21532/']}
jdg_375928
stackexchange
llm_judgeable_groundtruth_similarity
261416
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to take my desktop into a PC repair shop and leave it for a few days. It would be easy for them to copy the drives without me knowing. I am running Windows 10 with a password but this doesn't actually encrypt the drive. I have multiple SSDs in the PC. I considered just taking the SSDs out but this isn't a good idea because I want them to fix cabling issues (someone told me installing a new power supply is easy but I disagree). I thought about encrypting sensitive files and encrypting them with Veracrypt but this doesn't seem to be a great idea. I would have to: a) find each file; b) encrypt it and then decrypt to use; c) securely wipe the unencrypted file. Is there a better option? Now provide the response and nothing else.
Swapping the SSDs for blank (or at least empty of anything-you-care-about) ones would work, though of course then you'd have to swap them back afterward and that has some potential to mess up the cabling (depends on your case). It also requires some SSD(s) you don't care about. Actually encrypting the drive is a good option. You can use Bitlocker (the Windows built-in disk encryption feature), though depending on your hardware and your Windows edition you might need to upgrade some stuff and/or change some settings to make this work (by default, Bitlocker wants a TPM, and I'm not sure if it's available on Home editions or not). You might be able to use "Device Encryption" even on Windows 10 Home ; this is just BitLocker under the covers, but with less user control over its behavior (and in particular, it does require TPM 2.0, which many but not all modern machines have built into their CPUs). Alternatively you can use a third-party encryption utility. Veracrypt (among others) is able to perform full-volume encryption (same as Bitlocker) such that the OS and data are inaccessible without a password or USB key. In either case, the shop would still be able to turn the computer on, though not to get very far; they'd be stopped at or before the Windows login screen. However, all the data (not just specific files) on the disks would be encrypted at rest. Finally, depending on the shop and the machine in question, you could remove the SSDs while whatever else gets fixed, and then bring them with you and ask the technician to install them while you watch. Installing SSDs takes very little time in most cases, especially for a trained and experienced technician, and can be done without ever letting the SSDs or machine out of your sight. Of course, if the SSDs are SATA and the shop doesn't know you're going to install a bunch of SATA SSDs, they might not run the power and data cables where you'll need them, which might slightly increase the time to install them. Not by much, though. Replacing the PSU on most cases really is quite easy, with cable management being the only tricky part at all and still not that hard (unless your case layout is really inconvenient or the cables are too short, which sometimes happens).
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/261416', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/136923/']}
jdg_375929
stackexchange
llm_judgeable_groundtruth_similarity
54200465
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 noticed just now that the following code can be compiled with clang/gcc/clang++/g++, using c99 , c11 , c++11 standards. int main(void) { int i = i;} and even with -Wall -Wextra , none of the compilers even reports warnings. By modifying the code to int i = i + 1; and with -Wall , they may report: why.c:2:13: warning: variable 'i' is uninitialized when used within its own initialization [-Wuninitialized] int i = i + 1; ~ ^1 warning generated. My questions: Why is this even allowed by compilers? What does the C/C++ standards say about this? Specifically, what's the behavior of this? UB or implementation dependent? Now provide the response and nothing else.
Because i is uninitialized when use to initialize itself, it has an indeterminate value at that time. An indeterminate value can be either an unspecified value or a trap representation . If your implementation supports padding bits in integer types and if the indeterminate value in question happens to be a trap representation, then using it results in undefined behavior . If your implementation does not have padding in integers, then the value is simply unspecified and there is no undefined behavior. EDIT: To elaborate further, the behavior can still be undefined if i never has its address taken at some point. This is detailed in section 6.3.2.1p2 of the C11 standard: If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined. So if you never take the address of i , then you have undefined behavior. Otherwise, the statements above apply.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54200465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/528929/']}
jdg_375930
stackexchange
llm_judgeable_groundtruth_similarity
9561138
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 some HTML that contains a JSON string. In the on DOM ready callback, I have something like this: MyObject = JSON.parse($('#TheJsonString').html()); Later in my code, I write something this: var SomeVar = MyObject.MyProp1; And then when I run the code through the Google closure compiler, I get the warning Property MyProp1 never defined on MyObject. How should the code be written so that it doesn't generate a warning? Now provide the response and nothing else.
The cleanest way to remove the warning is by defining the structure of the JSON. This can be done using the @type tag: /** @type {{MyProp1:string}} */ Where MyProp1 is the name of the property, and string is the type. Google's Closure compiler will rename the variable. If you don't want that, you have to use quotes + brackets instead of the dot-notation: MyObject['MyProp1'] Example : paste the following in the Closure Compiler : // ==ClosureCompiler==// @compilation_level ADVANCED_OPTIMIZATIONS// ==/ClosureCompiler==var MyObject;function x() { // Magic happens at the next line /** @type {{MyProp1:string}}*/ MyObject = JSON.parse(prompt(''));}function afterX() { var SomeVar = MyObject.MyProp1; alert(SomeVar);}x();afterX(); Output: var a;a=JSON.parse(prompt(""));alert(a.a);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9561138', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565968/']}
jdg_375931
stackexchange
llm_judgeable_groundtruth_similarity
57707
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 just have a quick question about Markov Chain and linear algebra. Background. Let $\{M_n: n= 0, 1, 2, \dots \}$ be a Markov Chain. We can represent the transition probabilities $_{n}Q^{(i,j)}$ in a $s \times s$ matrix $Q$. Note that $_{n}Q^{(i,j)}$ is the same thing as $P(M_{m+n} = j|M_{m} = i)$. Question. Is the matrix $Q$ the same in the sense of linear transformations? In particular, suppose we have two vector spaces $V$ and $W$. If we choose an ordered basis for $V$ and an ordered basis for $W$ we can represent linear transformations from $V$ to $W$ as matrices. So then we can talk about the rank, nullity, kernel, etc...But does the term matrix in context of Markov chains just mean an array of numbers? Now provide the response and nothing else.
Let $s$ denote the number of states for the chain, so that $_n Q$ is an $s \times s$ matrix containing the $n$-step transition probabilities. Let's start with $n=1$, and consider the matrix $Q$ of $1$-step transition probabilities. If $S$ is the state space (a finite set of size $s$), consider the $s$-dimensional vector space $V$ of all functions $f : S \to \mathbb{R}$, with pointwise addition and scalar multiplication. Now let $(Af)(x) = E[f(M_1) | M_0 = x]$. You can check that $A$ is a linear transformation from $V$ to $V$. Moreover, if you choose the basis $\{f_1, \dots, f_s\}$ for $V$ where $f_i(j) = 1$ for $i=j$ and $0$ for $i \ne j$, then the matrix representation of $A$ in this basis is $Q$. So yes, there is an underlying linear transformation that can be defined in a manner independent of basis. This idea becomes very important in the case where the state space $S$ is infinite; in this case $A$ becomes a linear operator (typically unbounded) on some appropriate Banach space of functions on $S$, and many of the linear algebra arguments get replaced by functional analysis.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/57707', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12378/']}
jdg_375932
stackexchange
llm_judgeable_groundtruth_similarity
20410
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: Is it possible for one to connect a telephone cable to light up a light-bulb? Now provide the response and nothing else.
Theoretically - sort of yes. In practice, not really. The telephone system operator would be unhappy. It is possible to connect a telephone cable to light up a light-bulb (assuming that you mean the cable from a "Central Office" telephone exchange or a PBX system) BUT Doing so will probably disrupt telephone operation Doing so will be against the terms of service for the line involved The amount of power obtainable will be very very very small. An LED would be better and even that will be limited. Central Office telephone systems use 50 volt supplies. Anything below about 100,000 ohms may cause problems and even that is marginal. Available current at 100k would be 50/100k = 0.5 mA. An LED would glow dimly at that current. At 0.5 mA the available energy is V x I = 50 x 0.5 mA = 25 mW. If you used a buck converter at say 80% efficint to power an LED you'd get about 25 mW x 80% = 20 mW. For a white LED at say 3V that's about 7 mA A high efficiency modern LED would be "quite bright" to the eye but not much good for illumination. ie 1 person could read a paperback book at good light level with this. If you are prepared to draw as much power from a line as possible it will depend on how far you are away - but you may get tens of mA. Central Office systems are typically 50V. PBX may be 25V and possibly other voltages. I forget typical feed resistances by a figure of 600 ohms comes to mind. You get maximum load power when you load to half voltage (maximum power transfer theorum) so at say 600 ohm load, 25V Power = V^2/R = 625/600 or about 1 Watt. Quite possible less in practice and much less with distance. Not so good for a bulb - good for many things with an LED. BUT telephone circuits may shut the line circuit down if it sees this sort of loading.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/20410', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6018/']}
jdg_375933
stackexchange
llm_judgeable_groundtruth_similarity
12404735
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 sort my int array in ascending order. first I make a copy of my array: int[] copyArray = myArray.ToArray(); Then I would like to sort it in ascending order like this: int[] sortedCopy = from element in copyArray orderby element ascending select element; But I get a error, "selected" gets highligted and the error is:"cannot implicitly convert type 'system.linq.iorderedenumerable' to 'int[]'" Now provide the response and nothing else.
You need to call ToArray() at the end to actually convert the ordered sequence into an array. LINQ uses lazy evaluation , which means that until you call ToArray() , ToList() or some other similar method the intermediate processing (in this case sorting) will not be performed. Doing this will already make a copy of the elements, so you don't actually need to create your own copy first. Example: int[] sortedCopy = (from element in myArray orderby element ascending select element) .ToArray(); It would perhaps be preferable to write this in expression syntax: int[] sortedCopy = myArray.OrderBy(i => i).ToArray();
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12404735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1635406/']}
jdg_375934
stackexchange
llm_judgeable_groundtruth_similarity
2353342
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 am trying to study mathematics rigorously.It is mentioned in my book in the chapter of set theory that the symbol "$:$" stands for the phrase "such that". Then in the next chapter of relations, the cartesian product of two sets $A$ and $B$ is defined as follows: If $A$ and $B$ be two sets,$A\times B =\{(a,b):\forall (a\in A , b\in B) \}$. If this symbolic definition is translated into words, it reads:"The cartesian product of two sets $A$ and $B$ is defined as the set of all ordered pairs $(a,b)$ such that for all $a$ belongs to $A$ and $b$ belongs to to $B$. My concern is about the last part in the symbolic definition, that is, "$:\forall (a\in A , b\in B)$". If this is translated into words it reads "such that for all $a$ belongs to $A$ and all $b$ belongs to to $B$". This sounds incomplete to me. Is this correct both mathematically and grammatically? Would not it be better to define the cartesian product of $A$ and $B$ as $A\times B =\{(x,y):(x,y)=(a,b)\forall (a\in A , b\in B) \}$ or simply as $A\times B =\{(a,b):a\in A , b\in B) \}$. Among these three which is correct grammatically as well as rigorous mathematically? Now provide the response and nothing else.
The issue is of that of free variables. When you write $\{x : \varphi\}$, it is expected that $x$ is the only free variable of $\varphi$ (there might be parameters fixed in advance). Once you put a quantifier on $a$ and $b$, they are no longer free, and the formula is now a sentence which is either "always true" or "always false". So the set is either everything or empty. To add insult to injury, $\forall(a\in A, b\in B)$ is not a well-formed formula to begin with. The comma, while not a valid logical symbol is often taken to mean "and" in the set-builder context. So indeed the correct way to write this would be, as others and yourself have suggested $$A\times B=\{(a,b): a\in A, b\in B\}.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2353342', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/351620/']}
jdg_375935
stackexchange
llm_judgeable_groundtruth_similarity
24622725
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 wish to add git to my PATH in Windows 7, through the "shell" command in R. shell('set PATH=%PATH%;"C:\\Program%20Files%20(x86)\\Git\\bin"', intern = TRUE)shell("echo %PATH% ", intern= TRUE) But I do not see that path added. If I run the above code in cmd.exe, it does add it to PATH. Any idea what is the issue? UPDATE:I ended up manually running the following through cmd.exe (which I made sure to run as admin) setx PATH "C:\\Program Files (x86)\\Git\\bin" Which worked. But I wish I could have done so through R. (maybe create a temp file and run it?)I then had to restart some programs to make sure they had been affected. Now provide the response and nothing else.
If you want to permanantly update your path, then you pretty much had the answer: shell('setx PATH "C:\\Program Files (x86)\\Git\\bin"') R only notes a copy of the Windows environment variables when it starts up though, so strsplit(Sys.getenv("PATH"), ";") won't be different until you restart R. Also, this won't run as with admin permissions (unless you set R as an administrator?) so it will add the path to the user path variable not the system one. If you want R to see a different path in the current session, just use Sys.setenv . Sys.setenv( PATH = paste( Sys.getenv("PATH"), "C:\\Program Files (x86)\\Git\\bin", sep = ";" )) This won't make permanant changes to the path. Only R can see this change, and only until you close it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24622725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256662/']}
jdg_375936
stackexchange
llm_judgeable_groundtruth_similarity
1219974
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 say the task is to find the Taylor series at the origin of the function $$f(x) = \frac{3x}{1-x-2x^2}$$ The formula is $T^n_0 =\sum^n_{k=0} \frac{f^{(k)}(0)}{k!}x^k$. If I follow this formula, I need to at least compute the 4th or 5th derivatives to find the general expression which takes a long time and very likely ends up with a wrong expression. Now provide the response and nothing else.
HINT: Note that $1-x-2x^2=(1-2x)(1+x)$, so $$\frac{3x}{1-x-2x^2}=\frac1{1-2x}-\frac1{1+x}\;.$$ Now use a known Taylor series expansion to expand each of the fractions on the right-hand side, and combine the series into a single series. Added: Let me emphasize Math$1000$’s comment below: once you know a few power series, you should always try to make use of them to get new ones. Here it’s just a matter of adding a couple, but sometimes you may have to work a bit harder: differentiating or integrating one, multiplying it by some power of $x$, or applying some combination of these manipulations.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1219974', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145968/']}
jdg_375937
stackexchange
llm_judgeable_groundtruth_similarity
6621785
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 to code a multithreaded(say 2 threads) program where each of these threads do a different task. Also, these threads must keep running infinitely in the background once started. Here is what I have done. Can somebody please give me some feedback if the method is good and if you see some problems. Also, I would like to know how to shut the threads in a systematic way once I terminate the execution say with Ctrl+C. The main function creates two threads and let them run infinitely as below. Here is the skeleton: void *func1();void *func2();int main(int argc, char *argv[]){ pthread_t th1,th2; pthread_create(&th1, NULL, func1, NULL); pthread_create(&th2, NULL, func2, NULL); fflush (stdout); for(;;){ } exit(0); //never reached}void *func1(){ while(1){ //do something }}void *func2(){ while(1){ //do something }} Thanks. Edited code using inputs from the answers: Am I exiting the threads properly? #include <stdlib.h> /* exit() */#include <stdio.h> /* standard in and output*/#include <pthread.h>#include <unistd.h>#include <time.h>#include <sys/time.h>#include <sys/types.h>#include <signal.h>#include <semaphore.h>sem_t end;void *func1();void *func2();void ThreadTermHandler(int signo){ if (signo == SIGINT) { printf("Ctrl+C detected !!! \n"); sem_post(&end); }}void *func1(){ int value; for(;;){ sem_getvalue(&end, &value); while(!value){ printf("in thread 1 \n"); } } return 0;}void *func2(){ int value; for(;;){ sem_getvalue(&end, &value); while(!value){ printf("value = %d\n", value); } } return 0;}int main(int argc, char *argv[]){ sem_init(&end, 0, 0); pthread_t th1,th2; int value = -2; pthread_create(&th1, NULL, func1, NULL); pthread_create(&th2, NULL, func2, NULL); struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = ThreadTermHandler; // Establish a handler to catch CTRL+c and use it for exiting. if (sigaction(SIGINT, &sa, NULL) == -1) { perror("sigaction for Thread Termination failed"); exit( EXIT_FAILURE ); } /* Wait for SIGINT. */ while (sem_wait(&end)!=0){} //{ printf("Terminating Threads.. \n"); sem_post(&end); sem_getvalue(&end, &value); /* SIGINT received, cancel threads. */ pthread_cancel(th1); pthread_cancel(th2); /* Join threads. */ pthread_join(th1, NULL); pthread_join(th2, NULL); //} exit(0);} Now provide the response and nothing else.
There are mainly two approaches for thread termination. Use a cancellation point. The thread will terminate when requested to cancel and it reaches a cancellation point, thus ending execution in a controlled fashion; Use a signal. Have the threads install a signal handler which provides a mechanism for termination (setting a flag and reacting to EINTR ). Both approaches has caveats. Refer to Kill Thread in Pthread Library for more details. In your case, it seems a good opportunity to use cancellation points. I will work with a commented example. The error-checking has been omitted for clarity. #define _POSIX_C_SOURCE 200809L#include <pthread.h>#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>void sigint(int signo) { (void)signo;}void *thread(void *argument) { (void)argument; for (;;) { // Do something useful. printf("Thread %u running.\n", *(unsigned int*)argument); // sleep() is a cancellation point in this example. sleep(1); } return NULL;}int main(void) { // Block the SIGINT signal. The threads will inherit the signal mask. // This will avoid them catching SIGINT instead of this thread. sigset_t sigset, oldset; sigemptyset(&sigset); sigaddset(&sigset, SIGINT); pthread_sigmask(SIG_BLOCK, &sigset, &oldset); // Spawn the two threads. pthread_t thread1, thread2; pthread_create(&thread1, NULL, thread, &(unsigned int){1}); pthread_create(&thread2, NULL, thread, &(unsigned int){2}); // Install the signal handler for SIGINT. struct sigaction s; s.sa_handler = sigint; sigemptyset(&s.sa_mask); s.sa_flags = 0; sigaction(SIGINT, &s, NULL); // Restore the old signal mask only for this thread. pthread_sigmask(SIG_SETMASK, &oldset, NULL); // Wait for SIGINT to arrive. pause(); // Cancel both threads. pthread_cancel(thread1); pthread_cancel(thread2); // Join both threads. pthread_join(thread1, NULL); pthread_join(thread2, NULL); // Done. puts("Terminated."); return EXIT_SUCCESS;} The need for blocking/unblocking signals is that if you send SIGINT to the process, any thread may be able to catch it. You do so before spawning the threads to avoid having them doing it by themselves and needing to synchronize with the parent. After the threads are created, you restore the mask and install a handler. Cancellation points can be tricky if the threads allocates a lot of resources; in that case, you will have to use pthread_cleanup_push() and pthread_cleanup_pop() , which are a mess. But the approach is feasible and rather elegant if used properly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6621785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/489152/']}
jdg_375938
stackexchange
llm_judgeable_groundtruth_similarity
1270218
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: Two dice are rolled. What is the probability that the sum of the numbers on the dice is at least 10 Let $Z$ denote the set of successful outcomes: $Z=\{(4,6),(6,4),(5,5),(5,6),(6,5),(6,6)\}\\\text{Sample space: }S=6^2$ So the answer gives the probability as, $P=\frac{6}{36}$. My question is why are the pairs $(5,5),(6,6)$ only included once? The way I see it for two dice $D_1,D_2$ is it may appear as $D_1: 5,D_2: 5$ or $D_2: 5,D_1: 5$, so why don't we count for this as two outcomes? Now provide the response and nothing else.
Let $(x,y)$ be the ordered pair of rolls. When $x\ne y$, we have $(x,y)\ne (y,x)$. For instance, $(3,5)$ and $(5,3)$ are different. However, when $x=y$, we have $(x,x)=(x,x)$, (even though I switched the $x$s). You may want to consider the table of two die rolls that shows all possible outcomes: $$\begin{array}{c|c|c|c|c|c|c|} &1&2&3&4&5&6 \\ \hline 1&(1,1)&(1,2)&(1,3)&(1,4)&(1,5)&(1,6) \\ \hline 2&(2,1)&(2,2)&(2,3)&(2,4)&(2,5)&(2,6) \\&&&etc.\end{array}$$ Each double $(x,x)$ occurs only once in the table.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1270218', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/30166/']}
jdg_375939
stackexchange
llm_judgeable_groundtruth_similarity
569534
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: $N$ points are selected in a uniformly distributed random way in a disk of a unit radius. Let $L(N)$ denote the expected length of the shortest polygonal path that visits each of the points at least once (the path need not to be closed any may be self-intersecting). For what $N$ do we know the exact value of $L(N)$? Is there a general formula for $L(N)$? What is the asymptotic behavior of $L(N)$ as $N\to\infty$? What are the answers to previous questions, if the disk is replaced with a ball? Now provide the response and nothing else.
Given: $(X,Y)$ is Uniformly distributed on a disc of unit radius. Then, the joint distribution of $n$ such points, $((X_1,Y_1), ..., (X_n,Y_n))$, each drawn independently, will have joint pdf: $$f( (x_1,y_1), ..., (x_n,y_n) ) = \begin{cases}\pi^{-n}& (x_1^2 + y_1^2 < 1) & \text{ & } \cdots \text{ & }&(x_n^2 + y_n^2 < 1) \\ 0 & otherwise \end{cases}$$ Next, let $Z_n$ denote the Euclidean length of the shortest polygonal path that visits each point (at least) once. For any given $n$, it is possible to express $Z_n$ as an exact symbolic construct. This rapidly gets tiresome to do manually, so I have set up a function PolygonPathMinDistance[points] to automate same (I have provided the code at the bottom of this post). For example: Case $n = 2$: With 2 points, the shortest polygonal path $Z_2$ is, of course, ... : and so the desired exact solution is: $$E[Z_2] = E\left[\sqrt{\left(X_1-X_2\right){}^2+\left(Y_1-Y_2\right){}^2}\right] \approx 0.9054$$ where the random variables $(X_1, Y_1, X_2, Y_2)$ have joint pdf $f(\cdots)$ given above. Although getting a closed form solution for the expectation integral has thus far proved elusive (perhaps transforming to polar coordinates might be a path worth pursuing - see below), the result is just a number, and we can find that number to arbitrary precision using numerical integration rather than symbolic integration. Doing so yields the result that: $E[Z_2] = 0.9054 ...$. Case $n = 3$: With 3 points, the shortest polygonal path $Z_3$ is: and similarly obtain: $$E[Z_3] \approx 1.49 ...$$ Case $n = 4$: With 4 points, the shortest polygonal path $Z_4$ is: and similarly obtain: $$E[Z_4] \approx 1.96 ...$$ ... and so on. For cases above $n \ge 5$, the method still works fine, but numerical integration gets less reliable, and other methods, such as Monte Carlo simulation [ i.e. actually generating $n$ pseudorandom points in the disc (say 100,000 times), evaluating the actual shortest path for each and every $n$-dimensional drawing, and calculating the sample mean] appear to work more reliably. The latter is, of course, no longer an exact conceptual methodology, but as a practical evaluation method, for larger $n$, it appears to become the more practical option. Summary Plots and Fitting $$\color{red}{\text{Expected shortest polygon path connecting $n$ random points in a disc of unit radius }}$$ ... and with $n=50, 100$ and $150$ points added: The fitted model here is simply: $$a + b \frac{n-1}{\sqrt{n}}$$ with $a = -0.11$, $b = 1.388$. Fitting curves A number of 'natural' contenders present themselves, including models of form: $a + b n + c \sqrt{n}$ ... this performs neatly within sample, but as soon as one extends to larger values of $n$, the model performs poorly out of sample, and needs to be re-fitted given the extra data points. This suggests that the true model is not just square root $n$. $a + b n^c$ ... this works very neatly within sample, and outside sample, but the optimal parameter values show some instability as more data values are added. $a + b \frac{n-1}{\sqrt{n}}$ ... just 2 parameters, and works absolutely beautifully. The idea for this model was inspired by Ju'x posting. The parameter values are remarkably stable as more data points are added (they remain constant to 2 decimal places, irrespective of whether we use just $n = 2 ... 20$, or $n = 50$ is added, or $n=100$ is added, all the way up to $n = 300$), as shown here: The parameter values for $a$ and $b$ are the same as for the diagram above. Code for the PolygonPathMinDistance function Here is some Mathematica code for the exact PolygonPathMinDistance function that calculates all of the possible relevant permutations involved in calculating the shortest polygon path, as an exact symbolic/algebraic construct: PolygonPathMinDistance[points_] := Module[{orderings, pointorderings, pathsToCheck, ww}, orderings = Union[Permutations[Range[Length[points]]], SameTest -> (#1 == Reverse[#2] &)]; pointorderings = Map[points[[#]] &, orderings]; pathsToCheck = Map[Partition[#, 2, 1] &, pointorderings]; Min[Map[Total[Map[EuclideanDistance @@ # &, #1] /. Abs[ww_]->ww]&, pathsToCheck]]] . Alternative specification of problem in Polar Coordinates If points are Uniformly distributed on a disc of unit radius and independent, the joint distribution of $n$ points, $((X_1,Y_1), ..., (X_n,Y_n))$, with joint pdf $f(\cdots)$ is given above. Alternatively, consider the transformation to polar coordinates, $(X_i \to R_i cos(\Theta_i)$, $Y_i \to R_i sin(\Theta_i))$, for $i = 1$ to $n$. Then, the joint pdf is: $$f( (r_1,\theta_1), ..., (r_n,\theta_n) ) = \frac{r_1 \times r_2 \times \cdots \times r_n}{\pi^{n}}$$ with domain of support, $R_i=r_i \in \{r_i:0<r_i<1\}$ and $\Theta_i=\theta_i \in \{\theta_i:0<\theta_i<2 \pi\}$. Then, the distance between any two random points, say $(X_i,Y_i)$ and $(X_j,Y_j)$ is given by the distance formula for polar coordinates: $$\sqrt{\left(X_j-X_i\right){}^2+\left(Y_j-Y_i\right){}^2} = \sqrt{R_i^2 + R_j^2 -2 R_i R_j \cos \left(\Theta_i-\Theta_j\right)}$$ Taking expectations then yields the same results as above. For the $n = 2$ case, symbolic integration is a little easier, and one can obtain the result: $$\begin{align*}\displaystyle E\left[ Z_2\right] &= E\left[ \sqrt{R_1^2 + R_2^2 -2 R_1 R_2 \cos \left(\Theta _1-\Theta _2\right)}\right] \\ &= \frac{8}{\pi} \int_0^1\int_0^1 |r_1 - r_2| EllipticE[\frac{-4 r_1 r_2}{(r_1-r_2)^2}]r_1 r_2 dr_1\,dr_2 \\ &= \frac{8}{\pi} \frac{16}{45} \approx 0.9054 \text{(as above)}\end{align*}$$ Extending from a disc to a ball There is no inherent reason the same methods cannot be extended to a ball ... just more dimensions (and more computational grunt required).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/569534', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/109267/']}
jdg_375940