_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d7601
train
AutoMapper uses Castle Dynamic Proxy which requires Reflection.Emit which is not supported on the phone. If you want this you're going to need to look at building it all yourself. In terms of getting round the lack of reflection.Emit (if you really do need it) then you should look at using Mono.Cecil to provide this missing functionality. A: Seems that automapper is working on silverlight edition so possible WP7/WP8 compatibility coming soon. In the mean time there is a simple mapper library that you can use. It is very basic but probably meets most of your requirements for WP7 applications. // Configure LazyMapper Mapper.Create<SampleClass, SampleClassDto>(); // Perform mapping var dto = Mapper.Map<SampleClass, SampleClassDto>(new SampleClass { StringVal = "String1"}); Assert.AreEqual("String1",dto.StringVal); Download at http://lazycowprojects.tumblr.com/LazyMapper
unknown
d7602
train
So, several ways to accomplish this. My suggestion would be to utilize margin-top on the element you want to overflow. Everything else will render properly and only one item needs to be positioned properly. Visual Representation: HTML <div id="one">Item 1</div> <div id="two">Item 2</div> <div id="three">Item 3</div> CSS #one, #two, #three { position: relative; margin: 0 auto; } #one { width: 400px; height: 200px; background: #ABC; } #two { width: 200px; height: 100px; background: #CBA; margin-top: -50px; } #three { width: 400px; height: 300px; background: #BBB; } Example provided here: http://jsfiddle.net/dp83o0vt/ A: Instead of setting top: -50px; simply set margin-top: -50px; This way your .c still sticks to .b, and you don't have to mess with anything else. jsfiddle here: http://jsfiddle.net/gyrgfqdx/
unknown
d7603
train
The error happens because } catch { is a relatively recent (ES2019) language feature called "optional catch binding"; prior to its introduction, binding the caught error (e.g. } catch (err) {) was required syntactically. Per node.green, you need at least Node 10 to have that language feature. So why does this happen in ESLint? Per e.g. the release blog, version 7 has dropped support for Node 8; they're no longer testing against that version and more modern language features will be assumed to be supported. To fix it, either: * *Upgrade Node (Node 8 is out of LTS, which is why ESLint dropped support); or *npm install eslint@6 (with -g if you want to install globally) to use the older version of ESLint with Node 8 support. A: In case it's helpful for anyone, I had a slightly different twist on the other answer. In my case, the error was happening during the Travis CI build process and causing it to fail. The solution in my case was to update my .travis.yml file to node_js: "16"
unknown
d7604
train
HTTP 404 means the URL is not found: https://en.wikipedia.org/wiki/HTTP_404 It usually tells me that my packaging or mapping or request URL is incorrect. Start with the basics: write an index.html page and see that it's displayed. It's not typical to have an index controller. Once you have that page working, see if you can map to something meaningful. Is that controller in a package? I don't see a package statement at the top. It's impossible to be a Spring developer without being a solid Java developer first. No one would create a class without a package. A: I modified your code a bit to make it work. web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name></display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> </web-app> IndexController.java package com.requestengine.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/") @ResponseBody public String index(){ return "index"; }
unknown
d7605
train
You can set pyautogui.PAUSE to control the duration of the delay between actions. By default, it is set to 0.1 sec, that is why you are getting at most 10 clicks per second. pyautogui.PAUSE = 0.01 for example will reduce the delay to allow 100 clicks per second if your hardware supports it. From the doc, you can read the following: You can add delays after all of PyAutoGUI’s functions by setting the pyautogui.PAUSE variable to a float or integer value of the number of seconds to pause. By default, the pause is set to 0.1 seconds.
unknown
d7606
train
sometimes I receive these errors while terminating the process: QProcess: Destroyed while process (" ... server.exe ...") is still running It seems you are not waiting for the process to gracefully terminate. Here is a generic way to terminate a process you launched : server->terminate(); server->waitForFinished(timeoutMS); if (server->state() == QProcess::Running) { server->kill(); } Terminate will send a polite "can you please stop" signal, kill will abruptly stop the target process. How much time does it take for the server to shut down (it may be several seconds)? so you should have a generous timeout period which take this in account.
unknown
d7607
train
I was able to do this but not sure if this is the best practice. filename is set in UI in the preinit function preinit: { UploadFile: function (up, file) { // You can override settings before the file is uploaded // up.settings.url = 'upload.php?id=' + file.id; //up.settings.multipart_params = { type: $("#Type").val(), title: $("#Title").val() }; up.settings.multipart_params = { filename: file.name }; } }, Web api code [HttpPost] public async Task<IHttpActionResult> UploadPropertyImage() { if (!Request.Content.IsMimeMultipartContent()) throw new Exception(); // divided by zero var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); var name = await provider.Contents.SingleOrDefault(p => p.Headers.ContentDisposition.Name == "\"name\"").ReadAsStringAsync(); var chunk = await provider.Contents.SingleOrDefault(p => p.Headers.ContentDisposition.Name == "\"chunk\"").ReadAsStringAsync(); var chunks = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"chunks\"").ReadAsStringAsync(); var filename = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"filename\"").ReadAsStringAsync(); var buffer = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"file\"").ReadAsByteArrayAsync(); //var Id = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"Id\"").ReadAsByteArrayAsync(); var Id = Guid.Empty; var uploadPath = HostingEnvironment.MapPath(Path.Combine("~/app_data",Id.ToString())); if (!Directory.Exists(uploadPath)) Directory.CreateDirectory(uploadPath); using (var fs = new FileStream(Path.Combine(uploadPath,name), chunk == "0" ? FileMode.Create : FileMode.Append)) fs.Write(buffer, 0, buffer.Length); return Ok(); }
unknown
d7608
train
The negative number as an integer is the two's complement. To flip the sign using two's complement you do like this: "To get the two's complement of a binary number, the bits are inverted, or "flipped", by using the bitwise NOT operation; the value of 1 is then added to the resulting value, ignoring the overflow which occurs when taking the two's complement of 0." In JavaScript that would be: n = ~n + 1; If you are looking for performance, that is not likely to be the fastest way. That would most likely be to use the operator specifically designed for that: n = -n; A: It's not soo much faster. It does not make sense. When you need to negate the number noone can do it better than your CPU. http://jsperf.com/minus-vs-not A: In case anyone is wondering how you would go back and forth between a negative & positive number (n) without using the + or - signs ... n = ~n add = 1 while add: diff = add^n carry = (add&n)<<1 add = carry n = diff print(n)
unknown
d7609
train
* *Create variables for object and item *Create a SQL statement to extract data from T1 and store in object variable. Set the ResultSet to "Full result set" and map the Result SetResult Name(3) *Add a Foreach Loop Container using the Foreach ADO enumerator Use the Object variable as the source variable and map to the item (5). *Add a dataflow. In the data flow assign the T2 table as the DB source *Add a derived column and add the item variable as an extra column *Map the derived column and the T2 data to your output flatfile
unknown
d7610
train
$this->tablePopulationById[$tableId] tablePopulationById is an array that DOES NOT contain a key of index $tableId. $arrData[3]; DOES NOT contain an object of whatever class you were expecting! In both cases, var_dump them to see what you DO have! var_dump($this->tablePopulationById); var_dump($arrData);
unknown
d7611
train
There is no easy optimal solution. One approximation is as follows: * *Pick the group with the largest size. Let its size be x *Pick the largest group such that its size is less than 90-x *Keep repeating step 2 until you cannot find such a group *Remove the selected groups and repeat the process starting from Step 1 Eg. You would pick group1 (or group4 or groupN) first is step 1. In step 2 you would pick group4. Now the size is 80 and there are no groups smaller than 90-80=10. So stop and remove these two groups. In the next iteration, you will select groupN, followed by group2, and at last group3. In the last iteration you have only one group, that is group5.
unknown
d7612
train
Try function RadionButtonSelectedValueSet(name, SelectdValue) { $('input[name="' + name+ '"][value="' + SelectdValue + '"]').prop('checked', true); } also call the method on dom ready <script type="text/javascript"> jQuery(function(){ RadionButtonSelectedValueSet('RBLExperienceApplicable', '1'); }) </script> A: You can try this also function SetRadiobuttonValue(selectedValue) { $(':radio[value="' + selectedValue + '"]').attr('checked', 'checked'); } A: You can do more elegantly. function RadionButtonSelectedValueSet(name, SelectedValue) { $('input[name="' + name+ '"]').val([SelectedValue]); } A: Below script works fine in all browser: function RadionButtonSelectedValueSet(name, SelectdValue) { $('input[name="' + name + '"][value="' + SelectdValue + '"]').attr('checked',true); } A: $('input[name="RBLExperienceApplicable"]').prop('checked',true); Thanks dude... A: If the selection changes, make sure to clear the other checks first. al la... $('input[name="' + value.id + '"]').attr('checked', false); $('input[name="' + value.id + '"][value="' + thing[value.prop] + '"]').attr('checked', true); A: for multiple dropdowns $('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked"); here RBLExperienceApplicable is the matching part of the radio button groups input tag ids. and [id^=RBLExperienceApplicable] matches all the radio button whose id start with RBLExperienceApplicable A: <input type="radio" name="RBLExperienceApplicable" class="radio" value="1" checked > // For Example it is checked <input type="radio" name="RBLExperienceApplicable" class="radio" value="0" > <input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" > <input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" > $( "input[type='radio']" ).change(function() //on change radio buttons { alert('Test'); if($('input[name=RBLExperienceApplicable]:checked').val() != '') //Testing value { $('input[name=RBLExperienceApplicable]:checked').val('Your value Without Quotes'); } }); http://jsfiddle.net/6d6FJ/1/ Demo A: <asp:RadioButtonList ID="rblRequestType"> <asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem> <asp:ListItem Value="Value2">Value2</asp:ListItem> </asp:RadioButtonList> You can set checked like this. var radio0 = $("#rblRequestType_0"); var radio1 = $("#rblRequestType_1"); radio0.checked = true; radio1.checked = true; A: A clean approach I find is by giving an ID for each radio button and then setting it by using the following statement: document.getElementById('publicedit').checked = true; A: Can be done using the id of the element example <label><input type="radio" name="travel_mode" value="Flight" id="Flight"> Flight </label> <label><input type="radio" name="travel_mode" value="Train" id="Train"> Train </label> <label><input type="radio" name="travel_mode" value="Bus" id="Bus"> Bus </label> <label><input type="radio" name="travel_mode" value="Road" id="Road"> Other </label> js: $('#' + selected).prop('checked',true); A: This is the only syntax that worked for me $('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked'); A: document.getElementById("TestToggleRadioButtonList").rows[0].cells[0].childNodes[0].checked = true; where TestToggleRadioButtonList is the id of the RadioButtonList.
unknown
d7613
train
Inserting a new Tag into published_tags does not set its published attribute to true by default. What you need to do is to extend the published_tags association and override the << method of it to set the published attribute to true upon insertion. The code will look something like that: has_many :published_tags do def <<(tag) tag.published = true proxy_association.owner.posts_tags+= [tag] end end I've written a full working example of exactly this case here, you should definitely have a look at it to get some more insights.
unknown
d7614
train
I have resolved this by using the promise directly in the action. return dbConnect('<SQL here>=:id', { id: Id }) .then(function(response) { var res = response.rows console.info(res); const newState = { ...state, status: res} return newState }) .catch(function(error) { console.info(error) }) Note that response has the resultset.
unknown
d7615
train
You just have the DoEvents in the wrong place. Try it like this. Sub test() UserForm1.Show vbModeless For i = 1 To 700 For j = 1 To 5000 UserForm1.Label1.Caption = 100 * i / 700 & "% Completed" UserForm1.Bar.Width = 200 * i / 700 '200 - width of the bar DoEvents Next Next End Sub
unknown
d7616
train
This is pretty simple really. You don't need the template but you do need to be in the correct namespace. namespace std { void swap(VecFoo& lhs, VecFoo& rhs) { std::cout << "void swap(VecFoo&, VecFoo&)\n"; //do your custom swap here!!! } } A: std::move requires the class to be move-assignable and move-constructible, but the class VecFoo is not any of them. You added a bunch of method to support these constraints in the class Foo, which didn't requires any (you are swapping pointers). Also, there is a typo in the swap declaration: it says std::swap<VecFo> instead of std::swap<VecFoo>. Finally, I would recommend NOT using friend. Just add a method swap to the class and put the logic there.
unknown
d7617
train
One can register a custom from-python converter with Boost.Python that handles conversions from NumPy array scalars, such as numpy.uint8, to C++ scalars, such as unsigned char. A custom from-python converter registration has three parts: * *A function that checks if a PyObject is convertible. A return of NULL indicates that the PyObject cannot use the registered converter. *A construct function that constructs the C++ type from a PyObject. This function will only be called if converter(PyObject) does not return NULL. *The C++ type that will be constructed. Extracting the value from the NumPy array scalar requires a few NumPy C API calls: * *import_array() must be called within the initialization of an extension module that is going to use the NumPy C API. Depending on how the extension(s) are using the NumPy C API, other requirements for importing may need to occur. *PyArray_CheckScalar() checks if a PyObject is a NumPy array scalar. *PyArray_DescrFromScalar() gets the data-type-descriptor object for an array scalar. The data-type-descriptor object contains information about how to interpret the underlying bytes. For example, its type_num data member contains an enum value that corresponds to a C-type. *PyArray_ScalarAsCtype() can be used to extract the C-type value from a NumPy array scalar. Here is a complete example demonstrating using a helper class, enable_numpy_scalar_converter, to register specific NumPy array scalars to their corresponding C++ types. #include <boost/cstdint.hpp> #include <boost/python.hpp> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/arrayobject.h> // Mockup functions. /// @brief Mockup function that will explicitly extract a uint8_t /// from the Boost.Python object. boost::uint8_t test_generic_uint8(boost::python::object object) { return boost::python::extract<boost::uint8_t>(object)(); } /// @brief Mockup function that uses automatic conversions for uint8_t. boost::uint8_t test_specific_uint8(boost::uint8_t value) { return value; } /// @brief Mokcup function that uses automatic conversions for int32_t. boost::int32_t test_specific_int32(boost::int32_t value) { return value; } /// @brief Converter type that enables automatic conversions between NumPy /// scalars and C++ types. template <typename T, NPY_TYPES NumPyScalarType> struct enable_numpy_scalar_converter { enable_numpy_scalar_converter() { // Required NumPy call in order to use the NumPy C API within another // extension module. import_array(); boost::python::converter::registry::push_back( &convertible, &construct, boost::python::type_id<T>()); } static void* convertible(PyObject* object) { // The object is convertible if all of the following are true: // - is a valid object. // - is a numpy array scalar. // - its descriptor type matches the type for this converter. return ( object && // Valid PyArray_CheckScalar(object) && // Scalar PyArray_DescrFromScalar(object)->type_num == NumPyScalarType // Match ) ? object // The Python object can be converted. : NULL; } static void construct( PyObject* object, boost::python::converter::rvalue_from_python_stage1_data* data) { // Obtain a handle to the memory block that the converter has allocated // for the C++ type. namespace python = boost::python; typedef python::converter::rvalue_from_python_storage<T> storage_type; void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes; // Extract the array scalar type directly into the storage. PyArray_ScalarAsCtype(object, storage); // Set convertible to indicate success. data->convertible = storage; } }; BOOST_PYTHON_MODULE(example) { namespace python = boost::python; // Enable numpy scalar conversions. enable_numpy_scalar_converter<boost::uint8_t, NPY_UBYTE>(); enable_numpy_scalar_converter<boost::int32_t, NPY_INT>(); // Expose test functions. python::def("test_generic_uint8", &test_generic_uint8); python::def("test_specific_uint8", &test_specific_uint8); python::def("test_specific_int32", &test_specific_int32); } Interactive usage: >>> import numpy >>> import example >>> assert(42 == example.test_generic_uint8(42)) >>> assert(42 == example.test_generic_uint8(numpy.uint8(42))) >>> assert(42 == example.test_specific_uint8(42)) >>> assert(42 == example.test_specific_uint8(numpy.uint8(42))) >>> assert(42 == example.test_specific_int32(numpy.int32(42))) >>> example.test_specific_int32(numpy.int8(42)) Traceback (most recent call last): File "<stdin>", line 1, in <module> Boost.Python.ArgumentError: Python argument types in example.test_specific_int32(numpy.int8) did not match C++ signature: test_specific_int32(int) >>> example.test_generic_uint8(numpy.int8(42)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: No registered converter was able to produce a C++ rvalue of type unsigned char from this Python object of type numpy.int8 A few things to note from the interactive usage: * *Boost.Python was able to extract boost::uint8_t from both numpy.uint8 and int Python objects. *The enable_numpy_scalar_converter does not support promotions. For instance, it should be safe for test_specific_int32() to accept a numpy.int8 object that is promoted to a larger scalar type, such as int. If one wishes to perform promotions: * *convertible() will need to check for compatible NPY_TYPES *construct() should use PyArray_CastScalarToCtype() to cast the extracted array scalar value to the desired C++ type. A: Here's a slightly more generic version of the accepted answer: https://github.com/stuarteberg/printnum (The converter is copied from the VIGRA C++/Python bindings.) The accepted answer points out that it does not support casting between scalar types. This converter will allow implicit conversion between any two scalar types (even, say, int32 to int8, or float32 to uint8). I think that's generally nicer, but there is a slight convenience/safety trade-off made here. #include <iostream> #include <boost/python.hpp> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // http://docs.scipy.org/doc/numpy/reference/c-api.array.html#importing-the-api #define PY_ARRAY_UNIQUE_SYMBOL printnum_cpp_module_PyArray_API #include <numpy/arrayobject.h> #include <numpy/arrayscalars.h> /* * Boost python converter for numpy scalars, e.g. numpy.uint32(123). * Enables automatic conversion from numpy.intXX, floatXX * in python to C++ char, short, int, float, etc. * When casting from float to int (or wide int to narrow int), * normal C++ casting rules apply. * * Like all boost::python converters, this enables automatic conversion for function args * exposed via boost::python::def(), as well as values converted via boost::python::extract<>(). * * Copied from the VIGRA C++ library source code (MIT license). * http://ukoethe.github.io/vigra * https://github.com/ukoethe/vigra */ template <typename ScalarType> struct NumpyScalarConverter { NumpyScalarConverter() { using namespace boost::python; converter::registry::push_back( &convertible, &construct, type_id<ScalarType>()); } // Determine if obj_ptr is a supported numpy.number static void* convertible(PyObject* obj_ptr) { if (PyArray_IsScalar(obj_ptr, Float32) || PyArray_IsScalar(obj_ptr, Float64) || PyArray_IsScalar(obj_ptr, Int8) || PyArray_IsScalar(obj_ptr, Int16) || PyArray_IsScalar(obj_ptr, Int32) || PyArray_IsScalar(obj_ptr, Int64) || PyArray_IsScalar(obj_ptr, UInt8) || PyArray_IsScalar(obj_ptr, UInt16) || PyArray_IsScalar(obj_ptr, UInt32) || PyArray_IsScalar(obj_ptr, UInt64)) { return obj_ptr; } return 0; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { using namespace boost::python; // Grab pointer to memory into which to construct the C++ scalar void* storage = ((converter::rvalue_from_python_storage<ScalarType>*) data)->storage.bytes; // in-place construct the new scalar value ScalarType * scalar = new (storage) ScalarType; if (PyArray_IsScalar(obj_ptr, Float32)) (*scalar) = PyArrayScalar_VAL(obj_ptr, Float32); else if (PyArray_IsScalar(obj_ptr, Float64)) (*scalar) = PyArrayScalar_VAL(obj_ptr, Float64); else if (PyArray_IsScalar(obj_ptr, Int8)) (*scalar) = PyArrayScalar_VAL(obj_ptr, Int8); else if (PyArray_IsScalar(obj_ptr, Int16)) (*scalar) = PyArrayScalar_VAL(obj_ptr, Int16); else if (PyArray_IsScalar(obj_ptr, Int32)) (*scalar) = PyArrayScalar_VAL(obj_ptr, Int32); else if (PyArray_IsScalar(obj_ptr, Int64)) (*scalar) = PyArrayScalar_VAL(obj_ptr, Int64); else if (PyArray_IsScalar(obj_ptr, UInt8)) (*scalar) = PyArrayScalar_VAL(obj_ptr, UInt8); else if (PyArray_IsScalar(obj_ptr, UInt16)) (*scalar) = PyArrayScalar_VAL(obj_ptr, UInt16); else if (PyArray_IsScalar(obj_ptr, UInt32)) (*scalar) = PyArrayScalar_VAL(obj_ptr, UInt32); else if (PyArray_IsScalar(obj_ptr, UInt64)) (*scalar) = PyArrayScalar_VAL(obj_ptr, UInt64); // Stash the memory chunk pointer for later use by boost.python data->convertible = storage; } }; /* * A silly function to test scalar conversion. * The first arg tests automatic function argument conversion. * The second arg is used to demonstrate explicit conversion via boost::python::extract<>() */ void print_number( uint32_t number, boost::python::object other_number ) { using namespace boost::python; std::cout << "The number is: " << number << std::endl; std::cout << "The other number is: " << extract<int16_t>(other_number) << std::endl; } /* * Instantiate the python extension module 'printnum'. * * Example Python usage: * * import numpy as np * from printnum import print_number * print_number( np.uint8(123), np.int64(-456) ) * * ## That prints the following: * # The number is: 123 * # The other number is: -456 */ BOOST_PYTHON_MODULE(printnum) { using namespace boost::python; // http://docs.scipy.org/doc/numpy/reference/c-api.array.html#importing-the-api import_array(); // Register conversion for all scalar types. NumpyScalarConverter<signed char>(); NumpyScalarConverter<short>(); NumpyScalarConverter<int>(); NumpyScalarConverter<long>(); NumpyScalarConverter<long long>(); NumpyScalarConverter<unsigned char>(); NumpyScalarConverter<unsigned short>(); NumpyScalarConverter<unsigned int>(); NumpyScalarConverter<unsigned long>(); NumpyScalarConverter<unsigned long long>(); NumpyScalarConverter<float>(); NumpyScalarConverter<double>(); // Expose our C++ function as a python function. def("print_number", &print_number, (arg("number"), arg("other_number"))); }
unknown
d7618
train
<script type="text/javascript"> $(document).on('change','#country',function() { var param = 'country='+$('#country').val(); $.ajax({ showLoader: true, url: YOUR_URL_HERE, data: param, type: "GET", dataType: 'json' }).done(function (data) { //data.value has the array of regions }); }); Add this script in your js file. public function getCountries() { $country = $this->directoryBlock->getCountryHtmlSelect(); return $country; } use \Magento\Customer\Model\ResourceModel\Group\Collection and the above code in your block. <div class="field group_id required"> <label for="group_id" class="label"><span><?php echo __('Group') ?></span></label> <div class="control"> <select name="group_id"> <?php foreach ($groups as $key => $data) { ?> <option value="<?php echo $data['value']; ?>"><?php echo $data['label']; ?></option> <?php }?> </select> </div> </div> And in the phtml file add the above field. I know it's an old post, but giving the solution just in case anyone needs it. A: Create your own module instate of using /app/code/local/Mage/Customer/controllers/AccountController.php. Please add the following code in your congig.xml if your module name Custom and namespace Mymodule. <global> <fieldsets> <customer_account> <group_id><create>1</create><update>1</update></group_id> </customer_account> </fieldsets> </global> <frontend> <routers> <customer> <args> <modules> <Mymodule_Custom before="Mage_Customer_AccountController">Mymodule_Custom</Mymodule_Custom> </modules> </args> </customer> </routers> This will override your AccountController. Now find the following code for the controller. <?php require_once(Mage::getModuleDir('controllers','Mage_Customer').DS.'AccountController.php'); class Mymodule_Custom_AccountController extends Mage_Customer_AccountController { public function createPostAction() { $session = $this->_getSession(); if ($session->isLoggedIn()) { $this->_redirect('*/*/'); return; } $session->setEscapeMessages(true); // prevent XSS injection in user input if (!$this->getRequest()->isPost()) { $errUrl = $this->_getUrl('*/*/create', array('_secure' => true)); $this->_redirectError($errUrl); return; } $customer = $this->_getCustomer(); try { $errors = $this->_getCustomerErrors($customer); if (empty($errors)) { if($this->getRequest()->getPost('group_id')){ $customer->setGroupId($this->getRequest()->getPost('group_id')); } else { $customer->getGroupId(); } $customer->cleanPasswordsValidationData(); $customer->save(); $this->_dispatchRegisterSuccess($customer); $this->_successProcessRegistration($customer); return; } else { $this->_addSessionError($errors); } } catch (Mage_Core_Exception $e) { $session->setCustomerFormData($this->getRequest()->getPost()); if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) { $url = $this->_getUrl('customer/account/forgotpassword'); $message = $this->__('There is already an account with this email address. If you are sure that it is your email address, <a href="%s">click here</a> to get your password and access your account.', $url); $session->setEscapeMessages(false); } else { $message = $e->getMessage(); } $session->addError($message); } catch (Exception $e) { $session->setCustomerFormData($this->getRequest()->getPost()) ->addException($e, $this->__('Cannot save the customer.')); } $errUrl = $this->_getUrl('*/*/create', array('_secure' => true)); $this->_redirectError($errUrl); } } ?> Hope this will work for you.
unknown
d7619
train
Give the fields class names in Contact Form 7: <div class="clearfix">[recaptcha id:recaptchaform]<p class="cf7submitbtn">[submit "Send"]</p></div> Then set your CSS to be: .recaptchaform {float:left} .cf7submitbtn {float:right}
unknown
d7620
train
This one-liner might help: awk '/[^\x00-\x7f]/{print >"cn.txt";next}{print > "en.txt"}' file It will generate two files cn.txt and en.txt. It checks if the line contains at least one non-ascii character, if found one, the line would be considered as Chinese line. Little test: kent$ cat f this is line1 in english 你好 this is line2 in english 你好你好 this is line3 in english this is line4 in english 你好你好你好 kent$ awk '/[^\x00-\x7f]/{print >"cn.txt";next}{print > "en.txt"}' f kent$ head *.txt ==> cn.txt <== 你好 你好你好 你好你好你好 ==> en.txt <== this is line1 in english this is line2 in english this is line3 in english this is line4 in english
unknown
d7621
train
Yes, this is expected. Starting with Spring Session 2.0, DefaultCookieSerializer uses Base64 encoding by default. So what you're actually seeing as session cookie value is the Base64 encoded session id. If you wish to restore the previous (Spring Session 1.x) default, you can explicitly configure DefaultCookieSerializer bean with useBase64Encoding property set to false.
unknown
d7622
train
Solution is to remove <version>...</version>, let Spring boot handle the versions. Thanks to tgdavies.
unknown
d7623
train
Use this code: if(window.location.hash){ $('a[href="'+ window.location.hash +'"]').addClass('active'); } and example CSS class: a.active{ color: red; font-size: 18px; } This checks whether window.location.hash exists, if it does it searches for an a element with an href value equal to the hash. It then adds the .active class to any matched elements.
unknown
d7624
train
For that Android Support library is required See this image: Then just import the v7 compact library project into your work space and add it as a library to your project you can find it in sdk\extras\android\support\v7\appcompat where your SDK is present in directory. After importing, select your project right click ->Properties-> Android->Add->Select app compact click ok. A: The problem resolve when i downloaded API-19 & re-created the AVD. On a very first attempt, the AVD shows "Hello World" the default text on emulator.
unknown
d7625
train
class ValidEmailValidationRule extends RegexValidationRule { protected $regex = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"; public function __construct() { $this->validate(); } } You can't be statements in the middle of a class definition like that, they have to be called inside functions.
unknown
d7626
train
This approach seems somewhat common: * *Maintain a completely separate identity database. There should be no connection at all with any of the Line-Of-Business (LOB) databases. *Each LOB database should have its own user table, with appropriate referential integrity constraints with other LOB tables, e.g. events or messages in your case. *When a user hits one of your LOB web sites for the first time, he should be "enrolled" in the LOB database. A LOB user record is inserted. Use the access token to call the identity server to get any demographic information your LOB site will need. *When a user hits one of your LOB web sites for the Nth time, you can use the access token to call the identity server and get the most recent, up-to-date demographic information, just in case any of it has changed since his last visit. You can then store this information in the LOB user table so that it is available to you offline, e.g. if you need to push marketing emails you'll have a copy of the email address. The advantage of this approach is separation of concerns and the ability to support more than one authentication provider (e.g. in the future you could support Facebook or Google+ logins as well). Also you avoid any dependencies between the identity server and the LOB servers, so you can add or remove lines of business as needed, and you keep the identity server nice and lightweight.
unknown
d7627
train
In the same app, frameworks all get executed on the same process. They just locate at different places in memory allocated by the app. On the same running process, NSNofitcationCenter can communicate with each other no matter which framework the sender or receiver locates at. If you are talking about app and its extension, they run on different process and thus NSNofitcationCenter can not send notification to each other. You have to use CFNotificationCenter
unknown
d7628
train
Create a wrapper (just a simple batch script) that calls the appropriate program. Set the file type association to use the wrapper. A: I would suggest you to use registry entry. Call a CustomAction in WIX to check for the registry entry. The check can be as simple as if...else IF (Regitry_A != null && Registry_B != null) { //Choose program A } ELSE IF (Regitry_A != null) { //Choose Program A } ELSE { //Choose Program B }
unknown
d7629
train
The problem's solution is calculated with excel solver as below, but python code doesn't give the same result. If objective function is designed in brief: max revenue: price*(1-discount) * f(price*(1-discount)) subject to discount [0., 0.2] > Optimal Solution: Max Revenue: 78.0447 f(price*(1-discount)):0.99575 discount: 0.020275
unknown
d7630
train
I think that the following will work: The client: import requests ... client = Client() files = [('audio': open('my_modified_audio.mp3', 'rb'))] url = f"/resource/{resource_id}/" # response = client.put(url, data=None, files=files) # You can test it using the `requests` instead of Client() response = requests.put(url, data=None, files=files) The serializer: class AudioSerializer(serializers.Serializer): """ AudioSerializer """ audio = serializers.FileField(...) def create(self, validated_data): ... def update(self, instance, validated_data): ... The view: from rest_framework.generics import UpdateAPIView class AudioView(UpdateAPIView): ... parser_classes = (FormParser, MultiPartParser) serializer_class = AudioSerializer ... A: Inspired by @athansp's answer, I compared the source code of client.post and client.put and it turns out, put's implementation slightly differs from post, so a workable way of submitting files with put is: from django.test.client import MULTIPART_CONTENT, encode_multipart, BOUNDARY client = Client() with open('my_modified_audio.mp3', 'rb') as fp: response = client.put( f"/resource/{resource_id}/", data=encode_multipart(BOUNDARY, { 'other_field': 'some other data', 'audio': fp, }), content_type=MULTIPART_CONTENT ) Lol.
unknown
d7631
train
The given code is not valid. Try the below code. Create table emp_avg as Select e.employee_id, e.department_id from HR.employees e where 1=0; A: That's not valid syntax. The point of an anchored type declaration (the %type syntax) in PL/SQL is that when the underlying data type changes, the PL/SQL code uses the new type automatically. But that doesn't work when you're defining a table where Oracle has to know the actual data type when it writes a data block to disk and can't just dynamically recompile the table when the parent data type changes. When you create a table, you have to specify actual data types.
unknown
d7632
train
put this: plusreps.setOnClickListener(this); menusreps.setOnClickListener(this);
unknown
d7633
train
This is a bit hard to answer without seeing the whole compilation. However I often got this error when compiling third-party schemas in the case when the same schema was included via different URLs. I.e. I've implemented a project which compiled an extensive set of OGC Schemas. The problem was that these schemas referenced each other via relative and absolute URLs. So when I customized one of the schemas there were other schemas for the same namespace URI. Since JAXB processes imports and includes, it is not quite transparent what exactly gets compiled. Try to check your XJC logs for cues or - if you compile schemas directly via URLs (which is not recommended) - go through a logging proxy and see what actually gets accessed.
unknown
d7634
train
From the error I take, that the data file cannot be opened: C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop\MyFile.txt" -C -T I think, you have to add a filename behind the \Desktop. Desktop is an existing directory and cannot be opened as file ... And - btw - it might be necessary to add -S Servername... UPDATE Found this here Whenever I get this message, it's because of one of three things: 1) The path/filename is incorrect (check your typing / spelling) 2) The file does not exist. (make sure the file is where you expect it to be) 3) The file is already open by some other app. (close the other app to release the file) For 1) and 2) - remember that paths are relative to where bcp is executing. Make sure that bcp.exe can access the file/path from it's context. /Kenneth A: If you are running BCP through xp_cmdshell, run the following--> xp_cmdshell 'whoami'; GO --Make sure whatever user value you get back has full access to the file in question A: Run: EXEC master..xp_cmdshell 'DIR C:\Users\Serge\Desktop', this will show if you have access to the path. Remember if you are accessing SQL remotely or over a network, the output ie. "C:\Users\Serge\Desktop" will be the C drive on the SQL Server, not your remote PC you are working on. A: I know this is old, but you also appear to have the schema spelled wrong. C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop" -C -T s/b C:\Users\Serge>BCP Testing.dbo.Exporttable out "C:\Users\Serge\Desktop" -C -T
unknown
d7635
train
That sounds that the simulator is just too big for your monitor. Try going to the Window menu and changing the scale to something smaller. You could also try setting the device to the non-retina iPad.
unknown
d7636
train
Check out array_intersect(). Use it to get values that are the same and do a count() on the resulting array. A: I figured it out. It was not as complicated as I first thought. Just needed a function to calculate the sum. Perhaps it could be more efficient, I would love any ideas on that, but here it is: $rowColumns = array(); for($i=0;$i<=$count-1;$i++) { $currentRow = $rows[$i]; $currentCol = $cols[$i]; //count occurences of columns in row $colSum = $this->getColumnOccurences($count,$rows,$cols,$currentRow,$currentCol); $rowColumns[$currentRow][$currentCol] = $colSum; } private function getColumnOccurences($count,$rows,$cols,$rowValue,$colValue) { $retValue = 0; for($i=0;$i<=$count-1;$i++) { if($rows[$i] == $rowValue && $cols[$i] == $colValue) { $retValue = $retValue + 1; } } return $retValue; } The result is: Array ( [11] => Array ( [1] => 2 [2] => 1 ) [12] => Array ( [1] => 1 [2] => 1 ) [13] => Array ( [2] => 1 ) [14] => Array ( [1] => 1 [2] => 1 ) )
unknown
d7637
train
I need to add a two factor authentication implementation to [my java spring web application]. Here's a good package that I wrote which implements 2FA/two-factor authentication in Java code. Copying from the READ_ME, to get this to work you: * *Properly seed the random number generator. *Use generateBase32Secret() to generate a secret key for a user. *Store the secret key in the database associated with the user account. *Display the QR image URL returned by qrImageUrl(...) to the user. *User uses the image to load the secret key into his authenticator application. Whenever the user logs in: * *The user enters the number from the authenticator application into the login form. *Read the secret associated with the user account from the database. *The server compares the user input with the output from generateCurrentNumber(...). *If they are equal then the user is allowed to log in.
unknown
d7638
train
for file in *.csv; do cp "$file" "H_$file" done A: for f in *.csv; do cp -v -- "$f" "H_$f"; done
unknown
d7639
train
Adding custom user code sections is not supported by CubeMX. See this support post: https://community.st.com/s/question/0D50X0000ALxNlmSQF/is-it-possible-to-add-custom-user-code-sections
unknown
d7640
train
We can use Memoization technique for generating prime numbers using dynamic programing. You can write a function which accepts the number to be checked(say x) for primality and another parameter which accepts divisor(say the variable is i). Inside the function check for the conditions like i==1 then return 1 and x%i==0 then return 0 and again call the function recursivly with decrementing i and the result shoiud be stored in to an array. A: If you will google it, you will find the solution very easily: BTW solution is Use method described here: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
unknown
d7641
train
Empty age (example) <E06_14></E06_14> could have a special meaning, for example be "unknown" age. In this case, the real question is how to make the field nillable on the Delphi side. From this post of J.M. Babet: Support for 'nil' has been an ongoing issue. Several built-in types of Delphi are not nullable. So we opted to use a class for these cases (not elegant but it works). So with the latest update for Delphi 2007 I have added several TXSxxxx types to help with this. Basically: TXSBoolean, TXSInteger, TXSLong, etc. TXSString was already there but it was not registered. Now it is. When importing a WSDL you must enable the Use 'TXSString for simple nillable types' option to make the importer switch to TXSxxxx types. On the command line it is the "-0z+" option. The DocWiki for the Import WSDL Wizard also shows two options related to nillable elements: * *Process nillable and optional elements - Check this option to make the WSDL importer generate relevant information about optional and nillable properties. This information is used by the SOAP runtime to allow certain properties be nil. *Use TXSString for simple nillable types - The WSDL standard allows simple types to be nil, in Delphi or NULL, in C++, while Delphi and C++ do not allow that. Check this option to make the WSDL importer overcome this limitation by using instances of wrapper classes.
unknown
d7642
train
Probably you can use Paginator. Then call the client, to start the workspace workspaces."WorkSpaces.Paginator.DescribeWorkspaces"
unknown
d7643
train
AppHarbor currently only supports deploying one application from any given repository. One option might be to fold the API into the web project. I did this for a non-web API WCF service here. Another option is to maintain two AppHarbor applications, and use solution files named according to what application you want deployed for that application. That is, OurApp.Web.sln contains the Web project and any supporting projects and, OurApp.Api.sln references the API project and any supporting projects. Read more about AppHarbor solution file convention. (disclaimer, I'm co-founder of AppHarbor)
unknown
d7644
train
You are after git filter-branch. With it you can easily change committer names, author names and commit messages throughout the whole history. But be aware that this changes all SHA1 values, so if someone has cloned that repository and based work off of it, he has to manually rebase all his branches onto the new history.
unknown
d7645
train
Not really an answer but closing this off - simply put the report generation takes time.
unknown
d7646
train
you can pass in URL query params if data is not sensitive otherwise you can use session value.
unknown
d7647
train
I'm not generally a fan of nested select statements, but that is one way to approach this in MySQL: select (select contact_id from ak_contact where email = '[email protected]' and contact_id is not null order by contact_id desc limit 1 ) as contact_id, (select name from ak_contact where email = '[email protected]' and name is not null order by contact_id desc limit 1 ) as name, (select phone from ak_contact where email = '[email protected]' and phone is not null order by contact_id desc limit 1 ) as phone, (select city from ak_contact where email = '[email protected]' and city is not null order by contact_id desc limit 1 ) as city Each column might be coming from a different row, so each gets its own query. A: More along the lines of Gordon's answer... SELECT a.c_id, CASE WHEN b.name IS NULL THEN (SELECT name FROM ak_contact WHERE name IS NOT NULL AND email = a.email ORDER BY c_id DESC LIMIT 1) ELSE b.name end AS name, b.email, CASE WHEN b.phone IS NULL THEN (SELECT phone FROM ak_contact WHERE phone IS NOT NULL AND email = a.email ORDER BY c_id DESC LIMIT 1) ELSE b.phone end AS phone, CASE WHEN b.city IS NULL THEN (SELECT city FROM ak_contact WHERE city IS NOT NULL AND email = a.email ORDER BY c_id DESC LIMIT 1) ELSE b.city end AS city FROM (SELECT email, Max(c_id) AS c_id FROM ak_contact WHERE email = '[email protected]' GROUP BY email) a LEFT JOIN ak_contact b ON b.c_id = a.c_id Result | C_ID | NAME | EMAIL | PHONE | CITY | ---------------------------------------------------- | 8499 | Serj | [email protected] | 3-33-333 | London | See the demo
unknown
d7648
train
Seems like you have declared the JTable globally and initializing every time when some action event is triggered. As like JTable, you can declare your DefaultTableModel globally and initialize both JTable and TableModel. If you don't want to maintain the old records in JTable, you can clear the JTable every time when some action event is trigerred. A: Finally I got the solution to my Problem. I just need to call 2 methods whenever I press a button before running the SQL Query. Those 2 methods are panel.removeAll(); and panel.validate(); This erase everything on your previous panel from your screen and displays only the result which you desire to see.
unknown
d7649
train
You can use rails' update_all method. See here for a description: http://apidock.com/rails/ActiveRecord/Relation/update_all EDIT: It's part of the Relation class, so you may call this on scopes (It doesn't say that explicit in the documentation) EDIT2: It works very much like destroy_all which may also be called on scopes (Relation)
unknown
d7650
train
OAuth is method for authentication, you should use REST API provided by Twitter. Please check this: https://dev.twitter.com/docs/api/1.1 (statuses/user_timeline) Edit: https://github.com/abraham/twitteroauth Please check "Extended flow using example code" section, there's everything you want to know. Just one note, if you have long-live access token (from your app dashboard, see oauth tab), you just pass token and token secret as third and fourth parameter when you create new instance of TwitterOAuth class, like this: $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
unknown
d7651
train
To add further to @eol's response, if you want to query on the entry db collection, you need to pass an empty object to the Question.find({}) method. If you want to return one of the different difficulties within the doc, then I believe you treat the response like any other object with properties.
unknown
d7652
train
For those that came here for the actual question 'Remove timezone information from datetime object', the answer would be something like: datetimeObject.replace(tzinfo=None) from datetime import datetime, timezone import time datetimeObject = datetime.fromtimestamp(time.time(), timezone.utc) print(datetimeObject) datetimeObject = datetimeObject.replace(tzinfo=None) print(datetimeObject) A: use strftime if you already have a datetime object dt.strftime('%Y-%m-%d %H:%M:%S') If you need a datetime object from a string, the fastest way is to use strptime and a slice: st = '2016-12-14 15:57:16.140645' dt = datetime.strptime(st[:19], '%Y-%m-%d %H:%M:%S')
unknown
d7653
train
You should better use $_SERVER['REQUEST_URI']. Since it is the last string in your URL, you can use the following function: function getIdFromUrl($url) { return str_replace('/', '', array_pop(explode('-', $url))); } @Kristian 's solution will only return numbers from 0-9, but this function will return the id with any length given, as long as your ID is separated with a - sign and the last element. So, when you call echo getIdFromUrl($_SERVER['REQUEST_URI']); it will echo, in your case, 1. A: If the ID will not always be the same number of digits (if you have any ID's greater than 9) then you'll need something robust like preg_match() or using string functions to trim off everything prior to the last "-" character. I would probably do: <?php $parts = parse_url($_SERVER['REQUEST_URI']); if (preg_match("/truck-gallery-(\d+)/", $parts['path'], $match)) { $id = $match[1]; } else { // no ID found! Error handling or recovery here. } ?> A: Use the $_SERVER['REQUEST_URI'] variable to get the path (Note that this is not the same as the host variable, which returns something like http://www.yoursite.com). Then break that up into a string and return the final character. $path = $_SERVER['REQUEST_URI']; $ID = $path[strlen($path)-1]; Of course you can do other types of string manipulation to get the final character of a string. But this works.
unknown
d7654
train
You can use HK2 DI. What you can do to configure it is create a standalone ServiceLocator and set that locator to be the parent locator of the app, using a Jersey property. public static void main(String... args) { SourceHandler source = new SparkHandler(inputSource); ServiceLocator locator = ServiceLocatorUtilities.bind(new AbstractBinder() { @Override protected void configure() { bind(source).to(SourceHandler.class); } }); ServletHolder serHol = ctx.addServlet(ServletContainer.class, "/rest/*"); serHol.setInitParameter(ServletProperties.SERVICE_LOCATOR, locator); } Then you can just @Inject the SourceHandler anywhere you need it @Path("whatever") public class Resource { @Inject private SourceHandler sourceHandler; }
unknown
d7655
train
Each article has this structure: <article class="col_4"> <a href="https://www.cnnindonesia.com/..."> <span>...</span> <h2 class="title">...</h2> </a> </article> Simpler to iterate over the article elements then look for a elements. Try: from bs4 import BeautifulSoup import requests links = [] response = requests.get(f"https://www.cnnindonesia.com/search?query=covid") soup = BeautifulSoup(response.text, 'html.parser') for article in soup.find_all('article'): url = article.find('a', href=True) if url: link = url['href'] print(link) links.append(link) print(links) Output: https://www.cnnindonesia.com/nasional/...pola-sawah-di-laut-natuna-utara ... ['https://www.cnnindonesia.com/nasional/...pola-sawah-di-laut-natuna-utara', ... 'https://www.cnnindonesia.com/gaya-hidup/...ikut-penerbangan-gravitasi-nol'] Update: If want to extract the URLs that are dynamically added by JavaScript inside the <div class="list media_rows middle"> element then you must use something like Selenium that can extract the content after the full page is rendered in the web browser. from selenium import webdriver from selenium.webdriver.common.by import By url = 'https://www.cnnindonesia.com/search?query=covid' links = [] options = webdriver.ChromeOptions() pathToChromeDriver = "chromedriver.exe" browser = webdriver.Chrome(executable_path=pathToChromeDriver, options=options) try: browser.get(url) browser.implicitly_wait(10) html = browser.page_source content = browser.find_element(By.CLASS_NAME, 'media_rows') for elt in content.find_elements(By.TAG_NAME, 'article'): link = elt.find_element(By.TAG_NAME, 'a') href = link.get_attribute('href') if href: print(href) links.append(href) finally: browser.quit() A: Sorry, can't add comments not enough reputation. I think this line: for url in lm_row_cont.find_all('a'): Should have the a tag as '<a>' Or you could use regex (skipping the above) to match the relevant items after grabbing a div.
unknown
d7656
train
vlookup will not work as it will continue to only grab the first instance of "Rec". On Sheet 2 list all the possible categories in column A then in column B1 put = sumif(Sheet1!C:C,A1,Sheet1!D:D) then copy down. This will Get you the totals by category. If you want to use VBA, you will still need a list of categories setup somewhere, either hard coded or listed somewhere that you can loop through. If your list was in column A on Sheet2 then you would: dim ws as worksheet set ws = Worksheets("Sheet2") For each i in ws.range(ws.Range("A1"),ws.Range("A1").offset(xldown)).Cells i.offset(,1) = WorksheetFunction.Sumif(Worksheets("Sheets1").Range("C:C"), _ i,Worksheets("Sheets1").Range("D:D")) next i
unknown
d7657
train
Thanks a lot sideshowbarker for your help. I changed the dash_path to /usr/local/nginx/stream/dash and root location to /usr/local/nginx/stream and it works fine.
unknown
d7658
train
Instead of making Vue do the same work over and over, You could make use of the v-else directive, which may work better for you: <li v-if="!$auth.check()" class="pull-right" v-cloak> <router-link :to="{ name: 'register' }">Register</router-link> </li> <li v-else class="pull-right"> <a href="#" @click.prevent="$auth.logout()">Logout</a> </li> A: v-cloak is not helping because that gets taken away as soon as the Vue app is ready. Apparently there's a delay from when Vue is ready and when the $auth function returns a response. I'd recommend hiding all of the login/logout links until $auth returns something. You'd have to hook into what $auth returns somehow, and use that hook to change the authCheckDone to true. Vue { data: { authCheckDone: false ... } } <ul class="list-inline"> <li> <router-link :to="{ name: 'home' }">Home</router-link> </li> <span v-if="authCheckDone"> <li v-if="!$auth.check()" class="pull-right"> <router-link :to="{ name: 'login' }">Login</router-link> </li> <li v-if="!$auth.check()" class="pull-right" v-cloak> <router-link :to="{ name: 'register' }">Register</router-link> </li> <li v-if="$auth.check()" class="pull-right"> <a href="#" @click.prevent="$auth.logout()">Logout</a> </li> </span> </ul> A: You have to wait a bit until vue-auth is actually ready. From the docs: ready * *Get binded ready property to know when user is fully loaded and checked. *Can also set a single callback which will fire once (on refresh or entry). <div v-if="$auth.ready()"> <vue-router></vue-router> </div> <div v-if="!$auth.ready()"> Site loading... </div> created() { this.$auth.ready(function () { console.log(this); // Will be proper context. }); } In other words, instead of v-cloak use: <div class="panel panel-default" v-if="$auth.ready()"> Note: this can do some quick "flashing" of a white page. In that case you may want to add a loading image or something, like: <div v-if="!$auth.ready()"> <img src="loading.gif"> </div> Naturally, if this div is close to the other v-else can be used.
unknown
d7659
train
I believe this may work. jQuery("#firmos").html($(this).val()); In your document ready function it would look like this. jQuery(function() { jQuery('#list4').jqDropDown({ optionChanged: function(){ jQuery("#firmos").html($(this).val()); }, direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); }); Edited Actually if you want to redisplay the option in another element this control has a parameter called place holder you could do this. jQuery(function() { jQuery('#list4').jqDropDown({ placeholder: '#firmos', direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); }); Edited Again If you want a custom value you can do something like this jQuery(function() { jQuery('#list4').jqDropDown({ optionChanged: function(){ jQuery("#firmos").html((function (currentElement) { switch (currentElement.val()) { case "someval": return "somethingSpecial1"; break; case "someval2": return "somethingSpecial2"; break; /// more case statements. } })($(this))); }, direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); }); A: Well, I looked that this plugin just replicates a select element in a list <li> and seems not possible to get the exact changed value from the select because it doesn't change if you see the DOM (that makes me assume that the onchange event from that plugin is used just to trigger something when your list changes). So, it seems you need to do some tricky thing to get the selected value implementing an onchange event recreation. Like this: Live Demo: http://jsfiddle.net/oscarj24/nuRKE/ $(function () { var firmos = $('#firmos'); $('#list4').jqDropDown({ direction: 'up', defaultStyle: false, containerName: 'theContainer', toggleBtnName: 'awesomeToggleClass', optionListName: 'thisListIsRocking', effect: 'fade', effectSpeed: 300 }); //This will be your new 'onchange' event when using 'jqDropDown' plugin. $('ul .ddOption').on('click', function(e){ var selected = $.trim($(e.target).text()); switch (selected) { case 'Aspen': firmos.html('You selected Aspen.'); break; case 'Tokyo': firmos.html('You selected Tokyo.'); break; //Do the same for other options. } }); });
unknown
d7660
train
Might be wrong about this, but I think you can only refer to the intermediary table if you specify it yourself explicitly. class SomeModel(models.Model): user=models.ManyToManyField(User,related_name='linked',blank=True,null=True, through='SomeModelUser') class SomeModelUser(models.Model): user = models.ForeignKey(User) some_model = models.ForeignKey(SomeModel) linked_objects=SomeModel.objects.filter(user__id__contains=request.user.id).order_by('somemodeluser__pk')
unknown
d7661
train
To deal with the null you can use is distinct from: Select * from temp where lower(category) is distinct from 'fruits' or if you do want the regular expression: Select * from temp where category !~* 'fruits' or category is null; alternatively treat null as something else: Select * from temp where coalesce(category, '') !~* 'fruits'
unknown
d7662
train
I have solve my problem var s = $("#sel").select2({ tags: true, closeOnSelect: false, width: 400, }); var $search = s.data('select2').dropdown.$search || $el.data('select2').selection.$search; s.on("select2:selecting", function(e) { $search.val(e.params.args.data.text); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" /> <select id="sel"> <option value="Option one">Option one</option> <option value="Option two">Option two</option> <option value="Option three">Option three</option> <option value="Option four">Option four</option> </select> A: Try this: $('#sel').click(function() { var selectedOption = $(this).children("option").filter(":selected"); if (selectedOption.val() === 'Option one') { selectedOption.text('First Option'); selectedOption.attr('value', 'First option'); } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="sel"> <option value="Option one">Option one</option> <option value="Option two" selected="1">Option two</option> <option value="Option three">Option three</option> <option value="Option four">Option four</option> </select> A: You can use the built-in change event like this : $("#sel").select2({ width: 400, tags: true }).on("change", function (e) { var elem = $("#sel"); if( elem.val() == "Option one" ){ $('#sel option:contains("Option one")').val('First option').text('First option'); elem.select2("destroy"); elem.select2({ width: 400, tags: true }); } }); Here is the fiddle : https://jsfiddle.net/9aotj2or/17/
unknown
d7663
train
Might be a bit late, but the issue might be that you have a latin-1 character set: See the following post in the google forums: http://www.google.com/support/forum/p/websiteoptimizer/thread?tid=70b4938cf4de24f2&hl=en
unknown
d7664
train
You said that the gbox data is initialized like: clEnqueueWriteBuffer(queue, gauss_buf, CL_FALSE, 0, 5*5, gauss5, 0, NULL, NULL); That is wrong, since you are copying 1/4th of the real amount of memory. The proper way is: clEnqueueWriteBuffer(queue, gauss_buf, CL_FALSE, 0, 5*5*sizeof(cl_int), gauss5, 0, NULL, NULL); Otherwise, the rest is 0s, leading to a low value in the output.
unknown
d7665
train
You can use ImageIcon JLabel l = new JLabel(new ImageIcon("path-to-file")); A: Try this code: ImageIcon imageIcon = new ImageIcon("yourFilepth"); JLabel label = new JLabel(imageIcon); For more Info A: jLabel1 = new javax.swing.JLabel(); jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\admin\\Desktop\\Picture 34029.jpg")); Here i posted the code that got generated automatically in netbeans.Hope my code helps in this regards keep coding goodluck. A: You have to supply to the JLabel an Icon implementation (i.e ImageIcon). You can do it trough the setIcon method, as in your question, or through the JLabel constructor: Image image=GenerateImage.toImage(true); //this generates an image file ImageIcon icon = new ImageIcon(image); JLabel thumb = new JLabel(); thumb.setIcon(icon); I recommend you to read the Javadoc for JLabel, Icon, and ImageIcon. Also, you can check the How to Use Labels Tutorial, for more information. Also have a look at this tutorial: Handling Images in a Java GUI Application
unknown
d7666
train
If you are using session in fragment, try this code, it works for me: else { Log.d("ss", "Session Closed"); // start Facebook Login Session.openActiveSession(getActivity(), MyFragment.this, true, callback); } Don't forget to use UiLifecycleHelper for onActivityResult, onResume, onCreate, onDestroy, onSaveInstancceState... or manage the session yourself to save the state.
unknown
d7667
train
Split q to an array with comma and loop through each value to select the input you want and change the prop q.split(",").forEach(function(value){ $('input[data-value='+ value +']').prop('checked', true); }) A: You can use a simple .each() loop to achieve this with jQuery, or Array.prototype.foreach() in vanilla JavaScript. If you actually have a string of numbers to start off with, you'll need to split them out into an array by running .split() on the comma. This can be seen in the following example: // If you have a string rather than an array const q = "5,1,3,4"; const values = q.split(","); // If you start with an array //const values = [5, 1, 3, 4]; $(values).each(function(index, value) { $('input[data-value=' + value + ']').prop('checked', true); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" data-value="1"> <input type="checkbox" data-value="2"> <input type="checkbox" data-value="3"> <input type="checkbox" data-value="4"> <input type="checkbox" data-value="5">
unknown
d7668
train
I wrote a tutorial with step-by-step instructions on how to write a PhoneGap plugin for iOS. It might be helpful for you. Good luck!
unknown
d7669
train
Either your users need to instal the same SQL Server driver you use, or you need to change yours to match their drivers: https://support.microsoft.com/en-us/help/2022518/error-message-class-not-registered-when-you-update-powerpivot-data
unknown
d7670
train
This worked for me : import Vue from "vue" import { Printd } from "printd"; Vue.prototype.$Printd = new Printd(); Then you can access this.$Printd in your whole app. A: Try adding: as any just like in the following. import Vue from "vue"; import { Printd } from "printd"; Vue.use(Printd as any); This might be your answer. But if that does not work, try this. import Vue from "vue"; const Printd = require("printd").Printd; Vue.use(Printd); ... And if that still does not work, try this. file: ~/types/index.d.ts declare module "printd"
unknown
d7671
train
Combine offers extensions around URLSession to handle network requests unless you really need to integrate with OperationQueue based networking, then Future is a fine candidate. You can run multiple Futures and collect them at some point, but I'd really suggest looking at URLSession extensions for Combine. struct User: Codable { var username: String } let requestURL = URL(string: "https://example.com/")! let publisher = URLSession.shared.dataTaskPublisher(for: requestURL) .map { $0.data } .decode(type: User.self, decoder: JSONDecoder()) Regarding running a batch of requests, it's possible to use Publishers.MergeMany, i.e: struct User: Codable { var username: String } let userIds = [1, 2, 3] let subscriber = Just(userIds) .setFailureType(to: Error.self) .flatMap { (values) -> Publishers.MergeMany<AnyPublisher<User, Error>> in let tasks = values.map { (userId) -> AnyPublisher<User, Error> in let requestURL = URL(string: "https://jsonplaceholder.typicode.com/users/\(userId)")! return URLSession.shared.dataTaskPublisher(for: requestURL) .map { $0.data } .decode(type: User.self, decoder: JSONDecoder()) .eraseToAnyPublisher() } return Publishers.MergeMany(tasks) }.collect().sink(receiveCompletion: { (completion) in if case .failure(let error) = completion { print("Got error: \(error.localizedDescription)") } }) { (allUsers) in print("Got users:") allUsers.map { print("\($0)") } } In the example above I use collect to collect all results, which postpones emitting the value to the Sink until all of the network requests successfully finished, however you can get rid of the collect and receive each User in the example above one by one as network requests complete.
unknown
d7672
train
This expression will get you 50% of the way there: (?<=:\s*)(".*?"(?<!\\")|\-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?)(?=\s*}) Or, when written as a multi-line regex: (?x: (?<=:\s*) # After : + space ( ".*?"(?<!\\") # String in double quotes | # -or- \-? # Optional leading -ve (0|[1-9]\d*) # Number (\.\d+)? # Optional fraction ([eE][+-]?\d+)? # Optional exponent ) (?=\s*}) # space + } ) This will not match your nested object example ({ "not": { "want" ...) or rather, it will match, but on the wrong thing. Also, your final example ({ "nothing": 0 } => null / not found) is difficult because 0 is a valid number. To work around the this problem, I would just check the result in procedural code and replace a result of 0 with null. The nested objects problem is a whole different ball game though. It's getting into the realm of lexical analysis rather than simple tokenizing. At that point, you might as well just use a JSON library because you'd be writing a full JSON parser anyway. Fortunately, JSON is a simple enough grammar that it wouldn't be that expensive to use a third party library - certainly no more than doing it yourself. I think the short answer is: from a simple { "name" : <value> } object, yes, but from anything more complicated, no. For info on the JSON syntax, see http://www.json.org/.
unknown
d7673
train
start_tls() and ldaps is mutually exclusive, meaning you cannot issue start_tls() on the ssl port (standard 636), or initiate ldaps on an unecrypted port (standard 389). The start_tls() command initiate a secure connection on the unencrypted port after connection is initiated, so you would then issue this before the bind takes place to make it encrypted. Another set of common ports is 3268 (unecrypted) and 3269 (ssl) which might be enabled in your server. ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); is logging to your web servers error log, depending on your log level, or to stout (from PHP CLI). To gain more information here, check your web server log level setting, or simply run your php script from command line. To successfully use the ssl port, you need to specify the ldaps:// prefix, while on the unencrypted port this is not necessary (with a ldap:// prefix). Looking at your code, this could be a protocol version issue as PHP by default use version 2. To solve this, you can issue: ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION,3); ldap_set_option($conn, LDAP_OPT_REFERRALS,0); before you attempt to bind. You can also have a look at the code in Problems with secure bind to Active Directory using PHP which I successfully use in CentOS 5, but is having problems in Ubuntu. If your server has an open unencrypted port, it's a good idea to do an unencrypted test bind against it to rule out any connectivity issues. To check if the port is open, you can check if telnet connects to it, E.G: telnet my.server.com 3268 If the port is open, then you should be able to bind using it. *Edit: If the ssl certificate is deemed invalid, the connection will fail, if this is the case, setting the debug level to 7 would announce this. To get around this specific problem you need to ignore the validity: You can ignore the validity in windows by issuing putenv('LDAPTLS_REQCERT=never'); in your php code. In *nix you need to edit your /etc/ldap.conf to contain TLS_REQCERT never A: The port 636 is the SSL enabled port and requires an SSL enabled connection. You should try to connect on port 389, or change your code to include the secure layer (much more complex). Kind regards, Ludovic A: To connect using SSL you should try $ldapconn = ldap_connect('ldaps://'.$ldaphost); This will automatically connect on port 636 which is the default ldaps-port. Depending on your server installation and configuration it may be possible that connections are only allowed on port 389 (using no encryption or using TLS) or only on port 636 using SSL-encryption. Although it might be possible that your server exposes other ports. So in general you need to know which port you're gonna connect to and which encryption method the server requires (no encryption, SSL or TLS). A: Is the certificate of the LDAP server signed by a valid CA? Maybe your client just rejects the certificate!
unknown
d7674
train
Using CDI in JAVA SE requires the beans.xml to be put in META-INF although this is optional since Java EE 7. Then, set discovery mode to annotated and your producer should be detected. Here is a working configuration : <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> <deltaspike.version>1.8.2</deltaspike.version> <weld.version>3.0.4.Final</weld.version> </properties> Now, here is how you setup the base DeltaSpike dependency : <dependencyManagement> <dependencies> <dependency> <groupId>org.apache.deltaspike.distribution</groupId> <artifactId>distributions-bom</artifactId> <version>${deltaspike.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> In the dependencies, you should have theses specs : <dependency> <groupId>javax.enterprise</groupId> <artifactId>cdi-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>javax.transaction-api</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>javax.persistence-api</artifactId> <version>2.2</version> </dependency> Now it's time to depend on implementations. First, Deltaspike itself : <dependency> <groupId>org.apache.deltaspike.core</groupId> <artifactId>deltaspike-core-api</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.deltaspike.core</groupId> <artifactId>deltaspike-core-impl</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.deltaspike.cdictrl</groupId> <artifactId>deltaspike-cdictrl-api</artifactId> <scope>compile</scope> </dependency> Then JBoss Weld 3 (CDI 2.0 impl) <dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se-shaded</artifactId> <version>${weld.version}</version> <scope>runtime</scope> </dependency> And Weld controler for DeltaSpike : <dependency> <groupId>org.apache.deltaspike.cdictrl</groupId> <artifactId>deltaspike-cdictrl-weld</artifactId> <scope>runtime</scope> </dependency> Then the DeltaSpike Data module : <dependency> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>deltaspike-data-module-api</artifactId> <version>${deltaspike.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>deltaspike-data-module-impl</artifactId> <version>${deltaspike.version}</version> <scope>runtime</scope> </dependency> Now it's time for the JPA implementation (EclipseLink JPA 2.7.1) and an embedded database server H2 : <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> <version>2.7.1</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.197</version> <scope>runtime</scope> </dependency> To create unit test with JUnit 5, you need this : <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <version>5.1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <version>1.1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-runner</artifactId> <version>1.1.0</version> <scope>test</scope> </dependency> And to be able to launch CDI with a single annotation in a JUnit class, you need this as well : <dependency> <groupId>org.jboss.weld</groupId> <artifactId>weld-junit5</artifactId> <version>1.2.2.Final</version> <scope>test</scope> </dependency> To enable JUnit 5 in Maven, you must configure maven-surefire-plugin : <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.19.1</version> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.0.3</version> </dependency> </dependencies> </plugin> </plugins> </build> And, I'll use Lombok and SLF4J : <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency> Here is my project structure : main/java/fr/fxjavadevblog +-- VideoGame.java (JPA Entity) +-- VideoGameFactory.java +-- VideoGameRepository.java (interface) +-- InjectedUUID.java (annotation def.) +-- Producers.java (produces EntityManager and UUID has string) /resources/META-INF +-- beans.xml +-- persistence.xml test/java/fr/fxjavadevblog +-- VideoGameReposityTest.java (JUnit 5) /resources/META-INF +-- beans.xml +-- persistence.xml Here is are my CDI producers, needed by DeltaSpike Data and to inject UUID as private keys : package fr.fxjavadevblog; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; import javax.persistence.Persistence; import java.util.UUID; /** * composite of CDI Producers. * * @author robin */ @ApplicationScoped public class Producers { public static final String UNIT_NAME = "cdi-deltaspike-demo"; /** * produces the instance of entity manager for the application and for DeltaSpike. */ @Produces @SuppressWarnings("unused") // just remove the warning, because the field serves as CDI Producer and the IDE cannot detect it. private static EntityManager em = Persistence.createEntityManagerFactory(UNIT_NAME).createEntityManager(); /** * produces randomly generated UUID for primary keys. * * @return UUID as a HEXA-STRING * */ @Produces @InjectedUUID @SuppressWarnings("unused") // just remove the warning, because the method serves as CDI Producer and the IDE cannot detect it. public String produceUUIDAsString() { return UUID.randomUUID().toString(); } } this class uses a custom CDI Qualifier called @InjectedUUID : package fr.fxjavadevblog; import javax.inject.Qualifier; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * CDI Qualifier for UUID Producers * * @author robin */ @Qualifier @Retention(RUNTIME) @Target({METHOD, FIELD, PARAMETER, TYPE}) public @interface InjectedUUID { } Here is my JPA entity, using Lombok and CDI annotations : package fr.fxjavadevblog; import lombok.*; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.persistence.*; import java.io.Serializable; /** * simple JPA Entity, using Lombok and CDI Injected fields (UUID). * * @author robin */ // lombok annotations @NoArgsConstructor(access = AccessLevel.PROTECTED) // to avoid direct instanciation bypassing the factory. @ToString(of = {"id","name"}) @EqualsAndHashCode(of="id") // CDI Annotation @Dependent // JPA Annotation @Entity public class VideoGame implements Serializable { @Id @Inject @InjectedUUID // ask CDI to inject an brand new UUID @Getter private String id; @Getter @Setter private String name; // this field will work as a flag to know if the entity has already been persisted @Version @Getter private Long version; } Here is a simple factory for my entity class : /** * simple Factory for creation VideoGame instances populated with UUID, ready to persist. * This factory is need to get a proper Entity. Entities must not be created with the "new" operator, but must be build * by invoking CDI. * * @author robin */ public class VideoGameFactory { /** * creates and brand new VideoGame instance with its own UUID as PK. * * @return instance of a VideoGame */ public static VideoGame newInstance() { // ask CDI for the instance, injecting required dependencies. return CDI.current().select(VideoGame.class).get(); } } And last but not least, the DeltaSpike Data Resposity for my entity : package fr.fxjavadevblog; import org.apache.deltaspike.data.api.EntityRepository; import org.apache.deltaspike.data.api.Repository; /** * CRUD (and much more) interface, using DeltaSpike Data module. * * @author robin */ @Repository interface VideoGameRepository extends EntityRepository <VideoGame, String> { // nothing to code here : automatic Repo generated by DeltaSpike } Here are the configuration files : beans.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd" bean-discovery-mode="annotated" version="2.0"> </beans> persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"> <persistence-unit name="cdi-deltaspike-demo" transaction-type="RESOURCE_LOCAL"> <class>fr.fxjavadevblog.VideoGame</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/> <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/> <property name="javax.persistence.schema-generation.database.action" value="create"/> </properties> </persistence-unit> </persistence> These files are duplicated into the test/resources/META-INF folder as well. And finally, here is the unit test : package fr.fxjavadevblog; import org.jboss.weld.junit5.EnableWeld; import org.jboss.weld.junit5.WeldInitiator; import org.jboss.weld.junit5.WeldSetup; import org.junit.Assert; import org.junit.jupiter.api.Test; import lombok.extern.slf4j.Slf4j; import javax.inject.Inject; /** * simple test class for the VideoGameRepository, using LOMBOK and WELD. * * @author robin */ @Slf4j @EnableWeld class VideoGameRepositoryTest { @WeldSetup // This is need to discover Producers and DeltaSpike Repository functionality private WeldInitiator weld = WeldInitiator.performDefaultDiscovery(); @Inject private VideoGameRepository repo; @Test void test() { VideoGame videoGame = VideoGameFactory.newInstance(); videoGame.setName("XENON"); repo.save(videoGame); // testing if the ID field had been generated by the JPA Provider. Assert.assertNotNull(videoGame.getVersion()); Assert.assertTrue(videoGame.getVersion() > 0); log.info("Video Game : {}", videoGame); } } Usage of Lombok and the UUID producer is optional. You can find the full code source, and clone the repo, on github : https://github.com/fxrobin/cdi-deltaspike-demo A: I had similar issues with Deltaspike and a Junit5 integration test of a database repository. Basically, I could not inject the repository when using Junit5 @Test annotations. I had to use Junit4 @Test annotations as a workaround.
unknown
d7675
train
The easiest way is Pandas. Read data from file into DataFrame: import pandas as pd df = pd.read_csv('file.txt', sep=' ') 1) Show students names with 22 age. result = df[df['Age'] == 22] 2) Show students of Electronics. result = df[df['Faculty'] == 'Electronics'] A: I can give you a hint on building a dictionary: a = [] with open("file.txt") as f: keys = f.readline().strip().split(' ', 4) for line in f: val = line.strip().split(' ', 4) # spacebar in file a.append(dict(zip(keys, val))) Now a contains a list of dictionaries like this one: {'Name': 'Chris', 'Surname': 'M', 'Age': '20', 'Grade': '5', 'Faculty': 'Electronics' }
unknown
d7676
train
Raw sockets, as given by the example above (by Carl) can work to give you access for L3 header. However, note that on more up-to-date Windows (XP SP3, Vista and 7) raw sockets are greatly restricted by the socket layer, making it difficult to send arbitrary data of your choosing. You can also use special libraries that allow for a much more raw access to the Ethernet adapter. WinPcap (for Windows) or libpcap (for Linux) will allow you to manipulate the entire packet data, including the Ethernet header, and indeed send any other L2 protocol you wish.
unknown
d7677
train
You can enable from GUI of Pydio >> Settings >> Application Core >> Authentication >> Sele
unknown
d7678
train
You code showed you applied GaussianBlur(), cv2.adaptiveThreshold() and cv2.morphologyEx(), all those filtering would likely make the details lost in some degree in the resulted image. If you need to convert color space from BGR to HSV, cv2.cvtColor(img, cv2.COLOR_BGR2HSV), then you may just do minimal preprocessing to reduce the distortion before converting the image to HSV, and before you further any processing in HSV color space.
unknown
d7679
train
The problem is that when you are selecting a folder and updating self.label_directory with the String of the path to the selected folder it is manipulating the grid and expanding your Click Here Button. To fix this issue, firstly button_1 should have a its sticky option set to W, so then it doesn't move to the right side of it's grid cell, when it's grid cells width is manipulated. Another issue you have is that you are increasing you rows and columns of your grid placement too much, you should only increment by the needed spaces, for example, you should start at row 1 and then place your next row at row 2, this helps make sure it is easy to understand where each element is placed. With that all said I believe this code will fix the issue suitably: import tkinter as tk from tkinter import * import tkinter.filedialog as fdialog class karl(Frame): def __init__(self): tk.Frame.__init__(self) self.pack(fill = tk.BOTH) self.master.title("Image Selector") self.master.geometry("500x500") self.master.resizable(0, 0) self.pack_propagate(0) self.label_button_1 = Label(self, text="Select directory for picking images") self.label_button_1.grid(row = 0, column = 0, columnspan = 1, sticky = W) self.button_1 = tk.Button(self, text="CLICK HERE", width=25, command=self.open_dialog_box_to_select_folder) self.button_1.grid(row=0, column=1, columnspan=2, sticky=W) self.label_for_label_directory = Label(self, text="Current chosen directory") self.label_for_label_directory.grid(row=1, column=0, rowspan=1, columnspan=1, sticky=W) self.label_directory = Label(self, text="") self.label_directory.grid(row=1, column=1, rowspan=1, columnspan=2, sticky=W) self.label_for_entry_for_class_label_values = Label(self, text="Enter (+) seperated class labels\nto be assigned to the images") self.label_for_entry_for_class_label_values.grid(row = 2, column = 0, rowspan = 1, columnspan = 2, sticky = W) self.entry_for_class_label_values = Entry(self) self.entry_for_class_label_values.grid(row = 2, column = 1, rowspan = 1, columnspan = 1, sticky = W) def open_dialog_box_to_select_folder(self): self.chosen_directory_name = fdialog.askdirectory() self.label_directory.config(text = self.chosen_directory_name) def main(): karl().mainloop() if __name__ == '__main__': main() I changed the elements previously mentioned to accomplish this, if you have any questions about my solution feel free to ask :) Here is your tkinter program converted to an excel file, to visualize how the grid system works, the light blue is where your path string will be put when you select a folder. When you select a long file path, the path_label expands (the light blue section of the excel, this will push the click me button to the right. So far right that it will push the button of the windows view-able area like so.
unknown
d7680
train
Check the value being assigned to finalrow. Without having your file available, this is difficult to diagnose. I'm unable to find any obvious errors in your code, so I'll go based on experience. There are quite a few ways to determine what the final row of a spreadsheet is. You're using my favorite, but it has a couple pitfalls: * *Column A could be blank. I usually encounter this when using data pasted from another sheet or an SQL query, but this would be project specific. *Column A could extend beyond 12000 rows. I usually encounter this when I've populated column A with a formula and "autofilled" too far down. "End(xlUp)" would then go to "A1". To (usually) get around either of these issues, I always use the max possible row as a starting point; A65563 for Office 2010 or earlier, or A1048576 for anything after that. It doesn't take any longer to process, and gets more consistent results.
unknown
d7681
train
If NGINX work through PHP-FPM (FastCGI Process Manager) then you can uncomment the important part for PHP is the location ~ \.php$ {} stanza in the default vhost which is defined in the file vi /etc/nginx/sites-available/default like [...] location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } [...] And for NodeJS you can also modify the same Vhost file vi /etc/nginx/sites-available/default and add lines below location ~ \.php$ {} stanza like [...] location /testapp/ { proxy_pass http://localhost:3000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } [...] from this you can forwarding port to Node.js app with Nginx Now you can access the your page by this URL http://localhost/testapp/ instead of http://localhost:3000/ Hope It will work for you
unknown
d7682
train
// // create a C function that does some cleanup or reuse of the object // void RecycleFunction ( MyClass * pObj ) { // do some cleanup with pObj } // // when you create your object and assign it to a shared pointer register a cleanup function // std::shared_ptr<MyClass> myObj = std::shared_ptr<MyClass>( new MyClass, RecycleFunction); Once the last reference expires "RecyleFunction" is called with your object as parameter. I use this pattern to recycle objects and insert them back into a pool. A: This would allow std::weak_ptr, who still refer to the deleted object, to be cleaned up right in time. Actually, they only hold weak references, which do not prevent the object from being destroyed. Holding weak_ptrs to an object does not prevent it's destruction or deletion in any fashion. The quote you've given sounds to me like that guy just doesn't know which objects own which other objects, instead of having a proper ownership hierarchy where it's clearly defined how long everything lives. As for boost::signals2, that's what a scoped_connection is for- i.e., you're doing it wrong. The long and short is that there's nothing wrong with the tools in the Standard (except auto_ptr which is broken and bad and we have unique_ptr now). The problem is that you're not using them properly.
unknown
d7683
train
InputStream is = null; try { is = conn.getInputStream(); int ch; StringBuffer sb = new StringBuffer(); while ((ch = is.read()) != -1) { sb.append((char) ch); } return sb.toString(); } catch (IOException e) { throw e; } finally { if (is != null) { is.close(); } }
unknown
d7684
train
Look at the Git commits history from that PEP. A: I found the answer (1999) by emailing Python's db-sig. In this case, 1999 is two years before the first git commit on the project.
unknown
d7685
train
for i in list_of_stats: getattr(pageprocs, i, lambda: None)() The lambda: None part is optional, but will prevent AttributeError being raised if the specified function doesn't exist (it's an anonymous do-nothing function).
unknown
d7686
train
The nn.Linear layer is a linear fully connected layer. It corresponds to wX+b, not sigmoid(WX+b). As the name implies, it's a linear function. You can see it as a matrix multiplication (with or without a bias). Therefore it does not have an activation function (i.e. nonlinearities) attached. If you want to append an activation function to it, you can do so by defining a sequential model: model = nn.Sequential( nn.Linear(2, 1) nn.Sigmoid() ) Edit - if you want to make sure: x = torch.tensor([[0.2877, 0.2914]]) model = nn.Linear(2,1) m1 = nn.Sequential(model, nn.Sigmoid()) m1(x)[0].item(), torch.sigmoid(model(x))[0].item() A: Not surprisingly, PyTorch implements Linear as a linear function. Why the sigmoid is not included? * *well, in that case it'd be weird to call the resultant module Linear, since the purpose of the sigmoid is to "break" the linearity: the sigmoid is a non-linear function; *having a separate Linear module makes it possible to combine Linear with many activation functions other than the sigmoid, like the ReLU. If the course says that a sigmoid is included in a "linear layer", that's a mistake (and I'd suggest you to change course). Maybe you're mistaking a linear layer for a "fully-connected layer". In practice, a fully-connected layer is made of a linear layer followed by a (non-linear) activation layer.
unknown
d7687
train
You can use custom TypeAdapter in this case. Example: class ListWrapper<T> extends ArrayList<T> { private static final long serialVersionUID = 1L; String id = "asd"; List<T> list = new ArrayList<T>(); transient T listener = null; } Create your custom TypeAdapter class CustomTypeAdapter<T> extends TypeAdapter<ListWrapper<T>> { @Override public void write(JsonWriter writer, ListWrapper<T> value) throws IOException { if (value == null) { writer.nullValue(); return; } writer.beginObject(); // Add id field writer.name("id").value(value.id); // Add list field StringBuilder builder = new StringBuilder(""); builder.append("list : [ "); for (T t : value.list) { builder.append("T : " + t.toString() + ","); } String txt = builder.substring(0, builder.length() - 1) + "]"; writer.name("list").value(StringUtils.join(value.list, ";")); // Add other fields // TODO writer.endObject(); } @Override public ListWrapper<T> read(JsonReader in) throws IOException { // Implement your deserialization logic here return null; } } Sample usage: public static void main(String[] args) { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(ListWrapper.class, new CustomTypeAdapter<String>()); Gson gson = builder.create(); ListWrapper<String> lw = new ListWrapper<String>(); lw.list.add("as"); lw.list.add("is"); System.out.println(gson.toJson(lw)); } Sample output JSON: {"id":"asd","list":"as;is"}
unknown
d7688
train
Take a careful read of the API docs for BatchWrite. It will answer your questions. Since you're not showing your batch code (are you using set? update?), we have to look at the API docs to assess the failure cases: create() This will fail the batch if a document exists at its location. It sounds like you're probably not using create(), but this is the failure case. set() If the document does not exist yet, it will be created. So, a set will not fail if the documented was deleted before the batch got committed. update() If the document doesn't yet exist, the update fails and the entire batch will be rejected. So, if you try to update a nonexistent document, the batch will fail. If you want to decide what to do with each document, depending on its existence and contents, then control the failure cases, use a transaction. A: If I understand your question, I had a similar scenario and here's how I did it. First, I use generated universal ID's, uid's, for all my item keys/id's. Then, what you do is on the grandchildren, simply write the uid of the parent it is associated with. Each grandchild could be associated with more than one parent. As you create new items, you have to recursively update the parent with the uid of the item so the parent has record of all its associated child items. fetchPromise = []; fetchArray = []; if(!selectIsEmpty("order-panel-one-series-select") || !selectIsUnselected(orderPanelOneSeriesSelect)){ orderPanelOneTitle.innerHTML = "Select " + orderPanelOneSeriesSelect.value.toString().toUpperCase() + " Option"; } //on change we need to populate option select based on this value //now we need to get the particular series doc and fill get array then prmise all to get all options familyuid = getRecordFromList(doc.getElementById("order-panel-one-family-select"),orderPanelOneFamilySelect.selectedIndex); seriesuid = getRecordFromList(doc.getElementById("order-panel-one-series-select"),orderPanelOneSeriesSelect.selectedIndex); optionuid = getRecordFromList(doc.getElementById("order-panel-one-option-select"),orderPanelOneOptionsSelect.selectedIndex); optionRef = db.collection("products").doc(familyuid).collection("option"); itemRef = db.collection("products").doc(familyuid).collection("item"); targetRef = db.collection("products").doc(familyuid).collection("option").doc(optionuid); try { targetRef.get().then(function(snap) { if (snap.exists) { for (var key in snap.data()) { if (snap.data().hasOwnProperty(key)) { fetchPromise = itemRef.doc(key).get(); fetchArray.push(fetchPromise); } } Promise.all(fetchArray).then(function(values) { populateSelectFromQueryValues(values,"order-panel-one-item-select"); if(!selectIsEmpty("order-panel-one-item-select")){ enableSelect("order-panel-one-item-select"); } targetRef.get().then(function(snap){ if(snap.data().name){ var str = snap.data().name.toString(); orderAsideInfo.innerHTML = "Select " + capitalizeFirstLetter(str) + " item."; } }); }); } }).catch(function(error) { toast("error check console"); console.log("Error getting document:", error); }); }
unknown
d7689
train
Seems like you're loading the whole content of your file into a byte[] directly in memory, then writing this in the OutputStream. The problem with this approach is that if you load files of 1 or 2 GBs entirely in memory then you will encounter with OutOfMemoryError quickly. To avoid this, you should read the data from InputStream in small chunks and write these chunks in the output stream. Here's an example for file downloading: BufferedInputStream bis = new BufferedInputStream( new FileInputStream(new File("/path/to/folder", "file.pdf"))); ServletOutputStream outStream = response.getOutputStream(); //to make it easier to change to 8 or 16 KBs //make some tests to determine the best performance for your case int FILE_CHUNK_SIZE = 1024 * 4; byte[] chunk = new byte[FILE_CHUNK_SIZE]; int bytesRead = 0; while ((bytesRead = bis.read(chunk)) != -1) { outStream.write(chunk, 0, bytesRead); } bis.close(); outStream.flush(); outStream.close();
unknown
d7690
train
The injection code is simply chrome.tabs.insertCSS(tabId, { file : "mystyle.css" }); Make sure that mystyle.css is whiletlisted in the manifest "web_accessible_resources": [ "mystyle.css" ], Use Chrome Devtools to check if the injection succeeded. I had a problem where I thought my CSS wasn't being injected. On investigating, it was, but my selectors were incorrect. I ended up adding !important to many of the styles.
unknown
d7691
train
One common approach is to put public header files in a include directory and the rest of the source files (both hpp and cpp) in a src directory. For example, suppose you're working on a project called foo. A possible file hierarchy would be the following: foo include foo x.hpp y.hpp src x.cpp y.cpp z.cpp z.hpp In this case, you can simply add the include directory to the include path and you'll then be able to include the public header files like this: #include <foo/x.hpp>. A: I want to share my ideas while I am not sure if I have the right answer:). A: * *If the headers have complex inter-dependencies, it will be safer to simply install them all. Or you might want to read the source codes and clean the inter-dependencies. *It is the right thing to put all the headers in one discretionary. :)
unknown
d7692
train
From this post we can know: .NET Core doesn't support inclusion of .NET Framework libraries. Period. However, .NET Core supports .NET Standard, and since .NET Framework also implements .NET Standard, Microsoft made a special exception in the compiler to allow you include .NET Framework libraries, with the caveat that they may not actually function at all or totally. You get a warning to this effect when you include a .NET Framework library in a .NET Core project, and it's on you to ensure that the library works correctly end-to-end. Because .NET Core supports .NET Standard library, you can use the package of .NET Standard. This post is similar to your problem, his solution may inspire you.
unknown
d7693
train
In Angularjs, You wanna start working with basic animation stuff, you can know the Animation. Basic fade out Example: HTML: <div ng-controller="myCtrl"> <button ng-click="hideStuff()">Click me!</button> <div class="default" ng-hide="hidden" ng-class="{fade: startFade}">This will get hidden!</div> </div> CSS: .default{ opacity: 1; } .fade{ -webkit-transition: opacity 2s; /* For Safari 3.1 to 6.0 */ transition: opacity 2s; opacity: 0; } Angular: var myApp = angular.module('myApp',[]); myApp.controller("myCtrl", function($scope, $timeout){ $scope.hideStuff = function () { $scope.startFade = true; $timeout(function(){ $scope.hidden = true; }, 2000); }; });
unknown
d7694
train
Thanks for making the effort of adding applescript support to your app! Just a quick observation / criticism: When constructing terminology, by all means include spaces, but if that terminology takes the form of 'verb noun' (like 'do update') appleScripters will be irritated if the noun 'update' is not a properly modelled object, and if 'do' is not a proper command. I would argue that 'do' is a poor choice for a command name, because it is very vague. What's wrong with just using 'update' as the command? (i.e. treat it as a verb). This issue is treated in some detail by Apple's own technote 2106 (currently here), which you definitely should read and digest if you hope to please your AppleScripting user community. Apple themselves are not beyond stupid terminology choices such as updatePodcast and updateAllPodcasts (in iTunes). These are stupid choices because (according to tn2106) they contain no spaces, and because the better choice would be to have a proper podcast class and then have an update command which could be used on an individual podcast, all podcasts, or a particular chosen set of podcasts.
unknown
d7695
train
You can get the data using -string, defined by NSText (e.g. NSString *savedString = [aTextView string]) Your save code can be put in your NSTextDelegate (read, delegate of the NSTextView, because it's the immediate superclass), in – textDidEndEditing: which will be called, well, when editing is finished (e.g. when the user clicks outside the view) or one of the other methods. Then to reload the saved string if you emptied the text view or something, use [textView setString:savedString] before editing begins. NSTextDelegate documentation: here. I'm not sure what you mena when you say "store the contents of the box into a variable (array, etc.) Are you hoping for an array of custom notes? Text views store a string of data, so the easiest way of storing its value is using one string; if you need an array of notes you'd have to split the string value into different paragraphs, which shouldn't be too hard.
unknown
d7696
train
Put the await ctx.message.delete() out of your for loop. If a message is deleted and you're trying to delete it again it will throw an error.
unknown
d7697
train
what is the expected result? mixed up = the “pokemon_category” array?
unknown
d7698
train
I found solution to this after a bit of research: Here's the fiddle The JS code to be used is as follows: $(document).ready(function() { $('.multiselect').multiselect({ buttonWidth: 'auto', numberDisplayed:15, enableHTML: true, optionLabel: function(element) { return '<img src="http://placehold.it/'+$(element).attr('data-img')+'"> '+$(element).text(); }, onChange: function(element, checked) { //console.log(element.attr('value') + checked); $("ul.multiselect-container").find("input[type=checkbox]").each(function(){ //console.log(element.attr('value')); var valueAttr = $(this).attr('value'); if (element.attr('value') == valueAttr) { var checkParent = $(this).parent().parent().parent().hasClass('active'); //console.log(checkParent); if (checkParent == false) { $(this).removeAttr('disabled') }else{ $(this).attr('disabled','disabled') } } }); } }); });
unknown
d7699
train
I found a way to simulate the above behaviour by not destroying the console I created before but instead simply hiding and displaying it again. if (FirstTime) { FirstTime = false; Win32Wrapper.SetStdHandle(Win32Wrapper.STD_OUTPUT_HANDLE, HWND.Zero); Win32Wrapper.SetStdHandle(Win32Wrapper.STD_INPUT_HANDLE, HWND.Zero); Win32Wrapper.AllocConsole(); // show implicitly } else { Console.Clear(); // clear => simulate new console Win32Wrapper.ShowWindow(Win32Wrapper.GetConsoleWindow(), 5); // show (again) } Console.WriteLine("Hello World!"); Console.Read(); Console.ReadKey(true); Win32Wrapper.ShowWindow(Win32Wrapper.GetConsoleWindow(), 0); // hide Only the first function call allocates a new console further calls only show the already existing console again. All I need is a static variable to take track of it.
unknown
d7700
train
You can do this with sass. You just need to take maximum amount of Childs into $elements. <div class="parent"> <div class="child"> child one </div> <div class="child"> child two </div> <div class="child"> child three </div> </div> <style> $elements: 15; @for $i from 0 to $elements { .parent .child:nth-child(#{$i + 1}){ margin-left: ($i * 2)+px; } } </style>
unknown