text
stringlengths
15
59.8k
meta
dict
Q: How to force g++ to create C symbol name I have a function called init in a cpp file, but when I compile it, g++ creates in the object file a symbol named _Z4initv, so when I link after with ld with the option -e init, obviously ld doesn't recognize the symbol init. Is there a way to create symbols name in C style with g++ ? A: If you have a definition like e.g. void init() { ... /* some code */ ... } Then to inhibit name mangling you need to declare it as extern "C": extern "C" void init() { ... /* some code */ ... } If you have a declaration in a header file that you want to include in a C source file you need to check if you're including the header file in a C or C++ source file, using the __cplusplus macro: #ifdef __cplusplus extern "C" #endif void init(void); Note that the function in the header file has to be declared with void in the argument list, if it doesn't take any arguments. That's because the declaration void init() means something else in C.
{ "language": "en", "url": "https://stackoverflow.com/questions/42716612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angularjs : failing to generate c3 directive based charts dynamically I am trying to create c3 charts dynamically using c3 chart directives. C3 chart directive is working fine. However dynamic chart creation upon button click is not working. Can any one suggest where I am going wrong? Please find my plunker at http://plnkr.co/edit/wWJx3zU3Sm1cN9ZCtvoh?p=preview I am compiling my c3 directive as shown below: $scope[chartName] = { data: { x: 'x', columns: [["x","2014-02-01","2014-03-01","2014-04-01","2014-05-01","2014-06-01","2014-07-01","2014-08-01","2014-09-01"],["LH",".00",".00",".00",".00",".00",".00",".00","31.50"],["DW","42.57",".00",".00","321.14","1070.06","6501.42","144337.85","329159.85"],["PS",".00","82.22","-2.87","179.60","835.85","6925.52","479631.24","1386751.16"]], type: 'line' }, axis: { x: { type: "timeseries", tick: { format: "%d-%m-%Y" } } }, subchart: { show: true } }; var template = ' <div class="col"> <p class="graphtitle">' + dashletterName + ' </p> <c3-simple id = "' + chartName + '" config="' + chartName + '"></c3-simple> </div>'; angular.element(document.body).append($compile(template)($scope)); A: I downloaded you Plnkr and tried it in browser. Here is error from Chrome console: ReferenceError: $compile is not defined This means that AngularJS can't use $compile, because it is not injected into your controller. This should be done in controllers.js like this: // I have added $compile controller('DemoCtrl', ['$scope', 'c3SimpleService', '$compile', function ($scope, c3SimpleService, $compile) { // rest of the controller code } I also fixed your Plnkr. Hope it helps :)
{ "language": "en", "url": "https://stackoverflow.com/questions/28188479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SqlDataReader.GetString and sqlnullvalueexception I am new to C#. I was executing some select queries from database tables using System.Data.SqlClient classes. I got sqlnullvalueexception while executing some select query. On googling I come to know that if the value is null in the database, SqlDataReader.GetString (or it's variants) will throw sqlnullvalueexception. What is the best coding practice for this? if (!sqlDataReader.IsDBNull(n)) value = r.GetString(n); Any better way of coding? A: If you don't want to repeat this a lot, just create a helper function, like this: public static class DataReaderExtensions { public static string GetStringOrNull(this IDataReader reader, int ordinal) { return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal); } public static string GetStringOrNull(this IDataReader reader, string columnName) { return reader.GetStringOrNull(reader.GetOrdinal(columnName)); } } Which you can call like this: value = reader.GetStringOrNull(n); A: That really is the best way to go about it if you wish to avoid any exceptions. You need to decide whether or not a null field represents an exceptional situation in your code - if it doesn't then use this method. If it does then I would suggest that you either allow the exception to be thrown or catch the exception and wrap it in a more meaniful exception and throw that one. But the main thing to know is that this is the standard way to retrieve values from a data reader when a null field does not represent an exceptional situation in the application domain. A: This worked for me: value = reader.GetValue(n).ToString(); A: The code you posted is fine. You could also do something like that : value = r[n] as string; If the value in the database is null, r[n] will return DBNull.Value, and the cast to string will return null.
{ "language": "en", "url": "https://stackoverflow.com/questions/1222116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Selenium Chrome Driver opens a different page than regular Chrome Browser I'm trying to pull some information from this URL and ones like it: "https://www.rockymountainatvmc.com/tires-and-wheels/tusk-impact-complete-wheel-rear-p?s=1033997&v=1216" My goal is to get the MSRP and other info for a specific part. To do this, I'm using python to run a selenium chrome webdriver that opens several of these URLs. The problem is the links aren't opening with the same information that I would get in my regular Chrome browser. The link is supposed to contain all the information to "select a vehicle" and thus a specific part. When I open this in my regular chrome browser, everything works fine. When I open this using the automated Chrome page, it fails to select a vehicle and shows a general part page. I can't figure out what the difference might be between these two browsers that would cause this. My regular chrome browser and the chromedriver are both version 81.0.4044.113. I've tried going to whatismybrowser.com and all settings are identical. Another interesting thing is opening this in internet explorer gives me the same result as the automated chrome browser. Help! regular chrome browser automated chrome browser A: The Regular chrome browser is fetching the details of your bike(Something -- yamaha 125). It could be from past cookies or cache. However, once you are opening it with Automation, a clean session s opened. Try cleaning your cookies and cache on the browser(regular) and then try, both of them should appear same. Or you can use options in chrome to select the profile your regular chrome browser is using. See https://startingwithseleniumwebdriver.blogspot.com/2015/07/working-with-chrome-profile-with.html. Hope it Helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/61358459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Envoy proxy forward to https endpoint: facing protocol error I'm trying to do this one: call public.com/api/v1/{proxy} to envoy proxy behind an ingress proxy. Envoy proxy will forward traffic to https private endpoint inside my VPC with diffrent path: https://private.com/internal/{proxy}. But I'm still facing the issue upstream reset: reset reason: connection termination, transport failure reason: I even tried with public https endpoint but it's still the same. Below is my configuration: admin: access_log_path: /tmp/admin_access.log address: socket_address: protocol: TCP address: 0.0.0.0 port_value: 9901 static_resources: listeners: - name: listener address: socket_address: address: 0.0.0.0 port_value: 10000 filter_chains: - filters: - name: envoy.filters.network.http_connection_manager typed_config: '@type': "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager" stat_prefix: http_proxy access_log: - name: envoy.access_loggers.stdout typed_config: "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog route_config: name: all virtual_hosts: - name: local_service domains: - '*' routes: - match: { prefix: "/api/v1"} route: prefix_rewrite: "/internal/" cluster: allbackend_cluster http_filters: - name: envoy.filters.http.router clusters: - name: allbackend_cluster connect_timeout: 1s type: strict_dns lb_policy: round_robin load_assignment: cluster_name: allbackend_cluster endpoints: - lb_endpoints: - endpoint: address: socket_address: address: private.com port_value: 443 transport_socket: name: envoy.transport_sockets.tls typed_config: "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext common_tls_context: validation_context: trusted_ca: {filename: /etc/ssl/certs/ca-certificates.crt} A: I believe you need to add certificates information for envoy tls_context: common_tls_context: tls_certificates: - certificate_chain: filename: "/etc/ssl/certs/https.crt" private_key: filename: "/etc/ssl/certs/key.pem" And also add trust the certificate used by cluster. tls_context: common_tls_context: validation_context: trusted_ca: filename: "/etc/ssl/certs/cluster.crt"
{ "language": "en", "url": "https://stackoverflow.com/questions/73582704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing Value in ASP.NET Pages I am developing a web application using asp.net and C#. I have a question Is there any way for passing values in asp pages without using QueryString or Session values or Cookies or previous page? A: You may see: ASP.NET State Management Overview Profile Properties You can use: ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner. A: You can use asp.net cache or save data from one page in to some persistent medium and other page would read from that medium could be database or xml etc. A: Beside your requirements(not using QueryString or Session values or Cookies) yes you can use public property like public String YourProperty { get { return "Return What you want to pass"; } } Check this MSDN article for full code
{ "language": "en", "url": "https://stackoverflow.com/questions/13680817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Different unit for Kubernetes resource memory on pods My question is related to Kubernetes and the units of the metrics used for the HPA (autoscaling). When I run the command kubectl describe hpa my-autoscaler I get (a part of more information) this: ... Metrics: ( current / target ) resource memory on pods: 318067507200m / 1000Mi resource cpu on pods (as a percentage of request): 1% (1m) / 80% ... In this example, when you can see the metrics for the resource memory on pods, you can see that the unit for the current value is m, which is "millis" (as is described in the official documentation), but the unit used for the target value is Mi, which is "Mebis" Is there any problem with the usage of different units? Thanks! A: No, they are just different multipliers. The actual code is using a raw number of bytes under the hood.
{ "language": "en", "url": "https://stackoverflow.com/questions/58148095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Haskell Attoparsec infinite loop The code is based on Haskell Attoparsec, and when I use parseOnly pString "v", it gives me the right answer as Right (DontNeedTrim, "v"). While when I use the instruction parseOnly (many' pString) "v", it seems drops into the infinite loop and finally failed with the overflowed stack. data Signal = NeedTrim | DontNeedTrim deriving (Show) pString :: Parser (Signal, [Char]) pString = ((char '\"' *> many' pChar' <* char '\"') >>= \s -> return (NeedTrim, s)) <|> (many' pChar >>= \s -> return (DontNeedTrim, s)) pChar :: Parser Char pChar = char '\\' *> (pEscape <|> spaces *> endOfLine *> pChar) <|> satisfy (`C.notElem` "\"\\\n#;") pChar' :: Parser Char pChar' = char '\\' *> pEscape <|> satisfy (`C.notElem` "\\\"") pEscape :: Parser Char pEscape = choice (zipWith decode "bnt\\\"" "\b\n\t\\\"") where decode c r = r <$ char c A: The second alternative in pString accepts the empty string: many' pChar >>= \s -> return (...). Thus many' pString keeps consuming the empty string ad infinitum.
{ "language": "en", "url": "https://stackoverflow.com/questions/51093771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery select element outside of li by ID im looking to select the follow element by id toggleThisDiv. The markup looks like: <li id="liCategory" runat="server"> <asp:HyperLink ID="lnkCategory" runat="server"> <span><asp:Literal ID="litCategory" runat="server" Visible="true" /></span> <asp:Image ID="imgMan" runat="server" Visible="false" /></asp:HyperLink> <asp:Button ID="btnToggleDiv" runat="server" Text="+" Visible="false" /> </li> <div id="toggleThisDiv" runat="server" style="display:none;margin-top:-16px;"> And the jQuery: $(document).ready(function () { $('[id*="btnToggleDiv"]').click(function () { $(this).next().slideToggle(100); return false; }); }); This works when the button is outside of the listitem but this is all inside a repeater and if i leave it like that, all of the buttons created will be next to each other instead of within their associated list item. I'm looking for something within jQuery that would allow me to select the next div (toggleThisDiv), is this possible? Thankyou A: Use unique ID's, or classes if generating elements where the same identifier will be used. To target an element outside the current parent of the clicked element you can find the closest parent that matches a selector, and then the next element etc. $(document).ready(function () { $('[class*="btnToggleDiv"]').on('click', function () { $(this).closest('li').next('div').slideToggle(100); return false; }); }); A: Use something like this to select the toggleThisDiv $('#<%= toggleThisDiv.ClientID %>') When the website is generated from your asp code, your IDs will be different than what you have given them. This is because they are run at server. Anytime that you are using runat server, use the format above to find the generated ID. You should use a class inside to repeater though.
{ "language": "en", "url": "https://stackoverflow.com/questions/12689130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: create a mp3 player embedded in a facebook post The Serial podcast has this cool feature where they share their webpage on their facebook page and Facebook lets the audio be played within Facebook. See this image: I've created a blog post with all of the proper meta tags to match the relevant tags expected by facebook: music:preview_url:url, the og:type is music.song, etc. But I can't get a mp3 player to appear. When I compare the open graph meta data in the Facebook debugger from the Serial webpage to my own webpage, the tags match up fine. Yes, mine has a 'locale' array but that can't be the issue. I'm thinking they must have some type of Facebook app? Or I don't know what. I've never built a Facebook app so if you think that is how they are doing it, where would I start looking? This is my non-working open graph output: This is the one from the Serial podcast. You can see in the Share Dialog the player buttons for the MP3. How are they getting that in there? I would have thought just be me using the correct meta tags, Facebook would put player buttons on top of my mp3 and create the player for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/34362659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "The server could not update. Check your API credentials and internet connection and try again." - Google Sheets API, service account error I'm currently building a website/platform following using this: https://forensic-architecture.org/investigation/timemap-for-cartographic-platforms. It works by reading a Google sheet I have, and I need to press an 'update' button in order for the sheets to be read. However, rather than it updating, I get the following: "The server could not update. Check your API credentials and internet connection and try again." I'm unsure what's going wrong, as I've followed all the steps as needed for the Google Sheets api, as outlined in the link above. I also previously had this running with a different API key locally (which I since deleted). Now, I can't even get it to work locally, though previously there was no issue. The service account has permission on the Sheet itself. I've also tried setting the sheet to publicly available online with no change. I've checked the service account and key are correct about a million times, and have created a new project with whole new key etc so see if the issue was reproduced. I also tried making a new sheet (and granting a new key etc permission) but still get the same error. The metrics panel for Sheets API tells me "google.apps.sheets.v4.SpreadsheetsService.GetSpreadsheet" has an error rate of 100%. I'm well below my quota, and have billing enabled (two other reasons I keep seeing on Stack as possible reasons for similar errors), so I'm not sure that's the issue. Below is also what I see in terminal when trying to run locally (rn switched to trying to fix this locally as this is the last step for me in making the platform live, and I'm wary of doing anything on my remote server that could end up causing problems elsewhere): Enabling CORS in development... Connected to {{My Google Sheet name}} (Google Google Sheet with ID {{Sheet ID}}). =================== grant access to: {{my service account email}} =================== Started on port 4040 GET /api/blueprints 200 46.784 ms - 1677 GET /api/update 404 452.498 ms - 115 The platform reads my service key credentials through my .env (which it seems to be doing fine going from what I see in terminal), and uses a config file to find the Google Sheets id (which again seems fine from above). Please let me know if there's any extra info needed here; I'm pretty new to all of this, and so not necessarily aware when I'm relaying issues what is vital info and what is not.
{ "language": "en", "url": "https://stackoverflow.com/questions/67787033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The model item passed into the dictionary is of type ' ', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable? After executing the application I get the "The model item passed into the dictionary is of type 'ClubStarterKit.Web.ViewData.Forum.NewMessageListViewData', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ClubStarterKit.Web.ViewData.Forum.NewMessageListViewData]'. In view I have the codes below <%if ( User.Identity.IsAuthenticated) { %> <div class="fullwidth" id="message-add-block"> <%using (Ajax.AsyncForm(Website.Shared.Views.DisplayTemplates.NewForumMessageList, new AsyncFormOptions(AsyncFormType.TargetUpdate, FormMethod.Post, "newMessages", targetUpdate: "messages", elementBlockId: "message-add-block", postRequestFunction: "afterMessageUpdate"))) {%> <h3>Add New Message Final Test</h3> <br /> <%: Html.Wysiwyg("message") %> <br /> <%-- <input type="hidden" value="<%: Model.ThreadSlug %>" name="thread" />--%> <input type="hidden" value="-1" name="messageId" /> <input type="submit" value="Add Message4 final" /> <%}%> <br /> <a id="newmessage" href="#">New message4 final</a> </div> <%}%> in the controller the code is public virtual ActionResult Index() { ViewData.Title("New Message"); return View(Views.List, new ClubStarterKit.Web.Infrastructure.Forum.NewMessageListAction().Execute()); } and in screenshot below it is : The model item passed into the dictionary is of type 'Myapplication.Web.ViewData.application.NewMessageListViewData', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable Please advise which area of code is the issue A: You are passing the View a single NewMessageListViewData, but it has been strongly typed to accept only objects implementing IEnumerable<T> where T is NewMessageListViewData. For example, a List<NewMessageListViewData> would work. As mentioned in the comments, I would start by looking at the return type of ClubStarterKit.Web.Infrastructure.Forum.NewMessageListAction.Execute(), or, if you only intend to display a single instance of NewMessageListViewData in this View, you need to set the model in the View to reflect that.
{ "language": "en", "url": "https://stackoverflow.com/questions/11160786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Confirm dialog in Cordova I'm writing an app in javascript and html with phonegap/cordova. I have this code in javascript: $('#diario_delete_btn').live('tap',function(e){ var iddb = $(this).find('a').attr('rel'); confirm_diario_delete(iddb); }); function diario_delete(iddb) { var db = window.openDatabase("Database", "1.0", "123nozze", 200000); db.transaction(function(tx){ tx.executeSql('DELETE FROM AgendaItemJDO WHERE id='+iddb); lastChangeUpdate(); }); $('.diario_row[db_id="'+ iddb +'"]').remove(); $('#popupMenuDiario').popup("close"); } function confirm_diario_delete(iddb) { var r = confirm("Confermi l'eliminazione dell'elemento?"); if (r) { diario_delete(iddb); } else { $('#popupMenuDiario').popup("close"); } } It seems to work but if I choose "cancel button" (so r = false) n times before I press "confirm button", next time the confirm dialog is displayed 2 times, next time it is displayed 3 times, and so on. I don't know why this behaves this way. The same is if a change the code and I use the Cordova example code for confirm dialog. Any ideas on what is the problem and how can I solve it? Thanks! A: You should use the native notification which Phonegap supports. Specifically the .confirm() method taken from link above; // process the confirmation dialog result function onConfirm(button) { alert('You selected button ' + button); } // Show a custom confirmation dialog // navigator.notification.confirm( 'You are the winner!', // message onConfirm, // callback to invoke with index of button pressed 'Game Over', // title 'Restart,Exit' // buttonLabels ); A: navigator.notification.confirm( 'Are you sure you want to signup ', // message onConfirm, // callback to invoke with index of button pressed 'SignUp', // title ['yes','no'] // buttonLabels ); function onConfirm(buttonIndex){ alert('You selected button ' + buttonIndex); if(buttonIndex==2){ alert('You selected button - no'); }else{ alert('You selected button - yes'); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/19964552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to do this type of incrementation in PHP? I am using this category script: <?php include("connect.php"); $nav_query = mysql_query("SELECT * FROM `categories` ORDER BY `id`"); $tree = ""; $depth = 1; $top_level_on = 1; $exclude = array(); array_push($exclude, 0); while ($nav_row = mysql_fetch_array($nav_query)) { $goOn = 1; for ($x = 0; $x < count($exclude); $x++) { if ($exclude[$x] == $nav_row['id']) { $goOn = 0; break; } } if ($goOn == 1) { $tree .= $nav_row['name'] . "<br>"; array_push($exclude, $nav_row['id']); if ($nav_row['id'] < 6) { $top_level_on = $nav_row['id']; } $tree .= build_child($nav_row['id']); } } function build_child($oldID) { global $exclude, $depth; $child_query = mysql_query("SELECT * FROM `categories` WHERE parent_id=" . $oldID); while ($child = mysql_fetch_array($child_query)) { if ($child['id'] != $child['parent_id']) { for ($c=0; $c < $depth; $c++) { $tempTree .= "&nbsp;"; } $tempTree .= "- " . $child['name'] . "<br>"; $depth++; $tempTree .= build_child($child['id']); $depth--; array_push($exclude, $child['id']); } } return $tempTree; } echo $tree; ?> It relies on the following mysql database structure: id | parent_id | name 1 Cats 2 1 Siamese Cats 3 2 Lilac Point Siamese Cats 4 Dogs etc... The script allows for unlimited category depth but has one major downfall. It displays the category navigation to the front end like so: Cats - Siamese Cats - Lilac Point Siamese Cats Dogs How can I have it display like this: Cats - Siamese Cats - Lilac Point Siamese Cats Dogs So that for each additional category depth another space with be added to the beginning indentation of the category text? A: As you are already keep track of the depth, make use of it. E.g. $indent = ''; for($i = 0; $i < $depth; $i++) { $indent .= "&nbsp;"; } $tempTree .= $indent . "- " . $child['name'] . "<br>"; To make it look the way you want it you might have to initialize $depth with 0. Also note that executing SQL queries in a nested for loop is not the best approach. If possible, try to reduce the number of queries. You could for example use classes and, get all the entries at once and then build the tree structure with objects and arrays.
{ "language": "en", "url": "https://stackoverflow.com/questions/3076576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pass cookie and reload one frame from another frame I have main html page which have two frames frame1 and frame2. In frame1, a textbox & a button where the button click passes the value in textbox to a cookie. In frame2 this value passed through cookie is used. I need to refresh or reload the frame2 page as & when the cookie value is changed from the button click event on frame1. Any suggestions for achieving this???
{ "language": "en", "url": "https://stackoverflow.com/questions/13534079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Docker Machine error: Hyper-V PowerShell Module is not available I've checked my Hyper-V settings and PowerShell Module is enabled. I've also found this documented issue: https://github.com/docker/machine/issues/4342 but it is not the same issue since I do not have VMware PowerCLI installed. The issue was closed with a push to the repo and is supposedly fixed in 0.14.0-rc1, build e918c74 so I tried it anyways. After replacing my docker-machine.exe, I'm still getting the error and still getting the error even if I reinstall Docker for Windows. For some more background, this error starting happening after a reinstall because my Docker install had an error: https://github.com/docker/for-win/issues/1691, however, I'm not longer getting that issue after reinstalling. A: For those who struggle with this issue in Windows, Follow the instruction here A: When creating a Hyper-v VM using docker-machine on win10, an error was returned"Error with pre-create check: "Hyper-V PowerShell Module is not available"。 The solution is very simple. The reason is the version of the docker-machine program. Replace it with v0.13.0. The detailed operation is as follows: * *Download the 0.13.0 version of the docker-machine command. Click to download: 32-bit system or 64-bit system *After the download is complete, rename and replace the " docker-machine.exe " file in the " C:\Program Files\Docker\Docker\resources\bin" directory. It is best to back up the original file. A: Here is the solution https://github.com/docker/machine/releases/download/v0.15.0/docker-machine-Windows-x86_64.exe Save the downloaded file to your existing directory containing docker-machine.exe. For my system this is the location for docker-machine.exe /c/Program Files/Docker/Docker/Resources/bin/docker-machine.exe Backup the old file and replace it file with the new one. cp docker-machine.exe docker-machine.014.exe Rename the downloaded filename to docker-machine.exe mv docker-machine-Windows-x86_64.exe docker-machine.exe Build Instructions * *Create virtual switch in Hyper-V manager named myswitch *Request Docker to create a VM named myvm1 docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 Results docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 Running pre-create checks... (myvm1) Image cache directory does not exist, creating it at C:\Users\Trey Brister\.docker\machine\cache... (myvm1) No default Boot2Docker ISO found locally, downloading the latest release... (myvm1) Latest release for github.com/boot2docker/boot2docker is v18.05.0-ce (myvm1) Downloading C:\Users\Trey Brister\.docker\machine\cache\boot2docker.iso from https://github.com/boot2docker/boot2docker/releases/download/v18.05.0-ce/boot2docker.iso... (myvm1) 0%....10%....20%....30%....40%....50%....60%....70%....80%....90%....100% Creating machine... (myvm1) Copying C:\Users\Trey Brister\.docker\machine\cache\boot2docker.iso to C:\Users\Trey Brister\.docker\machine\machines\myvm1\boot2docker.iso... (myvm1) Creating SSH key... (myvm1) Creating VM... (myvm1) Using switch "myswitch" (myvm1) Creating VHD (myvm1) Starting VM... (myvm1) Waiting for host to start... Waiting for machine to be running, this may take a few minutes... Detecting operating system of created instance... Waiting for SSH to be available... Detecting the provisioner... Provisioning with boot2docker... Copying certs to the local machine directory... Copying certs to the remote machine... Setting Docker configuration on the remote daemon... Checking connection to Docker... Docker is up and running! To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: C:\Program Files\Docker\Docker\Resources\bin\docker-machine.exe env myvm1 A: (1), V0.15 fixed this issue officially: Fix issue #4424 - Pre-create check: "Hyper-V PowerShell Module is not available" Official Introduction: https://github.com/docker/machine/pull/4426 Address to donload V0.15 https://github.com/docker/machine/releases (2), I tested this, it works fine. No need restart docker It take effect immdiately after the "docker-machine.exe" is replaced with version 0.15 (3), Backup the original one is a good habit A: Just start docker desktop if you are on Windows
{ "language": "en", "url": "https://stackoverflow.com/questions/49421953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: HTTP mp4 filetransfer. IE downloads file too fast I have a web server that serves mp4 files. When I get a http request for a video that is 35mb, I use “send()” repeatedly in a loop to send 1mb each time. Chrome and Firefox handle this well and receive no more data than needed. Only if the user has reached far enough in the webplayer, the browser requests/receives more data. IE however, receives my "send()" every two seconds, which means the entire file is downloaded in about a minute. That is not good for a user who only watched 1 min of 14 (considering data consumption/useage). Can I do something differently? Best regards Arre
{ "language": "en", "url": "https://stackoverflow.com/questions/59702927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redirect a Page to Another Page for 10 Seconds Then Redirect Back Again to Original URL I want to temporarily redirect users to an ad page and then return them to their desired page again after 10 seconds. I don't know how to do this because I don't have much knowledge of PHP or Java. So please provide me complete redirect code and guide me where to put that code. I am using $_GET parameters on first page so let say my urls are as follow: mydomain.net/games/?game=PUBG+Mobile&Rating=5 mydomain.net/games/?game=Apex+Legends&Rating=4 mydomain.net/games/?game=GTA+5&Rating=4.5 I want every url to redirect to ads.php page and then redirect back to original url after 10 seconds and never redirect again. A: First of all: Java !== Javascript Java and Javascript are similar like Car and Carpet are similar. Source: https://stackoverflow.com/a/245068/3119231 - To redirect an user to another location you may use: // Simulate a mouse click: setTimeout(function() { // timer window.location.href = url; }, 10000); // 10000 ms = 10 seconds // Simulate an HTTP redirect: setTimeout(function() { // timer window.location.replace(url); }, 10000); // 10000 ms = 10 seconds Place it in the documents you like. Source: https://www.w3schools.com/howto/howto_js_redirect_webpage.asp Bonus (CaitLAN Jenner): You need to prevent your documents from redirecting in an infinite loop. Your visitors would get pushed from one site to another every 10 seconds. A: @Maurice mentioned how to perform a HTTP redirect in JavaScript. If you do this on both pages, however, then you will find yourself in an infinite redirect loop, which is very bad. To expand on that answer here is some PHP to dynamically disable the second redirect from the original page through the use of a query string parameter (see https://en.wikipedia.org/wiki/Query_string). First, you need to include the following PHP code at the top of your document. If you have other PHP code, just put the inside of this code below it. This will accept the redirect query string. <?php $redirect = 1 if (isset($_GET['redirect'])) { $redirect = htmlspecialchars($_GET["redirect"]); } ?> Now, later in the document (preferably at the end of body or within head) you need to dynamically generate the JavaScript using PHP as such. <?php if ($redirect == 1) { echo "<script>"; echo "// Simulate an HTTP redirect:"; echo "setTimeout(function() { // timer"; echo "window.location.replace(url);"; echo "}, 10000); // 10000 ms = 10 seconds"; echo "</script"; } ?> Note that you will need to replace "url" here with the appropriate url, which may require properly escaping quotations (see https://www.php.net/manual/en/function.addslashes.php) As a final note, you need to set the "redirect" query string appropriately on the page that redirects back to the original. You can do so with something like this: mydomain.net/games/?game=PUBG+Mobile&Rating=5&redirect=0 UPDATE PER REQUEST On the second page you don't need the PHP logic mentioned above. You simply need a JavaScript 10 second redirect. Something like this should work. <script> url = "mydomain.net/games/?game=PUBG+Mobile&Rating=5&redirect=0"; // Simulate an HTTP redirect: setTimeout(function() { // timer window.location.replace(url); }, 10000); // 10000 ms = 10 seconds </script> Note that here I've used a static URL. If you want this URL to be dynamic you can use the exact same approach I've mentioned for solving the infinite redirect. In other words, pass the original URL as a query string parameter to the ad page, parse it on the ad page through PHP, and use PHP to dynamically create the url in the code above.
{ "language": "en", "url": "https://stackoverflow.com/questions/56989430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Plugin with id 'io.fabric' not found" error. after removing fabric from build.gradle in my ionic react project android version build using capacitor, i followed the steps of removing all the fabric and replacing them with crashlytics reference: https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=android the build command: ionic cap copy android ionic cap open android now I am just getting the error when building: Caused by: org.gradle.api.plugins.UnknownPluginException: Plugin with id 'io.fabric' not found. here's my project build.gradle: buildscript { repositories { google() jcenter() } dependencies { classpath "com.android.tools.build:gradle:4.1.1" classpath 'com.google.gms:google-services:4.3.4' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } apply from: "variables.gradle" ext { var = '4.1.1' } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } and here's my app build.gradle: apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.firebase.crashlytics' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { applicationId "com.xxx.xxx" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' // firebaseCrashlytics { // nativeSymbolUploadEnabled true // } } } } repositories { flatDir{ dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs' } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" implementation project(':capacitor-android') testImplementation "junit:junit:$junitVersion" androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" implementation project(':capacitor-cordova-android-plugins') implementation platform('com.google.firebase:firebase-bom:26.0.0') implementation 'com.google.firebase:firebase-analytics:18.0.0' implementation 'com.google.firebase:firebase-crashlytics:17.2.2' } apply from: 'capacitor.build.gradle' try { def servicesJSON = file('google-services.json') if (servicesJSON.text) { apply plugin: 'com.google.gms.google-services' } } catch(Exception e) { logger.warn("google-services.json not found, google-services plugin not applied. Push Notifications won't work") } version reference: android studio: 1.4 android gradle plugin version: 4.1.1 gradle version: 6.6 A: when installing firebase don't install "cordova-plugin-firebase" if you are using react with ionic, it will create this error! fixed after removed
{ "language": "en", "url": "https://stackoverflow.com/questions/64803150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use the Symfony 2 Container in a legacy app Would like to integrate a legacy application with a Symfony 2 application - replacing more and more parts of the old application with Symfony components. The approach I would take is using the Symfony 2 container in the legacy application getting the services that are already configured for the Symfony 2 application. The first services I would like to use are the session and the security context. Questions: * *Is this feasible? *How do I get the configured service container? More info in the legacy application: The typical PHP mess: Single PHP files, as "controllers" (checking $_GET and $_POST for different execution paths). Each page includes init.php which sets up autoloading, database connection etc. The session management has its own class (which i would like to replace), the data is retrieved through calls to static methods (!) of database objects. A: I believe you can access the container instance from your legacy application like this $kernel = new AppKernel('prod', true); $kernel->loadClassCache(); $kernel->boot(); $request = Request::createFromGlobals(); $container = $kernel->getContainer(); $sc = $container->get('security.context'); A: Using Symfony's DIC as a standalone component is possible but you'd have to do many things "manually" (as you're not planning on using full Symfony Framework from the very beginning). You'll probably won't get much of using DIC with all that legacy stuff. If you want to go this path I'd consider choosing another component first (like HttpFoundation and HttpKernel). As @Cerad suggested you might wrap your legacy code in Symfony. Have a look at IngewikkeldWrapperBundle bundle. You can't use it as is but it might give you some ideas. There's a third way. You can decide to implement every new feature in a Symfony app. Than, you can make that both legacy and Symfony apps coexist. On a server level (i.e. Nginx), you might proxy legacy URLs to the legacy app and all the migrated URLs to a Symfony2 app. In my case this scenario was the best option and proved to be working. However, we were committed to abandon legacy app development (so every new feature or change had to be developed in a Symfony2 app). Edit: here's how you could boot the Symfony kernel in a legacy app and dispatch an event (which is needed for the firewall): $kernel = new \AppKernel('dev', true); $kernel->boot(); $request = Request::createFromGlobals(); $request->attributes->set('is_legacy', true); $request->server->set('SCRIPT_FILENAME', 'app.php'); $container = $kernel->getContainer(); $container->enterScope('request'); $container->get('request_stack')->push($request); $container->set('request', $request); $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); $eventDispatcher = $container->get('event_dispatcher'); $eventDispatcher->dispatch('kernel.request', $event);
{ "language": "en", "url": "https://stackoverflow.com/questions/10170989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: virtual machine query? hi i have installed ubuntu 10.4 as guest OS on vmware and windows xp is my host. now i want do know does vmware give a new ip address to the linux os.. if yes how do i get that ip address A: yes it should, try running ifconfig from the console. Hope this helps, Jason.
{ "language": "en", "url": "https://stackoverflow.com/questions/3159210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to "lock" radio buttons, checkboxes, and menus without graying them out? I have a form that I want to present in two states: 1) Normal form 2) Person can look at the form as filled out by a user but can't change anything It's easy to handle text inputs with the readonly property, but radio buttons, checkboxes, and dropdown menus don't use it. I can set the "disabled" property for those, but in most browsers they show up grayed out and barely visible. What I really want is for them to look like a normal form but be unclickable the way a disabled element is. Is there a way to override the normal "disabled" look? Or is the solution to disable them in some roundabout way handling clicks? I'm using jQuery for most of this stuff, if that matters... A: well, you could try hacks like this.... ​$(':radio:disabled').removeAttr('disabled').click(function(){ this.checked=false; })​; this will select all disabled radio buttons and enabled it but when click, will not be checked... demo and on <select> you could do like, $('select:disabled').removeAttr('disabled').change(function(){ $(this).find('option').removeAttr('selected'); // this.value = this.defaultValue; // you may also try this.. }); A: Just replace them with your own more controllable HTML/CSS construct, à la Niceforms, et al. (with disabled or readonly attribute, as appropriate, as fallback). A: A suggestion rather an answer: you can associate an event with the state change of an element, and cancel the change. You can do it the same way as the validate tools which allows to enter only digits or only some characters in <input type="text" /> fields. See a StackOverflow post about this. Another solution is to put something in front of your controls. For example: <div style="position:absolute;width:200px;height:200px;"></div> <input type="radio" /> will make your radio button unclickable. The problem is that doing so will prevent the users to copy-paste text or using hyperlinks, if the <div/> covers the whole page. You can "cover" each control one by one, but it may be quite difficult to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/3269926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bootstrap Responsive - Not Working I've created a very simple landing page using Bootstrap. As I was designing it I was working on the responsive breakpoints and in Chrome, they all looked and worked great. Now that I've uploaded my site, I realized that the responsive isn't working. In desktop I have no issues, but in mobile the text and button sizes remain the same. www.woodtechms.com Thanks for your help! A: I'm pretty sure it's due to missing meta tags inside header. Here's Bootstrap template I've also added img-responsive class to your logo image and then the logo scales down as it supposed to. A: It does work but only for screen sizes more than 768 and less than 900px as written in your custom-css: @media screen and (min-width: 768px) and (max-width: 900px) { /* ---- Logo Woodtech ---- */ .logo { margin-top: 230px; } /* ---- Title ---- */ h2 { font-size: 5.9rem; margin-top: 130px; margin-bottom: 60px; line-height: 70px; } /* ---- Text ---- */ p { font-size: 34px; padding-bottom: 34px; } /* ---- Button ---- */ .contact-button { width: 400px; font-size: 4rem; height: 100px; } } If you want it to change styles for other widths then you need to add more media queries like the one added in your css. For e.g., if you want the button width to be 300px in between screen size 600px and 800px you can write the following: @media screen and (min-width: 600px) and (max-width: 800px){ .contact-button{ width:300px; } } And likewise you can add styles for other elements at different widths.
{ "language": "en", "url": "https://stackoverflow.com/questions/43855301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is it possible to use if -> where in MySQL? I have a list of templates which user creates with some data (type of data is not important). The templates are stored in a table which have field private of enum type with values 0, 1 which means false/true. The main idea is that the each user can create a private template which can be see only by him, all other templates can see all system users. So my sql should be like this: SELECT `templates`.`id`, `templates`.`name`, `templates`.`description`, `templates`.`datetime`, `users`.`username` FROM (`templates`) JOIN `users` ON `templates`.`user_id` = `users`.`id` -- WHERE -- `users`.`id` <> 1 AND `templates`.`private` = 0 ORDER BY `templates`.`datetime` DESC LIMIT 5 In where i say that i need all rows except private where is not my id, but it miss my own private templates... A: There seems to be no reason to JOIN the users table. You can get all public and your own private templates with SELECT `templates`.`id`, `templates`.`name`, `templates`.`description`, `templates`.`datetime`, FROM `templates` WHERE `templates`.`user_id` = 42 OR `templates`.`private` = 0 I am assuming that the id of the current user is 42, substitute this with the real value when constructing the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/18498451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert date formatted string to DateTime object? I need to convert a date formatted string to a datetime object so that I can use the Twig date() function on the datetime object. Example string: '2015-06-20' Can Twig accomplish this or perhaps could it be done with a custom Twig extension? A: you can do this {{ "12/14/2016"|date("Y-m-d", option_timezone_convert) }} be aware, it will create from that string a datetime object with the default timezone, if you apply a timezone option, it will convert it. A: PHP's DateTime object can do this as a constructor: $date = new DateTime('2015-06-20');
{ "language": "en", "url": "https://stackoverflow.com/questions/30956572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Finding IP Address for IPhone I am working on IPhone. I want to know how to find a ip address of a iphone through USB/3G not on wifi. I am aware of seeing IP if it is connected through WiFI.(Going through settings and looking under Wifi) But i need IP through USB / 3G. what i did means i used personal hotspot and i connected my iphone to PC through usb. I got an IP. But when i added one more Iphone with same hot spot enabled and connected through USB i am getting like unidentified network. By using whatismyip.com site i am getting an ip . but i cant do anything with it. I am unable to reach my iphone with the provided ip of that site. So can anyone kindly provide information on how to look for IP of multiple Iphones connected to same PC. The purpose is to communicate to muliple iphones with their IP's. Thanks a million in advance. A: Unfortunately the responses are not completely correct. In a 3G/4G network every device gets an IP address, but THAT's NOT the IP address that you see when going to sites like www.whatismyip.com. That's the address that the Telco presents to the external world, not the device IP address. Telcos such AT&t, Verizon, Telefonica and similar assign a "private" IP address that is only valid in their network. This is similar to the internal IP address that you have in your phone when connect to the house wireless, but if you check in www.whatismyip.com you get the external IP address of your wireless router (You can check that those are different addresses). What Telcos do is known as NAT or PAT. The reason is that the current version of IP has a very limited number of available IP addresses, and all those million of devices cannot get public IP addresses (like the one you see in whatismyip.com). Actually several devices share that external IP address. Unlike Android devices where you can get the IP that the telco assigned to the device, iOS does not present that information to the user (unless you jailbreak the device or have an App). Although the address that whatismyip presents is not your real IP, it is the one that the external world recognizes so it suffices for most purposes. A: What you see on whatismyip.com is the IP address you get from your mobile provider, on which it depends what kind op IP you get. Very often 3G networks are NATted, meaning that you get an IP address from the range 10.0.0.0/8 which cannot be reached from outside. A: Using www.whatismyip.com should definitely give you the correct address? What address did you get when it came back? How did you verify if this was your iPhone's address? I assume you don't have a firewall installed on your iPhone? Hmm, other thing is your provider is doing some kind of filtering, NAT-ing, or other tomfoolery. If you don't mind me asking, what exactly are you trying to achieve here? Are you trying to run some kind of server-style app on your iPhone? Or do you just want to get a connection between the iPhone and a server - might be easier to initiate the connection from the iPhone side. You should check if it's at your provider's IP block range - an online whois check should tell you that (www.whois.net). How did you test whether this was your iPhone's address? Other option is just to have your iPhone hit a server that you control (using 3G), and check the server logs. Or just make things easier, and use an app to tell you - e.g. iStat: http://bjango.com/iphone/istat/ which will give you your cell (3G) IP address as well. Cheers, Victor A: There are two types of IP addresses: Private IP address (your device IP that you get it from your home Wi-Fi router or from your Teleco provider router to speak to those two routers). Public IP address (your home Wi-Fi router and/or from your Teleco provider router which they will use it to allow you to speak to another person on the Internet). **NOTE: Without Public IP address, you cannot speak to people who are on the Internet. Now both (your home Wi-Fi router or your Teleco Provider router)they have something called DHCP, or Dynamic Host Configuration Protocol. This protocol is used to allocate private IP address to anyone connected to local network (either home Wi-Fi or Teleco provider). That means both (home Wi-Fi router and Teleco provider router) have one single IP address called Public IP address to allow you to speak to outside world, but first they need to give private IP address to able you to speak with them (your home Wi-Fi router and your Teleco provider router). If your iOS connected to your home Wi-Fi, then you will have a Private IP address: 1- Go to settings. 2- Click on Wi-Fi. 3- List of Wi-Fi networks will be appeared. 4- Click on your Wi-Fi network name (known as SSID). 5- Click on the blue circle of the exclamation mark on the right side of your Wi-Fi name. You will see your Private IP Address there very clearly. Now if your iOS device is not connected to any Wi-Fi network, but it connected to your Teleco provider, then you cannot see your private IP address. I am sure there is a way to see your Private IP address that you got it from your Teleco Provider DHCP. You have to search from internet or ruin your device by jailbreak it. For the Public IP Address (no matter if you are connected to your home Wi-Fi or your Teleco Provider), go to your internet browser (e.x. google chrome) and type: "What is my ip address". The result will be between your hand in fractions of seconds! Now Back to your question: If you connected two iPhones to your PC and both have hotspot enabled, that means your PC USB ports will handle two IP Private addresses because your iPhones will act as your home Wi-Fi router. if you have windows OS in your laptop, then go to windows CMD terminal and type: ipconfig the CMD prompt terminal will give you number of IP address, there are your two Private IP addresses from your iPhones. Now if unidentified network message still there, open RUN in your windows OS and type [ ncpa.cpl ], it will take you to network connection setting section, right click on one of your iPhones networks and disable it, keeping the other enabled. I hope it is crystal clear now. A: When the phone is the hotspot for the Telecom cellular provider it actually being used as a Router therefor if you connect laptop to that hotspot you can open network setting on the laptop to view its tcp/ip settings and see the ip of the laptop and the ip of the Router which is the IP of your Phone. The Ip is a private one, you can ping to it or do what ever you want. Example of connecting Iphone to Mac Xcode wirelessly: * *share personal hotSpot from your phone. *connect your laptop to your phone private network using wifi, search for the ssid you set in your phone and set a correct password. *in Mac go to System prefences->Network->wifi connected->Advanced->Tcp/Ip copy Router Ip - this is your Iphone private Ip. In order to connect Xcode to Iphone wirelessly you first need to connect the phone with usb, open window->device and simulators, select your phone and set checkbox "connect via network" Now if the phone is disconnected from the Mac and the private network is shared as explained, you know the phone Ip, then you can select the phone in Xcode (it remember phones that were connected), open window->device and simulators, select your phone , click on it to get menu of options, select "connect with ip", provide the ip you saw as "Router" previously. Thats all, hope it'll help somebody.
{ "language": "en", "url": "https://stackoverflow.com/questions/10946624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to resize a Python matplotlib.pyplot.figure already created I'm working with this custom Py visual in PowerBI. Unfortunately, Power BI has some Python code leading my code that pre-defines the image size (5.55555555555556,4.16666666666667). The result is a small image surrounded by a lot of empty space: Is there any way I can redefine the size of the image, even though I cannot modify the leading code? Any other suggestions are welcome, Thanks! # Prolog - Auto Generated # import os, uuid, matplotlib matplotlib.use('Agg') import matplotlib.pyplot import pandas os.chdir(u'C:/Users/USER/PythonEditorWrapper_443a6d71-c4cc-4e62-ac6f-2dad3eeace3d') dataset = pandas.read_csv('input_df_d2b6d8be-2212-4ece-902c-f85219eff22b.csv') matplotlib.pyplot.figure(figsize=(5.55555555555556,4.16666666666667), dpi=72) matplotlib.pyplot.show = lambda args=None,kw=None: matplotlib.pyplot.savefig(str(uuid.uuid1())) #My code starts here, I cannot modify anything above this line. #I wish I could add a line here to redefine figsize=(5.55555555555556,4.16666666666667) A: from matplotlib import pyplot as plt plt.figure(figsize=(15,20)) try this
{ "language": "en", "url": "https://stackoverflow.com/questions/61680367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pe:keyfilter not working I need regex for primefaces keyfilter to allow input between 0-100 for percentage. I tried lot of expression but none seems working. I need my inputbox not to allow typing apart from 0-100. Any suggestions
{ "language": "en", "url": "https://stackoverflow.com/questions/33909177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: File modification time gets overwritten by background cache flushing I have code that performs following steps: * *open file *write data *set file timestamps (via SetFileInformationByHandle(FileBasicInfo)) *close file When file is stored on certain NAS devices (and accessed via share) it's modification time ends up being set to current time. According to Process Monitor Close() in step 4 results in a Write (local cache gets flushed/pushed to NAS device) that (seemingly) updates file's mtime on server. If I add FlushFileBuffers() (or sleep for few seconds) between steps 2 and 3 -- everything is fine. Is this a bug in SMB implementation of this NAS device (Dell EMC Isilon) or SetFileInformationByHandle() never promised anything? What is the best way to deal with this situation? I would really like to avoid having to call FlushFileBuffers()... Edit: Great... :-/ It looks like for executables (and only executables) atime (last access time) gets screwed up too (in the same way). Only these are harder to reproduce -- need to run this logic few times. Could be some antivirus... I am still investigating. Edit 2: According to procmon access time gets updated by EXPLORER.EXE -- when it sees an executable, it can't resist opening it and reading portions of it (probably extracting the icon). A: You can't really do anything -- I guess Isilon's SMB implementation doesn't support certain things (that would've preserved timestamps). I simply added FlushFileBuffers() before SetFileInformationByHandle() and made sure there are no related race conditions in my code.
{ "language": "en", "url": "https://stackoverflow.com/questions/65816670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yii2 dropDownList get selected value I have dropDownList in my view ( data from db) : use yii\widgets\ActiveForm; \app\assets\HelloAsset::register($this); $form = ActiveForm::begin(); $users=\app\models\User::find()->all(); $items=\yii\helpers\ArrayHelper::map($users,'id','username'); echo $form->field($model, 'username')->dropDownList($items); echo \yii\bootstrap\Html::submitButton('Send'); ActiveForm::end(); I want to get data from 'username' in my controller: $model=new Data(); if ($model->load(\Yii::$app->request->post())){ echo 'it is status:'.$model->username; }else { return $this->render('simple', ['model' => $model]); } But data is null. How I must get data in right? Please, help me solve this problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/38977762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: fixed-length permutations of a string I'm trying to take a seven-character string and generate all the possible 3- and 4-letter permutations of it. This seems like something that recursion would be handy for (most all permutation generators I've seen are recursive), but I keep getting stuck at how to avoid repetition. That is, if my input string is "aabcdef" I don't want any of the permutations to contain more than two "a" characters. Any insights you can provide are greatly appreciated. A: This can be done both iteratively and recursively. Here is a decent permutation generator. That can be adapted to your needs and made generic (to take a List<T> of elements) so it can take a list of numbers, a string (list of characters) and so on. A: Try thinking about the characters as elements in a bag of characters. Here's some pseudocode that should work: permute ( bag < character > : theBag, integer : length, string : resultSoFar ) if length <= 0 then: print resultSoFar exit end-if for each x in theBag: nextResult = resultSoFar + x nextBag = theBag - x permute( nextBag, length - 1, nextResult ) end-for end-method Good luck! A: make a function that takes a set of letters make it return the set of n permutations (3 or 4) that start with the letter you specify. Then run it once for each of the unique chars in your set. The full result set will be the union of the subsets. A: Here's a clue that might help. If you have input "aabcdef" and you don't want permutations with two "a"s, it is easier to remove one of the "a"s from the input rather than trying to eliminate the permutations with multiple "a"s as you generate them. A: @ Chip Uni: when I implemented your code, it generated all permutations of length x to max. So when I fed it length 3 with a bag containing 7 characters it generated all permutations of length 3 through 7. It was a simple matter to eliminate all results greater than length 4, though. Thank you very much, y'all! I greatly appreciate your suggestions and assistance. A: This is in Ruby, but it might help: http://trevoke.net/blog/2009/12/17/random-constrained-permutations-in-ruby/
{ "language": "en", "url": "https://stackoverflow.com/questions/1732601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extracting XML data reverse XSLT? I have some XML data that resides in an XML file and I am trying to get it into datatables. I have tried putting it into a Dataset. I have tried putting it in XML nodes. However, it all seems random and just all over the place and it's not working. I have tried to include a summarized version of how the data looks below. How can I extract it into clear tables and rows and columns? Also, I am not sure if this would help or not, but this XML is created from 4 tables that are then extracted to an XML file using and XSLT file. Is there a way to do it in REVERSE to take the XSLT and XML file into the original datatables? <obj name="TableName0"> <int name="ANumberThatsAColumn1" val="" /> <int name="ANumberThatsAColumn2" val="" /> <int name="ANumberThatsAColumn3" val="" /> <str name="ADateThatsAColumn4" val="2022-12-16T08:43:07.9870485-06:00" /> </obj> <list name="TableName1"> <obj href="RowOfData1/"> <int name="ColName1" val="0" /> <str name="ColName2" val="1" /> <int name="ColName3" val="1" /> <int name="ColName4" val="0" /> <int name="ColName5" val="6" /> <int name="ColName6" val="0" /> <str name="ColName7" val="#3062" /> <ref name="ColName8" href="SomeValue1" /> </obj> <obj href="RowOfData2/"> <int name="ColName1" val="0" /> <str name="ColName2" val="1" /> <int name="ColName3" val="1" /> <int name="ColName4" val="0" /> <int name="ColName5" val="6" /> <int name="ColName6" val="0" /> <str name="ColName7" val="#2543" /> <ref name="ColName8" href="SomeValue2" /> <int name="ColName9" val="0" /> <int name="ColName10" val="0" /> <int name="ColName11" val="0" /> </obj> </list> <list name="TableName2"> <list name="row1"> <int name="R0" val="0" displayName="#7925" /> <int name="R1" val="1" displayName="#7926" /> </list> <list name="row2"> <int name="R0" val="0" displayName="#21641" /> <int name="R1" val="1" displayName="#21642" /> <int name="R2" val="2" displayName="#21643" /> </list> </list> A: Here is a conceptual example for you. XML shredding is happening in T-SQL via two XQuery methods: * *.node() *.value() XQuery Language Reference (SQL Server) SQL DECLARE @xml XML = N'<root> <obj name="TableName0"> <int name="ANumberThatsAColumn1" val=""/> <int name="ANumberThatsAColumn2" val=""/> <int name="ANumberThatsAColumn3" val=""/> <str name="ADateThatsAColumn4" val="2022-12-16T08:43:07.9870485-06:00"/> </obj> <list name="TableName1"> <obj href="RowOfData1/"> <int name="ColName1" val="0"/> <str name="ColName2" val="1"/> <int name="ColName3" val="1"/> <int name="ColName4" val="0"/> <int name="ColName5" val="6"/> <int name="ColName6" val="0"/> <str name="ColName7" val="#3062"/> <ref name="ColName8" href="SomeValue1"/> </obj> <obj href="RowOfData2/"> <int name="ColName1" val="0"/> <str name="ColName2" val="1"/> <int name="ColName3" val="1"/> <int name="ColName4" val="0"/> <int name="ColName5" val="6"/> <int name="ColName6" val="0"/> <str name="ColName7" val="#2543"/> <ref name="ColName8" href="SomeValue2"/> <int name="ColName9" val="0"/> <int name="ColName10" val="0"/> <int name="ColName11" val="0"/> </obj> </list> <list name="TableName2"> <list name="row1"> <int name="R0" val="0" displayName="#7925"/> <int name="R1" val="1" displayName="#7926"/> </list> <list name="row2"> <int name="R0" val="0" displayName="#21641"/> <int name="R1" val="1" displayName="#21642"/> <int name="R2" val="2" displayName="#21643"/> </list> </list> </root>'; -- INSRT INTO <targetTable> SELECT c.value('@name', 'VARCHAR(20)') AS name , c.value('@val', 'INT') AS val , c.value('@displayName', 'VARCHAR(20)') AS displayName FROM @xml.nodes('/root/list[@name="TableName2"]/list/int') AS t(c); -- INSRT INTO <targetTable> SELECT c.value('@name', 'VARCHAR(20)') AS name , c.value('@val', 'VARCHAR(20)') AS val , c.value('@href', 'VARCHAR(20)') AS href FROM @xml.nodes('/root/list[@name="TableName1"]/obj/*') AS t(c);
{ "language": "en", "url": "https://stackoverflow.com/questions/75299259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: firefox moz, Web Transitions I have the following: .ui-dialog-body { position: relative; /* Needed for sliding left, right */ min-height:60px; padding: .5em 1em; } .ui-dialog-body.slideLeft { left:-500px; -webkit-transition: left .5s linear; -webkit-transition-delay: .2s; -moz-transition-property: left; -moz-transition-duration: .5s; } When the user clicks an item which requires loading, the class slideLeft is added which slides the div out of view. This works great in webkit (safari, chrome) but not in FireFox 4 beta. Any ideas why that is? A: Maybe you need left: 0 in the first style rule so that the transition is from 0px to 500px (which can be interpolated) rather than auto to 500px (which can't). (Also, there are differences between your -webkit-* declarations and your -moz-* declarations, but I don't think there need to be.) A: Put the declaration on the element, not the added class: .ui-dialog-body { position: relative; /* Needed for sliding left, right */ min-height:60px; padding: .5em 1em; -webkit-transition: left .5s linear; -moz-transition: left .5s linear; -ms-transition: left .5s linear; -o-transition: left .5s linear; transition: left .5s linear; } .ui-dialog-body.slideLeft { left:-500px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/4589083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mapping JPA native query to DTO returns column name instead of column value I'm working on a project using JPA and Spring Boot. I have an Entity named (for example) Model: This class is like this: private String model_id; private String attr1; private String attr2: private String attr3; I want to query according to model_id and one of these attributes. So I've created this query in SQL and works using MySQL: SELECT model_id AS modelId, attr1 AS attribute FROM my_table WHERE attribute LIKE '%my_value%' So native query is: @Query(SELECT model_id AS modelId, :attribute AS myAttribute FROM my_table WHERE :attribute LIKE '%:filter%', nativeQuery=true) List<MyModelDTO> doQuery(@Param("filter") String filter, @Param("attribute") String attribute) And MyModelDTO is an interface like this: public interface MyModelDTO{ String getModelId(); String getMyAttribute(); } But the desired output doesn't contains the correct value to myAttribute field. Is the column name instad the value. For example, using this table: | model_id | attr1 | attr2 | attr3 | --------------------------------------------- | "id_1" | "value1" | "value2" | "value3" | --------------------------------------------- If I query using filter=alue and attribute=attr2 expected result is: { modelId: "id_1", myAttribute: "value2" } Because I'm looking a value that contains alue into attr2 column. But I get: { modelId: "id_1", myAttribute: "attr2" } The column name is outpouted instead of column value. Have I missing something using nativeQuery or trying to parse into DTO object? Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/65704458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex: How to include character of "if" condition I'm making a date extractor using regex in java. Problem is that date is 20-05-2014 and my program is extracting 0-5-14. In short, how can I get the character on which I'm checking the second character of date? int count = 0; String data = "HellowRoldsThisis20-05-2014. [email protected]@gmail.com"; String regexOfDate = "((?<=[0])[1-9]{2})|((?<=[12])[0-9])|((?<=[3])[01])\\.\\-\\_((?<=[0])[1-9])|((?<=[1])[0-2])\\.\\-\\_((?<=[2])[0-9]{4})"; \\THE PROBLEM String[] extractedDate = new String[1000]; Pattern patternDate = Pattern.compile(regexOfDate); Matcher matcherDate = patternDate.matcher(data); while(matcherDate.find()){ System.out.println("Date "+count+"Start: "+matcherDate.start()); System.out.println("Date "+count+"End : "+matcherDate.end()); extractedDate[count] = data.substring(matcherDate.start(), matcherDate.end()); System.out.println("Date Extracted: "+extractedDate[count]); } A: You can try the regular expression: // (0[1-9]|[12][0-9]|[3][01])[._-](0[1-9]|1[0-2])[._-](2[0-9]{3}) "(0[1-9]|[12][0-9]|[3][01])[._-](0[1-9]|1[0-2])[._-](2[0-9]{3})" A: A single regex o match valid dates is awful. I'd do: String regexOfDate = "(?<!\\d)\\d{2}[-_.]\\d{2}[-_.]\\d{4}(?!\\d)"; to extract the potential date, then test if it is valid.
{ "language": "en", "url": "https://stackoverflow.com/questions/27459138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Azure Function .NET Core 3.1 C# unit test case with nUnit I need to create a unit test cases in Azure Function .NET Core using C# and NUnit framework. Please share a good example with links. Thanks in advance. A: Your unit tests shouldn’t include the Function App entry point, just like they shouldn’t include Asp.Net controllers, or the Main method of a Console app.
{ "language": "en", "url": "https://stackoverflow.com/questions/70367088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: AJAX success response not working Rails I have a mailer that is successfully sending using AJAX, but when the submit button is clicked, it is left depressed and no success message is displayed. Clicking the button multiple times results in multiple form submissions. The button should reset, and (from my understanding) the AJAX:success event should generate some sort of text to show it was successful. The AJAX Script (from rails guides) <script> $(document).ready -> $("#AJAX-form").on("ajax:success", (e, data, status, xhr) -> $("#AJAX-form").append xhr.responseText ).on "ajax:error", (e, xhr, status, error) -> $("#AJAX-form").append "<p>ERROR</p>" </script> The (UPDATED) form: <%= form_tag("/pages/thank_you", remote: true, id: 'AJAX-form') do %> <div class="row"> <div class="col-md-2"> <div class="input-group"> <%= text_field_tag :name, nil, class: 'form-control', placeholder: 'Name' %> </div> </div> <div class="col-md-4"> <div class="input-group"> <span class="input-group-addon" id="basic-addon1">@</span> <%= text_field_tag :email, nil, class: 'form-control', placeholder: 'Email' %> </div> </div> </div> <br> <div class="row"> <div class="col-md-6"> <div class="input-group text-area-wide"> <%= text_area_tag :message, nil, class: 'form-control text-area-wide', placeholder: 'Message' %> </div> </div> </div> <br> <%= submit_tag 'Send Message', class: 'btn btn-success' %> <% end %> The controller action: def thank_you @name = params[:name] @email = params[:email] @message = params[:message] || "Hello!" UserMailer.contact_form(@email, @name, @message).deliver end A: Double-check your JavaScript bindings. $("#AJAX-form").on(...) is looking for an element with id="AJAX-form". Your form appears to have class="AJAX-form". Either bind to the class with $(".AJAX-form").on(...) or change your form id to match <%= form_tag("/pages/thank_you", remote: true, id: 'AJAX-form') do %> A: From 1.9 version ajaxSuccess can be attached just only on the document object. "$(document).ajaxSucces(function(){...});" But you can use the following code: $('form').submit( function(){ return $.ajax({ url: $(this).attr("action"), data:data, processData: false, contentType: false, type: "POST", dataType : "json", success: function( result ) { $form.trigger('submit:success'); }, error: function( xhr, status, errorThrown ) { console.log( "Error: " + errorThrown ); console.log( "Status: " + status ); console.dir( xhr ); $form.trigger('submit:error'); }, complete: function( xhr, status ) { $form.trigger('submit:complete'); console.log( "The request is complete!" ); } } ); $('form.SpecialForm').on('submit:success', myFunction1); $('form.OtherSpecialForm').on('submit:success', otherFunction); $('form.ThirdSpecialForm').on('submit:error', thirdFunction); $('form.OneMoreSpecialForm').on('submit:complete', oneMoreFunction); $('form.theLastSpecialForm').on('submit:complete', theLastFunction);
{ "language": "en", "url": "https://stackoverflow.com/questions/29270855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to write runnable tests of static_assert? I am writing a unit-test suite for a source code library that contains static_asserts. I want to provide assurance these static_asserts do no more and no less than they are desired to do, in design terms. So I would like to be able to test them. I could of course add uncompilable unit tests of the interface that cause the static asserts to be violated by a comprehensive variety of means, and comment or #if 0 them all out, with my personal assurance to the user that if any of them are un-commented then they will observe that the library does not compile. But that would be rather ridiculous. Instead, I would like to have some apparatus that would, in the context of the unit-test suite, replace a static_assert with an equivalently provoked runtime exception, that the test framework could catch and report in effect: This code would have static_asserted in a real build. Am I overlooking some glaring reason why this would be a daft idea? If not, how might it be done? Macro apparatus is an obvious approach and I don't rule it out. But maybe also, and preferably, with a template specialization or SFINAE approach? A: As I seem to be a lone crank in my interest in this question I have cranked out an answer for myself, with a header file essentially like this: exceptionalized_static_assert.h #ifndef TEST__EXCEPTIONALIZE_STATIC_ASSERT_H #define TEST__EXCEPTIONALIZE_STATIC_ASSERT_H /* Conditionally compilable apparatus for replacing `static_assert` with a runtime exception of type `exceptionalized_static_assert` within (portions of) a test suite. */ #if TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1 #include <string> #include <stdexcept> namespace test { struct exceptionalized_static_assert : std::logic_error { exceptionalized_static_assert(char const *what) : std::logic_error(what){}; virtual ~exceptionalized_static_assert() noexcept {} }; template<bool Cond> struct exceptionalize_static_assert; template<> struct exceptionalize_static_assert<true> { explicit exceptionalize_static_assert(char const * reason) { (void)reason; } }; template<> struct exceptionalize_static_assert<false> { explicit exceptionalize_static_assert(char const * reason) { std::string s("static_assert would fail with reason: "); s += reason; throw exceptionalized_static_assert(s.c_str()); } }; } // namespace test // A macro redefinition of `static_assert` #define static_assert(cond,gripe) \ struct _1_test \ : test::exceptionalize_static_assert<cond> \ { _1_test() : \ test::exceptionalize_static_assert<cond>(gripe){}; \ }; \ _1_test _2_test #endif // TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1 #endif // EOF This header is for inclusion only in a test suite, and then it will make visible the macro redefinition of static_assert visible only when the test suite is built with `-DTEST__EXCEPTIONALIZE_STATIC_ASSERT=1` The use of this apparatus can be sketched with a toy template library: my_template.h #ifndef MY_TEMPLATE_H #define MY_TEMPLATE_H #include <type_traits> template<typename T> struct my_template { static_assert(std::is_pod<T>::value,"T must be POD in my_template<T>"); explicit my_template(T const & t = T()) : _t(t){} // ... template<int U> static int increase(int i) { static_assert(U != 0,"I cannot be 0 in my_template<T>::increase<I>"); return i + U; } template<int U> static constexpr int decrease(int i) { static_assert(U != 0,"I cannot be 0 in my_template<T>::decrease<I>"); return i - U; } // ... T _t; // ... }; #endif // EOF Try to imagine that the code is sufficiently large and complex that you cannot at the drop of a hat just survey it and pick out the static_asserts and satisfy yourself that you know why they are there and that they fulfil their design purposes. You put your trust in regression testing. Here then is a toy regression test suite for my_template.h: test.cpp #include "exceptionalized_static_assert.h" #include "my_template.h" #include <iostream> template<typename T, int I> struct a_test_template { a_test_template(){}; my_template<T> _specimen; //... bool pass = true; }; template<typename T, int I> struct another_test_template { another_test_template(int i) { my_template<T> specimen; auto j = specimen.template increase<I>(i); //... (void)j; } bool pass = true; }; template<typename T, int I> struct yet_another_test_template { yet_another_test_template(int i) { my_template<T> specimen; auto j = specimen.template decrease<I>(i); //... (void)j; } bool pass = true; }; using namespace std; int main() { unsigned tests = 0; unsigned passes = 0; cout << "Test: " << ++tests << endl; a_test_template<int,0> t0; passes += t0.pass; cout << "Test: " << ++tests << endl; another_test_template<int,1> t1(1); passes += t1.pass; cout << "Test: " << ++tests << endl; yet_another_test_template<int,1> t2(1); passes += t2.pass; #if TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1 try { // Cannot instantiate my_template<T> with non-POD T using type = a_test_template<int,0>; cout << "Test: " << ++tests << endl; a_test_template<type,0> specimen; } catch(test::exceptionalized_static_assert const & esa) { ++passes; cout << esa.what() << endl; } try { // Cannot call my_template<T>::increase<I> with I == 0 cout << "Test: " << ++tests << endl; another_test_template<int,0>(1); } catch(test::exceptionalized_static_assert const & esa) { ++passes; cout << esa.what() << endl; } try { // Cannot call my_template<T>::decrease<I> with I == 0 cout << "Test: " << ++tests << endl; yet_another_test_template<int,0>(1); } catch(test::exceptionalized_static_assert const & esa) { ++passes; cout << esa.what() << endl; } #endif // TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1 cout << "Passed " << passes << " out of " << tests << " tests" << endl; cout << (passes == tests ? "*** Success :)" : "*** Failure :(") << endl; return 0; } // EOF You can compile test.cpp with at least gcc 6.1, clang 3.8 and option -std=c++14, or VC++ 19.10.24631.0 and option /std:c++latest. Do so first without defining TEST__EXCEPTIONALIZE_STATIC_ASSERT (or defining it = 0). Then run and the the output should be: Test: 1 Test: 2 Test: 3 Passed 3 out of 3 tests *** Success :) If you then repeat, but compile with -DTEST__EXCEPTIONALIZE_STATIC_ASSERT=1, Test: 1 Test: 2 Test: 3 Test: 4 static_assert would fail with reason: T must be POD in my_template<T> Test: 5 static_assert would fail with reason: I cannot be 0 in my_template<T>::increase<I> Test: 6 static_assert would fail with reason: I cannot be 0 in my_template<T>::decrease<I> Passed 6 out of 6 tests *** Success :) Clearly the repetitious coding of try/catch blocks in the static-assert test cases is tedious, but in the setting of a real and respectable unit-test framework one would expect it to package exception-testing apparatus to generate such stuff out of your sight. In googletest, for example, you are able to write the like of: TYPED_TEST(t_my_template,insist_non_zero_increase) { ASSERT_THROW(TypeParam::template increase<0>(1), exceptionalized_static_assert); } Now I can get back to my calculations of the date of Armageddon :)
{ "language": "en", "url": "https://stackoverflow.com/questions/17408824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: XSLT loaded with AJAX, contains A: Would it help to put the alert in a CDATA tag? So <script type="text/javascript"> <![CDATA[alert('Only in Firefox');]]> </script> I've started doing that for all javascript that I include in xslt templates
{ "language": "en", "url": "https://stackoverflow.com/questions/29869327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to give priority to stages in a Jenkins parallel pipeline? I have a Jenkins pipeline with some parallel stages: pipeline { stages { stage("Parallel build") { parallel { stage("A") { /* takes 5 min */ } stage("B") { /* takes 5 min */ } stage("C") { /* takes 15 min */ } } } } } Assuming there aren't enough free executors to start all stages at once, how do I make sure stage C is among those started first? This will reduce build time from 20 minutes to 15, since A and B can run on the same executor consecutively.
{ "language": "en", "url": "https://stackoverflow.com/questions/75323571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to update Json object value dynamically in jquery? var jsonObj = [ { "key1": "value1", "key2": "value2", "key3​": "value3" }, { "key1": "value1", "key2": "value2", "key3​": "value3" } ]; I want to update all the values of all the objects. Here the keys and values are dynamic not key1 and value1. Could you help to figure it out the requirement. I want to make each value of each object to "changedvalue". So the final result after updating the jsonObj is [ { "key1": "changedvalue", "key2": "changedvalue", "key3​": "changedvalue" }, { "key1": "changedvalue", "key2": "changedvalue", "key3​": "changedvalue" } ]; A: jsonObj is an array thus you first have to iterate this array jsonObj.forEach(o => {...}); o is now an object. You have to iterate the keys/values of it for(let k in o) k is a key in the object. You can now alter the value o[k] = 'WhateverYouNeed' var jsonObj = [{ "key1": "value1", "key2": "value2", "key3": "value3" }, { "key1": "value1", "key2": "value2", "key3": "value3" }]; jsonObj.forEach(o => { for(let k in o) o[k] = 'ChangedValue' }); console.log(jsonObj); References: As stated, your structure is an array of objects and not JSON: Javascript object Vs JSON Now breaking you problem into parts, you need to * *Update property of an object: How to set a Javascript object values dynamically? *But you need to update them all: How do I loop through or enumerate a JavaScript object? *But these objects are inside an array: Loop through an array in JavaScript *But why do I have different mechanism to loop for Objects and Arrays? for cannot get keys but we can use for..in over arrays. Right? No, you should not. Why is using "for...in" with array iteration a bad idea? ReadMe links: Please refer following link and check browser compatibility as the solution will not work in older browsers. There are other ways to loop which are highlighted in above link. Refer compatibility for them as well before using them. * *Arrow functions *Array.forEach A: You might want to use a mixture of forEach and Object.keys const jsonObj = [ { "key1": "value1", "key2": "value2", "key3​": "value3" }, { "key1": "value1", "key2": "value2", "key3​": "value3" } ]; jsonObj.forEach( obj => { Object.keys( obj ).forEach( key => { const value = obj[ key ]; console.log( key, value ); } ); } ); A: Here you go with a solution https://jsfiddle.net/Lha8xk34/ var jsonObj = [{ "key1": "value1", "key2": "value2", "key3": "value3" }, { "key1": "value1", "key2": "value2", "key3": "value3" }]; $.each(jsonObj, function(i) { $.each(jsonObj[i], function(key) { jsonObj[i][key] = "changed" + key; }); }); console.log(jsonObj); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> A: Try pinch in your Case : var jsonObj = [ { "key1": "value1", "key2": "value2", "key3​": "value3" }, { "key1": "value1", "key2": "value2", "key3​": "value3" } ]; pinch(data, "/key1/", function(path, key, value) { return (value === "value1") ? "updatedValue" : value; });
{ "language": "en", "url": "https://stackoverflow.com/questions/45318501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Git rebase commit replays vs merge commits: a concrete example I have a question about how rebasing works in git, in part because whenever I ask other devs questions about it I get vague, abstract, high level "architect-y speak" that doesn't make a whole lot of sense to me. It sounds as if rebasing "replays" commits, one after another (so sequentially) from the source branch over the changes in my working branch, is this the case? So if I have a feature branch, say, feature/xyz-123 that was cut from develop originally, and then I rebase from origin/develop, then it replays all the commits made to develop since I branched off of it. Furthermore, it does so, one develop commit at a time, until all the changes have been "replayed" into my feature branch, yes? If anything I have said above is incorrect or misled, please begin by correcting me! But assuming I'm more or less correct, I'm not seeing how this is any different than merging in changes from develop by doing a git merge develop. Don't both methods result with all the latest changes from develop making their way into feature/xyz-123? I'm sure this is not the case but I'm just not seeing the forest through the trees here. If someone could give a concrete example (with perhaps some mock commits and git command line invocations) I might be able to understand the difference in how rebase works versus a merge. Thanks in advance! A: " It sounds as if rebasing "replays" commits, one after another (so sequentially) from the source branch over the changes in my working branch, is this the case? " Yes. " Furthermore, it does so, one develop commit at a time, until all the changes have been "replayed" into my feature branch, yes? " No, it's the contrary. If you rebase your branch on origin/develop, all your branch's commits are to be replayed on top of origin/develop, not the other way around. Finally, the difference between merge and rebase scenarios has been described in details everywhere, including on this site, but very broadly the merge workflow will add a merge commit to history. For that last part, take a look here for a start. A: RomainValeri's answer covers a lot of this, but let me add a few more items: * *"Replaying" a commit is a matter of running git cherry-pick or doing something equivalent. Some versions of git rebase literally do run git cherry-pick and if you want to think about how rebase works, that's the concrete piece to consider. (If you want to get into all the side details, the other principal way to "copy" a commit is to use git format-patch and git am: this goes faster because it doesn't handle renames properly. So the cherry-pick method is normally better. It was not the default until relatively recently, though, except for interactive rebases and any rebases that used the interactive machinery.) *Merge commits literally cannot be cherry-picked, so when using git rebase --rebase-merges, Git can't do that. Instead, Git will re-perform the merges. That is, Git figures out, at the start of the rebase operation, which commits are ordinary (single-parent) commits that can be cherry-picked, and which ones are merges with two or more parents. It then lays out, in the interactive rebase script—this particular kind of rebase always uses the interactive machinery—the special extra commands that interactive rebase needs in order to run git merge again. You can see these commands by adding --interactive to your rebase command. Be careful if you edit them: they have to be run in the right order for everything to work. *If you have merge commits that git rebase would need to "replay", and you don't use --rebase-merges, git rebase simply drops these merge commits entirely. The result is ... often not good. But if you did a merge that you did not mean to do, and want to do a rebase instead, it actually is good: this strips out the final merge. The TL;DR version of this is: both are complicated. Using git merge often makes one (1) new merge commit, that combines work. Using git rebase copies, as if by cherry-pick, many commits, and abandons the old (and lousy?) commits for the new-and-improved copies. When using either git cherry-pick or git merge, merge conflicts can occur. Git 2.33 is likely to have git rerere enabled by default, so that any previous resolution for some particular merge conflict will be picked up automatically and re-used. Currently you must enable this manually. The way rerere works is a bit complicated; it's worth reading through this blog entry.
{ "language": "en", "url": "https://stackoverflow.com/questions/67986445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DataGridView CellPainting drawing text with ampersand displays weirdly I have implemented a CellPainting event handler that uses TextRenderer.DrawText and it has worked great up until a cell had an ampersand in it. The cell shows the ampersand correctly while editing the cell, but when editing is done and it is drawn, it shows up as a small line (not an underscore). using System; using System.Drawing; using System.Windows.Forms; namespace StackOverFlowFormExample { public partial class DataGridViewImplementation : DataGridView { public DataGridViewImplementation() { InitializeComponent(); this.ColumnCount = 1; this.CellPainting += DGV_CellPainting; } private void DGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (!e.Handled && e.RowIndex > -1 && e.Value != null) { e.PaintBackground(e.CellBounds, false); TextRenderer.DrawText(e.Graphics, e.Value.ToString(), e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter); e.Handled = true; } } } } //creating the datagridview public partial class MainForm : Form { public MainForm() { InitializeComponent(); DataGridViewImplementation dgvi = new DataGridViewImplementation(); this.Controls.Add(dgvi); dgvi.Rows.Add("this is a & value"); } } replacing TextRenderer.DrawText(e.Graphics, e.Value.ToString(), e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter); with e.PaintContent(e.ClipBounds); shows it correctly, of course I want to be able to customize the painting of the content though. I've also tried using e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds); but it doesn't draw it the same as e.Paint(e.ClipBounds, e.PaintParts); I use e.Paint in my actual code when a cell is being painted that doesn't need my customized painting. How can I get e.Graphics.DrawString to look the same as e.Paint or get TextRenderer.DrawText to display the ampersand correctly? A: You want to use the TextRenderer version since DrawString should really only be used for printing: TextRenderer.DrawText(e.Graphics, e.Value.ToString(), e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor, TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter); The NoPrefix flag will show the ampersand correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/40753405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Where am I making mistake in VHDL? So I have posted this already but I haven't got any answer so I decided to try it one more time. The entity shall implement the following arithmetic functionality: • Substraction I1 - I2 • Input operand 1 (I1): 12 bit, two’s complement • Input operand 2 (I2): 8 bit, two’s complement • Output (O): 12 bit, two’s complement • Overflow (V) and Carry flag (C) set accordingly • Valid flag (VALID): indicates if the computed solution is valid or not So what I have done? Here is it: library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity arithmetic is port( I1 :in std_logic_vector(12-1 downto 0); -- Operand 1 I2 :in std_logic_vector(8-1 downto 0); -- Operand 2 O :out std_logic_vector(12-1 downto 0); -- Output C :out std_logic; -- Carry Flag V :out std_logic; -- Overflow Flag VALID :out std_logic -- Flag to indicate if the solution is valid or not ); end arithmetic; architecture behavior of arithmetic is begin process(I1,I2) begin if ((unsigned(I1)-unsigned(I2)) > unsigned(I1)) and ((unsigned(I1)-unsigned(I2)) > unsigned(I2)) then C <= '1'; else C <= '0'; end if; if I1(11)='1' and signed(std_logic_vector(unsigned(I1)-unsigned(I2)))>0 then V <= '1'; else V <= '0'; end if; if unsigned(I1) < unsigned(I2) then VALID <= '0'; else VALID <= '1'; end if; O <= std_logic_vector(unsigned(I1)-unsigned(I2)); end process; end behavior; There is no syntax mistakes or something like that. Only mistake is that: Error for: comp2,SUB I1= 100000011110 I2= 01000001 Expected: O= 011111011101 C= '0', V= '1', VALID= '0' Received: O= 011111011101 C= '0', V= '1' and VALID= '1' If someone could help I would be really thankful. A: If the numbers are twos complement, then signed is the correct type. With that either: 1. Make the ports signed rather than std_logic_vector or 2. Use signed internally and cast all inputs to signed and outputs to std_logic_vector once: signal I1_sv : signed(11 downto 0) ; . . . signal result : signed(11 downto 0) ; . . . I1_sv <= signed(I1) ; . . . O <= std_logic_vector(result) ; . . . All the individual type conversions (casting) you are doing in the code makes it difficult to read.
{ "language": "en", "url": "https://stackoverflow.com/questions/41127050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nginx filter module installation I am working on a nginx filter module. I could successfully install my module by following this - http://www.evanmiller.org/nginx-modules-guide.html tutorial. But it seems that all the other filter modules are not called now except the one which I have added. How can I debug this ? A: I know it's a long time since the question was asked, but after spending quite a bit of time on this, here is the issue: In the config file of your module, you need to provide this line: HTTP_AUX_FILTER_MODULES="$HTTP_AUX_FILTER_MODULES your_module_name" And you can remove the HTTP_MODULES line if you only have a filter. A: before * *ps awx | grep nginx to check nginx process id *Stop Nginx server gdb <path> // may be ->sr/local/nginx/sbin/nginx (gdb) set-follow-fork-mode child set detach-on-fork off set logging on set confirm off rbreak ngx_http* // you want to break point .. run
{ "language": "en", "url": "https://stackoverflow.com/questions/19492063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to confige an abstract class with structure map is there any problem with this kinda registration via structure map?? static public class ContainerBootstrapper { static public void BootstrapDefaultContainer(bool test = false) { StructureMap.ObjectFactory.Initialize(x => { x.Scan(p => { p.AssemblyContainingType<IPropertyType>(); p.AddAllTypesOf<IPropertyType>(); // p.AddAllTypesOf<IPropertyType>().NameBy(c => c.Name); }); }); } public interface IPropertyType : IIdentityObject, IPriority { string PropertyName { get; set; } ObjectType ObjectType { get; } string DisplayName { get; set; } IEntityType EntityType { get; set; } IList<IPropertyRuleObject> RuleObjects { get; set; } void AddRuleObject(IPropertyRuleObject ruleObject); } public abstract class PropertyTypeBase : PersistentObject, IPropertyType { public PropertyTypeBase() { } public PropertyTypeBase(string propertyName, string displayName) { PropertyName = propertyName; DisplayName = displayName; } .... } public class StringType : PropertyTypeBase { private ObjectType _objectType; public StringType() { _objectType = new ObjectType(typeof(string)); } public StringType(string propertyName, string displayName) : base() { PropertyName = propertyName; DisplayName = displayName; } public override ObjectType ObjectType { get { return _objectType; } } } when ContainerBootstrapper.BootstrapDefaultContainer(); execute I see this line of error: StructureMap Exception Code: 200 Could not find an Instance named "StringType" for PluginType Azarakhsh.Domain.Core.AdaptiveObjectModel.Interface.IPropertyType the calling code: public IPropertyType GetPropertyType(IIdentityObject identityObject, string name) { string[] Properties = name.Split('.'); object Result = identityObject; foreach (var Property in Properties) Result = Result.GetType().GetProperty(Property).PropertyType.Name; IPropertyType propertyType = StructureMap.ObjectFactory.GetNamedInstance<IPropertyType> (Result + "Type"); if (propertyType==null) throw new Exception("Property type not found"); return propertyType; } what is the problem? A: You are trying to get a named instance, but from what I can see of the code you have provided, you dont name your instances. The line of code that name your instances is commented out. But even if you would just use the ObjectFactory.GetInstance<IPropertyType>(); here, you would have got an error because structuremap dont know what constructor to use. There are several solutions to theis problem. * *Change your design so you only have one constructor *Mark your default constructor with the [DefaultConstructor] attribute, then it will work. *You can register it with objectFactory manually with something like this: x.For().Use().Ctor("propertyName").Is("someValue").Ctor("displayName").Is("someValue"); *You can write a custom registrationconvention as described here
{ "language": "en", "url": "https://stackoverflow.com/questions/6440917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular2 Component is not defined I am building up an Angular2 app, but my files aren't compiled correctly. Found some similar issues, but no solution worked to me. I am getting Error in console: (index):19 Error: (SystemJS) ReleasesComponent is not defined ReferenceError: ReleasesComponent is not defined at eval (http://localhost:3000/app/app.component.js:21:26) at Object.eval (http://localhost:3000/app/app.component.js:27:2) at eval (http://localhost:3000/app/app.component.js:30:4) at eval (http://localhost:3000/app/app.component.js:31:3) at eval (<anonymous>) at Object.eval (http://localhost:3000/app/app.module.js:15:23) at eval (http://localhost:3000/app/app.module.js:48:4) at eval (http://localhost:3000/app/app.module.js:49:3) at eval (<anonymous>) Evaluating http://localhost:3000/app/app.component.js Evaluating http://localhost:3000/app/app.module.js Evaluating http://localhost:3000/app/main.js Error loading http://localhost:3000/app/main.js at eval (http://localhost:3000/app/app.component.js:21:26) at Object.eval (http://localhost:3000/app/app.component.js:27:2) at eval (http://localhost:3000/app/app.component.js:30:4) at eval (http://localhost:3000/app/app.component.js:31:3) at eval (<anonymous>) at Object.eval (http://localhost:3000/app/app.module.js:15:23) at eval (http://localhost:3000/app/app.module.js:48:4) at eval (http://localhost:3000/app/app.module.js:49:3) at eval (<anonymous>) Evaluating http://localhost:3000/app/app.component.js Evaluating http://localhost:3000/app/app.module.js Evaluating http://localhost:3000/app/main.js Error loading http://localhost:3000/app/main.js app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule, JsonpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { ReleasesComponent } from './releases/releases.component'; import { DistroComponent } from './distro/distro.component'; import { ContactsComponent } from './contacts/contacts.component'; import { routing } from './app.routes'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, JsonpModule, routing ], declarations: [ AppComponent, HomeComponent, ReleasesComponent, DistroComponent, ContactsComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } releases.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'releases', templateUrl: 'app/releases/releases.component.html', providers: [ReleasesService] }) export class ReleasesComponent implements OnInit { releases: Observable<Array<string>>; constructor(private releasesService: ReleasesService) { } ngOnInit() { this.releases = this.releasesService.getReleases(); } } tsconfig.json { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": [ "es2015", "dom" ], "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true } } index.html <!DOCTYPE html> <html> <head> <base href="/"> <title>PR PR PR</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="app/assets/flex.css"> <link rel="stylesheet" href="app/assets/styles.css"> <!-- Polyfill(s) for older browsers --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <script src="systemjs.config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> </head> <body> <my-app>Loading AppComponent content here ...</my-app> </body> </html> app.component.ts import { Component } from '@angular/core'; import { Http } from '@angular/http'; import { ReleasesComponent } from './releases/releases.component'; import { ReleasesService } from './releases/releases.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', directives: [ReleasesComponent], providers: [Http, ReleasesService] }) export class AppComponent { name = 'My name'; } Folders structure A: You are wrong with the path name. Look at the below code. import { Component } from '@angular/core'; import { Http } from '@angular/http'; //modified the below lines import { ReleasesComponent } from './app/releases/releases.component'; import { ReleasesService } from './app/releases/releases.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', directives: [ReleasesComponent], providers: [Http, ReleasesService] }) export class AppComponent { name = 'My name'; } Also replace these in all the import statements where ever ReleasesComponent and ReleasesService is needed. Alternatively, you can also use import { ReleasesComponent } from './../app/releases/releases.component'; import { ReleasesService } from './../app/releases/releases.service'; A: Seems NgModule reference is missing. Import NgModule and FormModue in app.module.ts import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms';
{ "language": "en", "url": "https://stackoverflow.com/questions/41515306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Html forms in html table with JSP and servlets Im coding an web app that requires me to fill a table with data of the employees of a company and users should be able to access this table and then click on a employee's name to go to their info page. Im thinking of using forms (each clickable cell in table) to send the data to a servlet to process it and return the results, but im wondering if there is some other way of doing this without creating a form for each clickable cell. Thanks in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/19358353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I pass a variable to an event that isn't a class instance? I have an Event that I fire when someone favourites an entity on my system. This is fired using Event::fire(new AddedAsFav($entity_id));. In that event I want to pull some info about that $entity_id. To do this I believe I need to pass the $entity_id as part of the constructor of my Listener and then I can access it. Unfortunately the constructor expects a type, and I can't seem to pass just an integer. The docs have lots of examples where they pass Eloquent ORM instances, which is prefixed with the name of the class (Entity $entity, for example). But I don't want to pass a full object, just an ID, as the controller it's coming from only has an ID. I'd rather do the query (which is expensive and time consuming, hence the event) in the event itself. So how can I pass and access a basic int? Here's my listener: <?php namespace App\Listeners; use App\Events\AddedAsFav; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class GetFullEntity { /** * Create the event listener. * * @return void */ public function __construct(int $entity_id) { $this->entity_id = $entity_id; } /** * Handle the event. * * @param MovieAddedAsToWatch $event * @return void */ public function handle(AddedAsFav $event) { dd($event); } } A: If you will have public $entity_id in you Event file, then you will be able to get that value in Listener's handle method like so: $event->entity_id. A: You only type cast something you may want to use in the listener. if you want to simply access the data/object/array you passed to the event class, assign it to a public property in the event class: class AddedAsFav extends Event { public $entity_id; public function __construct($entity_id) { $this->entity_id = $entity_id; } } You can now access it in your listener like any property: <?php namespace App\Listeners; use App\Events\AddedAsFav; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class GetFullEntity { /** * Create the event listener. * * @return void */ public function __construct() { } /** * Handle the event. * * @param MovieAddedAsToWatch $event * @return void */ public function handle(AddedAsFav $event) { $entity_id = $event->entity_id; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/41911327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MarkerClustererPlus and nested clusters What I mean to do is the following: Suppose you have in a certain area a number of transmitting-receiving stations (pylons) (5, for example), and two hundred customers connected wirelessly to them (40 to each on average). I want first an icon to appear on that area showing the number 5 (number of stations), then on click event on this icon I want those 5 pylons icons to appear, and subsequently on click event on any of those icons all customers icons (only customers connected to the clicked pylon) to appear. All this for many areas in my country. The question is: what are the basic steps I should implement to get the task accomplished? What I have done at the moment is simply define a cluster of those 5 stations so, by clicking on its icon, all stations are shown. Should I now define new clusters, one for each station, each one containing customers connected to it? Or should I take a bottom-up approach, I mean, define a single big cluster of customers, and then move on? In such a case how should I proceed? I am a newbie to HTML and Javascript ( and I am 66!!! ), nonetheless I am trying to accomplish a task by using those languages and MarkerClusterePlus library. I need suggestions, please. Thanks to all. A: thanks for answering. I have only done few modifications on the example code provided with the library, both HTML and JS. HTML <script type="text/javascript" src="oNet.js"></script> <script type="text/javascript"> google.maps.event.addDomListener(window, 'load', oNet.init); </script> <div> Markers: <select id="nummarkers"> <option value="6" selected="selected">6</option> </select> </div> <strong>Tralicci Bari</strong> <div id="markerlist"> </div> </div> <div id="map-container"> <div id="map"></div> </div> JS function $(element) { return document.getElementById(element); } var oNet = {}; oNet.tralicci = null; oNet.map = null; oNet.markerClusterer = null; oNet.markers = []; oNet.infoWindow = null; oNet.init = function() { var latlng = new google.maps.LatLng(41, 16.38); var options = { 'zoom': 6, 'center': latlng, 'mapTypeId': google.maps.MapTypeId.ROADMAP }; oNet.map = new google.maps.Map($('map'), options); oNet.tralicci = data.tralicci; var numMarkers = document.getElementById('nummarkers'); google.maps.event.addDomListener(numMarkers, 'change', oNet.change); oNet.infoWindow = new google.maps.InfoWindow(); oNet.showMarkers(); }; Please note that what here appears as "oNet" is "speedTest" in the distributed example code, and "tralicci" is equivalent to "stations". Data_BA.json var data = { "tralicci": [ {"trl_id": "BA_01", "trl_nome": "1o traliccio", "longitude": 16.58, "latitude": 41.09, "title": "Traliccio n. 1\nPotenza 15 KW\nAltezza 37.5 m\nClienti connessi: 40", "stato": "on", "altezza": 375} , {"trl_id": "BA_02", "trl_nome": "2o traliccio", "longitude": 16.578, "latitude": 41.112, "title": "Traliccio n. 2\nPotenza 18 KW\nAltezza 42.5 m\nClienti connessi: 42", "stato": "on", "altezza": 350} , {"trl_id": "BA_03", "trl_nome": "3o traliccio", "longitude": 16.544, "latitude": 41.09, "title": "Traliccio n. 3\nPotenza 12 KW\nAltezza 22 m\nClienti connessi: 34", "stato": "off", "altezza": 474} , {"trl_id": "BA_04", "trl_nome": "4o traliccio", "longitude": 16.556, "latitude": 41.08, "title": "Traliccio n. 4\nPotenza 16 KW\nAltezza 35 m\nClienti connessi: 47", "stato": "on", "altezza": 375} , {"trl_id": "BA_05", "trl_nome": "5o traliccio", "longitude": 16.580, "latitude": 41.085, "title": "Traliccio n. 5\nPotenza 20 KW\nAltezza 39 m\nClienti connessi: 42", "stato": "on", "altezza": 375} , {"trl_id": "BA_06", "trl_nome": "6o traliccio", "longitude": 16.790, "latitude": 41.12, "title": "Traliccio n. 6\nPotenza 15 KW\nAltezza 32 m\nClienti connessi: 54", "stato": "on-off", "altezza": 333} I've done very little, as you can see. I use my own image as station image, different from the distributed m2.png.
{ "language": "en", "url": "https://stackoverflow.com/questions/40259487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: App doesn't filter correctly echo's from server I have created an app which sends and reads data from a server. It should react to the response it receives (the responses from server works correctly). The problems is that the code in the if-statement where I check this is never executed, the app always executes the code in the else block. My PHP code is: <?php require "init.php"; $user_name = $_POST["user_name"]; $user_pass = $_POST["user_pass"]; $user_name = utf8_encode($user_name); $user_pass = utf8_encode($user_pass); $sql_query = "SELECT user_name FROM user_info WHERE user_name ='".$user_name."' AND user_pass = '".$user_pass."' ;"; $result = mysqli_query($con, $sql_query); if(mysqli_num_rows($result) == 1){ echo "Login Success..Welcome "; }else{ echo"null"; } mysqli_close($con); ?> And this is my AsyncTask class: public class SendLogData extends AsyncTask <String, Void, String>{ String serverURL = "http://192.168.1.105/myapp/login.php"; Intent startapp ; private Context mcontext; private String response; private String error = null; ProgressDialog alertDialog; public SendLogData(Context context, Intent intent) { startapp = intent; mcontext = context; } @Override protected void onPreExecute() { alertDialog = new ProgressDialog(mcontext); alertDialog.setMessage("Connecting to server"); } @Override protected String doInBackground(String... params) { String username = params[0]; String password = params[1]; try { URL url = new URL(serverURL); HttpURLConnection client = (HttpURLConnection) url.openConnection(); client.setRequestMethod("POST"); client.setDoOutput(true); client.setDoInput(true); OutputStream outputStream = client.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); String data = URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" + URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); bufferedWriter.write(data); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); InputStream inputStream = client.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1")); String line = ""; while ((line = bufferedReader.readLine())!=null) { response = ""; response+= line; } bufferedReader.close(); inputStream.close(); client.disconnect(); return response; } catch (IOException e) { error = e.getMessage(); } return null; } @Override protected void onPostExecute(String result) { if (result.equals("null")){// This is were, the appp never actives the if, and goes right to the else Toast.makeText(mcontext, "You dont have a account with us.", Toast.LENGTH_LONG).show(); }else{ alertDialog.setMessage(result); alertDialog.show(); mcontext.startActivity(startapp); } } } Note: as im not getting any error from the app, i cant debug it, and the logcat doesnt show anything relevant. A: Try something like this: try { Charset myCharset = Charset.forName("iso-8859-1"); // and I really hope the name is correct - maybe "ISO-8859-1" BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, myCharset.newDecoder())); // .. process your input here ... } catch(Exception ex) { Log.e("DECODER", ex.getMessage() ); } A: I found the answer, thanks to @0X0nosugar, who helped me a lot. The problem was, the data that the server was retriving, was coming with 4 spaces, so when i was reiciving "null" in the app, which have 4 characters, the app was reading it with 8 characters. So, with simply trimming the data, it will convert the 8 char string, into a 4 char string: if (result.trim().equals("null")){ Toast.makeText(mcontext, "You dont have a account with us.", Toast.LENGTH_LONG).show(); }else{ alertDialog.setMessage(result); alertDialog.show(); mcontext.startActivity(startapp); } Don't know if the problem of inflate the data with spaces is actually a problem of the PHP or Android, but at least trim() helps to fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/31947325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Create multiple lists that meet one condition Python 3.6 I have a class City: class City(object): #A city has two coordinates in a graph(x,y), and a set of order def __init__(self, name, x, y, orders): self.name = name self.x = x self.y = y self.orders = orders I create a list of cities: Example: list_cities = [City1, City2, City3, City4] City1 (0.0, 0.0) [1, 2] City2 (1.0, 0.0) [2, 3] City3 (2.0, 0.0) [1, 3] City4 (3.0, 0.0) [2] I would like to group the cities by orders so that it would look like this: list1 = [City1, City3] list2 = [City1, City2, City4] list3 = [City2, City3] I've tried it with dictionaries, list lists and sets but it still does not give me results and I do not know how else I could get it. I leave you a code that I have tried: tours = [] city = City.create(arrayCity) for i in range(0,len(city.orders)): tours[city.orders[i]].append(city) This outputs: IndexError: list index out of range I hope you can help me. Thank you very much A: You are getting an IndexError because you are trying to access items in an unpopulated list. I imagine you are trying to fill out something more like this: tours = [[],[],[]] There are a few other problems here. You are indexing by integers starting from 1 it seems from your example of how each city is set up. You need to adjust for the offset. You don't need to iterate the indices of city.orders you really only need the values. The below code requires hard coding the number of lists you will need to fill out. Easy if it is known, but annoying if it can change. The below code assumes there are 3 tours as in your example. tours = [[],[],[]] city = City.create(arrayCity) for i in city.orders: tours[i-1].append(city) Ideally you might want a more dynamic set up where you don't have to specify the number of groups before hand: tours = [] city = City.create(arrayCity) for i in city.orders: while len(tours) < i: tours.append([]) tours[i-1].append(city) The above code introduces a while loop that will add lists to tours if you have not yet created the sub-lists you are trying to fill out. A: If you want list1 to contain Cities that have 1 in their order, you can test for that and take action: if 1 in city.order: list1.append(city) Similarly if 2 in city.order: list2.append(city) if 3 in city.order: list3.append(city) A: class City: def __init__(self,name,x,y,orders): self.name = name self.x = x self.y = y self.orders = orders City1 = City('City1',0.0,0.0,[1,2]) City2 = City('City2',1.0,0.0,[2,3]) City3 = City('City3',2.0,0.0,[1,3]) City4 = City('City4',3.0,0.0,[2]) list_cities = [City1, City2, City3, City4] group_cities_by_orders = {} for i in range(1,len(list_cities)+1): for city in list_cities: if i in city.orders: if i in group_cities_by_orders: group_cities_by_orders[i].append(city.name) else: group_cities_by_orders[i] = [city.name] print(group_cities_by_orders) Output: {1: ['City1', 'City3'], 2: ['City1', 'City2', 'City4'], 3: ['City2', 'City3']}
{ "language": "en", "url": "https://stackoverflow.com/questions/45361268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using the "existence" of a list item as an if-statement conditional with Python I have a program in Python3 where I take values and append them to 1 of two lists (I sort certain values into a certain list). Then I want to do something like this (just an example using the 1st item from the lists): if list1[0] and list2[0] exist: #do something using both lists else: if list1[0] exists: #do something using just the first list else: #do something using just the second list It's supposed to be a backup: in case I dont get a value for both the lists, I want to just use the value from the first list. Then, if I don't have an item from the first list, I use the second list. So what I'm asking is: how do I test if an item in a list 'EXISTS'? A: Check the lengths of the lists. if len(list1) > 0 and len(list2) > 0: # do something using both lists elif len(list1) > 0: # do something using just the first list else: # do something using just the second list If you're looking specifically for the first element, you can shorten this to: if list1 and list2: # do something using both lists elif list1: # do something using just the first list else: # do something using just the second list Evaluating a list in a boolean context checks if the list is non-empty. A: If you want to check if list[n] exists, use if len(list) > n. List indexes are always consecutive, and never skip, so it works. A: If you want to check if element of specific index is in the list you can check if index < len(list1). (assuming index is a non negative integer) if index < len(list1) and index < len(list2): #do something using both lists elif index < len(list1): #do something using just the first list elif index < len(list2): #do something using just the second list If you want to check whether element of specific value is in the list you will use if value in list1. if value in list1 and value in list2: #do something using both lists elif value in list1: #do something using just the first list elif value in list2: #do something using just the second list
{ "language": "en", "url": "https://stackoverflow.com/questions/45065447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to detect invalid command in speech recognition c#? I have a problem. I'm creating a speech recogntion program in c#. I want my program to be able to detect an incorrect command. I tried using the try and catch but i think i got it wrong. void Default_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { string speech = e.Result.Text; switch (case)... { //Commands } } try { if (speech != e.result.Text) Bill.Speak("You have given an invalid command. Please try again."); } catch{} How can I do this properly? A: Just add an default to your switch case switch (speech) { case "1": Bill.Speak("Command 1"); break; case "2": Bill.Speak("Command 2"); break; default: Bill.Speak("You have given an invalid command. Please try again."); break; } A: I think what you want is a default for your switch. so switch (case)... { //Commands default: // not recognized Bill.Speak("You have given an invalid command. Please try again."); } A: add Default: Bill.Speak("I donot understand command"); to your case statement
{ "language": "en", "url": "https://stackoverflow.com/questions/27153894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to force App to re-render after mutation? I have a React app built using Next.js. I want to be able to login and then cause the app to re-render in order for it to attempt to fetch the current logged in user. My _app.js component is wrapped with the apollo provider and has a get user Query as well: class MyApp extends App { render() { const { Component, pageProps, apolloClient } = this.props; return ( <> <Container> <ApolloProvider client={apolloClient}> <Query query={GET_USER} fetchPolicy="network-only" errorPolicy="ignore"> {({ loading, data, error }) => console.log("rendering app", data) || ( <> <Component {...pageProps} user={data && data.me} /> </> )} </Query> </ApolloProvider> </Container> </> ); } } I then have a login form which simply sends the email and password to my API which then returns a set-cookie token header with the access token. <Mutation mutation={LOGIN} onError={error => { this.setState({error: "Incorrect email or password"}) }} onCompleted={() => { window.location.reload() // temp solution to cause app to re-render }} > {(login, {loading}) => ( <Login {...this.props} login={login} loading={loading} error={error} /> )} </Mutation> I can successfully log in but I was expecting the Apollo cache to get written to with the user data: { "data": { "login": { "_id": "abcd1234", "accessToken": "abc123", "firstName": "First", "lastName": "Last", "email": "[email protected]", "__typename": "User" } } } As the cache is getting written to, I was expecting the _app.js / ApolloProvider children to re-render as they receive props from the cache. My get user Query should then attempt to run again (this time with the access token set in a cookie) and a user should be returned (indicating the user is logged in). Why is my mutation not telling my app to re-render onCompleted? A: This is the perfect scenario for refetchQueries(): https://www.apollographql.com/docs/angular/features/cache-updates/#refetchqueries In your scenario, you could pass this prop to your Login mutation component to refetch the GET_USER query after login. Export the GET USER from your _app.js (or wherever you're moving it to if you're putting it in a User Hoc). Then in your login mutation: import { GET_USER } from '...' <Mutation mutation={LOGIN} onError={error => { this.setState({error: "Incorrect email or password"}) }} onCompleted={() => { window.location.reload() // temp solution to cause app to re-render }} // takes an array of queries to refetch after the mutation is complete refetchQueries={[{ query: GET_USER }]} > {(login, {loading}) => ( <Login {...this.props} login={login} loading={loading} error={error} /> )} </Mutation> The other alternative is to use the update method to manually set it to the cache and then keep a reference to that data or retrieve it from the cache with a cache id so you don't have to fetch more data, but the refetchQueries is perfect for simple login mutations like this that aren't too expensive to retrieve.
{ "language": "en", "url": "https://stackoverflow.com/questions/56584512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I resolve the outer promise inside a mocked function with Jest? Here is my basic setup I'm trying to test. First, Method I'm testing: Thing.prototype.getStuff = function(){ return new Promise((resolve, reject) => { // Bunch of business logic... this.getOtherStuff().then((data) => { // Perform business logic with data. I want to test that certain things get called depending on the response. mockedThirdParty._performLogic().nestedLogic(null, () => { // Now resolve outer promise here with new data resolve({newdata: goodstuff}); // Or depending on the logic, reject }); }); }); } In my test for getStuff, I am mocking the response for getOtherStuff. I'm doing that like so: Thing.prototype.getOtherStuff.mockImplementationOnce(()=> Promise.resolve({data: 'value'})); So my whole test looks like this: test('Here is my test name', async () => { Thing.prototype.getOtherStuff.mockImplementationOnce(()=> Promise.resolve({data: 'value'})); let instance = new Thing(); await instance.getStuff(); // We never get to this test because the test timeouts expect(Thing.prototype._performLogic).toHaveBeenCalled() }); So my test always timeout because I'm never resolving the outer promise in getStuff. I get this error: Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error: How can I resolve this outer Promise while also mocking the inner async call getOtherStuff? EDIT -> See function above How do I pass a callback to a mocked implementation of a third-party library? I'm trying it like this, but I don't think I defining nestedLogic correctly: const mockedScene = { nestedLogic: jest.fn().mockImplementation(() => Promise.resolve()) } jest .spyOn(Thirdparty.prototype, "_performLogic") .mockImplementation(() => (mockedScene)) A: The reason is you don't add a spy on _performLogic method. You can use jest.spyOn(object, methodName) method to spy on the _performLogic method. E.g. index.js: function Thing() {} Thing.prototype.getStuff = function() { return new Promise((resolve, reject) => { this.getOtherStuff().then(data => { this._performLogic(); const goodstuff = data; resolve({ newdata: goodstuff }); }); }); }; Thing.prototype.getOtherStuff = function() { console.log("real get other stuff"); }; Thing.prototype._performLogic = function() { console.log("real perform logic"); }; module.exports = Thing; index.spec.js: const Thing = require("."); describe("Thing", () => { describe("#getStuff", () => { afterEach(() => { jest.restoreAllMocks(); }); it("should pass", async () => { // make a stub jest .spyOn(Thing.prototype, "getOtherStuff") .mockImplementationOnce(() => Promise.resolve({ data: "value" })); // add a spy jest.spyOn(Thing.prototype, "_performLogic"); let instance = new Thing(); await instance.getStuff(); expect(Thing.prototype._performLogic).toHaveBeenCalled(); expect(Thing.prototype.getOtherStuff).toBeCalledTimes(1); }); }); }); Unit test result with coverage report: PASS src/stackoverflow/59148901/index.spec.js (7.573s) Thing #getStuff ✓ should pass (12ms) console.log src/stackoverflow/59148901/index.js:375 real perform logic ----------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | ----------|----------|----------|----------|----------|-------------------| All files | 91.67 | 100 | 83.33 | 90.91 | | index.js | 91.67 | 100 | 83.33 | 90.91 | 14 | ----------|----------|----------|----------|----------|-------------------| Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 9.013s Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59148901
{ "language": "en", "url": "https://stackoverflow.com/questions/59148901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Jenkins Amazon Cloud slave can't checkout multibranch pipeline repo I configured ec2 cloud slave on jenkins - when my multibranch pipeline starting it's first checkout the scm when this run on master everything works fine and the checkout success but when it run on slave it's look it does not know the key: In the multibranch pipeline configurations it's configured to use my SSH credentials: This is the key configuration: So it's look like the slave don't know the key - how can I configure this key in the slave ?
{ "language": "en", "url": "https://stackoverflow.com/questions/52717912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validation didnt work well after submit $(function(){ $("form").validate( { rules: { username: {required: true}, email: {required: true, email: true}, }, messages: { username: {required: 'Please enter your username'}, email: {required: 'Please enter your email address', email: 'Please enter a VALID email address'}, } }); }); input.error, select.error, select.error, textarea.error{ background: #fff0f0; border: 2px solid #ee9393; } .error{ color: #ee9393; } input.valid, select.valid, select.valid, textarea.valid{ background: #e3ffd4; border: 2px solid #6fb679; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script> <form> <label class="input"> <i class="icon-append fa fa-user"></i> <input type="text" name="username" placeholder="Username"> </label> <label class="input"> <i class="icon-append fa fa-envelope-o"></i> <input type="email" name="email" placeholder="Email address"> </label> <button type=submit>Submit</button> </form> I use jQuery Validation Plugin to check form. I have little problem with one of my field. 1) When user enter some text in "username" field, its became green which mean field is valid. 2) Then I press submit button. As you see from the picture "email" field became red cause it was empty. 3) After that I deleted the text from the "username" field but its still green while color of the field must change to red. So my question is how to change that strange behavior with 'username' field?! A: The validation plugin from https://jqueryvalidation.org/ triggered when you submit the form. The issue is, you only clear the username field without resubmit it. You can try validation on keyup event to that field. Here's the example, you just need to define the border color or another css properties in red class. $("input").keyup(function() { var value = $(this).val(); if (value.length == 0) { $(this).addClass('red'); $(this).after('<div class="err-msg">Please fill this field</div>'); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/40935325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opening the app from show 2 app icons on React native/android I just ejected from Expo and implemented a Deeplink the problem is when I open the link in android there are 2 apps that will open the first one is from an android manifest because I can change it a name but 2nd it I don't where it triggered or how it generated.
{ "language": "en", "url": "https://stackoverflow.com/questions/64547347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery validation plugin - numbers only, min & max length - space issue I'm using jQuery Validation (PLUGIN URL) plugin for most of my form validation: I have following example (LIVE EXAMPLE): FORM: <form class="form" id="feedback-form" method="post" action="#"> <label for="phone">Contact number:</label> <input type="text" value="" id="phone" name="phone" class="required"> <br class="clr"> <div class="form-buttons"> <input id="submit" type="submit" value="Submit" class="button" > </div> <br class="clr"> <br /><br /> </form> jQuery: $("#feedback-form").validate({ rules: { phone: { number: true, // as space is not a number it will return an error minlength: 6, // will count space maxlength: 9 } } }); I have two issues, both relating to space usage. * *min & max length will count space as an character *if number = true and space is used, it will return error as space is not a number Is there any workaround this? Have any of you bumped in on the same problem? Please note I want to keep allowing to type in space (for readability). A: You can add a beforeValidation callback to send the value without spaces, take a look here: Jquery Validator before Validation callback, it seems to be what you're looking for A: a very smiple solution is : replace the type of the phone input as the following : <input id="phone" type="number" maxlength="10" size="2" max="99" style="width:36px;" required /> and you would never have issues with spaces and stuff, just used that in my code ! enjoy
{ "language": "en", "url": "https://stackoverflow.com/questions/7318024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Importing a MySQL schema to Xcode as a CoreData Data Model I have an existing MySQL database, I would like to import the schema into Xcode and create a Core Data data model. Is there a way (tool, process) to import the CREATE statements so I don't have to build the models "by hand"? As an intermediary step I could convert to SQLite, I'm not worried about the relationships, foreign keys etc just auto-generating the Entities (Tables) and Properties (Columns). A: Actually I needed the feature so badly too that I have decided to make an OSX utility to do so. BUT... then I found a utility in the Mac Appstore that (partially) solves this problem (it was free for some time, I do not know its current state). Its called JSONModeler and what it does is parsing a json tree and generates the coredata model and all derived NSManagedObject subclasses automatically. So a typical workflow would be: * *Export the tables from MySQL to xml *Convert the xml to json *Feed the utility with that json and get your coredata model Now, for a more complicated scenario (relationships etc) I guess you would have to tweak your xml so it would reflect a valid object tree. Then JSONModeler will be able to recreate that tree and export it for coredata. A: The problem here is that entities are not tables and properties are not columns. Core Data is an object graph management system and not a database system. The difference is subtle but important. Core Data really doesn't have anything to do with SQL it just sometimes uses SQL as one its persistence options. Core Data does use a proprietary sqlite schema and in principle you can duplicate that but I don't know of anyone who has succeeded in a robust manner except for very simple SQL databases. Even when they do, its a lot of work. Further, doing so is unsupported and the schema might break somewhere down the line. The easiest and most robust solution is to write a utility app to read in the existing DB and create the object graph as it goes. You only have to run it once and you've got to create the data model anyway so it doesn't take much time.
{ "language": "en", "url": "https://stackoverflow.com/questions/3924856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a AudioManager.MODE_IN_COMMUNICATION Bluetooth permission interaction? I have a very simple line of code: audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); However, recently on 4.0+ devices, I am seeing a crash due to this line saying it requires the bluetooth permission. To be more precise, the error I'm seeing says: java.lang.SecurityException: Need BLUETOOTH permission at the line of my setMode. I have the MODIFY_AUDIO_SETTINGS permission, however I do not see how this interacts with bluetooth, so I am looking for a confirmation of whether or not I truly need the BLUETOOTH permission for MODE_IN_COMMUNICATION A: From a logical point of view, there is no way that AudioManager would use Bluetooth and thus need android.permission.BLUETOOTH. From a source code point of view, setMode() needs only android.permission.MODIFY_AUDIO_SETTINGS: * *AudioManager:1425 public void setMode(int mode) { IAudioService service = getService(); try { service.setMode(mode, mICallBack); } catch (RemoteException e) { Log.e(TAG, "Dead object in setMode", e); } } *AudioService:703 public void setMode(int mode, IBinder cb) { if (!checkAudioSettingsPermission("setMode()")) { return; } *AudioService:1250 boolean checkAudioSettingsPermission(String method) { if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS") == PackageManager.PERMISSION_GRANTED) { return true; } String msg = "Audio Settings Permission Denial: " + method + " from pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid(); Log.w(TAG, msg); return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/21417127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NSIS Exec command with very long parameter list being cut off by the next line In my NSIS script, I have the following lines (Didn't turn the 1st line into a code block because it was too long and looked bad as 1 line): Exec '"$BINDIR\SubscriberACD.exe" //IS//SubscriberACD --Install="$BINDIR\SubscriberACD.exe" --Description="Subscriber service with Apache Commons Daemon" --Jvm="$JVMDIR\jvm.dll" --Classpath="$CLASSESDIR\SubscriberACD.jar;$CLASSESDIR\jeromq-0.3.5.jar;$CLASSESDIR\jackson-databind-2.6.3.jar;$CLASSESDIR\jackson-core-2.6.3.jar;$CLASSESDIR\jackson-annotations-2.6.0.jar;$CLASSESDIR\management-core-util-4.1.2.jar;$CLASSESDIR\management-measurement-4.1.2.jar;$CLASSESDIR\management-measurement-checkpoint-writer-1.0.jar;$CLASSESDIR\jna-4.2.2.jar;$CLASSESDIR\jna-platform-4.2.2.jar" --StartMode=jvm --StartClass=SubscriberACD.Subscriber --StartMethod=windowsService --StartParams=start --StopMode=jvm --StopClass=SubscriberACD.Subscriber --StopMethod=windowsService --StopParams=stop --LogPath="$INSTDIR\SubscriberACD\logs" --StdOutput=auto --StdError=auto' Sleep 5000 ExecWait '"sc" config SubscriberACD start=" auto"' Somehow, when I look at my NSIS logs, I see the following: Execute: "C:\Program Files (x86)\MyProduct\SubscriberACD\bin\SubscriberACD.exe" //IS//SubscriberACD --Install="C:\Program Files (x86)\MyProduct\SubscriberACD\bin\SubscriberACD.exe" --Description=" Subscriber service with Apache Commons Daemon" --Jvm="C:\Program Files (x86)\MyProduct\SubscriberACD\jdk7\jre\bin\server\jvm.dll" --Classpath="C:\Program Files (x86)\MyProduct\SubscriberACD\classes\SubscriberACD.jar;C:\Program Files (x86)\MyProduct\SubscriberACD\classes\jeromq-0.3.5.jar;C:\Program Files (x86)\MyProduct\SubscriberACD\classes\jackson-databind-2.6.3.jar;C:\Program Files (x86)\MyProduct\SubscriberACD\classes\jackson-core-2.6.3.jar;C:\Program Files (x86)\MyProduct\SubscriberACD\classes\jackson-annotations-2.6.0.jar;C:\Program Files (x86)\MyProduct\SubscriberACD\classes\management-core-util-4.1.2.jar;C:\Program Files (x86)\MyProduct\SubscriberACD\classes\management-measurement-4.1.2.jar;C:\PrograExecute: "sc" config SubscriberACD start= auto Notice how NSIS combined the two lines and actually overwrote some of the content from the first line. Any ideas on on what is causing this? Does NSIS not like commands with long parameters? Originally, I used ExecWait for my first command. When I was seeing the same problem, I switch to using Exec and then added a Sleep 5000 after that to sleep for 5 seconds since I thought it might have been a timing issue. I double checked my quotation marks to make sure that they match. A: NSIS has a 1024 character limit by default. I'm guessing when $INSTDIR is expanded you exceed that limit. You can download the large string build or execute a batch file instead: Section InitPluginsDir FileOpen $0 "$PluginsDir\test.cmd" w FileWrite $0 '@echo off$\n' ; Write out example command in pieces: FileWrite $0 '"$sysdir\forfiles.exe"' FileWrite $0 ' /P "$windir" /S' FileWrite $0 ' /M "*shell32*"$\n' FileClose $0 ExecWait '"$PluginsDir\test.cmd"' SectionEnd
{ "language": "en", "url": "https://stackoverflow.com/questions/38728790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLite with ArrayList and ArrayAdapter Could you please tell me what's wrong with this code. It runs but results are not listed. I just want a simple SQLiteDB running test to finalize my another project. I assume that something wrong with ArrayList use. public class MainActivity extends Activity { String names; ListView lvMain; ArrayList<String> values; ArrayAdapter<String> adapter; DBHelper dbHelper; EditText et; Button btnAdd; Button btnRead; Button btnClear; Button btnShow; Cursor c; int nameColIndex; int idColIndex; /** * Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnAdd = (Button) findViewById(R.id.btnAdd); btnRead = (Button) findViewById(R.id.btnRead); btnClear = (Button) findViewById(R.id.btnClear); btnShow = (Button) findViewById(R.id.btnShow); dbHelper = new DBHelper(this); lvMain = (ListView) findViewById(R.id.lvMain); values = new ArrayList<String>(); } public void onButtonClick(View v) { ContentValues cv = new ContentValues(); String name = et.getText().toString(); SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (v.getId()) { case R.id.btnAdd: cv.put("name", name); // вставляем запись и получаем ее ID long rowID = db.insert("mytable", null, cv); break; case R.id.btnRead: // делаем запрос всех данных из таблицы mytable, получаем Cursor c = db.query("mytable", null, null, null, null, null, null); // ставим позицию курсора на первую строку выборки // если в выборке нет строк, вернется false if (c.moveToFirst()) { // определяем номера столбцов по имени в выборке idColIndex = c.getColumnIndex("id"); nameColIndex = c.getColumnIndex("name"); do { // получаем значения по номерам столбцов c.getInt(idColIndex); names = c.getString(nameColIndex); values.add(names); // переход на следующую строку // а если следующей нет (текущая - последняя), то false - выходим из цикла } while (c.moveToNext()); } else { c.close(); } break; case R.id.btnClear: // удаляем все записи int clearCount = db.delete("mytable", null, null); break; case R.id.btnShow: break; } // закрываем подключение к БД adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values); lvMain.setAdapter(adapter); dbHelper.close(); adapter.notifyDataSetChanged(); } class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context) { // конструктор суперкласса super(context, "myDB", null, 1); } @Override public void onCreate(SQLiteDatabase db) { // создаем таблицу с полями db.execSQL("create table mytable (" + "id integer primary key autoincrement," + "name text," + "email text" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } } Here is main, may be I am missing something? `<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"> </TextView> <EditText android:id="@+id/et" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1"> <requestFocus> </requestFocus> </EditText> </LinearLayout> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btnAdd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onButtonClick" android:text="Add"> </Button> <Button android:id="@+id/btnRead" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onButtonClick" android:text="Read"> </Button> <Button android:id="@+id/btnClear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onButtonClick" android:text="Clear"> </Button> <Button android:id="@+id/btnShow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onButtonClick" android:text="Show"> </Button> </LinearLayout> <ListView android:id="@+id/lvMain" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView> </LinearLayout>` A: Try calling ArrayAdapter.notifyDataSetChanged(). This tells the ListView that the underlying data has changed and it should invalidate. A: at the end in the method of onClick() try calling adapter.notifyDataSetChanged(); This refreshes all the views that are using the adapter to set values to the view. A: values = new ArrayList<String>(); values is null. Change: dbHelper = new DBHelper(this); lvMain = (ListView) findViewById(R.id.lvMain); values = new ArrayList<String>(); } public void onButtonClick(View v) { ContentValues cv = new ContentValues(); String name = et.getText().toString(); SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (v.getId()) { case R.id.btnAdd: cv.put("name", name); long rowID = db.insert("mytable", null, cv); break; case R.id.btnRead: c = db.query("mytable", null, null, null, null, null, null); if (c.moveToFirst()) { idColIndex = c.getColumnIndex("id"); nameColIndex = c.getColumnIndex("name"); do { c.getInt(idColIndex); names = c.getString(nameColIndex); values.add(names); } while (c.moveToNext()); } else { c.close(); } break; case R.id.btnClear: int clearCount = db.delete("mytable", null, null); break; case R.id.btnShow: break; } adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values); lvMain.setAdapter(adapter); dbHelper.close(); adapter.notifyDataSetChanged(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/12845039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stripe token - why isn't data-amount included in the token I've been playing with stripe recently and while i fully understand that the token hides the clients credit card details from the server. This tutorial suggests that the server should not rely on the data-amount since it can be changed by the client Don’t Rely on the Form’s Price A frequent mistake stems from using form data to contain the price of the product being purchased, possibly via a hidden input. Because a user can easily edit this input’s value, it’s unwise to depend on it. Always fetch the price of the product from the server-side. Never rely on the form to tell you. A simple database query is the preferred option. Can someone explain to be why stripe does not include the data-amount value as a parameter in the token generation? Is there not a potential for a server side code to change the agreed price and overcharge the client. A: The token is a placeholder of a pending charge, it does not know how much you are going to charge yet. Once you are ready to charge the card an api request will be sent to Stripe along with the token. The concern about the amount deals with relying on POST data from a form that can be manipulated by the customer. A: Its up to you to set the charge amount. For example a hotel could authorize $100 to spend the night but then at check out discover that you used the minibar and then charge $150. Or the auto calculated shipping is off so when you actually purchase the shipping its $5 less and you decide to charge $5 less than your auth. What you should be doing is calculating the amount to charge the customer, save it via a shopping cart like function in your DB (or serverside somehow) sending the checkout form to the customer then using the previously calculated amount run the auth then the charge. Form data can easily be changed by the end user. Just open the page and right click (in chrome) and click inspect element. You can then arbitrarily change form data. So if you were using that, the user could set the price to $.01 for your $1,000.00 product. The propose of tokenization in the PCI world is to keep sensitive data off your servers. Otherwise you would collect the PCI data yourself then send the amount off to the processor along with the PCI data. By not ever having the sensitive data touch your systems you save a ton of money and headache in PCI compliance. See this 115 page document: https://www.pcisecuritystandards.org/documents/PCI_DSS_v3-1.pdf Hope that helps, Please comment and I'll try to help further if it doesn't.
{ "language": "en", "url": "https://stackoverflow.com/questions/31478840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pass the data between pages in ionic 5 I want to pass some data between the pages in ionic version 5. Is there any possible way to do this? I am using ionic version '5.4.16' and angular version '10.0.8'. A: Page 1 constructor(public nav: NavController){} pushToNextScreenWithParams(pageUrl: any, params: any) { this.nav.navigateForward(pageUrl, { state: params }); } Page 2 constructor(public router: Router){ if (router.getCurrentNavigation().extras.state) { const pageName = this.router.getCurrentNavigation().extras.state; console.log(pageName) } } A: so after looking at a variety of sources, if your only passing data forward and you don't care about passing data back, here's an example: // from export class SomePage implements OnInit { constructor (private nav: NavController) {} private showDetail (_event, item) { this.nav.navigateForward(`url/${item.uid}`, { state: { item } }) } } // to export class SomeOtherPage implements OnInit { item: any constructor (private route: ActivatedRoute, private router: Router) { this.route.queryParams.subscribe(_p => { const navParams = this.router.getCurrentNavigation().extras.state if (navParams) this.item = navParams.item }) } } Hope that's clear. A: I found a solution for passing the parameters between the pages using the 'ActivatedRoute' and the 'Router' in "@angular/router". In here we can use the url to pass the parameters. Following youtube video will help to solve this problem. https://youtu.be/C6LmKCSU8eM A: The easiest way is pass it to a service in the first page, and pick it from same service on the next page. First Create a service and then declare a public variable inside your service like this public result: any; then go down and declare a function to always change this variable anytime changeData(result){ this.result = result; } Second go to the page where you want to pass the data and pass it like below, using the name of the service and the public variable. this.util.changeData(data); note: data here is the data you want to pass Thirdly you can pick the data from anywhere on your app, example i am accessing the data from my view like below {{this.util.result}}
{ "language": "en", "url": "https://stackoverflow.com/questions/65607106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL Query COUNT Output I am trying to get information from another SELECT inside of the same query, however I am not too sure how to get the required field I am after. SELECT t.`id`, t.`title`, t.`author`, t.`content`, ctitle, cid, comments FROM `tutorials` AS `t`, ( SELECT tc.`id` as `cid`, tc.`title` as `ctitle` FROM `tutorial_categories` AS `tc` WHERE `title` LIKE '%category title' ) AS `c`, ( SELECT COUNT(com.`id`) as `comments` FROM `tutorial_comments` AS `com` WHERE `tutorial_id` = c.cid ) as `comments` WHERE t.`category` = c.`cid` AND t.`status` = '1' ORDER BY `id` ASC I am trying to fetch the id from tutorial_categories and use it in tutorial_comments. All I am trying to do as the final output is get the count of how many comments are listed for each tutorial. Cheers, Jacob A: Jacob You need add a group by clause like this select t.id, t.tilte, t.author, t.content, count(com.id) as comments from tutorials as t join tutotials_categories as cat on t.category = cat.id join tutorials_comments as com on com.tutorial_id = t.id where cat.title like'%category title' and t.status = 1 group by com.id order by t.id asc I used the ansi join form A: This should clean up your query: SELECT t.id, t.title, t.author, t.content, c.ctitle, c.cid, com.comments FROM tutorials AS t LEFT JOIN ( SELECT tutorial_id, COUNT(com.id) as comments FROM tutorial_comments AS com GROUP BY 1 ) AS com ON com.tutorial_id = t.category LEFT JOIN ( SELECT tc.id as cid, tc.title as ctitle FROM tutorial_categories AS tc WHERE title LIKE '%category title' ) AS c ON t.category = c.cid WHERE t.status = '1' ORDER BY t.id The LEFT JOIN prevents that tutorials disappear that don't find a match. I made that explicit JOINs with JOIN conditions, that is easier to understand and also the proper way. Your cardinal problem was that you had the join condition for the counted comments inside the brackets instead of outside, which cannot work that way. A: Can you try this one: SELECT t.`id`, t.`title`, t.`author`, t.`content`, c.title, c.cid, ct.comments FROM `tutorials` AS `t` LEFT OUTER JOIN ( SELECT tc.`id` as `cid`, tc.`title` as `ctitle` FROM `tutorial_categories` AS `tc` WHERE `title` LIKE '%category title' ) AS `c` ON t.`category` = c.`cid` LEFT OUTER JOIN ( SELECT COUNT(com.`id`) as `comments` FROM `tutorial_comments` AS `com` group by com.`id` ) as `ct` on ct.`tutorial_id` = c.cid WHERE t.`status` = '1' ORDER BY `id` ASC
{ "language": "en", "url": "https://stackoverflow.com/questions/8425578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala program cannot find JDBC driver for Sql Server My classpath begins: C:\Tools\Microsoft JDBC Driver 4.0 for SQL Server\JDBC-Sql\sqljdbc_40\enu\sqljdbc.jar; My test program is: import java.sql.DriverManager import java.sql.Connection object TestJDBCSqlConnect { def main(args: Array[String]) { val driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; try { // make the connection Class.forName(driver) } catch { case e => e.printStackTrace } } and when I run it via scala -cp . TestJDBCSqlConnect scala returns: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver Is there some naming convention I am violating? I am on JRE Version 8.
{ "language": "en", "url": "https://stackoverflow.com/questions/37466385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems while getting custom dimensions via API from Google Analytics Goog day. When I try to get custom dimensions via API, I got error Exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/customDimensions: (400) Cannot query by ~all for id webPropertyId' My code $service_account_name = '<Service Email>@developer.gserviceaccount.com'; $key_file_location = '<keyName>.p12'; $key = file_get_contents($key_file_location); $cred = new Google_Auth_AssertionCredentials( $service_account_name, array(Google_Service_Analytics::ANALYTICS), $key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer', '<My email>' ); $client->getAuth()->setAssertionCredentials($cred); $service = new Google_Service_Analytics($client); $result = $service->management_customDimensions->listManagementCustomDimensions('~all', '~all'); print_r($result); Similar code for getting goals works correctly $service_account_name = '<Service Email>@developer.gserviceaccount.com'; $key_file_location = '<keyName>.p12'; $key = file_get_contents($key_file_location); $cred = new Google_Auth_AssertionCredentials( $service_account_name, array(Google_Service_Analytics::ANALYTICS), $key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer', '<My email>' ); $client->getAuth()->setAssertionCredentials($cred); $service = new Google_Service_Analytics($client); $result = $service->management_profiles->listManagementProfiles('~all', '~all'); print_r($result); Both methods listManagementProfiles and listManagementProfiles get parametrs $accountId and $webPropertyId . Could someone help, why I get error, while getting custom dimensions via API? A: Looking at the documentation "~all" is specifically mentioned as valid parameter value for listManagementProfiles: Account ID for the view (profiles) to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access. but not for listManagementCustomDimensions, here is says simply Account ID for the custom dimensions to retrieve. (same for property id). So your problem is quite literally what the error message says, you cannot use "~all" when querying custom dimensions. So it seems that to list all custom dimensions you'd have to iterate through a list of property ids (as returned by the properties/list method) instead of using "~all".
{ "language": "en", "url": "https://stackoverflow.com/questions/34523435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use variable inside this constant declared in angular services I have this constant webroot declared inside my angularjs v1 services. angular.module('myApp.services', []) .value('version', '0.1') .constant('configuration', { webroot: 'http://127.0.0.1:10840' } ]) I have a variable port for port number used by webroot. I want to use port to declare the constant webroot in a way that looks like something below; let port = 10840; angular.module('myApp.services', []) .value('version', '0.1') .constant('configuration', { webroot: 'http://127.0.0.1:' + port } ]) How can this be done in angular v1? A: yes you can do that. Here is a sample demo let port = 10840; angular.module("app",[]) .value('version', '0.1') .constant('configuration', { webroot: 'http://127.0.0.1:' + port } ) .controller("ctrl",function($scope,configuration){ console.log(configuration.webroot) }) <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/42522357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R plumber Installation SSH key Error on creating droplet in Digital Ocean I am trying to deploy R plumber API on digital ocean (DO). I am using windows 10 and following these steps to create droplets from RStudio. For SSH keys, I am using PuTTY key generator, followed step mentioned here and saved private key in c:/user/myname/.ssh folder and uploaded public key as copy and paste into the Add SSH section as describe here. The problem I am facing is an “Error please install ssh“ when I am creating a droplet from RStudio. mydrop <- plumber::do_provision() I can see the droplet is created on DO control panel, however, when I am copying and pasting the IP address in the browser window to see the results I get “problem loading page” / ” Unable to connect “. If I am trying to install any other R package, I get the same error, Error Image : or if I deploy using this code plumber::do_deploy_api() I get the same. Any help will be highly appreciated. Thanks A: Maybe you already have figured this out. if not, please try installing the ssh package. install.packages("ssh")
{ "language": "en", "url": "https://stackoverflow.com/questions/60481403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JS URL regex, allow only urls and empty string I have the following regext: var regex = /^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g; function test() { alert(regex.test(document.getElementById("myinput").value)); } I want to allow url or empty string. regex solution please How do I allow empty in this case? https://jsfiddle.net/6kptovwc/2/ Thanks A: Just add OR(||) condition function test() { const elm = document.getElementById("myinput") alert(elm.value === '' || regex.test(elm.value)); } A: ^$|pattern var regex = /^$|(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g; A: Add an alternation with empty string (I've simplified a bit your regex): ^((?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9@:%_\+.~#?&\/=]*|)$ or ^((?:https?:\/\/)?(?:www\.)?[-\w@:%.+~#=]{2,256}\.[a-z]{2,6}\b[-\w@:%+.~#?&\/=]*|)$ Demo & explanation
{ "language": "en", "url": "https://stackoverflow.com/questions/60814497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Algorithm to code URL is there some algorithm in C# to encode url with symbols that can correct display in web-browser? something like Base64. A: The Standard (RFC 3986 aka STD 66) lays it out for you. In particular, §2 and 2.1: 2. Characters The URI syntax provides a method of encoding data, presumably for the sake of identifying a resource, as a sequence of characters. The URI characters are, in turn, frequently encoded as octets for transport or presentation. This specification does not mandate any particular character encoding for mapping between URI characters and the octets used to store or transmit those characters. When a URI appears in a protocol element, the character encoding is defined by that protocol; without such a definition, a URI is assumed to be in the same character encoding as the surrounding text. The ABNF notation defines its terminal values to be non-negative integers (codepoints) based on the US-ASCII coded character set [ASCII]. Because a URI is a sequence of characters, we must invert that relation in order to understand the URI syntax. Therefore, the integer values used by the ABNF must be mapped back to their corresponding characters via US-ASCII in order to complete the syntax rules. A URI is composed from a limited set of characters consisting of digits, letters, and a few graphic symbols. A reserved subset of those characters may be used to delimit syntax components within a URI while the remaining characters, including both the unreserved set and those reserved characters not acting as delimiters, define each component's identifying data. 2.1. Percent-Encoding A percent-encoding mechanism is used to represent a data octet in a component when that octet's corresponding character is outside the allowed set or is being used as a delimiter of, or within, the component. A percent-encoded octet is encoded as a character triplet, consisting of the percent character "%" followed by the two hexadecimal digits representing that octet's numeric value. For example, "%20" is the percent-encoding for the binary octet "00100000" (ABNF: %x20), which in US-ASCII corresponds to the space character (SP). Section 2.4 describes when percent-encoding and decoding is applied. pct-encoded = "%" HEXDIG HEXDIG The uppercase hexadecimal digits 'A' through 'F' are equivalent to the lowercase digits 'a' through 'f', respectively. If two URIs differ only in the case of hexadecimal digits used in percent-encoded octets, they are equivalent. For consistency, URI producers and normalizers should use uppercase hexadecimal digits for all percent- encodings. In general, the only characters that may freely be represented in a URL without being percent-encoded are * *The unreserved characters. These are the US-ASCII (7-bit) characters * *A-Z *a-z *0-9 *-._~ *The reserved characters ... when in use as within their role in the grammar of a URL and its scheme. These reserved characters are: * *:/?#[]@!$&'()*+,;= Any other characters, per the standard must be properly percent-encoded. Further note that a URL may only contains characters drawn from the US-ASCII character set (0x00-0x7F): If your URL contains characters outside that range of codepoints, those characters will need to be suitably encoded for representation in US-ASCII (e.g., via HTML/XML entity references). Further, you application is responsible for interpreting such.
{ "language": "en", "url": "https://stackoverflow.com/questions/17493471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Creating Conditional Script in PHP / Wordpress I'm still pretty new to PHP, and I'm having trouble getting this to work. What I want to do, is make the slide linked (if link is available). Otherwise, print the post thumbnail without the Here's my code so far: <?php // START SLIDER ?> <div class="slider"> <ul class="rslides"> <?php $args = array( 'posts_per_page' => 0, 'post_type' => 'slide'); $alert = new WP_Query( $args ); ?> <?php if( $alert->have_posts() ) { while( $alert->have_posts() ) { $alert->the_post(); ?> <li><a href="<?php echo get_post_meta($post->ID, "_location", true); ?>" title="More Info"><?php the_post_thumbnail('full'); ?><div class="caption"><p class="captiontitle"><?php the_title(); ?></p><p class="caption"><?php the_content(); ?></p></div></a></li> <?php } } ?> </ul> </div> <?php wp_reset_query(); ?> <?php // END SLIDER ?> I've done this before using the WP Custom fields, but I'm not sure how to apply it to my custom post type (called slider). Here's what I did for my Custom Field script: <?php $slider_url = get_post_meta($post->ID, 'Slider_URL', true); if ($slider_url) { ?> LINKED SLIDE HERE <?php } else { ?> UNLINKED SLIDE HERE <?php } ?> <?php endwhile; ?> <?php endif; // have_posts() ?> Here's what I tried (when combining the two), but there's an error somewhere: <?php // START SLIDER ?> <div class="slider"> <ul class="rslides"> <?php $args = array( 'posts_per_page' => 0, 'post_type' => 'slide'); $alert = new WP_Query( $args ); ?> <?php if( $alert->have_posts() ) { while( $alert->have_posts() ) { $alert->the_post(); ?> <?php $slide_url = get_post_meta($post->ID, 'Slide_URL', true); if ($slide_url) { ?> <li><a href="<?php echo get_post_meta($post->ID, "_location", true); ?>" title="More Info"><?php the_post_thumbnail('full'); ?><div class="caption"><p class="captiontitle"><?php the_title(); ?></p><p class="caption"><?php the_content(); ?></p></div></a></li> <?php } else { ?> <li><?php the_post_thumbnail('full'); ?><div class="caption"><p class="captiontitle"><?php the_title(); ?></p><p class="caption"><?php the_content(); ?></p></div></li> <?php } } ?> <?php endwhile; ?> <?php endif; // have_posts() ?> </ul> </div> <?php wp_reset_query(); ?> <?php // END SLIDER ?> A: If I'm correct in thinking, you just want to check if the link is there, before outputting, otherwise, just show the image. Try the following: <?php // START SLIDER ?> <div class="slider"> <ul class="rslides"> <?php $args = array( 'posts_per_page' => 0, 'post_type' => 'slide'); $alert = new WP_Query( $args ); ?> <?php if( $alert->have_posts() ) { while( $alert->have_posts() ) { $alert->the_post(); ?> <!-- Get a link --> <?php $theLink = get_post_meta($post->ID, "_location", true); ?> <li> <!-- Check for a link --> <?php if($theLink != ''): ?> <a href="<?php echo $theLink; ?>" title="More Info"> <?php endif; ?> <?php the_post_thumbnail('full'); ?> <div class="caption"> <p class="captiontitle"> <?php the_title(); ?> </p> <p class="caption"> <?php the_content(); ?> </p> </div> <!-- Close the link --> <?php if($theLink != ''): ?> </a> <?php endif; ?> </li> <?php } } ?> </ul> </div> <?php wp_reset_query(); ?> <?php // END SLIDER ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/21999882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display image in column of grid based on value in column's renderer? I have a grid panel like: Ext.define('Demo.view.main.content.source.Ex', { extend: 'Ext.grid.Panel', requires: [ 'Demo.store.main.content.source.Ex', 'Demo.view.main.content.source.ExController', ], xtype: 'app-main-content-ex', title: 'Example', store: 'Demo.store.main.content.source.Ex', controller:'main-content-source-ex', //multiSelect: false, columnLines: true, initComponent: function() { var store = Ext.create('Demo.store.main.content.source.Ex', { storeId: 'app-main-content-source-exstore' }); Ext.apply(this, { store: store }); this.columns= [ { text : 'Driver Name', flex : 3, sortable : false, dataIndex: 'name' }, { xtype: 'gridcolumn', getEditor: function(record) { console.log(record.get('state')); var value; if (record.get('state') == 'free') { value = 'xf09c@FontAwesome' } else { value = 'xf023@FontAwesome' } return Ext.create('Ext.grid.CellEditor', { field:{ xtype: 'image', glyph: value } }); }, text : 'State', flex : 1, dataIndex: 'state' }] this.callParent(); }, listeners:{ afterRender: 'setUpInfo' } }); I am loading the store of that in grid afterrender event. I want to set the image in the State column based on the value of state(free/busy). Its not working. How should I do it? A: You can use a renderer to augment the displayed value of the cell. columns: [{ xtype: 'gridcolumn', dataIndex: 'name', text: 'Driver Name', flex: 1, editor: { xtype: 'textfield' } }, { xtype: 'gridcolumn', renderer: function(value) { if (value == 'free') { return 'xf09c@FontAwesome' } else { return 'xf023@FontAwesome' } }, getEditor: function(record) { var value; if (record.get('state') == 'free') { value = 'xf09c@FontAwesome' } else { value = 'xf023@FontAwesome' } return Ext.create('Ext.grid.CellEditor', { field: { xtype: 'image', glyph: value } }); }, text: 'State', flex: 1, dataIndex: 'state' }] Docs: - http://docs.sencha.com/extjs/5.1/5.1.0-apidocs/#!/api/Ext.grid.column.Column-cfg-renderer
{ "language": "en", "url": "https://stackoverflow.com/questions/28826867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use a script with GNU license I have a question about softwares and webapps license. I get a php script, it published with "GNU GENERAL PUBLIC LICENSE". Can I use this script in my webapp, and when my app is complete (I write my code and design pages), can I sell this app?? (I won't change license of that script, just the license of downloaded script!) Thanks... A: As long as the script doesn't put part of itself into your code when you use it, you should be OK. IOW: If it is just some kind of tool you use to help build your real code (which is totally separate and entirely your own work), then you can liscense that stuff however you want. What you can't do is relicense somebody else's work without their permission. If the script injects part of itself into your code, that would include that injected part. Also, if you link anything GPLed (object file, link library, etc), then your license needs to be GPL-compatible (and the linked part has to stay GPL). A: My understanding of the GPL is that if your code relies on the script, then you have to release your code under the GPL as well. If your code interfaces with the script, but it isn't a neccessary component (i.e. the script is or is part of a module or plugin) then only the module/plugin needs to be released under the GPL. IANAL... A: First, you need to determine to what extent your app depends on the GPL script. If your app doesn't work without the script, then I think it's safe to say that it depends on it on a fundamental way. If this is the case, then your code must also be released under the GPL license - please notice that this doesn't imply that you can not sell your app, you are free to do so, but now the code of your app must be available for any one to use, see, modify, and distribute the modifications. If you're not OK with the last part, maybe you should look for other script alternatives, licensed under a more permisible model. For instance, any of the following licenses would be fine: Apache, MIT, even LGPL
{ "language": "en", "url": "https://stackoverflow.com/questions/4555890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET and WordPress I have 2 websites (www.example.co.uk and www.example.net) * *www.example.co.uk is a WordPress brochure website (front end) *www.example.net is built in asp.net and is hosted on Microsoft's AZURE and allows people to manage their data etc. (back end) People are getting confused when they visit www.example.co.uk and then end up at www.example.net to manage their account. Would it be possible to host them both under the same domain (still keeping them separate) so people don't get confused? Thanks A: It can by hosted on azure, but domain will be www.example.net/wordpresssite or wordpresssite.example.net A: Here are the detailed steps for you to configure your custom domain, you could refer to it. I assume that your domain is example.co.uk and the domain of your back-end hosted on Azure is wordpresssite.azurewebsites.net by default. Firstly, you need to log in to your domain registrar and add a CNAME record as follows: |---------FQDN EXAMPLE--------|--CNAME HOST---|------------CNAME VALUE----------| | wordpresssite.example.co.uk | wordpresssite | wordpresssite.azurewebsites.net | Then, you need to log in to the Azure Portal, select your web app, click Custom domains > Add hostname to enable the custom domain name for your app. After you finish the configuration steps,it would take some period for the changes to propagate, depending on your DNS provider. And you could verify the DNS status by using digwebinterface.com. For more details, you could follow web-sites-custom-domain-name.
{ "language": "en", "url": "https://stackoverflow.com/questions/40377358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use a bookmark with javascript to alter a website css I'm not too good with colours and on a moodle course I'm tutoring I have a really difficult time spotting the difference in unread and read posts. The unread posts are highlighted but the colour is too similar to the background for me. Previously I've used a javascript bookmark in firefox to alter a website (select all for Amazon's AWS S3 which worked really well). I'm trying to rework the AWS bookmark javascript to change the CSS of moodle page. So far I have: javascript:(function () { document.domain = 'whatever.domain'; var unread = document.querySelectorAll(".unread"); for (var i = 0; i < unread.length; i++) { unread[i].style.background-color="blue"; }; })(); Using inspector to view the CSS the Span element CSS looks like this: #page-mod-forum-view .unread, .forumpost.unread .row.header, .path-course-view .unread, span.unread { background-color: #FFD; } A: Note that the property names are in camel-case and not kebab-case while setting the style using elt.style. (i.e. elt.style.fontSize, not elt.style.font-size) https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style So there should be backgroundColor instead of background-color in your bookmarklet JavaScript code.
{ "language": "en", "url": "https://stackoverflow.com/questions/43913971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compiling tensorflow/models/rnn/translate:translate with local numpy I am trying to run the neural machine translation demo on a gpu. The GPU example in tensorflow's getting started page works. $ bazel build -c opt --config=cuda //tensorflow/cc:tutorials_example_trainer $ bazel-bin/tensorflow/cc/tutorials_example_trainer --use_gpu produces the expected output. But when I try to compile the translation demo: bazel build -c opt --config=cuda --verbose_failures //tensorflow/models/rnn/translate:translate it fails: ... ____Loading package: @jpeg_archive// ____Loading package: @png_archive// ____Loading package: @re2// ____Loading complete. Analyzing... ____Found 1 target... ____Building... ____[0 / 2] BazelWorkspaceStatusAction stable-status.txt ____[25 / 324] Executing genrule @six_archive//:copy_six ____[237 / 1,193] Executing genrule @png_archive//:configure [for host] ____[242 / 1,193] Executing genrule //third_party/gpus/cuda:cuda_check ____[361 / 1,193] Executing genrule //google/protobuf:protobuf_python_internal_copied_filegroup_genrule ____From Executing genrule @png_archive//:configure: ____From Executing genrule @png_archive//:configure [for host]: ____From Executing genrule @jpeg_archive//:configure: ____From Executing genrule @jpeg_archive//:configure [for host]: ____[677 / 1,193] Compiling tensorflow/core/kernels/argmax_op.cc ____From Compiling tensorflow/python/client/tf_session_helper.cc: tensorflow/python/client/tf_session_helper.cc: In function 'tensorflow::Status tensorflow::{anonymous}::TF_StringTensor_GetPtrAndLen(const TF_Tensor*, tensorflow::int64, tensorflow::int64, const char**, tensorflow::uint64*)': tensorflow/python/client/tf_session_helper.cc:248:14: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] if (offset >= (limit - data_start) || !p || (*len > (limit - p))) { ^ tensorflow/python/client/tf_session_helper.cc:248:53: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] if (offset >= (limit - data_start) || !p || (*len > (limit - p))) { ^ tensorflow/python/client/tf_session_helper.cc: In function 'tensorflow::Status tensorflow::{anonymous}::TF_Tensor_to_PyObject(TF_Tensor*, PyObject**)': tensorflow/python/client/tf_session_helper.cc:311:32: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] if (PyArray_NBYTES(py_array) != TF_TensorByteSize(tensor)) { ^ tensorflow/python/client/tf_session_helper.cc: In function 'void tensorflow::TF_Run_wrapper(TF_Session*, const FeedVector&, const NameVector&, const NameVector&, tensorflow::Status*, tensorflow::PyObjectVector*)': tensorflow/python/client/tf_session_helper.cc:416:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] for (int i = 0; i < inputs.size(); ++i) { ^ tensorflow/python/client/tf_session_helper.cc:430:41: error: 'PyArray_SHAPE' was not declared in this scope dims.push_back(PyArray_SHAPE(array)[i]); ^ tensorflow/python/client/tf_session_helper.cc:513:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] for (int i = 0; i < output_names.size(); ++i) { ^ ERROR: /home/mifs/fs439/bin/tensorflow/tensorflow/python/BUILD:710:1: C++ compilation of rule '//tensorflow/python:tf_session_helper' failed: crosstool_wrapper_driver_is_not_gcc failed: error executing command ... Probably because of tensorflow/python/client/tf_session_helper.cc:430:41: error: 'PyArray_SHAPE' was not declared in this scope dims.push_back(PyArray_SHAPE(array)[i]); This is probably because the global numpy installation is old and does not know PyArray_SHAPE. I don't have admin rights to update it globally, but I have installed an updated numpy in $HOME/.local/lib/python2.7/site-packages/ using pip install --user. If I add the path to the corresponding rule in tensorflow/tensorflow/python/BUILD like this: tf_cuda_library( name = "tf_session_helper", srcs = ["client/tf_session_helper.cc"], hdrs = ["client/tf_session_helper.h"], copts = numpy_macosx_include_dir + ["-I<path-to-local-numpy>"] + ["-I/usr/include/python2.7"], deps = [ ":construction_fails_op", ":test_kernel_label_op_kernel", "//tensorflow/core", "//tensorflow/core:direct_session", "//tensorflow/core:kernels", "//tensorflow/core:lib", "//tensorflow/core:protos_cc", ], ) it complains: ERROR: <tensorflow-dir>/tensorflow/python/BUILD:710:1: in cc_library rule //tensorflow/python:tf_session_helper: The include path '/home/mifs/fs439/.local/lib/python2.7/site-packages/numpy/core/include' references a path outside of the execution root.. ERROR: <tensorflow-dir>/tensorflow/python/BUILD:710:1: in cc_library rule //tensorflow/python:tf_session_helper: The include path '/home/mifs/fs439/.local/lib/python2.7/site-packages/numpy/core/include' references a path outside of the execution root.. ERROR: Analysis of target '//tensorflow/models/rnn/translate:translate' failed; build aborted. ____Elapsed time: 18.559s How can I tell tensorflow to use the local numpy version? (gcc 4.9.3, bleeding edge tensorflow + bazel, local numpy 1.10.1, ubuntu 12.04) EDIT: When I follow the instructions from here as suggested by syncd I get ERROR: /home/mifs/fs439/bin/tensorflow/tensorflow/python/BUILD:710:1: undeclared inclusion(s) in rule '//tensorflow/python:tf_session_helper': this rule is missing dependency declarations for the following files included by 'tensorflow/python/client/tf_session_helper.cc': 'third_party/numpy/arrayobject.h' 'third_party/numpy/ndarrayobject.h' 'third_party/numpy/ndarraytypes.h' 'third_party/numpy/npy_common.h' 'third_party/numpy/numpyconfig.h' 'third_party/numpy/_numpyconfig.h' 'third_party/numpy/npy_endian.h' 'third_party/numpy/npy_cpu.h' 'third_party/numpy/utils.h' 'third_party/numpy/_neighborhood_iterator_imp.h' 'third_party/numpy/npy_1_7_deprecated_api.h' 'third_party/numpy/old_defines.h' 'third_party/numpy/__multiarray_api.h' 'third_party/numpy/npy_interrupt.h'. Target //tensorflow/models/rnn/translate:translate failed to build Various attempts to add them to hdrs in the tf_cuda_library rule do not help: hdrs = ["client/tf_session_helper.h"] + glob([ "**/arrayobject.h", "numpy/*.h", "**/numpy/*.h", ]), A: One possible solution is presented here. Create a link to $HOME/.local/lib/python2.7/site-packages/numpy/core/include/numpy in the tensorflow/third_party dir and edit -Ithird_party to tensorflow/python/build and tensorflow/tensorflow.bzl A: Here is a very nasty workaround if you get the "undeclared inclusion(s) in rule" errors: 1.) Pick a path in your gccs build-in include directories (i.e. one of the cxx_builtin_include_directory paths in bazel-workspace/tools/cpp/CROSSTOOL - should be equal to those given by g++ -v bla.cc) 2.) Lets say you picked directory dir .Create a directory called "bla" within dir 3.) In dir/bla, create a symlink to your numpy include directory (ln -s .../core/include/numpy .) 4.) Add "dir/bla" to tensorflow/python/BUILD and tensorflow/tensorflow.bzl as described in the link. 5.) Feel guilty but happy that it compiles
{ "language": "en", "url": "https://stackoverflow.com/questions/33790135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perform OpenURL action using new AdaptiveCards.Renderer.UWP package Before new nuged package with braking changes arrived, I was able to subscribe to actions and defined what app should do for OpenURL action: renderer.Action += Renderer_Action; .. private void Renderer_Action(AdaptiveCardRenderer sender, AdaptiveActionEventArgs args) { var openUrlAction = args.Action as AdaptiveOpenUrlAction; if (openUrlAction != null) {...} } I was not able to find any Events at new AdaptiveCardRenderer, how should I listen and react to buttons clicks in this case? A: Sorry about the breaking changes in the latest beta. The new API allows more flexibility by associating the Action event to the rendered card. When you call RenderAdaptiveCard(...) you get a RenderedAdaptiveCard object back. This object has the OnAction event
{ "language": "en", "url": "https://stackoverflow.com/questions/46572339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ignore Case sql query I am trying to basically ignore the case sensitivity for my db2 sql select * query, so that I can populate the products to my catalogue page. Ex. If I type in my search bar 'squeege', I want the item 'Squeege' to populate, even if there is a difference in Upper/lower case. What is the best way to do this, based on the code I have below? var searchProduct = "select * from LISTOFPRODUCTS where ITEM LIKE '%" + searchValue + "%'" Thanks in advance for the help :) A: I think this could work: var searchProduct = "select * from LISTOFPRODUCTS where UPPER(ITEM) LIKE UPPER('%" + searchValue + "%'") Also the same with LOWER() Note that the trick is parse both values to UPPER() or LOWER() to match them. A: You can use the function LOWER(). For example: var searchProduct = "select * from LISTOFPRODUCTS where LOWER(ITEM) LIKE '%" + searchValue + "%'" A: You can also consider using REGEXP_LIKE which has a case-insensitive option i
{ "language": "en", "url": "https://stackoverflow.com/questions/64813688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VS 2017 - Rebuild until it works? Whenever I open a new project (usually, it's branched from TFS) and sync it locally, the first build never succeeds... i have to keep pressing rebuild, until it works... I assume this is some kind of bug related to my solution, because other smaller solutions work fine. Details: * *It's always complaining about missing DLL's *There's no exact number of rebuilds, it's around 3 or 4, but i just "fixed" a project doing about 10... *Using VS 2017 enterprise, fully updated A: Sounds like you don't have your dependencies specified properly in your solution. When your build fails look to see what project it is that fails and what project it couldn't find. Then add the dependency.
{ "language": "en", "url": "https://stackoverflow.com/questions/42867854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i make my caroutine run in every x seconds I created a caroutine, and i want it to run in every x seconds. i tried using while loop but it didn't worked for this caroutine. can anybody please help ? thanks. IEnumerator StartFire() { { Firing = true; animator.SetBool("isFiring", true); yield return new WaitForSeconds(2); Firing = false; animator.SetBool("isFiring", false); } } A: I think you would be better off using InvokeRepeating(string methodName, float time, float repeatRate). You only need to call it once and it will repeat. Example: void Start() { InvokeRepeating("myTask", 1.5f, 1.5f); } void myTask() { // Execute repetitive task. } If you want to stop it at any point you simply have to call: CancelInvoke(string methodName);. Example: void Update() { if (Input.GetKeyDown(KeyCode.S)) CancelInvoke(); } This would put an end to the repetitive task.
{ "language": "en", "url": "https://stackoverflow.com/questions/70319713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where can I place external JAR references of a WAR file other than WEB-INF/lib or WL_HOME/server/lib I have 120 Java Projects exported as JAR files in D:/FC/APP_LIB folder. Now I developed a Web Service (JAX-WS), to be deployed on Weblogic 12c (12.1.2), which refers to those JAR files. I don't think it will be a good practice to add all the JARs into the WEB-INF/lib of the WAR file (and it will continue in all subsequent WARs I develop). Also, I want to avoid those JARs to be kept in WL_HOME/server/lib folder (default reference) as anytime a change is made in any of the Java Projects will require a deployment in WL_HOME/server/lib. Is there any way I can give an external JAR(s) reference in WAR or Weblogic without embedding them into WAR? A: You can write (and use) a separate class loader to load classes from anywhere. That being said I suggest putting the jars into each .war file. Disk space and RAM should not be the problem. * *If a central .jar is modified (and a bug is introduced), all web apps will fail. *You probably test your web app against a specific version of your libraries. If you update a central .jar, you have to re-run the tests for each application. Generally speaking you will probably run into problems because of dependencies. A: May you need Create Shared Java EE Library or Optional Package. See more in Install a Java EE library and Understanding WebLogic Server Application Classloading. A: You can modify the script used to start Weblogic to include the external directory in the server's classpath. See %DOMAIN_HOME%\bin\setDomainEnv.sh (or .cmd if Windows).
{ "language": "en", "url": "https://stackoverflow.com/questions/18223571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to write asp.net to create a file in sharepoint? After giving up java script, I'm writing the asp.net to make a popup, and once the user finish wrting the content and title, it will make a .aspx file and upload to documentary library. But how can I do that? I googled but not many materials on that! Anyone can help?
{ "language": "en", "url": "https://stackoverflow.com/questions/11689909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Core Data Fetch GrandChild from Parent Thank you for your help in advance. I am able to fetch a child entity from a parent, as seen in the code below, but I can not figure out how to fetch the grandchild based on certain on child in a parent. How do I add on to or change my existing code to get values out of a grandchild based on the child attributes? NSMutableArray *createdMutable = [[NSMutableArray alloc]init]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"randomAttribute" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:2]; NSMutableArray *sortedResults = [[NSMutableArray alloc] initWithArray: [parentEntity.parentToChild allObjects]]; [sortedResults sortUsingDescriptors:sortDescriptors]; [sortedResults valueForKey:@"randomAttribute"]; NSString *addedCreatedMutable; for (int i = 0; [sortedResults count] > i; i++) { addedCreatedMutable = [[sortedResults valueForKey:@"randomAttribute"]objectAtIndex:i]; addedCreatedMutable = [addedCreatedMutable stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; if ([createdMutable containsObject:addedCreatedMutable]) { }else{ [createdMutable addObject:addedCreatedMutable]; } A: Can you list the objects and their relationship names? What you're asking is of course possible, but it's a bit hard to grok (for me) from what's above. A couple of suggestions without that; * *You can traverse the relationship from parent to children (not sure if child is a to-many or a to-one though) and again out to the grandchild *You can get funkier using a SUBQUERY() NSPredicate. Advantage is fetch speed, disadvantage is that it's a bit more complex (and sometimes can indicate that you're going about things in not the best way).
{ "language": "en", "url": "https://stackoverflow.com/questions/9719550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I pass an array through a Helm template? I'm using Helm v3. The issue is that I've a template which gets an input value from a values.yaml file. I've a parameter that looks as follows: {{ if .Values.school.students}} students: {{ .Values.school.students}} {{ end }} Now, the actual value of students looks something like this: students: ["student1", "student2", "student3"] I need students to be an array but currently it gets passed as a string. I read a few answers online where it was mentioned that we can use "--set" flag but I'm not clear. Does anyone know how to fix this? A: You can loop through .Values.school.students using range {{- if .Values.school.students }} students: -| {{- range .Values.school.students }} - {{ . | quote }} {{- end }} {{- end -}}
{ "language": "en", "url": "https://stackoverflow.com/questions/64911269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails and authlogic, Not able to solve dependencies This is my Gemfile: gem "rails", "~> 2.3.8" gem "rake", "0.9.2" gem 'mysql', '2.8.1' gem 'aasm', '2.1.5' gem "authlogic", "2.1.6" gem "acl9", "0.12.0" gem "formtastic", "1.2.5" But bundle install reports: Bundler could not find compatible versions for gem "activesupport": In Gemfile: rails (~> 2.3.8) ruby depends on activesupport (= 2.3.8) ruby authlogic (= 2.1.6) ruby depends on activesupport (1.0.0) UPDATE I've tried different combinations of gem versions. And finally found a row without the version specification... that I didn't saw between comments. So the code snippet above was already correct. A: Do you really need to use those versions? Why not simply replace gem "authlogic", "2.1.6" with gem "authlogic" and let the bundle solve version dependencies? Sometimes after doing so in the gemfile you get an error from the bundler and you have to run bundle update authlogic before the general bundle install
{ "language": "en", "url": "https://stackoverflow.com/questions/26526753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Testing fragment using FragmentScenario results in java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState I have tried to test my fragment using fragment scenario but I always get the below error @RunWith(AndroidJUnit4::class) class HomeFragmentTest { @Test fun fab() { val scenario = launchFragmentInContainer<HomeFragment>() } }. java.lang.RuntimeException: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at androidx.test.runner.MonitoringInstrumentation.runOnMainSync(MonitoringInstrumentation.java:441) at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:564) at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:300) at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282) at com.example.myapplication.ui.home.HomeFragmentTest.fab(HomeFragmentTest.kt:31) at java.lang.reflect.Method.invoke(Native Method) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:104) at org.junit.runners.Suite.runChild(Suite.java:128) at org.junit.runners.Suite.runChild(Suite.java:27) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at org.junit.runner.JUnitCore.run(JUnitCore.java:115) at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56) at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2209) Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at androidx.fragment.app.FragmentManager.checkStateLoss(FragmentManager.java:1691) at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1794) at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1814) at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:297) at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:317) at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:301) at androidx.test.core.app.ActivityScenario.lambda$onActivity$2$ActivityScenario(ActivityScenario.java:551) at androidx.test.core.app.ActivityScenario$$Lambda$4.run(Unknown Source:4) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:2227) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:237) at android.app.ActivityThread.main(ActivityThread.java:7811) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1076)
{ "language": "en", "url": "https://stackoverflow.com/questions/61544932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: flex 3 - canvas background visibility issue, how to place bg on top left corner update1 please read the updated para below update2 created a test app. figured out that the flex tries to place the bg in the center of the container (canvas). so the new question is "how to position bg image to the left top corner when the bg image is smaller than the canvas (parent). but still there is mystical puzzle unsolved which I am thinking is related to how flex places the child. please read update2 at bottom update3 workaround - not working I am trying to figure out to fix the issue where the background image of a canvas is not appearing. I have flex 3.5 app, I have set height and width to 648x1008 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="1008" height="648" in this I have a 3 child canvas components. all of them are added dynamically and positioned to 0,0, two canvas' height, width are set to 100%. width="100%" height="100%" my 3rd canvas comp is the main component which is quit larger (4096x4096). i have code to start and stop drag this canvas in mousedown and up handlers mouseDown="mouseDownHandler()" mouseUp="mouseUpHandler()" width="{GameConfig.FULL_GAME_SCREEN_WIDTH}" height="{GameConfig.FULL_GAME_SCREEN_HEIGHT}" backgroundImage="{GameResource.bg}" dimensions defined in variables in GameConfig.as //game screen dimensions public static const FULL_GAME_SCREEN_WIDTH:int = 4096; public static const FULL_GAME_SCREEN_HEIGHT:int = 4096; bg class defined in variable in GameResource.as [Embed(source="../../../../assets/images/bg.jpg")] public static const bg:Class; background image path is perfect, I have verified by adding a dummy image to the problem canvas and set the same source ({GameResource.bg}) Now the problem is that the background image is not at all appearing Other two canvas doesnt have any background color they just have few components (buttons and images) positioned in bottom and top which means the problem canvas is not hidden behind the other canvas. Most importantly the children inside the problem canvas are appearing I have created a dummy app which is working fine as excpeted <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" height="600" width="800" layout="absolute" horizontalScrollPolicy="off" verticalScrollPolicy="off"> <mx:Script> <![CDATA[ import com.fg.greenrev.config.GameResource; ]]> </mx:Script> <mx:Canvas id="bg" horizontalScrollPolicy="off" verticalScrollPolicy="off" height="1600" width="4096" backgroundColor="0xccbbdd" backgroundImage="{GameResource.bg}" mouseDown="{bg.startDrag(false,new Rectangle(-3296,-1000,3296,1000))}" mouseUp="{bg.stopDrag()}"> </mx:Canvas> </mx:Application> can some one please help me. Update1: I have just modified the code, I turned on scrolling policy of main application and I have removed the bgimage from problem canvas to its child canvas whos size is also same as problem canvas and now bg appears roughly at 2x (1400) of the app screen height and slightly to the right of the screen (around 200px). If move the bgimage to problem canvas it doesnt appear atall again. It seems like the problem with how/where flex adds the bgimage. I was assuming it adds at 0,0 but it looks like its not. Update2: I have tried created a dummy app simulating the scenario with dummy code. I narrowed down the issue by changing the FULL_GAME_SCREEN_HEIGHT to the actual size of the bg (1600). Earlier it was larger than the bg (more than 2.5x). Now the image is appearing properly. The issue seems to be with the flex trying to lay the image in the center of the canvas. I could replicate the issue so that you can try this in your environment and see what is happening Main App <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" height="600" width="800" layout="absolute" creationComplete="init()"> <!--horizontalScrollPolicy="off" verticalScrollPolicy="off"--> <mx:Script> <![CDATA[ import _dummy.test1; import _dummy.test2; import _dummy.test3; import com.fg.greenrev.config.GameResource; private function init():void{ var t1:test1 = new test1(); addChild(t1); t1.init(); var t2:test2 = new test2(); addChild(t2); var t3:test3 = new test3(); addChild(t3); } ]]> </mx:Script> </mx:Application> ** test1.mxml - Child component (the problem 1)* <mx:Script> <![CDATA[ import com.fg.greenrev.config.GameConfig; import com.fg.greenrev.config.GameResource; import mx.states.AddChild; public function init():void{ var c1:test1Child = new test1Child(); addChild(c1); } ]]> </mx:Script> <mx:Label x="10" y="10" text="Test1"/> </mx:Canvas> * test2.mxml - child2 (no problem) * <?xml version="1.0" encoding="utf-8"?> <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" horizontalScrollPolicy="off" verticalScrollPolicy="off" width="100%" height="100%" x="0" y="0"> <mx:Label x="96" y="0" text="Test2"/> </mx:Canvas> * test3.mxml - child3 (no problem) * <?xml version="1.0" encoding="utf-8"?> <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" horizontalScrollPolicy="off" verticalScrollPolicy="off" width="100%" height="100%" x="0" y="0"> </mx:Canvas> * test1Child.mxml - child of child1 (no problem, but moving the bg from test1.mxml to here isnt making any difference in this test app but making diff in my originial app) <?xml version="1.0" encoding="utf-8"?> <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" horizontalScrollPolicy="off" verticalScrollPolicy="off" width="{GameConfig.FULL_GAME_SCREEN_WIDTH}" height="{GameConfig.FULL_GAME_SCREEN_HEIGHT}" > <mx:Script> <![CDATA[ import com.fg.greenrev.config.GameConfig; ]]> </mx:Script> <mx:Label x="390" y="0" text="Test1Child"/> </mx:Canvas> As you can see test1 and test1Child are same size and larger (huge) than the main app child2 and child3 are 100% width and height replace FULL_GAME_SCREEN_WIDTH and FULL_GAME_SCREEN_HEIGHT with 4096. have a dummy image of 4096x1600 and run the app you will see the bg is laid some where in the center (you can see the image if you scroll the app. now change the FULL_GAME_SCREEN_HEIGHT to 1600 (size of the bg), bg is shown perfectly. now there are two questions q1) how to make the bg appear in the center of the parent when bg image is smaller than the container(parent/canvas) q2) its actually puzzle, surprisingly the bg image is appearing to almost to the right corner (at around 4000px) when it is placed in problem canvas (in my original app, test1.mxml in dummy) but appearing properly when i moved the bg to its child (test1Child in the test app) update 3: workaround not working I have added this as the first line in the problem canvas, bg is appearing and it is covering remaining children. I knew adding it at first lines makes it first child meaning index = 0 meaning always stays back side but surprisingly, its not just making its' children canvas invisible but also occluding the other controls which are inside the other canvas. I have also tried to dynamically add the image using addChildAt(img,0) and also forecefully made the index to 0 by setChildIndex(img,0) but no use. Sick and tired A: working workaround well i thought this woould work <mx:Image x="0" y="0" source="{GameResource.bg}" mouseEnabled="false"/> but for some reason it was occlding remaining controls and containers, despite it was added at the very first line (which makes ints displayindex = 0) then I addeed this code to add them dynamically var img:Image = new Image(); img.mouseEnabled = false; img.mouseChildren = false; img.source = GameResource.bg; addChildAt(img,0); working like charm. BLOODY FLEX VERY UNPREDICTABLE
{ "language": "en", "url": "https://stackoverflow.com/questions/8635039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove tmp directory files of an ios app? I'm working on an app that uses the iPhone camera and after making several tests I've realised that it is storing all the captured videos on the tmp directory of the app. The captures don`t disappear even if the phone is restarted. Is there any way to remove all these captures or is there any way to easily clean all cache and temp files? A: Yes. This method works well: + (void)clearTmpDirectory { NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL]; for (NSString *file in tmpDirectory) { [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL]; } } A: Try this code to remove NSTemporaryDirectory files -(void)deleteTempData { NSString *tmpDirectory = NSTemporaryDirectory(); NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:tmpDirectory error:&error]; for (NSString *file in cacheFiles) { error = nil; [fileManager removeItemAtPath:[tmpDirectory stringByAppendingPathComponent:file] error:&error]; } } and to check data remove or not write code in didFinishLaunchingWithOptions - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [self.window makeKeyAndVisible]; NSString *tmpDirectory = NSTemporaryDirectory(); NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:tmpDirectory error:&error]; NSLog(@"TempFile Count ::%lu",(unsigned long)cacheFiles.count); return YES; } A: Thanks to Max Maier and Roman Barzyczak. Updated to Swift 3, using URLs instead of strings. Swift 3 func clearTmpDir(){ var removed: Int = 0 do { let tmpDirURL = URL(string: NSTemporaryDirectory())! let tmpFiles = try FileManager.default.contentsOfDirectory(at: tmpDirURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) print("\(tmpFiles.count) temporary files found") for url in tmpFiles { removed += 1 try FileManager.default.removeItem(at: url) } print("\(removed) temporary files removed") } catch { print(error) print("\(removed) temporary files removed") } } A: Swift 3 version as extension: extension FileManager { func clearTmpDirectory() { do { let tmpDirectory = try contentsOfDirectory(atPath: NSTemporaryDirectory()) try tmpDirectory.forEach {[unowned self] file in let path = String.init(format: "%@%@", NSTemporaryDirectory(), file) try self.removeItem(atPath: path) } } catch { print(error) } } } Example of usage: FileManager.default.clearTmpDirectory() Thanks to Max Maier, Swift 2 version: func clearTmpDirectory() { do { let tmpDirectory = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(NSTemporaryDirectory()) try tmpDirectory.forEach { file in let path = String.init(format: "%@%@", NSTemporaryDirectory(), file) try NSFileManager.defaultManager().removeItemAtPath(path) } } catch { print(error) } } A: Swift 4 One of the possible implementations extension FileManager { func clearTmpDirectory() { do { let tmpDirURL = FileManager.default.temporaryDirectory let tmpDirectory = try contentsOfDirectory(atPath: tmpDirURL.path) try tmpDirectory.forEach { file in let fileUrl = tmpDirURL.appendingPathComponent(file) try removeItem(atPath: fileUrl.path) } } catch { //catch the error somehow } } } A: This works on a jailbroken iPad, but I think this should work on a non-jailbroken device also. -(void) clearCache { for(int i=0; i< 100;i++) { NSLog(@"warning CLEAR CACHE--------"); } NSFileManager *fileManager = [NSFileManager defaultManager]; NSError * error; NSArray * cacheFiles = [fileManager contentsOfDirectoryAtPath:NSTemporaryDirectory() error:&error]; for(NSString * file in cacheFiles) { error=nil; NSString * filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:file ]; NSLog(@"filePath to remove = %@",filePath); BOOL removed =[fileManager removeItemAtPath:filePath error:&error]; if(removed ==NO) { NSLog(@"removed ==NO"); } if(error) { NSLog(@"%@", [error description]); } } } A: I know i'm late to the party but i'd like to drop my implementation which works straight on URLs, too: let fileManager = FileManager.default let temporaryDirectory = fileManager.temporaryDirectory try? fileManager .contentsOfDirectory(at: temporaryDirectory, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants) .forEach { file in try? fileManager.removeItem(atPath: file.path) } A: // // FileManager+removeContentsOfTemporaryDirectory.swift // // Created by _ _ on _._.202_. // Copyright © 202_ _ _. All rights reserved. // import Foundation public extension FileManager { /// Perform this method on a background thread. /// Returns `true` if : /// * all temporary folder files have been deleted. /// * the temporary folder is empty. /// Returns `false` if : /// * some temporary folder files have not been deleted. /// Error handling: /// * Throws `contentsOfDirectory` directory access error. /// * Ignores single file `removeItem` errors. /// @discardableResult func removeContentsOfTemporaryDirectory() throws -> Bool { if Thread.isMainThread { let mainThreadWarningMessage = "\(#file) - \(#function) executed on main thread. Do not block the main thread." assertionFailure(mainThreadWarningMessage) } do { let tmpDirURL = FileManager.default.temporaryDirectory let tmpDirectoryContent = try contentsOfDirectory(atPath: tmpDirURL.path) guard tmpDirectoryContent.count != 0 else { return true } for tmpFilePath in tmpDirectoryContent { let trashFileURL = tmpDirURL.appendingPathComponent(tmpFilePath) try removeItem(atPath: trashFileURL.path) } let tmpDirectoryContentAfterDeletion = try contentsOfDirectory(atPath: tmpDirURL.path) return tmpDirectoryContentAfterDeletion.count == 0 } catch let directoryAccessError { throw directoryAccessError } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/9196443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "50" }
Q: Why is my react stepper component is look like small? I've used material-UI stepper to make multi-step form inside of the Drawer content which also a material-UI Drawer. But when I use that stepper code it looks like the below picture. So, where is the error? And that stepper code would be like: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Stepper from '@material-ui/core/Stepper'; import Step from '@material-ui/core/Step'; import StepButton from '@material-ui/core/StepButton'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles((theme) => ({ root: { width: '100%', }, button: { marginRight: theme.spacing(1), }, backButton: { marginRight: theme.spacing(1), }, completed: { display: 'inline-block', }, instructions: { marginTop: theme.spacing(1), marginBottom: theme.spacing(1), }, })); function getSteps() { return ['Select campaign settings', 'Create an ad group', 'Create an ad']; } function getStepContent(step) { switch (step) { case 0: return 'Step 1: Select campaign settings...'; case 1: return 'Step 2: What is an ad group anyways?'; case 2: return 'Step 3: This is the bit I really care about!'; default: return 'Unknown step'; } } export default function HorizontalNonLinearAlternativeLabelStepper() { const classes = useStyles(); const [activeStep, setActiveStep] = React.useState(0); const [completed, setCompleted] = React.useState(new Set()); const [skipped, setSkipped] = React.useState(new Set()); const steps = getSteps(); const totalSteps = () => { return getSteps().length; }; const isStepOptional = (step) => { return step === 1; }; const handleSkip = () => { if (!isStepOptional(activeStep)) { // You probably want to guard against something like this // it should never occur unless someone's actively trying to break something. throw new Error("You can't skip a step that isn't optional."); } setActiveStep((prevActiveStep) => prevActiveStep + 1); setSkipped((prevSkipped) => { const newSkipped = new Set(prevSkipped.values()); newSkipped.add(activeStep); return newSkipped; }); }; const skippedSteps = () => { return skipped.size; }; const completedSteps = () => { return completed.size; }; const allStepsCompleted = () => { return completedSteps() === totalSteps() - skippedSteps(); }; const isLastStep = () => { return activeStep === totalSteps() - 1; }; const handleNext = () => { const newActiveStep = isLastStep() && !allStepsCompleted() ? // It's the last step, but not all steps have been completed // find the first step that has been completed steps.findIndex((step, i) => !completed.has(i)) : activeStep + 1; setActiveStep(newActiveStep); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleStep = (step) => () => { setActiveStep(step); }; const handleComplete = () => { const newCompleted = new Set(completed); newCompleted.add(activeStep); setCompleted(newCompleted); /** * Sigh... it would be much nicer to replace the following if conditional with * `if (!this.allStepsComplete())` however state is not set when we do this, * thus we have to resort to not being very DRY. */ if (completed.size !== totalSteps() - skippedSteps()) { handleNext(); } }; const handleReset = () => { setActiveStep(0); setCompleted(new Set()); setSkipped(new Set()); }; const isStepSkipped = (step) => { return skipped.has(step); }; function isStepComplete(step) { return completed.has(step); } return ( <div className={classes.root}> <Stepper alternativeLabel nonLinear activeStep={activeStep}> {steps.map((label, index) => { const stepProps = {}; const buttonProps = {}; if (isStepOptional(index)) { buttonProps.optional = <Typography variant="caption">Optional</Typography>; } if (isStepSkipped(index)) { stepProps.completed = false; } return ( <Step key={label} {...stepProps}> <StepButton onClick={handleStep(index)} completed={isStepComplete(index)} {...buttonProps} > {label} </StepButton> </Step> ); })} </Stepper> <div> {allStepsCompleted() ? ( <div> <Typography className={classes.instructions}> All steps completed - you&apos;re finished </Typography> <Button onClick={handleReset}>Reset</Button> </div> ) : ( <div> <Typography className={classes.instructions}>{getStepContent(activeStep)}</Typography> <div> <Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}> Back </Button> <Button variant="contained" color="primary" onClick={handleNext} className={classes.button} > Next </Button> {isStepOptional(activeStep) && !completed.has(activeStep) && ( <Button variant="contained" color="primary" onClick={handleSkip} className={classes.button} > Skip </Button> )} {activeStep !== steps.length && (completed.has(activeStep) ? ( <Typography variant="caption" className={classes.completed}> Step {activeStep + 1} already completed </Typography> ) : ( <Button variant="contained" color="primary" onClick={handleComplete}> {completedSteps() === totalSteps() - 1 ? 'Finish' : 'Complete Step'} </Button> ))} </div> </div> )} </div> </div> ); } I just changed the width. But it doesn't work. How can I correct this error? A: I just found out the answer to that. In useStyles (styles in my code) I added marginRight: 700, to root class. Then the stepper stretched. const useStyles = makeStyles((theme) => ({ root: { width: '100%', marginRight: 700, }, Now it's look like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/63765416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Using statement, As vs = Is there a difference between using 'As' keyword and the '=' operator in vb.net? Example: Using aThing As New Thing() ... End Using ' OR Using aThing = New Thing() ... End Using A: There will be no effective difference if you have Option Infer On. If you have Option Infer Off then the first snippet will always result in a variable of type Thing while the second snippet will fail to compile with Option Strict On and result in a variable of type Object with Option Strict Off. The first code snippet is explicit in its typing of the variable so it will be the type you specify regardless of what settings you have for Option Strict and Option Infer. The second code snippet is not explicit about the type so that type must be determined implicitly by the compiler. With Option Infer On, the type Thing can be inferred from the initialising statement. With Option Infer Off, the type will default to Object and late-binding must be used, which is not allowed with Option Strict On. It's worth noting that your original question isn't really valid because it's actually not a case of using As or =. This: Using aThing As New Thing() is actually just a shorthand for this: Using aThing As Thing = New Thing() so you're actually using = either way and the choice is just whether or not to provide an As clause. An As clause is required with Option Strict On unless you also have Option Infer On and the type can be inferred from the initialising statement. If there is no initialising statement or the type of that statement is different to the type you want the variable to be then an As clause is required to tell the compiler the type of the variable that it cannot infer for itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/43795184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Maps Storelocator with filter (attributes) i am using this tutorial: https://developers.google.com/maps/articles/phpsqlsearch_v3?hl=de Everything works so far, but how can i add a function to filter within the results by attributes? Anyone here who has something for me? I can not find anything so far. many Thanks! A: Create a selectbox with id "cat": <select id="cat"> add the selected value of this select to searchUrl in function searchLocationsNear: var e = document.getElementById("cat"); var cat = e.options[e.selectedIndex].value; var searchUrl = 'phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; searchurl += '&cat=' + cat; add your filter to the query in phpsqlsearch_genxml.php: // Search the rows in the markers table $query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers WHERE `category`='%s' HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20", mysql_real_escape_string($center_lat), mysql_real_escape_string($center_lng), mysql_real_escape_string($center_lat), mysql_real_escape_string(empty($_GET['cat'])?'':$_GET['cat'])) mysql_real_escape_string($radius); $result = mysql_query($query);
{ "language": "en", "url": "https://stackoverflow.com/questions/16275775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compare two array's and disable a single element if the id's are equal I have two array in the state and both have id's. if some array have the same value (In this case 8) I would like to disable all the buttons that have this equal value. The buttons already exist, I just want to disable the ones that have the same non-unique ids. I tried like this but i'm not getting it var setOne = [2,6,8]; var setTwo = [3, 8, 4] const button = () => { var hasDuplicateValues = [...new Set(setOne)].filter(item => setTwo.includes(item)); if(hasDuplicateValues.length > 0) { <button disabled /> } else { <button /> } } render(){ this.button() } This solution is disabling all the buttons but i want to disable the one with the same id only. Thanks A: It's not quite clear where in the app hierarchy that component is so I've attempted a bit of guess work. You're almost there by the looks of things. You just need to iterate over the buttons and create them. function Button(props) { const { disabled, text } = props; return <button disabled={disabled}>{text}</button>; } // Buttons creates the buttons in the set function Buttons() { const setOne = [2, 6, 8]; const setTwo = [3, 8, 4]; // Remove the duplicates from the combined sets const combined = [...new Set([...setOne, ...setTwo])]; // Get your duplicate values const hasDuplicateValues = setOne.filter(item => setTwo.includes(item)); // `map` over the combined buttons // If `hasDuplicateValues` includes the current button, disable it return combined.map((n) => ( <Button text={n} disabled={hasDuplicateValues.includes(n) && 'disabled'} /> )); } ReactDOM.render(<Buttons />, document.querySelector("#root")) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/58541212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cakephp 1.3: Displaying user data in paginated comments another fairly basic question I suppose, but I feel like I'm running in circles and out of ideas, haha. I'm trying to create a commenting system with pagination (via Ajax), which has to be able to display the name, avatar, etc. of the user that wrote a particular comment. Sounds simple enough, right? Well, everything works fine, except so far I simply wasn't able to find a way to retrieve the corresponding users information and I couldn't find anything helpful in the docs either. Here's my pagination code so far: $this->paginate['Comment'] = array( 'conditions'=>array('Entry.id'=>$id), 'contain' => array('Entry', 'User'=>array('avatar', 'username') ), 'limit' => 10 ); $comments = $this->paginate('Comment'); $this->set(compact('comments')); So I've used contain to get the data of the user model, which I try to display in my view like this: echo $comment['User']['username']; echo $comment['User']['avatar']; But that way, it of course displays the information of the user corresponding to $id... However, I need to get a users info through the foreignkey user_id of the current comment. And at the moment I'm at a loss how to do that... Any help would be greatly appreciated. Thanks in advance! A: if I remember correctly 'contain' => array('Entry', 'User.avatar,User.username')), should do the trick A: Okay, I solved it... I just had to add the proper foreignKey to my Comment model, i.e: var $belongsTo = array( 'Entry' => array('className' => 'Entry', 'foreignKey' => 'page_id'), 'User' => array('className' => 'User', 'foreignKey' => 'user_id'), ); Now it finally fetches the appropriate user information!
{ "language": "en", "url": "https://stackoverflow.com/questions/7861969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to wait for a function to finish it's execution in angularJS? I've a function named validityCheck() and it's returns valid if an user is valid and invalid if the user is invalid. I need to call this function from somewhere else and use the result in if-else condition. Here's the function definition (This function is defined in a plain javascript library name library.js): function validityCheck(userid, serviceid, system) { $(document).ready(function () { $.get("https:*******userValidation?serviceid=" + serviceid + "&userid=" + userid + "&system=" + system, function (data, status) { console.log(data); return data[0]; }); }); } Now I want to do this (This code section is in my project's controller): var validity = validityCheck($scope.userid, serviceid, 'abc'); if(validity=="VALID"){ //do something }else{ //do something } I need to wait till I get the data. I think I need to use callback_ or something like that but I don't know how to do it. A: Why not return promise of angularjs $http and use then in your code like this? function validityCheck(userid, serviceid, system) { let params = { userid: userid, serviceid: serviceid, system: system }; let request = { url: "https:*******userValidation", method: "GET", headers: {"Content-Type": "application/x-www-form-urlencoded"}, params: params }; return $http(request).then((response) => { return response.data[0] ? response.data[0] : ''; }); } Usage: validityCheck($scope.userid, serviceid, 'abc').then((validity) => { if (validity === "VALID") { //do something } else { //do something } }); P.S. Don't forget to inject angularjs $http UPDATE: Register library.js in angular (function () { "use strict"; angular .module("yourAngularModuleName") .factory("LibraryFactory", LibraryFactory); function LibraryFactory($http) { // Add your functions here... } })(); UPDATE: Plain JavaScript Using The Existing Code function validityCheck(userid, serviceid, system) { return new Promise((resolve, reject) => { $.get("https:*******userValidation?serviceid=" + serviceid + "&userid=" + userid + "&system=" + system, function (data, status) { console.log(data); resolve(data[0]); }); }); } Use the same code in the USAGE that I have provided.
{ "language": "en", "url": "https://stackoverflow.com/questions/62528627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django prefetch table that is not directly related With the following models is it possible to get Category objects and prefetch OrderLine so that it can be accessed by category.orderlines.all()? class Category(models.Model): name = models.CharField(...) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', ...) name = models.CharField(...) price = models.DecimalField(...) class OrderLine(models.Model): product = models.ForeignKey(Product, related_name='orderlines', ...) I know you can do a nested prefetch through products but I'd like to access OrderLine objects directly from a Category rather than go through Product from django.db.models import Prefetch categories = Category.objects.prefetch_related(Prefetch( 'products__orderlines', queryset=OrderLine.objects.filter(...) )) for category in categories: for product in category.products.all(): for line in product.orderlines.all(): ... Desired usage: for category in categories: for line in category.orderlines.all(): ... Update Adding to_attr='orderlines' results in: ValueError: to_attr=orderlines conflicts with a field on the Product model. Changing the attribute name to_attr='lines' doesn't cause an error but the attribute isn't added to the Category objects. It prefetches Product then adds a lines attribute to each product. A: The closest I've come to this is using an ArraySubquery. The only downside being that lines is a list of dictionaries rather than model instances. Category.objects.annotate( lines=ArraySubquery( OrderLine.objects .filter(category=OuterRef('id')) .values(json=JSONObject( id='id', product_name='product__name', quantity='quantity', )) ) )
{ "language": "en", "url": "https://stackoverflow.com/questions/59247634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: IIS6 and .Net 4.5? In the past, the .NET framework has been independent from IIS versions, and have worked with IIS 6+. Will IIS 6 be supported for .NET 4.5? A: IIS 6 is part of Windows Server 2003 (and technically XP 64-bit). The .NET Framework 4.5 System Requirements indicate that Server 2003, thus IIS 6, is not supported. A: Not trying to throw the last answer off, this could be a typo on MS website, but looking for the same question, I found this. http://msdn.microsoft.com/en-us/library/ms733890.aspx "WCF can also be installed on Windows XP SP2, Windows Server 2003 R2, or Windows Server 2003 SP1" and that is while I have .net 4.5 selected at the top. I am thinking typo.. but hopeful ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/11935534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: GCC ignores `-mcpu=arm7tdmi` flag and generates unsupported instruction I'm trying to compile a small program for arm7tdmi (i.e. armv4t), using the command arm-linux-gnueabi-gcc -march=armv4t -mcpu=arm7tdmi -nostartfiles -static test.c -o test on Debian (gcc version 10.2.1, Debian 10.2.1-6). However, GCC seems to ignore the cpu and arch flags, and generates instructions that are unsupported on armv4t, e.g. clz, as shown by objdump: 104f4: 0a000071 beq 106c0 <.divsi3_skip_div0_test+0x1f0> 104f8: e16f2f13 clz r2, r3 104fc: e16f0f11 clz r0, r1 10500: e0402002 sub r2, r0, r2 10504: e272201f rsbs r2, r2, #31 I also checked the binary using readelf, and it shows the architecture is actually armv5te: File Attributes Tag_CPU_name: "5TE" Tag_CPU_arch: v5TE Tag_ARM_ISA_use: Yes Tag_THUMB_ISA_use: Thumb-1 May I ask what's going on here? Why is GCC ignoring the -mcpu and -march flags? Here's the content of test.c: #include <stdint.h> #include <stddef.h> void _start() { const size_t len = 8; uint8_t arr[8] = {10, 12, 8, 5, 0, 2, 3, 55}; uint8_t *data = arr; uint16_t a = 1, b = 0, m = 7; for(int i=0; i<len; i++) { a = (a + data[i]) % m; b = (a + b) % m; } uint32_t res = (uint32_t)b << 16 | (uint32_t)a; } A: You also need to add '-nostdlib' or it will drag in files that have been compiled with Armv5. The 'arm-linux' kernel does not support ARMv4 CPUs as they do not have an MMU. You are viewing assembler from the gcc library which is compiled for Armv5. The example label divsi3, shows that you are using division operation and this is coded in libgcc, which will link with the code. It is brought in by your % m code. You can code and supply your own divsi3, or get a compiler library that supports Armv4. The libgcc.a must be generated (downgraded) to support that CPU. Gcc's backend is capable of generating code for all members of the ARM32/Thumb family, but not support libraries (without multi-lib support). There is no bug in the compiler. If you look at the assembler for _start, it will not contain clz. If the % 7 could be % 8, you can downgrade to a &7 and the divsi3 would not be needed. You can see why here. It is a variation on this question. The issue is that the linker 'gnu ld' has no flag to say, reject Armv5 code. * *Provide divsi3 configured with Armv4. *Provide your own divsi3 with a Division algorithm. *Avoid the functionality (down grade to &).
{ "language": "en", "url": "https://stackoverflow.com/questions/72693275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }