text
stringlengths
15
59.8k
meta
dict
Q: Images (inside divs) stacking instead of being inline I'm trying to place a series of images on my website, and I want them to flow side by side and automatically wrap to the width of the container div. I made a separate div for each image, because I also need text to stay with each image. However, my image divs are stacking (as if there were a hard return between each one, though there isn't), rather than flowing. I've been searching for the answer, and everything I've read says that the default positioning for a div is static, which means flow will be automatic. But... it's not seeming to work. Here's my HTML: <div id="contentArea"> <div id="frame2"> <div id="f2title"> <u>Everything Changed</u> <br> <i>A reflection on life's contingencies.</i> </div> </div> <a href="foreveramen.html"><div id="frame1"> <div id="f1title"> <u>Forever Amen</u> <br> <i>A wedding song, written for my brother and his wife.</i> </div> </div></a> <a href="friendswithyou.html"><div id="frame3"> <div id="f3title"> <u>Friends With You</u> <br> <i>Warm, caring friendships often happen without trying.</i> </div> </div></a> And here's my CSS: #contentArea { margin-top: 5px; margin-left: 45px; margin-right; 45px; overflow: auto; width: 540px; height: 590px; position: relative; background: rgba(255, 255, 255, 0.3); font-family:Cambria, "Avenir Black", Futura, "Gill Sans", sans-serif; font-size: 0.8em; } #frame1 { background-image:url(images/frame1thumb.png); width:250px; height:217px; } #f1title { width:140px; height:188px; margin-left:55px; margin-right:auto; margin-top:70px; font-size:14px; text-align:center; overflow:auto; position:absolute; } (And so on for the other frames. There's styling for frame 2, 3, and so on, and the only thing that changes is the width and positioning of the text inside the frame.) I tried typing position:static; into my CSS, under the #frame1 and it doesn't affect anything. Thanks! A: Okay, well first of all, here is a link to a working fiddle: jsfiddle What you need to do is, to give every element, you want to float a float: left; I would also give every #frame a position: relative; so that the #title's can position themselves according to their parent element. As @Antony also pointed out, you made a syntax error with margin-right; 45px;, the first semicolon should be a regular colon! A: I would first rethink your structure a bit. Here's how I would do it. You can use the link element itself for the thumbnail wrapper - and I would suggest you define the importance of the headings etc with heading tags. Search engines read sites like newspapers. If you don't declare importance, they wont know how to structure your site. I wouldn't use underline tag or italic tag because they are deprecated and I wouldn't use br linebreak because it's unnecessary and it's not really a line break. You can declare that in your .css file. jsfiddle HERE The magic is basically the float: left; but this will set you up with a more solid foundation. You see, for example - if you decided that you didn't want italics anymore - you would have to go remove all of those tags from the html. This way you only declare it in one place. Further more, styles that all of the blocks share need not be repeated. All blocks are the same I'm imagining. Mabybe they have different background-images.. but the rest is the same. Think modular. HTML <section class="content"> <a class="link-wrapper one" alt="song thumbnail" href="#"> <h2>Song Title</h2> <h3>Tag line etc I'm guessing</h3> </a> <a class="link-wrapper two" alt="song thumbnail" href="#"> <h2>Song Title</h2> <h3>Tag line etc I'm guessing</h3> </a> </section> CSS /* moves padding inside the box - start your project off right */ * { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } html, body { margin: 0; padding: 0; } .content { padding: 1em; } .link-wrapper { position: relative; display: block; float: left; width:250px; height:217px; text-align: center; margin-right: 1em; text-decoration: none; } .link-wrapper h2 { /* heiarchy of text importance is how SEO works */ font-weight: normal; text-decoration: underline; padding-top: 1em; } .link-wrapper h3 { /* heiarchy of text importance is how SEO works */ font-weight: normal; font-style: italic; } /* to differentiate + unique classes for thumbnails */ .one { background-image:url(http://placehold.it/250x217/ff0066); } .two { background-image:url(http://placehold.it/250x217/99edee); } I hope this helps. -nouveau
{ "language": "en", "url": "https://stackoverflow.com/questions/16877493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure filebeat to read log files from multiple linux servers I need to know how to configure filebeat to read log files from multiple linux servers. I tried this for multiple windows computers and it works fine. Following is the used paths to access multiple log files from multiple windows computers in the network. paths: - \\192.168.8.101\path\to\log\log.log - \\192.168.8.102\path\to\log\log.log - \\192.168.8.103\path\to\log\log.log I want to do the same for multiple linux hosts. What is the recommended way to do that?
{ "language": "en", "url": "https://stackoverflow.com/questions/58601853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading the default namespace through Roslyn API Is there a way to read the default namespace setting from the IProject interface or any other Roslyn interface? I know that I can parse the project's file but I think this should be possible using Roslyn API but I cannot find how to do that. Thanks in advance for information. A: Unfortunately, Roslyn does not expose a way to do that at the moment, but I agree that it is something we will probably need eventually. A: The library Microsoft.Build.Evaluation, which is, I believe, the successor of Roslyn does have this feature, but it is not easy to find. I use the code below to obtain the default namespace. My tests have shown that it matches the RootNamespace, stored in the .csproj file. private string GetDefaultNamespace(Microsoft.Build.Evaluation.Project p) { string rtnVal = "UNKNOWN_NAMESPACE"; foreach (ProjectItemDefinition def in p.ItemDefinitions.Values) { if (def.ItemType == "ProjectReference") { foreach(ProjectProperty prop in def.Project.AllEvaluatedProperties){ if(prop.Name == "RootNamespace"){ rtnVal = prop.EvaluatedValue; } } } } return rtnVal; }
{ "language": "en", "url": "https://stackoverflow.com/questions/15132175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change ganache Owner Account in WEB3J from account[0] to account[1]or account[2] I'm looking for a way to change owner of the smart contracts in java web3j as we do in web3 javascript using from: getMetaskAccountID: function () { web3 = new Web3(App.web3Provider); // Retrieving accounts web3.eth.getAccounts(function(err, res) { if (err) { console.log('Error:',err); return; } App.metamaskAccountID = res[0]; if (res.length > 1){ document.getElementById("divType").innerText = "Ganache Address" console.log("Using Ganache"); App.FirstID = res[1]; document.getElementById("account1").value = App.account1; App.secondID = res[2]; document.getElementById("account2").value = App.account2; }else{ document.getElementById("divType").innerText = "Using MetaMask Address" App.account1 = document.getElementById("account1").value; App.account2 = document.getElementById("account2").value; } }) } //using account for transaction in javascript await contract.function(param1, param2, {from: account1}); await contract.function(param1, param2, {from: account2}); I can't find any solution regarding this for java web3j to change account for transaction. contract.function(param1, param2).sendAsync(); It uses default account[0] for all the transactions. I want to change the owner for various transctions. Would be nice to get a suitable answer for web3j to change account, thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/73897199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL How to find which customer has rented the most films? I'm struggling with a question that said Which customer has rented the most films? I am doing this using the Seikila sample database in MySQL. I have something that joins my tables together and attempts to give me a count but I know its wrong just looking at the actual data in the rental table. my code is as below SELECT r.rental_id, cust.customer_id, count(*) as Total_Rentals FROM rental as r INNER JOIN customer AS cust on r.customer_id = cust.customer_id GROUP BY cust.customer_id; but it tells me for example customer 1 has rented 32 movies, which I know is wrong. what am I doing wrong? since I was asked for clarification, the database I am using is: https://dev.mysql.com/doc/sakila/en/ And I am trying to find which customer has rented the most films, I am not entirely sure what my script is actually returning. A: Remove the column rental_id from the select list and sort the result by count(*) descending to return the top 1 row: SELECT cust.customer_id, cust.name, count(*) as Total_Rentals FROM rental as r INNER JOIN customer AS cust on r.customer_id = cust.customer_id GROUP BY cust.customer_id, cust.name ORDER BY Total_Rentals DESC LIMIT 1 But if you only need the customer's id then there is no need for a join: SELECT customer_id, count(*) as Total_Rentals FROM rental GROUP BY customer_id ORDER BY Total_Rentals DESC LIMIT 1 A: You need to join customer and rental, group by customer id (without rental id) and count it: SELECT cust.customer_id, count(*) as Total_Rentals FROM rental as r INNER JOIN customer AS cust on r.customer_id = cust.customer_id GROUP BY cust.customer_id; So this code should work. If it doesn't work, that probably means that you have duplicates or other nonconventional issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/60792314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: CSS: Overlay two images perfectly on all screen sizes I have two images. One is a picture that has rounded edges, the other is a picture of a round frame. I want to place the frame over the picture so that it looks like it is a single image. I am struggling with the CSS to do this because on different screen sizes, it does not remain constant. Here is my HTML: <div class="image"> <img src="picture.png" id="profile"/> <img src="frame.png" id="frame"/> </div> My CSS: div.image {position: relative;} img#profile {width: 250px; border-radius: 50%} img#frame {width: 250px; position: absolute; z-index: 100;} I want the result to look like this (the blue is the picture #profile and the orange is the frame #frame: In addition, this needs to stay this way regardless of the screen size so using left values does not really work. With the above markup, the images are doing this: How do I solve this? A: You didn't provide any pictures. So, I used css styles. You can remove the background color and add your pic urls. div.image { position: relative; } img#profile { width: 250px; height: 250px; background: blue; border-radius: 50%; z-index: 100; left: 10px; top: 10px; position: absolute; } img#frame { width: 270px; height: 270px; background: tomato; border-radius: 50%; z-index: -1; } JSFIDDLE A: You need to fix it yourself whenever you change the size. div.image { position: fixed; margin: 100px; } img#profile { width: 250px; height: 250px; background: skyblue; border-radius: 100%; z-index: 100; position: absolute; } img#frame { width: 270px; height: 270px; background: orange; border-radius: 100%; z-index: -1; position: absolute; top:-10px; left:-10px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/41956792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can we fliter data from header's TextInput on onChangeText in react native? I have custom header which has TextInput for searching in StackNavigator.How can i get result on onChangeText of TextInput on particular class, here is demo: const StackNavigator = createStackNavigator({ TABS: { screen: TabNav, navigationOptions: ({ navigation }) => { return { header: <View style={{ backgroundColor: '#025281', flexDirection: 'row', alignItems: 'center', height: 60 }}> <TouchableOpacity style={{ paddingLeft: 5 }}> <Image source={require(back_arrowimg)} style={{ width: 25, height: 25, resizeMode: 'contain' }}/> </TouchableOpacity> <TextInput style={{ color: 'white', paddingLeft: 15, }} type='text' placeholder={headerTitle} onChangeText={this.loadUsers} /> </View>, } } }, [ConstFile.SCREEN_TITLES.WELCOME_SEARCH]: { screen: WELCOMESEARCH, navigationOptions: { header: null } }, } ) A: from navigationOption you can not do anything to other screen, so what you can do is, move your header code into another file and use it as component in TabNav something like this, let say Header.js <View style={{ backgroundColor: '#025281', flexDirection: 'row', alignItems: 'center', height: 60 }}> <TouchableOpacity style={{ paddingLeft: 5 }}> <Image source={require(back_arrowimg)} style={{ width: 25, height: 25, resizeMode: 'contain' }}/> </TouchableOpacity> <TextInput style={{ color: 'white', paddingLeft: 15, }} type='text' placeholder={headerTitle} onChangeText={this.props.loadUsers} // see this change /> </View> and in your TabNav.js use header as component, <Header loadUsers={(...your params)=>{ //do your necessary stuffs to display data in this file }) />
{ "language": "en", "url": "https://stackoverflow.com/questions/55016836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a as a new row using external css? I am new to stack overflow and I'm trying to make a mobile webpage from the existing desktop version webpage someone else created. Basically, I have to use same webpage for both mobile and desktop. For this specific page with table, I am trying to change the pattern of table for mobile using external style sheet.I had attached the html skeleton and css with this post. Initially, there is only one row with two s. I want to bring ".td2" to new in next line. I tried a basic table in which I was able to bring down all converted to tr worked but in this case, second containing a table is making me hard. I tried all the way I could. I will be helpful if someone help me. tr{ display:table; width:100%; } .lfttbl .td1, .td2{ display:table-row; border-bottom: solid 1px #2b9ed5 !important; } <table class="out"> <tr><td> <table class="outtbl"> <tr> <td> <table class="lfttbl"> <tr> <td class= td1> <p> hihi hii </td> <td class= td2> <table class = rttbl""> </table> </td> </tr> </table> </td> </tr> </table> A: There are a lot of bugs in your code: * *<p> not closed! *Using tables for layout. *More worse: Using nested tables. Going ahead with your layout, I was able to make these corrections to make it work in CSS. tr{ display:table; width:100%; } .lfttbl .td1, .td2{ display:table-row; border-bottom: solid 1px #2b9ed5 !important; } .td1 { display: block; background: #f00; } <table class="out"> <tr><td> <table class="outtbl"> <tr> <td> <table class="lfttbl"> <tr> <td class= td1> <p> hihi hii</p> </td> <td class= td2> <table class = rttbl""> </table> </td> </tr> </table> </td> </tr> </table> A: You must close your <p>hihi hi and use display: block; on the td. Check this: tr{ display:table; width:100%; } .lfttbl .td1, .td2{ display:block; border-bottom: solid 1px #2b9ed5 !important; } <table class="out"> <tr><td> <table class="outtbl"> <tr> <td> <table class="lfttbl"> <tr> <td class= td1> <p> hihi hii</p> </td> <td class= td2> <table class = rttbl""> <p>Lorem ipsum</p> </table> </td> </tr> </table> </td> </tr> </table> A: So, here is what I was struggling on. After several trials and errors, I came to know it works in desktop version now but not in mobile devices. I had attached my code and css on which I was working (Initially "edit" and "delete" were in different td). Now I don't know why its not working on mobo device. I know I can't use if else statement in css (either for desktop or for mobile). #shipIMtd, #shipIMrighttd1, #shipIMrighttd2{display:block;} <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0;"> <link href="mno.css" rel="stylesheet" type="text/css" /> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <META Name="Robots" Content="noindex"> </head> <table id="shipIMmaintbl" width="100%" cellpadding="0" cellspacing="0"> <tr><td align="center"> <table id= "shipIMsubtbl" border="0" width="940"> <tr> <td valign="top" align="center" width="80%"> <div id="shipIMmidacdiv" class="account-mid"><br /> <table width="95%" border="0" cellspacing="0" cellpadding="0" id="table12"> <tr> <td> <table id="shipIMshipadtbl" width="735px" style="width:735px;border:solid 1px #D4D6D8;margin-bottom:15px;"> <tr> <td id="shipIMsubtitle" valign="top" style="border-right: solid 1px #E7E4E4;padding:5px;"><span style="font:600 18px verdana;#2972B6"><strong> Addresses</strong></span></td> <td height="35" align="left" bgcolor="#F6F4F4" class="padd-top-lt">&nbsp;</td> <div id="shipIMtitlediv" class="floatright newAddrBtn"><a href="uvx.asp"><input id="shipIMtitlebtn" type="button" value="+ Add"></a></div> </div> </tr> <tr id="shipIMshipaddtr"> <td id="shipIMtd" valign="top" style="border-right: solid 1px #E7E4E4;width:200px;padding:15px;"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi.</p> </td> <td id="shipIMrighttd1" align="left" class="padd-15 border-tbt1"> <table id="shipIMeditship" cellpadding=3 cellspacing=0 border=0 width=80><tr><td> <form name="editship" action="abc.asp" method="post" /> <input type="hidden" name="shipID" value="shpid"> <input id="shipIMeditbtn" type="submit" value="Edit"> </form> </td><td id="shipIMrighttd2"> <form name="deleteship" action="xyz.asp" method="post"> <input type="hidden" name="shipID" value="shpid" /> <input type="hidden" name="asktype" value="firstask"> <input id="shipIMdelbtn" type="submit" value="Delete"> </form> </td></tr></table> </td> </tr> </table> </td> </tr> </table> </div> </td> </tr> </table> </body> </html> .
{ "language": "en", "url": "https://stackoverflow.com/questions/30942369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server : Join from multiple table references Forgive me for adding yet another JOIN question, but I've been stumped all day and haven't been able to find a good answer for this. I'm trying to join 4 tables, such that they look like below: QuarterID ReviewID SaleID PotentialID 1 1 1 1 1 2 2 null 1 3 null 2 1 4 null null The relevant info from the tables is below Sale: QuarterID ReviewID IsArchived Potential: QuarterID ReviewID IsArchived Quarter: ID Review: ID We can have multiple Sales and Potentials associated with one Quarter-Review pairing, but only one Sale and one Potential will have IsArchived = 0 for the given Quarter-Review pairing. SELECT quarter.id AS QID, review.id AS RID, Sales.id AS SID, Potentials.id AS PID FROM dbo.quarter JOIN (SELECT * FROM dbo.sale WHERE isarchived = 0) AS Sales ON Sales.quarterid = quarter.id JOIN (SELECT * FROM dbo.potential WHERE isarchived = 0) AS Potentials ON Potentials.quarterid = quarter.id JOIN dbo.review ON dbo.review.id = Sales.reviewid AND dbo.review.id = Potentials.reviewid ORDER BY quarter.id, rid Using the above (there are some unnecessary columns, I know), I've managed to get the joins so that they get the 1st condition (where its all the Sales and Potentials that are in the same Quarter and Review combination, but I also want to see if there is a Quarter/Review combo with only a Sale and no Potential, if there is a Q/R combo with only a Potential and no Sale, and just every Quarter and Review combo, since there are only a few Q/R combos that have both a Sale and Potential, with almost all of the Q/R combos only having a Sale or Potential. I guess overall the difficulty comes from needing to get the join from two intermediate tables. I can join Quarter, Sale, and Review easily, but having the Potential table joining on the same fields (ReviewID, QuarterID) as Sale is making me only get the AND, and I can't figure out an OR. I've been throwing around ORs for hours trying to get the right sequence without any luck. Help? --Edit to include sample data-- Quarter ID 1 2 Review ID (Other fields, not relevant to join) 1 2 3 4 5 Sale ID ReviewID QuarterID isArchived (Other fields, not relevant) 1 1 1 0 2 2 1 1 3 2 1 0 4 1 2 0 5 5 1 0 6 5 2 0 Potential ID ReviewID QuarterID isArchived (Other fields, not relevant) 1 1 1 0 2 3 1 0 3 4 2 1 4 4 2 0 5 5 2 0 Joining the above sample data, I would expect the output to look like: QuarterID ReviewID SaleID PotentialID 1 1 1 1 1 2 3 null 1 3 null 2 1 4 null null 1 5 5 null 2 1 4 null 2 2 null null 2 3 null null 2 4 null 4 2 5 6 5 But the problem I am having is I am only returning the rows like the first and last row, where there is both a Sale and Potential for a given Quarter/Review combo, and not the ones where one or many may be null. A: Not sure if I understood your question correctly (some sample data will help) but I think you mean that you need all the combinations of Quarter and Review and then any related Sale and Potential data for each combination of Quarter and Review. If that is what you need, then try the below query: SELECT [Quarter].ID AS QID, Review.ID AS RID, Sales.ID AS SID, Potentials.ID AS PID FROM [Quarter] CROSS JOIN [Review] LEFT JOIN (SELECT * FROM Sale WHERE IsArchived = 0) Sales ON [Quarter].ID = Sales.QuarterID AND [Review].ID = Sales.ReviewID LEFT JOIN (SELECT * FROM Potential WHERE IsArchived = 0) Potentials ON [Quarter].ID = Potentials.QuarterID AND [Review].ID = Potentials.ReviewID
{ "language": "en", "url": "https://stackoverflow.com/questions/36024453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding the points of contact between two convex polygons Okay, so I am trying to create a simple 2d polygon physics engine for the experience. Here is what I already know (plus sources for those who want to find out: -How to determine if polygons are intersecting using the SAT method (http://elancev.name/oliver/2D%20polygon.htm) -How to find the normal of the collision by finding the minimum translation axis -How to respond to a collision via implulse (http://chrishecker.com/Rigid_Body_Dynamics#articles) There is one thing however that keeps eluding me. That is, how to find the points of contact between two intersecting polygons. I was going to upload a simple picture to help illustrate what I mean, but it seems like I am not able to do that yet. Specifically what I would like help on is: -Determining which sides and/or points are colliding -This includes when the polygons are intersecting -Getting a vector location of each contact point I would really appreciate anything on this because I have been searching for a good while with no luck. Thanks. A: After doing some more digging I found what I was looking for. I found a rather well written example (in C#) of a technique called polygon clipping. This method finds the contact points in world coordinates. It goes through all the steps and code implementation for multiple different situations. Here is the url: http://www.codezealot.org/archives/394
{ "language": "en", "url": "https://stackoverflow.com/questions/16074548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: -libraryjars has no effect on resulting apk, proguard using the tools dex2jar and Java Decompiler I examined two versions of an apk file that was built in eclipse with proguard enabled. One version of the apk was made with this command as part of proguard-project.txt file -libraryjars /libs/GraphView-3.1.1.jar and in the other verson of the apk has this line commented out looking at the resulting apk files after conversion from apk to jar and viewing them. both of the apk files are obfuscated however they are exactly the same. so the -libraryjars command is having no effect at all? why is the obfuscated code exactly the same in both cases? in comparison I make two versions of apk files with other modifications and they result in different looking files. for example I added this line to the proguard-project.txt file -keep class com.example.proguardwithgson.MainActivity$TestObject { *; } and it changed the resulting code for the apk, the TestObject inner class is no longer obfuscated and is clearly readable. if the -keep command is working, then why does the -libraryjars command not do anything? A: The Android build process already specifies all the necessary -injars/-libraryjars/-outjars options for you. You should never specify them in your configuration file; you'd only get lots of warnings about duplicate classes. You can find an explanation of their purpose in the ProGuard manual > Introduction.
{ "language": "en", "url": "https://stackoverflow.com/questions/22475414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can an SKSpriteNode Object be Searched by Name I am creating a game using Apple's SpriteKit, and I am wondering what is the most efficient way to find an SKSpriteNode object after creating it. In one method I initialize a sprite node and assign a name to it: SKSpriteNode* playerBody = [SKSpriteNode spriteNodeWithImageNamed:@"playerBody.png"]; playerBody.name = @"player"; Later on inside the touchesBegan:withEvent: method I want to find the previously defined sprite node again and store it so I can run actions on it. First I attempted to do this: SKSpriteNode* body = [self childNodeWithName:@"player"]; However, I have realized that childNodeWithName: is only available in the SKNode class, not SKSpriteNode. So this does not work. What I am thinking now is that I can create an SKNode object and place my SKSpriteNode inside of it. This way I can search for the SKNode using the above method. This seems a bit convoluted, however. Is there a better way? A: SKSpriteNode inherits from SKNode. You can use childNodeWithName. SKSpriteNode *someSprite = [SKSpriteNode node]; [someSprite childNodeWithName:@"someChildOfSprite"]; Code for comment below asking how to cast SKNode as an SKSpriteNode: SKSpriteNode *theChildYouWant = (SKSpriteNode*)[someSprite childNodeWithName:@"someChildOfSprite"];
{ "language": "en", "url": "https://stackoverflow.com/questions/24224180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python tuple duplication with * This works just fine and straight-forward: >>> ('a',) * 3 ('a', 'a', 'a') But I was experimenting with tuple a little and came across this: >>> 'a', * ('b', 'c') ('a', 'b', 'c') >>> ('a',) * ('b', 'c') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> ('a',) * ('b', 'c') TypeError: can't multiply sequence by non-int of type 'tuple' Can anybody explain how did the * make the tuple concatenate in the line 'a', * ('b', 'c')? A: In this expression 'a', * ('b', 'c') You have two primary things going on * *'a', creates a tuple with a single element 'a' ** ('b', 'c') uses extended iterable unpacking (PEP 3132) So the result of #2 is used to continue the tuple definition from #1. To show a more intuitive example this is the same idea >>> 'a', *range(5) ('a', 0, 1, 2, 3, 4)
{ "language": "en", "url": "https://stackoverflow.com/questions/74129807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error in google map loading I got this crash when Try to start any map activity .. this is my gradle dependencies: dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.jakewharton:butterknife:7.0.1' compile 'com.android.support:design:23.4.0' compile 'com.facebook.android:facebook-android-sdk:4.5.0' compile 'de.hdodenhof:circleimageview:2.1.0' compile 'com.mcxiaoke.volley:library-aar:1.0.0' compile 'cn.pedant.sweetalert:library:1.3' compile 'com.squareup.picasso:picasso:2.3.2' compile 'com.android.support:support-v4:23.4.0' compile 'com.android.support:multidex:1.0.0' compile 'com.google.android.gms:play-services-location:8.4.0' compile 'com.android.support:cardview-v7:23.4.0' compile 'com.melnykov:floatingactionbutton:1.3.0' compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2' compile 'com.google.code.gson:gson:2.7' compile 'com.google.android.gms:play-services-maps:8.4.0' compile 'com.google.android.gms:play-services-gcm:8.4.0' compile 'com.onesignal:OneSignal:3.4.1' compile 'com.wang.avi:library:1.0.3' compile 'com.nineoldandroids:library:2.4.0' } this is logcat 11-05 10:00:19.603 10285-10285/com.wneet.white E/AndroidRuntime: FATAL EXCEPTION: main Process: com.wneet.white, PID: 10285 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wneet.white/com.wneet.white.LoadingFirst}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2578) at android.app.ActivityThread.access$900(ActivityThread.java:170) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:146) at android.app.ActivityThread.main(ActivityThread.java:5727) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.wneet.white.LoadingFirst.onCreate(LoadingFirst.java:88) at android.app.Activity.performCreate(Activity.java:5581) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2483) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2578)  at android.app.ActivityThread.access$900(ActivityThread.java:170)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:146)  at android.app.ActivityThread.main(ActivityThread.java:5727)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:515)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)  at dalvik.system.NativeStart.main(Native Method)  thanx in advance. A: Please check and make sure that you were able to set up your project with a compatible Google Play services SDK as discussed in Setting Up Google Play Services. If you haven't installed the Google Play services SDK yet, go get it now by following the guide to Adding SDK Packages. Solutions given in this blog post and GitHub post might also give you possible workaround and might help.
{ "language": "en", "url": "https://stackoverflow.com/questions/40435444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there an async-safe way to get the current thread ID in Linux? Is there any way to get the current thread ID from a signal handler in Linux? The getpid() method does what I want, but it is not clear if it is async-safe. man 7 signal provides a list of POSIX methods which are async safe, but this tells us nothing about non-POSIX methods such as getpid(). Presumably some of the many non-POSIX methods Linux has added are async safe, but I can't find the list. There is also this answer which claims that all direct (not multiplexed) syscalls are async safe, but provides no evidence. The goal is to build some kind of async-safe thread local storage, since __thread is not safe in the general case. It doesn't have to be the "Linux thread ID" - any consistent thread ID would be fine. For example pthread_self would be great, but there is nothing claiming that is async safe. If we examine the implementation of that method in glibc Linux, it defers to the THREAD_SELF macro, which looks like: # define THREAD_SELF \ ({ struct pthread *__self; \ asm ("movl %%gs:%c1,%0" : "=r" (__self) \ : "i" (offsetof (struct pthread, header.self))); \ __self;}) It seems to be that this should be async-safe, if the thread in question was created under a regime that populates the gs resgister (perhaps all threads in Linux are, I'm not sure). Still looking at that header makes me pretty scared... A: As mentioned in Async-signal-safe access to __thread variables from dlopen()ed libraries? you provided (emphasis is mine): The __thread variables generally fit the bill (at least on Linux/x86), when the variable is in the main executable, or in a directly-linked DSO. But when the DSO is dlopen()ed (and does not use initial-exec TLS model), the first access to TLS variable from a given thread triggers a call to malloc... In other words, it only requires one access to that thread specific variable to bring it to life and make it available in signal handlers. E.g.: * *Block the signals you are interested in in the parent thread before creating a child thread. *Unblock those interesting signals in the parent thread after the call to pthread_create. *In the child thread initialize your __thread variable and unblock those interesting signals. I normally store the write end of a unix pipe in that tread-specific variable and the signal handler writes the signal number into that pipe. The read end of the pipe is registered with select/epoll in that same thread, so that I can handle signals outside of the signal context. E.g.: __thread int signal_pipe; // initialized at thread start extern "C" void signal_handler(int signo, siginfo_t*, void*) { unsigned char signo_byte = static_cast<unsigned>(signo); // truncate ::write(signal_pipe, &signo_byte, 1); // standard unix self pipe trick }
{ "language": "en", "url": "https://stackoverflow.com/questions/21743889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How Get xml content from xml Ip api and display it on webpage? I am using XML api of http://ip-api.com/docs/api:xml on my webpage to get information about a visiter visiting my website. following is the successful xml document returned from their api : <country>United Kingdom</country> <countryCode>UK</countryCode> <region>Bristol</region> <ip>xx.xx.xx.x</ip> <ISP>VodafoneM</ISP> I want to show content of this xml document on my webpage using javascript, I know it can easily be done using a server side language like PHP, My php version is old and it's returning error for parsing an xml document. So I am looking for a client side solution. Here is what I have tried so far : <script> xmlDoc=loadXMLDoc("http://ip-api.com/xml/xx.xx.xx.x"); x=xmlDoc.getElementsByTagName("country")[0]y=x.childNodes[0]; document.write(y.nodeValue); </script> It doesn't work, I am getiing a blank page. How can I display the content of xml file on my webpage? Please help me, I have been trying to solve this since morn A: I have adapted your code as follows: //txt = loadXMLDoc("http://ip-api.com/xml/xx.xx.xx.x"); var txt = '<country>United Kingdom</country><countryCode>UK</countryCode><region>Bristol</region><ip>xx.xx.xx.x</ip><ISP>VodafoneM</ISP>'; txt = '<query>' + txt + '</query>'; // Info: http://www.w3schools.com/xml/xml_parser.asp if (window.DOMParser) { parser = new DOMParser(); xmlDoc = parser.parseFromString(txt, "text/xml"); } else // Internet Explorer { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = false; xmlDoc.loadXML(txt); } var x = xmlDoc.getElementsByTagName("country")[0]; var y = x.childNodes[0]; //document.write(y.nodeValue); document.getElementById("content").innerHTML = y.nodeValue; Please check the result in jsfiddle.
{ "language": "en", "url": "https://stackoverflow.com/questions/31514556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trigger to enforce M-M relationship Suppose I have following schema : DEPARTMENT (DepartmentName, BudgetCode, OfficeNumber, Phone) EMPLOYEE (EmployeeNumber, FirstName, LastName, Department, Phone, Email) The problem am facing is how to design a system of triggers to enforce the M-M relationship.Assuming that departments with only one employee can be deleted. Also I need to assign the last employee in a department to Human Resources. I have no idea to enforce M-M relationship through trigger. Please help A: Many-to-many conditions should not be enforced using a trigger. Many-to-many conditions are enforced by creating a junction table containing the keys in question, which are then foreign-keyed back to the respective parent tables. If your intention is to allow many employees to be in a department, and to allow an employee to be a member of many departments, the junction table in question would look something like: CREATE TABLE EMPLOYEES_DEPARTMENTS (DEPARTMENTNAME VARCHAR2(99) CONSTRAINT EMPLOYEES_DEPARTMENTS_FK1 REFERENCES DEPARTMENT.DEPARTMENTNAME, EMPLOYEENUMBER NUMBER CONSTRAINT EMPLOYEES_DEPARTMENTS_FK2 REFERENCES EMPLOYEE.EMPLOYEENUMBER); This presumes that DEPARTMENT.DEPARTMENTNAME and EMPLOYEE.EMPLOYEENUMBER are either primary or unique keys on their respective tables. Get rid of the column EMPLOYEE.DEPARTMENT as it's no longer needed. Now by creating rows in the EMPLOYEES_DEPARTMENTS table you can relate multiple employees with a department, and you can relate a single employee with multiple departments. The business logic requiring that only departments with one or fewer employees can be deleted should not be enforced in a trigger. Business logic should be performed by application code, NEVER by triggers. Putting business logic in triggers is a gatèw̢ay to unending debugging sessions. M̫̣̗̝̫͙a̳͕̮d̖̤̳̙̤n̳̻̖e͍̺̲̼̱̠͉ss̭̩̟ lies this way. Do not give in. Do not surrender. ̬̦B҉usi͢n̴es̡s logic ̶in triggers opens deep wounds in the fabric of the world, through which unholy beings of indeterminate form will cross the barrier between the spheres, carryi͞n̨g o̡f͠f t͢h̶e ̕screaming͡ sou͏ĺs o͜f͜ ̢th͜e̴ ̕de͏v́e̡lop͏e͜r͝s to an et͞er͜n̸it̶y ́of͢ pain̶ ąn̨d͢ ̨to͟r̨ment͟. Do not, as I have said, put b́u͜siness͞ ̸log̛i͘ç ̵in͢ ͞trigge͠rs͞.̡ Be firm. Resist.You must resist. T̷he ̢Tem͟p͞t̶at͏i͝o̶n҉s͘ ̢m͘a̶y ́śing hymns̷ ́o͢f̴ ̸un͘hol̵y r̶ev͢ęla͠t̡ion̴ ͢buţ ́yo͠u̵ mu͏s͝t ͝n͜͏͟o҉t̶͡͏ ̷l̸̛͟͢ì̧̢̨̕s̵̨̨͢t̵̀͞e̶͠n̶̴̵̢̕. Only by standing firmly in the door between the worlds and blocking out the hideous radiance cast off by bú̧s̷i̶̢n̵̕e̵ş͝s ́l̴ó̢g̛͟i̕͏c i͞n̕ ͏t̵͜r͢͝i̸̢̛ģ͟ge̸̶͟r̶s͢͜, which perverts the very form of the world ąnd̴̀͝ ç͞a̧͞l̶l͟͜s̕͘͢ Z̶̴̤̬͈̤̬̲̳͇ͯ̊ͮ͐̒̆͂͠Â̆́̊̓͛́̚͏̮̘̗̻̞̬̱ͅL̛̄̌͏̦͕̤͎̮̦G̷͖̙̬͛̇ͬ̍͒̐̅O̡̳͖͎̯̯͍ͫ̽ͬ͒͂̀ i͜҉nt͝ǫ̴ ̸b̷͞è͢ì̕n̴g͏,̛̀͘ ̴c҉á̴͡ń ̀͠youŕ̨ ̧̨a̸p͏̡͡pl̷͠ic͞a̢t̡i͡҉ǫn̴ ̸s̶͜u̶͢ŗv̛í̴v́ȩ.͘͘ Resist. R͏͢͝e͏͢͟s̸͏͜ì̢̢s͠ţ̀. T̶̀h̨̀e̶r̀͏e͢͞ ̶i̶̡͢s̴ ͞͞n̵͝o̡ ́ẁ҉̴a̡y̕҉ ̶b́͏u̵̶̕t͜ ̨s͘͢t͘͠į͟l͘l̷̴ ̴͜͜ỳò͜u҉̨ ̨͏mus̸͞t̸̛͜ ̧rȩ̴s̢͢i͘͡s͏t̸.̛̀͜ Your very śo͡u̧̧͘ļ͟͡ is compromised by p͝u͘͝t̢͜t͠i̸ņ̸̶g͟͡ ̵̶̛b̴҉u̶̡̨͜͞s̷̵̕͜͢i͝҉̕͢ǹ͏e̡͞ś̸͏ş̕͜͡҉ ̴̨ĺ̵̡͟͜o̶̕g͠i͢͠c̕͝ ̕͞i̧͟͡n̡͘͟ ̶̕͞t̡͏͟҉̕r̸̢̧͡͞i̴̡͏̵͜g̵̴͟͝ģ̴̴̵ę̷̷͢r̢̢ś̸̨̨͜. T̀͜͢o̷͜ny̕ ͟͡T̨h̶̷̕e ̢͟P̛o̴̶n͡y shall rise from his dark stable and d͞ę̡v̶̢ó͟u̸̸r̴͏ ̷t͞h̀e̛ ̨͜s̷o̧͝u҉l̀ ͟͡o͢͏f̵͢ ̛t͢h̶̛e̢̢ ̡̀vi͜͞r̢̀g̶i̢n͞, and yet y͢ơú͝ m̷̧u͏s͡t̡͠ ̛s̷̨t̸̨i̴̸l̶̡l ͝ǹot̵ ͞p̧u̵t̨ ͜͏b̀̕u̕s̨í̵ņ̀͠ȩs̵͟s ́͞l̛҉o̸g̨i̴͟c ͘͘i͘nt̛o͡ ͘͘͞t̶͞r̀̀i̕ǵ̛g̵̨͞e̸͠҉r̵͟ś! It is too much to bear, we cannot stand! Not even the children of light may put business logic into their triggers, for b̴̸̡̨u͜͏̧͝ş̶i̷̸̢̛҉ń̸͟͏́e̡͏͏͏s̷̵̡s̕͟ ͏̴҉͞l̷̡ǫ̷̶͡g҉̨̛i͘͠͏̸̨c̕͢͏ ̸̶̧͢͢i̸̡̛͘n͢͡ ̀͢͝t̷̷̛́ŗì̴̴̢g̶͏̷ǵ͠ȩ̀́r̸̵̢̕͜s͞͏̵ is the very es̵s̕͡ę̢n͞c̨e̢͟ ̴o̶̢͜f͏ ͟d́ar͟͞͠k̡͞n̢̡es̵̛͡s̀̀͡ and dev͘ou͝͡r̨̡̀s͢͝ ҉͝t҉h̴e̡͘ l̫̬i̤͚ͅg̞̲͕̠͇̤̦̹h̩̙̘̭̰͎͉̮̳t͙̤̘̙! Yea, yea, the blank-faced ones rì͢s̨͘e from the f͟͢͏o̵͜͝n̶t̨ ̵o͏f̸̡͠ ͏͝fl͟͞a̵̷҉me̶̵͢ and ca͝s͜t́ down the p̹̤̳̰r̮̦̥̥̞̫͑͂ͤ͑ͮ͒̑ï̄̌ͬͨe̦̗͔ͥͣ̆̾̂s̬̭̮̮̜ͭt̻̲̍sͫͣ̿ ̐͗̈ͤ͂ͦ̅f̭͚̪̻̣̩ͮ̒ṟͨ͌ͮ̅̓ỏ̝͓̝̣̟̼m̳͇̱̝͔͒ ͒ͫͧ͂̓̈̈́t̲̔̅̎͐h̺͈͍ͣͧ̿ē̪̼̪̻͉̪̙̐̽̎̉i̠͎̗͕̗̣̬̐̎͛r͓̫͌ͅ ̼a͑̈ͯͦ̍l̪͉͖̥͚̤͌ͨ͊ͦͤ̔t̫͎̹ͯa̼̻͍̳̟̤̬̓ͪ̀r̭͖̓ͬ̉̉ͤ͊ṡ̐ͪ̊̋̄̅! A̵̵̛v͝é͜ŕt̶͏ ̶y̸͝͠o̶u̧͘r͏̡ ̧e͞y҉e̕͝s,̀ ͡t̛h̛o̢͞ug̸̢h̵͟ ̡y̷o͢҉͢u̧͡ ̕͡c҉̵̶an͠͏n҉o̧͢t!̸̨͘ ͡H̵e̸͢͡ ̧̕c̶ơm̷̢̢e̶͞ś͢!̨́ ̷H̕ȩ ̵c̨̡͟o̴҉m̷͢es͠!̷͘͞ P̱̼̯̟͈h̝̳̞̖͚'͉̙͉̰̲̺n̪̦͕̗͜g͔̹̟̰̰̻̩l̬͈̹̥͕͖ͅụ̻̺̤̤̬̳i̸̯̬̝̻̣͚̫ ̰̹̞̞m͟g̷̝͓͉̤l̩͇̙͕w̪̦̰͔'̮̟̱̀n̢̜a̦f̘̫̤̘̬͓̞h̠͍͖̯ͅ ̩̠͓̯̘̫C̟̘̗̘͘ṭ͍͕ͅh̤ͅu̼̦̘̥ͅl҉̦hu̠̤̤̘͚ ̘̕R̶̟'̠͔̞̻͇l̩̺̗̻͖͓̕ͅy̛̖ȩ͉̭̖ẖ̡̥̼͈̖ w̟̫̮͇͔͞ͅg͈̘̱̻a̰͟h̘͙͖͢'̮̲̯͞n̤̜͍̯̳a͓͓̲̲g̱̻͈ĺ͍ ̷̣̞̲͖͍̲̺f̲ͅh͇͕̪̘͟t͔͈̙a͓͢g҉̳̜̲͚n͓͚͎̱̠̜! Don't ask me how I know. Best of luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/31998789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove server from react-boilerplate How should one do to remove server folder from react-boilerplate? Question is also asked here by another person https://github.com/react-boilerplate/react-boilerplate/issues/2110. A: Removing just server folder will not work because the webpack dev configuration is utilising it for hot reload as well as your npm start command starts express server from this folder. If you want to remove server folder completely and still want the application to be working as it was like hot reloading etc, follow the below steps. We will require webpack dev server in that case: * *Remove ./server folder manually. *Install webpack-dev-server and react-hot-loader as dev dependencies. *In your ./internals/webpack/webpack.dev.babel.js, do the following modifications: * *Change entry to this: entry: [ require.resolve('react-app-polyfill/ie11'), 'react-hot-loader/patch', `webpack-dev-server/client?http://localhost:3000/`, 'webpack/hot/only-dev-server', path.join(process.cwd(), 'app/app.js'), // Start with js/app.js ], *Add publicPath in output: output: { filename: '[name].js', chunkFilename: '[name].chunk.js', publicPath: `http://localhost:3000/`, }, *Add webpack dev server config property in the same file: devServer: { port: 3000, publicPath: `http://localhost:3000/`, compress: true, noInfo: false, stats: 'errors-only', inline: true, lazy: false, hot: true, open: true, overlay: true, headers: { 'Access-Control-Allow-Origin': '*' }, contentBase: path.join(__dirname, '..', '..', 'app', 'build'), watchOptions: { aggregateTimeout: 300, ignored: /node_modules/, poll: 100, }, historyApiFallback: { verbose: true, disableDotRule: false, }, }, *In ./internals/webpack/webpack.base.babel.js, add the line: devServer: options.devServer, And finally, modify your start script in package.json as below: "start": "cross-env NODE_ENV=development node --trace-warnings ./node_modules/webpack-dev-server/bin/webpack-dev-server --color --config internals/webpack/webpack.dev.babel.js", And you are good to go!! A: Just remove with rm -rf ./server if you feel harassed :)
{ "language": "en", "url": "https://stackoverflow.com/questions/53066145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Case Statement Block Level Declaration Space in C# Is there a reason I am missing that a block within a case statement isn't considered a block level declaration space? I keep getting an error (variable has already been declared) when I try case x: var someVariable = 42; break; case y: var someVariable = 40; break; but I can do case x: try{var someVariable = 42;}catch{} break; case y: try{var someVariable = 40;}catch{} break; If C# allowed fall through statements, that would make sense, but it doesn't, and I can't think of a scenario where you can declare a variable in a case statement and use it outside of that block. A: You could also do: case x: {var someVariable = 42;} break; case y: {var someVariable = 40;} break; Essentially the braces create the lexical scope, so without the braces, someVariable is loaded into the symbol table twice. I believe this choice is likely made simply to avoid confusion, and possibly to avoid adding complexity to the building of the symbol table. A: UPDATE: This question was used as the inspiration for this blog post; see it for further details. http://ericlippert.com/2009/08/13/four-switch-oddities/ Thanks for the interesting question. There are a number of confusions and mis-statements in the various other answers, none of which actually explain why this is illegal. I shall attempt to be definitive. First off, to be strictly correct, "scope" is the wrong word to use to describe the problem. Coincidentally, I wrote a blog post last week about this exact mis-use of "scope"; that will be published after my series on iterator blocks, which will run throughout July. The correct term to use is "declaration space". A declaration space is a region of code in which no two different things may be declared to have the same name. The scenario described here is symptomatic of the fact that a switch section does not define a declaration space, though a switch block does. Since the OP's two declarations are in the same declaration space and have the same name, they are illegal. (Yes, the switch block also defines a scope but that fact is not relevant to the question because the question is about the legality of a declaration, not the semantics of an identifier lookup.) A reasonable question is "why is this not legal?" A reasonable answer is "well, why should it be"? You can have it one of two ways. Either this is legal: switch(y) { case 1: int x = 123; ... break; case 2: int x = 456; ... break; } or this is legal: switch(y) { case 1: int x = 123; ... break; case 2: x = 456; ... break; } but you can't have it both ways. The designers of C# chose the second way as seeming to be the more natural way to do it. This decision was made on July 7th, 1999, just shy of ten years ago. The comments in the notes from that day are extremely brief, simply stating "A switch-case does not create its own declaration space" and then giving some sample code that shows what works and what does not. To find out more about what was in the designers minds on this particular day, I'd have to bug a lot of people about what they were thinking ten years ago -- and bug them about what is ultimately a trivial issue; I'm not going to do that. In short, there is no particularly compelling reason to choose one way or the other; both have merits. The language design team chose one way because they had to pick one; the one they picked seems reasonable to me. A: Because cases aren't blocks, there are no curly braces denoting the scope. Cases are, for lack of a better word, like labels. You're better off declaring the variable outside the switch() statement and using it thereafter. Of course, in that scenario, you won't be able to use the var keyword, because the compiler won't know what type to initialize. A: Ah - you don't have fall through, but you can use goto to jump to another labelled case block. Therefore the blocks have to be within the same scope. A: As of C# 8.0 you can now do this with switch expressions you use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression var someVariable = caseSwitch switch { case x => 42, case y => 40, _ => throw new Exception("This is how to declare default") }; A: You could just declare the variable outside the scope of the switch statement. var someVariable; switch(); case x: someVariable = 42; break; case y: someVariable = 40; break;
{ "language": "en", "url": "https://stackoverflow.com/questions/1074589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: String [] to char Array using java I have a weird situation, am working on a Data base project that only gives me a string [] s = ["A","B","C","D"] and I wanted to change from string array to Char Array since it's a char but i dunno what function to use to convert the entire array to char with one line of code. char ch = [ 'A', 'B', 'C'] --> this is what am looking to get My plan B is to loop the entire string and convert to char one by one. but am avoiding that one. any help I will highly appreciate A: this might help you. Would be better if we could use Stream<char>, but, this does not work, so, we need to use the wrapper class. Since you want the first index, you can use 0. String.charAt(index) returns a char primitive, so, it will use less memory than a String.substring(...) that returns a new String. final String[] array = {"A", "B", "C", "D"}; final Character [] char_array = Arrays.stream(array) .map(s -> s.charAt(0)) .toArray(Character[]::new); for(char a: char_array) { System.out.println(a); } A: You can use streams, this will return a char [] array. Arrays.stream(S).map(s -> s.substring(0,1)).collect(Collectors.joining()).toCharArray(); Full code String [] S = { "A", "B", "C"} ; char [] ch =Arrays.stream(S).map(s -> s.substring(0,1)) .collect(Collectors.joining()).toCharArray(); for(int i=0;i<ch.length;i++){ System.out.println(ch[i]); } For better use, I suggest making a method that implements this stream and returns a char [] public char [] convertToChar(String [] yourArray){ return Arrays.stream(youArray).map(s -> s.substring(0,1)).collect(Collectors.joining()).toCharArray(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/66573377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: AWS NEXRAD and pyart grid_from_radars Can someone take a look at this code and help me debug? import numpy as np import pyart radar_data=[] RADAR_FILE = r'C:\Sourcecode\NEXRAD\KTLX20150506_235157_V06.gz' radar = pyart.io.read_nexrad_archive(RADAR_FILE) radar.fields['reflectivity']['data'][:, -10:] = np.ma.masked gatefilter = pyart.filters.GateFilter(radar) gatefilter.exclude_transition() gatefilter.exclude_masked('reflectivity') grid = pyart.map.grid_from_radars( (radar,), gatefilters=(gatefilter, ), grid_shape=(1, 9720, 1832), grid_limits=((2000, 2000), (-123000.0, 123000.0), (-123000.0, 123000.0)), fields=['reflectivity']) It fails to make the grid with the error: "numpy.core._exceptions.MemoryError: Unable to allocate array with shape (9720, 1832) and data type float64" I think my grid_shape is off somehow... THanks A: Solved. Installed 32-bit Python by mistake, should be 64-bit for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/57667416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: reading config file in python with ConfigParser I have used configparser to read configurations in my python written program . I am reading file from s3 for now , but my requirement is to configurations defined in the program itself rather than from any other external source . code written is below: config = configparser.ConfigParser() config.readfp(open(s3:path\config)) config file format : config.ini [section1] var1=Y var2=Y var3=['col1','col2'] I am reading above file that is located in s3 , but instead of reading from s3 I want to read from program in itself . what needs to be done in order to achieve this ? above code is written in pyspark program , I am passing config file with spark submit command but to read config file i need to provide path and this is not desirable . spark submit in aws emr : 'Args': ['spark-submit','--deploy-mode', 'cluster','--master', 'yarn','--executor-memory', conf['emr_step_executor_memory'],'--executor-cores', conf['emr_step_executor_cores'],'--conf','spark.yarn.submit.waitAppCompletion=true','--conf','spark.rpc.message.maxSize=1024',f'{s3_path}/file1.py', '--py-files',f'{s3_path}/file2.py',f'{s3_path}/file3.py',f'{s3_path}/file4.py','--files', f'{s3_path}/config ] because of config.readfp(open(s3:path\config)) line i need to provide s3 path , that is not desirable options are either pass config file from spark submit and make available to every other python files those are reading configs or read configuration inside of program itself . A: you can do something like this: parser = configparser.ConfigParser() parser.read_dict({'section1': {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}, 'section2': {'keyA': 'valueA', 'keyB': 'valueB', 'keyC': 'valueC'}, 'section3': {'foo': 'x', 'bar': 'y', 'baz': 'z'}}) Check this for detailed info as well as some other alternative way to achieve this. Sample retrieval parser["section1"]["key1"] 'value1'
{ "language": "en", "url": "https://stackoverflow.com/questions/64096449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reporting shadow prices from SimplexSolver I'm using the SimplexSolver class directly to solve a linear program, with AddRow, AddVariable and SetCoefficient. This works quite well. We need to come up with shadow prices now, and I don't see any way to access either the shadow prices or the simplex matrix. If I set SimpleSolverParams.GetSensitivityReport to true, casting the return of SimplexSolver.GetReport to ILinearSolverSensitivityReport may be the key here. Checking it out. A: It looks like ILinearSolverSensitivityReport.GetDualValue returns the shadow price. Hopefully this saves someone else a merry chase through dotPeek. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/27082503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display NSDates in terms of week Scenario: I have an expense tracking iOS Application and I am storing expenses from a expense detail view controller into a table view (with fetched results controller) that shows the list of expenses along with the category and amount and date. I do have a date attribute in my entity "Money" which is a parent entity for either an expense or an income. Question: What I want is to basically categorize my expenses for a given week, a month, or year and display it as the section header title for example : (Oct 1- Oct 7, 2012) and it shows expenses amount and related stuff according to that particular week. Two buttons are provided in that view, if I would press the right button, it will increment the week by a week (Oct 1- Oct 7, 2012 now shows Oct8 - Oct 15, 2012) and similarly the left button would decrement the week by a week. How would I accomplish that? I am trying the following code - doesn't work. - (void)weekCalculation { NSDate *today = [NSDate date]; // present date (current date) NSCalendar* calendar = [NSCalendar currentCalendar]; NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:today]; [comps setWeekday:1]; // 1: Sunday firstDateOfTheWeek = [[calendar dateFromComponents:comps] retain]; [comps setWeekday:7]; // 7: Saturday lastDateOfTheWeek = [[calendar dateFromComponents:comps] retain]; NSLog(@" first date of week =%@", firstDateOfTheWeek); NSLog(@" last date of week =%@", lastDateOfTheWeek); firstDateOfWeek = [dateFormatter stringFromDate:firstDateOfTheWeek]; lastDateOfWeek = [dateFormatter stringFromDate:lastDateOfTheWeek]; } Code for incrementing date - - (IBAction)showNextDates:(id)sender { int addDaysCount = 7; NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease]; [dateComponents setDay:addDaysCount]; NSDate *newDate1 = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:firstDateOfTheWeek options:0]; NSDate *newDate2 = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:lastDateOfTheWeek options:0]; NSLog(@" new dates =%@ %@", newDate1, newDate2); } Suppose the week shows like this (Nov4, 2012 - Nov10, 2012) and I press the increment button, I see in the console, date changes to Nov11,2012 and Nov.17, 2012 which is right but if I press the increment button again, it shows the same date again (Nov 11, 2012 and Nov.17, 2012). Please help me out here. A: Declare currentDate as an @property in your class. And try this. @property(nonatomic, retain) NSDate *currentDate; Initially set self.currentDate = [NSDate date]; before calling this method. - (void)weekCalculation { NSCalendar* calendar = [NSCalendar currentCalendar]; NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:self.currentDate]; [comps setWeekday:1]; // 1: Sunday firstDateOfTheWeek = [[calendar dateFromComponents:comps] retain]; [comps setWeekday:7]; // 7: Saturday lastDateOfTheWeek = [[calendar dateFromComponents:comps] retain]; NSLog(@" first date of week =%@", firstDateOfTheWeek); NSLog(@" last date of week =%@", lastDateOfTheWeek); firstDateOfWeek = [dateFormatter stringFromDate:firstDateOfTheWeek]; lastDateOfWeek = [dateFormatter stringFromDate:lastDateOfTheWeek]; } Once the view is loaded self.currentDate value should be updated from showNextDates. Make sure it is not getting reset anywhere else. - (IBAction)showNextDates:(id)sender { int addDaysCount = 7; NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease]; [dateComponents setDay:addDaysCount]; NSDate *newDate1 = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:firstDateOfTheWeek options:0]; NSDate *newDate2 = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:lastDateOfTheWeek options:0]; NSLog(@" new dates =%@ %@", newDate1, newDate2); self.currentDate = newDate1; } A: I had needed similar thing in one of my old projects and achieved it via the code below. It sets this weeks date to an NSDate variable and adds/removes 7 days from day component in each button click. Here is the code: NSCalendar *calendar = [NSCalendar currentCalendar]; [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; NSDate *date = [NSDate date]; NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSWeekdayCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date ]; // [components setDay:([components day] - ([components weekday] )+2)]; self.currentDate = [calendar dateFromComponents:components]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"dd.MM.yyyy HH:mm:ss"; self.datelabel.text = [formatter stringFromDate:self.currentDate]; The code above calculates this week start and sets it to currentDate variable. I Have two UIButtons with UIActions named prevClick and nextClick which calls the method that sets the next or previous weekstart: - (IBAction)prevClick:(id)sender { [self addRemoveWeek:NO]; } -(void)addRemoveWeek:(BOOL)add{ NSCalendar *calendar = [NSCalendar currentCalendar]; [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSWeekdayCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.currentDate ]; components.day = add?components.day+7:components.day-7; self.currentDate = [calendar dateFromComponents:components]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"dd.MM.yyyy HH:mm:ss"; self.datelabel.text = [formatter stringFromDate:self.currentDate]; } - (IBAction)nextClk:(id)sender { [self addRemoveWeek: YES]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/13303909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting a linechart entry label MPAndroidChart I have a line chart with entries that the user can click on via line chart.setOnChartValueSelectedListener. Is there a way that I can programmatically get the label of whichever entry is clicked? Or is there some other way of achieving this in my code? private void chartAreaClickResponse(LineChart lineChart) { lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() { @Override public void onValueSelected(Entry e, Highlight h) { //get the label of the entry here } @Override public void onNothingSelected() { } }); } A: I figured it out, in case anyone needs to know this in the future.Simply add the following line under "onValueSelected": @Override public void onValueSelected(Entry e, Highlight h) { String label = dataSets.get(h.getDataSetIndex()).getLabel(); //add this } In this case, dataSets is the "ILineDataSet" used to populate the line chart
{ "language": "en", "url": "https://stackoverflow.com/questions/48456982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: equivalent of __FUNCTION__ of C lanauage in Java For debug purpose, I want to print out current executing function name in Java. If it were C, I would just do printf("%s \n" ,__FUNCITON__). A: new Exception().getStackTrace()[0].getMethodName(); A: I'd use one of the logging frameworks (logback with slf4j is probably the best one at the moment, but log4j should suffice), then you can specify a layout that will print the method name logback layout documentation here
{ "language": "en", "url": "https://stackoverflow.com/questions/3183817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Google Script - get data from Gmail into Sheet I have been looking around here on SO and on Google, but I cannot find anything that is working. So when I am running my code below, I am getting the result on the image. I want to extract data from the newest/most recent thread in mails that have a specific label. However, in my Gmail, I only have the 3 mails under "Action"-label that I have highlighted in bold. The other mails have been deleted, hence, they are in trash, but do still have the "Action" label. I want to only show the mails that I have "Action"-label on - meaning that I only want the newest thread time/date, subject line as well as the ID, so I can create a link to that mail. function myFunction() { var ss = SpreadsheetApp.getActiveSheet(); var query = "label:action -label:trash -label:action-done -from:me"; var threads = GmailApp.search(query); for (var i = 0; i < threads.length; i++) { var messages = threads[i].getMessages(); for (var j = 0; j < messages.length; j++) { var mId = messages[j].getId() var from = messages[j].getFrom(); var cc = messages[j].getCc(); var time = messages[j].getDate() var sub = messages[j].getSubject(); ss.appendRow([from, cc, time, sub, 'https://mail.google.com/mail/u/0/#inbox/'+mId]) } } } } A: So I managed to solve it, by finding the max index in the array. I have commented the code, so it can help others. Thanks, all. function myFunction() { // Use sheet var ss = SpreadsheetApp.getActiveSheet(); // Gmail query var query = "label:support -label:trash -label:support-done -from:me"; // Search in Gmail, bind to array var threads = GmailApp.search(query); // Loop through query results for (var i = 0; i < threads.length; i++) { // Get messages in thread, add to array var messages = threads[i].getMessages(); // Used to find max index in array var max = messages[0]; var maxIndex = 0; // Loop through array to find maxIndexD = most recent mail for (var j = 0; j < messages.length; j++) { if (messages[j] > max) { maxIndex = j; max = messages[j]; } } // Find data var mId = messages[maxIndex].getId() // ID used to create mail link var from = messages[maxIndex].getFrom(); var cc = messages[maxIndex].getCc(); var time = threads[i].getLastMessageDate() var sub = messages[maxIndex].getSubject(); // Write data to sheet ss.appendRow([from, cc, time, sub, 'https://mail.google.com/mail/u/0/#inbox/'+mId]) } } A: What do you mean by recent? How about adding newer_than:3d to the search? You can test the search in your own Gmail account and when it's doing what you want then just paste it into the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/47417288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create gifs with images in Python Are there any APIs or libraries I can use to create a .gif out of .jpgs and .pngs? I'm looking for one that will work with Python 3. A: Try googling, there are a lot of answers for this question. Here are the top three when I looked Programmatically generate video or animated GIF in Python? Generating an animated GIF in Python https://sukhbinder.wordpress.com/2014/03/19/gif-animation-in-python-in-3-steps/ A: Here is something that I wrote a while ago. I couldn't find anything better when I wrote this in the last six months. Hopefully this can get you started. It uses ImageMagick found here! import os, sys import glob dataDir = 'directory of image files' #must contain only image files #change directory gif directory os.chdir(dataDir) #Create txt file for gif command fileList = glob.glob('*') #star grabs everything, can change to *.png for only png files fileList.sort() #writes txt file file = open('blob_fileList.txt', 'w') for item in fileList: file.write("%s\n" % item) file.close() #verifies correct convert command is being used, then converts gif and png to new gif os.system('SETLOCAL EnableDelayedExpansion') os.system('SET IMCONV="C:\Program Files\ImageMagick-6.9.1-Q16\Convert"') # The following line is where you can set delay of images (100) os.system('%IMCONV% -delay 100 @fileList.txt theblob.gif') New convert call For whatever reason (I didn't look at differences), I no longer needed the set local and set command lines in the code. I needed it before because the convert command was not being used even with path set. When you use the new 7.. release of image magick. See new line of code to replace last three lines. Be sure to check box that ask to download legacy commands e.g convert when installing. Everything was converted to a single magick command, but I didnt want to relearn the new conventions. os.system('convert -delay 50 @fileList.txt animated.gif')
{ "language": "en", "url": "https://stackoverflow.com/questions/38444619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to connect Dialogflow (Api.ai) with Slack so that humans can monitor and possibly even intervene or add to the conversation via Slack? I know Dialogflow (Api.ai) can be a bot in Slack. But what about monitoring the conversation and possibly manually intervene in the conversation? If possible, what would be the general direction to implement this? A: So Slack has Open APIs for interacting with the Slack App. Here Since you want to monitor the conversations so Events APIs and Conversations APIs would help you to notify as well as capture the conversations. conversations.history will help you to fetch the messages within public or private channels. Since you want to intervene in the conversation then I suggest using chatbot, which will provide a suitable way to intervene and respond to some particular events. Bot Users A: Dialogflow has an sample on how to do this: https://github.com/dialogflow/agent-human-handoff-nodejs You'll have to build you own front end for the human to override the response and call the Dialogflow query API to integrate: Slack <--> Front end w/human override <--> Dialogflow's query API <--> Dialogflow Agent A: Yes, it's possible. Just login to DialogFlow with your Google credentials, then on the left sidebar you can see the Integrations Tab. Click on it. You will find a bunch of different integrations for line, telegram, Twilio, kik, Viber, Skype and a lot more. Click on Slack. It will ask you for some details for connecting with endpoints such as client ID, token, client secret. You can get it from the Slack API. You can also check the Slack API integration link here. After everything is properly set up, click the "Test in Slack" button in the DialogFlow Slack integration.
{ "language": "en", "url": "https://stackoverflow.com/questions/47523029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get recent nth set of data from tables with Group in SQL I have got a table like this Here as you can see there are different groups of data for different dates. (When we ignore the time part in the datetime there, we have groups of dates) So what I need is to take most recent from every group and from that result I need to get the recent nth set. For example if I pass 2, it should return LogId etime -------------------- 19 2021-07-16 -------------------------- Same way if we pass the parameter 3 it should return LogId etime -------------------- 18 2021-07-15 -------------------------- I did some query which I really believe its not the best way and it looks little twisty.. create table MYTABLE(logid int,etime datetime) insert into MYTABLE (logid,etime) values (15,'2021-07-12 01:32:00 PM'), (16,'2021-07-15 01:32:00 PM'), (17,'2021-07-15 04:32:00 PM'), (18,'2021-07-15 07:32:00 PM'), (19,'2021-07-16 11:32:00 AM'), (20,'2021-07-16 08:10:00 AM'), (21,'2021-07-17 11:20:00 PM') select logid,etime from ( select *,ROW_NUMBER() over (order by etime desc) serial from ( select logid,dense_rank() over(partition by cast(etime as date) order by etime desc) drnk,Cast(etime as date) etime from @table )tbl where drnk=1 )tbl2 where serial=3 Could you please share some optimal way Here is the fiddle SQLFiddle A: Seems like OFFSET and FETCH would be more succinct here: DECLARE @N int = 2, @Date date = '20210716'; SELECT LogID, etime FROM dbo.MYTABLE WHERE etime >= @Date AND eTime < DATEADD(DAY, 1, @Date) ORDER BY etime ASC OFFSET @N-1 ROWS FETCH NEXT 1 ROWS ONLY; A: Imo the way you're doing it now is a really good way and you could stick with it. Again imo: the nested SELECT are not as nice as common table expressions. I would rewrite and parameterize the code something like this declare @param int=3; with dr_cte(logid, etime_dt, drnk) as ( select logid, Cast(etime as date), dense_rank() over(partition by cast(etime as date) order by etime desc) from #MYTABLE), serial_cte(logid, etime_dt, drnk, serial) as ( select *, row_number() over (order by etime_dt desc) from dr_cte where drnk=1) select * from serial_cte where serial=@param; [EDIT] It could be made a tiny bit more concise (or maybe it's the same?) by using TOP 1 WITH TIES in the dr_cte. Then the WHERE condition in the second CTE could be removed. Afaik this code is equivalent declare @param int=2; with dr_cte(logid, etime_dt) as ( select top 1 with ties logid, Cast(etime as date) from #MYTABLE order by row_number() over(partition by cast(etime as date) order by etime desc)), serial_cte(logid, etime_dt, serial) as ( select *, row_number() over (order by etime_dt desc) from dr_cte) select * from serial_cte where serial=@param; [Edit 2] It could also be done by OFFSET paging. declare @param int=3; with dr_cte(logid, etime_dt) as ( select top 1 with ties logid, Cast(etime as date) from #MYTABLE order by row_number() over(partition by cast(etime as date) order by etime desc)) select * from dr_cte order by etime_dt desc offset @param-1 rows fetch next 1 rows only;
{ "language": "en", "url": "https://stackoverflow.com/questions/68561084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Huawei Mobile Services SDK violation Device and Network Abuse policy Your app contains content that doesn’t comply with the Device and Network Abuse policy. We found your app is using a non-compliant version of Huawei Mobile Services SDK which contains code to download or install applications from unknown sources outside of Google Play. I am using Huawei Mobile Services SDK for Auto Eraser. List of used dependency implementation 'com.huawei.hms:ml-computer-vision-segmentation:3.0.0.301' implementation 'com.huawei.hms:ml-computer-vision-image-segmentation-body-model:2.0.2.300' buildscript { repositories { mavenCentral() jcenter() google() maven {url 'http://developer.huawei.com/repo/'} } dependencies { classpath 'com.android.tools.build:gradle:4.2.2' //Auto eraser classpath 'com.huawei.agconnect:agcp:1.3.1.300' } } Added below meta data in manifest.xml <meta-data android:name="com.huawei.hms.ml.DEPENDENCY" android:value="imgseg" /> A: If you have dependencies that can be replaced with Google compatible equivalent dependencies then this could be a possible solution to manage both in one code base. Using app flavours I was able to separate my GMS and HMS dependencies. In your app level build.gradle file you can create product flavour like so android { flavorDimensions "platforms" ... productFlavors { gms { dimension "platforms" } hms { dimension "platforms" } } ... } More on product flavors here. And then you can specify if a dependency should be part of the flavour by prefixing it to the keyword implementation under dependencies. dependencies { ... gmsImplementation 'com.google.android.gms:play-services-maps:18.0.2' hmsImplementation 'com.huawei.hms:maps:5.0.0.300' ... } I then went a bit further by wrapping the usage of each dependency in a class that is available in both flavours but the implementation differs based on the dependency's requirements. com.example.maps.MapImpl under src>hms>java and com.example.maps.MapImpl under src>gms>java So I am free to use the wrapper class anywhere without worrying about the dependency mismatch. The HMS dependency is no longer part of the GMS build variant so I would be able to upload that to the Google playstore. A: I solved it by doing similar to what @Daniel has suggested to avoid such worries in the future: * *Create different product flavors in your app level Gradle file: android { ... flavorDimensions 'buildFlavor' productFlavors { dev { dimension 'buildFlavor' } production { dimension 'buildFlavor' } huawei { dimension 'buildFlavor' } } } *Restrict the Huawei related dependencies so they're only available for Huawei product flavor: huaweiImplementation "com.huawei.hms:iap:3.0.3.300" huaweiImplementation "com.huawei.hms:game:3.0.3.300" huaweiImplementation "com.huawei.hms:hwid:5.0.1.301" huaweiImplementation "com.huawei.hms:push:5.0.0.300" huaweiImplementation "com.huawei.hms:hianalytics:5.0.3.300" huaweiImplementation "com.huawei.hms:location:5.0.0.301" *Since dev and production flavors are not going to have Huawei dependencies now, you may get build errors for the Huawei related classes that you use in your app. For that I create dummy classes with the same packages tree as Huawei, for instance: app > src > dev > java > com > huawei > hms > analytics > HiAnalytics.kt class HiAnalytics { companion object { @JvmStatic fun getInstance(context: Context): HiAnalyticsInstance { return HiAnalyticsInstance() } } } *This solves the Cannot resolve symbol error when trying to import Huawei classes in your main, dev, or production flavors and you can import those classes anywhere: import com.huawei.hms.analytics.HiAnalytics Now if you change the build variant to dev, you should have access to the dummy classes in your app. If you change it to huawei, you should be able to access the classes from Huawei dependencies. A: Update: Note: If you have confirmed that the latest SDK version is used, before submitting a release to Google, please check the apks in all Testing track on Google Play Console(including Open testing, Closed testing, Internal testing). Ensure that the APKs on all tracks(including paused track) have updated to the latest HMS Core SDK. HMS Core SDKs have undergone some version updates recently. To further improve user experience, update the HMS Core SDK integrated into your app to the latest version. HMS Core SDK Version Link Keyring com.huawei.hms:keyring-credential:6.4.0.302 Link Location Kit com.huawei.hms:location:6.4.0.300 Link Nearby Service com.huawei.hms:nearby:6.4.0.300 Link Contact Shield com.huawei.hms:contactshield:6.4.0.300 Link Video Kit com.huawei.hms:videokit-player:1.0.12.300 Link Wireless kit com.huawei.hms:wireless:6.4.0.202 Link FIDO com.huawei.hms:fido-fido2:6.3.0.304com.huawei.hms:fido-bioauthn:6.3.0.304com.huawei.hms:fido-bioauthn-androidx:6.3.0.304 Link Panorama Kit com.huawei.hms:panorama:5.0.2.308 Link Push Kit com.huawei.hms:push:6.5.0.300 Link Account Kit com.huawei.hms:hwid:6.4.0.301 Link Identity Kit com.huawei.hms:identity:6.4.0.301 Link Safety Detect com.huawei.hms:safetydetect:6.4.0.301 Link Health Kit com.huawei.hms:health:6.5.0.300 Link In-App Purchases com.huawei.hms:iap:6.4.0.301 Link ML Kit com.huawei.hms:ml-computer-vision-ocr:3.6.0.300com.huawei.hms:ml-computer-vision-cloud:3.5.0.301com.huawei.hms:ml-computer-card-icr-cn:3.5.0.300com.huawei.hms:ml-computer-card-icr-vn:3.5.0.300com.huawei.hms:ml-computer-card-bcr:3.5.0.300com.huawei.hms:ml-computer-vision-formrecognition:3.5.0.302com.huawei.hms:ml-computer-translate:3.6.0.312com.huawei.hms:ml-computer-language-detection:3.6.0.312com.huawei.hms:ml-computer-voice-asr:3.5.0.301com.huawei.hms:ml-computer-voice-tts:3.6.0.300com.huawei.hms:ml-computer-voice-aft:3.5.0.300com.huawei.hms:ml-computer-voice-realtimetranscription:3.5.0.303com.huawei.hms:ml-speech-semantics-sounddect-sdk:3.5.0.302com.huawei.hms:ml-computer-vision-classification:3.5.0.302com.huawei.hms:ml-computer-vision-object:3.5.0.307com.huawei.hms:ml-computer-vision-segmentation:3.5.0.303com.huawei.hms:ml-computer-vision-imagesuperresolution:3.5.0.301com.huawei.hms:ml-computer-vision-documentskew:3.5.0.301com.huawei.hms:ml-computer-vision-textimagesuperresolution:3.5.0.300com.huawei.hms:ml-computer-vision-scenedetection:3.6.0.300com.huawei.hms:ml-computer-vision-face:3.5.0.302com.huawei.hms:ml-computer-vision-skeleton:3.5.0.300com.huawei.hms:ml-computer-vision-livenessdetection:3.6.0.300com.huawei.hms:ml-computer-vision-interactive-livenessdetection:3.6.0.301com.huawei.hms:ml-computer-vision-handkeypoint:3.5.0.301com.huawei.hms:ml-computer-vision-faceverify:3.6.0.301com.huawei.hms:ml-nlp-textembedding:3.5.0.300com.huawei.hms:ml-computer-ner:3.5.0.301com.huawei.hms:ml-computer-model-executor:3.5.0.301 Link Analytics Kit com.huawei.hms:hianalytics:6.5.0.300 Link Dynamic Tag Manager com.huawei.hms:dtm-api:6.5.0.300 Link Site Kit com.huawei.hms:site:6.4.0.304 Link HEM Kit com.huawei.hms:hemsdk:1.0.4.303 Link Map Kit com.huawei.hms:maps:6.5.0.301 Link Wallet Kit com.huawei.hms:wallet:4.0.5.300 Link Awareness Kit com.huawei.hms:awareness:3.1.0.302 Link Crash com.huawei.agconnect:agconnect-crash:1.7.0.300 Link APM com.huawei.agconnect:agconnect-apms:1.5.2.310 Link Ads Kit com.huawei.hms:ads-prime:3.4.55.300 Link Paid Apps com.huawei.hms:drm:2.5.8.301 Link Base com.huawei.hms:base:6.4.0.303 Required versions for cross-platform app development: Platform Plugin Name Version Link React Native react-native-hms-analytics 6.3.2-301 Link react-native-hms-iap 6.4.0-301 Link react-native-hms-location 6.4.0-300 Link react-native-hms-map 6.3.1-304 Link react-native-hms-push 6.3.0-304 Link react-native-hms-site 6.4.0-300 Link react-native-hms-nearby 6.2.0-301 Link react-native-hms-account 6.4.0-301 Link react-native-hms-ads 13.4.54-300 Link react-native-hms-adsprime 13.4.54-300 Link react-native-hms-availability 6.4.0-303 Link Cordova(Ionic-CordovaIonic-Capacitor) cordova-plugin-hms-analyticsionic-native-hms-analytics 6.3.2-301 Link cordova-plugin-hms-locationionic-native-hms-location 6.4.0-300 Link cordova-plugin-hms-nearbyionic-native-hms-nearby 6.2.0-301 Link cordova-plugin-hms-accountionic-native-hms-account 6.4.0-301 Link cordova-plugin-hms-pushionic-native-hms-push 6.3.0-304 Link cordova-plugin-hms-siteionic-native-hms-site 6.4.0-300 Link cordova-plugin-hms-iapionic-native-hms-iap 6.4.0-301 Link cordova-plugin-hms-availabilityionic-native-hms-availability 6.4.0-303 Link cordova-plugin-hms-adsionic-native-hms-ads 13.4.54-300 Link cordova-plugin-hms-adsprimeionic-native-hms-adsprime 13.4.54-300 Link cordova-plugin-hms-mapionic-native-hms-map 6.0.1-305 Link cordova-plugin-hms-mlionic-native-hms-ml 2.0.5-303 Link Flutter huawei_safetydetect 6.4.0+301 Link huawei_iap 6.2.0+301 Link huawei_health 6.3.0+302 Link huawei_fido 6.3.0+304 Link huawei_push 6.3.0+304 Link huawei_account 6.4.0+301 Link huawei_ads 13.4.55+300 Link huawei_analytics 6.5.0+300 Link huawei_map 6.5.0+301 Link huawei_hmsavailability 6.4.0+303 Link huawei_location 6.0.0+303 Link huawei_adsprime 13.4.55+300 Link huawei_ml 3.2.0+301 Link huawei_site 6.0.1+304 Link Xamarin Huawei.Hms.Hianalytics 6.4.1.302 Link Huawei.Hms.Location 6.4.0.300 Link Huawei.Hms.Nearby 6.2.0.301 Link Huawei.Hms.Push 6.3.0.304 Link Huawei.Hms.Site 6.4.0.300 Link Huawei.Hms.Fido 6.3.0.304 Link Huawei.Hms.Iap 6.4.0.301 Link Huawei.Hms.Hwid 6.4.0.301 Link Huawei.Hms.Ads-prime 3.4.54.302 Link Huawei.Hms.Ads 3.4.54.302 Link Huawei.Hms.Maps 6.5.0.301 Link If you have any further questions or encounter any issues integrating any of these kits, please feel free to contact us. Region Email Europe [email protected] Asia Pacific [email protected] Latin America [email protected] Middle East & Africa [email protected] Russia [email protected] A: UPDATE 06/04/2022 Huawei released a new version of their SDK : 3.4.0.300 3.4.0.300 (2022-03-04) New Features * *Real-time translation: Added Afrikaans to the list of languages supported. (Note that this language is available only in Asia, Africa, and Latin America.) Modified Features * *Deleted the capability of prompting users to install HMS Core (APK). *Modified the SDK privacy and security statement. Updated the SDK *versions of all subservices. For me, since I've migrated to Google ML Kit, I will wait till August, then I will switch back to Huawei ML Kit to make sure Google will not remove or suspend my apps. Old answer : I used to love the HMS ML kit, but because of this issue, I'm aware that Google will one day completely suspend my apps because I'm using HMS services, and even if Huawei fixes the issue, we'll have to wait 120 days to find out if we're safe. In my case, I'm using the HMS Segmentation ML Kit. I've just switched to Google Selfie Segmentation ML. I will wait till 120 days have passed and see if the issue is still persisting for other developers. If not, I will switch back to the HMS Kit. A: The solution to the problem is to update the dependencies like in this link. With this update, the ability to prompt users to install HMS Core (APK) has been removed. https://developer.huawei.com/consumer/en/doc/development/hmscore-common-Guides/hmssdk-kit-0000001050042513#section20948233203517 A: I just use hms push when upload to huawei. i fixed by commenting hms services in build.gradle and app/build.gradle when to upload to playstore. Then, I uncomment if upload to huawei. //apply plugin: "com.huawei.agconnect" apply plugin: 'com.google.gms.google-services' //implementation 'com.huawei.hms:push:5.3.0.304'.
{ "language": "en", "url": "https://stackoverflow.com/questions/71508566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Show another button when using "commitEditingStyle" in a UITableView datasource I want to show an "Edit" button below the default "Delete" button that shows up with a swipe gesture on a cell when you implement "commitEditingStyle" on the table's datasource. Is this possible by only implementing "commitEditingStyle" or will i have to implement my own way of showing the buttons on the cells? And if it is, how would i handle the commit? A: Yes you have to implement your own way of showing buttons on UITableViewCells by customizing the UITableViewCells. As far as your requirement is concerned, I dont think its a good idea to show the "edit" button below the "delete" button, as accommodating both buttons vertically one-by-one may disappoint the user to make desired touch actions. I mean to say, user may want to touch edit, but due to successive placing of custom edit/delete buttons, delete button may get clicked which is dangerous & not acceptable too. Of course,it will cause user to take proper care every-time making any of the edits.
{ "language": "en", "url": "https://stackoverflow.com/questions/10815550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET how to make slider for table? I have an ASP.NET table that gets lots of rows put into it. I want to have a slider to view more rows instead of making my page extremely long. This seemed like a basic task, but I cannot find any way to do this... I would love to hear any ideas! To be clear, my question is: how do I add a slider to my asp.net table? A: Not sure if this will exactly fit the bill, but check out the ASP.NET Scrollable Table Server Control Or were you asking for a slider pager control that will load more results for the user? A: For future reference, .FixedHeightContainer { float:left; height: 350px; width:100%; padding:3px; } .Content { height:224px; overflow:auto; } along with: <div class="FixedHeightContainer"> <h2>Results</h2> <div class="Content"> <asp:Table ID="Table1" runat="server" GridLines="Both" Height="350px" Width="80%"> <asp:TableHeaderRow> <asp:TableHeaderCell> </asp:TableHeaderCell> </asp:TableHeaderRow> </asp:Table> </div> </div> Is what I used to create a table with a slider Thanks for all the comments :) Nikita Silverstruk, your comment helped so much :) thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/17555479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between wic and hddimg format in yocto I have generated a core-image-minimal image for my Intel board in Yocto. Looking into tmp/deploy/images folder they are many images. I flashed *.wic image using dd command on USB and it created two partitions ( Boot and Platform ) and allowed only to perform a live booting without allowing it to install on the hard disk of the board. I then flashed *.hddimg on the USB using dd command. It only created a "boot" partition which has rootfs.img, syslinux and EFI folder. Booting using USB provided me an "Install" option, which installed on the board and when I rebooted after installing, it displays "No bootable media found" Using bootable image there are two partitions in the hard disk. Why it is not booting.. Steps followed: * *Created an minimal yocto image using "bitbake core-image-minimal" command *Flashed the USB using the dd command. sudo dd if=tmp/deploy/images/intel-corei7-64/core-image-minimal-intel-corei7-64.hddimg of=/dev/sdb *Clicked on install and typed “sda” *The installation was successful and when I tried to restart by removing the USB Drive, it says “No boot options found. Please install bootable media and restart." What is the mistake I am doing here. Which image to choose and when.. A: There was not much info about online, so I asked this question in the intel community and here is the response of that: Generally a .wic image is intended to be installed directly to its final destination, whereas an hddimg is for evaluation and installation elsewhere. By default meta-intel .wic images only have an EFI bootloader, and will not boot via legacy BIOS. An hddimg will have both an EFI bootloader and the syslinux binaries that let it boot from legacy BIOS. On startup with your installer USB image do you get a light gray screen with four options? If so it is booting via legacy BIOS.
{ "language": "en", "url": "https://stackoverflow.com/questions/49527057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How can I add cookies to Seaside responses without redirecting? I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output? I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie. Is there another way that already exist to add a cookie that will go out on the next response? A: There is currently no built-in way to add cookies during the action/callback phase of request processing. This is most likely a defect and is noted in this issue: http://code.google.com/p/seaside/issues/detail?id=48 This is currently slated to be fixed for Seaside 2.9 but I don't know if it will even be backported to 2.8 or not. Keep in mind that there is already (by default) a redirection between the action and rendering phases to prevent a Refresh from re-triggering the callbacks, so in the grand scheme of things, one more redirect in this case isn't so bad. If you still want to dig further, have a look at WARenderContinuation>>handleRequest:. That's where callback processing is triggered and the redirect or rendering phase begun. Edited to add: The issue has now been fixed and (in the latest development code) you can now properly add cookies to the current response at any time. Simply access the response object in the current request context and add the cookie. For example, you might do something like: self requestContext response addCookie: aCookie This is unlikely to be backported to Seaside 2.8 as it required a fairly major shift in the way responses are handled. A: I've just looked into this in depth, and the answer seems to be no. Specifically, there's no way to get at the response from the WARenderCanvas or anything it can access (it holds onto the WARenderingContext, which holds onto the WAHtmlStreamDocument, which holds onto the response's stream but not the response itself). I think it would be reasonable to give the context access to the current response, precisely to be able to set headers on it, but you asked if there was already a way, so: no. That said, Seaside does a lot of extra redirecting, and it doesn't seem to have much impact on the user experience, so maybe the thing to do is to stop worrying about it seeming kludgey and go with the flow of the API that's already there :)
{ "language": "en", "url": "https://stackoverflow.com/questions/88306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SymbolSource Nightmare So after hours of jumping through hoops, I have gotten SymbolSource running except I am unable to push any packages. The error I am getting now is: Response status code does not indicate success: 418 (Reading package metadata failed: The schema version of 'MyNugetPackage' is incompatible with version 2.1.31002.9028 of NuGet. Please upgrade NuGet to the latest version from See http://www.symbolsource.org/Public/Home/Help for possible reasons. Fiddler may help diagnosing this error if your client discards attached detailed information.). First problem is that you can no longer download the command line version of v2.1.3 of Nuget. I tried the the oldest version available: v2.8.6 but I get the same error. Second problem is it looks like SymbolSource.Server.Basic hasn't been touched in 3 years. Is this project dead? Am I wasting my time? I can't find any other alternative for debugging nuget packages without publishing to a third party service (which my company won't allow)? A: The Symbol Server project master branch hasn't been touched for 4 years as of writing, and there is a queue of pull requests and issues left open for even longer. There is an 'upgrade' branch which hasn't been touched since 2014, but that has updated NuGet version. There is a slightly more recent fork at https://github.com/TrabacchinLuigi/SymbolSource.Community/tree/upgrade which uses more recent versions of NuGet. Also have a look at the GitHub 'network' for other potential maintained forks: https://github.com/SymbolSource/SymbolSource.Community/network And alternative hosting solutions include: * *https://inedo.com/proget *https://github.com/GitTools/GitLink Edit -- I got my own version running: https://github.com/i-e-b/SymbolSourceSane
{ "language": "en", "url": "https://stackoverflow.com/questions/39521705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Print 2 arrays into a CSV file with javascript I was following the mentioned question and this one: JavaScript array to CSV Trying to print 2 arrays in columns A and B which i can turn into a string separated by comas"," which ever is more easy to do but i just can´t get it to work with the examples available. My arrays look like this: var Test = ["John", "Ivar", "Peter", "Tony"]; var Addres = ["Canada", "Sweden", "England", "Chile"]; And in string format its the same only separated by comas I thought it was going to be an easy task but it's more complicated than I expected Hope anyone here can help me with this, Thanks A: You can accomplish it with one-liner reduce: var Test = ["John", "Ivar", "Peter", "Tony"]; var Addres = ["Canada", "Sweden", "England", "Chile"]; var result = Test.reduce((str, name, i) => `${str}${name},${Address[i]}\n`, 'Test,Address\n'); console.log(result);
{ "language": "en", "url": "https://stackoverflow.com/questions/51037826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is this C program returning correct value in VC++2008? We know that automatic variables are destroyed upon the return of the function. Then, why is this C program returning correct value? #include <stdio.h> #include <process.h> int * ReturningPointer() { int myInteger = 99; int * ptrToMyInteger = &myInteger; return ptrToMyInteger; } main() { int * pointerToInteger = ReturningPointer(); printf("*pointerToInteger = %d\n", *pointerToInteger); system("PAUSE"); } Output *pointerToInteger = 99 Edit Then why is this giving garbage values? #include <stdio.h> #include <process.h> char * ReturningPointer() { char array[13] = "Hello World!"; return array; } main() { printf("%s\n", ReturningPointer()); system("PAUSE"); } Output x≈§ A: There is no answer to that question: your code exhibits undefined behavior. It could print "the right value" as you are seeing, it could print anything else, it could segfault, it could order pizza online with your credit card. Dereferencing that pointer in main is illegal, it doesn't point to valid memory at that point. Don't do it. There's a big difference between you two examples: in the first case, *pointer is evaluated before calling printf. So, given that there are no function calls between the line where you get the pointer value, and the printf, chances are high that the stack location pointer points to will not have been overwritten. So the value that was stored there prior to calling printf is likely to be output (that value will be passed on to printf's stack, not the pointer). In the second case, you're passing a pointer to the stack to printf. The call to printf overwrites (a part of) that same stack region the pointer is pointing to, and printf ends up trying to print its own stack (more or less) which doesn't have a high chance of containing something readable. Note that you can't rely on getting gibberish either. Your implementation is free to use a different stack for the printf call if it feels like it, as long as it follows the requirements laid out by the standard. A: This is undefined behavior, and it could have launched a missile instead. But it just happened to give you the correct answer. Think about it, it kind of make sense -- what else did you expect? Should it have given you zero? If so, then the compiler must insert special instructions at the scope end to erase the variable's content -- waste of resources. The most natural thing for the compiler to do is to leave the contents unchanged -- so you just got the correct output from undefined behavior by chance. You could say this behavior is implementation defined. For example. Another compiler (or the same compiler in "Release" mode) may decide to allocate myInteger purely in register (not sure if it actually can do this when you take an address of it, but for the sake of argument...), in that case no memory would be allocated for 99 and you would get garbage output. As a more illustrative (but totally untested) example -- if you insert some malloc and exercise some memory usage before printf you may find the garbage value you were looking for :P Answer to "Edited" part The "real" answer that you want needs to be answered in disassembly. A good place to start is gcc -S and gcc -O3 -S. I will leave the in-depth analysis for wizards that will come around. But I did a cursory peek using GCC and it turns out that printf("%s\n") gets translated to puts, so the calling convention is different. Since local variables are allocated on the stack, calling a function could "destroy" previously allocated local variables. A: * *Destroying is the wrong word imho. Locals reside on the stack, if the function returns the stack space may be reused again. Until then it is not overwritten and still accessible by pointers which you might not really want (because this might never point to something valid) *Pointers are used to address space in memory, for local pointers the same as I described in 1 is valid. However the pointer seems to be passed to the main program. *If it really is the address storing the former integer it will result in "99" up until that point in the execution of your program when the program overwrite this memory location. It may also be another 99 by coincidence. Any way: do not do this. These kind of errors will lead to trouble some day, may be on other machines, other OS, other compiler or compiler options - imagine you upgrade your compiler which may change the behaviour the memory usage or even a build with optimization flags, e.g. release builds vs default debug builds, you name it. A: In most C/C++ programs their local variables live on the stack, and destroyed means overwritten with something else. In this case that particular location had not been overwritten yet when it was passed as a parameter to printf(). Of course, having such code is asking for trouble because per the C and C++ standards it exhibits undefined behavior. A: That is undefined behavior. That means that anything can happen, even what you would expect. The tricky part of UB is when it gives you the result you expect, and so you think that you are doing it right. Then, any change in an unrelated part of the program changes that... Answering your question more specifically, you are returning a pointer to an automatic variable, that no longer exists when the function returns, but since you call no other functions in the middle, it happens to keep the old value. If you call, for example printf twice, the second time it will most likely print a different value. A: The key idea is that a variable represents a name and type for value stored somewhere in memory. When it is "destroyed", it means that a) that value can no longer be accessed using that name, and b) the memory location is free to be overwritten. The behavior is undefined because the implementation of the compiler is free to choose what time after "destruction" the location is actually overwritten.
{ "language": "en", "url": "https://stackoverflow.com/questions/8455822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Code to define biological and technical replicate samples (brain twister) In my expression dataset I have various kinds or replicates, biological and technical. A biological replicate I consider if the same person was sampled at different dates. A technical replicate I consider if a sample was taken from the same person at the same date and measured either at the same or different dates. I tried to define this by code but unfortunately im hitting a wall with trying to define technical and biological replicates. Below is my code that defines replicates and first replicates (=index case) but for the rest it would be amazing if someone could help me. Its kind of a brain twister so kudos to anyone solving this! Thanks a lot! Sebastian df<- data.frame( sample = c(1,2,3,4,5,6,7,8, 9, 10, 11, 12), individual = c("a", "a", "a", "b", "b", "b", "c", "c", "c", "f", "d", "e"), date_collected = c(1.1, 1.1, 1.1, 1.1, 1.1, 1.2, 1.2, 1.1, 1.1, 1.2, 1.1, 1.1), date_processed = c(2.1, 2.1, 2.1, 2.2, 2.1, 2.1, 2.1, 2.1, 2.1, 2.2, 2.2, 2.1 )) #differentiate biological and technical replicates df$has_replicate <- FALSE #all that have a replicate df$is_first_of_replicates <- FALSE #primary sample df$is_technical_replicate_same_run <- FALSE #same sample, same date processed df$is_technical_replicate_different_run <- FALSE #same sample, different date processed df$is_biological_replicate_same_run <- FALSE #same individual, different date collected, same day proc df$is_biological_replicate_different_run <- FALSE #same individual, diff date col, dif day proc #check all samples that have replicates = same individual (including first one) replicates_index <- which(df$individual %in% df$individual[which(duplicated(df$individual))]) #mark df[replicates_index, ]$has_replicate <- TRUE #define first samples (by checking which ones are not the first ones) replicates_not_first_index <- duplicated(df$individual) df[replicates_index, ]$sample #all that have replicates incl first df[replicates_not_first_index, ]$sample #all replicates that are not first #find replicates that are first = present in rep but not in not first firstsIDs_ <- setdiff(df[replicates_index, ]$sample, df[replicates_not_first_index, ]$sample) #get index firsts_index <- which(df$sample %in% firstsIDs_) #mark df[firsts_index, ]$is_first_of_replicates <- TRUE expected output df$is_technical_replicate_same_run # TRUE if is replicate & date.collected same & date processed is the same df$is_technical_replicate_different_run # TRUE if is replicate & date.collected same & date processed is different df$is_biological_replicate_same_run # TRUE if is replicate & date collected is different & date processed is the same df$is_biological_replicate_different_run # TRUE if is replicate & date collected is different & date processed is different
{ "language": "en", "url": "https://stackoverflow.com/questions/54691987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Tuple list inside class inside class not set to instance of object I'm trying to use a tuple list inside a custom class that wraps some methods from mutliple classes inside a game. I'm getting an 'object reference not set to instance of object error' just after the "ENTERED ADD METHOD A-1" is displayed in the cosole from the 1st Add method of the wrapper class. Clearly, Im not setting up the list correctly, but I can't see where the issue is. Any help would be appreciated as I'm new to working with 'classes'. // wrappers & classes KilledActorsWrapper KilledActors = new KilledActorsWrapper(); public class KilledActorsWrapper #region KilledActorsWrapper class { public KilledActorsWrapper() { // constructor if (Type.GetType("KilledActorsWrapper") == null) // check to see if class has been initiated { //class with the given name does not exist so instantiate it List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>(); m_KilledActors.Clear(); ConsoleWriteline("INITIALISED KILLEDACTORS LIST"); } else { // class with the given name exists so show an error, cannot initate the class twice ColoredConsoleWrite(ConsoleColor.DarkGreen, "INITIALISING KILLEDACTORS LIST FAILED"); throw new Exception("KilledActorsWrapper class already exists. Are you typing to initiate a second instance of this class?"); } } public void Add(AiActor killedActor, List<DamagerScore> damages) { ConsoleWriteline("ENTERED ADD METHOD A"); Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>> tuple = new Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>(killedActor, null, NamedDamageTypes.AirbrakeDriveFailure, damages); ConsoleWriteline("ENTERED ADD METHOD A-1"); m_KilledActors.Add(tuple); ConsoleWriteline("ENTERED ADD METHOD A-2"); } public void Add(AiActor killedActor, AiDamageInitiator initiator, NamedDamageTypes damageType) { ConsoleWriteline("ENTERED ADD METHOD B"); Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>> tuple = new Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>(killedActor, initiator, damageType, null); ConsoleWriteline("ENTERED ADD METHOD B-1"); this.m_KilledActors.Add(tuple); ConsoleWriteline("ENTERED ADD METHOD B-2"); } public int Count { get { return m_KilledActors.Count; } } public List<DamagerScore> GetDamagerScore(AiActor killedActor) { for (int i = 0; i < m_KilledActors.Count; i++) { if (m_KilledActors[i].Item1 == killedActor) { return (List<DamagerScore>)m_KilledActors[i].Item1; } } return null; } public List<AiDamageInitiator> GetDamageInitiators(AiActor killedActor) { List<AiDamageInitiator> damageinitiators = null; for (int i = 0; i < m_KilledActors.Count; i++) { if (m_KilledActors[i].Item1 == killedActor) { damageinitiators.Add((AiDamageInitiator)m_KilledActors[i].Item2); } } return damageinitiators; } public List<NamedDamageTypes> GetNamedDamageTypes(AiActor actor) { List<NamedDamageTypes> nameddamagetypes = null; for (int i = 0; i < m_KilledActors.Count; i++) { if (m_KilledActors[i].Item1 == actor) { nameddamagetypes.Add((NamedDamageTypes)m_KilledActors[i].Item3); } } return nameddamagetypes; } public void Clear() { m_KilledActors.Clear(); } private List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors { get; set; } } #endregion public override void OnActorDead(int missionNumber, string shortName, AiActor actor, List<DamagerScore> damages) #region process when an actor dies { base.OnActorDead(missionNumber, shortName, actor, damages); KilledActors.Add(actor, damages); // call the wrapper class } public override void OnActorDamaged(int missionNumber, string shortName, AiActor actor, AiDamageInitiator initiator, NamedDamageTypes damageType) { base.OnActorDamaged(missionNumber, shortName, actor, initiator, damageType); KilledActors.Add(actor, initiator, damageType); // call the wrapper class } A: Either m_KilledActors or tuple is not defined. In this case the bug is in your constructor List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>(); This causes a duplicate definition of m_KilledActors.. change it to just m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>();
{ "language": "en", "url": "https://stackoverflow.com/questions/23464243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Live lock on Linux UNIX socket, what to do? We operate an Linux application that forks a large number (more than 1000) of child processes. These child processes communicate with master process over UNIX datagram socket (one shared among all child processes). The UNIX datagram socket is used besides other communications also for logging. The whole system works fine until the app has to react to a massive external error - let's say a crash of application database. We observed that in such a situation, child processes start to generate a huge amount of error log events, which is probably correct since each child is impacted by that crash. After few minutes, the load increases above 8000 with 80-100% CPU system (not user!) consumption. The state is recoverable only if the app is killed or more commonly, the box becomes unusable due to slow responses and has to be rebooted. The investigation of core dumps shows that child processes are blocked in send() syscall on the UNIX socket, speaking to master process. The UNIX socket is configured as a non-blocking and the app implement proper handling of EAGAIN. More in-depth analysis indicates that there is a live lock condition in the kernel. Obviously, processes are competing for access to some resource related to UNIX socket. Questions: Did you ever meet this or similar behavior before? Do we miss anything about UNIX socket parallelism? Versions: - CentOS Linux release 7.3.1611 (Core). - Kernel Linux 3.10.0-514.16.1.el7.x86_64 x86_64. A: There is clearly room for improvement on the kernel side here and chances are it's a reasonably low hanging fruit. I'm not going to speculate. Chances are the problem will be easily visible with flamegraphs. However, considerations of the sort in this context are a red herring. For the sake of argument let's assume the kernel pushes all these error messages with 0 overhead. You have generated gigabytes of repetitive error messages adding no value. Instead, when there is a major event just log it once and then log again that it is cleared (e.g. note the connection to the database died, note when it got back up, but don't log on each query that it is dead). Alternatively you can log this periodically or with ratelimit. Either way, just spamming is the wrong thing to do. The sheer number of children (1000+?) seems extremely excessive and puts a question mark on the validity of the design of this project. Can you elaborate what's happening there?
{ "language": "en", "url": "https://stackoverflow.com/questions/44569015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Combine Google_Org_Chart with Mysql Im all new at PHP.. i have a task to make an organizational chart (just like google chart) but it is rendered from mysql, just like as follows org chart and this is my database: sql here is code from google chart.. ` <!-- You are free to copy and use this sample in accordance with the terms of the Apache license (http://www.apache.org/licenses/LICENSE-2.0.html) --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title> Google Visualization API Sample </title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages: ["orgchart"]}); </script> <script type="text/javascript"> function drawVisualization() { // Block of codes below I want to change and render it from mysql, unfortunately dont know how to do it // Create and populate the data table. var data = google.visualization.arrayToDataTable([ ['Name', 'Manager', 'Tooltip'], ['Mike', null, 'The President'], [{v: 'Jim', f: 'Jim<br/><font color="red"><i>Vice President<i></font>'}, 'Mike', null], ['Alice', 'Mike', null], ['Bob', 'Jim', 'Bob Sponge'], ['Carol', 'Bob', null] ]); // Create and draw the visualization. new google.visualization.OrgChart(document.getElementById('visualization')). draw(data, {allowHtml: true}); } google.setOnLoadCallback(drawVisualization); </script> </head> <body style="font-family: Arial;border: 0 none;"> <div id="visualization" style="width: 300px; height: 300px;"></div> </body> </html> Anybody knows something?? Any help would be appreciated.. Thanks.. Regards, Aryo A: You can try something like this: <?php // set database connection parameters $databaseName = '<name of database>'; $username = '<user>'; $password = '<password>'; try { $db = new PDO("mysql:dbname=$databaseName", $username, $password); } catch (PDOException $e) { echo $e->getMessage(); exit(); } $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = $db->prepare('SELECT id, nama, parent_id FROM tbl_dummy'); $query->execute(); $results = $query->fetchAll(PDO::FETCH_ASSOC); $flag = true; $table = array(); $table['cols'] = array( array('label' => 'ID', 'type' => 'number'), array('label' => 'Name', 'type' => 'string'), array('label' => 'Parent ID', 'type' => 'number') ); $table['rows'] = array(); foreach ($results as $row) { $temp = array(); $temp[] = array('v' => (int) $row['id']); $temp[] = array('v' => $row['nama']); $temp[] = array('v' => (int) $row['parent_id']); $table['rows'][] = array('c' => $temp); } $jsonTable = json_encode($table); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title> Google Visualization API Sample </title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> function drawVisualization() { // Create and populate the data table. var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>); // Create and draw the visualization. new google.visualization.OrgChart(document.getElementById('visualization')). draw(data, {allowHtml: true}); } google.setOnLoadCallback(drawVisualization); google.load('visualization', '1', {packages: ['orgchart']}); </script> </head> <body style="font-family: Arial;border: 0 none;"> <div id="visualization" style="width: 300px; height: 300px;"></div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/17718321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Website Optimizer Validation Warning I have been using Google website optimizer(GWO) to run a multivariate test on my web page. When I either do offline or online validation, I receive a warning stating there is multiple occurrences of my page sections. For example, if one of my page sections was Description Changes, optimizer would say I have two or more occurrences of that script. I have gone through and checked through my code and have no duplicated any of the page section scripts. Even though GWO states that are multiple occurrences I can still create the experiment. Does anyone know how to fix multiple occurrences from happening or if there are multiple occurrences if it affects the results. A: Might be a bit late, but the issue might be that you have a latin-1 character set: See the following post in the google forums: http://www.google.com/support/forum/p/websiteoptimizer/thread?tid=70b4938cf4de24f2&hl=en
{ "language": "en", "url": "https://stackoverflow.com/questions/3269278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Batch API, inviting friends I'm trying to invite all fans of a page to a facebook event using the batch API. It's the first time I'm using this API, and at this time I have nothing to test this part of code... can someone tell me how to test without using a real page, with real fans... or tell me if it looks correct ? //Getting all the likers of the page $result = $facebookObj->api(array( 'method' => 'fql.query', 'query' => 'select uid,name from user where uid in ( select uid from page_fan where uid in (select uid2 from friend where uid1 = me()) and page_id = '.$fbPage.')' )); //If liker are more than 50 we use batch request if($numLikers >50){ // split array into several part of 50 users accounts $splitLikers = array_chunk($result, 50); // count how many arrays are generated by the array_chunk $countSplit = count($splitLikers); //Start a loop through the numbers of groups of 50 users (or less if last group contains less than 50 users for($a=0; $a<$countSplit; $a++){ //Second loop to go through the 50 likers in one group for($b=0; $b<count($splitLikers[$a]); $b++){ // construct an array containing the whole group $queries[$a] = array('method' => 'POST', 'relative_url' => $event_fbID . "/invited/" . $splitLikers[$a][$b]['uid']); } //Send POST batch request with the array above $ret_val = $facebookObj->api('/?batch='.json_encode($queries[$a]), 'POST'); } }else{ foreach ($result as $value) { $ret_val = $facebookObj->api($event_fbID . "/invited/" . $value['uid'],'POST'); if($ret_val) { // Success $numInvited++; } } } A: Your code seems ok, but dont forget you may need to add the access token to the batch request like: $params['access_token']=[USER_ACCESS_TOKEN]; $ret_val = $facebookObj->api('/?batch='.json_encode($queries[$a]), 'POST', $params); And for testing you may want to create a new page with a couple of friends added and test it. Also remember you need to handle the response, the batch request will response with an array with the same length that the batch array, and each object may be a diferent code, true if it was send. Also you can try your FQL code in the Graph Explorer (clic here) Seems ok, but it shows a extrange result.
{ "language": "en", "url": "https://stackoverflow.com/questions/12979957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I stop my program from jumping to a different if-Statement after receiving an invalid input? I´m new to Stackoverflow and to Python. As my first own program I wrote a text game where you enter (a) or (b) and decide this way which decision your character makes. Its working out quite well, but I have one problem. If the user enters, for example, "a" on the first decision, "b" on the second decision, but something invalid on the third, the next valid input will trigger the first decision again instead of the third. I tried to make a short version which portrays my problem. Any help is appreciated. def test(): while True: input_zero = input("1. > ") if input_zero == "a": print("a") input_a = input("2. > ") if input_a == "a": print("a, a") break elif input_a == "b": print("a, b") break else: print("Invalid input.") elif input_zero == "b": print("b") input_b = input("2. > ") if input_b == "a": print("b, a") break elif input_b == "b": print("b, b") break else: print("Invalid input.") else: print("Invalid input.") test() A: So, packaging your choices into a dictionary, similar to that shown below, should make it slightly easier to manage the choices here, I think (there's almost certainly a better way than this). Then add to the empty string each time a choice is made and try to access the dictionary. If the choice is in the dictionary then it will recover a text string and an end-state, which will enable us to end the game when we need to. This approach also makes testing easier by using itertools to generate all possible combinations of states so you can work out which are missing. If an end_state is found (a value of 1 in the second position of the tuple), then you get the game over message and it closes the loop. If the element isn't in the dictionary, then the last selection was removed and the invalid_input function is called. def test(): choice_dict = {"a": (dP_lvl1.path_a, 0), "b": (dP_lvl1.path_b, 0), "c": (dP_lvl1.path_c, 1) "bb": (dP_lvl2.path_bb, 0), "aa": (dP_lvl2.path_aa, 0), "ba": (dP_lvl2.path_ba, 0), "ab": (dP_lvl2.path_ab, 0), "aaa": (dP_lvl3.path_aaa, 0), "aab": (dP_lvl3.path_aab 0), "aba": (dP_lvl3.path_aba, 0), "abb": (dP_lvl3.path_abb, 0), "bab": (dP_lvl3.path_bab, 0), "bba": (dP_lvl3.path_bba} 0), "bbb": (dP_lvl3.path_bbb, 0), "aaaa": (dP_lvl4.path_aaaa, 0), "abaa": (dP_lvl4.path_abaa, 0), "aaba": (dP_lvl4.path_aaba, 0), "aaab": (dP_lvl4.path_aaab, 1), "bbba": (dP_lvl4.path_bbba, 0), "bbab": (dP_lvl4.path_bbab, 0), "babb": (dP_lvl4.path_babb, 0), "abbb": (dP_lvl4.path_abbb, 0), "abba": (dP_lvl4.path_abba, 1), "abab": (dP_lvl4.path_abab, 0), "aabb": (dP_lvl4.path_aabb, 0), "baab": (dP_lvl4.path_baab, 0), "bbaa": (dP_lvl4.path_bbaa, 1), "baba": (dP_lvl4.path_baba, 0), "baaa": (dP_lvl4.path_baaa, 0), "bbbb": (dP_lvl4.path_bbbb, 0),} # etc. you get the idea decisions = "" playing = True while playing: decision = input("choose an option 'a' or 'b':") decisions += decision try: data, end_state = choice_dict[decisions] print(data) if end_state: playing = False print("Game over") else: continue except KeyError: decisions = decisions[:-1] invalid_input()
{ "language": "en", "url": "https://stackoverflow.com/questions/64248824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: why the kill function does not work in linux Possible Duplicate: Child process receives parent’s SIGINT the is my code in below The function is after the father receive the signal of CTRL-C. the father process send signal to son1 and son2; after the son1 and son2 exit, the father process exit; but the result does not like that; this is the answer son1 son2 ^Cheeell the son1 id 5963 the son2 id 5964 Parent process is killed !! who can help me, thank you before!! #include <stdio.h> #include <sys/signal.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #define SIGNAL_TO_SON1 10 #define SIGNAL_TO_SON2 12 #define FLAG_MSG_NO 0 #define FLAG_MSG_YES 1 int parent_msg = FLAG_MSG_NO; void signal_sendToParent( int sig ) { printf("heeell\n"); parent_msg = FLAG_MSG_YES; } int son1_flag = FLAG_MSG_NO; void signal_handle_son1( int sig ) { printf("handle_son1\n"); son1_flag = FLAG_MSG_YES; } int son2_flag = FLAG_MSG_NO; void signal_handle_son2( int sig ) { printf("handle_son2\n"); son2_flag = FLAG_MSG_YES; } int main( void ) { int pid1, pid2; if ( ( pid1 = fork() ) < 0 ) { printf("erro!!!!"); return -1; } if ( pid1 > 0 ) { // in the parent while( ( pid2 = fork() ) == -1); if ( pid2 == 0 ) { signal( SIGNAL_TO_SON2, signal_handle_son2 ); printf("son2\n"); // in the son2; while ( son2_flag != FLAG_MSG_YES ); { printf("Child process 2 is killed by parent !!\n"); exit(0); } }else{ // setup the signal signal( SIGINT, signal_sendToParent ); while ( parent_msg != FLAG_MSG_YES ); { kill( pid1, SIGNAL_TO_SON1 ); kill( pid2, SIGNAL_TO_SON2 ); wait(0); printf("the son1 id %d\n", pid1 ); printf("the son2 id %d\n", pid2 ); wait(0); int status , pid ; while( ( pid = waitpid( -1, &status, 0 ) ) > 0 ) { printf("child %d \n", pid ); } printf("Parent process is killed !!\n"); exit(0); } } }else{ // in the son1; printf("son1\n"); signal( SIGNAL_TO_SON1, signal_handle_son1 ); while ( son1_flag != FLAG_MSG_YES ); { printf("Child process 1 is killed by parent !!\n"); exit(0); } } return 0; } A: to get what you want you must ignore SIGINT in the childs. see this What happens to a SIGINT (^C) when sent to a perl script containing children? In short Ctrl-C is send to all processes in the foreground group. That means your child processes get SIGINT too, they do not have a handler and get killed. signal( SIGINT, SIG_IGN ); add in the child code, near setting the other signal handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/14126305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Hybris Backoffice update with ant updatesystem I want to update backoffice with ant updatesystem, I'm doing it this way: ant updatesystem -DconfigFile=configWithBackofficeExt.json For example - I have "Administration" and "MyWidget" widgets, I want to remove "Product Cockpit", so I remove config from *extension-backoffice-widgets.xml. And now, If I run my ant command - dropdownlist with widgets not updated. If I run an update from HAC or in backoffice with F4, all works fine. As far as I understand, there is no web-context when I running ant command, so there are no beans responsible for update/rebuild of widgets.xml(composed widget config, which we can see in orchestrator). Is there any way to attach backoffice web context, so that beans would be available when ant command called. Or maybe there is a more elegant way to do it? Ps: I know about config properties to update backoffice on startup/login, but still prefer to do it with ant. A: Finally, after research, I haven't find appropriate way to update backoffice with ant updatesystem. To update backoffice upon application start or/and login to backoffice we can use these properties: backoffice.cockpitng.reset.triggers=start,login backoffice.cockpitng.reset.scope=widgets,cockpitConfig When the application starts, configuration files will be reassembled and saved. This won't take much time(I didn't notice any impact on application startup time, with all OOTB backoffice extensions enabled, sometimes app took 10 sec longer to start, sometimes 10 sec faster).
{ "language": "en", "url": "https://stackoverflow.com/questions/48385903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: google tag manager v2 basic configuration I'm not getting hits on google analytics I'm working on a cordova/phonegap project. I'm using a plugin for GTM that allows me to track events. The problem is that I'm not getting hits on google analytics. According with the developer it's working fine, and from my testing, everything seems ok, no errors at all on Javascript console, and all events are firing correctly. Since I'm new with GTM, I believe that I'm missing something on configureting it. These are my confs: First, the GA tag: I used the built-in trigger "Any event" so it triggers every time an event is registered. This is the config I set for the GA tag, I want it to trigger on every event, that's why I left empty the fields And the GTM container type I'm using is "mobile". For I what haver been reading so far is far different from GTM V1 where I had to create macros, and another tag to be able to track this same information. I tried manual triggers such as, "Event matches RegEx .*" (which I believe it's the same as the built-in "Any event" trigger) A: You have to fill in the Category and Action field at the very least for GA to register a hit. (Categoira, Accion, I guess) Those aren't filter fields, they are the fields sent in an event hit. You will need to use something like the macros {{element text}} or something you want to record to see hits in GA. Check out the Event Tracking Guide by Google for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/30582680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What should be the lucene indexing and searching strategy for providing search capabilities to end user over set of unrelated business objects? I want to provide ability to end user to do a free form search over all business objects. The user will provide Lucene search expression. The business objects are completely unrelated and have nothing in common. Each business object comprises of there own specific attributes. For the sake of this question, the following are the business objects: Blog { Title; Body; } User { FirstName; LastName; Country; EmailAddress; Gender(M/F); } How could I create an index which can serve the following use-cases: * *Free form text search in both - Blog and User. For e.g. Search those users and blog entries where the word 'India' appears. End user should not be required to specify ORing between all Lucene document fields. *Free form text search for only users. For e.g. Search for those users where the word 'yahoo' appears. End user should not be required to specify ORing between all Lucene document fields related to User. *Free form text search for only blog entries. For e.g. Search for those blog entries where either of the word 'Skeet Async' appears. End user should not be required to specify ORing between all Lucene document fields related to Blog. *Free form text search by attributes for blog entries. For e.g. Search those blog entries where 'asynchronous' appears in the 'Title' attribute. *Free form text search by attributes for users. For e.g. Search those users where 'Skeet' appears in the 'LastName' attribute. How to define the index strategy - single index or multiple index, analyzer to use, how to provide context in the search query, etc. Thanks. A: For the given business objects, simplest way is to have lucene documents with the following fields: title, body, firstName, lastName, country, emailAddress, gender You might want to have title and user-related fields as STORED. Choice of analyzers depends on your search requirements (like do you want to support partial matches, suffix queries, stemming etc). Queries for the given use-cases: 1) title:india OR body:india OR country:india 2) title:yahoo OR body:yahoo OR emailAddress:yahoo 3) title:(Skeet OR Async) OR body:(Skeet OR Async) 4) title:asynchronous 5) lastName:skeet
{ "language": "en", "url": "https://stackoverflow.com/questions/14100211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SetInterval several elements at the same time Jquery I have this code, It appends comments after clicking on comment button. (the php processes via other function).... I want to simulate that every comment was posted at certain time, and the set interval after a while work independently with each li appendend. PROBLEM In the snippet it is shown that if I post a comment set interval works with it to show how long time ago it was posted (need format but it has the idea). The problem is that anytime I post a new comment, set intervals reloads all the previous times and shows the same results for all the comments. $('.comment').on('click', function(){ timeIni=$.now(); comment=$(".textarea").val(); $("#comments").append("<li data-t='"+timeIni+"'>"+comment+" <span>1s</span>"+"</li>"); $(".textarea").val(""); //adding the time to looks like /* */ setInterval(function(){ time=$.now(); tempo="time: "+time; $("#comments span").text(tempo); }, 2000); }); textarea{ height:30px; width:200px; border:1px solid red; display:block; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <ul id="comments"></ul> <textarea class=textarea></textarea> <input type=submit class="comment" value='comment' /> I want every comments shows its own time interval, according with the time it was posted. Other try using .each() https://jsfiddle.net/s8650s18/16/ A: You need to declare your variables with a keyword such as var, let, const otherwise the variable becomes global. All boils down to a scoping issue. let timeIni = Number($.now()); Here is the fiddle working: https://jsfiddle.net/s8650s18/22/
{ "language": "en", "url": "https://stackoverflow.com/questions/49330351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Objective c UIlabel is hang for a while when API is called As title, when users click a button as many times as they want, the uilabel will be updated to the number and the app will call an api to post the number to the server. Everything works fine except when the api is being called, the uilabel will hang for 2 - 5 seconds and will not update even the user is pressing the button. I have tried calling api in the background and update the ui in the main queue, it works but still will hang for a little while like 1 - 3 seconds. The reason I need to post the count to server is because there will be many users pressing the button simultaneously thus the label will be updated to total of all users. The flow: Users press button, as many as they want, uilabel will be updated to how many times the users have pressed the button, every 5 seconds an api will be called to post the count, uilabel will update the number again. Any suggestion to fix or enhance this issue? Thank you dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ [MyApiManager postHitCount:hitCountModel block:^(id object, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ [self setUpCount]; }); if ([self checkError:error]) return; }]; }); A: You need to add loader (activityIndicator) while your process start and hide while process complete . And you need to manage that while process is working user not interact any thing in the current view // Start here dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ [MyApiManager postHitCount:hitCountModel block:^(id object, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ [self setUpCount]; // stop here }); if ([self checkError:error]) // stop here return; }]; });
{ "language": "en", "url": "https://stackoverflow.com/questions/41948811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Animation in iOS 14 widget I can't find solution to implement kind of ProgressBar in Widget. I see, that Text component should be changed if has type .timer for example. I see default widget Clock, with nice animation of moving arrow. But am I able to implement custom animation in widget? A: According to a Frameworks Engineer on Developer Apple Forum: Animations and pan/zoom gesture do not work in widgets built with WidgetKits. Checkout https://developer.apple.com/videos/play/wwdc2020/10028/, where what works and doesn't. Throughout the WWDC20 Meet WidgetKit video mentioned above, Apple stresses that Widgets are not mini-apps, so they don't support gesture based views (like scroll views) or animations. Widgets are meant to only have glanceable information. From WWDC20 Meet WidgetKit Video Transcript: These widgets are not mini-apps. We do not support scrolling within the widget, interactive elements like switches and other system controls, nor videos or animated images.
{ "language": "en", "url": "https://stackoverflow.com/questions/64501754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: scope of variable in nodejs inside a function How to scope datat ? Here datat is empty. And i would like to put data in a var so i can use it outside the function. var datat; twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) { // and output to the console: datat = data; }); sys.puts(sys.inspect(datat)); Regards Bussiere A: 'datat' is scoped outside your function. twit.search is async and therefore may not return 'data' before you check 'datat' with sys.inspect. This should let you see datat: var datat; twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) { // and output to the console: datat = data; sys.puts(sys.inspect(datat)); }); But ideally you'd use a callback like this... var datat; var callback = function(d){ sys.puts(sys.inspect(d)); datat = d; // do something more with datat }; twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) { callback(data); }); EDIT - simplified as per comment... var datat; var callback = function(d){ sys.puts(sys.inspect(d)); datat = d; // do something more with datat }; twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt},callback(data));
{ "language": "en", "url": "https://stackoverflow.com/questions/15570142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create mutation between related types in GraphQL I'm using GraphQL to try to create a record that has a relation to another type. The types are Task and Day datamodel.graphql: type Task { id: ID! @unique content: String! completed: Boolean! dateToDo: Day! } type Day { id: ID! @unique content: String! tasks: [Task] } I want to create a task so that it has a reference of the date it should be completed (from the Day type) schema.graphql type Mutation { createTask(content: String!, completed: Boolean!, dateToDo: ID! ): Task! } my mutation resolver looks like this: const Mutations = { async createTask(parent, args, ctx, info) { const task = await ctx.db.mutation.createTask( { data: { dateToDo: { connect: { id: args.dateToDo } }, ...args } }, info ); return task; }, when I run this mutation to create the task: mutation CREATE_ONE_TASK { createTask( content: "a new task", completed: false, dateToDo: "cjqycv9dtjklr09179y9zfntq") { id } } I get this error: "message": "Variable \"$_v0_data\" got invalid value {\"dateToDo\":\"cjqycv9dtjklr09179y9zfntq\",\"content\":\"a new task\",\"completed\":false}; Expected type DayCreateOneWithoutTasksInput to be an object at value.dateToDo.", My questions are: Am I using connect correctly in the mutation resolver? And what the heck is DayCreateOneWithoutTasksInput (I see its been automagically added in prisma.graphql) and how do I use it to create a Task that has a relation to a Day's ID? A: The mutation to create the task has the following shape: mutation b { createTask( data: { content: "Task1" completed: false dateToDo: { connect: { id: "cjqzjvk6w000e0999a75mzwpx" } } } ) { id } } The type DayCreateOneWithoutTasksInput Prisma is asking for is autogenerated and is the one expected for the field dataToDo. The name means that Prisma would accept a type that creates one Day node but does not have the field tasks or a type that specifies a connection. The WithoutTasksInput part states is there because the type can only be used nested in a mutation where you start from a task, Prisma therefore already has the value to fill in for the tasks field on the nested Day node and you do not need to specify it if you create the day instead of connecting an existing one. If you use the Playground you can explore the schema that contains all the types on the right side. schema explorer in the playground Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/54222787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: why doesn't std::remove_copy_if() actually remove? Could this be the worst named function in the STL? (rhetorical question) std::remove_copy_if() doesn't actually appear to do any removing. As best I can tell, it behaves more like copy_if_not. The negation is a bit confusing, but can be worked around with std::not1(), however I might be misunderstanding something as I cannot fathom what this function has to do with removing - am I missing something? If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container? Editing to add an example so readers are less confused. The following program appears to leave the input range (V1) untouched: #include <vector> #include <iostream> #include <algorithm> #include <iterator> using std::cout; using std::endl; int main (void) { std::vector<int> V1, V2; V1.push_back(-2); V1.push_back(0); V1.push_back(-1); V1.push_back(0); V1.push_back(1); V1.push_back(2); std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(cout, " ")); cout << endl; std::remove_copy_if( V1.begin(), V1.end(), std::back_inserter(V2), std::bind2nd(std::less<int>(), 0)); std::copy(V2.begin(), V2.end(), std::ostream_iterator<int>(cout, " ")); cout << endl; std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(cout, " ")); cout << endl; } It outputs: -2 0 -1 0 1 2 0 0 1 2 -2 0 -1 0 1 2 I was expecting so see something like: -2 0 -1 0 1 2 0 0 1 2 0 0 1 2 ? ? ? Where ? could be any value. But I was surprised to see that the input range was untouched, & that the return value is not able to be used with (in this case) std::vector::erase(). (The return value is an output iterator.) A: is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container? The closest thing I can think of is std::stable_partition: std::vector<int> v; // ... auto it = std::stable_partition(v.begin(), v.end(), pick_the_good_elements); std::vector<int> w(std::make_move_iter(it), std::make_move_iter(v.end())); v.erase(it, v.end()); Now v will contain the "good" elements, and w will contain the "bad" elements. A: Could this be the worst named function in the STL? A bit of background information: in the standard library (or the original STL), there are three concepts, the containers, the iterators into those containers and algorithms that are applied to the iterators. Iterators serve as a cursor and accessor into the elements of a range but do not have a reference to the container (as mentioned before, there might not even be an underlying container). This separation has the nice feature that you can apply algorithms to ranges of elements that do not belong to a container (consider iterator adaptors like std::istream_iterator or std::ostream_iterator) or that, belonging to a container do not consider all elements (std::sort( v.begin(), v.begin()+v.size()/2 ) to short the first half of the container). The negative side is that, because the algorithm (and the iterator) don't really know of the container, they cannot really modify it, they can only modify the stored elements (which is what they can access). Mutating algorithms, like std::remove or std::remove_if work on this premise: they overwrite elements that don't match the condition effectively removing them from the container, but they do not modify the container, only the contained values, that is up to the caller in a second step of the erase-remove idiom: v.erase( std::remove_if( v.begin(), v.end(), pred ), v.end() ); Further more, for mutating algorithms (those that perform changes), like std::remove there is a non-mutating version named by adding copy to the name: std::remove_copy_if. None of the XXXcopyYYY algorithms are considered to change the input sequence (although they can if you use aliasing iterators). While this is really no excuse for the naming of std::remove_copy_if, I hope that it helps understanding what an algorithm does given its name: remove_if will modify contents of the range and yield a range for which all elements that match the predicate have been removed (the returned range is that formed by the first argument to the algorithm to the returned iterator). std::remove_copy_if does the same, but rather than modifying the underlying sequence, it creates a copy of the sequence in which those elements matching the predicate have been removed. That is, all *copy* algorithms are equivalent to copy and then apply the original algorithm (note that the equivalence is logical, std::remove_copy_if only requires an OutputIterator, which means that it could not possibly copy and then walk the copied range applying std::remove_if. The same line of reasoning can be applied to other mutating algorithms: reverse reverses the values (remember, iterators don't access the container) in the range, reverse_copy copies the elements in the range to separate range in the reverse order. If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container? There is no such algorithm in the STL, but it could be easily implementable: template <typename FIterator, typename OIterator, typename Pred> FIterator splice_if( FIterator first, FIterator last, OIterator out, Pred p ) { FIterator result = first; for ( ; first != last; ++first ) { if ( p( *first ) ) { *result++ = *first; } else { *out++ = *first; } } return result; } A: If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container? Not really. The idea is that the modifying algorithms are allowed to "move" (not in the C++ sense of the word) elements in a container around but cannot change the length of the container. So the remove algorithms could be called prepare_for_removal. By the way, C++11 provides std::copy_if, which allows you to copy selected elements from one container to another without playing funny logic games with remove_copy_if. A: You are right, that is what it does... std::remove_copy_if copies the vector, removing anything that matches the pred. std::remove_if ... removes on condition (or rather, shuffles things around). A: I agree that remove is not the best name for this family of functions. But as Luc said, there's a reason for it working the way it does, and the GoTW item that he mentions explains how it works. remove_if works exactly the same way as remove - which is what you would expect. You might also want to read this Wikibooks article.
{ "language": "en", "url": "https://stackoverflow.com/questions/11928115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Retrieve correct data from Core Data? I have a REST API and I want to save the responses with Core Data. I was trying to implement DATAStack and Sync but I can't understand how they work. I know I can save an object into Core Data and retrieve them. But I don't find how to retrieve the objects related to an specific URL that I requested before e.g: GET my_url.com/home_page { "posts":[ { "id": 1, "title": "Example Post", }, { "id": 2, "title": "Another example", } ] } and GET my_url.com/another_page { "posts":[ { "id": 4, "title": "This is another post", }, { "id": 5, "title": "Last Post", } ] } How do I get data from Core Data related to an URL request?
{ "language": "en", "url": "https://stackoverflow.com/questions/34397105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load data from SQL file to Realm Is it possible to have a SQL file inside Swift project where Realm database will import data as soon as project will be executed? I want to use a 30MB+ file of data... and don't want to download it all from a JSON API. A: Why not bundle a prebuilt Realm file as part of your application instead? To do this you'll need to: * *Create the prebuilt Realm file, either using Realm Browser or a simple Mac app of your own creation. *Add the prebuilt Realm file to your app target in your Xcode project, ensuring that it appears in the Copy Bundle Resources build phase. *Add code similar to that found in the above link to your app to have it open the prebuilt Realm file as read-only. Alternatively, you could copy the file out of your app bundle into the user's documents or cache directory and open it read-write.
{ "language": "en", "url": "https://stackoverflow.com/questions/39253223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting a Pandas datetime index on a DataFrame object to *MultiIndex* with the levels "month" and "year" Say I have a table of data with monthly datetime indices (the following code gives two years, january through december): import pandas as pd import numpy as np from datetime import datetime N = 12*2 c = [datetime(1970 + i//12, (i%12)+1, 1) for i in range(N)] d = pd.DataFrame(np.random.rand(N), index=c) print(d) What is the best way to convert the DateTimeIndex into a MultiIndex with the separate levels month and year? Perhaps there is a way to do this with groupby, but I'm not sure. A: You can construct a MultiIndex object from the year and month and assign it to the data frame's index: import pandas as pd d.index = pd.MultiIndex.from_arrays([d.index.year, d.index.month]) d.index # MultiIndex(levels=[[1970, 1971], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]], # labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]) d.head() # 0 #1970 1 0.657130 # 2 0.047241 # 3 0.984799 # 4 0.868508 # 5 0.678536 A: d.index = pd.MultiIndex.from_tuples(d.reset_index()['index'].\ apply(lambda x:(x.year,x.month)))
{ "language": "en", "url": "https://stackoverflow.com/questions/42640166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MediaPlayer audio doesn't stop immediately when stop() is called A button has onClickMethod openTheLock() which makes an ImageView visible and starts an audio. On tapping on the ImageView it disappears and the audio stops. Audio is initialized in onCreate(). The problem is the audio doesn't stop immediately when the ImageView is tapped. What could be the reason? MediaPlayer jokerAudio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_earth_room); jokerAudio= MediaPlayer.create(EarthRoomActivity.this, R.raw.joker_laugh); } public void openTheLock(View v){ if(selectedItem == R.id.key_er_item || keyUsed == true){ jokerAudio.start(); ImageView joker = (ImageView)parentLayout.findViewById(R.id.joker); joker.setVisibility(View.VISIBLE); joker.setOnClickListener(new OnClickListener(){ @Override public void onClick(View view) { jokerAudio.stop(); view.setVisibility(View.INVISIBLE); } }); } A: If you are not using the MediaPlayer again then you can try releasing the MediaPlayer. joker.setOnClickListener(new OnClickListener(){ @Override public void onClick(View view) { jokerAudio.stop(); jokerAudio.reset(); jokerAudio.release(); view.setVisibility(View.INVISIBLE); } }); However if you are using MediaPlayer again later in your code don't forget to reinitialize it again.
{ "language": "en", "url": "https://stackoverflow.com/questions/20004818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Contact form using nodemailer is not working I have created a contact form and trying to use nodemailer to send the message to my email, but not sure where is the issue. I created a server.js and put it in the main folder while Mailer.js that contain the form in components I am not sure how the server know that I want to use the form this is my first project on React and I think I still don't understand some basics of React const express = require('express'); const bodyParser = require('body-parser'); const exphbs = require('express-handlebars'); const path = require('path'); const nodemailer = require('nodemailer'); const app = express(); // View engine setup app.engine('handlebars', exphbs()); app.set('view engine', 'handlebars'); // Static folder app.use('/public', express.static(path.join(__dirname, 'public'))); // Body Parser Middleware app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.get('/', (req, res) => { res.render('contact'); }); app.post('/send', (req, res) => { const output = ` <p>You have a new contact request</p> <h3>Contact Details</h3> <ul> <li>Name: ${req.body.name}</li> <li>Email: ${req.body.email}</li> </ul> <h3>Message</h3> <p>${req.body.message}</p> `; // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.EMAIL, // generated ethereal user pass: process.env.PASSWORD // generated ethereal password }, tls:{ rejectUnauthorized:false } }); // setup email data with unicode symbols let mailOptions = { from: process.env.EMAIL, // sender address to: email, // list of receivers subject: 'Node Contact Request', // Subject line text: 'Hello world?', // plain text body html: output // html body }; // send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message sent: %s', info.messageId); console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info)); res.render('contact', {msg:'Email has been sent'}); }); }); app.listen(3000, () => console.log('Server started...')); This is the form import React from 'react'; import "./Mailer.scss"; const Mailer = () =>{ return ( <div className="container"> <div className="section ContactPage"> <div className="ContactPage-banner"> <h1 className="ContactPage-banner__title">Contact Us</h1> </div> <div className="ContactPage-content"> <form method="POST" className="form" action="send"> <div className="row"> <label className="labels">Name</label> <input type="text" name="name" className="input"/> </div> <div className="row"> <label className="labels">Email</label> <input type="email" name="email" className="input"/> </div> <div className="row"> <label className="labels">Message</label> <textarea name="message" rows='4' className="input"/> <input type="submit" value="Send"/> </div> </form> </div> </div> </div> ); }; export default Mailer; this is what I get when I click on SEND A: From what I could gather, you're posting to the wrong URL. In your server app, you create a post handler for /send However, in your React App, you post to /xxxxx/send (You obscured the xxxxx part) I advise that you replace your <form method="POST" className="form" action="send"> With <form method="POST" className="form" action="http://127.0.0.1:3000/send"> And try again
{ "language": "en", "url": "https://stackoverflow.com/questions/68369981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: c# html - hide kendo grid when empty I have the following Kendo grid in my html code and am trying to hide it if there is no data. I am confused on how to do this since I am using a datasource and not iterating through something to add data. @(Html.Kendo().Grid<CustomerQuickHistory>() .Name("TransactionDetails") .Columns(cols => { cols.Bound(c => c.DateOfItem).Format("{0:MM/dd/yyyy}"); cols.Bound(c => c.ProductName); cols.Bound(c => c.Price); }) .DataSource(ds => ds .Ajax() //.Group(g => g.Add(d => d.CustomerName)) .Sort(s => s.Add(ad => ad.DateOfItem).Descending()) .Read(r => r.Action("TransactionHistory_Read", "Customers", new { customerId = Model.CustomerId })) ) ) A: What about using the DataBound event handler to define check the dataSource binded and show or hide the grid. Here is an example of something similar, but in this case it shows a message when the grid is empty. http://blog.falafel.com/displaying-message-kendo-ui-grid-empty/ code example: @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>() .Name("grid") .Columns(columns => { columns.Bound(p => p.ProductName).Title("Product Name"); columns.Bound(p => p.UnitPrice).Title("Unit Price"); columns.Bound(p => p.UnitsInStock).Title("Units In Stock"); }) .Events(events => events.DataBound("onGridDataBound")) .DataSource(dataSource => dataSource .Ajax() .Read(read => read.Action("Products_Read", "Grid")) ) ) <script> function onGridDataBound(e){ var grid = e.sender; if (grid.dataSource.total() == 0 ){ //Hide grid $(grid).hide(); } else{ //Show grid $(grid).show(); } } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/35440681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to download receipt and invoice from stripe through my site I am using stripe from payment. After payment using invoice id how can i download receipt and invoice from my site
{ "language": "en", "url": "https://stackoverflow.com/questions/49974911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not able to install J2OBJC using terminal I have download the J2OBJC version and while running the command on terminal A:j2objc-master $ make dist I am getting below error building j2objc jar javac: invalid source release: 1.8 Usage: javac use -help for a list of possible options make[1]: * [/Users/Downloads/j2objc-master/translator/build_result/j2objc.jar] Error 2 make: * [translator] Error 2 Please suggest A: That's a javac error, stating that the version of javac on your system (which is part of the JDK you have installed) does not support the j2objc project's Java 8 minimum version. Upgrade your system to JDK 8 from Oracle to support this minimum.
{ "language": "en", "url": "https://stackoverflow.com/questions/45468200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 503 Error After Microsoft Request Routing Is Installed - 32 bit 64 bit madness I have a requirement to install the Microsoft Request Routing component for IIS 7.5 running on a Windows 2008 R2 SP1 64Bit machine. After installing Microsoft Request Routing via the Web Platform installer our ASP.NET 4.0 application gets a "HTTP Error 503. The service is unavailable." The Windows event log error details says: The Module DLL 'C:\Program Files\IIS\Application Request Routing\requestRouter.dll' could not be loaded due to a configuration problem. The current configuration only supports loading images built for a AMD64 processor architecture. The data field contains the error number. To learn more about this issue, including how to troubleshooting this kind of processor architecture mismatch error, see http://go.microsoft.com/fwlink/?LinkId=29349. I can make this error go away by changing the application pool to run in 32 bit mode by changing the "Enable 32-Bit Applications" setting to true. However I would prefer not to have to do that to resolve the issue. My questions are: * *Why is the Microsoft Request Routing feature trying to load a 32 bit version, isn't there a 64 bit version for it? *How do I resolve this issue without having to change my application pool to a 32 bit mode? A: having done some research into this I can inform you that there are currently two version of Microsoft's Application Request Routing one for 32-bit architecture and the other for 64-bit. Although it does not say, I would presume that the Web Platform Installer version is only for 32-bit, in order to get a 64-bit specific version you are going to have to download from one these two locations: http://blogs.iis.net/wonyoo/archive/2011/04/20/how-to-install-application-request-routing-arr-2-5-without-web-platform-installer-webpi.aspx or http://www.microsoft.com/en-us/download/details.aspx?id=7173 the blog (first URL) gives details on how to install into IIS once you have downloaded. hope this proves useful. A: What processor architecture are you using? The error seems to suggest that only 64bit AMD processors are currently supported, perhaps it might be worth looking into a solution more specific to your processor. I'm guessing your using an Intel CPU? I'm aware that there are certain scenarios where running IIS in 32 bit mode on a 64 bit system is required. A: it might be worth looking at these installation guidelines on the IIS site found at this address: http://www.iis.net/learn/extensions/installing-application-request-routing-%28arr%29/install-application-request-routing if these don't solve the issue it might well be worth either posting on the IIS forum: http://forums.iis.net/ or posting on technet forum: http://social.technet.microsoft.com/Forums/en-gb/categories/
{ "language": "en", "url": "https://stackoverflow.com/questions/12302847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: find common files between two directories - exclude file extension I have two directories with files that end in two different extensions: Folder A called profile (1204 FILES) file.fasta.profile file1.fasta.profile file2.fasta.profile Folder B called dssp (1348 FILES) file.dssp file1.dssp file2.dssp file3.dssp #<-- odd one out I have some files in folder B that are not found in folder A and should be removed for example file3.profile would be deleted as it is not found in folder A. I just want to retain those that are common in their filename, but excluding extension to end up with 1204 files in both I saw some bash lines using diff but it does not consider this case, where the ones I want to remove are those that are not found in the corresponding other file. A: Here is a way to do it: * *for both A and B directories, list the files under each directory, without the extension. *compare both lists, show only the file that does not appear in both. Code: #!/bin/bash >a.list >b.list for file in A/* do basename "${file%.*}" >>a.list done for file in B/* do basename "${file%.*}" >>b.list done comm -23 <(sort a.list) <(sort b.list) >delete.list while IFS= read -r line; do rm -v A/"$line"\.* done < "delete.list" # cleanup rm -f a.list b.list delete.list * *"${file%.*}" removes the extension *basename removes the path *comm -23 ... shows only the lines that appear only in a.list EDIT May 10th: my initial code listed the file, but did not delete it. Now it does. A: Try this Shellcheck-clean Bash program: #! /bin/bash -p folder_a=PATH_TO_FOLDER_A folder_b=PATH_TO_FOLDER_B shopt -s nullglob for ppath in "$folder_a"/*.profile; do pfile=${ppath##*/} dfile=${pfile%.profile}.dssp dpath=$folder_b/$dfile [[ -f $dpath ]] || echo rm -v -- "$ppath" done * *It currently just prints what it would do. Remove the echo once you are sure that it will do what you want. *shopt -s nullglob makes globs expand to nothing when nothing matches (otherwise they expand to the glob pattern itself, which is almost never useful in programs). *See Removing part of a string (BashFAQ/100 (How do I do string manipulation in bash?)) for information about the string manipulation mechanisms used (e.g. ${ppath##*/}). A: With find: find 'folder A' -type f -name '*.fasta.profile' -exec sh -c \ '! [ -f "folder B/$(basename -s .fasta.profile "$1").dssp" ]' _ {} \; -print Replace -print by -delete when you will be convinced that it does what you want. Or, maybe a bit faster: find 'folder A' -type f -name '*.fasta.profile' -exec sh -c \ 'for f in "$@"; do [ -f "folder B/$(basename -s .fasta.profile "$f").dssp" ] || echo rm "$f"; done' _ {} + Remove echo when you will be convinced that it does what you want. A: Python version: EDIT: now suports multiple extensions #!/usr/bin/python3 import glob, os def removeext(filename): index = filename.find(".") return(filename[:index]) setA = set(map(removeext,os.listdir('A'))) print("Files in directory A: " + str(setA)) setB = set(map(removeext,os.listdir('B'))) print("Files in directory B: " + str(setB)) setDiff = setA.difference(setB) print("Files only in directory A: " + str(setDiff)) for filename in setDiff: file_path = "A/" + filename + ".*" for file in glob.glob(file_path): print("file=" + file) os.remove(file) Does pretty much the same as my bash version above. * *list files in A *list files in B *get the list of differences *delete the differences from A Test output, done on Linux Mint, bash 4.4.20 mint:~/SO$ l drwxr-xr-x 2 Nic3500 Nic3500 4096 May 10 10:36 A/ drwxr-xr-x 2 Nic3500 Nic3500 4096 May 10 10:36 B/ mint:~/SO$ l A total 0 -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file1.fasta.profile -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.fasta.profile -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:14 file3.fasta.profile -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:36 file4.fasta.profile -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file.fasta.profile mint:~/SO$ l B total 0 -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:05 file1.dssp -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.dssp -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file3.dssp -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:05 file.dssp mint:~/SO$ ./so.py Files in directory A: {'file1', 'file', 'file3', 'file2', 'file4'} Files in directory B: {'file1', 'file', 'file3', 'file2'} Files only in directory A: {'file4'} file=A/file4.fasta.profile mint:~/SO$ l A total 0 -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file1.fasta.profile -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.fasta.profile -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:14 file3.fasta.profile -rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file.fasta.profile
{ "language": "en", "url": "https://stackoverflow.com/questions/72179324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Should I prevent branching if there will be perfect pattern so prediction should be good? My question is very much related to this question but something remained unclear for me after reading that question and very good answer. So as I understand it, the processor executing the code makes a branch prediction such that it already does the processing towards one branch in the hope that branch will be the one that needs to be executed. If it is wrong it will have to reroll some instructions which takes time. As I understand it the prediction is based on the pattern in the past. So now my question would be: if I know for sure there will be a pattern in what the if statement will evaluate to, is that just as fast when the decision would have been made at compile time? More specific for my case, I have a template function and I could do template specialization such that the decision is made on compile time, but in my opinion the code will be more clear if I use std:is_same inside my function. But speed is also highly important for my application so if speed might be compromised I would still rather go for template specialization although that will be less readable/maintainable in my specific case. (I could make the template specialization more readable as well, but it's a big code (not fully written by me) and I rather not go through the whole code and change many things to make it nice again. Yes basically I'm lazy.) (I think the question can go without MWE but if not I'll add some)
{ "language": "en", "url": "https://stackoverflow.com/questions/66545718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rust serde deserialize dynamic trait I have a recursive data structure in my pet-project: (this is a simplified example) pub trait Condition { fn validate(&self, s: &str) -> bool; } pub struct Equal { ref_val: String, } impl Condition for Equal { fn validate(&self, s: &str) -> bool { self.ref_val == s } } pub struct And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized { left: Box<A>, right: Box<B>, } impl<A, B> Condition for And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized { fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) } } and i want to serialize and de-serialize the condition trait (using serde) eg.: fn main() { let c = And { left: Box::new(Equal{ ref_val: "goofy".to_string() }), right: Box::new(Equal{ ref_val: "goofy".to_string() }), }; let s = serde_json::to_string(&c).unwrap(); let d: Box<dyn Condition> = serde_json::from_string(&s).unwrap(); } Because serde cannot deserialize dyn traits out-of-the box, i tagged the serialized markup, eg: #[derive(PartialEq, Debug, Serialize)] #[serde(tag="type")] pub struct Equal { ref_val: String, } and try to implement a Deserializer and a Vistor for Box<dyn Condition> Since i am new to Rust and because the implementation of a Deserializer and a Visitor is not that straightforward with the given documentation, i wonder if someone has an idea how to solve my issue with an easier approach? I went through the serde documentation and searched for solution on tech sites/forums. i tried out typetag but it does not support generic types UPDATE: To be more precise: the serialization works fine, ie. serde can serialize any concrete object of the Condition trait, but in order to deserialize a Condition the concrete type information needs to be provided. But this type info is not available at compile time. I am writing a web service where customers can upload rules for context matching (ie. Conditions) so the controller of the web service does not know the type when the condition needs to be deserialized. eg. a Customer can post: {"type":"Equal","ref_val":"goofy"} or {"type":"Greater","ref_val":"Pluto"} or more complex with any combinator ('and', 'or', 'not') {"type":"And","left":{"type":"Greater","ref_val":"Gamma"},"right":{"type":"Equal","ref_val":"Delta"}} and therefore i need to deserialze to a trait (dyn Condition) using the type tags in the serialized markup... A: I would say the “classic” way to solve this problem is by deserializing into an enum with one variant per potential “real” type you're going to deserialize into. Unfortunately, And is generic, which means those generic parameters have to exist on the enum as well, so you have to specify them where you deserialize. use serde::{Deserialize, Serialize}; use serde_json; // 1.0.91 // 1.0.152 pub trait Condition { fn validate(&self, s: &str) -> bool; } #[derive(PartialEq, Debug, Serialize, Deserialize)] pub struct Equal { ref_val: String, } impl Condition for Equal { fn validate(&self, s: &str) -> bool { self.ref_val == s } } #[derive(PartialEq, Debug, Serialize, Deserialize)] pub struct And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized, { left: Box<A>, right: Box<B>, } impl<A, B> Condition for And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized, { fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) } } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] enum Expr<A, B> where A: Condition + ?Sized, B: Condition + ?Sized, { Equal(Equal), And(And<A, B>), } fn main() { let c = And { left: Box::new(Equal { ref_val: "goofy".to_string(), }), right: Box::new(Equal { ref_val: "goofy".to_string(), }), }; let s = serde_json::to_string(&c).unwrap(); let d: Expr<Equal, Equal> = serde_json::from_str(&s).unwrap(); println!("{d:?}"); } Prints And(And { left: Equal { ref_val: "goofy" }, right: Equal { ref_val: "goofy" } }) A: I removed the generics from the combinator conditions, so i can now use typetag like @EvilTak suggested: #[derive(Serialize, Deserialize)] #[serde(tag="type")] pub struct And { left: Box<dyn Condition>, right: Box<dyn Condition>, } #[typetag::serde] impl Condition for And { fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) } } (on the downside, i had to remove the derive macros PartialEq, and Debug) Interesting side fact: i have to keep the #[serde(tag="type")] on the And Struct because otherwise the typetag will be omitted in the serialization (for the primitive consitions it is not needed) UPDATE: typetag adds the type tag only for trait objects so the #[serde(tag="type")] is not needed...
{ "language": "en", "url": "https://stackoverflow.com/questions/75413768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does dependency injection (in NestJS, for example) depends on TypeScript features? When applying the dependency injection pattern in NestJS, like in this example from the documentation: import { Controller, Get, Post, Body } from '@nestjs/common'; import { CreateCatDto } from './dto/create-cat.dto'; import { CatsService } from './cats.service'; import { Cat } from './interfaces/cat.interface'; @Controller('cats') export class CatsController { constructor(private catsService: CatsService) {} // Some other methods... } How does this work? As far as I understand, TypeScript will be compiled to plain JavaScript, and then the class type (CatsService) will disappear. How does NestJS know what class to inject in this case? A: Dependency injection does not depend on the typescript. Whenever we boot up the nest app, a Dependency Injection (DI) container gets created for us. DI is just an object. Nest will look at the all different classes that we created except controllers. It will register all those different classes with the DI container. The container will check all the dependencies that are required for each class and map this class to its dependencies: class1 ---> dependencies class2 ---> dependencies class3 ---> it might now have any dependency Then eventually we want to create the controller. we tell DI to create the controller with the required dependencies. DI will look at the constructor argument and see all the dependencies that are required. the container will see that it needs to create a service and service needs to create some dependencies. So DI container will create the instances of required dependencies and store each instance internally so if in the future another class needs to those instances it can use them. Now dependencies are already created and DI container will use those to create the Controller and return it. As you see we do not worry about creating all those services ourselves. DI container will take care of it for us. Dependency injection is used for reusing the code and test the app easier. A: Take a look at the example. This: @Injectable() export default class RequestService { constructor( @InjectRepository(RequestEntity) private requestEntityRepository: Repository<RequestEntity>, ) {} Is being transpiled to this: let RequestService = class RequestService { constructor(requestEntityRepository) { this.requestEntityRepository = requestEntityRepository; } ... RequestService = __decorate([ common_1.Injectable(), __param(0, typeorm_1.InjectRepository(RequestEntity_1.default)), __metadata("design:paramtypes", [typeorm_2.Repository]) ], RequestService); exports.default = RequestService; A: Dependency injection in general does not depend on typescript, and even in NestJS it can be done in (mostly) plain JavaScript by using Babel as a transpiler. I've gone into a bit of detail here about how the decorators work with typescript, and Semyon Volkov has shown how the decorators transpile as well. So inherently, no, it doesn't depend on Typescript, the way Nest wants you to do it (being opinionated and all) does. In your example, Nest will read the type of design:paramtypes and see that there is a CatsService class, so it knows to match up the class names and inject a CatsService here. There's a lot more going on under the hood, when it comes to keeping track of what modules have access to what, but that's the general idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/65807414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Assigning to a quosure in R / dplyr / rlang Within a function, I want to update-in-place the values of columns specified by the user, where the user specified column names are captured via enquo(). So, here's a simplified example: f1 <- function(df, x, y) { x <- enquo(x) y <- enquo(y) df %>% mutate((!! x) := (!! x)^2, (!! y) := (!! y)+1) } dat <- data.frame(a=1:10, b=10:1) f1(dat, x=a, y=b) This fails with an error: "The LHS of := must be a string or a symbol". I've also tried replacing, for example, (!! x) with quo_get_expr(x) and f_text(x), but get the same error. For example: f1 <- function(df, x, y) { x <- enquo(x) y <- enquo(y) df %>% mutate(quo_get_expr(x) := (!! x)^2, quo_get_expr(y) := (!! y)+1) } Can anyone point out what I'm doing wrong? I'm using R 4.1, dplyr 0.7.4, and rlang 0.2.0 Thanks in advance. A: You need to use quo_name. This works: f1 <- function(df, x, y) { x <- enquo(x) y <- enquo(y) df %>% mutate( !!quo_name(x) := (!!x)^2, !!quo_name(y) := (!!y)+1) } dat <- data.frame(a=1:10, b=10:1) f1(dat, x=a, y=b)
{ "language": "en", "url": "https://stackoverflow.com/questions/50050783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why my key commands are not working My issue is that my javascript is not seeing when i push my key down to move the object on the screen. So here is my java script code: var canvas = document.getElementById("maincanvas"); var context = canvas.getContext("2d"); var keys = []; var width = 500, height = 400, speed = 3; var player = { x: 10, y: 10, width: 20, height: 20 }; window.addEventListener("keydown", function (e) { keys[e.keycode] = true; }, false); window.addEventListener("keyup", function (e) { delete keys[e.keycode]; }, false); /* up - 38 down - 40 left - 37 right - 39 */ function game() { update(); render(); } function update() { if (keys[38]) player.y -= speed; if (keys[40]) player.y += speed; if (keys[37]) player.x -= speed; if (keys[39]) player.x += speed; } function render() { context.clearRect(0, 0, 100, 100) context.fillRect(player.x, player.y, player.width, player.height); } setInterval(function () { game(); }, 1000 / 30); if you can not tell i am very new to this and just learning the basics. A: The value you want out of the event object is called keyCode, not keycode: var canvas = document.getElementById("maincanvas"); var context = canvas.getContext("2d"); var keys = []; var width = 500, height = 400, speed = 3; var player = { x: 10, y: 10, width: 20, height: 20 }; window.addEventListener("keydown", function(e) { keys[e.keyCode] = true; }, false); window.addEventListener("keyup", function(e) { delete keys[e.keyCode]; }, false); /* up - 38 down - 40 left - 37 right - 39 */ function game() { update(); render(); } function update() { if (keys[38]) player.y -= speed; if (keys[40]) player.y += speed; if (keys[37]) player.x -= speed; if (keys[39]) player.x += speed; } function render() { context.clearRect(0, 0, 100, 100) context.fillRect(player.x, player.y, player.width, player.height); } setInterval(function() { game(); }, 1000 / 30); <canvas id="maincanvas"></canvas> A: Another issue you might be running into is that keys is an array and you are treating it like an object. keys[38] is looking for a key at index 38 NOT a key with a value of 38. Set keys = {}; Edit Never mind, I see you are just setting the index at 38. I would say it's a little bit of a weird approach, consider using an object rather than an array.
{ "language": "en", "url": "https://stackoverflow.com/questions/37126563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How React rerenders tree, if both parent and child components are dependent from one Redux store prop? I have Layout component, which checks if a user is logged in. It simply examines user prop in Redux store. If it is, it renders children, otherwise Login. * *Layout.jsx const Layout = ({ user, children }) => { if (user) return children; return <Login />; }; export default connect(state => ({ user: state.user }))(Layout); * *Profile.jsx const Profile = ({ user }) => <div>{user.name}</div>; export default connect(state => ({ user: state.user }))(Profile); * *App itself <Layout> <Profile /> </Layout> The issue is when Profile component is rendered and I log out, I get can not read property name of undefined. I expect Profile component not to be rendered at all, because it is how Layout works. But looks like React first tries updating Profile component and fails. For now I ended up returning null from Profile if there is no user, but it's not ideal. So if both parent and child components are dependent on one Redux store prop, React rerenders them from down to the top, from top to down, or simultaneously? Is there a canonical or best practice way to avoid it?
{ "language": "en", "url": "https://stackoverflow.com/questions/47631930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error MSB3073 when creating a Monogame C# project in Visual Studio 2019 So I'm trying to simply create a new Monogame project in Visual Studio 2019 with C#, and every time I create a new project, the following error appears: Error MSB3073 - The command "dotnet C:\Users\<name>\.nuget\packages\monogame.content.builder.task\3.8.0.1641\build\\..\tools\netcoreapp3.1\any\mgcb.dll /quiet /@:"E:\Programming\Locally-stored projects\C Family\C#\Monogame -OxygOS\Game1\Game1\Content\Content.mgcb" /platform:DesktopGL /outputDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/bin/DesktopGL/Content" /intermediateDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/obj/DesktopGL/Content" /workingDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/"" exited with code 1. Game1 C:\Users\<name>\.nuget\packages\monogame.content.builder.task\3.8.0.1641\build\MonoGame.Content.Builder.Task.targets 138 The only files in the projects are ones that are automatically created as part of the Monogame Cross-platform template. I've already looked on Google and Stack Overflow, and, while there are answers, I haven't found any that have helped me. Apologies if I messed up while creating the post, this is my first Stack Overflow question :D I may have messed up the formatting somewhere so sorry in advance if I have. A: It is a better approach that you would use the terminal to create your project (and then open them in Visual Studio). It is far more convenient for the Monogame community to release NuGet templates of the projects rather than releasing plugins for Visual Studio, and therefore it is safe to assume that Monogame won't be releasing such plugins for Visual Studio anytime soon. Make sure you have dotnet-sdk installed and the Monogame tools are installed by doing all the steps mentioned here, Including the last two scripts dotnet tool install --global dotnet-mgcb-editor mgcb-editor --register and dotnet new --install MonoGame.Templates.CSharp Now use the command dotnet new to view all the templates. You will probably see an output such as Templates Short Name Language Tags ------------------------------------------------------ ------------------- ------------ ---------------------- ... ... MonoGame Android Application mgandroid [C#] MonoGame MonoGame Cross-Platform Desktop Application (OpenGL) mgdesktopgl [C#] MonoGame MonoGame iPhone/iPad Application mgios [C#] MonoGame MonoGame Windows Universal Application (CoreApp) mguwpcore [C#] MonoGame MonoGame Windows Universal Application (XAML) mguwpxaml [C#] MonoGame MonoGame Windows Desktop Application (Windows DirectX) mgwindowsdx [C#] MonoGame MonoGame NetStandard Library mgnetstandard [C#] MonoGame MonoGame Pipeline Extension mgpipeline [C#] MonoGame MonoGame Shared Library Project mgshared [C#] MonoGame ... ... Select the project you want to create, for example dotnet new mgwindowsdx -o MyGame This will create a folder "MyGame" and put the code for your game. You can open the .csproj file using Visual Studio.
{ "language": "en", "url": "https://stackoverflow.com/questions/65752265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: webpack -- how to include nodejs module for js/jsx in non-current directory Trying to include a npm module in my jsx. My dir structure is something like: app/ node_modules/ webpack.config.json package.json main.js react/ myreact1.jsx myreact2.jsx Note: purposely do not want a package.json & node_modules in react/ I've figured out that I have to do this for webpack2 config: resolve: { modules: ["node_modules", path.resolve(__dirname, "node_modules") } This forces webpack to first always try ./node_modules, then default to app/node_modules However, for the module I'm trying to include in myreact.jsx (npm: "request"), this module uses alot of native node libraries like "fs" and "tls", etc. webpack now gives me this error: Abbreviated error: ERROR in ./~/request/lib/har.js Module not found: Error: Can't resolve 'fs' in '/myproj/app/node_modules/request/lib' @ ./~/request/lib/har.js 3:9-22 @ ./~/request/request.js @ ./~/request/index.js @ ../react/myreact1.jsx @ ./app.jsx @ ./main.js Display-error-details version of the error: ERROR in ./~/request/lib/har.js Module not found: Error: Can't resolve 'fs' in '/myproj/app/node_modules/request/lib' resolve 'fs' in '/myproj/app/node_modules/request/lib' How do I get webpack to correctly find the native node modules 'fs', 'tls', 'net' etc for 'request' module and the other 3rd party modules it uses inside it's own node_modules? Thanks for any help
{ "language": "en", "url": "https://stackoverflow.com/questions/41784512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JsnLog error posting in angular 4 with elmah at server side We are using Asp.net Web API 2 - Server side Angular 4 in client side (angular-cli) We have integrated Elmah on the server side for error handling. We have integrated Jsnlog in the client side. Our angular released version is hosted in http://ng.local.com and API released version is hotsed in http://api.local.com/. Now, We have gone through the docs of Jsnlog configuration. But, facing issue in error posting to the server (to our api released http://api.local.com/) i.e missing some configuration. Can anyone know the configuration for Jsnlog to have the URL of the API server. A: There is information found here to configure the endpoint for JSNLog. Take a look at the "Configuring JSNLog" Section of this page (http://jsnlog.com/Documentation/HowTo/Angular2Logging and http://jsnlog.com/Documentation/JSNLogJs/AjaxAppender/SetOptions). But to summarize, just add this line to your app.module.ts before the @NgModule({... // Set the endpoint for JSNLog. JL().setOptions({ 'appenders': [JL.createAjaxAppender('example appender').setOptions({'url': [Your Desired Endpoint Address] + '/jsnlog.logger'})] }); @NgModule({ ...
{ "language": "en", "url": "https://stackoverflow.com/questions/46258110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Freeing map of struct I am working with a very large map of pointer to struct. It is growing over the lifetime of the program (I use it as a buffer) and I wrote a function that is supposed to reduce it size when it is called. type S struct { a uint32 b []uint32 } s := make(map[uint32]*S) for k, v := range s { delete(s, k) s[k] = &S{a: v.a} } I remove b from every element of the map, so I expected the size of the map in memory to shrink (b is a slice of length > 10). However the memory is not freed, why? A: The size of the map value &S, a pointer, is the same irrespective of the capacity of slice b. package main import ( "fmt" "unsafe" ) type S struct { a uint32 b []uint32 } func main() { size := unsafe.Sizeof(&S{}) fmt.Println(size) size = unsafe.Sizeof(&S{b: make([]uint32, 10)}) fmt.Println(size) s := make(map[uint32]*S) for k, v := range s { delete(s, k) s[k] = &S{a: v.a} } } Output: 8 8 A slice is represented internally by type slice struct { array unsafe.Pointer len int cap int } When you set &S{a: v.a} you set b to initial values: array to nil and len and cap to zero. The memory formerly occupied by the underlying array is returned to the garbage collector for reuse. A: The map size is bounded to the maximum size it had at any point. Because you store pointers (map[uint32]*S) and not values the deleted objects will get garbage collected eventually but usually not immediately and that why you don’t see it in top/htop like monitors. The runtime is clever enough and reserves memory for future use if the system is not under pressure or low on resources. See https://stackoverflow.com/a/49963553/1199408 to understand more about memory. In your example you don't need to call delete. You will achieve what you want just by clearing the slice in the struct. type S struct { a uint32 b []uint32 } s := make(map[uint32]*S) for k, v := range s { v.b = []uint32{} }
{ "language": "en", "url": "https://stackoverflow.com/questions/56728142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Add Web Interface to existing Project I tried to understand this several times allready, but still have not found out how this should be done. I want to create a web interface for some existing console or swing application. Something like the web interface SABNzb offers (I know, it's Python – it's just an example). I have looked at several technologies allready, like creating web services using a tomcat server, or java server pages/faces, but all the tutorials that I found so far start with "Create a new Web Project..." at wich point I stop because this is not what I want! I have a finished an application in which I want to integrate a web interface, not some web service that instantiates my program as a local variable and uses its code. So basicaly it feels like all the tutorials I find are the wrong way around. The core procedure of this is clear, the application should listen for http requests on a port I choose and answer with a created html code to it. So basicaly I could open a port using a socket and write an html page to its output on connect. But this rather feels like inventing the wheel all over again, also I'm not sure how an interactive web page would work this way. Maybe I am thinking somewhat strange here or did not understand how some of these things work, but I am pretty unexperienced with web technologies, so grasping the concept is rather hard at the moment. Can anyone point me to a tutorial that shows how this might be done, or some other source of information on it? A: You don't need JSP or JSF; all you need is a servlet. It's an HTTP listener class. You can do REST with that. The moment you say that you have to deploy your servlet in a WAR on a servlet/JSP engine. Tomcat is a good choice. Google for a servlet tutorial and you'll be on your way. My First Tomcat Servlet A: Ok, thanks to duffymos answer and comments i realized i was actualy searching with the wrong keywords. Embedded web server is the thing i was looking for. Like Simple or build in HTTPServer class in java.
{ "language": "en", "url": "https://stackoverflow.com/questions/26777222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: not able to match code between two comments, mutiple times I want to get content between two comments in some file. like a file x #user code alert(""); alert(""); #user code { === ==== } #user code alert("as"); alert("as"); #user code i am using this regex pattern to match final Pattern pat = Pattern.compile("//#User code\r?\n(.*)\r?\n//#User code" , Pattern.DOTALL); but its matching from first #user code to end of the file. pls help. A: A quick fix is to use .*? instead of just .*. The ? changes the * into a non-greedy repetition, which will match up until the nearest #user code, instead of the furthest.
{ "language": "en", "url": "https://stackoverflow.com/questions/13638860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Snakemake container for htslib (bgzip + tabix) I have a pipeline which uses a global singularity image and rule-based conda wrappers. However, some of the tools don't have wrappers (i.e. htslib's bgzip and tabix). Now I need to learn how to run jobs in containers. In the official documentation link it says: "Allowed image urls entail everything supported by singularity (e.g., shub:// and docker://)." Now I've tried the following image from singularity hub but I get an error: minimal reproducible example: config.yaml # Files REF_GENOME: "c_elegans.PRJNA13758.WS265.genomic.fa" GENOME_ANNOTATION: "c_elegans.PRJNA13758.WS265.annotations.gff3" Snakefile # Directories------------------------------------------------------------------ configfile: "config.yaml" # Setting the names of all directories dir_list = ["REF_DIR", "LOG_DIR", "BENCHMARK_DIR", "QC_DIR", "TRIM_DIR", "ALIGN_DIR", "MARKDUP_DIR", "CALLING_DIR", "ANNOT_DIR"] dir_names = ["refs", "logs", "benchmarks", "qc", "trimming", "alignment", "mark_duplicates", "variant_calling", "annotation"] dirs_dict = dict(zip(dir_list, dir_names)) GENOME_INDEX=config["REF_GENOME"]+".fai" VEP_ANNOT=config["GENOME_ANNOTATION"]+".gz" VEP_ANNOT_INDEX=config["GENOME_ANNOTATION"]+".gz.tbi" # Singularity with conda wrappers singularity: "docker://continuumio/miniconda3:4.5.11" # Rules ----------------------------------------------------------------------- rule all: input: expand('{REF_DIR}/{GENOME_ANNOTATION}{ext}', REF_DIR=dirs_dict["REF_DIR"], GENOME_ANNOTATION=config["GENOME_ANNOTATION"], ext=['', '.gz', '.gz.tbi']), expand('{REF_DIR}/{REF_GENOME}{ext}', REF_DIR=dirs_dict["REF_DIR"], REF_GENOME=config["REF_GENOME"], ext=['','.fai']), rule download_references: params: ref_genome=config["REF_GENOME"], genome_annotation=config["GENOME_ANNOTATION"], ref_dir=dirs_dict["REF_DIR"] output: os.path.join(dirs_dict["REF_DIR"],config["REF_GENOME"]), os.path.join(dirs_dict["REF_DIR"],config["GENOME_ANNOTATION"]), os.path.join(dirs_dict["REF_DIR"],VEP_ANNOT), os.path.join(dirs_dict["REF_DIR"],VEP_ANNOT_INDEX) resources: mem=80000, time=45 log: os.path.join(dirs_dict["LOG_DIR"],"references","download.log") singularity: "shub://biocontainers/tabix" shell: """ cd {params.ref_dir} wget ftp://ftp.wormbase.org/pub/wormbase/releases/WS265/species/c_elegans/PRJNA13758/c_elegans.PRJNA13758.WS265.genomic.fa.gz bgzip -d {params.ref_genome}.gz wget ftp://ftp.wormbase.org/pub/wormbase/releases/WS265/species/c_elegans/PRJNA13758/c_elegans.PRJNA13758.WS265.annotations.gff3.gz bgzip -d {params.genome_annotation}.gz grep -v "#" {params.genome_annotation} | sort -k1,1 -k4,4n -k5,5n -t$'\t' | bgzip -c > {params.genome_annotation}.gz tabix -p gff {params.genome_annotation}.gz """ rule index_reference: input: os.path.join(dirs_dict["REF_DIR"],config["REF_GENOME"]) output: os.path.join(dirs_dict["REF_DIR"],GENOME_INDEX) resources: mem=2000, time=30, log: os.path.join(dirs_dict["LOG_DIR"],"references", "faidx_index.log") wrapper: "0.64.0/bio/samtools/faidx" Error Building DAG of jobs... Pulling singularity image shub://biocontainers/tabix. WorkflowError: Failed to pull singularity image from shub://biocontainers/tabix: ESC[31mFATAL: ESC[0m While pulling shub image: failed to get manifest for: shub://biocontainers/tabix: the requested manifest was not found in singularity hub File "/home/moldach/anaconda3/envs/snakemake/lib/python3.7/site-packages/snakemake/deployment/singularity.py", line 88, in pull ~ It appears this is a problem with the container? (snakemake) [moldach@arc CONTAINER_TROUBLESHOOT]$ singularity pull shub://biocontainers/tabix FATAL: While pulling shub image: failed to get manifest for: shub://biocontainers/tabix: the requested manifest was not found in singularity hub In fact, I experience this problem with other biocontainers containers. For example, I also need to use a container to do bowtie2 indexing and this is the error I get from the biocontainers/bowtie2 versus another developers container of the same tool comics/bowtie2: ^C(snakemake) [moldach@arc CONTAINER_TROUBLESHOOT]$ singularity pull docker://biocontainers/bowtie2 FATAL: While making image from oci registry: failed to get checksum for docker://biocontainers/bowtie2: Error reading manifest latest in docker.io/biocontainers/bowtie2: manifest unknown: manifest unknown (snakemake) [moldach@arc CONTAINER_TROUBLESHOOT]$ singularity pull docker://comics/bowtie2 INFO: Converting OCI blobs to SIF format INFO: Starting build... Getting image source signatures Copying blob a02a4930cb5d done Does anyone know why? A: Biocontainers does not allow latest as tag for their containers, and therefore you will need to specify the tag to be used. From their doc: The BioContainers community had decided to remove the latest tag. Then, the following command docker pull biocontainers/crux will fail. Read more about this decision in Getting started with Docker When no tag is specified, it defaults to latest tag, which of course is not allowed here. See here for bowtie2's tags. Usage like this will work: singularity pull docker://biocontainers/bowtie2:v2.4.1_cv1 A: Using another container solves the issue; however, the fact I'm getting errors from biocontainers is troubling given that these are both very common and used as examples in the literature so I will award the top-answer to whomever can solve that specific issue. As it were, the use of stackleader/bgzip-utility solve the issue of actually running this rule in a container. container: "docker://stackleader/bgzip-utility" Once again, for those coming to this post, it's probably best to test any container first before running snakemake, e.g. singularity pull docker://stackleader/bgzip-utility.
{ "language": "en", "url": "https://stackoverflow.com/questions/64050974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AngularJS form gets pristine but still submitted According to the source of AngularJS (1.3.15), the FormController's method $setPristine() resets the forms $submitted status to false: form.$setPristine = function() { $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); form.$dirty = false; form.$pristine = true; form.$submitted = false; forEach(controls, function(control) { control.$setPristine(); }); }; The problem is that after submitting and calling this method inside a controller, the form reverts to $submitted = false. Is that expected or a bug? A: The reason you are seeing this behavior is that the reset button does not have type="button" or type="reset" attribute and therefore it behaves as a submit button by default. So the ng-click that sets the form to pristine actually set $submitted to false correctly, but immediately afterwards, the form is submitted again. app.js var app = angular.module('plunker', []); app.controller('MainCtrl', function() { this.data = { name: '' }; this.reset = function(form) { this.data.name = ''; form.$setPristine(); }; }); HTML Page: <html ng-app="plunker"> <head> <title>form.$submitted</title> <script src="http://code.angularjs.org/1.3.2/angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-controller="MainCtrl as ctrl"> <form name="form" novalidate> <input name="name" ng-model="ctrl.data.name" placeholder="Name" required /> <input type="submit" /> <button type="button" class="button" ng-click="ctrl.reset(form)">Reset</button> </form> <pre> Pristine: {{form.$pristine}} Submitted: {{form.$submitted}} </pre> </div> http://plnkr.co/edit/kRxEVu?p=preview Hope this is the one that you have wanted Source: https://github.com/angular/angular.js/issues/10006#issuecomment-62640975 A: You can reset the form after submit by adding $setUntouched() & $setPristine() to the form name after submitting the form OR on success of your Ajax request. Eg:- <form name="userDetailsForm" ng-submit="addUserDetails(userDetailsForm.$valid)" novalidate> <div class="field name-field"> <input class="input" type="text" name="name" ng-model="form.data.name" required placeholder="First Name + Last Name" /> <div ng-if="userDetailsForm.$submitted || userDetailsForm.name.$touched" ng-messages="signupForm.name.$error"> <div ng-message="required">You did not enter your name</div> </div> </div> <input type="submit" value="Add Details" class="btn btn-default" /> </form> $scope.addUserDetails = function(valid) { if(!valid) return; //Your Ajax Request $scope.userDetailsForm.$setUntouched(); $scope.userDetailsForm.$setPristine(); };
{ "language": "en", "url": "https://stackoverflow.com/questions/29549821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL if value exists select else insert What is the most efficient mysql query to SELECT from a table IF a value already exists ELSE INSERT? I have already tried several options but can't find something that works for me. A: I'm new to Stackoverflow and dont know how to tag a question as duplicate. But i think there is a really similar question with plenty of answers. Give a look here [Possible solution] You could insert if it not exists and then select it. INSERT INTO Test(Key_Value , Name , ...) VALUES(@Key_Value ,@Name,..) WHERE NOT EXISTS (SELECT 1 FROM Test WHERE KeyValue = @KeyValue); SELECT Name FROM Test WHERE Key_Value = @Key_Value
{ "language": "en", "url": "https://stackoverflow.com/questions/28990506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reattempt to pay a subscription that payment method failed with another payment method? I'm using stripe to subscribe, so I have this issue. When I subscribe and the card does not have sufficient funds, the subscription object is created So my question is how can I reattempt to pay the subscription that I just created. I am guiding from this example: https://stripe.com/docs/billing/subscriptions/fixed-price Here is a photo of the function that is supposed to do the retry, but all it does is change the user's default card. A: It's described further down that document, right here: https://stripe.com/docs/billing/subscriptions/fixed-price#manage-subscription-payment-failure
{ "language": "en", "url": "https://stackoverflow.com/questions/64165905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Incorrect behavior of a pointer in function in C I have a problem with the following program. The main function calls the function returnArrayOfWords(arrS1, &ptrArray1) twice. On the first call, the array is parsed perfectly, and afterward the pointer always points to the first word. On the other hand, after the second call, the pointer of the first array points to the second word, the third word, or sometimes the first word, but it should always point to the first word -- nowhere else. Why does the function misbehave when called for the second time? #include <stdio.h> #include <string.h> #include <stdlib.h> void returnArrayOfWords (char *str4Parsing, char *arrayParsed[]) { char seps[] = " ,\t\n"; // separators char *token1 = NULL; char *next_token1 = NULL; int i = 0; // Establish string and get the first token: token1 = strtok_s( str4Parsing, seps, &next_token1); // While there are tokens in "str4Parsing" while (token1 != NULL) { // Get next token: if (token1 != NULL) { arrayParsed[i] = token1; printf( " %s\n", token1 ); token1 = strtok_s( NULL, seps, &next_token1); i++; } } } //int main1 () int main () { int i, j, n = 80; /*max number of words in string*/ char arrS1[80], arrS2[80]; const char *w1, *w2; /*pointers*/ char *ptrArray1, *ptrArray2; int currLength1 = 0, currLength2 = 0 ; int sizeArr1 = 0, sizeArr2 = 0; int maxLength = 0; char wordMaxLength ; printf("Type your first string: "); fgets(arrS1, 80, stdin); returnArrayOfWords(arrS1, &ptrArray1); sizeArr1 = sizeof(ptrArray1) / sizeof(ptrArray1[0]); printf("Type your second string: "); fgets(arrS2, 80, stdin); returnArrayOfWords(arrS2, &ptrArray2); sizeArr2 = sizeof(ptrArray2) / sizeof(ptrArray2[0]); for (i = 0; i < sizeArr1; i++) { // to find the largest word in the array w1 = &ptrArray1[i]; currLength1 = strlen(w1); for (j = 0; j < sizeArr2; j++) { w2 = &ptrArray2[j]; currLength2 = strlen(w2); if (strcoll(w1, w2) == 0) // compares the strings { if (currLength2 >= maxLength) // in the 0th element -> the length of the longest word { maxLength = currLength2; wordMaxLength = ptrArray2[j]; } } } } printf("The largest word is: %s", wordMaxLength); return 0; } EDIT: Here's the latest version of the code, everything here works fine, managed to fix it myself. I'm just posting it in case somebody needs it as a solution: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stddef.h> #include <ctype.h> #define n 80 /*max number of words in string*/ /* Arrays and pointers */ int returnArrayOfWords (char *str4Parsing, char *arrayParsed[]) { // returns the length of array int elArr = 0, na = 0; char *delim = " .,;-\t\n"; /* word delimiters */ char *next_token1 = NULL; char *ap = str4Parsing; /* pointer to str4Parsing */ for (ap = strtok_s (str4Parsing, delim, &next_token1); ap; ap = strtok_s( NULL, delim, &next_token1)) { arrayParsed[na++] = ap; elArr++; } return elArr; } void printArr(char *arr[]) { int i; for ( i = 0; i < n; i++) { printf("Element %d is %s \n", i, arr[i]); } } void findLargestWord(char *ptrArray1[], int sizeArr1, char *ptrArray2[], int sizeArr2) { size_t maxLength = 0; char *wordMaxLength = NULL ; int i = 0, j = 0; char *w1 = NULL, *w2 = NULL; /*pointers*/ size_t currLength1 = 0, currLength2 = 0 ; for (i = 0; i < sizeArr1; i++) { // to find the largest word in the array w1 = (ptrArray1[i]); // value of address (ptrArray1 + i) currLength1 = strlen(w1); //printf("The word from the first string is: %s and its length is : %d \n", w1, currLength1); // check point for (j = 0; j < sizeArr2; j++) { w2 = (ptrArray2[j]); // value of address (ptrArray2 + j) currLength2 = strlen(w2); //printf("The word from the second string is : %s and its length is : %d \n", w2, currLength2); // check point if (strcoll(w1, w2) == 0 && currLength1 == currLength2) // compares the strings { if (currLength2 >= maxLength) // in the variable maxLength -> the length of the longest word { maxLength = currLength2; wordMaxLength = w2; //printf("The largest word for now is : %s and its length is : %d \n", wordMaxLength, maxLength); // check point } } } } printf("The largest word is: %s \n", wordMaxLength); printf("Its length is: %d \n", maxLength); } void typeArray (char *arrS1) { int err = 0; if (!fgets (arrS1, n, stdin)) { /* validate 'arrS1' */ fprintf (stderr, "Error: invalid input for string.\n"); err = 1; } while (err == 1) { if (!fgets (arrS1, n, stdin)) { /* validate 'arrS1' */ fprintf (stderr, "Error: invalid input for string.\n"); err = 1; } } } int main(void) { char arrS1[n], arrS2[n]; char *ptrArray1[n] = {NULL}, *ptrArray2[n] = {NULL}; int sizeArr1 = 0, sizeArr2 = 0; printf("Type your first string: "); typeArray (arrS1); sizeArr1 = returnArrayOfWords (arrS1, ptrArray1); // sizeArr1 = number of elements in array 1 printf("Type your second string: "); typeArray (arrS2); sizeArr2 = returnArrayOfWords (arrS2, ptrArray2); // sizeArr2 = number of elements in array 2 findLargestWord(ptrArray1, sizeArr1, ptrArray2, sizeArr2); return 0; } A: There are numerous errors in the program although it compiled without any warnings. Chiefly the pointer types for your array, and the memory allocated. Secondly the function does not know how many words is allowed, and does not return how many were read - your method did not work at all (as in comments). Thirdly the string comparisons: you did not state the goals clearly, but in comment you want the "biggest string". strcoll does not do that - it's a lexical comparison, so I changed that section to find the longest string for the two sentences you enter. See comments, I made a large number of changes. #include <stdio.h> #include <string.h> #include <stdlib.h> int returnArrayOfWords (char *str4Parsing, char *arrayParsed[], int maxtokens) // added max { char seps[] = " ,\t\n"; // separators char *token1 = NULL; char *next_token1 = NULL; int i = 0; // Establish string and get the first token: token1 = strtok_s( str4Parsing, seps, &next_token1); // While there are tokens in "str4Parsing" while (token1 != NULL) { if(i >= maxtokens) return i; // ignore the rest arrayParsed[i] = token1; printf( " %s\n", token1 ); token1 = strtok_s( NULL, seps, &next_token1); i++; } return i; } int main (void) // correct signature { int i, j, n = 80; /*max number of words in string*/ char arrS1[80], arrS2[80]; //const char *w1, *w2; /*pointers*/ // deleted char **ptrArray1, **ptrArray2; // changed type int currLength1 = 0, currLength2 = 0 ; int sizeArr1 = 0, sizeArr2 = 0; int maxLength = 0; char *wordMaxLength; // changed to pointer ptrArray1 = malloc(n * sizeof (char*)); // allocate mem for pointer array if (ptrArray1 == NULL) return 1; ptrArray2 = malloc(n * sizeof (char*)); // allocate mem for pointer array if (ptrArray2 == NULL) return 1; printf("Type your first string: "); fgets(arrS1, 80, stdin); sizeArr1 = returnArrayOfWords(arrS1, ptrArray1, n); // indirection error, added max words, get actual num printf("Type your second string: "); fgets(arrS2, 80, stdin); sizeArr2 = returnArrayOfWords(arrS2, ptrArray2, n); // indirection error, added max words, get actual num for (i = 0; i < sizeArr1; i++) // this section rewritten { // to find the largest word in the array currLength1 = strlen(ptrArray1[i]); if(currLength1 > maxLength) { maxLength = currLength1; wordMaxLength = ptrArray1[i]; // changed definition to pointer } } for (j = 0; j < sizeArr2; j++) { // to find the largest word in the array currLength2 = strlen(ptrArray2[j]); if(currLength2 > maxLength) { maxLength = currLength2; wordMaxLength = ptrArray2[j]; // changed definition to pointer } } printf("The largest word is: %s", wordMaxLength); free(ptrArray1); // added free(ptrArray2); return 0; } Program session: Type your first string: one two three four one two three four Type your second string: apple banana pear apple banana pear The largest word is: banana
{ "language": "en", "url": "https://stackoverflow.com/questions/37577500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: JQuery nested each loops with ajax calls and promises? Context - My page dynamically loads a lot of div containers within which there are either 1 or 2 images loaded but hidden. Once all hidden images are loaded (I'm using the waitForImages JQuery plugin to ensure this) I loop through each container and through each image in each container and send an ajax call off to a php function which determines the dominant colour pixel within that image. When this ajax call returns the colour or colours (if there are two images) the script sets the container to that colour/those colours. I've got it working perfectly if I force the ajax call to work synchronously but this freezes my page when there's a lot of images to go through, as you can imagine. I could really do with it loading the containers and then allowing interaction on the page while it updates the container colours in the background. Here is an example of one of the containers, after the process is complete (with background colours therefore applied): <div class="image_product" style="background-color: rgb(186, 214, 78);" onclick="view_product(27);"> <img style="display:none;" src="/module_uploads/image_replacer/23/110914130755_0_94.jpg"> <img style="display:none;" src="/module_uploads/image_replacer/13/180614104219_0_94.jpg"> <div class="product_grid_heart_container" style="border-top-color: rgb(255, 255, 255) !important; background-color: rgb(239, 63, 63);"> <div class="product_grid_heart"> AK/H </div> </div> </div> and here is my code that makes that happen, by synchronously: $('div.image_product').each(function() { var colors = []; $(this).find('img').each(function() { var img = $(this).attr('src'); var sanitised_img1 = img.replace(/\//, ""); var sanitised_img = sanitised_img1.replace(/\//g, "***"); $.ajax({ async: false, type: "POST", url: '/general/dominant_colour/'+sanitised_img+'/rgb', success: function(dominant_colour) { colors.push(dominant_colour); } }); }); if($(this).find('.secondary_cat_image').length > 0) { $(this).find('.product_grid_heart_container').css({"background-color": "rgb(" + colors[0] + ")"}); } else { $(this).css("background-color", "rgb(" + colors[0] + ")"); if(colors.length > 1) { $(this).find('.product_grid_heart_container').css({"background-color": "rgb(" + colors[1] + ")"}); } else { $(this).find('.product_grid_heart_container').css({"background-color": "rgb(" + colors[0] + ")", "border-top-color": "rgb(" + colors[0] + ")"}); } } }); Like I said this works perfectly as is, it just freezes the page which I cannot have. I'm sure the answer lies in promises but while the examples I've found make sense I really struggle with applying them to my situation and I end up totally baffled. Any help appreciated greatly!
{ "language": "en", "url": "https://stackoverflow.com/questions/25817865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot Write to Access database from azure datafactory I'm trying to export data from an Azure SQL Database to an MS Access database using Data Factory, ODBC, and ADF's Integration Runtime. I’ve been able to register the destination Access database in ADF using the documented process of setting up a “self-hosted” Integration Runtime. The actual connection from ADF to the Access database works as expected – i.e., I can successfully “Test Connection” and query tables that reside in the local Access database. I can even move data FROM the Access db to the Azure SQL Database. However, our requirement is to move data OUT of our ASQLDB and into the Access db. Which is where the problem occurs. I cannot write data from our ASQLDB to the Access database, and receive the following error: { "errorCode": "2200", "message": "Failure happened on 'Sink' side. ErrorCode=UserErrorOdbcOperationFailed,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=ERROR [IM001] [Microsoft][ODBC Driver Manager] Driver does not support this function,Source=Microsoft.DataTransfer.ClientLibrary.Odbc.OdbcConnector,''Type=Microsoft.DataTransfer.ClientLibrary.Odbc.Exceptions.OdbcException,Message=ERROR [IM001] [Microsoft][ODBC Driver Manager] Driver does not support this function,Source=ACEODBC.DLL,'", "failureType": "UserError", "target": "Assemblies_ASQL_to_MSA_VM" } I’ve scoured Google, but have not been able to find someone who’s experiencing the same/similar issue trying to get data from ASQLDB to Access. I’ve also tried tweaking settings (i.e., connection strings, folders, shares, etc.) as many ways as I could possibly see to do, but to no avail. Bottom line, the connectivity to the Access database works as expected, but I absolutely cannot write data to the Access database from ADF. Assistance would be greatly appreciated. A: jjones64. I have to say that Access DB is not supported as a sink dataset in the ADF,please see this support list: My advice is you could transfer to sql db data into on-prem csv file with copy activity, then load csv file into Access DB following this tutorial:https://blog.ip2location.com/knowledge-base/how-to-import-csv-into-microsoft-access-database/
{ "language": "en", "url": "https://stackoverflow.com/questions/57435705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to programmatically access buffer in dos command window? I used the word "programmatically" but I'm not sure it's the right one... I'll try to explain the question with an example if I do: dir /S/B | find "something" and I receive 10 different file than I would like, instead of copy and paste, just to type del @1 where 1 is the first line produced by last command and @ is a magic symbol to access the buffer. Of course I would like to have this feature whatever is the command (not only for dir).
{ "language": "en", "url": "https://stackoverflow.com/questions/27285198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RStudio Crashes When Plotting For some reason, R keeps getting stuck whenever I try to plot something. Neither ggplot or base R is working, and I've tried this in both RStudio and R. I do not receive an error message, but when I run code like the code below, the command just runs endlessly and I end up having to terminate the session. x <- rnorm(100) hist(x) Here are the technical details: R version 4.1.2 "Bird Hippie" OS: macOS Monterey 12.2.1 I've tried dev.off(), which isn't really a solution to my problem. Does anyone have any clue what's going on? I tried running the code in both R and RStudio and get the same result. R just runs endlessly with no output or error message.
{ "language": "en", "url": "https://stackoverflow.com/questions/75140864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find duplicates documents? It's very strange that I did not find answer in documentation and here for a very simple question. How to find duplicated records in collections. For example I need to find duplicated by id for next documents: {"id": 1, name: "Mike"}, {"id": 2, name: "Jow"}, {"id": 3, name: "Piter"}, {"id": 1, name: "Robert"} I need to query that will return two documents with same id (id: 1 in my case). A: Have a look at the COLLECT AQL command, it can return the count of documents that contain duplicate values, such as your id key. ArangoDB AQL - COLLECT You can use LET a lot in AQL to help break down a query into smaller steps, and work with the output in future queries. It may be possible to also collapse it all into one query, but this technique helps break it down. LET duplicates = ( FOR d IN myCollection COLLECT id = d.id WITH COUNT INTO count FILTER count > 1 RETURN { id: id, count: count } ) FOR d IN duplicates FOR m IN myCollection FILTER d.id == m.id RETURN m This will return: [ { "_key": "416140", "_id": "myCollection/416140", "_rev": "_au4sAfS--_", "id": 1, "name": "Mike" }, { "_key": "416176", "_id": "myCollection/416176", "_rev": "_au4sici--_", "id": 1, "name": "Robert" } ]
{ "language": "en", "url": "https://stackoverflow.com/questions/62655714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Ionic v2 + CORS Preflight Access-Control-Allow-Methods Having issues communicating with an external API via ionic serve and ionic run -l, essentially anything that uses a localserver. I've followed the guide @ http://blog.ionic.io/handling-cors-issues-in-ionic/, which provides an option for handling the issue in Ionic 1 projects, but I'm struggling to get it working in a v2 project. Fetch API cannot load https://test.api.promisepay.com/items/100fd4a0-0538-11e6-b512-3e1d05defe79/make_payment. Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response. I have no control over how the API handles theses requests, as it is controlled by PromisePay. Following the closest thing to a possible solution on StackOverflow: CORS with Firebase+IONIC2+Angularjs: No 'Access-Control-Allow-Origin' still exists I've updated my ionic.config.json to { "name": "project", "app_id": "xxxxxxx", "proxies": [{ "path": "/api", "proxyUrl": "https://test.api.promisepay.com" }] } In the library that makes the http calls, I've updated the base URL to const PRE_LIVE_API = '/api'; The request method looks as follows: let Requester = class Requester { constructor() { let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.config = config; const baseUrl = PRE_LIVE_API; this.log(`API endpoint: ${ baseUrl }`); this.client = _requestPromise2.default.defaults({ baseUrl: baseUrl, auth: { user: config.userName, pass: config.token }, headers: { Accept: 'application/json', Authorization: `basic ${ config.apiToken }` }, resolveWithFullResponse: true }); } When making a call to the most basic of API endpoints /status/ I am now receiving the following error: "Error: Invalid URI "/api/status"" It seems the proxy path isn't being passed through. A: I was facing the same problem when I was trying to use the MailGun to send e-mails using REST API. The solution is to use HTTP instead of http. ionic 2 provides the class [HTTP]: http://ionicframework.com/docs/v2/native/http/ . In your projects root folder, run this command from the terminal: ionic plugin add cordova-plugin-http In your .ts file: import { HTTP } from 'ionic-native'; Then, wherever you want to send the HTTP post/get using Basic Authentication, use this: HTTP.useBasicAuth(username, password) //replace username and password with your basic auth credentials Finally, send the HTTP post using this method: HTTP.post(url, parameters, headers) Hope this helps! Good luck! A: Solved. Explicitly setting the BaseURL constant (PRE_LIVE_BASE) to http://localhost:8100/api resolves the issue. Now all requests are passed via the proxy alias and subvert the CORS issue. The only downside of this approach, is that I had to change a variable that was part of a package in node_modules, which will be overwritten during any future updates. So I should probably create my own fork for a cleaner solution. A: For Development purposes where the calling url is http://localhost, the browsers disallow cross-origin requests, but when you build the app and run it in mobile, it will start working. For the sake of development, 1. Install CORS plugin/Extension in chrome browser which will help get over the CORS issue. 2. If the provider is giving a JSONP interface instead of a normal get/post, You will be able to get over the CORS issue. I prefer using the 1st option as not a lot of api's provide a jsonP interface. For Deployment, You need not worry as building a app & running it in your mobile, you will not face the same issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/41687235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically created content is updating "a step behind" on button click So I am creating a simple question/answer format and having an issue when submitting an answer. I dynamically create divs/buttons/textboxs from the database via a "RenderQuestions()" function. This creates a list of questions and answer textbox/buttons. When attempting to answer a question, I type my answer click submit and nothing happens. I do it again and it shows my first answer. It's a "step behind".. If I refresh it then shows all answers as it should. I've been struggling with this all night. Here's some code: -----My page load----- (Relevant parts) protected void Page_Load(object sender, EventArgs e) { //If authenticated hide login & show welcome bloc if (User.Identity.IsAuthenticated) { //Show question & render questionsBloc.Visible = true; //if(Page.IsPostBack) RenderQuestions(); } -----RenderQuestions() function---- (The relevant parts) //Initialize & get answers List<Answer> answers = new List<Answer>(); answers = um.GetAnswers(q.QuestionID); //Initialize html render HtmlGenericControl questionDiv = new HtmlGenericControl("div"); TextBox txtAnswer = new TextBox(); Button btnAnswer = new Button(); //Set Answer Button btnAnswer.Text = "Answer"; btnAnswer.Click += new EventHandler(btnAnswer_Click); //Set ID's btnAnswer.ID = "btnAnswer" + q.QuestionID.ToString(); questionDiv.ID = "questionDiv" + q.QuestionID.ToString(); //Set classes questionDiv.Attributes.Add("class", "questionBloc"); btnAnswer.CausesValidation = false; btnAnswer.EnableViewState = false; //btnAnswer.UseSubmitBehavior = true; //Fill inner text with question questionDiv.InnerText = q.QuestionContent; //Insert question.. //actionDiv.InnerText = "Like/Dislike/Comment/Flag"; //Insert answer.. //Add answer textbox and button to action div actionDiv.Controls.Add(btnAnswer); //Add question div to qaDiv qaDiv.Controls.Add(questionDiv); //Add action div to qaDiv qaDiv.Controls.Add(actionDiv); //Add all controls to feedbloc feedBloc.Controls.Add(qaDiv); -----My btnAnswer event handler ----- private void btnAnswer_Click(object sender, EventArgs e) { UserManager um = new UserManager(); um.PostAnswer("My first answer!"); //RenderGlobalFeed(); } That's every reference to my button.. Should I be initializing the btn click event in my page_init? Any help is much appreciated. Thanks guys A: Set AutoPostBack=true on btnAnswer. It's not triggering the server to act on the button click. A: If you want to get event btnAnswer_Click triggered , then you must render the same Content and assign the eventHandler in every pageload(ie; the page load after the client button click must render the button again and EventHandler must be assigned). Asp.net won't trigger the event if it doesn't find the controls in the pageload. Remember, after clicking a button, the page load event triggers first and then only the Click_event will be triggered. The RenderQuestions() must be called in the btnAnswer_Click Event too. This will avoid the a step back problem. In this scenario I would recommend you to learn about ajax (using jQuery library) requests in asp.net (using WebMethods or webservices) to avoid these postbacks.
{ "language": "en", "url": "https://stackoverflow.com/questions/18028539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Perform Animation in Matplotlib alongside a Thread? I would like to change the circle color every 0.25 seconds through a thread, and showing the result live through matplotlib animation. Here is my code (I don't even understand why the animation is not performed): import threading import time import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib.animation import FuncAnimation def apply_color_shift(fig, circle): def func(): for i in range(100): circle.set_fc((i/100, 0, 0, 1)) time.sleep(0.25) print("something") anim = threading.Thread(target = func) def do_nothing(frame): print("ANIM") fig.show() FuncAnimation(fig, do_nothing, frames = [0.1*i for i in range(100)]) anim.start() plt.show() fig, ax = plt.subplots() ax.axis('square') c = Circle(xy = (0, 0), color = "red") ax.add_patch(c) ax.set_xlim([-50, 50]) ax.set_ylim([-50, 50]) fig.show() apply_color_shift(fig, c) What is the problem here, and how to solve it? A: If you want to change the color every 0.25 seconds, that should be the interval of the animation: import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() ax.axis('square') c = Circle(xy = (0, 0), color = "red") ax.add_patch(c) ax.set_xlim([-50, 50]) ax.set_ylim([-50, 50]) def change_color(i): c.set_fc((i/100, 0, 0, 1)) ani = FuncAnimation(fig, change_color, frames = range(100), interval=250) plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/55443690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Easily Change the .contains() method in the Collections interface in Java for Asserting Equality I'm wondering if there is a way to easily modify the ".contains()" method in the List interface in Java without creating a custom class. For example: When dealing with a collection of arrays in java, the .contains() method will always return false because the .contains() method always checks for equality with a generic .equals() call from the Object class that only returns true if the compared objects have the same reference in memory. However, with arrays, it is much more useful to do an Arrays.equals() check on the two arrays. Code: public class Temp { public static void main(String[] args) { int[] myIntArray = new int[] {1, 2, 3}; List<int[]> myList = new ArrayList<>(); myList.add(myIntArray); System.out.println(myList.contains(new int[] {1, 2, 3})); } // Output in the console: false // Preferred output: true } I understand that it is possible to do this rather easily by using a for loop and iterating over the whole list using the Arrays.equals() method, but the goal for me is to learn how to easily sculpt the .contains() method into what I need for future use. Thanks a lot! A: No. contains() can't do anything other than use Object.equals, because that's required by the specification. That's not to say that it's not reasonable to want a notion of contains for an array; merely that you can't overload the existing concept. You can straightforwardly create a static method: static <T> boolean containsArray(List<? extends T[]> list, T[] query) { return list.stream().anyMatch(e -> Arrays.equals(e, query)); } And then invoke this where you would otherwise invoke list.contains(query). This has the advantage that it works for any list (with reference-typed array elements): you don't have to create it specially, merely update these specialized comparisons. (The above would work for any reference-typed array. You'd need to specialize it for primitive-typed arrays). It also has the advantage that you don't have to deal with the thorny consequences highlighted by Stephen C (e.g. how indexOf, remove etc work). There's another alternative: use a list element type which supports equals "correctly". For example, you can wrap arrays using Arrays.asList to store them in the list, so you have a List<List<T>> instead of List<T[]>. This would be quite an invasive change: it would require changing the type of the list throughout your code; you've not provided any indication of how pervasively-used your list of arrays is. A: I am wondering if there is a way to easily modify the contains method in the List interface in Java without creating a custom class. There isn't a way. The contains method of the standard implementations of List behave as specified by the List API; i.e. they use the equals method. The flip-side that it would not be hard to extend the ArrayList class and override contains to do what you want. But if you are doing it properly, you need to consider whether you want: * *indexOf and lastIndexOf to be consistent with contains *the semantics of equals(Object) to be consistent with it *the semantics of a list returned by sublist(int, int) to be consistent with the semantics of the main list.
{ "language": "en", "url": "https://stackoverflow.com/questions/61426668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two Jquery for the same input box I am trying to limit the box to 8 words, But also replace Space with "comma Space" Can someone advise how I can do this please, I can either get the word count working or the space replace working, but not both. Thank you Here is my HTML <input name="input_4" type="text" id="input_10_4" size="100" /> and Here is my Jquery jQuery("#input_10_4").keyup(function() { var textValue = $(this).val(); textValue = textValue.replace(/ /g, ", "); $(this).val(textValue); }); jQuery(document).ready(function() { $("#input_10_4").keyup(function() { var content = $("#input_10_4").val(); //content is now the value of the text box var words = content.split(/\s+/); //words is an array of words, split by space var num_words = words.length; //num_words is the number of words in the array var max_limit = 8; if (num_words > max_limit) { alert("Exceeding the max limit"); var lastIndex = content.lastIndexOf(" "); $("#input_10_4").val(content.substring(0, lastIndex)); $('#remainingChars').text('Limit Exceeding'); return false; } else { $('#remainingChars').text(max_limit + 1 - num_words + " words remaining"); } }); }); A: Here is how I would do this. It's not exactly like you wanted, but IMHO its a better user experience. // this timer function allows us to wait till the user is done typing, // rather than calling our code on every keypress which can be quite annoying var keyupDelay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); $('#input_10_4').keyup(function() { var $this = $(this); // use our timer function keyupDelay(function(){ // user has stopped typing, now we can do stuff var max_limit = 8; var words = $this.val().trim().replace(/,/g, ' ').replace(/,?\s+/g, ' ').trim().split(' '); words = words.slice(0, max_limit); // get all the words up to our limit console.log(words); var wordString = words.join(', '); $this.val(wordString); var remainingWords = max_limit - words.length; $('#remainingChars').text('Words remaining: '+remainingWords); }, 800 ); // number of milliseconds after typing stops, this is equal to .8 seconds }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="input_4" type="text" id="input_10_4" size="100" /> <br> <div id="remainingChars"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/47127733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What triggers extensions to say "Use this extension by clicking on this icon" Afte completing the installation some Chrome extensions say "Use this extension by clicking on this icon": Others don't: My extension doesn't have this line, but I want it to have it. What's triggering this? Any hints are greatly appreciated!
{ "language": "en", "url": "https://stackoverflow.com/questions/69608442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: To play Youtube Video in iOS app I want to play youtube videos in my iOS App. I searched for that but the only solution I found is to embed youtube videos in the iOS app, in which video plays in webview, so in that, we can scroll and also play other videos which are in suggestion. I don't want to play video in webview, I want to play video just like it plays in player and user cannot scroll it. Is there any solution for that in Swift and also I don't want to use libraries which are against terms and condition of Youtube A: There also are solutions for playing Youtube Videos in an app on Github. Like this one: https://github.com/rinov/YoutubeKit Or this one: https://github.com/gilesvangruisen/Swift-YouTube-Player Just simply add the pod for the project that you want to use, install the pod in terminal, and you can use the functionality in that project. Hope that this is helpful. A: Here's another solution if you don't want to use the API provided by YouTube and instead continue using a UIWebView. YouTube has functionality to load any video in fullscreen in a webview without any of the scrolling features using a URL in the format https://www.youtube.com/embed/<videoId>. For example, to load Gangnam Style using this method, simply direct the UIWebView to the URL https://www.youtube.com/embed/9bZkp7q19f0. A: The API that YouTube provides to embed videos in iOS apps is indeed written in Objective-C, but it works just as well in Swift. To install the library via CocoaPods, follow the CocoaPods setup instructions and add the following line to your Podfile: pod ‘youtube-ios-player-helper’, ‘~> 0.1’ Once you have run pod install, be sure to use the .xcworkspace file from now on in Xcode. To import the pod, simply use the following import statement at the top of your Swift files: import youtube_ios_player_helper You can then create youtube player views as follows: let playerView = YTPlayerView() You can include this view in your layouts as you would any other UIView. In addition, it includes all of the functions listed in the YouTube documentation. For instance, to load and play a video, use the following function: playerView.load(withVideoId: videoId); Where videoId is the string id found in the URL of the video, such as "9bZkp7q19f0". A: Play youtube video in Swift 4.0 if let range = strUrl.range(of: "=") { let strIdentifier = strUrl.substring(from: range.upperBound) let playerViewController = AVPlayerViewController() self.present(playerViewController, animated: true, completion: nil) XCDYouTubeClient.default().getVideoWithIdentifier(strIdentifier) { [weak playerViewController] (video: XCDYouTubeVideo?, error: Error?) in if let streamURLs = video?.streamURLs, let streamURL = (streamURLs[XCDYouTubeVideoQualityHTTPLiveStreaming] ?? streamURLs[YouTubeVideoQuality.hd720] ?? streamURLs[YouTubeVideoQuality.medium360] ?? streamURLs[YouTubeVideoQuality.small240]) { playerViewController?.player = AVPlayer(url: streamURL) } else { self.dismiss(animated: true, completion: nil) } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/44499332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: css a tag didn't go to the right Please enlarge the html view width to see my point. I have used the a tag in for places (as you see), just in two of them the a tag goes to the right but in two of them the a tag didn't. The ID is DropdownSeviceLinkAvgWaitingTime and DropdownSeviceLinkQueuedCalls. I tried to give fload right but doesn't work. I really tried hard to re produce the problem, i hope you got me. if you need any other information please tell me. The left is correct, the right is not A: Your selector: #DropdownSeviceLink, #DropdownSeviceLinkAbandon, DropdownSeviceLinkAvgWaitingTime, DropdownSeviceLinkQueuedCalls is wrong. You are missing #s to indicate IDs.
{ "language": "en", "url": "https://stackoverflow.com/questions/25144187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reindex pandas DataFrame to fill missing dates I have daily data in the pandas DataFrame df with certain days missing (e.g. 1980-12-25 below). I would like to reindex the DataFrame to add those dates with NaN values. date close None 0 1980-12-12 28.75 1 1980-12-15 27.25 2 1980-12-16 25.25 3 1980-12-17 25.87 4 1980-12-18 26.63 5 1980-12-19 28.25 6 1980-12-22 29.63 7 1980-12-23 30.88 8 1980-12-24 32.50 9 1980-12-26 35.50 I have generated the list dates with the full set of dates I want. [Timestamp('1980-12-12 00:00:00'), Timestamp('1980-12-15 00:00:00'), Timestamp('1980-12-16 00:00:00'), Timestamp('1980-12-17 00:00:00'), Timestamp('1980-12-18 00:00:00'), Timestamp('1980-12-19 00:00:00'), Timestamp('1980-12-22 00:00:00'), Timestamp('1980-12-23 00:00:00'), Timestamp('1980-12-24 00:00:00'), Timestamp('1980-12-25 00:00:00'), Timestamp('1980-12-26 00:00:00')] Unfortunately when I run the reindex command below, the table becomes completely filled with NaN. df.reindex(dates) I ran the below checks, which all check out fine... >>> type(df['date'][0]) <class 'pandas._libs.tslib.Timestamp'> >>> type(dates[0]) <class 'pandas._libs.tslib.Timestamp'> >>> dates[0] == df['date'][0] True A: From what I see in your question, you'll need to set_index(): df date close 0 1980-12-12 28.75 1 1980-12-15 27.25 2 1980-12-16 25.25 3 1980-12-17 25.87 4 1980-12-18 26.63 5 1980-12-19 28.25 6 1980-12-22 29.63 7 1980-12-23 30.88 8 1980-12-24 32.50 9 1980-12-26 35.50 df['date'] = pd.to_datetime(df['date']) df.set_index('date', inplace=True) df.reindex(dates) df close date 1980-12-12 28.75 1980-12-15 27.25 1980-12-16 25.25 1980-12-17 25.87 1980-12-18 26.63 1980-12-19 28.25 1980-12-22 29.63 1980-12-23 30.88 1980-12-24 32.50 1980-12-25 NaN 1980-12-26 35.50 You need to set index so it knows how to align your new index. Is this your expected output?
{ "language": "en", "url": "https://stackoverflow.com/questions/45145276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to capture the data sent by alloy ui io request in serveresource method? Getting blank values for title and description in serveResource method.Is this the right way to send the parameters from io request? After inserting blank values in database I have to reload the page to see the inserted values?So io-request is not ajax request? <aui:script use="aui-base"> A.one('#<portlet:namespace/>save').on('click', function(event) { var A = AUI(); var title=A.one('#<portlet:namespace/>title').val(); alert(title); var description=A.one('#<portlet:namespace/>description'); var url = '<%= newJob.toString() %>'; A.io.request( url, { method:'POST', data: { <portlet:namespace />title: title, <portlet:namespace />description: description, }, } ['aui-io-deprecated'] ); Liferay.Util.getOpener().<portlet:namespace/>closePopup('<portlet:namespace/>dialog'); }); A: AUI's io request is ajax request only. You can get parameters in serveResource method using code below: ParamUtil.get(resourceRequest, "NAMEOFPARAMETER"); Modify your javascript function and provide data attribute as below: data: { '<portlet:namespace />title': title, '<portlet:namespace />description': description, } A: I assume both title and description are textfields. If so, description is missing a .val() call, or more appropriately, .get('value'). I didn't use a dialog/modal in my source, but the overall approach should be the same. <script> AUI().use('aui-base', 'aui-io-request', function(A){ A.one('#<portlet:namespace />save').on('click', function(event) { var title= A.one('#<portlet:namespace />title').get('value'); var description=A.one('#<portlet:namespace />description').get('value'); var url = '<%=myResourceURL.toString()%>'; A.io.request(url, { method:'POST', data: { title: title, description: description, }, }); }); }); </script> I'm still relatively new to Liferay and have had trouble with this as well. I've noticed that the data parameters are not in the parametersMap of the default ResourceRequest, as you have stated. Out of curiosity, I decided to use UploadPortletRequest req = PortalUtil.getUploadPortletRequest(resourceRequest); in the serveResource method and check it's parametersMap. The title and description parameters are available therein. I'm still learning where and how to access data from Liferay objects, but it would seem that for the UploadPortletRequest to have the data, it would be plucked from somewhere within the default ResourceRequest ... where still remains elusive to me. After inserting blank values in database I have to reload the page to see the inserted values? You have to reload the page because a resource action does not trigger a page refresh. If you are manipulating data that you want reflected in some other "view" you'll need to configure the appropriate communication or use one of the other available url types that does trigger the doView method of your other "view".
{ "language": "en", "url": "https://stackoverflow.com/questions/25052479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Horizontal orientation of DataGrid in Silverlight 4 I want to change the orientation of the datagrid to horizontal in Silverlight 4. In other words, I want to display the headers on the left hand side and the values corresponding to it on right hand side. How can I do it? A: The DataGrid does not support horizontal item scrolling. One very mad idea would be to use the Toolkit's LayoutTransformer to rotate the whole grid by 90degrees then template all the headers and cells with a LayoutTransfomer to rotate their contents back. One issue (likely of many, if it's even possible) would be the scrollbar would appear on the top rather than the bottom. You might be able to sort that out with further templating.
{ "language": "en", "url": "https://stackoverflow.com/questions/2875379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IBInspectable property values not updating in xib I'm running into a minor complication using IBInspectable properties and not sure if it might have something to do with my xibs and xib usage. I'm trying to reuse a custom control between multiple view controllers. The control is a custom tab manager: The IBInspectable Attributes are configured in this xib as: First, Second, Third. Here is the corresponding code for the header file. IB_DESIGNABLE @interface TabContainerView : NSView @property (nonatomic, strong) IBOutlet NSView *view; @property (weak) IBOutlet TabContentView *contentView; @property (weak) IBOutlet TabView *firstTab; @property (weak) IBOutlet TabView *secondTab; @property (weak) IBOutlet TabView *thirdTab; @property (nonatomic, strong) IBInspectable NSString *tabOneText; @property (nonatomic, strong) IBInspectable NSString *tabTwoText; @property (nonatomic, strong) IBInspectable NSString *tabThreeText; @end #import "TabContainerView.h" @interface TabContainerView () @property (nonatomic, strong) NSMutableArray *tabsArray; @property (nonatomic, assign) NSInteger selectedTabIndex; @property (weak) IBOutlet NSTextField *tabOneTextField; @property (weak) IBOutlet NSTextField *tabTwoTextField; @property (weak) IBOutlet NSTextField *tabThreeTextField; @end @implementation TabContainerView #pragma mark Init - (id)initWithFrame:(NSRect)frameRect { NSString* nibName = NSStringFromClass([self class]); self = [super initWithFrame:frameRect]; if (self) { if ([[NSBundle mainBundle] loadNibNamed:nibName owner:self topLevelObjects:nil]) { [self configureView]; } } return self; } #pragma mark Configure View - (void)configureView{ [self.view setFrame:[self bounds]]; [self addSubview:self.view]; self.tabOneTextField.stringValue = self.tabOneText; self.tabTwoTextField.stringValue = self.tabTwoText; self.tabThreeTextField.stringValue = self.tabThreeText; } @end This works fine in the TabContainerView.xib without issue. Now when I attempt to use this control in two different view controllers, I run into problems. Both of my view controllers are also loaded from Xibs. In view controller 1 I have something like this: In view controller 1 I've subclassed the custom view to the TabContainerView subclass which works just fine when I run the application. I've also changed the text to be specific for this view controller. List, Map, Filter are the IBInspectable property values for view controller one. In view controller 2 (not shown), I've done the exact same thing, however different IBInspectable property values specific for view controller 2. However, when I run the application the values never update and always stay as First, Second, and Third. I'm not sure if there is something I'm doing that's causing this problem but any help or tips would be appreciated. (IBDesignable seems to give me a lot of warnings where it breaks and not sure if maybe it's just loading the last saved value for the xib.) A: Have you imported #import "TabContainerView.h" in controller 2 .h file.
{ "language": "en", "url": "https://stackoverflow.com/questions/36075095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linq - In memory join vs EF Join Using EF 6 and SQL 2014. Assuming you have a well indexed and normalized DB. Is it 'better' to pull entities into memory then perform the join on the IEnumerables or let EF do join via IQueryable? By better -> faster execution time, less reads on DB, Mem usage. Example in memory: using (var context = myDbContext()) { var table1 = await context.Table1.ToListAsync(); var table2 = await context.Table2.ToListAsync(); var table3 = await context.Table3.ToListAsync(); var resultSet = table1 .Join(table2, t1 => t1.Id, t2 => t2.Table1Id, (t1,t2) => new {t1, t2}) .Join(table3, x => x.t2.Table2Id, t3 => t3.Table2Id, (x, t3) => new { x.t1, x.t2, t3}) .ToList(); } Example EF: using (var context = myDbContext()) { var resultSet = await context.Table1 .Join(context.Table2, t1 => t1.Id, t2 => t2.Table1Id, (t1,t2) => new {t1, t2}) .Join(context.Table3, x => x.t2.Table2Id, t3 => t3.Table2Id, (x, t3) => new { x.t1, x.t2, t3}) .ToListAsync(); } A: How do you know if one car is faster than another? Drive both of them and compare the times. Generally, databases are more efficient at joining data than in-memory Linq (due to pre-computed indices, hashes, etc.) but there certainly could be cases where in-memory would be faster. However, when you're not pulling ALL of the data into memory, the benefit of having less data over the wire might make a bigger difference than any performance improvement in joining. So there's not a definitive answer. Start with something that works, THEN focus on performance improvements by measuring the time before and after the changes. A: One of the slower parts of executing a database query is the transport of the data from the DBMS to your local process. Hence it is wise to limit the amount of data to be transported to your process. Only transport the data you actually plan to use. So if you query "Teachers with their Students", you'll know that the ID of the teacher will equal the foreign key 'TeacherIdin everyStudent`. So why transport this foreign key for every of the teacher's 1000 students if you already know the value? Another reason to let the DBMS perform the query is because the software in the database is optimized to perform queries. If the DBMS created a temporary table for a query, and it detects that a new query needs the same temporary table, a smart DBMS will reuse this temporary table, even if the query came from another process. Smart DBMSes will detect that certain indexes are used more often than others, and keep them in memory, instead of reading them from disk all the time. So a DBMS has all kinds of tricks to speed up the execution of queries. You can see that this tricks help by measuring: perform a query twice in a row and see that the second query is executed faster than the first one. This effect is also a reason that you can't measure whether it is faster to let given query execute by the DBMS or to execute it in local memory., as some suggested. The only proper method would be to measure the chosen strategy with all kinds of queries during a longer period of time (minutes, if not hours), with a lot of processes that perform these queries. One thing you'll know for certain is that executing queries AsEnumerable can't benefit from the queries executed by others.
{ "language": "en", "url": "https://stackoverflow.com/questions/51977336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }