id
stringlengths
3
6
prompt
stringlengths
100
55.1k
response_j
stringlengths
30
18.4k
156950
``` <div class="row"> <?php $r=mysql_query("SELECT * FROM advertisements WHERE $filter exposure!='0' AND `status`='2' AND (clicks_left_micro>0 OR clicks_left_mini>0 OR clicks_left_standard>0 OR clicks_left_extended>0) ORDER BY exposure DESC"); while($ar=mysql_fetch_array($r)): echo "<div class='span4'> text here text here</div>"; endwhile; ?> </div> ``` As you can see in the `$r` query, I am ordering by `exposure`. The exposure field can contain the numbers from `1-3`. What I am trying to do is to create a new row for each exposure number. Example: Advertisements that have exposure = 1, will be in the first row Below that, will be advertisements that have exposure = 2 And last, there will be advertisements that have exposure = 3 The way it is now, the advertisements/span4 divs are just being echoed out next to each other. I want to sort them inside the while loop in `<div class='row'></div>`
Why not try [jQuery post](http://api.jquery.com/jQuery.post/)? Example ``` <input type="text" name="text" id="text"> <div id="content" name="content"> <script> $('#text').keyup(function(){ $.post('posttothis.php', {text:$('#text').val()}, function(data) { $("#content").html(data); }); }); </script> ```
157028
I have an AngularJS front-end, which uses Restangular to make a call to the backend through a Java Servlet, which returns JSON data, which is then parsed to make a chart using Charts.js **Angular Factory** ``` app.factory('graphService', function($http, Restangular) { var exports = {}; exports.getRestangular = function() { // return Restangular.setBaseUrl("/api"); return Restangular.setBaseUrl("/apm/graph"); }; exports.getGraphDataDC = function(dcName) { return exports.getRestangular().all("graphData/DC/" + dcName).getList(); }; } ``` **Angular UI RestangularCall** ``` graphService.getGraphDataDC(item.name).then(function (data) { $scope.summary = data; $scope.JSONtoArrays(data); console.log(data); $scope.createChart(); }, function(data) { //Error }); ``` **Java Servlet** ``` try { dcData = persistance.getSummaryDelaysDC80Perc(from, to, pathInfo[pathInfo.length-1]); } catch(RuntimeException e) { LOGGER.error("Could not load data form database, reason: {}", e); throw new ServletException(e); } // parse to json json = ThreadsafeUtils.getGsonInstance(pretty).toJson(dcData); LOGGER.debug(dcData.size() + " summary entries were read"); out.write(json); break; } ``` **Persistence Facade** This is the function being called by the Servlet ``` public List<SummaryDelaysDataCenter80Perc> getSummaryDelaysDC80Perc(Date from, Date to, String dcName) throws RuntimeException { List<SummaryDelaysDataCenter80Perc> result = new ArrayList<>(); Calendar c = Calendar.getInstance(Locale.GERMANY); java.sql.Date minDate; java.sql.Date maxDate; String call; if (from != null) minDate = new java.sql.Date(from.getTime()); else minDate = Utils.getDBMinDate(); if (to != null) { maxDate = new java.sql.Date(to.getTime()); } else { maxDate = Utils.getDBMaxDate(); } call = "CALL " + summaryDelaysDCProcedureName + "(?, ?, ?, ?)"; try { //prepare statement java.sql.Connection connection = em.unwrap(java.sql.Connection.class); java.sql.CallableStatement cst = connection.prepareCall(call); //set parameters cst.setDate(1, minDate, c); cst.setDate(2, maxDate, c); cst.setString(3, dcName); // execute statement and retrieve result cst.execute(); ResultSet rs = cst.getResultSet(); while (rs.next()) { SummaryDelaysDataCenter80Perc sdeldc80 = new SummaryDelaysDataCenter80Perc(); DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMANY); String strDate = dateFormat.format(rs.getTimestamp(1)); sdeldc80.setName(rs.getString(2)); sdeldc80.setDate(strDate); sdeldc80.setPerc80serverdelay(Double.toString(rs.getDouble(3))); sdeldc80.setPerc80networkdelay(Double.toString(rs.getDouble(4))); sdeldc80.setPerc80clientdelay(Double.toString(rs.getDouble(5))); sdeldc80.setPerc80roundtrips(Long.toString(rs.getLong(6))); result.add(sdeldc80); } } catch (java.sql.SQLException e) { throw new RuntimeException("StoredProcedureCall was not successful", e); } return result; } ``` The json variable after calling getGsonInstance().toJson() looks like: ``` [{"Name" : "WER", "Count" : 90, "Date": "2016-05-25" }, {"Name" : "TWK", "Count" : 17, "Date": "2016-05-26" }, {"Name" : "XPR", "Count" : 26, "Date": "2016-05-27" }] ``` The Java Servlet code executes completely, but before `$scope.summary` is assigned the values retrieved, the code error with `Unexpected token [ in JSON at position 1367`. The JSON string does have a size of 1367 chars, but that means the last position 1366, so I'm not sure why it says error at 1367. How can I fix this error?
Try this : ``` //Select the first 2 elements of each row var rowSize = 4; $("div.col-sm-6").filter(function() { return $(this).index() % rowSize < 2; }); ``` **Demo:** ```js $("div.col-sm-6").filter(function() { return $(this).index() % 4 < 2 }).addClass('selected'); ``` ```css .selected { background-color:green; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="row"> <div class="col-sm-6"> <div>1 </div> </div> <div class="col-sm-6"> <div>2 </div> </div> <div class="col-sm-6"> <div>3 </div> </div> <div class="col-sm-6"> <div>4 </div> </div> <div class="col-sm-6"> <div>5 </div> </div> <div class="col-sm-6"> <div>6 </div> </div> <div class="col-sm-6"> <div>7 </div> </div> <div class="col-sm-6"> <div>8 </div> </div> ```
157124
See if i can get it working here: <https://codepen.io/canovice/pen/pVoBXJ> I have searched a bit for this answer but have had no luck resolving the issue. Here is a screenshot of an anchor tag in a react component of mine: [![enter image description here](https://i.stack.imgur.com/XToHn.png)](https://i.stack.imgur.com/XToHn.png) Notice the 3px margin (orange) and 3px padding (green), and also notice that below the text is a massive amount of white space that I would like to get rid of, but am struggling to do so. Any help is appreciated. \*Note: I've tried the suggestions [at this link here](https://stackoverflow.com/questions/3197601/white-space-at-bottom-of-anchor-tag) with no luck... \*Edit: let me know if theres more i can share on my app, ie. the current stylings, that will help. **Javascript for the React component:** ``` import React from 'react'; import FaTwitter from 'react-icons/lib/fa/twitter'; import './TopPageHeader.css' const TopPageHeader = () => <div className="top-page-container"> <a href="/">Canova's Analytics Dashboards</a> <div className="social-links"> <a href="https://twitter.com/SmokeyCanova"> <FaTwitter /> </a> </div> </div> export default TopPageHeader; ``` **and CSS:** ``` .top-page-container { padding: 15px 20px; margin: 0; min-height: 30px; height: auto; width: 100%; border-bottom: 1px solid #000; display: flex; justify-content: space-between; } .top-page-container a { /*display: block;*/ /*height: auto;*/ vertical-align: bottom; padding: 3px; margin: 3px; font-size: 1.75em; /*padding: 15px 0px;*/ color: #000; } .top-page-container .social-links { font-size: 1.75em; /*padding: 15px 0px;*/ } ``` Lastly, here's what the component looks like on the top of my page. Canova Analytics Dashboard is not centered, but rather offcenter up a bit (due to this extra white space below the anchor tag)... Ideally, the vertical center of the text, and the vertical center of the twitter logo, would both be vertically centered on the div they are contained in. [![enter image description here](https://i.stack.imgur.com/LWL9a.png)](https://i.stack.imgur.com/LWL9a.png) Here's what the component is contained within... This is a top page header component, and hence nothing before it. I don't think the css is being impacted anywhere else, but i could be wrong. [![enter image description here](https://i.stack.imgur.com/z42W1.png)](https://i.stack.imgur.com/z42W1.png)
Simple : ``` IO.Stream st1 ///Set MultiSelect property to true openfiledialog1.MultiSelect = true; ///Now get the filenames if (openfiledialog1.ShowDialog() == DialogResult.OK) { foreach (String file in openfiledialog1.FileNames) { try { if ((st1 = openfiledialog1.OpenFile()) != null) { using (st1) { List.Add(file); } } } ``` **Note: Don't know if this will also work with the custom control as well as no code is provided regarding the custom control**
157360
This is my sql query ``` SELECT a.CLASS_ID,a.ACTIVITY_TYPE_ID,COUNT(*) FROM AIS.CLASS_ASSESSMENT_DATE_INFO a WHERE a.CLASS_ID =22222 GROUP by a.CLASS_ID,a.ACTIVITY_TYPE_ID ``` I want to convert this query to linq query. Can you help me ?
Try this:- ``` var result = db.CLASS_ASSESSMENT_DATE_INFO.Where(x => x.CLASS_ID == 22222) .GroupBy(x => new { x.CLASS_ID, x.ACTIVITY_TYPE_ID }) .Select(x => new { CLASS_ID = x.Key.CLASS_ID, ACTIVITY_TYPE_ID = x.Key.ACTIVITY_TYPE_ID, Count = x.Count() }); ``` or in case if you prefer `query syntax` :- ``` var result = from x in db.CLASS_ASSESSMENT_DATE_INFO where x.CLASS_ID == 22222 group x by new { x.CLASS_ID, x.ACTIVITY_TYPE_ID } into g select new { CLASS_ID = g.Key.CLASS_ID, ACTIVITY_TYPE_ID = g.Key.ACTIVITY_TYPE_ID, Count = g.Count() }; ```
157776
I am new to Magento and maybe its a very basic question, but I want to display Pre-Order products on my home page. I have created an attribute `Product_Release_Date` and set it to a future date. When I try to get `Product_Release_Date` its returning blank. What I am doing wrong? ``` $_productCollection=$this->getLoadedProductCollection(); to get all products foreach ($_productCollection as $_product): <?php $currentDate = Mage::getModel('core/date')->date('Y-m-d H:i:s'); to get current date for compare echo $_product->getResource()->getAttribute('Product_Release_Date'); ``` When I try to display its showing blank, but it returns `productName` and other things. Only this date is not showing. Please help or provide some tutorial where it shows how to enable pre-order.
If you want to know whenever the Activity ceases to become visible (for whatever reason), override onPause (see <http://developer.android.com/reference/android/app/Activity.html>). As an aside, as a user, I would want this behaviour - if I move away from an Activity without pressing the back button or quit, I am hoping that it will handle everything silently - ie you use onPause (or alternatives) to store things so that when the activity resumes it has everything as I left it.
158499
I'm currently getting troubled with the react router dom@6. Like, I want to redirect users to other pages If they logged in. But when I use Navigate component It threw error saying that : "[Navigate] is not a component. All component children of Routes must be a Route or React.Fragment" Though I have wrapped it in the fragment but the result still the same. Please help me, this is my code: ``` import {BrowserRouter as Router, Routes, Route, Navigate} from 'react-router-dom'; import Home from './pages/Home'; import ProductList from './pages/ProductList'; import Product from './pages/Product'; import Register from './pages/Register'; import Login from './pages/Login'; import Cart from './pages/Cart'; import ErrorPage from './pages/ErrorPage'; function App() { const user = true; return ( <Router> <Routes> <Route path="/" element={<Home/>} /> <Route path="/products/:category" element={<ProductList/>} /> <Route path="/product/:id" element={<Product/>} /> <Route path="/cart" element={<Cart/>} /> <Route path="/dang-ky" element={<Register/>} /> <Route path="/dang-nhap" element={<Login/>} > {user ? <><Navigate to="/" replace/></> : <Login/>} </Route> <Route path="*" element={<ErrorPage/>} /> </Routes> </Router> ); } export default App; ```
Edit: This is also a possible solution, drawback is that you cant redirect properly. You just have to make sure that you have the fallbackroutes set up right. ``` {isSignedIn && <Route path="" element={} />} ``` I would recommend using an AuthRout to wrap your Routes. ```js function AuthRoute ({children}) { if(!user.isSignedIn){ //Not signed in return <Navigate to="/signIn" /> } //Signed in return children } //Route itself <Route path="/abc" element={<AuthRoute><YourComponent /></AuthRoute>} /> ``` That way the user gets redirected if he is not signed in
158783
I have a custom block loading products on my front page that loads the four newest products that have a custom product picture attribute set via: ``` $_helper = $this->helper('catalog/output'); $_productCollection = Mage::getModel("catalog/product")->getCollection(); $_productCollection->addAttributeToSelect('*'); $_productCollection->addAttributeToFilter("image_feature_front_right", array("notnull" => 1)); $_productCollection->addAttributeToFilter("image_feature_front_right", array("neq" => 'no_selection')); $_productCollection->addAttributeToSort('updated_at', 'DESC'); $_productCollection->setPageSize(4); ``` What I am trying to do is grab the `image_feature_front_right` label as set in the back-end, but have been unable to do so. Here is my code for displaying the products on the front end: ``` <?php foreach($_productCollection as $_product) : ?> <div class="fll frontSale"> <div class="productImageWrap"> <img src="<?php echo $this->helper('catalog/image')->init($_product, 'image_feature_front_right')->directResize(230,315,4) ?>" /> </div> <div class="salesItemInfo"> <a href="<?php echo $this->getUrl($_product->getUrlPath()) ?>"><p class="caps"><?php echo $this->htmlEscape($_product->getName());?></p></a> <p class="nocaps"><?php echo $this->getImageLabel($_product, 'image_feature_front_right') ?></p> </div> </div> ``` I read that `$this->getImageLabel($_product, 'image_feature_front_right')` was the way to do it, but produces nothing. What am I doing wrong? Thanks! Tre
It seems you asked this same question in another thread, so to help others who might be searching for an answer, I'll anser it here as well: I imagine this is some sort of magento bug. The issue seems to be that the Magento core is not setting the custom\_image\_label attribute. Whereas for the default built-in images [image, small\_image, thumbnail\_image] it does set these attributes - so you could do something like: ``` $_product->getData('small_image_label'); ``` If you look at `Mage_Catalog_Block_Product_Abstract::getImageLabel()` it just appends '\_label' to the `$mediaAttributeCode` that you pass in as the 2nd param and calls `$_product->getData()`. If you call `$_product->getData('media_gallery');` you'll see the custom image label is available. It's just nested in an array. So use this function: ``` function getImageLabel($_product, $key) { $gallery = $_product->getData('media_gallery'); $file = $_product->getData($key); if ($file && $gallery && array_key_exists('images', $gallery)) { foreach ($gallery['images'] as $image) { if ($image['file'] == $file) return $image['label']; } } return ''; } ``` It'd be prudent to extend the Magento core code (Ideally `Mage_Catalog_Block_Product_Abstract`, but I don't think Magento lets you override Abstract classes), but if you need a quick hack - just stick this function in your phtml file then call: ``` <?php echo getImageLabel($_product, 'image_feature_front_right')?> ```
159719
Is there an equivalent to `getopt()` in the visual studio CRT? Or do I need to get it and compile it with my project? **Edit** clarification `getopt` is a utility function in the unix/linux C Run Time library for common command line parsing chores i.e. parsing arguments of the form `-a -b` `-f someArg` etc'
Advice: boost::program\_options instead. <http://www.boost.org/doc/libs/1_41_0/doc/html/program_options.html>
159784
I have a normal list, and I want to change the element of that list every 25 indexes (starting by the second index). So I've created a loop to generate that number and store it in a list (i.e 2,27,52,77....). Then I've printed every item of that index, but for now I can't seem to find a way to work with re.sub. I want to replace those elements by new ones, and then write all of items on the list (not just those I've changed) into a file. **So the goal is using re.sub or some other method to replace:** ``` ' Title =' by ' Author =' ``` How do I achieve this? Here is my code: ``` counter = 0 length = len(flist) # Max.Size of List ab = [2] for item in flist: counter +=1 a = ((25*counter)+2) #Increment ab.append(a) if a >= length: ab.pop() #Removing last item break for i in ab: print(flist[i-1]) #Printing element in that index #replace item #write to file fo = open('somefile.txt', 'w') for item in flist: fo.write(item) fo.close() ``` **PS: I'm new to python, sugestions and criticism is much apreciated!**
To match the text you can use: ``` new_str = re.sub(r'\s+Title\s+=', 'Author =', old_str) ``` `\s` means whitespace, `+` means one or more. You can use `\s{4}` to match exactly 4 whitespaces, or as many as you need. More info [here](https://docs.python.org/3/library/re.html). Alternatively, you can use `replace()`: ``` new_str = old_str.replace(' Title =', 'Author =') ``` --- You can use `range()` to simplify the rest of your code a bit. range() has 3 arguments, 2 of which are optional; start, end, step. ``` for i in range(2, 200, 25): print(i) ``` Finally, you can use `with open()` instead of `open()`: ``` with open('my_file.txt', 'w') as fo: # Do stuff here. .... .... # File closes automatically. ```
159808
Well, I would make it easier to add smileys and the code it should be replaced with a bit easier, So insted of creating 2 arrays, I would like to only have one. So this is a example how I wanted it. $Smileys = array(":D" => ""); So instead of using it like $Smileys = array(":D"); $SmileyReplace = array(""); But is it possible at all? I can't seem to find something on Google that helps. My new code that I wanted to use and the old. New: ``` function fixSmileys($Data) { $Smileys = array( ":D" => '<img src="/application/modules/Chat/externals/images/smilies/grin.png" title=":D" alt=":D"/>', ":)" => '<img src="/application/modules/Chat/externals/images/smilies/smile.png" title=":)" alt=":)"/>', ":P" => '<img src="/application/modules/Chat/externals/images/smilies/tongue.png" title=":P" alt=":P"/>', ":S" => '<img src="/application/modules/Chat/externals/images/smilies/confused.png" title=":S" alt=":S"/>', ":'(" => '<img src="/application/modules/Chat/externals/images/smilies/cry.png" title=":'."'".'(" alt=":Cry:"/>', ":$" => '<img src="/application/modules/Chat/externals/images/smilies/embarrassed.png" title=":$" alt=":$"/>', ":(" => '<img src="/application/modules/Chat/externals/images/smilies/frown.png" title=":(" alt=":("/>', ":@" => '<img src="/application/modules/Chat/externals/images/smilies/mad.png" title=":@" alt=":@"/>', ";)" => '<img src="/application/modules/Chat/externals/images/smilies/wink.png" title=";)" alt=";)"/>', "B)" => '<img src="/application/modules/Chat/externals/images/smilies/cool.png" title="B)" alt="B)"/>', ":|" => '<img src="/application/modules/Chat/externals/images/smilies/neutral.png" title=":|" alt=":|"/>', ":lol:" => '( ?° ?? ?°)', ":derp:" => '<img src="/application/modules/Chat/externals/images/smilies/derp.png" title=":derp:" alt=":derp:"/>', ";D" => '<img src="/application/modules/Chat/externals/images/smilies/awesome.png" title=";D" alt=";D"/>', ":troll:" => '<img src="/application/modules/Chat/externals/images/smilies/troll.png" title=":troll:" alt=":troll:"/>', ":spin:" => '<img src="/application/modules/Chat/externals/images/smilies/abspin.gif" title=":spin:" alt=":spin:"/>', ":love:" => '<img src="/application/modules/Chat/externals/images/smilies/heart.png" title=":love:" alt=":love:"/>', ":sick:" => '<img src="/application/modules/Chat/externals/images/smilies/sick.png" title=":lol:" alt=":sick:"/>', ":O_O:" => '<img src="/application/modules/Chat/externals/images/smilies/sawut.png" title=":O_O:" alt=":O_O:"/>', ":bath:" => '<img src="/application/modules/Chat/externals/images/smilies/bath-time.png" title=":bath:" alt=":bath:"/>', ":socks:" => '<img src="/application/modules/Chat/externals/images/smilies/socks.png" title=":socks:" alt=":socks:"/>', ":boss:" => '<img src="/application/modules/Chat/externals/images/smilies/SuitBozzsmiley.png" title=":boss:" alt=":boss:"/>', ":potato:" => '<img src="/application/modules/Chat/externals/images/smilies/potatoes.png" title=":potato:" alt=":potato:"/>'); return $Smileys[$Data]; } ``` And the old code that I currenty use that uses only str\_replace and alot of lines. ``` function fixSmileys($Data) { $xCommentx = $Data; $xCommentx1 = str_replace(":D", '<img src="/application/modules/Chat/externals/images/smilies/grin.png" title=":D" alt=":D"/>', $xCommentx); $xCommentx2 = str_replace(":)", '<img src="/application/modules/Chat/externals/images/smilies/smile.png" title=":)" alt=":)"/>', $xCommentx1); $xCommentx3 = str_replace(":P", '<img src="/application/modules/Chat/externals/images/smilies/tongue.png" title=":P" alt=":P"/>', $xCommentx2); $xCommentx4 = str_replace(":S", '<img src="/application/modules/Chat/externals/images/smilies/confused.png" title=":S" alt=":S"/>', $xCommentx3); $xCommentx5 = str_replace(":'(", '<img src="/application/modules/Chat/externals/images/smilies/cry.png" title=":'."'".'(" alt=":Cry:"/>', $xCommentx4); $xCommentx6 = str_replace(":$", '<img src="/application/modules/Chat/externals/images/smilies/embarrassed.png" title=":$" alt=":$"/>', $xCommentx5); $xCommentx7 = str_replace(":(", '<img src="/application/modules/Chat/externals/images/smilies/frown.png" title=":(" alt=":("/>', $xCommentx6); $xCommentx8 = str_replace(":@", '<img src="/application/modules/Chat/externals/images/smilies/mad.png" title=":@" alt=":@"/>', $xCommentx7); $xCommentx9 = str_replace(";)", '<img src="/application/modules/Chat/externals/images/smilies/wink.png" title=";)" alt=";)"/>', $xCommentx8); $xCommentx10 = str_replace("B)", '<img src="/application/modules/Chat/externals/images/smilies/cool.png" title="B)" alt="B)"/>', $xCommentx9); $xCommentx11 = str_replace(":lol:", '( ͡° ͜ʖ ͡°)', $xCommentx10); $xCommentx12 = str_replace(":derp:", '<img src="/application/modules/Chat/externals/images/smilies/derp.png" title=":derp:" alt=":derp:"/>', $xCommentx11); $xCommentx13 = str_replace(";D", '<img src="/application/modules/Chat/externals/images/smilies/awesome.png" title=";D" alt=";D"/>', $xCommentx12); $xCommentx14 = str_replace(":troll:", '<img src="/application/modules/Chat/externals/images/smilies/troll.png" title=":troll:" alt=":troll:"/>', $xCommentx13); $xCommentx15 = str_replace(":approve:", '<img src="/application/modules/Chat/externals/images/smilies/approved.png" title=":approve:" alt=":approve:"/>', $xCommentx14); $xCommentx16 = str_replace(":lolol:", '<img src="/application/modules/Chat/externals/images/smilies/lolol.png" title=":brohoof:" alt=":brohoof:"/>', $xCommentx15); $xCommentx17 = str_replace(":asdf:", '<img src="/application/modules/Chat/externals/images/smilies/asdf.png" title=":facehoof:" alt=":facehoof:"/>', $xCommentx16); $xCommentx18 = str_replace(":spin:", '<img src="/application/modules/Chat/externals/images/smilies/abspin.gif" title=":spin:" alt=":spin:"/>', $xCommentx17); $xCommentx19 = str_replace(":love:", '<img src="/application/modules/Chat/externals/images/smilies/heart.png" title=":love:" alt=":love:"/>', $xCommentx18); $xCommentx20 = str_replace(":sick:", '<img src="/application/modules/Chat/externals/images/smilies/sick.png" title=":lol:" alt=":sick:"/>', $xCommentx19); $xCommentx21 = str_replace(":O_O:", '<img src="/application/modules/Chat/externals/images/smilies/sawut.png" title=":O_O:" alt=":O_O:"/>', $xCommentx20); $xCommentx22 = str_replace(":bath:", '<img src="/application/modules/Chat/externals/images/smilies/bath-time.png" title=":bath:" alt=":bath:"/>', $xCommentx21); $xCommentx23 = str_replace(":socks:", '<img src="/application/modules/Chat/externals/images/smilies/socks.png" title=":socks:" alt=":socks:"/>', $xCommentx22); $xCommentx24 = str_replace(":boss:", '<img src="/application/modules/Chat/externals/images/smilies/SuitBozzsmiley.png" title=":boss:" alt=":boss:"/>', $xCommentx23); $xCommentx25 = str_replace(":potato:", '<img src="/application/modules/Chat/externals/images/smilies/potatoes.png" title=":potato:" alt=":potato:"/>', $xCommentx24); $xCommentxFinal = str_replace(":|", '<img src="/application/modules/Chat/externals/images/smilies/neutral.png" title=":|" alt=":|"/>', $xCommentx25); return $xCommentxFinal; } ``` The currenty code works as follow, The $Data that is being feeded contains like "Hello world :D" So it goes thru all the str\_replaces until it finds the match and replaces it with a html code. But I would just like to have it like the New, but useless nonworking code. The reason I would like have it like that is to have it easier to add smileys to the site.
You can try to use it in one function by spliting the array into two using buildin functions eg: ``` ... return str_replace(array_keys($Smileys), array_values($Smileys), $Data) ``` **EDIT:** Keep in mind that those functions do a copy of the array so propably there are better solutions than spliting one array into two ;)
159898
I have set an event-observer in my custom module but observer is not getting called. i have enabled my log and i am getting this warning : ``` 2013-08-14T11:17:48+00:00 ERR (3): Warning: include(Mage/CompanyName/ModuleName/Model/Observer.php): failed to open stream: No such file or directory in /var/www/nyp/lib/Varien/Autoload.php on line 93 2013-08-14T11:17:48+00:00 ERR (3): Warning: include(): Failed opening 'Mage/CompanyName/ModuleName/Model/Observer.php' for inclusion (include_path='/var/www/nyp/app/code/local:/var/www/nyp/app/code/community:/var/www/nyp/app/code/core:/var/www/nyp/lib:.:/usr/share/php:/usr/share/pear') in /var/www/nyp/lib/Varien/Autoload.php on line 93 ``` Code in my config.xml to attach event and observer : ``` <global> <events> <sales_order_place_after> <observers> <CompanyName_ModuleName_Observer> <type>singleton</type> <class>CompanyName_ModuleName/observer</class> <method>methodName</method> </CompanyName_ModuleName_Observer> </observers> </sales_order_place_after> </events> <global> ``` Code in my CompanyName/ModuleName/Model/Observer.php : ``` <?php class CompanyName_ModuleName_Model_Observer { public function __contruct() { } public function methodName(Varien_Event_Observer $observer) { } } ``` Thanks,
I think [this post](http://codegento.com/2011/04/observers-and-dispatching-events/) should help you. In your case it would be something like this: ``` <global> <events> <sales_order_place_after> <observers> <modulename_observername> <type>singleton</type> <class>modulename/observer</class> <method>methodName</method> </modulename_observername> </observers> </sales_order_place_after> </events> <models> <modulename> <class>CompanyName_ModuleName_Model</class> </modulename> </models> <global> ```
159998
I am very to Modern UI Programming and now i got stuck in a small C# WPF Application which is basically a learning project of MVVM design pattern. I have a DataGrid and some Buttons to handle data operation (add, edit, delete). What i want to achieve: the edit button should not be enable, when no row in grid is selected. **edit button:** ``` <Button Width="126" Height="22" Content="Edit" Margin="5,5,5,5" Command="{Binding KontoEdit}" /> ``` **grid:** ``` <DataGrid ItemsSource="{Binding Konten}" SelectedItem="{Binding SelectedKonto}"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Path=KtoNr}" Header="Nr" IsReadOnly="True" /> <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" IsReadOnly="True" /> <DataGridTextColumn Binding="{Binding Path=KtoArt}" Header="Kontoart" IsReadOnly="True" /> <DataGridTextColumn Binding="{Binding Path=KtoKlasse}" Header="Kontenklasse" IsReadOnly="True" /> </DataGrid.Columns> </DataGrid> ``` **view model:** ``` public class MainViewModel : INotifyPropertyChanged { KontenDB ctx = new KontenDB(); public MainViewModel() { FillKonten(); CanKontoEditExecute = true ; KontoEdit = new RelayCommand(o => { DoKontoEdit(SelectedKonto); }, param => CanKontoEditExecute); } #region //Commands public void DoKontoEdit(Konten k) { //Edit the Selected Item } private ICommand _kontoEdit; public ICommand KontoEdit { get { return _kontoEdit; } set { _kontoEdit = value; } } private bool _canKontoEditExecute; public bool CanKontoEditExecute { get { return _canKontoEditExecute; } set { _canKontoEditExecute = value; } } #endregion //Commands private void FillKonten() { var q = (from k in ctx.Konten select k).ToList(); Konten = new ObservableCollection<Konten>(q); } private ObservableCollection<Konten> _konten; public ObservableCollection<Konten> Konten { get { return _konten; } set { _konten = value; NotifyPropertyChanged(); } } private Konten _selectedKonto; public Konten SelectedKonto { get { return _selectedKonto; } set { _selectedKonto = value; NotifyPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } ``` model is generated by EF6. **edit: RelayCommand class:** ``` public class RelayCommand : ICommand { private Action<object> execute; private Predicate<object> canExecute; private event EventHandler CanExecuteChangedInternal; public RelayCommand(Action<object> execute) : this(execute, DefaultCanExecute) { } public RelayCommand(Action<object> execute, Predicate<object> canExecute) { if (execute == null) { throw new ArgumentNullException("execute"); } if (canExecute == null) { throw new ArgumentNullException("canExecute"); } this.execute = execute; this.canExecute = canExecute; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; CanExecuteChangedInternal += value; } remove { CommandManager.RequerySuggested -= value; CanExecuteChangedInternal -= value; } } public bool CanExecute(object parameter) { return canExecute != null && canExecute(parameter); } public void Execute(object parameter) { execute(parameter); } public void OnCanExecuteChanged() { EventHandler handler = CanExecuteChangedInternal; if (handler != null) { handler.Invoke(this, EventArgs.Empty); } } public void Destroy() { canExecute = _ => false; execute = _ => { return; }; } private static bool DefaultCanExecute(object parameter) { return true; } } ``` So how can i achieve that when: no row in datagrid is selected or SelectedKonto is null the CanKontoEditExecute property changes to false? Thanks a lot for your help!
Java implements Generics using [Erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html). That means that at run-time, the JVM can't know what types are associated with the Generic class/method/object/whatever. There are hacks and workarounds that can be used to try to work with this, but this is a fundamental part of the language. Given that you're working with JSON, you may wish to investigate whether the library has functions specialized for Generic datastructures. I happen to know for a fact that [GSON has functions specific to handling Generic data structures](https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html#toJson(java.lang.Object,%20java.lang.reflect.Type)).
160928
Trying to restore an Amazon S3 object from GLACIER with the code below. ``` import boto3 s3 = boto3.resource('s3', verify=False) bucket_name = r"my-source-bucket" bucket = s3.Bucket(bucket_name) key ="glacier_file2.txt" try: bucket.meta.client.restore_object(Bucket=bucket_name, Key=key, RestoreRequest={'Days': 1, 'GlacierJobParameters': {'Tier': 'Expedited'}}) except Exception as e: print({"Problem Restoring": str(e)}) ``` The code submits successfully, however the object still shows as in GLACIER in the AWS console as well as when I query it with boto3 even days later. If I run the following code I see it still shows GLACIER. ``` key = s3.Object(bucket_name,key) print (key.storage_class) print (key.restore) >>>>GLACIER >>>>ongoing-request="false", expiry-date="Sun, 19 Sep 2021 00:00:00 GMT" ``` When I try to do this same thing in the AWS console, I see that it says it's both in GLACIER AND restore is complete? [![enter image description here](https://i.stack.imgur.com/wJZsI.png)](https://i.stack.imgur.com/wJZsI.png) Does anyone have any insight? After restoring, I'm actually able to download the file, which tells me it's not actually in GLACIER, despite saying it is in the browser, and also in boto3. Is something wrong with how the storage class is being reported after a restore occurs? **edit** I should point out I'm doing an expedited restore, which only takes a few minutes.
After doing a little more research, it appears that a "restore" is not what one would expect. Once an object goes to GLACIER there is no going back, other than "temporarily" restoring it (like I've done above) and then overwriting it. For example, I was able to run this command after restoring glacier\_file2.txt ``` aws s3 cp s3://my-source-bucket/glacier_file2.txt s3://my-source-bucket/glacier_file2.txt --force-glacier-transfer --storage-class STANDARD ``` <https://newbedev.com/how-do-i-restore-from-aws-glacier-back-to-s3-permanently> This would not work if I had not triggered the temporary GLACIER restore.
161046
ideally, I'd like to get the name of the property referenced by a KeyPath. But this seems not to be possible out-of-the-box in Swift. So my thinking is that the KeyPath could provide this information based on protocol extension added by a developer. Then I'd like to design an API with an initializer/function that accepts a KeyPath conforming to that protocol (that adds a computed property). So far I was only able to define the protocol and conditional conformance of the protocol. The following code compiles fine. ``` protocol KeyPathPropertyNameProviding { var propertyName: String {get} } struct User { var name: String var age: Int } struct Person { var name: String var age: Int } extension KeyPath: KeyPathPropertyNameProviding where Root == Person { var propertyName: String { switch self { case \Person.name: return "name" case \Person.age: return "age" default: return "" } } } struct PropertyWrapper<Model> { var propertyName: String = "" init<T>(property: KeyPath<Model, T>) { if let property = property as? KeyPathPropertyNameProviding { self.propertyName = property.propertyName } } } let userAge = \User.age as? KeyPathPropertyNameProviding print(userAge?.propertyName) // "nil" let personAge = \Person.age as? KeyPathPropertyNameProviding print(personAge?.propertyName) // "age" let wrapper = PropertyWrapper<Person>(property: \.age) print(wrapper.propertyName) // "age" ``` But I am unable to restrict the API so that initialization parameter `property` has to be a KeyPath AND must conform to a certain protocol. For example, the following would result in a compilation error but should work from my understanding (but probably I miss a key detail ;) ) ``` struct PropertyWrapper<Model> { var propertyName: String = "" init<T>(property: KeyPath<Model, T> & KeyPathPropertyNameProviding) { self.propertyName = property.propertyName // compilation error "Property 'propertyName' requires the types 'Model' and 'Person' be equivalent" } } ``` Any tips are highly appreciated!
You are misunderstanding conditional conformance. You seem to want to do this in the future: ``` extension KeyPath: KeyPathPropertyNameProviding where Root == Person { var propertyName: String { switch self { case \Person.name: return "name" case \Person.age: return "age" default: return "" } } } extension KeyPath: KeyPathPropertyNameProviding where Root == User { var propertyName: String { ... } } extension KeyPath: KeyPathPropertyNameProviding where Root == AnotherType { var propertyName: String { ... } } ``` But you can't. You are trying to specify multiple conditions to conform to the same protocol. See [here](https://stackoverflow.com/questions/57282655/why-there-cannot-be-more-than-one-conformance-even-with-different-conditional) for more info on why this is not in Swift. Somehow, one part of the compiler thinks that the conformance to `KeyPathPropertyNameProviding` is not conditional, so `KeyPath<Model, T> & KeyPathPropertyNameProviding` is actually the same as `KeyPath<Model, T>`, because somehow `KeyPath<Model, T>` already "conforms" to `KeyPathPropertyNameProviding` as far as the compiler is concerned, it's just that the property `propertyName` will only be available *sometimes*. If I rewrite the initialiser this way... ``` init<T, KeyPathType: KeyPath<Model, T> & KeyPathPropertyNameProviding>(property: KeyPathType) { self.propertyName = property.propertyName } ``` This *somehow* makes the error disappear and produces a warning: > > Redundant conformance constraint 'KeyPathType': 'KeyPathPropertyNameProviding' > > >
161452
I'm using Rails 3 for the first time (especially asset pipelining and less-rails-bootstrap), so I might be missing some really basic concept here. I've tried two approaches for including the Twitter bootstrap CSS into my project and both have problems. **Approach #1:** `app/assets/stylesheets/application.css` has `require twitter/bootstrap`. This includes the bootstrap css file using a separate link/href tag, which is good. However, the **problem** is that in my custom CSS file, say `app/stylesheets/mystyles.css` I am unable to access variables+mixins defined in less within the bootstrap code, like `@gray`, `.box-shadow`, etc. **Approach #2:** Put `@import 'twitter/bootstrap'` at the top of `app/assets/stylesheets/mystyles.css`. This allows me to access variables+mixins defined in less (within the bootstrap code), which is good. However, the **problem** is that it pulls in the entire bootstrap CSS at the top of `mystyles.css` increasing the filesize. If there are a bunch of different stylesheets that `@import twitter/ bootstrap` it would cause a lot of duplication. What's the recommended approach for handling this situation?
Your answer is sufficient if you want to exclusively use the default twitter bootstrap variables. If you find yourself wanting to override the variables and have them applied to BOTH twitter bootstrap's styles AND your own styles, you'll need to do separate out your variables into its own myvariables.less file and have that file included with twitter bootstrap instead of in the manifest. Example ------- application.css: ``` /* * Notice we aren't including twitter/bootstrap/bootstrap in here *= require bootstrap_and_overrides *= require mystyles */ ``` bootstrap\_and\_overrides.less: ``` # Bootstrap with both bootstrap's variables, and your own @import "twitter/bootstrap/bootstrap"; @import "myvariables"; ``` mystyles.less: ``` # Your styles with both bootstrap's variables, and your own @import "myvariables"; h1 { // Use color: @textColor; } ``` myvariables.less: ``` @import "twitter/bootstrap/variables"; @textColor: green; ```
161535
I have a method which tests for the existence of a file prior to carrying out some manipulation of file content as follows: ``` Private Sub AddHeaderToLogFile() ''#Only if file does not exist If Not File.Exists(_logPath) Then Dim headerLogger As Logger headerLogger = LogManager.GetLogger("HeaderLogger") ''#Use GlobalDiagnosticContext in 2.0, GDC in pre-2.0 NLog.GlobalDiagnosticsContext.Set("appName", _appName) NLog.GlobalDiagnosticsContext.Set("fileVersion", _fileVersion) NLog.GlobalDiagnosticsContext.Set("logId", 0) headerLogger.Info("") End If End Sub ``` The idea is that if the file does not exist, then the file is generated by calls to the NLog logger instance, at which point the file is created and the specified header info is inserted. The method works fine from the application itself, however I have a simple NUnit test which implements a test method to verify that the file is created and populated as expected. When I step through with the debugger, I find that '\_logPath' is set to: D:\Documents and Settings\TE602510\Local Settings\Temp\nunit20\ShadowCopyCache\4288\_634286300896838506\Tests\_-1937845265\assembly\dl3\7cdfe61a\aa18c98d\_f0a1cb01\logs\2010-12-22.log Unfortunately, despite the fact that the file DOES exist, the call to File.Exists returns false. From earlier viewing of the config path the above path would appear to be correct for these NUnit tests. Does anybody have a clue what is happening here and what I need to do to get the desired result? The pathname to the log file as per the XP file system is: D:\Documents and Settings\TE602510\My Documents\_VSSWorkArea\PsalertsIp\Tests\bin\Debug\logs Kind Regards Paul J.
Short answer : of course it makes sense, you can apply a CPS-transform directly, you will only have lots of cruft because each argument will have, as you noticed, its own attached continuation In your example, I will consider that there is a `+(x,y)` uncurried primitive, and that you're asking what is the translation of ``` let add x y = +(x,y) ``` (This `add` faithfully represent OCaml's `(+)` operator) `add` is syntaxically equivalent to ``` let add = fun x -> (fun y -> +(x, y)) ``` So you apply a CPS transform¹ and get ``` let add_cps = fun x kx -> kx (fun y ky -> ky +(x,y)) ``` If you want a translated code that looks more like something you could have willingly written, you can devise a finer transformation that actually considers known-arity function as non-curried functions, and tream all parameters as a whole (as you have in non-curried languages, and as functional compilers already do for obvious performance reasons). ¹: I wrote "*a* CPS transform" because there is no "one true CPS translation". Different translations have been devised, producing more or less continuation-related garbage. The formal CPS translations are usually defined directly on lambda-calculus, so I suppose you're having a less formal, more hand-made CPS transform in mind. The good properties of CPS (as a *style* that program respect, and not a specific transformation into this style) are that the order of evaluation is completely explicit, and that all calls are tail-calls. As long as you respect those, you're relatively free in what you can do. Handling curryfied functions specifically is thus perfectly fine. Remark : Your `(cps-add k 1 2)` version can also be considered tail-recursive if you assume the compiler detect and optimize that cps-add actually always take 3 arguments, and don't build intermediate closures. That may seem far-fetched, but it's the exact same assumption we use when reasoning about tail-calls in non-CPS programs, in those languages.
161566
I am using LWJGL and I want to cause an event to rapidly take place when I press and hold a key (like holding a letter key in word). This is my attempt: ``` while(Keyboard.next()) { if (Keyboard.getEventKeyState()) { if (Keyboard.isKeyDown(Keyboard.KEY_UP)) { i += 5.0f; } if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { i -= 1.0f; } } } ```
classic closure problem. you need to use an anonymous function to induce scope, or break out all of your logic into its own function. Here's an article about Javascript closure: [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) KineticJS supports an unlimited number of Animations (until of course, you run out of memory)
161667
I want to generate a movie from an image sequence. I used this code: ``` %% 4.) GENERATE THE MOVIE disp("Generate the Movie..."); imageNames = dir(fullfile('images','*.png')); imageNames = {imageNames.name}'; outputVideo = VideoWriter(fullfile('images','AcousticCamera.mp4'),'MPEG-4'); outputVideo.FrameRate = 10; outputVideo.Quality = 95; open(outputVideo) for ii = 1:length(imageNames) %% loop over the images img = imread(fullfile('images',imageNames{ii})); writeVideo(outputVideo,img) end close(outputVideo) ``` The input images are png color images but the video is black white.
The vector `overlaps` is never resized, so it has length zero, but you are writing to it anyway. This causes the program to crash immediately on my system. Another issue is that you forget to check the last sphere when printing the results. Also, there is the issue that after reading the last line, `leer1.eof()` is still `false`. Only after trying to read past the end of the file will `eof()` be set. The correct way to read in the spheres is: ``` while (true) { leer1 >> a >> b >> c >> aux; if (!leer1) { // Either the end of the file was reached, // or some error occured while reading the file. break; } xcentro.push_back(a); ... } ```
162047
I have seen this effect on a few sites ( [CSS Wizardry](http://csswizardry.com/2012/02/pragmatic-practical-font-sizing-in-css/) - watch the logo/nav ) where an element stays in view while scrolling down the page (this is not the hard part) & then stops scrolling when it 'collides' (for want of a better word) with a specified element (the hard part). I have found two plugins that aim to do just this but do not have all the functionality I need: **1. jQuery lockScroll** <http://www.anthonymclin.com/code/7-miscellaneous/108-jquery-lockscroll-13> This forces the desired element to have position fixed to begin with, which could mean that if the element starts below the fold, it is never seen. (Demo: <http://www.anthonymclin.com/media/demos/jquery.lockScroll.1.3/>) **2. jQuery fixedScroll** Used on [CSS Wizardry](http://csswizardry.com/2012/02/pragmatic-practical-font-sizing-in-css/) This forces position fixed again & it needs a top offset in order to work. This offset is applied on DOMReady & moves the element if it is not at that position - it is the offset used when scrolling. Plugins that I am aware of that do not produce the desired effect: * <https://github.com/dutchcelt/Keep-in-View> * <http://imakewebthings.github.com/jquery-waypoints/sticky-elements/> **I need to be able to have the best of both worlds & unfortunately, I am unable to do that myself, does anyone know of a plugin that I haven't listed or knows a way to modify another?**
Looks like csswizardry is using <http://csswizardry.com/wp-content/themes/new/js/jquery.scroll-lock.js> if you change ``` $(window).bind('load scroll', function(e) { if ($(window).scrollTop() + offsetTop >= lockPosition) { el.css({ position: "absolute", top: lockPosition }); } else { el.css({ position: "fixed", top: offsetTop }); } }); ``` to ``` $(window).bind('load scroll', function(e) { if ($(window).scrollTop() + offsetTop >= maxlockPosition) { el.css({ position: "absolute", bottom: maxlockPosition }); } else if ($(window).scrollTop() + offsetTop >= lockPosition) { el.css({ position: "absolute", top: lockPosition }); } else { el.css({ position: "fixed", top: offsetTop }); } }); ``` and set maxlockPosition to the position of the element you want to block.
162208
I'd like, on "Release" button pressed, to trigger a server-side script of my own. I don't need to use big thing like Jenkins, I just need to run a simple script. I looked into the documentation and found "Listeners" on earlier versions, but there is nothing in the doc for latest version. Any idea?
Can you wrap your remote script in an HTTP interface and trigger it via a webhook? <https://developer.atlassian.com/jiradev/jira-apis/webhooks>
162241
I'm trying to get S3 hook in Apache Airflow using the Connection object. It looks like this: ``` class S3ConnectionHandler: def __init__(): # values are read from configuration class, which loads from env. variables self._s3 = Connection( conn_type="s3", conn_id=config.AWS_CONN_ID, login=config.AWS_ACCESS_KEY_ID, password=config.AWS_SECRET_ACCESS_KEY, extra=json.dumps({"region_name": config.AWS_DEFAULT_REGION}), ) @property def s3(self) -> Connection: return get_live_connection(self.logger, self._s3) @property def s3_hook(self) -> S3Hook: return self.s3.get_hook() ``` I get an error: ``` Broken DAG: [...] Traceback (most recent call last): File "/home/airflow/.local/lib/python3.8/site-packages/airflow/models/connection.py", line 282, in get_hook return hook_class(**{conn_id_param: self.conn_id}) File "/home/airflow/.local/lib/python3.8/site-packages/airflow/providers/amazon/aws/hooks/base_aws.py", line 354, in __init__ raise AirflowException('Either client_type or resource_type must be provided.') airflow.exceptions.AirflowException: Either client_type or resource_type must be provided. ``` Why does this happen? From what I understand the S3Hook calls the constructor from the parent class, AwsHook, and passes the client\_type as "s3" string. How can I fix this? I took this configuration for hook from [here](https://stackoverflow.com/questions/66014947/creating-boto3-s3-client-on-airflow-with-an-s3-connection-and-s3-hook). **EDIT:** I even get the same error when directly creating the S3 hook: ``` @property def s3_hook(self) -> S3Hook: #return self.s3.get_hook() return S3Hook( aws_conn_id=config.AWS_CONN_ID, region_name=self.config.AWS_DEFAULT_REGION, client_type="s3", config={"aws_access_key_id": self.config.AWS_ACCESS_KEY_ID, "aws_secret_access_key": self.config.AWS_SECRET_ACCESS_KEY} ) `` ```
No other answers worked, I couldn't get around this. I ended up using `boto3` library directly, which also gave me more low-level flexibility that Airflow hooks lacked.
162386
OK. I am facing some difficulties in understanding the basics of concurrency. This question is about Deadlock. Please tell me why are both of these threads end in a deadlock. I took this example from [this](http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html) tutorial. And it says, *"When Deadlock runs, it's extremely likely that both threads will block when they attempt to invoke bowBack. Neither block will ever end, because each thread is waiting for the other to exit bow."* What I understand from this is that: First, they would wait because when a thread invokes a synchronized method, it automatically acquires the intrinsic lock of the object to which the synchronized method belongs, and continues to own it until the method returns; and meanwhile no other thread can own it. **1. Now my first question is that the first thread calls zarah.bow(), so the intrinsic lock is associated with zarah. The second thread would call khan.bow() and so that would be a different intrinsic lock (because it is associated with a different object named khan), isn't it?** **And aren't zarah.bow() and khan.bow() different? Because they belong to two different instances?** **2. The second question is from the notion of "both" the threads waiting forever. Both the threads will be blocked forever waiting for each other to exit bow. I don't get this.** ``` package Threads; public class DeadlockModified { static class Friend { private final String name; Friend(String name){ this.name=name; } private String getName(){ return this.name; } private synchronized void bow(Friend bower){ System.out.format("%s: %s"+" bowed to me.%n",bower.getName(),name); bower.bowBack(this); } private synchronized void bowBack(Friend bower){ System.out.format("%s: %s" + " was nice enough to bow back to me.%n",bower.getName() ,name ); } } public static void main(String [] args){ final Friend zarah= new Friend("Zarah"); final Friend khan= new Friend("Khan"); new Thread(new Runnable(){ public void run(){zarah.bow(khan);} }).start(); new Thread(new Runnable() { public void run(){khan.bow(zarah);} }).start(); } } ``` OUTPUT:- ``` Khan: Zarah bowed to me. Zarah: Khan bowed to me. ``` Thank you in advance. **Edit:-** In this tutorial's section of "Synchronized methods" it was written that, *"Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness."* This is the section on Liveness. I see that another object's method bowBack() is being called from bow(). There are some problems as well- Looking at the output of the program, looks like bowBack() has not been executed by both the threads. But there aren't any more details given.
* Thread 1 calls `zarah.bow(khan)`: it acquires the intrinsic lock of the object referenced by `zarah` * Thread 2 calls `khan.bow(zarah)`: it acquires the intrinsic lock of the object referenced by `khan` * Thread 1 tries to call `khan.bowBack()`: it needs the intrinsic lock of khan to be able to do that. But this lock is held by Thread 2. So Thread 1 waits until thread 1 releases the lock of `khan` * Thread 2 tries to call `zarah.bowBack()`: it needs the intrinsic lock of zarahto be able to do that. But this lock is held by Thread 1. So Thread 2 waits until thread 1 releases the lock of `zarah` Both threads are thus waiting for each other, forever. That's a deadlock.
162711
I have this `JSON` output of a `SAP` function: ``` { "Z_HYD_GET_INVOICES": { "import": { "BRANCH": "0142", "DOCNUMS": null, "FINAL_DATE": "Tue Oct 08 00:00:00 BST 2019", "INITIAL_DATE": "Mon Oct 07 00:00:00 BST 2019" }, "export": { "ACCOUNTING": { "row": { "DOCNUM": "0002990790", "PSTDAT": "Mon Oct 07 00:00:00 BST 2019", "BUKRS": "TRV" }, "row": { "DOCNUM": "0003006170", "PSTDAT": "Mon Oct 07 00:00:00 BST 2019", "BUKRS": "TRV" } }, "FISCAL": { "row": { "DOC_DOCNUM": "0002990790", "DOC_NFTYPE": "ZW" }, "row": { "DOC_DOCNUM": "0003006170", "DOC_INVTYPE": "ZW" } }, "MESSAGE_RETURN": null, "STATUS_RETURN": null } } } ``` And I want it to be like this: ``` { "invoices": [ { "accounting": { "accountingDocumentID": "0002990790", "taxEntryDate": "Mon Oct 07 00:00:00 BST 2019", "company": "TRV" }, "fiscal": { "fiscalDocument": { "fiscalDocumentID": "0002990790", "fiscalDocumentCategory": "ZW" } } }, { "accounting": { "accountingDocumentID": "0003006170", "taxEntryDate": "Mon Oct 07 00:00:00 BST 2019", "company": "TRV" }, "fiscal": { "fiscalDocument": { "fiscalDocumentID": "0003006170", "fiscalDocumentCategory": "ZW" } } } ] } ``` I already tried some code with `map` and `mapObject`, but neither worked. `FISCAL.DOC_DOCNUM` is equal to `FISCAL.DOCNUM`, but it could be better to if the transformation fits by position. I mean, join the first element of ACCOUNTING with the first one of FISCAL, and so on... If someone could also provide transform joining by ID, it'll be really nice, for future reference.
Make sure that you close tab that were connected to pgAdmin before start the container.
163055
Is there such a thing as a day (festival or celebration) dedicated to a town or city in Great Britain or the USA? What would such an event be called? For instance, I live in Mtsensk, Russia. Each year on a certain date there's a celebration dedicated to Mtsensk, as there are for other towns and cities in Russia. Each town/city has its own holiday once a year. Can I call it, in my case, Mtsensk Day? Is there such a term as a "town/city day" in general? Is there New York Day? Is there London Day? I've never heard of such celebrations in Great Britain or the USA.
I think in context "Mtsensk Day" would be both clear and natural. It's not a concept I'm aware of in any English-speaking town, but we do have [Yorkshire Day](https://en.wikipedia.org/wiki/Yorkshire_Day) for the county.
163181
I have a vba code thats Auto\_Open. It does some checks then prompts a userform that asks for username and password. I called this userform with `userform_name.show`. My issue is how can I return a `Boolean` to my `Auto_Open` sub from the userform code. I linked the code that verifies if the credentials are correct to the "Login" button on the form. this is the code that produces the Boolean. I need to return it to the Auto\_Open. ``` Private Sub loginbutton() Dim bool As Boolean Dim lrup Dim r As Long Dim pass As String loginbox.Hide 'are fields empty Do While True If unBox.Text = "" Or pwBox.Text = "" Then MsgBox ("You must enter a Username and Password") Else Exit Do End If loginbox.Show Exit Sub Loop 'find pw reated to username (if existant) lrup = UserPass.Range("A1").Offset(UserPass.Rows.Count - 1, 0).End(xlUp).Row If unBox = "b0541476" And pwBox = "theone" Then bool = True Else MsgBox ("Invalid username or password. Please try again.") loginbox.Show Exit Sub End If For r = 2 To lrup If unBox = Cells(r, 1) Then pass = Cells(r, 2).Value Exit For End If Next If pass = "" Then MsgBox ("Invalid username or password. Please try again.") loginbox.Show Exit Sub Else bool = True End If End Sub ```
Remove `Dim bool As Boolean` from the userform code area and declare it in the module as shown below This is how your Code in the module would look like ``` Public bool As Boolean Sub Auto_Open() ' '~~> Rest of the code ' UserForm1.Show If bool = True Then '~~> Do Something Else '~~> Do Something End If ' '~~> Rest of the code ' End Sub ```
163488
Is it possible to run some Python command to not see so much ballast output in the console? I am talking now about running Scrapy where I see tons of not needed texts that disallow to see some meaningful output only. But I see some ballast in there also when running e.g. `pip install`. Not helpful at all. [![a sample of a screenful of output](https://i.stack.imgur.com/S2oMC.jpg)](https://i.stack.imgur.com/S2oMC.jpg)
Ok solved partly thanks to Steve Barnes and partly to my knowledge haha. I had set an environment variable `PYTHONVERBOSE=1` had to remove it and then it works as expected. Good.
163627
I have a Web application which will be deployed to Windows Azure and I'm looking for alternatives to generate Excel spreadsheets. Can I use VSTO to programatically generate an Excel spreadsheet in a Web Role running on Windows Azure?... If yes, how should I deploy the application to Windows Azure? What assemblies should I include?
I tested this and apparently it won't work, VSTO requires Office to be installed.
163753
I have been working on RAD Studio and on that this is performed automatically if the background is fully transparent, but it seems that it isn't as simple to do in Visual Studio. I have read articles and questions of functions GetWindowLong() and SetWindowLong(), but when I try to use them myself, I get error "the name xxx does not exist in the current context". What I tried was: ``` namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); int initialStyle = GetWindowLong(this.Handle, -20); SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20); } } } ``` So is there some file I have to include in order get it to work, or do I have to place the function elsewhere? I'm also curious to know why does it behave so differently in the RAD Studio and Visula Studio.
The methods you are using are not found in the standard .NET libraries, you need to invoke them through `user32.dll`. ``` [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)] private static extern IntPtr GetWindowLong32(HandleRef hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr", CharSet = CharSet.Auto)] private static extern IntPtr GetWindowLongPtr64(HandleRef hWnd, int nIndex); [DllImport("user32.dll", SetLastError = true)] static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] static extern int SetWindowLong(IntPtr hWnd, int nIndex, UInt32 dwNewLong); public static IntPtr GetWindowLong(HandleRef hWnd, int nIndex) { if (IntPtr.Size == 4) return GetWindowLong32(hWnd, nIndex); else return GetWindowLongPtr64(hWnd, nIndex); } ``` Calling them this way will now work correctly: ``` uint initialStyle = GetWindowLong(this.Handle, -20); SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20); ``` Make sure you are using `System.Runtime.InteropServices` **EDIT:** I found and modified some code from another question (I will add link if I can find it, I closed the tab and can't find it), and came up with this: [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern void mouse\_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); private const int MOUSEEVENTF\_LEFTDOWN = 0x02; private const int MOUSEEVENTF\_LEFTUP = 0x04; ``` public enum GWL { ExStyle = -20, HINSTANCE = -6, ID = -12, STYLE = -16, USERDATA = -21, WNDPROC = -4 } public enum WS_EX { Transparent = 0x20, Layered = 0x80000 } public enum LWA { ColorKey = 0x1, Alpha = 0x2 } [DllImport("user32.dll", EntryPoint = "GetWindowLong")] public static extern int GetWindowLong(IntPtr hWnd, GWL nIndex); [DllImport("user32.dll", EntryPoint = "SetWindowLong")] public static extern int SetWindowLong(IntPtr hWnd, GWL nIndex, int dwNewLong); [DllImport("user32.dll", EntryPoint = "SetLayeredWindowAttributes")] public static extern bool SetLayeredWindowAttributes(IntPtr hWnd, int crKey, byte alpha, LWA dwFlags); private void Form1_Click(object sender, EventArgs e) { base.OnShown(e); int originalStyle = GetWindowLong(this.Handle, GWL.ExStyle); int wl = GetWindowLong(this.Handle, GWL.ExStyle); wl = wl | 0x80000 | 0x20; SetWindowLong(this.Handle, GWL.ExStyle, wl); int X = Cursor.Position.X; int Y = Cursor.Position.Y; mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0); System.Threading.Thread.Sleep(50); SetWindowLong(this.Handle, GWL.ExStyle, originalStyle); TopMost = true; } ``` I'm not an expert on how to do this, and I'm not sure if I like that solution, but it works. Make sure you subscribe to the event with: `this.Click += Form1_Click;`
163898
hi I write a php file that contains two methods : **1)** ``` function restart(){ echo('restart') }; ``` **2)** ``` function shutdown(){echo ('shutdown')}; ``` then I include the **index.php** file to the **foo.php** and when I want to call index.php **methods** in an **eventHandler** in foo.php it doesn't work like this: ``` <?php include ('index.php'); ?> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <button id='res'>restart</button> <button id='sht'>shutdown</button> <script> document.getElementById('res').addEventListener('click',function(){ console.log('restarted'); <?php restart(); ?> }) </script> </body> </html> ``` output: **nothing and no errors** --- and when I **remove** the php code **inside the eventHandler** it works! like this: --- ``` <?php include ('index.php'); ?> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <button id='res'>restart</button> <button id='sht'>shutdown</button> <script> document.getElementById('res').addEventListener('click',function(){ console.log('restarted'); }) </script> </body> </html> ``` --- output: **restarted** **WHAT IS THE PROBLEM?**
The PHP code is being run when the file is 'rendered', so the function call to `restart`, even though it is within the JavaScript event listener, is being run on render. If you check the source (after fixing the missing semicolon), it should show `restart` in place of the PHP code. You cannot call PHP code within JavaScript, as JavaScript is client side and PHP is server side.
165052
I'm hosting a Minecraft server that gets updated from time to time. I'd like to make it easy for players to know which mods they will need to play without requiring me to communicate with them outside of Minecraft. This info would be good for new players, as well as regular players who need to be informed that a new mod has been added to the server. Currently, if a player is missing a mod in their client, they will see a generic error message. **Is there a way to inform users *in-game* which mods they will need?** One idea I have is to put a web address on the game screen they see before joining, and then keep that web page updated, but that seems clunky. I know that players can be given the option to download Resource Packs, but as far as I know, this kind of this isn't available for mods.
Players can't join a server if they don't have all the correct mods installed (for Forge at least). I'd put a link in the MOTD, linking to a website like Pastebin, etc., and direct users there. Note that users cannot directly click links in the MOTD, so ideally it should be short.
165180
I'm porting / debugging a device driver (that is used by another kernel module) and facing a dead end because dma\_sync\_single\_for\_device() fails with an kernel oops. I have no clue what that function is supposed to do and googling does not really help, so I probably need to learn more about this stuff in total. The question is, where to start? Oh yeah, in case it is relevant, the code is supposed to run on a PowerPC (and the linux is OpenWRT) EDIT: On-line resources preferrable (books take a few days to be delivered :)
On-line: [Anatomy of the Linux slab allocator](http://www.ibm.com/developerworks/linux/library/l-linux-slab-allocator/) [Understanding the Linux Virtual Memory Manager](http://www.phptr.com/content/images/0131453483/downloads/gorman_book.pdf) [Linux Device Drivers, Third Edition](http://lwn.net/Kernel/LDD3/) [The Linux Kernel Module Programming Guide](http://tldp.org/LDP/lkmpg/2.6/html/) [Writing device drivers in Linux: A brief tutorial](http://www.freesoftwaremagazine.com/node/1238/) Books: [Linux Kernel Development (2nd Edition)](https://rads.stackoverflow.com/amzn/click/com/0672327201) [Essential Linux Device Drivers](https://rads.stackoverflow.com/amzn/click/com/0132396556) ( Only the first 4 - 5 chapters ) Useful Resources: [the Linux Cross Reference](http://lxr.linux.no/+trees) ( Searchable Kernel Source for all Kernels ) [API changes in the 2.6 kernel series](http://lwn.net/Articles/2.6-kernel-api/) --- **[`dma_sync_single_for_device`](http://lxr.linux.no/#linux+v2.6.33/arch/arm/include/asm/dma-mapping.h#L425)** calls `dma_sync_single_range_for_cpu` a little further up in the file and this is the source documentation ( I assume that even though this is for arm the interface and behavior are the same ): ``` /** 380 * dma_sync_single_range_for_cpu 381 * @dev: valid struct device pointer, or NULL for ISA and EISA-like devices 382 * @handle: DMA address of buffer 383 * @offset: offset of region to start sync 384 * @size: size of region to sync 385 * @dir: DMA transfer direction (same as passed to dma_map_single) 386 * 387 * Make physical memory consistent for a single streaming mode DMA 388 * translation after a transfer. 389 * 390 * If you perform a dma_map_single() but wish to interrogate the 391 * buffer using the cpu, yet do not wish to teardown the PCI dma 392 * mapping, you must call this function before doing so. At the 393 * next point you give the PCI dma address back to the card, you 394 * must first the perform a dma_sync_for_device, and then the 395 * device again owns the buffer. 396 */ ```
165575
I have a device ([NXQ1TXH5](https://eu.mouser.com/datasheet/2/302/NXQ1TXH5_SDS-1152191.pdf)) that I want to run at 5V. I am also interfacing this device with a Raspberry Pi4 for i2c communication. This raspberry pi 4 is going to be the master in my i2c network. This runs at 3v3. As the title says, I want to pull up SDA/SCL to 3V3, as required by the datasheet (although the device can take up to 5v, the SDA/SCL only works with 3v3 (maximum 3.6V)). **Datasheet mentioning 3v3** [![enter image description here](https://i.stack.imgur.com/b1ZR7.png)](https://i.stack.imgur.com/b1ZR7.png) I could use a voltage regulator to step down from 5V to 3v3.t would require some filtering capacitor and more complex assembly The second option is a voltage divider. Would a voltage divider do the trick here, given that the 5V source will be constant? (it's cheaper, although it might be less efficient) If yes, what values?
The best option, when possible, especially in the case where there is a single I2C master, is to pull up to the same VCC as the I2C master. In your application that would be the Raspberry Pi VCC, I guess. But it is still an interesting question. The basic answer is, yes, you can use a divider for pullup. The effective pullup voltage is V \* R2 / (R1+R2) where R1 is the upper leg of the divider and R2 is the lower leg of the divider. The effective pullup resistance is R1 in parallel with R2, which is (R1\*R2)/(R1+R2). ![schematic](https://i.stack.imgur.com/VYySX.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fVYySX.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) Note that the divider will consume power even when SDA and SCL are not pulled down. In micropower designs, the divider approach may not be the wisest option for that reason. An option (a bit odd, but potentially workable) would be to use a low quiescent current (Iq) linear regulator (possibly an LDO) to generate the 3.3V for the pullups. I have never seen this or had to resort to it, so I suspect it is not commonly needed.
165587
My sql script is like this : ``` SELECT hotel_code, star FROM hotel WHERE star REGEXP '^[A-Za-z0-9]+$' ``` The result is like this : <http://snag.gy/kQ7t6.jpg> I want the result of select the field that contains numbers and letters. So, the result is like this : ``` 3EST 2EST ``` Any solution to solve my problem Thank you
I guess you're trying to get Must alphanumeric values. It can be achieved by following. ``` ^([0-9]+[A-Za-z]+[0-9]*)|([A-Za-z]+[0-9]+[A-Za-z]*)$ ```
165642
i'm using Netbeans 6.8 and build simple Maven web application project. create Entity and main file for persist Entity [also create persist unit] and use EclipsLink. but when i run main file get this error : ``` Exception in thread "main" java.lang.NoClassDefFoundError: javax/persistence/Persistence at Main.main(Main.java:34) Caused by: java.lang.ClassNotFoundException: javax.persistence.Persistence at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) ... 1 more ``` in netbeans projects window and in my project libraries folder only add this package : javaee-web-api-6.0.jar [provided] please help me for solve this Error thanks
Click [Here](http://repo1.maven.org/maven2/org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.1.Final/hibernate-jpa-2.0-api-1.0.1.Final.jar) to download `hibernate-jpa-2.0-api-1.0.1.Final.jar` and put it into the project library, your application will work fine. Good luck:)
165885
i want by group by 'Facturacion' and Motor Facturación Drools. I have this sql: ``` SELECT c.cname AS componente, w.timeworked / 3600 AS horas, Sum(w.timeworked / 3600) OVER () AS sum_tipo, Sum(w.timeworked / 3600) OVER ( partition BY c.cname) AS sum_by_component FROM jira.jiraissue j, jira.worklog w, jira.project p, jira.issuetype t, jira.component c, jira.nodeassociation na WHERE w.issueid = j.id AND J.project = P.id AND na.source_node_id = j.id AND na.sink_node_entity = 'Component' AND na.source_node_entity = 'Issue' AND na.sink_node_id = c.id AND t.id = j.issuetype AND p.pname = 'Area Económica' AND t.pname = 'Bug' AND w.startdate BETWEEN To_date('01/10/2018', 'dd/mm/yyyy') AND To_date('09/10/2018', 'dd/mm/yyyy') ``` the result is this: [![enter image description here](https://i.stack.imgur.com/nCoV2.png)](https://i.stack.imgur.com/nCoV2.png) if i put a select distinct, it grouped ok but some lines doesn't catch. the result is this:[![enter image description here](https://i.stack.imgur.com/zcE0x.png)](https://i.stack.imgur.com/zcE0x.png) i want quit the column HORAS and only watch 2 rows
First check that your cryptogen tool (the one you have setted in your path) is the one that you are using in your example, is very common to be pointing to an old version tool. I highly recommend if you are going to restart everything to clean all your containers running ``` ./byfn.sh -m down docker stop $(docker ps -a -q) docker rm $(docker ps -a -q) ``` After that re run the start command `./byfn.sh -c mychannel -m up -s couchdb -a` If you are still having problems, maybe you can start with an easier example, I figured out how to setup a Fabric (v1.2) y two differents hosts using the basic network example. [Setup hyperledger fabric in multiple physical machines](https://medium.com/1950labs/setup-hyperledger-fabric-in-multiple-physical-machines-d8f3710ed9b4) Hope that this help!
165949
Trying to generate a random number and use it for variable value in Windows batch script file. Maybe I am missing something very basic, but something is not working here for me. Created a batch file named `random_test.bat` with the following content. ``` SET rnumber=%random% echo %random% pause ``` Running the file consecutively three times produces the following set of outputs: One ``` C:\Users\user\Desktop>SET rnumber=28955 C:\Users\user\Desktop>echo 20160 20160 C:\Users\user\Desktop>pause Press any key to continue . . . ``` Two ``` C:\Users\user\Desktop>SET rnumber=29072 C:\Users\user\Desktop>echo 13887 13887 C:\Users\user\Desktop>pause Press any key to continue . . . ``` Three ``` C:\Users\user\Desktop>SET rnumber=29183 C:\Users\user\Desktop>echo 18885 18885 C:\Users\user\Desktop>pause Press any key to continue . . . ``` As you can see the command `echo %random%` keeps producing relatively random numbers between 0 and 32,767 as expected. At the same time using `%random%` to set a value for variable `rnumber` does not. It produces a not-so random number (possibly too between 0 and 32,767) but it is not random. If I were to guess right now it seems to be slowly growing in the 0 to 32,767 direction. To clarify the script keeps producing a random number with line 2 on each execution (20160, 13887, 18885...), but line 1 seems to produce a number that keeps increasing with each execution of the batch file (28955, 29072, 29183, and so on in my multiple tests). I already tried it on two different computers, Windows 7 x64 and Windows 2012 R2 respectively, running this 3 line script multiple times in row. Next thing to try will be on a computer from a completely different network, I'm wondering if this has anything to do with domain policies, network, software.. What is going on here? UPDATE: ======= When running the commands in sequence from the same CMD window it works as expected, but it does not when executing the same batch file multiple times. * The line in the script `echo %random%` works as expected. * The line `SET rnumber=%random%` does not. (When executing the same script multiple times)
To provide a summary of everything that was learned from the comment discussion, external resources and testing regarding my original question. Random number generator in batch script uses the following algorithm to seed the initial random number value when a new CMD window is opened. (from here - <https://devblogs.microsoft.com/oldnewthing/?p=13673>) ``` srand((unsigned)time(NULL)); ``` As a result when two(or more) CMD windows are started within the same second the initial returns of the %random% are the same. Subsequent returns of %random% within two CMD windows with the same seed and run time (to a second) are also the same. Moreover if CMD windows are consequently started with certain delays from each other the first return of the %random% pseudo-variable in each new CMD window will be far from random and will be slowly increasing (0 to 32767 range). In my testing this initial seed number grows by either 3 or 4 every one second for each new window. To learn more about this and to find workarounds look here: * <https://devblogs.microsoft.com/oldnewthing/?p=13673> * <https://ss64.com/nt/syntax-random.html> * [Why does rand() yield the same sequence of numbers on every run?](https://stackoverflow.com/questions/9459035/why-does-rand-yield-the-same-sequence-of-numbers-on-every-run) * [Random generator in the batch](https://stackoverflow.com/questions/19694021/random-generator-in-the-batch) * [Batch random function giving same first output](https://stackoverflow.com/questions/27880234/batch-random-function-giving-same-first-output) * [How do I get truly random numbers in batch?](https://stackoverflow.com/questions/31250864/how-do-i-get-truly-random-numbers-in-batch) Also look at PowerShell workaround provided by @lit.
166204
I've a strange issue. Let me explain in details below step by step: 1. I've a vendor developed REST WS (Made using WCF) for synchronizing data with MS CRM. 2. I've developed a windows service, which fetches batches of data to be synchronized from a database and then pass it to this web services using Post method as JSON objects. The windows service is deployed on one of the node. 3. The issue I am facing have never occurred in Dev, QA, UAT or staging environment. It's unique to Production environment only. 4. In production the application works for sometime and then starts throwing 400 Bad request error. Then until we restarts the site or reset the App Pool Identity the IIS keeps throwing 400 Bad request errors. When we restarts the site or App Pool then the same requests which were getting failed starts getting successful responses. It works for sometime like this and than again 400 starts happening. 5. The environment where web services are hosted is a Win Server 2012, 2 node load balanced environment. WS is deployed on port 8080 on boht nodes and configured to run under .Net 4.0. 6. I received the following error in my Windows Service log which is the client for these WS. > > System.Net.WebException: The remote server returned an error: (400) > Bad Request. > at SspToCrmSynchronizationService.Helpers.CrmWrapperWsHelper.CallService(String > data, String url, String method, String userName, String password, > String contentType) in CrmWrapperWsHelper.cs:line 79 > at SspToCrmSynchronizationService.Helpers.CrmWrapperWsHelper.CallDocumentCreateService(String > data) in CrmWrapperWsHelper.cs:line 20 > at SspToCrmSynchronizationService.Process.CommonOperations.GenerateJsonAndInvokeDocCreateWS(Int64 > appRefNo, Application app) in CommonOperations.cs:line 52 > at SspToCrmSynchronizationService.Process.SequentialProcess.Process(List`1 > appList, DatabaseHelper dbHelperForChildTask, CancellationToken ct) in > SequentialProcess.cs:line 88 > > > 6. First we've checked the IIS Logs and found that IIS is returning the 400 error in just few 100 MS. We suspect that it's not reaching to WS application since application is not logging any thing at all, despite that Logging the request is the first thing vendor is doing in the WS code. 7. Secondly we used Fiddler to capture the request and response and get the following: > > > ``` > HTTP/1.1 400 Bad Request > Cache-Control: private > Content-Length: 1647 > Content-Type: text/html > Server: Microsoft-IIS/8.5 > X-ASpNet-Version: 4.0.30319 > X-Powered-By: ASP.Net > Date: Tue, 17 Oct 2017 07:14:26 GMT > > ``` > > [![Fiddler log](https://i.stack.imgur.com/1gGrp.png)](https://i.stack.imgur.com/1gGrp.png) 8. Than we checked the IIS Httperr.log. In the log we found the following for some of the request and not for every failed requests. It seems nothing is there. > > 2017-07-07 03:32:45 10.102.2.52 63726 10.102.2.52 8080 - - - - - Timer\_ConnectionIdle - > > 2017-07-08 22:46:55 10.102.2.52 50916 10.102.2.52 8080 - - - - - Timer\_ConnectionIdle - > 2017-07-08 22:55:09 10.102.2.52 51004 10.102.2.52 8080 - - - - - Timer\_ConnectionIdle - > > > 9. Than we configured the Failed Traced Log in IIS for 400 and got one warning in the trace log when this 400 Error is thrown. I've erased some of the data from the image due to NDA and security reasons. [![IIS Failed Traced Log for 400 Bad Request](https://i.stack.imgur.com/VHHxs.png)](https://i.stack.imgur.com/VHHxs.png) Basically the Warning details are as follows: > > > ``` > 124. MODULE_SET_RESPONSE_ERROR_STATUS > ModuleName="ManagedPipelineHandler", > Notification="EXECUTE_REQUEST_HANDLER", > HttpStatus="400", > HttpReason="Bad Request", > HttpSubStatus="0", > ErrorCode="The operation completed successfully. (0x0)", > ConfigExceptionInfo="" > > ``` > > 10. After that I've compared one error case and one success case. Below is the image. What I noticed is that in case of failure General\_Read\_Entity\_Start and General\_Read\_Entity\_End didn't occurred at all. [![Error and Success Cases](https://i.stack.imgur.com/O382L.png)](https://i.stack.imgur.com/O382L.png) The maximum I can understand is that somehow IIS is not able to parse JSON String to some Entity and the AppPool gets crashes then starts throwing 400 errors until a AppPool or IIS Reset is not done. I've no idea what is causing this (Root Cause) and how to resolve this and why it's working initially and not working after some time. Any help would be highly appreciated. **[Edits]** 1. Resource consumption on the server is less then 10%. 2. For successful cases the average response time of WS are 5 secs, while for Error cases it returns within 100 Milli Seconds. 3. We did the Stress test for the service in test for about 100+ request and all went ok.
We need to understand how it works, there were quite a few conditions: 1. We were passing a datetime value in JSON. At the WS end the DateTime value was throwing some parsing errors when The WS container in our case (IIS and WCF) trying to pass the DateTime field to the application was failing in doing the conversion. I believe this could be due to locale. We fixed it by changing datetime to string in the WS accepted JSON. 2. The second issue was that our vendor used WCF as a technology to create RestAPI. One behavior of WCF is that if a request from a client causes a fatal exception to occour in the WS container the IIS will register this client on a block list and will not forward the request from the same client to the application until an IIS restart is done. The IIS will keep returning us Bad Request status message.
167620
I am new to python and using multiprocessing, I am starting one process and calling one shell script through this process. After terminating this process shell script keeps running in the background, how do I kill it, please help. python script(test.py) ====================== ``` #!/usr/bin/python import time import os import sys import multiprocessing # test process def test_py_process(): os.system("./test.sh") return p=multiprocessing.Process(target=test_py_process) p.start() print 'STARTED:', p, p.is_alive() time.sleep(10) p.terminate() print 'TERMINATED:', p, p.is_alive() ``` shell script (test.sh) ====================== ``` #!/bin/bash for i in {1..100} do sleep 1 echo "Welcome $i times" done ```
The reason is that the child process that is spawned by the os.system call spawns a child process itself. As explained in the [multiprocessing docs](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.terminate) descendant processes of the process will not be terminated – they will simply become orphaned. So. `p.terminate()` kills the process you created, but the OS process (`/bin/bash ./test.sh`) simply gets assigned to the system's scheduler process and continues executing. You could use [subprocess.Popen](https://docs.python.org/2/library/subprocess.html#popen-constructor) instead: ``` import time from subprocess import Popen if __name__ == '__main__': p = Popen("./test.sh") print 'STARTED:', p, p.poll() time.sleep(10) p.kill() print 'TERMINATED:', p, p.poll() ``` Edit: @Florian Brucker beat me to it. He deserves the credit for answering the question first. Still keeping this answer for the alternate approach using subprocess, which is recommended over os.system() in the [documentation for os.system()](https://docs.python.org/2/library/os.html#os.system) itself.
168756
I am very new to Java. I have written a small program to understand Encapsulation and access method. The code is : ``` package practise; public class EncapTest { private String name; String surname; public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` --- ``` package practise; public class RunEncap { public static void main(String[] args) { EncapTest encapObj = new EncapTest(); encapObj.setName("Prabh"); encapObj.surname = "Rana"; System.out.println("Name :" + encapObj.getName()); System.out.println("Surname :" + encapObj.surname); } } ``` --- Now if i create another package "practise2" and use import and try to create object of "EncapTest", I am able to access the variable name, but when i am trying to access surname, it shows error that the field surname is not visible.. ``` package practise2; import practise.EncapTest; public class Runencap2 { public static void main(String[] args) { EncapTest encapObj = new EncapTest(); encapObj.setName("Prabh"); encapObj.surname = "Rana"; // <<<<getting error here System.out.println("Name :" + encapObj.getName()); System.out.println("Surname :" + encapObj.surname); } } ```
Your `surname` field has default (package-private) access level, it means that this field visible only for classes, which declared in same package. ``` String surname; // access level implicitly sets to package-private ``` There are four access levels in Java: * public * protected * package-private (no explicit modifier) * private If your class member has no explicit modifier - it automatically sets to package-private. It's fully [described](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) in official tutorial.
168949
What is the problem with my for-loop? It is inside a helper function but the error "Member reference base type 'int [13]' is not a structure or union" is happening across my code. The 'int [13] changes to int[10] when I am using a 10 integer array, so I assume it is a problem there. Here are two examples: ``` int newisbn13[13]; newisbn13[0] = 9; newisbn13[1] = 7; newisbn13[2] = 8; for (int p = 3; p < newisbn13.length() - 1; p++) { newisbn13[p] = isbn10[p-3]; } ``` ERROR: Member reference base type 'int [13]' is not a structure or union Also: ``` int calc_check_digit_13(int input[], int size) { int sum = 0; for (int i = 0; i < input.length(); i++) { int tempnum = 0; if (i % 2 == 0) { tempnum = input[i]; } else if (i % 2 == 1) { tempnum = input[i] * 3; } sum = tempnum + sum; } etc. etc. etc. } ``` ERROR: Member reference base type 'int \*' is not a structure or union What is causing this error throughout my code? Thank you for your help.
You can simple add a click listener to the button: ``` <template> <div id="app"> <button @click="redirectToHome()">Go Back</button> <button @click="redirectToFoo()">Click ME</button> </div> </template> ``` and implement them inside methods ``` <script> export default { name: "#app", methods: { redirectToHome() { this.$router.push({ path: '/' }); }, redirectToFoo() { this.$router.push({ path: '/foo' }); } } }; </script> ``` For further details on programmatic navigation: <https://router.vuejs.org/guide/essentials/navigation.html#programmatic-navigation>
169014
Consider the following code: ``` Public Class Animal Public Overridable Function Speak() As String Return "Hello" End Function End Class Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function End Class Dim dog As New Dog Dim animal As Animal animal = CType(dog, Animal) // Want "Hello", getting "Ruff" animal.Speak() ``` How can I convert/ctype the instance of Dog to Animal and have Animal.Speak get called?
You don't; the subclass's method overrides the superclass's method, by definition of inheritance. If you want the overridden method to be available, expose it in the subclass, e.g. ``` Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function Public Function SpeakAsAnimal() As String Return MyBase.Speak() End Function End Class ```
169111
The problem: ============ I have several Rmarkdown documents representing different sections of my thesis (e.g. chapter 1 results, chapter 2 results), and I would like to combine the knitted latex versions of these documents with other TeX files into a master TeX 'thesis' document. The problem is, that when knitting to PDF and keeping the TeX file to include in the master TeX document, Rstudio auto-generates a bunch of preamble that ends up clashing with my preamble in the master.TeX document. A less than ideal, workaround: ============================== I have been working around this issue by deleting this preamble by hand before including the knitted output into the `master.tex` file. So far my current workflow is as follows: * set the output to pdf\_document in the YAML header, with the keep\_tex option set to true. * knitPDF using the Rstudio button * delete the preamble at the beginning of the knitted TeX files by hand. * include the files into my master.tex file using \include{} The question: ============= I would like to convert Rmd to LaTeX, without having to delete the preamble manually before including the knitted TeX files into a master TeX file. How do I do this? ### Sweave is not an option: I'm sure I could achieve this by working with Sweave, however I like the flexibility of output formats that Rmarkdown offers: I can knit to html and view in my browser as I'm writing, to quickly view the progress of my work and ensure that there are no bugs, and I can also choose to knit to word to share with my supervisor who works only in word. Then, when I'm ready to compile everything into my master LaTeX document for printing, I can select knit to PDF in Rstudio to obtain the latex output.
Here is a simpler solution using the LaTeX package `docmute`. Your main Rmarkdown document, (e.g., `main.Rmd`) should load the `docmute` package and include your other files (e.g., `part1.Rmd` and `part.Rmd`), once knitted and located in the same directory, with `\input` or `\include`like this: ``` --- title: "Main" output: pdf_document header-includes: - \usepackage{docmute} --- # Part 1 \input{part1.tex} # Part 2 \input{part1.tex} ``` Then your other files just need to have a `keep_tex` argument in the YAML front matter. Like this: ``` --- title: "Part 1" output: pdf_document: keep_tex: true --- Something ``` and this: ``` --- title: "Part 2" output: pdf_document: keep_tex: true --- Something else ``` Then all you need to do is knit `part*.Rmd`'s before `main.Rmd` and all the content will appear in `main.tex` and `main.pdf`. The `docmute` package strips the preamble from the input `.tex` files so you will need to make sure anything you need before `\begin{docunent}` in the input files is also in `main.Rmd`.
169607
I'm trying to save file directories so that when my app opens again the directories are remembered. I want to save the directories to a file called 'directories.txt' which is in my source code package. I did learn how to read from it by using: ``` getClass().getResourcesAsStream("/getresources/directories.txt") ``` So my question is how do I write to that file? Is this possible. Thanks, nt
It's not possible. The file you are getting is a resource in the class path of your application, like a .class file. And like a class file it cannot be rewriten into its original place (being either a jar, zip or binaries .class folder). It's read only and cannot be used for persistence. To persist any data you are going to have to use an external resource. You can write to an actual file in any path in the file system. That file is going to be external to your class path files.
169714
I am writing a bash script that reads a JSON string then loop based on the JSON values to execute a CLI command. ``` #!/usr/bin/env bash jq --version > /dev/null 2>&1 || { echo >&2 "jq is required but it's not installed. Aborting."; exit 1; } read -r -d '' USER_ACTIONS << EOM { "user1": [ "action1" ], "user2": [ "action2", "action3" ] } EOM USERS= #TODO for user in USERS; do ACTIONS= #TODO for action in ACTIONS; do echo "Executing ${command} ${user}-${action}" done done ``` If jq is present in the server, how do I populate the USERS and ACTIONS variable?
Depending on what command you want to execute, if it can be performed from within jq, it's easier to also move the loop inside. There are several ways to accomplish that. Here are some examples, all yielding the same output: ```bash jq -r 'to_entries[] | "Executing command \(.key)-\(.value[])"' <<< "$USER_ACTIONS" ``` ```bash jq -r 'keys[] as $user | "Executing command \($user)-\(.[$user][])"' <<< "$USER_ACTIONS" ``` ```bash jq -r --stream '"Executing command \(.[0][0])-\(.[1]? // empty)"' <<< "$USER_ACTIONS" ``` Output: ``` Executing command user1-action1 Executing command user2-action2 Executing command user2-action3 ```
169844
I am trying to determine which files will be touched based on their modified date. My directory is a top a list of perhaps several levels of subdirectories. From a terminal window I run this command: ``` find Program.8.koeb/ -mtime -10 ``` Which correctly produces a list of files modified within the past 10 days. However if I want to query this list to make sure that the files I want to touch using the `find` command, I would run this command: ``` find Program.8.koebe/ -mtime -10 -exec ls -gotrhR {} \; ``` Which produces a long list of all the files within directories of my current working directory, including subdirectories, along with the named directory `find` is assigned to look. So, `-exec ls -gotrhR {} \;` seems to be producing the same output as: ``` find . -mtime -10 -exec ls -gotrhR {} \; ``` Which is not my intention.
Just add '-type f' cause -exec ls -l {} will include those are directories and list them, too.
170020
I am writing a batch file that executes a Powershell script that at one point loops items with UNC paths as attributes and uses `Get-ChildItem` on those paths. In a minimal version, this is what is happening in my scripts: **Master.bat** ``` powershell -ExecutionPolicy ByPass -File "Slave.ps1" ``` **Slave.ps1** ``` $foo = @{Name = "Foo"} $foo.Path = "\\remote-server\foothing" $bar = @{Name = "Bar"} $bar.Path = "\\remote-server\barthing" @( $foo, $bar ) | ForEach-Object { $item = Get-ChildItem $_.Path # Do things with item } ``` The problem I'm running into is that when I run **Master.bat**, it fails at `Get-ChildItem` with an error along the lines of ``` get-childitem : Cannot find path '\\remote-server\foothing' because it does not exist. ``` However, it seems to work perfectly fine if I run the **Slave.ps1** file directly using Powershell. Why might this be happening only when the **Master.bat** file is run? **Things I have tried** * Prepending the UNC paths with `FileSystem::` with providers <http://powershell.org/wp/2014/02/20/powershell-gotcha-unc-paths-and-providers/> * Making sure there are no strange characters in the actual paths * Using the `-literalPath` parameter instead of the plain `-path` parameter for `Get-ChildItem` * Running `Get-ChildItem \\remote-server\foothing` in PowerShell and succeeding to verify connection to the remote server
I have found this issue when running scripts referring to UNC paths - but the error only occurs when the root of the script is set to a non file system location. e.g. PS SQLSEVER\ So the following fails with the same error: ``` cd env: $foo = @{Name = "Foo"} $foo.Path = "\\remote-server\foothing" $bar = @{Name = "Bar"} $bar.Path = "\\remote-server\barthing" @( $foo, $bar ) | ForEach-Object { $item = Get-ChildItem $_.Path # Do things with item Write-Host $item } ``` So my resolution was to ensure that the PS prompt was returned to a file system location before executing this code. e.g. ``` cd env: $foo = @{Name = "Foo"} $foo.Path = "\\remote-server\foothing" $bar = @{Name = "Bar"} $bar.Path = "\\remote-server\barthing" cd c: #THIS IS THE CRITICAL LINE @( $foo, $bar ) | ForEach-Object { $item = Get-ChildItem $_.Path # Do things with item Write-Host $item } ``` I hope this helps - I would be very happy with the bounty as this is my first answer on stack overflow. P.S. I forgot to add - the PS command prompt root may be set by auto loaded modules in the configuration of your machine. I would check with Get-Location to see if you are actually executng from a non FileSystem location.
170208
i need to disable or remove the Jsessionid in the URL how to do that, whether it causes any side effect during ajax request.I am using struts 1.2 version.
Servlet 3.0 allows you to specify the means of maintaining a session. I guess you are not using it, so see [this question](https://stackoverflow.com/questions/962729/is-it-possible-to-disable-jsessionid-in-tomcat-servlet). I favour the 2nd answer more than the rewrite.
170374
DX12 introduces a new feature of pipeline named 'Bundle'. It seems that can optimize the command list, and send it to final pipeline. Vulkan invent some different pipeline: The graphic pipeline and the compute pipeline. The graphic pipeline seems just the same with the original, the compute pipeline is used as an accessor of image memory. My CG knowledge is pretty basic, and can not confirm that cognition is correct. Would someone kindly provide some explanations for it - The main difference of pipelines between them ? References: * <https://msdn.microsoft.com/zh-cn/library/mt617309> * <https://www.khronos.org/registry/vulkan/specs/1.0/xhtml/vkspec.html#pipelines>
D3D12 has 4 separate kinds of command lists: direct, bundle, compute, and copy. Vulkan has similar concepts, but they happen in a different way. Command buffers are allocated from command pools. And command pools are directly associated with a queue family. And command buffers allocated from a pool can only be submitted to the queue family for which the pool was built. Queue families specify the kinds of operations that the queue can take: graphics, compute, or memory copying operations. D3D12's command queues have a similar concept, but D3D12's command list API has you to specify the list type. Vulkan's gets this information from the queue family the pool is meant for. The D3D12 "bundle" command list type seems similar on the surface to Vulkan secondary command buffers. However, they are quite different. The principle difference is this: bundles inherit *all state* from their executing direct command list, except for the bound PSO itself. This includes resource descriptor bindings. Vulkan secondary command buffers inherit *no state* from their primary command buffer execution environment, except for secondary CBs that execute in a subpass of a renderpass instance (and queries). And those *only* inherit the current subpass state (and queries). This means you do different things with them, compared to D3D bundles. Bundles are sometimes used to modify descriptor tables and render stuff, on the assumption that the direct command list they're executed within will have set those tables up. So bundles are kind of like light-weight OpenGL display lists, only without all of the bad things those do. So the intent with bundles is that you build them once and keep them around. They're supposed to be small things. Vulkan secondary CBs are essential for threaded building of commands intended for a single render pass instance. This is because a render pass instance can only be created within a primary CB, so for optimal use of threads, there needs to be a way to create commands meant to execute in the same subpass in different threads. That's one of the main use-cases of secondary CBs. So the intent is that you'll probably build secondary CBs each frame (though you can reuse them if you want). So in the end, bundles and secondary CBs are intended to solve separate problems. Bundles are generally dependent on the executing environment, while secondary CBs are more stand-alone. At the same time, Vulkan secondary CBs can do something bundles cannot: they can execute on compute/copy-only queues. Since Vulkan makes a distinction between the primary/secondary level of the command buffer and the queues where that CB can be sent, it is possible in Vulkan to have secondary command buffers that execute on compute or copy-only queues. Direct3D 12 can't do that with bundles. The [`ExecuteBundle` function](https://msdn.microsoft.com/en-us/library/windows/desktop/dn903882(v=vs.85).aspx) can only be called on a direct command list. So a copy-only command list cannot execute bundles. Granted, because Vulkan doesn't inherit anything between secondary CBs except for subpass state, and compute/copy operations don't use render passes, there isn't much to be gained from putting such commands in a secondary CB rather than a primary one. --- D3D12 has the same separation between [compute pipelines](https://msdn.microsoft.com/en-us/library/windows/desktop/dn788663(v=vs.85).aspx) and [graphics pipelines](https://msdn.microsoft.com/en-us/library/windows/desktop/dn770348(v=vs.85).aspx) that Vulkan does. However, when issuing commands, D3D12 has only one pipeline binding point, to which you can bind any kind of pipeline. By contrast, Vulkan has separate binding points for compute and graphics pipelines. Of course, Vulkan doesn't have different descriptor binding points for them, so the two pipelines can interfere with one another. But if you design their resource usage carefully, it is possible to invoke a dispatch operation without disturbing the needs of the graphics pipeline. So overall, there's no real difference in pipeline architecture here.
171102
I have a problem with renderUI and I couldn't find a solution anywhere. Probably I'm asking the wrong question to google and more than a shiny problem is a basic R problem. I have a function in R which depending on the input will return a table or a text. So I created both the options in my server.R in this way: ``` output$table <- renderTable {( x <- function (y) print(x) )} output$text <- renderText {( x <- function (y) print(x) )} ``` If I put both the outputs in renderUI one will always give me an error. In case of textOutput if the output is a table: ``` Error: argument 1 (type 'list') cannot be handled by 'cat' ``` and ``` Error:no applicable method for 'xtable' applied to an object of class "character" ``` if it is viceversa. My question is there a way to catch this error and use an if statement within renderUI to display only one of the two? I'm here to give you more details if you need. **[EDIT]** server.R ``` library(shiny) library(drsmooth) shinyServer(function(input, output,session) { -- upload dataframe and input management goes here -- output$nlbcd <- renderTable({ nlbcd<-nlbcd(dosecolumn="Dose", targetcolumn=response(),cutoffdose=cutoff(),data=data1()) print(nlbcd) }) output$nlbcdText <- renderText({ nlbcd<-nlbcd(dosecolumn="Dose", targetcolumn=response(),cutoffdose=cutoff(),data=data1()) print(nlbcd) }) output$tb <- renderUI({ tableOutput("nlbcd"), textOutput("nlbcdText") }) }) ```
You have some issues here, the function will return different classes, including errors and warnings with interpretations. Here is a standalone example of what can happen with this function, you are encouraged to include the TryCatch in your code: **ui.R** ``` shinyUI( pageWithSidebar( headerPanel("drsmooth"), sidebarPanel( numericInput("num", label = h3("Choose 'cutoffdose'"), value = 0) ), mainPanel( verbatimTextOutput('current') ) ) ) ``` **server.R** ``` library(drsmooth) shinyServer(function(input, output, session) { output$current <- renderPrint({ dose <- input$num tryCatch(isolate(nlbcd("dose", "MF_Log", cutoffdose=dose, data=DRdata)), error=function(e) { cat(isolate(conditionMessage(e))) } ) }) }) ``` Sample outputs: ![With <code>cuttoffdose</code>= 0](https://i.stack.imgur.com/L2P0Y.png) ![With <code>cutoffdose</code>= 1](https://i.stack.imgur.com/fXut1.png) ![With <code>cutoffdose</code>= 1.5](https://i.stack.imgur.com/h2PPS.png)
172043
so i was working on a project you should know i have just started and was trying to make a login/logout of emails and some stuff and i saw this can someone help me find out what does this def serialize do here. ``` class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"), "read": self.read, "archived": self.archived } ``` **i dont know what this serialize do in this class can someone help me out**
This `serialize` method is just translating the model into other format for interoperability. In your case it's translating `Email` object into `dictionary` format. This method is not built-in it's custom method, you can use custom method based on your use case. Moreover, the name `serialize` is not also fixed, like `self` you can use any name as you like. `django` has also it's own `serializer` check here to know about `django serializers` <https://docs.djangoproject.com/en/3.0/topics/serialization/>
172971
I have two VMs (in VirtualBox), both of them are Ubuntu Server 18.10 (cosmic): * the first one, `Server`, has two NICs: one in NAT, the other one in intnet * the second machine, `Client`, has only one NIC, in intnet, to communicate with `Server` Now I would like to make `Server` a gateway, and so I've enabled IP forwarding (by modifying `sysctl.conf`, restarted it and so on. When I check `sudo ufw status` (on `Server`), it says `inactive`. OK. But I cannot ping any external IP address on `Client` until I set iptables on `Server` with > > `iptables -t nat -A POSTROUTING -o enp0s3 -j MASQUERADE` > > > As soon as I press Enter, ping command typed in `Client` does work. But why, since UFW is inactive??
UFW being inactive has nothing to do with it. In `iptables` parlance, you *must* have a `MASQUERADE` rule set in the NAT table for traffic to work being forwarded outbound regardless. Otherwise, the system won't know what to do with the packets. This remains the case even if you directly use `iptables` to manipulate the `*filter` rules (to set `INPUT`, `OUTPUT`, etc. access control lists and such, or even to just `ALLOW` all traffic on those policysets) - NAT always is in play and you have to add the NAT rule to make forwarded traffic masquerade out to the Internet as the server's primary IP. Therefore, you must add the rule whether using UFW or not in order to get the system to understand how to translate the packet and route it via the server to the Internet, and thus how to automatically handle the reverse routing as well. --- [This Github GIST](https://gist.github.com/kimus/9315140#nat) which I found has a pretty good explanation of what to do for this for UFW: > > The final step is to add NAT to ufw’s configuration. Add the following > to /etc/ufw/before.rules just before the filter rules. > > > > ``` > # NAT table rules > *nat > :POSTROUTING ACCEPT [0:0] > > # Forward traffic through eth0 - Change to match you out-interface > -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE > > # don't delete the 'COMMIT' line or these nat table rules won't > # be processed > COMMIT > > ``` > >
173000
I would like to move #wctopdropcont elements slightly to the left. I have tried applying values for margin and padding however it simply doesn't work. I would ideally want the text to be 20px to the left. The URL to my blog is as follows: <http://www.blankesque.com> and below I have included the entire hovering navigation bar's html and css coding. ``` #wctopdropcont{ /* width of the main bar categories */ width:100%; height:45px; display:block; padding: 5.5px 0 0 0; z-index:100; top:0px; left: 0px; position:fixed; background:#f8f8f8; } #wctopdropnav{ /* social */ float: right; width:97%; height:7px; display:block; padding:0px; } #wctopdropnav ul{ float:right; margin:0; padding:0; } #wctopdropnav li{ float:left; list-style:none; line-height:13px; margin-left: 4px; padding: 10px 6.5px 6.5px 6.5px;/* height of the clicked bar */ background:#f8f8f8; } #wctopdropnav li a, #wctopdropnav li a:link{ color:#000000; float: right; display:block; margin-left: 4px; text-transform: uppercase; font-size: 9.5px!important; font-family: karla, arial!important; padding: 5px; text-decoration:none; font-weight: normal!important; letter-spacing : 0.09em; } #wctopdropnav li a:hover, #wctopdropnav li a:active, #wctopdropnav .current_page_item a { color:black; font-weight: normal; padding: 5px; background: #f8f8f8; /* Old browsers */ background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; filter:black; } #wctopdropnav li li a, #wctopdropnav li li a:link, #wctopdropnav li li a:visited{ font-size: 9.5px; background:#f8f8f8; color: #000000; width: 90px; margin: 0px; padding: 0; line-height: 15px; position: relative; } #wctopdropnav li li a:hover, #wctopdropnav li li a:active { color: black; background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; background: #f8f8f8; filter: #f8f8f8; } #wctopdropnav li ul{ z-index:9999; position:absolute; left:-999em; height:auto; width:170px; margin:22px 0 0 0; padding: 8px 0 0 0; } #wctopdropnav li:hover ul, #wctopdropnav li li:hover ul, #wctopdropnav li li li:hover ul, #wctopdropnav li.sfhover ul, #topwctopdropnav li li.sfhover ul, #topwctopdropnav li li li.sfhover ul{ left:auto } #wctopdropnav li:hover, #wctopdropnav li.sfhover{ position:static } </style> <div id='wctopdropcont'> <div id='wctopdropnav'> <ul> <li><a href='http://www.blankesque.com/p/about-blankesque-blog.html'>About</a></li> <li><a href='#'>Categories</a> <ul> <li><a href='http://www.blankesque.com/search/label/Beauty'>Beauty</a></li> <li><a href='http://www.blankesque.com/search/label/Blogging'>Blogging</a></li> <li><a href='http://www.blankesque.com/search/label/Fashion'>Fashion</a></li> <li><a href='http://www.blankesque.com/search/label/Fragrance'>Fragrance</a></li> <li><a href='http://www.blankesque.com/search/label/Haul'>Haul</a></li> <li><a href='http://www.blankesque.com/search/label/Lifestyle'>Lifestyle</a></li> <li><a href='http://www.blankesque.com/search/label/Skin &amp; Hair'>Skin &amp; Hair</a></li> </ul> </li> <li><a href='http://www.blankesque.com/p/contact-blankesque-for-press.html'>Contact</a></li> <li><a href='http://www.blankesque.com/p/discalimer-policy_13.html'>Policies</a></li> </ul> </div></div> ```
In your `#wctopdropnav ul` selector, you have `margin: 0` so if you want to override that and add `margin-right: 20px;` then it must be declared after it like so. ``` #wctopdropnav ul { float: right; margin: 0; margin-right: 20px; } ```
173039
I am just a beginner with angularJs , and i am trying to do CRUD Operations using $http and asp.net MVC :- 1. I am using ng-repeat to display list of "Terms" . 2. I have a button to display a dialog ,which in turn will be used to inserting new "Term". 3. ng-repeat works well and the dialog also displayed and i can insert new item successfully. the problem is :- - after inserting new term and closing the dialog , ng-repeat doesn't updating . and this the code i am using : ``` var glossayApp = angular.module("glossaryApp", ['ui.bootstrap.dialog']); var ctrl = glossayApp.controller("termController", function ($scope, $http, $route, $dialog, $window) { $scope.terms = []; $scope.init = function () { $http.get("/Home/List").success(function (data) { $scope.terms = data; }); } $scope.add = function () { $scope.opts = { backdrop: true, keyboard: true, backdropClick: true, templateUrl: '/Home/Add', controller: 'dialogController' }; var d = $dialog.dialog($scope.opts); d.open().then(function (term) { if (term) { $http.post('/Home/Add/', { Name: term.name, Definition: term.definition }).success(function () { $scope.init(); }); } }); } }); glossayApp.config(function ($routeProvider) { $routeProvider.when('/', { controller: 'termController', templateUrl: '/Home/list' }).when('/Details:id', { controller: 'termController', templateUrl: '/Home/details' }).otherwise({ redirectTo: '/' }); }); var dialogController = glossayApp.controller('dialogController', function ($scope, dialog) { $scope.save = function (term) { dialog.close(term); } $scope.close = function () { dialog.close(); } }); ``` and this the HTML I am using in ngrepeat :- ``` <table border="0" cellpadding="0" cellspacing="0" ng-init="init();"> <thead> <tr> <td> Term </td> <td> Definition </td> </tr> </thead> <tr ng-repeat="term in terms"> <td> {{term.Name}} </td> <td> {{term.Definition}} </td> </tr> </table> <br /> <input type="button" name="Add" value="Add New Term" ng-click="add();" /> ```
at the first glance , I guessed that the problem is the Scope , so I worked around it , I attached a CSS class to the table element which contains ng-repeat directive , this is my working code : ``` $scope.add = function () { $scope.opts = { backdrop: true, keyboard: true, backdropClick: true, templateUrl: '/Home/Add', controller: 'dialogController' }; var d = $dialog.dialog($scope.opts); d.open().then(function (term) { if (term) { $http.post('/Home/Add/', { Name: term.name, Definition: term.definition }).success(function () { $http.get("/Home/GetData").success(function (data) { var termscope = angular.element($(".term")).scope(); termscope.terms = data; termscope.$apply(); }); }); } }); } ``` I get the scope of the table which contains ng-repeat using :- ``` var termscope = angular.element($(".term")).scope(); ``` and set terms variable again :- ``` termscope.terms = data; ``` and at the end i need to call $apply to update view(html). ``` termscope.$apply(); ``` and it works well and updated the ng-repeat (view) after closing the dialog with no problem .
173537
I have custom UITableViewCell class which implements custom drawn design (as you can see, the cell has shadow effect.) As you can see below I'm trying to paint 1st cell with white color, any other cell must be gray. ``` - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGColorRef whiteColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0].CGColor; if (_rowNumber == 0) CGColorRef lightColor = [UIColor whiteColor].CGColor; else CGColorRef lightColor = [UIColor grayColor].CGColor; CGColorRef darkColor = _darkColor.CGColor; CGColorRef shadowColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.5].CGColor; CGContextSetFillColorWithColor(context, whiteColor); CGContextFillRect(context, _paperRect); CGContextSaveGState(context); CGContextSetShadowWithColor(context, CGSizeMake(0, 2), 7.0, shadowColor); CGContextSetFillColorWithColor(context, lightColor); CGContextFillRect(context, _coloredBoxRect); CGContextRestoreGState(context); } ``` The problem is: when I'm using dequeueReusableCellWithIdentifier the method "drawRect" invoked only 3 times (my cells have height 200), so the fourth cell has same color like the first one. Is there any way to manage this problem? Thanks UPDATE i've tried to invoke my custom redraw method from UITableViewController, but i have got "null" context error ``` - (void)refreshColorOfRow:(int)row{ CGContextRef context = UIGraphicsGetCurrentContext(); if (row > 0) _lightColor = [UIColor colorWithRed:200.0f/255.0f green:199.0f/255.0f blue:200.0f/255.0f alpha:1.0]; else _lightColor = [UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0]; CGColorRef lightColor = _lightColor.CGColor; CGContextSetFillColorWithColor(context, lightColor); CGContextFillRect(context, _coloredBoxRect); CGContextRestoreGState(context); } ```
OK, so the answer seem to be no! which surprised me some... Anyway. I made my own helper class which maybe can help you to. This is only one of many possible solutions. For my application it works nice to return null if nothing is found, maybe you want an exception instead. Also keep in mind that I am making this as a side project, so there are no extensive testing of the code, and therefore **I make NO guarantees that this works**. ``` public class ClipboardHtmlOutput { public Double Version { get; private set; } public String Source { get; private set; } public String Input { get; private set; } //public String Html { get { return Input.Substring(startHTML, (endHTML - startHTML)); } } public String Html { get { return Input.Substring(startHTML, Math.Min(endHTML - startHTML, Input.Length - startHTML)); } } public String Fragment { get { return Input.Substring(startFragment, (endFragment - startFragment)); } } private int startHTML; private int endHTML; private int startFragment; private int endFragment; public static ClipboardHtmlOutput ParseString(string s) { ClipboardHtmlOutput html = new ClipboardHtmlOutput(); string pattern = @"Version:(?<version>[0-9]+(?:\.[0-9]*)?).+StartHTML:(?<startH>\d*).+EndHTML:(?<endH>\d*).+StartFragment:(?<startF>\d+).+EndFragment:(?<endF>\d*).+SourceURL:(?<source>f|ht{1}tps?://[-a-zA-Z0-9@:%_\+.~#?&//=]+)"; Match match = Regex.Match(s, pattern, RegexOptions.Singleline); if (match.Success) { try { html.Input = s; html.Version = Double.Parse(match.Groups["version"].Value, CultureInfo.InvariantCulture); html.Source = match.Groups["source"].Value; html.startHTML = int.Parse(match.Groups["startH"].Value); html.endHTML = int.Parse(match.Groups["endH"].Value); html.startFragment = int.Parse(match.Groups["startF"].Value); html.endFragment = int.Parse(match.Groups["endF"].Value); } catch (Exception fe) { return null; } return html; } return null; } } ``` Usage could be something like this: ``` IDataObject iData = Clipboard.GetDataObject(); if (iData.GetDataPresent(DataFormats.Html)) { ClipboardHtmlOutput cho = ClipboardHtmlOutput.ParseString((string)iData.GetData(DataFormats.Html)); XmlDocument xml = new XmlDocument(); xml.LoadXml(cho.Fragment); } ```
174083
I use `defined runtime attributes` in button. ``` layer.cornerRadius layer.masksToBounds layer.borderWidth ``` And I want to paint my border in green colour. But my code doesn’t work: ``` layer.borderUIColor ``` Borders have black colour. How to paint border in colour with runtime attributes? [![enter image description here](https://i.stack.imgur.com/ufBQO.png)](https://i.stack.imgur.com/ufBQO.png)
Actually, you are using wrong attribute.The, correct attribute is `layer.borderColor`. But again it will not work because it is type of CGColor and from IB we can only assign UIColor, we can't assign CGColor. Eihter you can simply do it programaticlly. Or You can create extension with type CGColor.
174551
I cannot connect to a MySQL database, I am using xampp. It says this error from the code simple error: "Connection to the server failed!" ``` namespace Mysql { public partial class Form1 : Form { private MySqlConnection conn; private string server; private string database; private string uid; private string password; public Form1() { server = "localhost"; database = "tut1"; uid = "root"; password = ""; string connString; connString = $"SERVER={server};DATABASE={database};UID={uid};PASSWORD={password};"; conn = new MySqlConnection(connString); InitializeComponent(); } ```
OK, so I got it working. I fixed it adding SslMode=none.
174684
I'm new to Java and to Spring. How can I map my app root `http://localhost:8080/` to a static `index.html`? If I navigate to `http://localhost:8080/index.html` its works fine. My app structure is : ![dirs](https://i.stack.imgur.com/bMEaw.png) My `config\WebConfig.java` looks like this: ``` @Configuration @EnableWebMvc @ComponentScan public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("/"); } } ``` I tried to add `registry.addResourceHandler("/").addResourceLocations("/index.html");` but it fails.
if it is a Spring boot App. Spring Boot automatically detects index.html in public/static/webapp folder. If you have written any controller `@Requestmapping("/")` it will override the default feature and it will not show the `index.html` unless you type `localhost:8080/index.html`
174827
I am using the BigCommerce PHP API and am receiving this error when it attempts to connect to either my store or the webdav store: *failed setting cipher list* From the same server I have connected to both sites using cURL via the command line. I have the cURL php module installed with SSL enabled. Any thoughts would be appreciated.
Assuming this is a new installation and not a re-installation I think solving your problem is as simple as: ``` initdb `brew --prefix`/var/postgres/data -E utf8 ``` Typically the data directory is called "data' and is underneath the postgresql home directory. this allows for the possibility of sharing log file access and the like.
175142
I am confused by the behavior of `is.na()` in a for loop in R. I am trying to make a function that will create a sequence of numbers, do something to a matrix, summarize the resulting matrix based on the sequence of numbers, then modify the sequence of numbers based on the summary and repeat. I made a simple version of my function because I think it still gets at my problem. ``` library(plyr) test <- function(desired.iterations, max.iterations) { rich.seq <- 4:34 ##make a sequence of numbers details.table <- matrix(nrow=length(rich.seq), ncol=1, dimnames=list(rich.seq)) ##generate a table where the row names are those numbers print(details.table) ##that's what it looks like temp.results <- matrix(nrow=10, ncol=2, dimnames=list(1:10)) ##generate some sample data to summarize and fill into details.table temp.results[,1] <- rep(5:6, 5) temp.results[,2] <- rnorm(10) print(temp.results) ##that's what it looks like details.table[,1][row.names(details.table) %in% count(temp.results[,1])$x] <- count(temp.results[,1])$freq ##summarize, subset to the appropriate rows in details.table, and fill in the summary print(details.table) for (i in 1:max.iterations) { rich.seq <- rich.seq[details.table < desired.iterations | is.na(details.table)] ## the idea would be to keep cutting this sequence of numbers down with ## successive iterations until the desired number of iterations per row in ## details.table was reached. in other words, in the real code i'd do ## something to details.table in the next line print(rich.seq) } } ##call the function test(desired.iterations=4, max.iterations=2) ``` On the first run through the for loop the rich.seq looks like I'd expect it to, where 5 & 6 are no longer in the sequence because both ended up with more than 4 iterations. However, on the second run, it spits out something unexpected. UPDATE Thanks for your help and also my apologies. After re-reading my original post it is not only less than clear, but I hadn't realized count was part of the plyr package, which I call in my full function but wasn't calling here. I'll try and explain better. What I have working at the moment is a function that takes a matrix, randomizes it (in any of a number of different ways), then calculates some statistics on it. These stats are temporarily stored in a table--temp.results--where temp.results[,1] is the sum of the non zero elements in each column, and temp.results[,2] is a different summary statistic for that column. I save these results to a csv file (and append them to the same file at subsequent iterations), because looping through it and rbinding hogs a lot of memory. The problem is that certain column sums (temp.results[,1]) are sampled very infrequently. In order to sample those sufficiently requires many many iterations, and the resulting .csv files would stretch into the hundreds of gigabytes. What I want to do is create and then update a table (details.table) at each iteration that keeps track of how many times each column sum actually got sampled. When a given element in the table reaches the desired.iterations, I want it to be excluded from the vector rich.seq, so that only columns that haven't received the desired.iterations are actually saved to the csv file. The max.iterations argument will be used in a break() statement in case things are taking too long. So, what I was expecting in the example case is the exact same line for rich.seq for both iterations, since I didn't actually do anything to change it. I believe that flodel is definitely right that my problem lies in comparing a matrix (details.table) of length longer than rich.seq, leading to unexpected results. However, I don't want the dimensions of details.table to change. Perhaps I can solve the problem implementing %in% somehow when I redefine rich.seq in the for loop?
Your `break`s are breaking out of the `switch ... case` not the `while`. You'll need to use some kind of boolean flag to break out of the outer loop, e.g.: ``` bool someflag = true; while(someflag){ switch(something){ case a: someflag = false; // set the flag so we break out of the loop break; // break out of the switch-case so we don't enter case b case b: // do something else break; } } ``` `-------- EDIT, because I misunderstood the question ------------` I think you need an extra state in your logic, right now (ignoring state 1), you have two states: 1. Wait for a `p`, when you get one, goto 2. 2. `printf` for each character until you get an `r`, then goto 1 What you want is: 1. Wait for a `p`, when you get one, goto 2. 2. Do a `printf`, then goto 3. 3. Wait for an `r`, when you get one, goto 1.
175173
After doing a standard, App Store upgrade of Yosemite it seems that the recovery partition is still Mavericks-specific. Whether I hold Cmd+R or Option and select the recovery partition it takes me to the Mavericks recovery. If I choose Reinstall OS X it kicks off the Mavericks (re)install screens. Shouldn't there be a Yosemite recovery partition that replaced this? Is there any way to manually create the partition? Is this just how it's supposed to be with a Mavericks recovery partition after a Yosemite upgrade?
I had the same issue since the beta and the official release did not solve this issue. In the terminal I had the following output: > > diskutil list > > > ``` /dev/disk0 #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme *251.0 GB disk0 1: EFI EFI 209.7 MB disk0s1 2: Apple_HFS Macintosh HD 210.0 GB disk0s2 3: Apple_Boot Recovery HD 650.0 MB disk0s3 4: Microsoft Basic Data BOOTCAMP 40.1 GB disk0s4 ``` a recovery partition was available (but not working) The following did fix my issue: * downloaded the yosemite installer (again) * created a bootable installation (8GB USB) drive with yosemite (USB drive volume name is Untitled). > > sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Yosemite.app --nointeraction > > > * Removing the not working recovery partition > > diskutil eraseVolume HFS+ ErasedDisk /dev/disk0s3 > > > * merging the free space with the Macintosh HD partition > > diskutil mergePartitions HFS+ MacHD disk0s2 disk0s3 > > > * Install (like you upgrade) Yosemite over your existing (Yosemite) installation and complete the installation procedure (I used the installer from the fresh created USB). After the installation was completed I rebooted the machine and I was able to use the find my Mac option again (error related to the recovery partition was gone). This worked for me, **a small (typing) error might result in loosing your installation + data. Please be sure you have a good working backup before you start!** Used resource: [removing-and-rebuilding-a-malfunctioning-recover-hd-partition/](http://derflounder.wordpress.com/2011/10/22/removing-and-rebuilding-a-malfunctioning-recover-hd-partition/)
175259
I am sending an AJAX request having the "data" property being a FormData with a single key something like this: ``` var fData = new FormData($(accRegForm)); fData.append("Name", "Test Test"); $.ajax({ type: "POST", data: JSON.stringify(fData), url: "/DataService.ashx", contentType: "application/json; charset=utf-8", dataType: "json", cache: false }); ``` Now on the server, how can I retrieve the vale of "Name" inside ASP.NET? Thanks
After nearly 3 hours of experimenting I got it and even 260 times faster as before: ``` SELECT MAX(pd.id) AS max_id, pd.name AS player, MAX( pd.update_time ) AS last_seen, MIN( pd.login_time ) AS first_seen, SUM( pd.play_time ) AS ontime_total, SUM( CASE WHEN pd.login_time > NOW( ) - INTERVAL 1 DAY THEN pd.play_time END ) AS ontime_day, SUM( CASE WHEN pd.login_time > NOW( ) - INTERVAL 7 DAY THEN pd.play_time END ) AS ontime_week, SUM( CASE WHEN pd.login_time > NOW( ) - INTERVAL 1 MONTH THEN pd.play_time END ) AS ontime_month, (SELECT s.name FROM session_player sp INNER JOIN server s ON s.id=sp.server_id WHERE max(pd.id)=sp.id ) as last_server FROM ( SELECT sp.id AS id, sp.server_id as server_id, p.name AS name, sp.login_time AS login_time, sp.update_time AS update_time, sp.play_time AS play_time FROM session_player sp INNER JOIN players p ON p.id=sp.player_id WHERE p.name = ? ) as pd ```
175599
I am importing via RSS various news articles from various sources (all beyond my coding/formatting control) into my client's database (all legal!) and I am attempting to standardize some of their styling for presentation on client's site via jQuery. For example... Many many sites use various header tags seemingly for formatting only. When these are pulled into client's presentation they look like crap, so I have working code to find and replace these code blocks with a styled paragraph (the semantics of this code are not important, we mainly link back to original source), and it works fine. Code: ``` $(document).ready(function() { $('#selector h1, #selector h2:not(.article_name), #selector h3, #selector h4, #selector h5').replaceWith(function() { return '<p class="h_replace">' + $(this).text() + '</p>'; }); }); ``` The `.h_replace` CSS simply enlarges the `<p>` and adds some other attributes to make it more heading-like. So far, so good. But here's where I'm hitting a wall: same sites also often use a `<p>` immediately followed with a child `<b>` *as the only content* to substitute/act as a `heading`. I want to find and replace these code blocks with a styled paragraph (as above), but I am **unsuccessful** selecting any `<p>` that contains **ONLY** a `<b>` element. That is to say I want to select this: ``` <p><b>Some content here.</b></p> ``` and not this: ``` <p><b>Some Bold Text:</b> and some NOT bold text.</p> ``` In the first example, the `<p>` contains ONLY a child `<b>` element. In the second example the `<p>` contains a child `<b>` element as well as paragraph text not enclosed in the child `<b>`. I am looking to programmatically select only the first type of `<p>`, and not the second. Any ideas? Here's what I've got so far, but it selects both instances: ``` $(document).ready(function() { $('#selector p b:only-child').parent('p').replaceWith(function() { return '<p class="h_replace">' + $(this).text() + '</p>'; }); }); ``` The `:only-child` selector I thought would be a magic bullet, but then, of course, the `<b>` **IS** the only child of the `<p>` in both cases. I need to select paragraphs that contain *only* and *nothing but* `<b>` content. I hope that's clear. As always, any help is always greatly appreciated.
Try this: ``` var els = $('p').filter(function() { return /^<(b)>.+<\/\1>$/.test($.trim($(this).html())); }); ``` It will get you all `p` that have an only children `b` without any text nodes. You can change `(b)` with whatever tag in the code above. **Edit:** Don't know why the downvote but this works just fine: * `<p><b>Something</b></p> // true` * `<p> <b>Something</b> </p> // true` * `<p><b>Something</b> lorem</p> // false` * `<p>lorem <b>Something</b></p> // false` * `<p><span><b>Something</b></span></p> // false` **Demo:** <http://jsfiddle.net/elclanrs/LFt8x/>
175605
**Yes. I know they really only owned them for a day at this point in the movie.** > > TROOPER > How long have you had these droids? > > > LUKE > About three or four seasons. > > > BEN > They're for sale if you want them. > > > Is Luke referring to a farming season or planetary season? How long are these seasons? **In Luke's lie/fantasyland, how long did they own the droids?**
Based on Luke's conversation with Lars about him leaving, I think it's planetary seasons, with a yearly harvest: > > **LUKE**: I think those new droids are going to work out fine. In fact, I, uh, was also thinking about our agreement about my staying on another season. And if these new droids do work out, I want to transmit my application to the Academy this year. > > > **OWEN**: You mean the next semester before harvest? > > > **LUKE**: Sure, there're more than enough droids. > > > **OWEN**: Harvest is when I need you the most. Only one more season. This year we'll make enough on the harvest so I'll be able to hire some more hands. And > then you can go to the Academy next year. > > > **OWEN**: You must understand I need you here, Luke. > > > **LUKE**: But it's a whole 'nother year. > > > **OWEN**: Look, it's only one more season. > > > **LUKE**: Yeah, that's what you said last year when Biggs and Tank left. > > > *(Quoting from [Revised Fourth Draft, January 15, 1976](https://www.imsdb.com/scripts/Star-Wars-A-New-Hope.html); but the dialog hasn't changed much from that to the final release IIRC)* > > >
176293
I have created a new content element, but I have a problem with the image field. I have managed to save it in db. There it is saved as a integer. In the fluid it comes back as a integer but I need the image object to display it. I know it must be a typoscript configuration problem but can't seem to solve it. **tt\_content.php** ``` <?php // Poekmon Element \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTcaSelectItem( 'tt_content', 'CType', [ 'Pokemon Element', 'strange_elements', 'content-target', ], 'textmedia', 'after' ); $GLOBALS['TCA']['tt_content']['types']['strange_elements'] = [ 'showitem' => ' --div--;LLL:EXT:core/Resources/Private/Language/Form/locallang_tabs.xlf:general, --palette--;;general, header; Main Header, bodytext; Main Body, tx_selected_pokemon; Choose your pokemon, tx_type_pokemon; Pokemon Radio, tx_image_pokemon; Pokemon Image, --div--;LLL:EXT:core/Resources/Private/Language/Form/locallang_tabs.xlf:access, --palette--;;hidden, --palette--;;access, ', 'columnsOverrides' => [ 'bodytext' => [ 'config' => [ 'enableRichtext' => true, 'richtextConfiguration' => 'default', ], ], ], ]; $newPokemonElFields = [ 'tx_selected_pokemon' => [ 'exclude' => 0, 'label' => 'LLL:EXT:examples/Resources/Private/Language/locallang_db.xlf:tt_content.tx_selected_pokemon', 'config' => [ 'type' => 'select', 'renderType' => 'selectSingle', 'items' => [ ['Pikachu', 'pikachu'], ['Squirtle', 'squirtle'], ['Bulbasaur', 'bulbasaur'], ['Charmander', 'charmander'], ], 'default' => 'pikachu' ], ], 'tx_type_pokemon' => [ 'exclude' => 0, 'label' => 'LLL:EXT:examples/Resources/Private/Language/locallang_db.xlf:tt_content.tx_type_pokemon', 'config' => [ 'type' => 'radio', 'items' => [ ['Water', 'water'], ['Fire', 'fire'], ['Grass', 'grass'], ], ], ], 'tx_image_pokemon' => [ 'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_tca.xlf:sys_file_reference.tx_image_pokemon', 'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig('image', [ 'appearance' => [ 'createNewRelationLinkTitle' => 'LLL:EXT:frontend/Resources/Private/Language/Database.xlf:tt_content.asset_references.tx_image_pokemon' ], ], $GLOBALS['TYPO3_CONF_VARS']['SYS']['mediafile_ext']) ], ]; \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns('tt_content', $newPokemonElFields); ``` **ext\_tables.sql** ``` tx_image_pokemon int(11) unsigned DEFAULT '0' NOT NULL, ``` **setup.typoscript** ``` ######################### #### Content Element #### ######################### lib.contentElement { templateRootPaths.200 = EXT:youtube_demo/Resources/Private/Templates/ } tt_content { contenance_elements =< lib.contentElement contenance_elements { templateName = ContenanceEl dataProcessing.10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor dataProcessing.10 { references { table = tt_content fieldName = tx_image_pokemon } as = images_pokemon } } } ``` [![enter image description here](https://i.stack.imgur.com/GMhkr.png)](https://i.stack.imgur.com/GMhkr.png) [![enter image description here](https://i.stack.imgur.com/5CyJa.png)](https://i.stack.imgur.com/5CyJa.png)
A message queue seems like a good fit. When using a Azure Storage Queue you indeed need poll for new message. However, Azure Service Bus Queues push messages as stated by [the docs](https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-azure-and-service-bus-queues-compared-contrasted#consider-using-service-bus-queues): > > As a solution architect/developer, you should consider using Service Bus queues when: > > [...] > > Your solution needs to receive messages without having to poll the queue. With Service Bus, you can achieve it by using a long-polling receive operation using the TCP-based protocols that Service Bus supports. > > > I've successfully used near realtime communication using Azure Service Bus Queues, so it is definitely possible.
176508
I have a shell script called `setup_wsl.sh` which contains: ``` #!/bin/bash echo "hai" sudo apt-get update sudo apt-get install \ apt-transport-https \ ca-certificates \ curl \ gnupg-agent \ software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo apt-key fingerprint 0EBFCD88 sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ stable" sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io ``` When i run the script as ./setup\_wsl.sh in WSL ( installed distro is ubuntu 18.04), errors occur as: ``` hai E: Invalid operation update E: Unable to locate package ./setup_wsl.sh: 4: ./setup_wsl.sh: apt-transport-https: not found ./setup_wsl.sh: 5: ./setup_wsl.sh: ca-certificates: not found curl: (3) Illegal characters found in URL ./setup_wsl.sh: 7: ./setup_wsl.sh: gnupg-agent: not found : not found ./setup_wsl.sh: software-properties-common : not found ./setup_wsl.sh: ``` The first command of the script works fine as it gives output "hai". Can someone help me to find why these errors occured?
This is because of the carriage return in windows. Switch to the LF carriage with a text editor and save the new one to run the script or sed -i -e 's/\r$//' setup\_wsl.sh
176603
I need to arrange a table by performing some formatting, with a table like ``` DT <- read.table(text = "Year ST_ID N Overall Metric1 Metric2 1999 205 386 96.3 0 0 1999 205 15 0 0 0 1999 205 0 0 0 0 1999 205 0 0 0 NA 2000 205 440 100 0 0 2000 205 0 0 0 0 2000 205 0 0 NA 0 2000 205 0 0 0 NA", header = TRUE) ``` I need to obtain the following "Output" table. ``` Year ST_ID 1 2 3 4 Overall Metric1 Metric2 1999 205 386 15 0 0 96.3 0 NA 2000 205 440 0 0 0 100 NA NA . . ``` In the columns on the right, I want to aggregate any instances of NA => to NA else sum(values) How can I achieve this using R?
You can achieve this by adding a class when the div was clicked first. ``` $(document).ready(function () { $(".block-in-div").click(function () { return function () { cancelBg(); if(!$(this).hasClass('not-resized')) { $(this).css("background", getRandomColor()); $(this).addClass('not-resized'); } else if ($(this).hasClass('not-resized')) { $(this).addClass("active"); $(this).removeClass('not-resized'); } }; }()); }); ``` If you need to reset the state on click on other div you can just add $(".block-in-div").removeClass('not-resized'); at the end. Note 1: Adding active class like you did will have lower priority than the size on original class (add an !important as a temporal fix to see the changes or even better... make a stronger selector). Note 2: If I didn't get the requirements right pls. tell me.
176816
I am trying to read a single file from a `java.util.zip.ZipInputStream`, and copy it into a `java.io.ByteArrayOutputStream` (so that I can then create a `java.io.ByteArrayInputStream` and hand that to a 3rd party library that will end up closing the stream, and I don't want my `ZipInputStream` getting closed). I'm probably missing something basic here, but I never enter the while loop here: ``` ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream(); int bytesRead; byte[] tempBuffer = new byte[8192*2]; try { while ((bytesRead = zipStream.read(tempBuffer)) != -1) { streamBuilder.write(tempBuffer, 0, bytesRead); } } catch (IOException e) { // ... } ``` What am I missing that will allow me to copy the stream? **Edit:** I should have mentioned earlier that this `ZipInputStream` is not coming from a file, so I don't think I can use a `ZipFile`. It is coming from a file uploaded through a servlet. Also, I have already called `getNextEntry()` on the `ZipInputStream` before getting to this snippet of code. If I don't try copying the file into another `InputStream` (via the `OutputStream` mentioned above), and just pass the `ZipInputStream` to my 3rd party library, the library closes the stream, and I can't do anything more, like dealing with the remaining files in the stream.
Your loop looks valid - what does the following code (just on it's own) return? ``` zipStream.read(tempBuffer) ``` if it's returning -1, then the zipStream is closed before you get it, and all bets are off. It's time to use your debugger and make sure what's being passed to you is actually valid. When you call getNextEntry(), does it return a value, and is the data in the entry meaningful (i.e. does getCompressedSize() return a valid value)? IF you are just reading a Zip file that doesn't have read-ahead zip entries embedded, then ZipInputStream isn't going to work for you. Some useful tidbits about the Zip format: Each file embedded in a zip file has a header. This header can contain useful information (such as the compressed length of the stream, it's offset in the file, CRC) - or it can contain some magic values that basically say 'The information isn't in the stream header, you have to check the Zip post-amble'. Each zip file then has a table that is attached to the end of the file that contains all of the zip entries, along with the real data. The table at the end is mandatory, and the values in it must be correct. In contrast, the values embedded in the stream do not have to be provided. If you use ZipFile, it reads the table at the end of the zip. If you use ZipInputStream, I suspect that getNextEntry() attempts to use the entries embedded in the stream. If those values aren't specified, then ZipInputStream has no idea how long the stream might be. The inflate algorithm is self terminating (you actually don't need to know the uncompressed length of the output stream in order to fully recover the output), but it's possible that the Java version of this reader doesn't handle this situation very well. I will say that it's fairly unusual to have a servlet returning a ZipInputStream (it's much more common to receive an inflatorInputStream if you are going to be receiving compressed content.
176821
Is there a way to filter a list by User or Group column? I need to get all the tasks assigned to each user in a site. I got the below code for now, but that only works if I'm trying to get my tasks. Is there a way to pass an user ID to Membership Type so I can get the tasks of any user? ``` <Where> <Or> <Eq> <FieldRef ID="AssignedTo" /> <Value Type="Integer"> <UserID/> </Value> </Eq> <Membership Type="CurrentUserGroups"> <FieldRef Name="AssignedTo" /> </Membership> </Or> </Where> ```
I don’t think this issue has ever been fixed. It also happens when we use an Excel Web Part on a page. The only workaround in the mentioned [document](https://support.microsoft.com/en-us/office/refreshing-data-in-a-workbook-in-a-browser-window-89560193-0c11-420b-b7d8-744766ccdc94) is to use Excel client application (in the last section): > > If you run into a situation where you can’t refresh the data in a > browser window, try opening the workbook in Excel. > > >
176969
I am using elastic beanstalk to deploy my laravel application. Everything is working fine except for my images as I need to create a symbolic link with storage to access it publicly. *P.S. Works fine on my local* **My .ebextensions file is as follows -** ``` commands: composer_update: command: export COMPOSER_HOME=/root && /usr/bin/composer.phar self-update option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: COMPOSER_HOME value: /root container_commands: 01-install_dependencies: command: "php /usr/bin/composer.phar install" cwd: "/var/app/ondeck" 02_storage_sym_link: command: "php artisan storage:link" cwd: "/var/app/ondeck" leader_only: true ``` **Below is the log from my ec2 instance to confirm that the command worked just fine and the link was created successfully.** ``` [2019-04-21T15:47:16.899Z] INFO [21538] - [Application update symlink alt2@208/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_Synchro/Test for Command 02_storage_sym_link] : Starting activity... [2019-04-21T15:47:16.903Z] INFO [21538] - [Application update symlink alt2@208/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_Synchro/Test for Command 02_storage_sym_link] : Completed activity. Result: Completed successfully. [2019-04-21T15:47:16.903Z] INFO [21538] - [Application update symlink alt2@208/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_Synchro/Command 02_storage_sym_link] : Starting activity... [2019-04-21T15:47:17.014Z] INFO [21538] - [Application update symlink alt2@208/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_Synchro/Command 02_storage_sym_link] : Completed activity. Result: The [public/storage] directory has been linked. ``` **The error I am getting is as follows which makes the images unavailable for public access.** ``` Forbidden You don't have permission to access /storage/blog/images/8Yhb4OZJQIKwlMGaGE803niTxyjfzNSVTj2BiPaP.gif on this server. ``` Any help guiding me to the right path is appreciated. Cheers! --- **EDIT 1 :** ``` container_commands: 01-install_dependencies: command: "php /usr/bin/composer.phar install" cwd: "/var/app/ondeck" 02_storage_sym_link: command: "ln -s storage/app/public public/storage" cwd: "/var/app/ondeck" 03_give_ec2_user_perm_1: command: "sudo chown -R ec2-user /var/app/current" 03_give_ec2_user_perm_2: command: "sudo chmod -R 777 /var/app/current" ``` Tried creating the symlink manually plus gave permission to the ec2-user. **But still no luck :(**
Putting down an **alternate option** which does the job for people who are/might have a similar issue - **Use S3 for file storage in your Laravel application.** To make it happen - 1. Create a public S3 bucket. 2. Create an IAM user which has full access to S3 bucket. *(With the access key, the application will have permissions to read and write in the S3 bucket.)* 3. Update the config file `filesystems.php` to use the S3 bucket. *(This config handles the storage config of the application.)* Refer the [Laravel Doc](https://laravel.com/docs/5.8/filesystem) for more info. *Thanks to @PranavanSp for his suggestion.*
177195
I am writing a simple project using maven, scala and junit. One problem I found is that my tests cannot find org.junit.framework.Test. The test file: ``` import org.junit.framework.Test class AppTest { @Test def testOK() = assertTrue(true) @Test def testKO() = assertTrue(false) } ``` returns error: ``` [WARNING]..... error: object junit is not a member of package org [WARNING] import org.junit.framework.Test [WARNING] ^ ``` I did have junit added as a dependency and it clearly sits inside my repository. ``` <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> ``` Can someone tell me what causes this? Many thanks
As @nico\_ekito says, your import is incorrect, and should be `org.junit.Test`. But this doesn't explain your problem: ``` [WARNING]..... error: object junit is not a member of package org [WARNING] import org.junit.framework.Test [WARNING] ^ ``` So it can't find org.junit. This means that org.junit isn't in the classpath when you're compiling the tests. So either your dependency tree is screwed up, or the actual jar is. Try ``` mvn dependency:list ``` This should result in something like: ``` [INFO] The following files have been resolved: [INFO] junit:junit:jar:4.8.1:test ``` Ensure that you've got no other junit libraries being resolved. If everything looks ok, check the contents of your junit jar. It should contain the class org.junit.Test. If it doesn't, you've got a corrupted repo, or you're not looking in the right place. The easiest way to know this is to use: ``` mvn dependency:copy-dependencies ``` which creates target/dependency with a copy of the dependencies. You can look at the jar there.
178131
In Xcode 3.2.5 I use "Build And Archive" to create an IPA file without any problems. How can I do that in Xcode 4? I think I have to use "Product -> Archive", but I get over 100 error messages in the three20 framework. Most are "No such file or directory". ("Product -> Build For -> Build For Archiving" works. No errors.) For example, this is the first error message: ``` ../scripts/Protect.command: line 23: cd: /Users/[USERNAME]/Library/Developer/Xcode/DerivedData/[PROJECTNAME]-blabla/ArchiveIntermediates/[PROJECTNAME]/BuildProductsPath/Release-iphoneos/../three20/Three20Core: No such file or directory ``` The path `"/[PROJECTNAME]/BuildProductsPath/three20/"` really doesn't exists, but this path exists: `"/[PROJECTNAME]/three20/"` What can I do?
I had to go under Project Info > Build (tab) and add the following to the header search path: ``` three20/Build/Products/three20 ``` This path may be specific to my project, but there it is in case it works for someone else.
178417
I am confused by the Bundle/Gem approach of global dependencies. I thought global dependencies are a thing of a past. I present to you two approaches of handling dependencies, NPM vs Bundle/Gem. ### NPM Let me demonstrate the power of NPM. Say you have an app with the following folder structure: ``` /app /admin package.json /front-end package.json ``` You can see that inside my app I have two other mini-apps. Each of those has its own `package.json`. Say both of them have `q` as a requirement, but with **different version**. Running `npm install` in both of these folders will install appropriate versions to `node_modules` of each mini app. Everything is nicely isolated and works very well. ### Bundle/Gem Bundles approach is slightly different. You use `Gemfile` to specify your dependencies. After running `bundle install` the gems will be put into a system wide location. That means that if I have an app that requires different versions of a gem within its mini-apps then it wont work. Work arounds that make no sense to me: * I am aware that there is a `bundle install --deployment`, but its used only for deployments in production. How is my code supposed to work in development? * Also, I am aware that you have an options to require a specific version of the gem in your code but that beats the convenience of having `Gemfile` with specific versions in it. It also makes no sense in production environment since you already have `bundle install --deployment`. I am 100% sure I'm missing something very trivial here. Please point me into the right direction.
I found the 'answer'. Ruby unlike Node.js does not have a built in support for local node\_modules like implementation. Thus you have to use Bundler. But to use the dependencies in your code you need to let Ruby know where these dependencies are located. Bundler makes it easy for you with the following lines in your app code: ``` require 'rubygems' require 'bundler/setup' ``` This will read your Gemfile.lock and apply proper paths when your require something form your app. This is the part that I missed. You can also use `bundle exec {rubygem}` to run gems that are installed by bundler for your app and not those that are installed globally. I hope this helps someone!
178496
I know how to replace an Apostrophe from a String with a space, in php. However how can I remove Apostrophes in arrays items? ``` //Example replacing Apostrophe with space $string = str_replace("'", "", $escapestring); if ( $f_pointer === false ) die ("invalid URL"); $ar=fgetcsv($f_pointer); while(! feof($f_pointer)) { $ar=fgetcsv($f_pointer); //DO REPLACE HERE BEFORE INSERTION INTO SQL STATEMENT $sql="INSERT INTO x (1,2,3,4,5,6) values('$array[0]','$array[1]','$array[2]', 'array[3]','array[4]','array[5]')"; ```
I believe that you can compare a modulo of the time difference in months to match the months and dates regardless the year. You would just need to handle the date for the first and last months in the acceptable range. I've done this below, but since I don't have SQL Server installed, I can't test how DATEDIFF works with months, but I'm assuming here it gives integers. ``` SELECT expiration_date FROM mytable WHERE (DATEDIFF(month,GETDATE(),expiration_date) % 12 IN (1, -11) AND DATEPART(day,expiration_date) >= DATEPART(day,GETDATE())) OR (DATEDIFF(month,GETDATE(),expiration_date) % 12 IN (4, -8) AND DATEPART(day,expiration_date) < DATEPART(day,GETDATE())) OR (DATEDIFF(month,GETDATE(),expiration_date) % 12 IN (2, 3, -9, -10)); ```
178610
I'm trying to make a user control in wxWidgets to represent a channel in an audio mixer. So, each channel has a standard set of controls inside itself (some sliders, buttons, etc..). So inside my class I have a sizer in which I add the various child controls I need. So far that works. But the problems I have are * if I derive from wxPanel, the layout of the control works as I expect it (it gets expanded in the sizer to fit the child controls), however none of the children get any events (like EVT\_LEFT\_DOWN etc). I tried connecting an event for the main control that runs event.Skip() but that didn't help. * If I change my class to derive from wxControl instead (or wxFrame, or possibly a number of others I tried), the child controls *do* get events, but the whole thing doesn't get expanded in the sizer it's located in, it just gets drawn as a tiny box (some 10-20 square px) even though the child controls take up much more space. Any ideas? *Update:* **mangoMixerStrip.cpp** ``` mangoMixerStrip::mangoMixerStrip(wxFrame* parent, HostChannel* channel) : wxPanel(parent) { myChannel = channel; SetBackgroundColour(wxColour(172,81,90)); wxBoxSizer* s = new wxBoxSizer(wxVERTICAL); // some custom controls i made which all work fine when added like any other control, derived from wxPanel also faderPan = new mangoFader(parent, 200, false, 55); faderGain = new mangoFader(parent, 200, true, 126); buttonSolo = new mangoButton(parent, false, ButtonGraphic::Solo); s->Add(faderPan); s->Add(buttonSolo); s->Add(faderGain); this->SetSizer(s); this->Connect(wxEVT_LEFT_DOWN, wxMouseEventHandler(mangoMixerStrip::mouseDown)); // this function simply contains event.Skip() } ``` **in my main wxFrame** ``` mangoFrameMain::mangoFrameMain(wxWindow* parent) : FrameMain( parent ) { HostChannel* h = new HostChannel(); h->setName("what up"); // these 2 lines unrelated to the UI mangoMixerStrip *test = new mangoMixerStrip(this, h); this->GetSizer()->Add(test, 1, wxFIXED_MINSIZE, 0); } ``` And to clarify: the mangoMixerStrip instance itself gets any events I connect to it, but its child controls do not.
I haven't been playing with grappelli but in standard django-admin I would consider usage of: ModelAdmin.raw\_id\_fields. The limitation is that you don't select services using name but using pk. > > By default, Django's admin uses a > select-box interface () for > fields that are ForeignKey. Sometimes > you don't want to incur the overhead > of having to select all the related > instances to display in the drop-down. > > > raw\_id\_fields is a list of fields you > would like to change into an Input > widget for either a ForeignKey or > ManyToManyField: > > > ``` class ArticleAdmin(admin.ModelAdmin): raw_id_fields = ("newspaper",) ``` Harder approach would be to override admin manager for Service and add request level cache. Remember to make this manager available in case of elated objects access.
178731
I have created a stored procedure of insert command for employee details in SQL Server 2005 in which one of the parameters is an image for which I have used `varbinary` as the datatype in the table.. But when I am adding that parameter in the stored procedure I am getting the following error- > > *Implicit conversion from data type varchar to varbinary is not > allowed. Use the CONVERT function to run this query.* > > > Stored procedure: ``` ( @Employee_ID nvarchar(10)='', @Password nvarchar(10)='', @Security_Question nvarchar(50)='', @Answer nvarchar(50)='', @First_Name nvarchar(20)='', @Middle_Name nvarchar(20)='', @Last_Name nvarchar(20)='', @Employee_Type nvarchar(15)='', @Department nvarchar(15)='', @Photo varbinary(50)='' ) insert into Registration ( Employee_ID, Password, Security_Question, Answer, First_Name, Middle_Name, Last_Name, Employee_Type, Department, Photo ) values ( @Employee_ID, @Password, @Security_Question, @Answer, @First_Name, @Middle_Name, @Last_Name, @Employee_Type, @Department, @Photo ) ``` Table structure: ``` Column Name Data Type Allow Nulls Employee_ID nvarchar(10) Unchecked Password nvarchar(10) Checked Security_Question nvarchar(50) Checked Answer nvarchar(50) Checked First_Name nvarchar(20) Checked Middle_Name nvarchar(20) Checked Last_Name nvarchar(20) Checked Employee_Type nvarchar(15) Checked Department nvarchar(15) Checked Photo varbinary(50) Checked ``` Code in vb.net for calling stored procedure-> Public Function Submit(ByVal obj As UserData, ByVal opt As String) As Boolean ``` Using cnn As New SqlConnection(conn) Using cmd As New SqlCommand cmd.Connection = cnn If opt = "Submit" Then cmd.CommandText = "sp_emp_Registration" End If cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add(New SqlParameter("@Employee_ID", obj.EmpID)) cmd.Parameters.Add(New SqlParameter("@Password", obj.Pwd)) cmd.Parameters.Add(New SqlParameter("@Security_Question", obj.SecQues)) cmd.Parameters.Add(New SqlParameter("@Answer", obj.Ans)) cmd.Parameters.Add(New SqlParameter("@First_Name", obj.Firstname)) cmd.Parameters.Add(New SqlParameter("@Middle_Name", obj.Middlename)) cmd.Parameters.Add(New SqlParameter("@Last_Name", obj.Lastname)) cmd.Parameters.Add(New SqlParameter("@Employee_Type", obj.EmpType)) cmd.Parameters.Add(New SqlParameter("@Department", obj.dept)) cmd.Parameters.Add(New SqlParameter("@Photo", obj.photo)) cnn.Open() Try If (cmd.ExecuteNonQuery() > 0) Then cnn.Close() Return True Else Return False End If Catch ex As Exception Return False End Try End Using End Using End Function ``` I am not getting what to do..can anyone give me some suggestion or solution? Thanks in advance.
You assign a string to a varbinary as default value. This operation don't perform a implicit cast. To avoid error: Change line: ``` @Photo varbinary(50)='' ``` by: ``` @Photo varbinary(50) ``` If you don't have Photo value for some rows you should alter table column to **allow nulls**.
178766
I'm trying to use an `INNER JOIN` in SQL to show a column from one table into another. Here is the query that I'm using: ``` SELECT * FROM Person.BusinessEntity INNER JOIN HumanResources.Employee ON Person.BusinessEntity.BusinessEntityID = HumanResources.Employee.JobTitle ``` When I execute this, I get an error: > > Conversion failed when converting the nvarchar value 'Chief Executive Officer' to data type int > > > I'm not trying to convert the data so I'm not sure why I'm getting this error. Any help would be much appreciated!
As you are trying to join to columns with different data types you are forcing the database to make an implicit conversion which it can't do in this case. What you want to do is to join the tables on the keys the share (which would be BusinessEntityID in this case). The table and column names look familiar and I'm guessing that you are following the examples in the book *Beginning Microsoft SQL Server 2012 Programming* (or some similar book that uses the AdventureWorks sample database) and if so the source of the issue is that you are using the wrong column in the HumanResources.Employee table. It should be ``` SELECT Person.BusinessEntity.*, HumanResources.Employee.JobTitle FROM Person.BusinessEntity INNER JOIN HumanResources.Employee ON Person.BusinessEntity.BusinessEntityID = HumanResources.Employee.BusinessEntityID ```
179331
I have CKEditor & i save that as a Html in my database.Then i'm going to get that saved html stream & show it inside div But it shows the html codes. My webmethod return below line ``` <p> <strong>Test Heading </strong></p> <p> <img alt="" src="http://s7.postimg.org/511xwse93/mazda_familia_photo_large.jpg" style="width: 150px; height: 112px;" /></p> <p> test description goes here</p> ``` Div ``` <div id="usrnewsdesc"></div> ``` My Ajax Call ``` function LoadNewsToUsers() { debugger; var newurl = '<%= ResolveUrl("/WebMethods.aspx/GetIndividualUserNews") %>'; $.ajax({ url: newurl, type: "POST", data: JSON.stringify({ ToUser: "<%=GetUserID()%>" }), dataType: "json", contentType: "application/json; charset=utf-8", success: function (Result) { $.each(Result.d, function (key, value) { var html ="<body>"+value.News+"</body>"; $("#usrnewsdesc").append(html); }); }, error: function (e, x) { alert(x.ResponseText); } }); } ``` My div looks like this ![mydiv](https://i.stack.imgur.com/8ahf8.png) My WebMethod ``` [WebMethod, ScriptMethod] public static List<UserNews> GetIndividualUserNews(Guid ToUser) { List<UserNews> UserNewsDetails = new List<UserNews>(); try { SqlCommand comGetAllFiles = new SqlCommand("SP_GetNewsToUser", conDB); comGetAllFiles.CommandType = CommandType.StoredProcedure; if (conDB.State == ConnectionState.Closed) conDB.Open(); comGetAllFiles.Parameters.Add("@ToUser", SqlDbType.UniqueIdentifier); comGetAllFiles.Parameters["@ToUser"].Value = ToUser; SqlDataReader rdr = comGetAllFiles.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(rdr); foreach (DataRow r in dt.Rows) { UserNewsDetails.Add(new UserNews { Id = (int)r["Id"], News = r["News"].ToString(), DateTime =(DateTime) r["DateTime"], ToUser = (Guid)r["ToUser"] }); } } catch (Exception ee) { } finally { conDB.Close(); } return UserNewsDetails; } ``` Console.log is below ``` &lt;p&gt; &lt;strong&gt;Test Heading &lt;/strong&gt;&lt;/p&gt; &lt;p&gt; &lt;img alt=&quot;&quot; src=&quot;http://s7.postimg.org/511xwse93/mazda_familia_photo_large.jpg&quot; style=&quot;width: 150px; height: 112px;&quot; /&gt;&lt;/p&gt; &lt;p&gt; test description goes here&lt;/p&gt; ```
You need to decode your html content before you can use it as html. ``` success: function (Result) { $.each(Result.d, function (key, value) { var html = $("<div/>") // temp container .html(value.News) // "render" encoded content to text .text(); // retrieve text (actual html string now) // body tags are a bad idea here but whatever. html = "<body>" + html + "</body>"; $("#usrnewsdesc").append(html); }); }, ``` With credit to this post for the decoding instruction: [How to decode HTML entities using jQuery?](https://stackoverflow.com/questions/1147359/how-to-decode-html-entities-using-jquery)
179425
I am using the package titlesec to format the titles in my document. As I don't want to have the titles in a closed box (we could use "frame" as format parameter of \titleformat for that), I use a \colorbox between two \titlerule: ``` \usepackage[explicit]{titlesec} \titleformat{name=\section}[block] {\titlerule\normalfont\bfseries\large} {} {0pt} {\colorbox{LightSteelBlue!75}{\parbox{\dimexpr\columnwidth-2\fboxsep}{\strut\thesection .~#1\strut}}}[\titlerule] ``` The wanted result is the following: [![enter image description here](https://i.stack.imgur.com/hb2K4.jpg)](https://i.stack.imgur.com/hb2K4.jpg) Unfortunately, a tiny white space sometimes appears between the \titlerule of the top and the \colorbox: [![enter image description here](https://i.stack.imgur.com/tFiRX.jpg)](https://i.stack.imgur.com/tFiRX.jpg) Also, the \titlerule of the top is sometimes thinner as it should be : [![enter image description here](https://i.stack.imgur.com/WEPOu.jpg)](https://i.stack.imgur.com/WEPOu.jpg) As a reminder the \titleformat is defined as: [![enter image description here](https://i.stack.imgur.com/Ib0SR.jpg)](https://i.stack.imgur.com/Ib0SR.jpg) Here is the tex file i'm working on: <https://www.overleaf.com/read/qwksdgfjgbjt> Can someone find a solution to this problem ? Thank you :)
It seems that you looking for one from the following examples: ``` \documentclass[11pt]{article} \usepackage[margin=3cm]{geometry} \usepackage{tabularx} %---------------- show page layout. don't use in a real document! \usepackage{showframe} \renewcommand\ShowFrameLinethickness{0.15pt} \renewcommand*\ShowFrameColor{\color{red}} %---------------------------------------------------------------% \begin{document} \section*{TEST} \begin{tabularx}{\linewidth}{>{$}l<{$} !{\hspace{0.55in}} >{\raggedleft\arraybackslash}X} 2000 & Text\\ 2004-2005 & More Text Here\\ \end{tabularx} \medskip or \medskip \noindent% \begin{tabularx}{\linewidth}{@{} >{$}l<{$} !{\hspace{0.55in}} >{\raggedleft\arraybackslash}X @{}} 2000 & Text\\ 2004-2005 & More Text Here\\ \end{tabularx} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/e47gO.png)](https://i.stack.imgur.com/e47gO.png) As you can see, instead of `tabular` and your definitions for `L` and `R` is used `\tabularx` table and `X` column type. Since the width of `tabularx` is prescribed to be text width, table width is from left text border to right text border. **Addendum:** with editing your question you actually ask new question ... anyway, as solution for it can be the following (I guess): ``` \documentclass[11pt]{article} \usepackage[margin=3cm]{geometry} \usepackage{ragged2e} \usepackage{booktabs, tabularx} \newcolumntype{L}{>{\RaggedRight}X} \begin{document} \section*{Section 1} \begin{tabularx}{\linewidth}{p{5em} !{\hspace{0.1in}} L} Year -- Now & Data 1\\ & Data 2 may be different in length and may be much longer in fact\\ \addlinespace Year -- Now & Data 3 may vary in length \\ & Data 4 are very long, so and they may be longer than column width. Consequently in such a case they will be broken into two or more lines\\ \addlinespace Year -- Now & Data 5 may vary in length \\ & Data 4 even if it is longer and it may be broken into many lines\\ \end{tabularx} \section*{Section 2} \begin{tabularx}{\linewidth}{p{5em} !{\hspace{0.1in}} L} Year & This text is much longer \\ & Text in the second row is very long, consequently it is broken into many lines\\ \addlinespace 2020 -- 2020 & More information here\\ \end{tabularx} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/gG2Fp.png)](https://i.stack.imgur.com/gG2Fp.png)
179831
A professor asked me to help making a specification for a college project. By the time the students should know the basics of programming. The professor is a mathematician and has little experience in other programming languages, so it should really be in MATLAB. I would like some projects ideas. The project should 1. last about 1 to 2 months * be done individually * have web interface would be great * doesn't necessary have to go deep in maths, but some would be great * use a database (or store data in files) What kind of project would make the students excited? If you have any other tips I'll appreciate. **UPDATE:** The students are sophomores and have already studied vector calculus. This project is for an one year Discrete Mathematics course. **UPDATE 2:** The topics covered in the course are 1. Formal Logic 2. Proofs, Recursion, and Analysis of Algorithms 3. Sets and Combinatorics 4. Relations, Functions, and Matrices 5. Graphs and Trees 6. Graph Algorithms 7. Boolean Algebra and Computer Logic 8. Modeling Arithmetic, Computation, and Languages And it'll be based on this book [Mathematical Structures for Computer Science: A Modern Approach to Discrete Mathematics by Judith L. Gersting](https://rads.stackoverflow.com/amzn/click/com/071676864X)
MATLAB started life as a MATrix LAB, so maybe concentrating on problems in linear algebra would be a natural fit. Discrete math problems using matricies include: 1. Spanning trees and shortest paths 2. The marriage problem (bipartite graphs) 3. Matching algorithms 4. Maximal flow in a network 5. The transportation problem See [Gil Strang's "Intro to Applied Math"](https://rads.stackoverflow.com/amzn/click/com/0961408804) or [Knuth's "Concrete Math"](https://rads.stackoverflow.com/amzn/click/com/0201558025) for ideas.
180659
Check was sent for $2800? What are the steps to obtain additional $1400 for child? I was perusing below to no avail: [IRS 3rd payment here](https://www.irs.gov/coronavirus/third-economic-impact-payment)
> > If it is how come there are stuff called land loans? > > > Since mortgages on home are much more common, it's typically inferred that a "mortgage" means a loan on a house (or possibly on a multi-family structure or other type of building). The reason that "land loans" are specified may be because the *conditions* of such a mortgage are very different. With a home mortgage, there will be restrictions on what you can use the building for. i.e. can you rent it out or do you have to occupy it? Can you make renovations that materially impact the house's value without the bank's consent? What type of insurance must be carried? With a land loan the restrictions are different (and probably simpler). What can you put on the land? What modifications to the land can you make? etc. So they are also technically mortgages but are less common and thus have more specific descriptions. > > can you buy whatever you want as long as you have some sort of real estate property as collateral > > > The loan document *should* specify what the collateral for the loan is. So, for example, you couldn't take out a home mortage and use a boat as collateral. Now, if you had a paid-for house, you could take out a mortgage on the *house* and use the *money* to buy a boat, but the house would still be the collateral for the loan.
181106
I used this query to load data to mysql table. `LOAD DATA INFILE 'E:\upload.csv' REPLACE INTO TABLE ms.no_vas LINES TERMINATED BY '\n';` **Upload.csv** `123` `456` `789` `000` `111` `222` `333` Now i have another csv file `delete.csv` which contents i want to delete from the `ms.no_vas`table. **delete.csv** `456` `789` *Note*: these two files contain over 7 million records. Is there a way to delete all values on `delete.csv` from the `ms.no_vas`table?
Upload the delete.csv into a temporary database, then delete using a subquery. Example: ``` DELETE FROM ms.no_vas WHERE ms.no_vas.value IN (SELECT value FROM temp_delete_table); ```
181220
I have several websites running in Azure, intensively using ServiceBus (also hosted in Azure), all in one region. Sometimes (once every 2-3 days) I have same error in all web sites at the same time (during reading/waiting for messages): ``` Microsoft.ServiceBus.Messaging.MessagingCommunicationException: The X.509 certificate CN=servicebus.windows.net is not in the trusted people store. The X.509 certificate CN=servicebus.windows.net chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. A certificate chain could not be built to a trusted root authority. ``` Full stacktrace: ``` Microsoft.ServiceBus.Messaging.MessagingCommunicationException: The X.509 certificate CN=servicebus.windows.net is not in the trusted people store. The X.509 certificate CN=servicebus.windows.net chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. A certificate chain could not be built to a trusted root authority. ---> System.ServiceModel.Security.SecurityNegotiationException: The X.509 certificate CN=servicebus.windows.net is not in the trusted people store. The X.509 certificate CN=servicebus.windows.net chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. A certificate chain could not be built to a trusted root authority. ---> System.IdentityModel.Tokens.SecurityTokenValidationException: The X.509 certificate CN=servicebus.windows.net is not in the trusted people store. The X.509 certificate CN=servicebus.windows.net chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. A certificate chain could not be built to a trusted root authority. at System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult lazyResult) at System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result) at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult) at System.ServiceModel.Channels.SslStreamSecurityUpgradeInitiator.InitiateUpgradeAsyncResult.OnCompleteAuthenticateAsClient(IAsyncResult result) --- End of inner exception stack trace --- Server stack trace: at Microsoft.ServiceBus.Messaging.Channels.SharedChannel`1.CreateChannelAsyncResult.<GetAsyncSteps>d__7.MoveNext() at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.EnumerateSteps(CurrentThreadType state) at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result) at Microsoft.ServiceBus.Common.AsyncResult.AsyncCompletionWrapperCallback(IAsyncResult result) Exception rethrown at [0]: at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.ServiceBus.Common.AsyncResult`1.End(IAsyncResult asyncResult) at Microsoft.ServiceBus.Messaging.Channels.SharedChannel`1.OnEndCreateInstance(IAsyncResult asyncResult) at Microsoft.ServiceBus.Messaging.SingletonManager`1.EndGetInstance(IAsyncResult asyncResult) at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.<GetAsyncSteps>b__2(RequestAsyncResult thisPtr, IAsyncResult r) at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result) Exception rethrown at [1]: at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.ServiceBus.Common.AsyncResult`1.End(IAsyncResult asyncResult) at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.EndRequest(IAsyncResult result) at Microsoft.ServiceBus.Messaging.Sbmp.RedirectBindingElement.RedirectContainerChannelFactory`1.RedirectContainerSessionChannel.RequestAsyncResult.<>c__DisplayClass17.<GetAsyncSteps>b__a(RequestAsyncResult thisPtr, IAsyncResult r) at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result) Exception rethrown at [2]: at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.ServiceBus.Common.AsyncResult`1.End(IAsyncResult asyncResult) at Microsoft.ServiceBus.Messaging.Sbmp.RedirectBindingElement.RedirectContainerChannelFactory`1.RedirectContainerSessionChannel.EndRequest(IAsyncResult result) at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.<GetAsyncSteps>b__4(RequestAsyncResult thisPtr, IAsyncResult r) at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result) Exception rethrown at [3]: at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.ServiceBus.Common.AsyncResult`1.End(IAsyncResult asyncResult) at Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.EndRequest(IAsyncResult result) at Microsoft.ServiceBus.Messaging.Sbmp.CloseOrAbortLinkAsyncResult.<GetAsyncSteps>b__7(CloseOrAbortLinkAsyncResult thisPtr, IAsyncResult a) at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result) Exception rethrown at [4]: at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageReceiver.AbandonPrefetchedMessagesCloseAbortAsyncResult.<GetAsyncSteps>b__41(AbandonPrefetchedMessagesCloseAbortAsyncResult thisPtr, IAsyncResult r) at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result) Exception rethrown at [5]: at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageReceiver.OnEndClose(IAsyncResult result) --- End of inner exception stack trace --- at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageReceiver.OnEndClose(IAsyncResult result) at Microsoft.ServiceBus.Messaging.ClientEntity.OnClose(TimeSpan timeout) at Microsoft.ServiceBus.Messaging.ClientEntity.Close(TimeSpan timeout) at Olekstra.Common.QueueReader.<>c__DisplayClass3.<StartTask>b__2(Boolean force) ``` I'm using up-to-date version of `Microsoft.ServiceBus.dll` NuGet package (2.4.0.0), so answers from Google "certificate validation is off by default in ServiceBus 1.8" are useless - I had not turned any validation to ON, and moreover - it works many hours in a row and fails only once every 2-3 days. Similar [answer](https://stackoverflow.com/questions/24171931/azure-hosted-service-bus-the-x-509-certificate-cn-servicebus-windows-net-is-n) about self-hosted applications are not suitable too - website is running inside Azure, hosting VMs are manages by MS staff, I'm not allowed to update any root certificates. Does anybody know why ServiceBus client decides to check SSL cert sometimes and how to disable this behaviour? **UPD:** I added `<add key="Microsoft.ServiceBus.X509RevocationMode" value="NoCheck"/>` in `appSettings` in `web.config` two weeks ago - no difference. Also Reflector shows that 'NoCheck' value is default in `Microsoft.ServiceBus.Configuration.ConfigurationHelpers.GetCertificateRevocationMode()`
A change in Connectivity Mode *could* solve your problem. ``` ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Https ``` It is normally `ConnectivityMode.AutoDetect` According to a source in MS support > > "This will force all traffic to use a WebSockets tunnel that is > protected by a *prior* TLS/HTTPS handshake, and that handshake carries > the required intermediate certificate. The messaging protocol used > through that tunnel will still be AMQP or NetMessaging, so you should > not be worried to get HTTP characteristics when choosing this option." > > > So I figure that the certificate will only be fetched once in this scenario, and that may introduce an extra latency at that point, and then it is used forever after. It seems logical that the risk of getting your exception is thus reduced considerably.
181326
I think the question is clear from the heading. I have a PHP file, call it PHP1. In that PHP1, I have a URL looking pretty much like `www.mywebsite/script.php?color=red&sky=blue&past=gone` Where I am confused is that the values 'red' and 'blue' and 'gone' are in three dynamic variables: `$var1`, `$var2` and `$var3`. How can I post these variables through URL into a second PHP file, PHP2. In the PHP2 file, I want to recieve the values like: ``` $var1 = $_GET['color']; $var2 = $_GET['sky']; $var3 = $_GET['past']; ``` How can I achieve this? I know I can use ajax and all, but URL is my only resort here.
I think you are looking for how to generate dynamic url in your php1 file ``` $c = "red"; $s = "blue"; $stat ="past"; //Now you need to generate a dynamic url in your php1 file $url = 'www.mywebsite/script.php?color='.$c.'&sky='.$s.'&past='.$stat; //now genearte a dynamic link echo '<a href="'. $url.'">Click me</a>'; //you have dynamic link. after clicking it will take you to different page //your url shoule be www.mywebsite/script.php?color=red&sky=blue&past=gone //just concanate ``` Php2 file ``` echo 'color'.$_GET["color"].' SKY '.$_GET["sky"].' STAT '.$_GET["past"]; ``` //it should work
182447
Currently, my app allows the user to click on a "default avatar pic" and then select from a group of images. This image is then returned to the first activity via "startActivityForResult". My next task is to take the image that is now set in the first activity and send it to a third activity when the user presses the "submit button". Right now, I'm trying the below code, but it's not working as I don't know which image is going to be selected by the user until it's selected. Can anyone help me out here? ``` findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, DisplayActivity.class); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.select_avatar); intent.putExtra("IMAGE", bitmap); startActivity(intent); } }); //second activity Bitmap bitmap = intent.getParcelableExtra("Bitmap"); imageViewAvatar.findViewById(R.id.imageViewFinalAvatar); imageViewAvatar.setImageBitmap(bitmap); ```
You can just simply use the ImageView Id as a integer or string value, then pass it. No need to use any bitmap. Bitmap takes too much memory. Image should be work as a resource id if the image is selected from your resource folder. If your image comes from cloud, then definitely have a url as a string. So handle it as a **string as resource id/file path/url**. ``` int imageID = R.drawable.select_avatar; findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, DisplayActivity.class); intent.putInt("image_id", imageID); // Integer Value startActivity(intent); } }); //second activity Intent intent = getIntent(); int imageIdValue = intent.getIntExtra("image_id", 0); imageViewAvatar.setImageResource(0); imageViewAvatar.setImageResource(imageIdValue); ```
182716
I was reading a chapter on effective Java that talks about the advantages of keeping only one instance of an immutable object, such that we can do object identity comparison `x == y` instead of comparing the values for identity. Also, POJOs like [`java.awt.RenderingHints.Key`](http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/RenderingHints.Key.html) often use the one-instance-per-unique-immutable design pattern: > > > > > > Instances of this class are immutable and unique which means that tests for matches can be made using the == operator instead of the more expensive equals() method. > > > > > > > > > I can understand the speed boost with this approach, But wouldn't this design pattern eventually cause a memory leak ?
That is sometimes called the Flyweight pattern, especially if the space of possible objects is bounded.
183090
**Output to be produced** ![enter image description here](https://i.stack.imgur.com/XMvsv.jpg) using this as reference but now with different scenario [SQL Server query : get the sum conditionally](https://stackoverflow.com/questions/29597690/sql-server-query-get-the-sum-conditionally) **explanation:** Item, Sales, and remarks columns are given column from a database, New Sales column is a formulated column where in, it is getting the sum of items with the same keyword remarks except the default n/a remarks. (regardless the remarks is not fully identical, at least there's a common similarity like what is on the image above - item 5 has "new" in it, still it sums up with item 6 because of their similar keyword found "small") **code used** **FIRST OPTION- using partition** - This doesn't work because when the remarks is not identical to each other it will not get the sum properly (for item5 and item6) ``` CASE WHEN ([remarks] not like '%big%') AND ([remarks] not like '%PAENGS%') THEN sales ELSE SUM(sales) OVER(PARTITION BY [remarks]) END as 'New Sales' ``` **SECOND OPTION -using Cross Apply** - So it leave me to this, but I was lost as it is not getting the desired output. ``` CROSS APPLY SELECT d.*, NewSales = CASE WHEN ([remarks] not like '%big%') or ([remarks] not like '%small%') THEN Sales ELSE x.NewSales END FROM #MSRSuperFinal3 d CROSS APPLY(SELECT NewSales = SUM(Sales) FROM #MSRSuperFinal3 WHERE ([remarks] like '%big%') or ([remarks] like '%small%') )x ``` Any help will be highly appreciated
Try **Left Join** clause instead of Cross Apply: ``` SELECT a.item, a.sales, a.remarks, CASE WHEN a.remarks = 'n/a' THEN a.sales ELSE SUM( b.sales ) END AS [New Sales] FROM query_using_cross_apply_to_get_sum_conditionally a LEFT JOIN query_using_cross_apply_to_get_sum_conditionally b ON(a.remarks LIKE '%' + b.remarks + '%' AND b.remarks != 'n/a') GROUP BY a.item, a.sales, a.remarks; ```
183422
I know how to compare lists but working with unflatten data in Pandas is beyond my skills..anyway.. I have: ``` list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` and ``` df = pd.DataFrame({ "col1":["a", "b", "c", "d"], "col2":[[1, 2, 3, 4, 5], [20, 30, 100], [1, 3, 20], [20,30]] }) ``` I want to compare the `list` with the `df` and `print` rows that contain 100% matches, partial matches and dismatches. Desired outcome is then this: ``` "100% matches are in rows: a" "Partial matches are in rows: c" "Dismatches are in rows: b, d" ``` Python 3 solution would be much appreciated.Thanks!
Alternative #2: **Use the + operator for `object-node`** ```xquery let $extra := if (fn:exists($extraAttribute)) then object-node { "extra": $extraAttribute } else object-node {} let $data := object-node { "query": array-node { $id } } + $extra ``` I could not inline the `$extra` without an error, so I had to split it up like this.
183504
I am currently learning C++ and I am having an odd issue with threads. I've done lots of threaded stuff in Java and C# and not had an issue. I am currently trying to replicate a C# library that I have in C++ with a library and a test app. In main.cpp I create an instance of a `InitialiseLibrary` class and call the method `initialise`. This does config loading and is then supposed to start a thread which stays running through the duration the application is running. I am expecting this thread to start, and then my initialise function returns true where I then continue and I create an instance of a test class which writes to a log file every 1 second. Below is main.cpp ``` InitialiseLibrary initLibrary("config.ini"); if (!initLibrary.initialise(1)) { cout << "Failed to initialise library" << endl; return EXIT_FAILURE; } TestClass testClass; testClass.writeSomeLogsInThread(); cout << "The library config log file is: " << GlobalConfig::GeneralConfig::logFile << endl; ``` In my Initialise method (which is in the library) I have: ``` bool InitialiseLibrary::initialise(int applicationAlarmID, int applicationTerminationTimeout) { //statusManager.setApplicationStatus(StatusManager::ApplicationStatus::Starting); if (!this->loadInconfiguration(applicationAlarmID)) { cout << "*****Failed to configuration. Cannot continue******" << endl; return false; } GlobalConfig::libraryInitialised = true; LogRotation logRotation; logRotation.startLogRotation(); BitsLibrary bitsLibrary; //Set up the signal handler if its needed, 0 means it terminates instantly, doesn't wait -1 is don't use signal handler if (applicationTerminationTimeout >= 0) { bitsLibrary.setupSignalHandler(applicationTerminationTimeout); } return true; } ``` As you can see, I read in the configuration and I then call `logRotation.startLogRotation(). Where I have the following code: ``` void LogRotation::startLogRotation() { //Is the configuration successfully loaded if (!LogRotateConfiguration::configurationLoaded) { throw exception("Log Rotation not initialised"); } BitsLibrary bitsLibrary; stringstream logStream; logStream << "Log rotation thread starting, monitor cycle time is " << LogRotateConfiguration::archiveSleepTimeInSeconds << " second(s)"; bitsLibrary.writeToLog(logStream.str(), "LogRotation", "startLogRotation"); thread logRotationThread(&LogRotation::logRotationThread, this); logRotationThread.join(); } void LogRotation::logRotationThread() { BitsLibrary bitsLibrary; while (bitsLibrary.getApplicationStatus() == StatusManager::ApplicationStatus::Starting || bitsLibrary.getApplicationStatus() == StatusManager::ApplicationStatus::Running) { bitsLibrary.writeToLog("Running log monitoring"); this_thread::sleep_for(chrono::seconds(LogRotateConfiguration::archiveSleepTimeInSeconds)); } stringstream logStream; logStream << "Log rotation archive monitoring stopped. Current application status: " << bitsLibrary.getApplicationStatus(); bitsLibrary.writeToLog(logStream.str(), "LogRotation", "logRotationThread"); } ``` Here I am expecting, `startLogRotation()` to start run the method `logRotationThread` within a thread, the thread starts, and the startLogrotation() method finishes and backs through the stack to the initialise() method where that returns true, back up to main where I can then call my TestClass method within a thread. For some reason though, the thread starts and keeps logging every few seconds `Running log monitoring` so I know the thread has started, yet it doesn't seem to return back to the initialise function to return true, so the app gets stuck on that function call and doesn't go any further. I've read that you need to run `join` on the thread to keep it in sync with the main thread, otherwise the main thread exits, while the new threads are running and cause a SIGABRT which in deed it does, but having the join there seems to stop the method returning.
Your main thread blocks at this line, waiting for the logRotationThread to end. ``` logRotationThread.join(); ``` Your main thread should go and do whatever work it needs to do after spawning the other thread, then only when it has nothing left to do should it `join()` the log rotate thread.
183653
I have a Excel sheet, which includes many groups and subgroups. Each subgroup has their own subtotal. And as long as I can't know how many lines users will require for the subgroups, I only left 3 rows blank for each subgroup and created a button which triggers Automatically Copy and Insert Copied Row macro. Now I need to avoid users to trigger the button while they are on the First and the Last row of any subgroup. (If you copy and insert first row, subtotal formula doesn't recognise the new added line because it will be out of the range and Last row has another specific formulas which I don't want users to copy above) I've been searching SO and the other Excel blogs for a long time but because of my list is very dynamic and have many different subtotals none of them was suitable to my case. How can I define all of the first and last rows of my different subtotal ranges (and maybe their Title's rows) to avoid them being copied and then inserted above? [![Please also refer to the printscreen of my excel sheet](https://i.stack.imgur.com/DwQ9t.jpg)](https://i.stack.imgur.com/DwQ9t.jpg)
You can try something like: ``` file = open('traintag1.csv','r') csv_reader = csv.reader(file) data, target = zip(*[(x[-1], x[-2]) for x in csv_reader]) print len(data) print len(target) ``` This code creates a list of tuples, and then uses zip to expand the pairs into independent lists.
183969
I have a WCF service that is setup to be hosted within a unity container. I was intending to use this container to perform method interception. The problem is I cannot get my interceptor to fire... First here the definition of my interceptor attribute and handler: ``` [AttributeUsage(AttributeTargets.Method)] public class PCSecurityAttribute : HandlerAttribute { public PCSecurityAttribute(Modules module, int modulePermission) { SecurityModule = module; SecurityModulePermission = modulePermission; } public Modules SecurityModule { get; set; } public int SecurityModulePermission { get; set; } public override ICallHandler CreateHandler(IUnityContainer container) { return new PCSecurityCallHandler(0, SecurityModule, SecurityModulePermission); } } using System.ServiceModel.Security; using MHC.PracticeConnect.Contract.Data.Security; using Microsoft.Practices.Unity.InterceptionExtension; namespace MHC.PracticeConnect.Service { public class PCSecurityCallHandler : ICallHandler { private Modules securityModule; private int securityModulePermission; public PCSecurityCallHandler(Modules module, int modulePermission) { securityModule = module; securityModulePermission = modulePermission; Order = 0; } public PCSecurityCallHandler(int order, Modules module, int modulePermission) { securityModule = module; securityModulePermission = modulePermission; Order = order; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { bool validPermission = false; // check security permission IMethodReturn result; if (validPermission) result = getNext().Invoke(input, getNext); else throw new SecurityAccessDeniedException( "The current user does not have security " + "permissions to call this module."); return result; } public int Order { get; set; } } } ``` In my host I've tried to configure it to use interception to no avail... HELP!!!! ``` public class DocumentTemplateServiceHostFactory : ServiceHostFactory { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { UnityServiceHost host = new UnityServiceHost(serviceType, baseAddresses); UnityContainer unity = new UnityContainer(); host.Container = unity; host.Container.AddNewExtension<Interception>(); ; host.Container.RegisterType<IDocumentTemplateService, DocumentTemplateService>().Configure<Interception>(). SetInterceptorFor<IDocumentTemplateService>( new TransparentProxyInterceptor()); return host; } } ``` What am I doing wrong here?
You might want to check out using WCF behaviors. Here's links that might be useful. <http://msdn.microsoft.com/en-us/magazine/cc136759.aspx> AND <http://www.global-webnet.net/blogengine/post/2009/01/03/Integrating-IIS-WCF-and-Unity.aspx> -Bryan
184108
I am writing a sql query in Laravel to fetch all the data for current year but condition is I want to get status - Pending data first and Approved and Rejected data. According to 'status' = Pending/Approve and Reject? ``` $leaves = Leave::whereRaw('YEAR(start_date) = YEAR(CURDATE()) AND YEAR(end_date)=YEAR(CURDATE())') ->where('created_by', '=', \Auth::user()->creatorId())->get(); ```
Check if `READ_CALL_LOG` permission is there in your `app.json`, if no then add it like below ``` { "expo": { .... .... "android":{ "permissions":["READ_CALL_LOG"], "package":"your package name here" } } } ``` Ref : [Permissions](https://docs.expo.dev/versions/latest/config/app/#permissions)
184612
I followed the instructions at <https://create-react-app.dev/docs/deployment/#github-pages> and noticed that the command `gh-pages -b master -d build` replaced the contents of my working directory with the contents of the `build` folder and committed these changes to the `master` branch. This works as advertised to publish my React app at ***myusername*.github.io**, but it makes it impossible to make further changes to the source files since they are no longer available in the working directory. I understand that GitHub *project* pages work differently than GitHub user pages (they allow the application to be published from the `gh-pages` branch rather than `master`). So, do I have to move my code to a new project repository or is there a way to accomplish the same thing using my existing user repository?
Your logic is a bit backwards; you're doing: > > Every frame, scan for close Colliders and if the Player clicks E, do something for each of them > > > but should be doing: > > Every frame, check if Player clicks E and if someone is close, do something > > > Given the code supplied, it could probably be refactored to something like: ```cs Collider[] hitColliders = Physics.OverlapSphere(transform.position, radius); var playerCollided = hitColliders.FirstOrDefault(x => x.CompareTag("Player")) != null; if (playerCollided) { // *other stuff* } if (playerCollided && Input.GetKeyDown("e")) { Debug.Log("E pressed\nButton ID: " + buttonId); } ```
184653
referring to this question: [Finding duplicate values in multiple colums in a SQL table and count](https://stackoverflow.com/questions/70512433/finding-duplicate-values-in-multiple-colums-in-a-sql-table-and-count) I have the following table structure: ``` id name1 name2 name3 ... 1 Hans Peter Frank 2 Hans Frank Peter 3 Hans Peter Frank 4 Paul Peter Hans . . . ``` I use the following command to display the duplicates and the counts: ``` SELECT COUNT(name1), name1, name2, name3 FROM table GROUP BY name1, name2, name3 HAVING (COUNT(name1) > 1) AND (COUNT(name2) > 1) AND (COUNT(name3) > 1) ``` This command gives me a count of 2. I would like to know how the second line could also be counted as a dublicate. Unfortunately, the solution to the original question ([Finding duplicate values in multiple colums in a SQL table and count](https://stackoverflow.com/questions/70512433/finding-duplicate-values-in-multiple-colums-in-a-sql-table-and-count)) does not work for char
First normalize the table with `UNION ALL` in a CTE to get each of the 3 names in a separate row. Then with `ROW_NUMBER()` window function you can rank alphabetically the 3 names so that you can group by them: ``` WITH cte(id, name) AS ( SELECT id, name1 FROM tablename UNION ALL SELECT id, name2 FROM tablename UNION ALL SELECT id, name3 FROM tablename ) SELECT COUNT(*) count, name1, name2, name3 FROM ( SELECT id, MAX(CASE WHEN rn = 1 THEN name END) name1, MAX(CASE WHEN rn = 2 THEN name END) name2, MAX(CASE WHEN rn = 3 THEN name END) name3 FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY name) rn FROM cte ) GROUP BY id ) GROUP BY name1, name2, name3 HAVING COUNT(*) > 1; ``` Another way to do it, that uses similar logic to your previous question with numeric values, with string function `REPLACE()` instead of window functions, but works only if the 3 names in each row are different: ``` SELECT COUNT(*) count, MIN(name1, name2, name3) name_1, REPLACE( REPLACE( REPLACE(name1 || ',' || name2 || ',' || name3, MIN(name1, name2, name3), ''), MAX(name1, name2, name3), ''), ',', '' ) name_2, MAX(name1, name2, name3) name_3 FROM tablename GROUP BY name_1, name_2, name_3 HAVING COUNT(*) > 1; ``` See the [demo](https://dbfiddle.uk/?rdbms=sqlite_3.27&fiddle=ff34e2224bef75e3f7ad65f68f612e97).
184740
I have created an azure function that gets triggered when a new document is added to a collection. ``` public static void Run(IReadOnlyList<Document> input, ILogger log) { if (input != null && input.Count > 0) { log.LogInformation("Documents modified " + input.Count); log.LogInformation("First document Id " + input[0].Id); }} ``` Is it possible to select a particular document from this collection and then query the data in that selected document? Eg. in the collection called clothescollection, i have a document that has an id:12345Tops. I want to query the data found in the document with the id:12345Tops. Or alternatively retrieve the 1st document in the collection, and then query that 1st selected document i have viewed azure functions with http triggers: <https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb#trigger---attributes> but i need to use cosmosdb trigger as this needs to be triggered when a document is added to the collection.
If I understand correctly, you want to query documents on a second collection based on the changes that happen on a first collection? That is certainly doable, you need to use a [Cosmos DB Input Binding and pull the `DocumentClient` instance](https://learn.microsoft.com/azure/azure-functions/functions-bindings-cosmosdb-v2#http-trigger-get-multiple-docs-using-documentclient-c). The code would look something like: ``` [FunctionName("CosmosTrigger")] public static void Run([CosmosDBTrigger( databaseName: "ToDoItems", collectionName: "Items", ConnectionStringSetting = "CosmosDBConnection", LeaseCollectionName = "leases", CreateLeaseCollectionIfNotExists = true)]IReadOnlyList<Document> documents, [CosmosDB( databaseName: "ToDoItems", collectionName: "CollectionToQuery", ConnectionStringSetting = "CosmosDBConnection")] DocumentClient client, ILogger log) { foreach (var documentInsertedOrUpdated in documents) { try { // Do a read document on another collection var otherDocument = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri("ToDoItems", "CollectionToQuery", "some-id-maybe-taking-it-from-the-documentInsertedOrUpdated")); } catch(Exception ex) { log.LogError(ex, "Failed to process document"); } } } ```
184805
**UPDATE:** When installing both packages using setup.py alone they install just fine. When extracting the tarballs generated by sdist and installing them the same error occurs. This means that the problem is somewhere inside setuptools I guess. I developed two projects that have two namespace packages: testsuite and testsuite.prettyprint. Both of these namespace packages' `__init__.py` contain: ``` __import__('pkg_resources').declare_namespace(__name__) ``` Here's the setup.py for testsuite.prettyprint.outcomes: ``` import pkgutil from setuptools import setup def get_packages(): return [name for _, name, is_package in pkgutil.walk_packages('.') if name.startswith('testsuite') and is_package] dependencies = ['nose2>=0.4.6', 'colorama>=0.2.5'] setup( name='testsuite-prettyprint-outcomes', version='0.1.0-alpha.1', packages=get_packages(), url='', license='BSD3', author='Omer Katz', author_email='omer.drow@gmail.com', description='testsuite-prettyprint-outcomes is a nose2 plugin that prettyprints test outcomes.', namespace_packages=['testsuite', 'testsuite.prettyprint'], install_requires=dependencies ) ``` and here is the setup.py for testsuite.prettyprint.traceback: ``` import pkgutil import sys from setuptools import setup def get_packages(): return [name for _, name, is_package in pkgutil.walk_packages('.') if name.startswith('testsuite') and is_package] dependencies = ['nose2>=0.4.6', 'pygments>=1.6'] if sys.platform == 'win32': dependencies.append('colorama>=0.2.5') setup( name='testsuite-prettyprint-traceback', version='0.1.0-alpha.2', packages=get_packages(), url='', license='BSD3', author='Omer Katz', author_email='omer.drow@gmail.com', description='testsuite-prettyprint-traceback is a nose2 plugin that prettyprints traceback on failures and errors.', namespace_packages=['testsuite', 'testsuite.prettyprint'], install_requires=dependencies ) ``` When installing them both it refuses to install one: ``` pip install testsuite-prettyprint-outcomes testsuite-prettyprint-traceback --use-mirrors Downloading/unpacking testsuite-prettyprint-outcomes Downloading testsuite-prettyprint-outcomes-0.1.0-alpha.1.tar.gz Running setup.py egg_info for package testsuite-prettyprint-outcomes Downloading/unpacking testsuite-prettyprint-traceback Downloading testsuite-prettyprint-traceback-0.1.0-alpha.2.tar.gz Running setup.py egg_info for package testsuite-prettyprint-traceback Downloading/unpacking nose2>=0.4.6 (from testsuite-prettyprint-outcomes) Running setup.py egg_info for package nose2 warning: no previously-included files matching '__pycache__' found anywhere in distribution warning: no previously-included files matching '*~' found anywhere in distribution warning: no previously-included files matching '*.pyc' found anywhere in distribution Downloading/unpacking colorama>=0.2.5 (from testsuite-prettyprint-outcomes) Downloading colorama-0.2.5.zip Running setup.py egg_info for package colorama Downloading/unpacking pygments>=1.6 (from testsuite-prettyprint-traceback) Downloading Pygments-1.6.tar.gz (1.4MB): 1.4MB downloaded Running setup.py egg_info for package pygments Downloading/unpacking six>=1.1,<1.2 (from nose2>=0.4.6->testsuite-prettyprint-outcomes) Running setup.py egg_info for package six Installing collected packages: testsuite-prettyprint-outcomes, testsuite-prettyprint-traceback, nose2, colorama, pygments, six Running setup.py install for testsuite-prettyprint-outcomes Skipping installation of /home/omer/.virtualenvs/test/lib/python3.2/site-packages/testsuite/__init__.py (namespace package) Skipping installation of /home/omer/.virtualenvs/test/lib/python3.2/site-packages/testsuite/prettyprint/__init__.py (namespace package) Installing /home/omer/.virtualenvs/test/lib/python3.2/site-packages/testsuite_prettyprint_outcomes-0.1.0_alpha.1-py3.2-nspkg.pth Running setup.py install for testsuite-prettyprint-traceback error: package directory 'testsuite/prettyprint/outcomes' does not exist Complete output from command /home/omer/.virtualenvs/test/bin/python3.2 -c "import setuptools;__file__='/home/omer/.virtualenvs/test/build/testsuite-prettyprint-traceback/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-12l9lq-record/install-record.txt --single-version-externally-managed --install-headers /home/omer/.virtualenvs/test/include/site/python3.2: running install running build running build_py creating build creating build/lib creating build/lib/testsuite copying testsuite/__init__.py -> build/lib/testsuite creating build/lib/testsuite/prettyprint copying testsuite/prettyprint/__init__.py -> build/lib/testsuite/prettyprint error: package directory 'testsuite/prettyprint/outcomes' does not exist ---------------------------------------- Command /home/omer/.virtualenvs/test/bin/python3.2 -c "import setuptools;__file__='/home/omer/.virtualenvs/test/build/testsuite-prettyprint-traceback/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-12l9lq-record/install-record.txt --single-version-externally-managed --install-headers /home/omer/.virtualenvs/test/include/site/python3.2 failed with error code 1 in /home/omer/.virtualenvs/test/build/testsuite-prettyprint-traceback Storing complete log in /home/omer/.pip/pip.log ``` I can't figure out what is wrong. Even if you change the order of installation it says it can't find the other.
After installing one of your packages and downloading the other… You're not including `testsuite/__init__.py` and `testsuite/prettyprint/__init__.py` in the source files. The docs on [Namespace Packages](http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages) the `setuptools`/`pkg_resources` way explains: > > Note, by the way, that your project's source tree must include the namespace packages' `__init__.py` files (and the `__init__.py` of any parent packages), in a normal Python package layout. > > > If you don't actually install these files, they don't do any good. You just end up with a `testsuite` with nothing in it but `prettyprint`, and that has nothing in it but `outcomes`, so `testsuite` and `testsuite.prettyprint` are not packages at all, much less namespace packages.
185495
I have 2 models (`User` & `UsersDetails`) in relation with Eloquent Laravel. **Model "User" Realation With 'SelDetails'** ```php public function SelDetails { return $this->belongsTo('App\UsersDetails', 'users_id'); } ``` **I want to get only two column 'created\_by\_id', 'created\_by\_name' from SelDetails** UserController ```php $users = User::with(['SelDetails' => function($query){ $query->select(['created_by_id', 'created_by_name']); }]) ->where('is_active', '=', 0) ->orderBy('id', 'desc') ->get(); ``` I am getting data from `User` but getting blank in `SelDetails` ```php [relations:protected] => Array ( [SelDetails] => ) ``` Please correct me.
guys thanks for your precious response on this issue. i got the solution via following way. **changes in "User" model Relation With 'SelDetails'** ``` public function SelDetails { #return $this->belongsTo('App\UsersDetails', 'users_id');// the old one return $this->hasOne('App\UsersDetails', 'users_id'); } ``` **changes in "UserController"** ``` $users = User::with('SelDetails')->where('is_active', '=', 0)->orderBy('id', 'desc')->get(); ``` that's the changes that I have made and got the result [![enter image description here](https://i.stack.imgur.com/iQzAw.png)](https://i.stack.imgur.com/iQzAw.png) Thanks
186074
Inside `c:\test\` I have: * .\dir1 * .\dir2 * .\dir3 and * file1.txt * file2.txt * file3.txt * file4.txt I want to compress only `dir1`, `dir2`, `file1.txt` and `file2.txt` I use the following script to compress selected folders ``` $YourDirToCompress="C:\test\" $ZipFileResult=".\result.zip" $DirToInclude=@("dir1", "dir2") Get-ChildItem $YourDirToCompress -Directory | where { $_.Name -in $DirToInclude} | Compress-Archive -DestinationPath $ZipFileResult -Update ``` How would I be able to add my selected files (`file1.txt` & `file2.txt`) to final compressed `result.zip`? Ideally I want the compression to happen in one go meaning I pass the list of selected files and folders and then do the compression.
Try something like this: ``` Get-ChildItem -Path $YourDirToCompress | Where {$_.Name -in $DirToInclude} | Compress-Archive -DestinationPath $ZipfFileResult -Update ``` `Compress-Archrive` is capable of zipping both files and directories. So in this code we are using `Get-ChildItem` without the `-Directory` flag which will return all files and directories at the root-level of `$YourDirToCompress` Then we pass those files/folders to the `Compress-Archive` cmdlet just as we did before. *Assuming that the files are at the root level of `$YourDirToCompress`*
187010
I'm writing a custom xml deserializer for an iphone app. As you can see below, I'm looping through all the list elements in the xml, I have debugged it, and with each loop there is a new and different element. The problem is that the xpath helper methods (there are similar ones to the one posted below, but for int and decimal) always returns the same value. For example - 1st loop's xml "SomeValue" value will be "abc" and the helper method will return "abc", second item comes around and its xml "SomeValue" is "XYZ", but the helper method will still return "abc". I'm new to iphone/objective c/memory managment so it could be any number of things. I just cant determine what the problem is :( could someone please offer some help? ``` -(void) deserializeAndCallback:(GDataXMLElement *)response { NSError * error; NSArray *listings = [response nodesForXPath:@"//ListingSummary" error:&error]; NSMutableArray *deserializedListings = [[NSMutableArray alloc] init]; //loop through all listing elements, create a new listing object, set its values, and add //it to the list of deserialized objects. if(listings.count > 0) { for (GDataXMLElement *listingElement in listings) { Listing *list = [[Listing alloc] init]; //xpath helper function (shown below), just to get the value out of the xml list.someValue = [QuickQuery getString:listingElement fromXPath:@"//SomeValue"]; [deserializedListings addObject:list]; } } if([super.delegate respondsToSelector: @selector(dataReady:)]) { [super.delegate dataReady:deserializedListings]; } } +(NSString *) getString:(GDataXMLElement *)element fromXPath:(NSString *)xPath { NSError *error; NSArray *result = [element nodesForXPath:xPath error:&error]; if(result.count > 0) { GDataXMLElement *singleValue = (GDataXMLElement *) [result objectAtIndex:0]; return singleValue.stringValue; [singleValue release]; } return nil; [error release]; [result release]; } ``` EDIT: ok... I found a bit more info. Inside the helper function, the nodesForXpath method returns all the nodes from the entire xml, not just the current element I'm busy with. Does GDataXMLElement keep reference to its parent elements at all? Example of what the xml looks like ``` <ListingSummary> <SomeValue>abc</SomeValue> </ListingSummary> <ListingSummary> <SomeValue>jhi</SomeValue> </ListingSummary> <ListingSummary> <SomeValue>xyz</SomeValue> </ListingSummary> ```
It looks OK for me. Although the releases inside the getString:fromXPath: aren't necessary (you don't need to release parameters entered into a method or objects obtained from a NSArray. The proper way to release an object from a NSArray is removing it from the array, as for objects passed as a parameter, if you want to release it you should do it after you call the method. The problem to your question must be somewhere else.
187293
I am working with ARM mali 72 on my Android smartphonne. I would like to use the output buffer fron OpenCL to render it into OpenGL like a texture. I have no problem with openCL alone nether openGL alone. I got no cloud to how to use both in the same application. The goal is to use mY output OpenCL and send it to openGL. Some peice of code step by step would be very nice. I can use openCL 2.0 and opengl ES 3.0 on my smartphonne. \*\*\*\*\*\*\*\*\*\*\*\*\*\* ADDED THE 30/09/2020 \*\*\*\*\*\*\*\*\*\*\*\* It Look like I need more information on how to manage my problem. So my configuration is ! I got Java OpenGL ES Application to already develloped. I retreive the camera frame from Camera.OnPreviousFrame then a send it to OpenCL using JNI. So i would like to Get the EGL display from Java OpenGL ES Send it through JNI and then Compute my openCL kernel send It back to java OpenGL ES. I know how to retreive data from OpenCL, transform it to bitmap and use SurfaceTexture and GL\_TEXTURE\_EXTERNAL\_OES to display it into openGL ES. My problem is how to Retreive EGL display from java OpenGL ES. How to send it to C++, this i can manage to find out using JNI. But i do not know how to implement the C++ part using EGL and OpenCL. The Answer from BenMark is interresting concerning the processing but I am missing some part. It is possible to use my configuration, using java openGL ES or do i nedd to do all the EGL, openGL, openCL code in native ? Thanks a lot for help me to anderstand the problem and try to find a solution. ;))
You could do it with a recursive template like this : ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" > <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:variable name="linefeed" select="'&#xA;'"/> <xsl:template match="/"> <xsl:apply-templates select="root/Person"/> </xsl:template> <xsl:template match="Person"> <xsl:call-template name="PersonOutput"> <xsl:with-param name="index" select="1"/> <xsl:with-param name="person" select="."/> </xsl:call-template> </xsl:template> <xsl:template name="PersonOutput"> <xsl:param name="index"/> <xsl:param name="person"/> <xsl:if test="$index=1 or ($index mod 5)=1"> <xsl:value-of select="$linefeed"/> <xsl:value-of select="$person/Name"/> </xsl:if> <xsl:text>|</xsl:text> <xsl:value-of select="$person/Class[$index]/ClassID"/> <xsl:if test="$person/Class[$index]/following-sibling::Class"> <xsl:call-template name="PersonOutput"> <xsl:with-param name="index" select="$index+1"/> <xsl:with-param name="person" select="$person"/> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> ``` See it working here : <https://xsltfiddle.liberty-development.net/3Mvnt4c>
187608
I have code for a tabular environment that is not displayed properly. I have the right parenthesis following the lower-case Roman numerals `i`, `iii`, and `v` aligned, and I would like to have the right parenthesis following the lower-case Roman numerals `ii`, `iv`, and `vi` aligned. I thought that I had made the inter-column spacing 1.5 inches ... but that didn't happen. Why didn't the command `\hspace*{2em}` preceding the tabular environment indent the left edge of the box containing the contents of the tabular environment by `2em`? (I know there are other packages to use to display this table. I want to use the tabular environment and have my code modified.) ``` \documentclass{amsart} \usepackage{amsmath} \begin{document} \noindent The following sets have either a least upper bound or a greatest lower bound of 1. \\ \noindent \hspace*{2em} \setlength{\tabcolsep}{1.5in} \begin{tabular}{r@{}lr@{}l} \textbf{i.) } & $\displaystyle{\left\{1 - \frac{1}{n} \mid n \in \mathbb{N}\right\}}$ \textbf{ii.) } & $\displaystyle{\left\{1 + \frac{1}{n} \mid n \in \mathbb{N}\right\}}$ \\[1.2\normalbaselineskip] \textbf{iii.) } & $\displaystyle{\left\{9\sum_{n=1}^{N} \frac{1}{10^{n}} \mid N \in \mathbb{N}\right\}}$ \textbf{iv.) } & $\displaystyle{\left\{1 - \left(\frac{1}{2}\right)^{n} \mid n \in \mathbb{N}\right\}}$ \\[1.2\normalbaselineskip] \textbf{v.) } & $\displaystyle{\left\{\sqrt[\uproot{1} \leftroot{-1} n]{2} \mid n \in \mathbb{N}\right\}}$ \textbf{vi.) } & $\displaystyle{\left\{\sqrt[\uproot{1} \leftroot{-1} n]{n} \mid n \in \mathbb{N}\right\}}$ \end{tabular} \end{document} ```
Something like this? [![enter image description here](https://i.stack.imgur.com/Pq5rv.png)](https://i.stack.imgur.com/Pq5rv.png) ``` \documentclass{amsart} \usepackage{array} \newcolumntype{L}{>{$\displaystyle}l<$} \newcommand\mmid{\;\middle\vert\;} \begin{document} \noindent The following sets have either a least upper bound or a greatest lower bound of 1. \noindent\hspace{2em}% <-- added "\hspace{2em}" \setlength{\tabcolsep}{0.25in} \setlength{\extrarowheight}{3ex} \begin{tabular}{@{} *{2}{r@{\hspace{1em}}L} @{}} \textbf{i.)} & \left\{1 - \frac{1}{n} \mmid n \in \mathbb{N}\right\} & \textbf{ii.)} & \left\{1 + \frac{1}{n} \mmid n \in \mathbb{N}\right\} \\ \textbf{iii.)} & \biggl\{9\sum_{n=1}^{N} \frac{1}{10^{n}} \biggm|N \in \mathbb{N\biggr\} & \left\{1 - \left(\frac{1}{2}\right)^{n} \mmid n \in \mathbb{N}\right\} \\ \textbf{v.)} & \left\{\sqrt[\uproot{1} \leftroot{-1} n]{2} \mmid n \in \mathbb{N}\right\} & \textbf{vi.)} & \left\{\sqrt[\uproot{1} \leftroot{-1} n]{n} \mmid n \in \mathbb{N}\right\} \end{tabular} \end{document} ```