id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
b73caab15dee9cf6e3845bf67c72c22f4b8d5e2b
Stackoverflow Stackexchange Q: ImportError: cannot import name pyqtSignal? Background on the question: This is a previous PyQt project I am working on and trying to start the GUI. I have set an Anaconda Environment with Python 2.7 and used PyQt4. The Error is :- File "gui/gui.py", line 26, in <module> from qtpy.QtCore import (Qt, QFileSystemWatcher, QSettings, pyqtSignal) ImportError: cannot import name pyqtSignal Code :- enter #import qt from qtpy import QtCore, QtWidgets, QtGui, PYQT4 #changed from PYQT5 from qtpy.QtCore import (Qt, QFileSystemWatcher, QSettings, pyqtSignal) Even after trying to setup the environment and other aspects to the best of my ability, I am unable to pinpoint why this error still pops up.Tried on Mac, it errors out similarly even on Ubuntu. Does anyone have an idea how to tackle this? A: You're using qtpy rather than PyQt4 directly. According to Don't delete QtCore.{pyqtSignal,pyqtSlot,pyqtProperty} · Issue #76 · spyder-ide/qtpy · GitHub, they deliberately ditched PyQt-specific names like pyqtSignal and instead rename them upon import to generic names like Signal for uniformity. They comment that these names follow Qt5's naming scheme. So you should just from qtpy.QtCore import Qt, QFileSystemWatcher, QSettings, Signal and rename all pyqtSignal to Signal elsewhere in your code.
Q: ImportError: cannot import name pyqtSignal? Background on the question: This is a previous PyQt project I am working on and trying to start the GUI. I have set an Anaconda Environment with Python 2.7 and used PyQt4. The Error is :- File "gui/gui.py", line 26, in <module> from qtpy.QtCore import (Qt, QFileSystemWatcher, QSettings, pyqtSignal) ImportError: cannot import name pyqtSignal Code :- enter #import qt from qtpy import QtCore, QtWidgets, QtGui, PYQT4 #changed from PYQT5 from qtpy.QtCore import (Qt, QFileSystemWatcher, QSettings, pyqtSignal) Even after trying to setup the environment and other aspects to the best of my ability, I am unable to pinpoint why this error still pops up.Tried on Mac, it errors out similarly even on Ubuntu. Does anyone have an idea how to tackle this? A: You're using qtpy rather than PyQt4 directly. According to Don't delete QtCore.{pyqtSignal,pyqtSlot,pyqtProperty} · Issue #76 · spyder-ide/qtpy · GitHub, they deliberately ditched PyQt-specific names like pyqtSignal and instead rename them upon import to generic names like Signal for uniformity. They comment that these names follow Qt5's naming scheme. So you should just from qtpy.QtCore import Qt, QFileSystemWatcher, QSettings, Signal and rename all pyqtSignal to Signal elsewhere in your code.
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:903429", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44662553" }
0359a838032d06777872b3270c7fd4c65db01d1e
Stackoverflow Stackexchange Q: Issue with horizontal scroll with touchpad in gnome I have installed gnome-shell on my ubuntu 17.04 and selected Gnome at my the login screen, everything works fine, but the horizontal scroll with touchpad doesn't work. It works when i shift to unity but fails in gnome. I installed dconf-editor and tried to enable horizontal scroll in org/gnome/settings-daemon/peripherals/touchpad as mentioned in an online forum but the touchpad doesn't show up in the peripherals folder. Any suggestions please ?
Q: Issue with horizontal scroll with touchpad in gnome I have installed gnome-shell on my ubuntu 17.04 and selected Gnome at my the login screen, everything works fine, but the horizontal scroll with touchpad doesn't work. It works when i shift to unity but fails in gnome. I installed dconf-editor and tried to enable horizontal scroll in org/gnome/settings-daemon/peripherals/touchpad as mentioned in an online forum but the touchpad doesn't show up in the peripherals folder. Any suggestions please ?
stackoverflow
{ "language": "en", "length": 78, "provenance": "stackexchange_0000F.jsonl.gz:903453", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44662629" }
f867e916e152a0e5e63a23c71a25ce1b781d6128
Stackoverflow Stackexchange Q: forEach in scala shows expected: Consumer[_ >:Path] actual: (Path) => Boolean Wrong syntax problem in recursively deleting scala files Files.walk(path, FileVisitOption.FOLLOW_LINKS) .sorted(Comparator.reverseOrder()) .forEach(Files.deleteIfExists) A: The issue is that you're trying to pass a scala-style function to a method expecting a java-8-style function. There's a couple libraries out there that can do the conversion, or you could write it yourself (it's not complicated), or probably the simplest is to just convert the java collection to a scala collection that has a foreach method expecting a scala-style function as an argument: import scala.collection.JavaConverters._ Files.walk(path, FileVisitOption.FOLLOW_LINKS) .sorted(Comparator.reverseOrder()) .iterator().asScala .foreach(Files.deleteIfExists)
Q: forEach in scala shows expected: Consumer[_ >:Path] actual: (Path) => Boolean Wrong syntax problem in recursively deleting scala files Files.walk(path, FileVisitOption.FOLLOW_LINKS) .sorted(Comparator.reverseOrder()) .forEach(Files.deleteIfExists) A: The issue is that you're trying to pass a scala-style function to a method expecting a java-8-style function. There's a couple libraries out there that can do the conversion, or you could write it yourself (it's not complicated), or probably the simplest is to just convert the java collection to a scala collection that has a foreach method expecting a scala-style function as an argument: import scala.collection.JavaConverters._ Files.walk(path, FileVisitOption.FOLLOW_LINKS) .sorted(Comparator.reverseOrder()) .iterator().asScala .foreach(Files.deleteIfExists) A: In Scala 2.12 I expect this should work: ...forEach(Files.deleteIfExists(_: Path)) The reason you need to specify argument type is because expected type is Consumer[_ >: Path], not Consumer[Path] as it would be in Scala. If it doesn't work (can't test at the moment), try val deleteIfExists: Consumer[Path] = Files.deleteIfExists(_) ...forEach(deleteIfExists) Before Scala 2.12, Joe K's answer is the correct one.
stackoverflow
{ "language": "en", "length": 158, "provenance": "stackexchange_0000F.jsonl.gz:903459", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44662647" }
773a80671c85bd6d98599e66f82a5f72bb30e2dd
Stackoverflow Stackexchange Q: How can I know when Kestrel has started listening? I need to notify systemd that my service has started up successfully, and a task it needs to run after startup requires that the server is already listening on the target Unix domain socket. I am using IWebHost::Run to start the server, and that is a blocking call. Additionally, I am unable to find any obvious way to set a delegate or callback event for successful initialization. Anyone? A: You may use Microsoft.AspNetCore.Hosting.IApplicationLifetime: /// <summary> /// Triggered when the application host has fully started and is about to wait /// for a graceful shutdown. /// </summary> CancellationToken ApplicationStarted { get; } Look into this SO post for the configuration example.
Q: How can I know when Kestrel has started listening? I need to notify systemd that my service has started up successfully, and a task it needs to run after startup requires that the server is already listening on the target Unix domain socket. I am using IWebHost::Run to start the server, and that is a blocking call. Additionally, I am unable to find any obvious way to set a delegate or callback event for successful initialization. Anyone? A: You may use Microsoft.AspNetCore.Hosting.IApplicationLifetime: /// <summary> /// Triggered when the application host has fully started and is about to wait /// for a graceful shutdown. /// </summary> CancellationToken ApplicationStarted { get; } Look into this SO post for the configuration example. A: * *On .Net Core 1.x it is safe to just run IWebHost.Start() and assume that the server is initialized afterwards (instead of Run() that blocks the thread). Check the source. var host = new WebHostBuilder() .UseKestrel() (...) .Build(); host.Start(); *If you are using .NET Core 2.0 Preview 1 (or later), the source is different, the synchronous method is not available anymore so you should await IWebHost.StartAsync() and assume everything is ready afterwards. A: This is what I ended up going with, for now. Seems to be working fine: host.Start(); Log.Information("Press Ctrl+C to shut down..."); Console.CancelKeyPress += OnConsoleCancelKeyPress; var waitHandles = new WaitHandle[] { CancelTokenSource.Token.WaitHandle }; WaitHandle.WaitAll(waitHandles); Log.Information("Shutting down..."); Then, in the Ctrl+C event handler: private static void OnConsoleCancelKeyPress(object sender, ConsoleCancelEventArgs e) { Log.Debug("Got Ctrl+C from console."); CancelTokenSource.Cancel(); } A: This is what I did to overcome the issue. 1- I registered ApplicationStopped event. So that it brute force terminates the app by calling Kill() method of the current process. public void Configure(IHostApplicationLifetime appLifetime) { appLifetime.ApplicationStarted.Register(() => { Console.WriteLine("Press Ctrl+C to shut down."); }); appLifetime.ApplicationStopped.Register(() => { Console.WriteLine("Terminating application..."); System.Diagnostics.Process.GetCurrentProcess().Kill(); }); } See IHostApplicationLifetime docs 2- Don't forget to use the UseConsoleLifetime() while building the host. Host.CreateDefaultBuilder(args).UseConsoleLifetime(opts => opts.SuppressStatusMessages = true); See useconsolelifetime docs A: A working sample from .NET Core 6: In your Program.cs, you will have the following (with more or less embellishment, depending on the middleware): var builder = WebApplication.CreateBuilder(args); /* ... kestrel configuration, middleware setup ... */ var app = builder.Build(); app.Services.GetService<IHostApplicationLifetime>()!.ApplicationStarted.Register(() => { /* any code you put here will execute * after the host has started listening */ Console.WriteLine("Kestrel has started listening"); }); /* this is a blocking call. * the start event occurs from "in there" */ app.Run(); Working principle: The event handler with the Console.WriteLine call will be called after app.Run() is already blocking the main thread, at the exact moment when the server is first ready and will accept requests.
stackoverflow
{ "language": "en", "length": 439, "provenance": "stackexchange_0000F.jsonl.gz:903476", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44662711" }
a559919fa37d1429428de5c401733241a708ca4c
Stackoverflow Stackexchange Q: Default vector constructor with a unique_ptr and thread What is the right way to call teh default vector contructor that creates 'n' elements of std::unique_ptr's holding threads. std::vector<std::unique_ptr<std::thread>> thr_grp(5, std::move(std::make_unique<std::thread>(std::thread(), threadWorker))); or std::vector<std::unique_ptr<std::thread>> thr_grp(5, std::move(std::unique_ptr<std::thread>(new std::thread(threadWorker)))); or either with out the std::move semantic? A: This cannot be done in this way because fill constructors of the std::vector make copies of the specified parameter and the std::unique_ptr has deleted copy constructor. You can emplace elements into a default constructed std::vector<std::unique_ptr<std::thread>> like the following example does: #include <iostream> #include <memory> #include <thread> #include <vector> void threadWorker() { std::cout << "I'm thread: " << std::this_thread::get_id() << std::endl; } int main() { std::vector<std::unique_ptr<std::thread>> thr_grp; for(int i = 0; i < 5; ++i) thr_grp.emplace_back(std::make_unique<std::thread>(threadWorker)); for(auto& e : thr_grp) e->join(); return 0; } Another approach is to construct and fill your std::vector with default constructed values and assign the values later: std::vector<std::unique_ptr<std::thread>> thr_grp(5); for(auto& e : thr_grp) e = std::make_unique<std::thread>(threadWorker); The code above will use move semantics, you don't have to explicitly indicate it with std::move.
Q: Default vector constructor with a unique_ptr and thread What is the right way to call teh default vector contructor that creates 'n' elements of std::unique_ptr's holding threads. std::vector<std::unique_ptr<std::thread>> thr_grp(5, std::move(std::make_unique<std::thread>(std::thread(), threadWorker))); or std::vector<std::unique_ptr<std::thread>> thr_grp(5, std::move(std::unique_ptr<std::thread>(new std::thread(threadWorker)))); or either with out the std::move semantic? A: This cannot be done in this way because fill constructors of the std::vector make copies of the specified parameter and the std::unique_ptr has deleted copy constructor. You can emplace elements into a default constructed std::vector<std::unique_ptr<std::thread>> like the following example does: #include <iostream> #include <memory> #include <thread> #include <vector> void threadWorker() { std::cout << "I'm thread: " << std::this_thread::get_id() << std::endl; } int main() { std::vector<std::unique_ptr<std::thread>> thr_grp; for(int i = 0; i < 5; ++i) thr_grp.emplace_back(std::make_unique<std::thread>(threadWorker)); for(auto& e : thr_grp) e->join(); return 0; } Another approach is to construct and fill your std::vector with default constructed values and assign the values later: std::vector<std::unique_ptr<std::thread>> thr_grp(5); for(auto& e : thr_grp) e = std::make_unique<std::thread>(threadWorker); The code above will use move semantics, you don't have to explicitly indicate it with std::move.
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:903529", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44662884" }
e30ea448060aa6cf7b545371348fc213edb49c9e
Stackoverflow Stackexchange Q: Visual Effects View with blur turns dark gray Currently we have a Visual Effects View that was added in storyboard like so: The view is presented modally but for some strange reason I can see the image underneath blurred during the transition but when the transition is complete the blur turns a dark gray: No code has been written yet, I'm trying to do this all in storyboard. A: You need to set the presentation style of your second view controller. * *Select your second view controller *From the Attributes Inspector set Presentation to Over Current Context Note: Make sure your second view controller is presented modally.
Q: Visual Effects View with blur turns dark gray Currently we have a Visual Effects View that was added in storyboard like so: The view is presented modally but for some strange reason I can see the image underneath blurred during the transition but when the transition is complete the blur turns a dark gray: No code has been written yet, I'm trying to do this all in storyboard. A: You need to set the presentation style of your second view controller. * *Select your second view controller *From the Attributes Inspector set Presentation to Over Current Context Note: Make sure your second view controller is presented modally.
stackoverflow
{ "language": "en", "length": 108, "provenance": "stackexchange_0000F.jsonl.gz:903540", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44662925" }
99d40eca0e3dbe9964cba79f458e1fa80d769a4a
Stackoverflow Stackexchange Q: How do I include appsettings.json configuration settings in a nuget package? I am running .net core 1.1, nuget 3.5, and hosting packages on VS team services. I looked into transformations here: https://learn.microsoft.com/en-us/nuget/create-packages/source-and-config-file-transformations, But I need a solution for json files, not config files. I read that you can use an install.ps1 script to include the file, but I also read that install.ps1 is deprecated. What is the current method for including json configuration files in a nuget package? A: Try to use <files> node in the .nuspec file. Example from here: <?xml version="1.0"?> <package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd"> <metadata> <!-- ... --> </metadata> <files> <!-- Add a readme --> <file src="readme.txt" target="" /> <!-- Add files from an arbitrary folder that's not necessarily in the project --> <file src="..\..\SomeRoot\**\*.*" target="" /> </files> </package>
Q: How do I include appsettings.json configuration settings in a nuget package? I am running .net core 1.1, nuget 3.5, and hosting packages on VS team services. I looked into transformations here: https://learn.microsoft.com/en-us/nuget/create-packages/source-and-config-file-transformations, But I need a solution for json files, not config files. I read that you can use an install.ps1 script to include the file, but I also read that install.ps1 is deprecated. What is the current method for including json configuration files in a nuget package? A: Try to use <files> node in the .nuspec file. Example from here: <?xml version="1.0"?> <package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd"> <metadata> <!-- ... --> </metadata> <files> <!-- Add a readme --> <file src="readme.txt" target="" /> <!-- Add files from an arbitrary folder that's not necessarily in the project --> <file src="..\..\SomeRoot\**\*.*" target="" /> </files> </package>
stackoverflow
{ "language": "en", "length": 131, "provenance": "stackexchange_0000F.jsonl.gz:903544", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44662938" }
87f9a319f17c13857f081cbb451e506a512f7a09
Stackoverflow Stackexchange Q: How to present a view controller with smaller size I want presented view controller vc2 in smaller size than the screen, how to do that in Swift 3 ?? Thanks for help. This is my code: @IBAction func leftButtonPressed(_ sender: UIButton) { let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "Controller2") as! ViewController2 vc2.modalPresentationStyle = .currentContext present(vc2, animated: true, completion: nil) } A: Try this.. @IBAction func leftButtonPressed(_ sender: UIButton) { let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "Controller2") as! ViewController vc2.providesPresentationContextTransitionStyle = true vc2.definesPresentationContext = true vc2.modalPresentationStyle=UIModalPresentationStyle.overCurrentContext self.present(vc2, animated: true, completion: nil) // Make sure your vc2 background color is transparent vc2.view.backgroundColor = UIColor.clear }
Q: How to present a view controller with smaller size I want presented view controller vc2 in smaller size than the screen, how to do that in Swift 3 ?? Thanks for help. This is my code: @IBAction func leftButtonPressed(_ sender: UIButton) { let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "Controller2") as! ViewController2 vc2.modalPresentationStyle = .currentContext present(vc2, animated: true, completion: nil) } A: Try this.. @IBAction func leftButtonPressed(_ sender: UIButton) { let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "Controller2") as! ViewController vc2.providesPresentationContextTransitionStyle = true vc2.definesPresentationContext = true vc2.modalPresentationStyle=UIModalPresentationStyle.overCurrentContext self.present(vc2, animated: true, completion: nil) // Make sure your vc2 background color is transparent vc2.view.backgroundColor = UIColor.clear } A: You can simply use a container view to display the smaller view controller. Here is a great tutorial on container views: https://cocoacasts.com/managing-view-controllers-with-container-view-controllers/ Hope this was helpful :)
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:903569", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663002" }
b3e68a65b7d44f3afc44b8baafdbd55fef7fa7dc
Stackoverflow Stackexchange Q: Resolve SSIS Package with Kingswaysoft error: Connection type "DynamicsCRM" is not recognized as a valid connection manager type I am using visual-studio-2015 to create an ssis package targeted at sql-server-2012. I am using KingswaySoft to connect to dynamics-crm to read & update some data. My package runs correctly when I run it from Visual Studio. However, when I deploy the package to my server, the package no longer runs successfully. I am receiving multiple errors with the first error being: The connection type "DynamicsCRM" specified for connection manager "Dynamics CRM Connection Manager" is not recognized a valid connection manager type. Why am I receiving this error and why is it only showing up when the package has been deployed? I have tried restarting the Integration Services on the server. I checked the license on the server and I noticed that although I have the Ultimate Edition of KingswaySoft, one of the License Manager's doesn't have a license and won't accept my license key. Perhaps it's a licensing issue? A: The error message indicates that you do not have our software installed on your integration server. Edit: Re-installation solved the issue (per comments)
Q: Resolve SSIS Package with Kingswaysoft error: Connection type "DynamicsCRM" is not recognized as a valid connection manager type I am using visual-studio-2015 to create an ssis package targeted at sql-server-2012. I am using KingswaySoft to connect to dynamics-crm to read & update some data. My package runs correctly when I run it from Visual Studio. However, when I deploy the package to my server, the package no longer runs successfully. I am receiving multiple errors with the first error being: The connection type "DynamicsCRM" specified for connection manager "Dynamics CRM Connection Manager" is not recognized a valid connection manager type. Why am I receiving this error and why is it only showing up when the package has been deployed? I have tried restarting the Integration Services on the server. I checked the license on the server and I noticed that although I have the Ultimate Edition of KingswaySoft, one of the License Manager's doesn't have a license and won't accept my license key. Perhaps it's a licensing issue? A: The error message indicates that you do not have our software installed on your integration server. Edit: Re-installation solved the issue (per comments)
stackoverflow
{ "language": "en", "length": 193, "provenance": "stackexchange_0000F.jsonl.gz:903576", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663018" }
41c752fb5bdb278b3fd4c79624c91fc84607d045
Stackoverflow Stackexchange Q: How to optimize deployment to regions for minimum perceived latency and maximum cost savings? I will be using Azure Cosmos DB with Azure Functions deployed in the same regions, with a gateway (cloudflare or an Azure option) which will route to the azure function in the closest region, which is deployed along side a Cosmos DB replication. the benefits in perceived latency should be logarithmic right? like, having 2 regions is 3x better, 3 region ~5x times better perceived latency. etc. according to MS, Cosmos DB is available in all regions. considering our customers aren't clustered around a specific region and are all over the world. which is the optimal regions to deploy to? for replication in * *1 region *2 regions *3 regions *4 regions A: You can use the http://www.azurespeed.com/ to see the closest DC from the client and pick the optimal location.
Q: How to optimize deployment to regions for minimum perceived latency and maximum cost savings? I will be using Azure Cosmos DB with Azure Functions deployed in the same regions, with a gateway (cloudflare or an Azure option) which will route to the azure function in the closest region, which is deployed along side a Cosmos DB replication. the benefits in perceived latency should be logarithmic right? like, having 2 regions is 3x better, 3 region ~5x times better perceived latency. etc. according to MS, Cosmos DB is available in all regions. considering our customers aren't clustered around a specific region and are all over the world. which is the optimal regions to deploy to? for replication in * *1 region *2 regions *3 regions *4 regions A: You can use the http://www.azurespeed.com/ to see the closest DC from the client and pick the optimal location. A: As an extreme/unrealistic case you can imagine each customer/client having a copy of the db running next to them. This should cause the least latency for the customer. Right ? The answer is that it depends. If you talk about local read/write latency then that would be true. However, the more you replicate your database the more time write operations will take to synchronise across all nodes (and in turn affect what is available when you read). See consistency models here. Although you have customers spread across the globe, it would be better if you start from regions with the most load/requests and then spread out from there. Deciding this is also when the proverbial "rubber meets the road" as you would soon realise that business might be willing to relax some latency needs around edges given the cost increase to achieve 100% coverage.
stackoverflow
{ "language": "en", "length": 291, "provenance": "stackexchange_0000F.jsonl.gz:903585", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663034" }
a17748ea066e24aeb9b92944497de6555caf3957
Stackoverflow Stackexchange Q: Protocol Extension of Constrained Dictionary I'm trying to get a specific Dictionary type to conform to a protocol. typealias FirebaseDictionary = Dictionary<String, FirebaseValue> I would like to have the conform to a FirebaseValue protocol protocol FirebaseValue { // stuff here } I tried this extension FirebaseDictionary: FirebaseValue { } but I got an error Constrained extension must be declared on the unspecialized generic type 'Dictionary' with constraints specified by a 'where' clause. So I now have this extension Dictionary where Key == String, Value == FirebaseValue { } but I cannot figure out the proper syntax to make this conform to a protocol, if at all possible. If not possible is there any other way to achieve the same effect? I'm trying to only allow specific types into a property, and be able to discern easily what type they are when read back. This question was asked but was given no definitive answer, and it may have changed regardless A: Since Swift 4.2 you can do this with: extension Dictionary : FirebaseValue where Key == String, Value == FirebaseValue { }
Q: Protocol Extension of Constrained Dictionary I'm trying to get a specific Dictionary type to conform to a protocol. typealias FirebaseDictionary = Dictionary<String, FirebaseValue> I would like to have the conform to a FirebaseValue protocol protocol FirebaseValue { // stuff here } I tried this extension FirebaseDictionary: FirebaseValue { } but I got an error Constrained extension must be declared on the unspecialized generic type 'Dictionary' with constraints specified by a 'where' clause. So I now have this extension Dictionary where Key == String, Value == FirebaseValue { } but I cannot figure out the proper syntax to make this conform to a protocol, if at all possible. If not possible is there any other way to achieve the same effect? I'm trying to only allow specific types into a property, and be able to discern easily what type they are when read back. This question was asked but was given no definitive answer, and it may have changed regardless A: Since Swift 4.2 you can do this with: extension Dictionary : FirebaseValue where Key == String, Value == FirebaseValue { }
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:903591", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663049" }
6e45ad88b8bd4c7abb7b175d286483b5088c89fd
Stackoverflow Stackexchange Q: How to disable sticky sessions in Openshift3 If you scale up a Pod in Openshift3, all requests coming from the same client IP address are sent to container which has the session associated. Is there any configuration to disable sticky sessions? How can I manage the options of internal HAProxy in Openshift? A: oc set env dc/router ROUTER_TCP_BALANCE_SCHEME=roundrobin will change the load balancing algorithm haproxy uses for routes it just passes through (default is source). ROUTER_LOAD_BALANCE_ALGORITHM will change it for routes where it terminates TLS (default us leastconn). More info on changing the internals of how haproxy works in the OCP 3.5 docs .
Q: How to disable sticky sessions in Openshift3 If you scale up a Pod in Openshift3, all requests coming from the same client IP address are sent to container which has the session associated. Is there any configuration to disable sticky sessions? How can I manage the options of internal HAProxy in Openshift? A: oc set env dc/router ROUTER_TCP_BALANCE_SCHEME=roundrobin will change the load balancing algorithm haproxy uses for routes it just passes through (default is source). ROUTER_LOAD_BALANCE_ALGORITHM will change it for routes where it terminates TLS (default us leastconn). More info on changing the internals of how haproxy works in the OCP 3.5 docs . A: For posterity, and since I had the same problem, I want to document the solution I used from Graham Dumpleton's excellent comment. As it turns out, a cookie is set during the first request that redirects subsequent requests to the same back-end. To disable this behavior on a per-route basis: oc annotate routes myroute haproxy.router.openshift.io/disable_cookies='true' This prevents the cookie from being set and allows the balance algorithm to select the appropriate back-end for subsequent requests from the same client. To change the balance algorithm: oc annotate routes myroute haproxy.router.openshift.io/balance='roundrobin' With these two annotations set, requests from the same client IP address are sent to each back-end in turn, instead of the same back-end over and over.
stackoverflow
{ "language": "en", "length": 222, "provenance": "stackexchange_0000F.jsonl.gz:903603", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663089" }
46ae7e77c1d5a58edba1becd4b2bac4edd69616e
Stackoverflow Stackexchange Q: Swift modal view background appearing black after setting it to clear I am trying to present a custom view from a controller modally, however when I do so the background of everything but the textfield I have turns black as seen in here . (the intended modal) This seems to be a fairly common problem, however I have already implemented the code that most similar questions pose as the answer here is my addEvent method in the first controller: @IBAction func addEvent(_ sender: Any) { let newEventViewController = NewEventViewController() newEventViewController.view.backgroundColor = UIColor.clear newEventViewController.view.isOpaque = false navigationController?.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext navigationController?.present(newEventViewController, animated: true, completion: nil) } Any help figuring out what I am missing would be appreciated. If it makes a difference I am creating my app using individual xib files and not a storyboard. A: You need to set the modalPresentationStyle of newEventController not the navigationController like this: newEventViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext Also although not needed I would present from self rather than the navigation controller like this: self.present(newEventViewController, animated: true, completion: nil)
Q: Swift modal view background appearing black after setting it to clear I am trying to present a custom view from a controller modally, however when I do so the background of everything but the textfield I have turns black as seen in here . (the intended modal) This seems to be a fairly common problem, however I have already implemented the code that most similar questions pose as the answer here is my addEvent method in the first controller: @IBAction func addEvent(_ sender: Any) { let newEventViewController = NewEventViewController() newEventViewController.view.backgroundColor = UIColor.clear newEventViewController.view.isOpaque = false navigationController?.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext navigationController?.present(newEventViewController, animated: true, completion: nil) } Any help figuring out what I am missing would be appreciated. If it makes a difference I am creating my app using individual xib files and not a storyboard. A: You need to set the modalPresentationStyle of newEventController not the navigationController like this: newEventViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext Also although not needed I would present from self rather than the navigation controller like this: self.present(newEventViewController, animated: true, completion: nil)
stackoverflow
{ "language": "en", "length": 172, "provenance": "stackexchange_0000F.jsonl.gz:903629", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663174" }
923af5153be5e465e2383ab301d93684ceb2d613
Stackoverflow Stackexchange Q: Swift Change the tableviewcell border color according to data I have written a code for making the cell border color change according to inStock or outStock , if it is inStock it will be red border else it would be green, but I it is not working for me, I put it in willDisplayCell and here is my code : func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath){ cell.backgroundColor = UIColor.clear cell.contentView.backgroundColor = UIColor.clear let whiteRoundedView : UIView = UIView(frame: CGRect(x:10,y: 5,width: self.view.frame.size.width - 20,height: 214)) whiteRoundedView.layer.masksToBounds = false whiteRoundedView.layer.cornerRadius = 5.0 whiteRoundedView.layer.shadowOffset = CGSize(width: -1,height: 1) whiteRoundedView.layer.borderWidth = 2 cell.contentView.addSubview(whiteRoundedView) cell.contentView.sendSubview(toBack: whiteRoundedView) if stock[indexPath.row] == "inStock" { whiteRoundedView.layer.borderColor = UIColor.red.cgColor } else { whiteRoundedView.layer.borderColor = UIColor.green.cgColor } } A: Try to move your code into cellForRowAt method like that cell.layer.masksToBounds = true cell.layer.cornerRadius = 5 cell.layer.borderWidth = 2 cell.layer.shadowOffset = CGSize(width: -1, height: 1) let borderColor: UIColor = (stock[indexPath.row] == "inStock") ? .red : .green cell.layer.borderColor = borderColor.cgColor
Q: Swift Change the tableviewcell border color according to data I have written a code for making the cell border color change according to inStock or outStock , if it is inStock it will be red border else it would be green, but I it is not working for me, I put it in willDisplayCell and here is my code : func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath){ cell.backgroundColor = UIColor.clear cell.contentView.backgroundColor = UIColor.clear let whiteRoundedView : UIView = UIView(frame: CGRect(x:10,y: 5,width: self.view.frame.size.width - 20,height: 214)) whiteRoundedView.layer.masksToBounds = false whiteRoundedView.layer.cornerRadius = 5.0 whiteRoundedView.layer.shadowOffset = CGSize(width: -1,height: 1) whiteRoundedView.layer.borderWidth = 2 cell.contentView.addSubview(whiteRoundedView) cell.contentView.sendSubview(toBack: whiteRoundedView) if stock[indexPath.row] == "inStock" { whiteRoundedView.layer.borderColor = UIColor.red.cgColor } else { whiteRoundedView.layer.borderColor = UIColor.green.cgColor } } A: Try to move your code into cellForRowAt method like that cell.layer.masksToBounds = true cell.layer.cornerRadius = 5 cell.layer.borderWidth = 2 cell.layer.shadowOffset = CGSize(width: -1, height: 1) let borderColor: UIColor = (stock[indexPath.row] == "inStock") ? .red : .green cell.layer.borderColor = borderColor.cgColor A: You are adding your whiteRoundedView multiple time for each cell - as cell instances are reused. You should only create this once (when creating UITableViewCell) - and then manipulate color of it after that in willDisplayCell function. I would suggest creating custom UITableViewCell, but you can also avoid that problem by using view "tag" property and checking if it exists already.
stackoverflow
{ "language": "en", "length": 224, "provenance": "stackexchange_0000F.jsonl.gz:903648", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663217" }
e448d31de8a17a11d2e4260a10f143358df468ce
Stackoverflow Stackexchange Q: Firebase SignIn with idToken or refreshToken When a user signs into my app with Firebase auth, I save both the returned idToken and refreshToken as cookies. When the app is refreshed, rather than making the user go through the sign in process again, I'd like to just pull these stored tokens and re-auth with them. So I would just provide a token, and the currentUser would be the same as it was before the refresh occurred. As far as I can tell from the firebase docs on the matter, there is no way to trigger a "sign in" just from these tokens. What can I do? Or does Firebase store its own cookies to persist the currentUser across refreshes? A: Should have read the docs better, looks like Firebase persists the currentUser on its own, according to "The Current User" portion of this doc. So basically, I should stop storing the tokens on my own, and let firebase handle it.
Q: Firebase SignIn with idToken or refreshToken When a user signs into my app with Firebase auth, I save both the returned idToken and refreshToken as cookies. When the app is refreshed, rather than making the user go through the sign in process again, I'd like to just pull these stored tokens and re-auth with them. So I would just provide a token, and the currentUser would be the same as it was before the refresh occurred. As far as I can tell from the firebase docs on the matter, there is no way to trigger a "sign in" just from these tokens. What can I do? Or does Firebase store its own cookies to persist the currentUser across refreshes? A: Should have read the docs better, looks like Firebase persists the currentUser on its own, according to "The Current User" portion of this doc. So basically, I should stop storing the tokens on my own, and let firebase handle it.
stackoverflow
{ "language": "en", "length": 161, "provenance": "stackexchange_0000F.jsonl.gz:903680", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663299" }
905ac7ec8c260f1391e118b687989c610ebcf32f
Stackoverflow Stackexchange Q: Datetime - set seconds to 00 My problem is that when I'm trying to set todays date time to 00:00:00 I'm getting some weird decimal number as a seconds. Why is that happening and what is it? And how can I get rid of that decimal? This is what I get: 2017-06-20 00:00:00.652698+00:00 And this is what I want to achieve: 2017-06-20 00:00:00+00:00 code: todays_date = timezone.now().replace(hour=0, minute=0, second=0) print(todays_date) A: datetime.datetime supports microsecond precision. To truncate the fractional seconds, add microsecond=0 to your replace call: todays_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) print(todays_date) Or you can get just the date part as a datetime.date object with the date method: todays_date = timezone.now().date() print(todays_date) which shall output 2017-06-20
Q: Datetime - set seconds to 00 My problem is that when I'm trying to set todays date time to 00:00:00 I'm getting some weird decimal number as a seconds. Why is that happening and what is it? And how can I get rid of that decimal? This is what I get: 2017-06-20 00:00:00.652698+00:00 And this is what I want to achieve: 2017-06-20 00:00:00+00:00 code: todays_date = timezone.now().replace(hour=0, minute=0, second=0) print(todays_date) A: datetime.datetime supports microsecond precision. To truncate the fractional seconds, add microsecond=0 to your replace call: todays_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) print(todays_date) Or you can get just the date part as a datetime.date object with the date method: todays_date = timezone.now().date() print(todays_date) which shall output 2017-06-20
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:903682", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663303" }
1c516e0b276246968002e6024d8834d75ab7c16d
Stackoverflow Stackexchange Q: Swift 4 backwards compatibility I have the following code in my project in Xcode 8.3.3 (Swift 3.1): let font = CGFont(provider!) CTFontManagerRegisterGraphicsFont(font, &error) But in Xcode 9 Beta (Swift 4), I get the following error: Value of optional type 'CGFont?' not unwrapped; did you mean to use '!' or '?'? The error is because the initializer for CGFont that takes a CGDataProvider now returns an optional. But when I apply the fix of: let font = CGFont(provider) CTFontManagerRegisterGraphicsFont(font!, &error) The code no longer compiles in Xcode 8.3.3 with Swift 3.1 since font is not an optional and thus doesn't play nicely with the !. Is there a way to make this work in both versions of Xcode? Is Swift 4 supposed to be backwards compatible (compile with Swift 3 compiler)? A: This is a breaking change in Core Graphics not in Swift itself. API has changed, the initializer is now failable. Use conditional compilation to make your code compile with both 3.1 and 4.0 compiler: #if swift(>=4.0) let font = CGFont(provider!) #else let font = CGFont(provider)! #endif CTFontManagerRegisterGraphicsFont(font, &error)
Q: Swift 4 backwards compatibility I have the following code in my project in Xcode 8.3.3 (Swift 3.1): let font = CGFont(provider!) CTFontManagerRegisterGraphicsFont(font, &error) But in Xcode 9 Beta (Swift 4), I get the following error: Value of optional type 'CGFont?' not unwrapped; did you mean to use '!' or '?'? The error is because the initializer for CGFont that takes a CGDataProvider now returns an optional. But when I apply the fix of: let font = CGFont(provider) CTFontManagerRegisterGraphicsFont(font!, &error) The code no longer compiles in Xcode 8.3.3 with Swift 3.1 since font is not an optional and thus doesn't play nicely with the !. Is there a way to make this work in both versions of Xcode? Is Swift 4 supposed to be backwards compatible (compile with Swift 3 compiler)? A: This is a breaking change in Core Graphics not in Swift itself. API has changed, the initializer is now failable. Use conditional compilation to make your code compile with both 3.1 and 4.0 compiler: #if swift(>=4.0) let font = CGFont(provider!) #else let font = CGFont(provider)! #endif CTFontManagerRegisterGraphicsFont(font, &error) A: I ended up using the following method which allowed for backwards compatibility without conditional compilation (idea taken from this blog post): func optionalize<T>(_ x: T?) -> T? { return x } This way in both Xcode 8 and Xcode 9 I could use: guard let font = optionalize(CGFont(provider)) else { return } CTFontManagerRegisterGraphicsFont(font, &error)
stackoverflow
{ "language": "en", "length": 235, "provenance": "stackexchange_0000F.jsonl.gz:903687", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663315" }
c6e2a8bc260ac50c821ac124e618ff769227fd54
Stackoverflow Stackexchange Q: What does is the "exotic" naming in the version of npm packages? What does it mean the "exotic" naming that appears sometimes in the listing of npm packages on the version, for example in the command npm outdated I get: Package Current Wanted Latest URL gulp 4.0.0-alpha.2 exotic exotic github:gulpjs/gulp#4.0 thanks A: I think it's labeled as "exotic" because it's installed from a GitHub URL, rather than from the npm registry. So it's an "exotic" package, meaning foreign or non-native. My interpretation is that this is a dev-friendly warning that you are doing something "exotic" and that npm/yarn can't detect for you whether this package has become outdated. I looked in the npm/npm repo (and some other npm-related repos), but I couldn't find the text exotic, so it must originate from their (private) registry API? I did find some handling of exotic in the yarnpkg/yarn repo though, for reference: https://github.com/yarnpkg/yarn/blob/a3ce7c702f644efde783beb8e0b99dc08100f0df/src/package-request.js#L408
Q: What does is the "exotic" naming in the version of npm packages? What does it mean the "exotic" naming that appears sometimes in the listing of npm packages on the version, for example in the command npm outdated I get: Package Current Wanted Latest URL gulp 4.0.0-alpha.2 exotic exotic github:gulpjs/gulp#4.0 thanks A: I think it's labeled as "exotic" because it's installed from a GitHub URL, rather than from the npm registry. So it's an "exotic" package, meaning foreign or non-native. My interpretation is that this is a dev-friendly warning that you are doing something "exotic" and that npm/yarn can't detect for you whether this package has become outdated. I looked in the npm/npm repo (and some other npm-related repos), but I couldn't find the text exotic, so it must originate from their (private) registry API? I did find some handling of exotic in the yarnpkg/yarn repo though, for reference: https://github.com/yarnpkg/yarn/blob/a3ce7c702f644efde783beb8e0b99dc08100f0df/src/package-request.js#L408
stackoverflow
{ "language": "en", "length": 151, "provenance": "stackexchange_0000F.jsonl.gz:903688", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663318" }
9fe0bbe7b55a050602f89cc0a3fe1c2a93db7ec5
Stackoverflow Stackexchange Q: Python creating username and password program I am just a beginner programmer as of right now, and I am trying to create a username/password program. Here is my code below: username = 'Polly1220' password = 'Bob' userInput = input("What is your username?\n") if userInput == username: a=input("Password?\n") if a == password: print("Welcome!") else: print("That is the wrong password.") else: print("That is the wrong username.") Whenever I run my program and input the correct password as shown, it always says that the password is incorrect. A: You need to assign the second input statement to userInput: if userInput == username: userInput = input("Password?\n") if userInput == password: print("Welcome!") else: print("That is the wrong password.") else: print("That is the wrong username.")
Q: Python creating username and password program I am just a beginner programmer as of right now, and I am trying to create a username/password program. Here is my code below: username = 'Polly1220' password = 'Bob' userInput = input("What is your username?\n") if userInput == username: a=input("Password?\n") if a == password: print("Welcome!") else: print("That is the wrong password.") else: print("That is the wrong username.") Whenever I run my program and input the correct password as shown, it always says that the password is incorrect. A: You need to assign the second input statement to userInput: if userInput == username: userInput = input("Password?\n") if userInput == password: print("Welcome!") else: print("That is the wrong password.") else: print("That is the wrong username.") A: You forgot to assign the variable: if userInput == username userInput = input("Password?\n") if userInput == password: print("Welcome!") else: print("That is the wrong password.") else: print("That is the wrong username.")
stackoverflow
{ "language": "en", "length": 151, "provenance": "stackexchange_0000F.jsonl.gz:903714", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663389" }
286ba76d79e76a89e16b2b95b5d2a17ad016ad0d
Stackoverflow Stackexchange Q: AWS Redshift Spectrum - how to get the s3 filenames in the external table I have external tables created in AWS spectrum to query the s3 data however i am not able to identify the filenames which the record belongs to(i have thousands of files under a bucket) In AWS Athena we have a pseudo column "$PATH" which will display the s3 filenames is there any similar ways available while using spectrum? A: Since recently, you can use specific pseudo-columns to access the path and the size of the object in S3 for lineage information. http://docs.aws.amazon.com/redshift/latest/dg/c-spectrum-external-tables.html#c-spectrum-external-tables-pseudocolumns An example for such a query would be: >> select distinct "$path", "$size" from spectrum.sales_part; $path | $size ---------------------------------------+------- s3://awssampledbuswest2/tickit/spectrum/sales_partition/saledate=2008-01/ | 1616 s3://awssampledbuswest2/tickit/spectrum/sales_partition/saledate=2008-02/ | 1444 s3://awssampledbuswest2/tickit/spectrum/sales_partition/saledate=2008-02/ | 1444
Q: AWS Redshift Spectrum - how to get the s3 filenames in the external table I have external tables created in AWS spectrum to query the s3 data however i am not able to identify the filenames which the record belongs to(i have thousands of files under a bucket) In AWS Athena we have a pseudo column "$PATH" which will display the s3 filenames is there any similar ways available while using spectrum? A: Since recently, you can use specific pseudo-columns to access the path and the size of the object in S3 for lineage information. http://docs.aws.amazon.com/redshift/latest/dg/c-spectrum-external-tables.html#c-spectrum-external-tables-pseudocolumns An example for such a query would be: >> select distinct "$path", "$size" from spectrum.sales_part; $path | $size ---------------------------------------+------- s3://awssampledbuswest2/tickit/spectrum/sales_partition/saledate=2008-01/ | 1616 s3://awssampledbuswest2/tickit/spectrum/sales_partition/saledate=2008-02/ | 1444 s3://awssampledbuswest2/tickit/spectrum/sales_partition/saledate=2008-02/ | 1444
stackoverflow
{ "language": "en", "length": 125, "provenance": "stackexchange_0000F.jsonl.gz:903723", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663412" }
adf4171494c990ce6413357f1dfbd6bf7de54d52
Stackoverflow Stackexchange Q: How to setup Capybara with Safari Technology Preview in Ruby I can't establish a session with Safari Technology Preview (STP) using Capybara and Selenium. Capybara won't even open a browser window. I've upgraded to Ruby 2.3.0 Capybara 2.14.2 Selenium 3.4.0 I downloaded and installed STP from https://developer.apple.com/safari/download/ I am trying to use the following code: Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new( app, browser: :safari ) end Capybara.default_driver = :selenium How do I initialize Capybara to use the STP safaridriver that has implemented the W3C standards for automation? A: To get this to work I used the following code: #This is what we use to test the Safari release channel. #You will have to install Safari Technology Preview (STP) from Apple. #see standard properties here: https://www.w3.org/TR/webdriver/#capabilities #STP requires a capabilities object #you could use any of the properties from the link above. #I just used a accept_insecure_certs for the heck of it desired_caps = Selenium::WebDriver::Remote::Capabilities.safari( { accept_insecure_certs: true } ) Capybara.register_driver :safari_technology_preview do |app| Capybara::Selenium::Driver.new( app, browser: :safari, driver_path: '/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver', desired_capabilities: desired_caps ) end Capybara.default_driver = :safari_technology_preview
Q: How to setup Capybara with Safari Technology Preview in Ruby I can't establish a session with Safari Technology Preview (STP) using Capybara and Selenium. Capybara won't even open a browser window. I've upgraded to Ruby 2.3.0 Capybara 2.14.2 Selenium 3.4.0 I downloaded and installed STP from https://developer.apple.com/safari/download/ I am trying to use the following code: Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new( app, browser: :safari ) end Capybara.default_driver = :selenium How do I initialize Capybara to use the STP safaridriver that has implemented the W3C standards for automation? A: To get this to work I used the following code: #This is what we use to test the Safari release channel. #You will have to install Safari Technology Preview (STP) from Apple. #see standard properties here: https://www.w3.org/TR/webdriver/#capabilities #STP requires a capabilities object #you could use any of the properties from the link above. #I just used a accept_insecure_certs for the heck of it desired_caps = Selenium::WebDriver::Remote::Capabilities.safari( { accept_insecure_certs: true } ) Capybara.register_driver :safari_technology_preview do |app| Capybara::Selenium::Driver.new( app, browser: :safari, driver_path: '/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver', desired_capabilities: desired_caps ) end Capybara.default_driver = :safari_technology_preview A: There is now a way to do this without specifying the path (which you may not know). The Selenium driver supports telling the driver that you want Technology Preview. However this seems to work a little differently than other options. Calling Selenium::WebDriver::Safari.technology_preview! turns the feature on for any Safari Driver created after this. Capybara.register_driver :safari_tech_preview do |app| Selenium::WebDriver::Safari.technology_preview! capabilities = Selenium::WebDriver::Remote::Capabilities.safari Capybara::Selenium::Driver.new(app, browser: :safari, desired_capabilities: capabilities) end Make sure you've enabled remote automation in the tech preview browser first.
stackoverflow
{ "language": "en", "length": 258, "provenance": "stackexchange_0000F.jsonl.gz:903746", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663481" }
4da16e4cf69bde4a9b2314603d9b721082928fad
Stackoverflow Stackexchange Q: Can I use both Django and Rest Framework views in a single project? I want to add some REST API views to an existing Django project, which uses vanilla Django views. For that I'd like to use the REST Framework. I wonder if I can I mix Django and RF views in a single project and what pitfalls this might have (e.g. with authentication). A: Yes you can surely use both of them at the same time, there shouldn't be any issue. Typically the Django views use SessionAuthentication, adn you will use DRF using TokenAuthentication -- best practice is to add both Session and Token authentication to the authentication_classes in the DRF views - that way you can use the browsable api pages to browse the apis once you have signed in via password (session authentication) as well class GenericViewTest(SuperuserRequiredMixin, View): def get(self, request, *args, **kwargs): return HttpResponse("Test") class PostTrackingCode(CreateAPIView): """ """ authentication_classes = (SessionAuthentication, TokenAuthentication) ----> note this permission_classes = (permissions.IsAuthenticated,) serializer_class = TrackingInfoWriteSerializer model = TrackingInfo
Q: Can I use both Django and Rest Framework views in a single project? I want to add some REST API views to an existing Django project, which uses vanilla Django views. For that I'd like to use the REST Framework. I wonder if I can I mix Django and RF views in a single project and what pitfalls this might have (e.g. with authentication). A: Yes you can surely use both of them at the same time, there shouldn't be any issue. Typically the Django views use SessionAuthentication, adn you will use DRF using TokenAuthentication -- best practice is to add both Session and Token authentication to the authentication_classes in the DRF views - that way you can use the browsable api pages to browse the apis once you have signed in via password (session authentication) as well class GenericViewTest(SuperuserRequiredMixin, View): def get(self, request, *args, **kwargs): return HttpResponse("Test") class PostTrackingCode(CreateAPIView): """ """ authentication_classes = (SessionAuthentication, TokenAuthentication) ----> note this permission_classes = (permissions.IsAuthenticated,) serializer_class = TrackingInfoWriteSerializer model = TrackingInfo
stackoverflow
{ "language": "en", "length": 169, "provenance": "stackexchange_0000F.jsonl.gz:903843", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663754" }
a94de0432dc485fd7265265dbf3f3b4f7002ccd9
Stackoverflow Stackexchange Q: How to reference previously started processes in an Elixir supervisor I am starting a Supervisor that monitors two children. The second child needs a reference to the first. It seams like this should be possible because by using the one_for_rest strategy I can make sure that if the first dies the second is restarted. children = [ supervisor(SupervisorA, [arg1]), supervisor(SupervisorB, [arg2, ref_to_supervisor_a_process]), ] supervise(children, strategy: :one_for_rest) Ideally without having to globally name either process. A: SupervisorA can supply the name: option to Supervisor.start_link/3. SupervisorB can then use Process.whereis/1 to resolve the name to a pid or just send messages to the named process. https://hexdocs.pm/elixir/Supervisor.html#start_link/3 https://hexdocs.pm/elixir/Process.html#whereis/1
Q: How to reference previously started processes in an Elixir supervisor I am starting a Supervisor that monitors two children. The second child needs a reference to the first. It seams like this should be possible because by using the one_for_rest strategy I can make sure that if the first dies the second is restarted. children = [ supervisor(SupervisorA, [arg1]), supervisor(SupervisorB, [arg2, ref_to_supervisor_a_process]), ] supervise(children, strategy: :one_for_rest) Ideally without having to globally name either process. A: SupervisorA can supply the name: option to Supervisor.start_link/3. SupervisorB can then use Process.whereis/1 to resolve the name to a pid or just send messages to the named process. https://hexdocs.pm/elixir/Supervisor.html#start_link/3 https://hexdocs.pm/elixir/Process.html#whereis/1 A: Supervisor.Spec.supervisor/3 returns a spec. One might pass it through: {id, _, _, _, _, _} = sup_a = supervisor(SupervisorA, [arg1]) children = [ sup_a, supervisor(SupervisorB, [arg2, id]), ]
stackoverflow
{ "language": "en", "length": 135, "provenance": "stackexchange_0000F.jsonl.gz:903865", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663817" }
f38b982e7608b263e16d4f85ce11aba3eea9c2a3
Stackoverflow Stackexchange Q: How do I squash all commit history and push into another remote repository? I have not been able to figure out after much trying. I have two local branches, master and tests. I have two corresponding remote branches with the same repo, origin/master, origin/tests. I have another remote branch public/master. I have some pushed in commit history on both local master and remote origin/master. Now, I want to squash all the commits of origin/master and push into the remote branch public/master. I can't figure out how to do it. I have tried doing rebase on a new local branch but it didn't work. A: Reset to your first commit, then amend, finally force push. git pull origin master git checkout master git reset --soft <my-first-commit> git commit --amend -m "New commit message" git push public master --force-with-lease If the last command gives a "stale info" error, either * *run git fetch public master before the last command, or *run git push --force-with-lease public +master instead of the last command. You can find your first commit like this: git rev-list --max-parents=0 HEAD
Q: How do I squash all commit history and push into another remote repository? I have not been able to figure out after much trying. I have two local branches, master and tests. I have two corresponding remote branches with the same repo, origin/master, origin/tests. I have another remote branch public/master. I have some pushed in commit history on both local master and remote origin/master. Now, I want to squash all the commits of origin/master and push into the remote branch public/master. I can't figure out how to do it. I have tried doing rebase on a new local branch but it didn't work. A: Reset to your first commit, then amend, finally force push. git pull origin master git checkout master git reset --soft <my-first-commit> git commit --amend -m "New commit message" git push public master --force-with-lease If the last command gives a "stale info" error, either * *run git fetch public master before the last command, or *run git push --force-with-lease public +master instead of the last command. You can find your first commit like this: git rev-list --max-parents=0 HEAD A: Could also work by checking out an orphan branch (which will carry the current working tree to make the very first commit), and then you can push into whatever remote you feel like.
stackoverflow
{ "language": "en", "length": 216, "provenance": "stackexchange_0000F.jsonl.gz:903867", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663822" }
6b4da1986c364ecf264c97aa3b4745767941b8f4
Stackoverflow Stackexchange Q: NuGet Error: SecureChannelFailure (Object refence not set to an instance of an object) I'm using Monodevelop on ubuntu and it seems as though the NuGet package manager extension is not working. When I check the sources I get the following error for https://api.nuget.org/v3/index.json Error: SecureChannelFailure (Object refence not set to an instance of an object) I've installed via flatpak.
Q: NuGet Error: SecureChannelFailure (Object refence not set to an instance of an object) I'm using Monodevelop on ubuntu and it seems as though the NuGet package manager extension is not working. When I check the sources I get the following error for https://api.nuget.org/v3/index.json Error: SecureChannelFailure (Object refence not set to an instance of an object) I've installed via flatpak.
stackoverflow
{ "language": "en", "length": 60, "provenance": "stackexchange_0000F.jsonl.gz:903869", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663831" }
6df19c7448dabc413c48c2deb3d7cbcc15461677
Stackoverflow Stackexchange Q: What is "parent element" of ggplot2? R, ggplot2 question. ?ggplot2::rel() says rel() is used to specify sizes relative to the parent. What is the "parent" exactly? For example, I'd love to set the size of my plot title to rel(5). What is the width of my title in inches exactly? I noticed there are two "units" that I believe somehow are used as a relevant size in ggplot2, .pt. I think there is some relation between rel() and .pt. .pt equals to 2.845276. Why?? And 2.845276 of what? Pixels? A: The parents are defined in help("theme"). Note how for most arguments the documentation says "inherits from ...". This is object oriented programming. E.g., axis.text is the parent of axis.text.x: library(ggplot2) library(gridExtra) DF <- data.frame(x = 1, y = 2) p1 <- ggplot(DF, aes(x, y)) + geom_point() p2 <- p1 + theme(axis.text.x = element_text(size = rel(2))) p3 <- p2 + theme(axis.text = element_text(size = 5)) grid.arrange(p1, p2, p3, ncol = 1)
Q: What is "parent element" of ggplot2? R, ggplot2 question. ?ggplot2::rel() says rel() is used to specify sizes relative to the parent. What is the "parent" exactly? For example, I'd love to set the size of my plot title to rel(5). What is the width of my title in inches exactly? I noticed there are two "units" that I believe somehow are used as a relevant size in ggplot2, .pt. I think there is some relation between rel() and .pt. .pt equals to 2.845276. Why?? And 2.845276 of what? Pixels? A: The parents are defined in help("theme"). Note how for most arguments the documentation says "inherits from ...". This is object oriented programming. E.g., axis.text is the parent of axis.text.x: library(ggplot2) library(gridExtra) DF <- data.frame(x = 1, y = 2) p1 <- ggplot(DF, aes(x, y)) + geom_point() p2 <- p1 + theme(axis.text.x = element_text(size = rel(2))) p3 <- p2 + theme(axis.text = element_text(size = 5)) grid.arrange(p1, p2, p3, ncol = 1) A: The parent element is the graph itself as drawn by the current theme. You can use rel()to scale anything relative to the parent object which is not a part of the data (titles, axes and such). It is specifically used to scale things relative to the rest of the theme for the current plot. As you might expect with rel being short for relative, there is no absolute size for it, not inches or centimeters. But you can use it to scale your plot's title as follows: g + theme(plot.title = element_text(size = rel(5))) Where g is the plot you are adding things onto. This tells ggplot to scale the text in your plot title to scale it up 5 relative to rest of the theme. You can also scale it down using decimals. The numbers are a bit weird, like with line sizes or glyph sizes, the best thing is to try a few to see what gets you closest to where you want to be! A: with regards 2.845276, all.equal(convertUnit(unit(1,"mm"),"pt", valueOnly = TRUE), ggplot2::.pt)
stackoverflow
{ "language": "en", "length": 338, "provenance": "stackexchange_0000F.jsonl.gz:903894", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44663915" }
cdd45b1b060e6996640e939849bd058633ff9bf2
Stackoverflow Stackexchange Q: Access Cassandra from separate docker container using docker-compose I am trying to connect to a cassandra container from a separate container (named main). This is my docker-compose.yml version: '3.2' services: main: build: context: . image: main-container:latest depends_on: - cassandra links: - cassandra stdin_open: true tty: true cassandra: build: context: . dockerfile: Dockerfile-cassandra ports: - "9042:9042" - "9160:9160" image: "customer-core-cassandra:latest" Once I run this using docker-compose up, I run this command: docker-compose exec main cqlsh cassandra 9042 but I get this error: Connection error: ('Unable to connect to any servers', {'172.18.0.2': error(111, "Tried connecting to [('172.18.0.2', 9042)]. Last error: Connection refused")}) A: I figured out the answer. Basically, in the cassandra.yaml file it sets the default rpc_address to localhost. If this is the case, Cassandra will only listen for requests on localhost, and will not allow connections from anywhere else. In order to change this, I had to set rpc_address to my "cassandra" container so my main container (and any other containers) could access Cassandra using the cassandra container ip address. rpc_address: cassandra
Q: Access Cassandra from separate docker container using docker-compose I am trying to connect to a cassandra container from a separate container (named main). This is my docker-compose.yml version: '3.2' services: main: build: context: . image: main-container:latest depends_on: - cassandra links: - cassandra stdin_open: true tty: true cassandra: build: context: . dockerfile: Dockerfile-cassandra ports: - "9042:9042" - "9160:9160" image: "customer-core-cassandra:latest" Once I run this using docker-compose up, I run this command: docker-compose exec main cqlsh cassandra 9042 but I get this error: Connection error: ('Unable to connect to any servers', {'172.18.0.2': error(111, "Tried connecting to [('172.18.0.2', 9042)]. Last error: Connection refused")}) A: I figured out the answer. Basically, in the cassandra.yaml file it sets the default rpc_address to localhost. If this is the case, Cassandra will only listen for requests on localhost, and will not allow connections from anywhere else. In order to change this, I had to set rpc_address to my "cassandra" container so my main container (and any other containers) could access Cassandra using the cassandra container ip address. rpc_address: cassandra
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:903932", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664028" }
958ca4f431b2a9943c5069bca94cf9cdcd186a91
Stackoverflow Stackexchange Q: Favicon not showing up in Google Chrome browser For some reason my favicon is not showing up on my chrome tab. From all the articles I have read I am writing the code correctly. It does work in Firefox. I also cleared my cache and tried an incognito window and am still not seeing it. When I go to: localhost:8080/favicon.ico I do see the favicon. Here is my code within the HTML header: <link rel="shortcut icon" sizes="16x16 32x32 64x64" href="/favicon.ico" type="image/x-icon" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="apple-touch-icon" href="apple-touch-icon.png" /> Any help would be appreciated! Thanks! A: Try doing a favicon cache reset as explained in #3 here *FAVICON CACHE RESET A more drastic way to solve the problem, but that allows you to do it globally rather than site-by-site, is to clear the browser’s favicon cache. The procedure is: * *on Mac: delete the following file ${user.home}/Library/Application Support/Google/Chrome/Default/Favicons *on Windows: delete Favicons-journal and Favicons files from the following location C:\Users\nomeutente\AppData\Local\Google\Chrome\User Data\Default In both cases, a browser restart is suggested.
Q: Favicon not showing up in Google Chrome browser For some reason my favicon is not showing up on my chrome tab. From all the articles I have read I am writing the code correctly. It does work in Firefox. I also cleared my cache and tried an incognito window and am still not seeing it. When I go to: localhost:8080/favicon.ico I do see the favicon. Here is my code within the HTML header: <link rel="shortcut icon" sizes="16x16 32x32 64x64" href="/favicon.ico" type="image/x-icon" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="apple-touch-icon" href="apple-touch-icon.png" /> Any help would be appreciated! Thanks! A: Try doing a favicon cache reset as explained in #3 here *FAVICON CACHE RESET A more drastic way to solve the problem, but that allows you to do it globally rather than site-by-site, is to clear the browser’s favicon cache. The procedure is: * *on Mac: delete the following file ${user.home}/Library/Application Support/Google/Chrome/Default/Favicons *on Windows: delete Favicons-journal and Favicons files from the following location C:\Users\nomeutente\AppData\Local\Google\Chrome\User Data\Default In both cases, a browser restart is suggested. A: You should link your favicon.ico like below: <link rel="icon" href="wherever/your_icon/is?v=1.0" /> The thing is that, chrome could not find it for the first time and now it's assuming you don't have one as it renders from cache. The ?v=1.0 part makes sure that chrome loads it again. A: right-click on file (the favicon), go to properties, look towards the bottom and you will see attributes and the option to unblock the file, and unblock it. Worked immediately with browser-sync Blind luck, I wasn't even expecting it to be there. A: I am not sure why you have all of that extra icon formatting that isn't really needed. My icons only look like this: <link rel="icon" href="favicon.ico">. I would suggest you try that (unless the rest is absolutely needed). Also, it is possible that it just isn't loading properly. Whenever I set up my icons, depending on what I do it on (server or by clicking on index.html file), sometimes I have to reload it a few times. A: I have same issue. I have tried most suggestions, including; changing icon name, deleting chrome's local favicons file, ico and png formats, clearing cache. No joy with any of these attempts to fix. I have 2 projects with same header and it works with 1 icon but not the other? It works in IE but will not work in chrome. I'm convinced it is to do with the Chrome Favicons-journal but not sure how to prove it. Will reinstall Chrome and see how that goes :( A: I had tried a lot different things. My 1 machine kept showing them wrong, but they were fine on all my other machines. I even deleted my entire: C:\Users\\AppData\Local\Google\Chrome\User Data Folder and copied one from a working machine. When I first launched Chrome, they were fine... but went bad again soon after. Then I noticed that every time I'd launch a bookmark from Chrome on my Android phone, the icon on my bad machine would come back. But it seemed like I first needed to click on the bad bookmark, then navigate elsewhere, before it updated my bad machine (not 100% sure of this). So anyway, I just went through all my bad bookmarks through my phone, and they all came back on my bad machine. Now, I'm almost certain I had tried the same process from a good PC, but didn't work. Again, I'm not 100% certain of this. Hopefully, this can be tested with others.
stackoverflow
{ "language": "en", "length": 585, "provenance": "stackexchange_0000F.jsonl.gz:903954", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664111" }
591936e281a05feeedae6fa0ec88968124f8ac26
Stackoverflow Stackexchange Q: Python numpy unwrap function I am hoping to convert a array of radians into range [0, 2*pi) and numpy unwrap function is exactly what I need However, when I run the following code to input a = [pi, 2*pi, 3*pi]: import numpy as np a = np.array([np.pi, 2*np.pi, 3*np.pi]) np.unwrap(a) I expect the results to be close to [pi, 0, pi]. However, the output is still: array([ 3.14159265, 6.28318531, 9.42477796]) It is not unwrapped. However, if I instead run the following without using the numpy.pi a = np.array([3.14159265, 6.28318531, 9.42477796]) np.unwrap(a) The output is correct: array([ 3.14159265e+00, 2.82041412e-09, 3.14159265e+00]) what is going on? A: Taken from np.unwrap docs: Unwrap radian phase p by changing absolute jumps greater than discont to their 2*pi complement along the given axis. Where discont = np.pi (by default). When a = np.array([np.pi, 2*np.pi, 3*np.pi]) The jumps a[1] - a[0] = np.pi and a[2] - a[1] = np.pi are not greater than np.pi and therefore not 'unwraped'. However, if a = np.array([3.14159265, 6.28318531, 9.42477796]) you have a[1] - a[0] = 3.1415926600000001 greater than np.pi, thus the function unwraps the values.
Q: Python numpy unwrap function I am hoping to convert a array of radians into range [0, 2*pi) and numpy unwrap function is exactly what I need However, when I run the following code to input a = [pi, 2*pi, 3*pi]: import numpy as np a = np.array([np.pi, 2*np.pi, 3*np.pi]) np.unwrap(a) I expect the results to be close to [pi, 0, pi]. However, the output is still: array([ 3.14159265, 6.28318531, 9.42477796]) It is not unwrapped. However, if I instead run the following without using the numpy.pi a = np.array([3.14159265, 6.28318531, 9.42477796]) np.unwrap(a) The output is correct: array([ 3.14159265e+00, 2.82041412e-09, 3.14159265e+00]) what is going on? A: Taken from np.unwrap docs: Unwrap radian phase p by changing absolute jumps greater than discont to their 2*pi complement along the given axis. Where discont = np.pi (by default). When a = np.array([np.pi, 2*np.pi, 3*np.pi]) The jumps a[1] - a[0] = np.pi and a[2] - a[1] = np.pi are not greater than np.pi and therefore not 'unwraped'. However, if a = np.array([3.14159265, 6.28318531, 9.42477796]) you have a[1] - a[0] = 3.1415926600000001 greater than np.pi, thus the function unwraps the values. A: Although the accepted answer gives you the result you want, I don't think it gets to the heart of the problem which, if I'm interpreting your question correctly, is that you actually want wrap your phase, not unwrap it. The reason np.unwrap works in this case, with small changes to your data, is actually a consequence of the naive way that np.unwrap computes its result; it simply looks for local discontinuities in your data and adjusts accordingly. Getting the result you're looking for in this way is a result of sampling errors. In other words, if you improve your sampling by interpolating to get a = np.array([np.pi, 3*np.pi/2, 2*np.pi, 5*np.pi/2, 3*np.pi]), adjusting the data won't work any more. A more sophisticated method of phase unwrapping, such as a Fourier transform method, will leave your data unwrapped, even if the sampling is poor. If you really want to constrain your data to [0, 2*pi), np.unwrap is the inverse of what you want. The simplest way I can think of to wrap your phase is with the modulo operator: import numpy as np a = np.array([np.pi, 2 * np.pi, 3 * np.pi]) a_wrapped = a % (2 * np.pi) print (a_wrapped) Of course, because of the sampling errors, np.unwrap(a_wrapped) does not return your original a, so it may not be clear that this is the inverse. However, if you improve your sampling, it does indeed return the original a: import numpy as np a = np.arange(0, 4 * np.pi, np.pi/10) print (a) a_wrapped = a % (2 * np.pi) print (a_wrapped) a = np.unwrap(a_wrapped) print (a) A: There seems to be a rounding issue. The two test cases are not the same. a = np.array([np.pi, 2*np.pi, 3*np.pi]) a1 = np.array([3.14159265, 6.28318531, 9.42477796]) print('a ', ', '.join([str(i) for i in a])) print('a1', ', '.join([str(i) for i in a1])) a 3.14159265359, 6.28318530718, 9.42477796077 a1 3.14159265, 6.28318531, 9.42477796
stackoverflow
{ "language": "en", "length": 499, "provenance": "stackexchange_0000F.jsonl.gz:903956", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664116" }
183f5b5e94367af55f10d93c4e59bc02e5b82932
Stackoverflow Stackexchange Q: Merge data from multiple tables in RDS to export to Redshift using AWS DMS I am setting up a continuous replication from RDS to Redshift using AWS DMS, as suggested here. My usecase requires me to combine data from multiple RDS tables to export to Redshift. For eg. RDS has Tables School, Student, District. I want to export data like:- select sch.Name, stu.Name, dis.Name from School sch inner join Student stu on stu.schoolid = sch.id inner join District dis on dis.id = sch.districtid; So, I want to select columns from multiple tables and export to a single Redshift table. Is selection from multiple tables possible using AWS DMS?
Q: Merge data from multiple tables in RDS to export to Redshift using AWS DMS I am setting up a continuous replication from RDS to Redshift using AWS DMS, as suggested here. My usecase requires me to combine data from multiple RDS tables to export to Redshift. For eg. RDS has Tables School, Student, District. I want to export data like:- select sch.Name, stu.Name, dis.Name from School sch inner join Student stu on stu.schoolid = sch.id inner join District dis on dis.id = sch.districtid; So, I want to select columns from multiple tables and export to a single Redshift table. Is selection from multiple tables possible using AWS DMS?
stackoverflow
{ "language": "en", "length": 109, "provenance": "stackexchange_0000F.jsonl.gz:903963", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664139" }
a43a6655ab9ca424f9d2625c9693c9af6dcbf40d
Stackoverflow Stackexchange Q: Swashbuckle: Multiple [SwaggerResponse] with the same status code but different description/model I'm writing a demonstration shopping cart API and I've come across a situation where I can return NotFound for multiple reasons (either a cart item isn't found or the cart itself is not found). I want to return a Swagger description for both cases. I've tried this but it doesn't work. [SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(CartNotFoundResponse), Description = "Cart not found (code=1)")] [SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(ItemNotFoundResponse), Description = "Item not found (code=104)")] [SwaggerResponse(HttpStatusCode.NoContent)] public async Task<IHttpActionResult> DeleteItemWithSKUAsync(Guid cartId, string sku) { } Any suggestions? A: Unfortunately that is not possible with the current implementation: https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Swagger/SwaggerDocument.cs#L29 As you can see the responses is a dictionary and the key is the StatusCode. My recommendation: use a more generic class that can cover both of you cases (CartNotFound & ItemNotFound)
Q: Swashbuckle: Multiple [SwaggerResponse] with the same status code but different description/model I'm writing a demonstration shopping cart API and I've come across a situation where I can return NotFound for multiple reasons (either a cart item isn't found or the cart itself is not found). I want to return a Swagger description for both cases. I've tried this but it doesn't work. [SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(CartNotFoundResponse), Description = "Cart not found (code=1)")] [SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(ItemNotFoundResponse), Description = "Item not found (code=104)")] [SwaggerResponse(HttpStatusCode.NoContent)] public async Task<IHttpActionResult> DeleteItemWithSKUAsync(Guid cartId, string sku) { } Any suggestions? A: Unfortunately that is not possible with the current implementation: https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Swagger/SwaggerDocument.cs#L29 As you can see the responses is a dictionary and the key is the StatusCode. My recommendation: use a more generic class that can cover both of you cases (CartNotFound & ItemNotFound) A: Consider not caring about: * *The cart not being found; *The item not being found or already being deleted. Just respond with a NoContent whether or not you actually deleted something or not. If it is not there, it is not there, which is exactly what you wanted to happen. Why do I advice to do this? Because it makes your API less complex and it keeps you from having to think about the situation where either the cart or the cart item is not there at all. But what if my DB throws when I try to delete something that is not there? Just catch that and pretend you deleted it. Make your API respond with NoContent, because there really is no content.
stackoverflow
{ "language": "en", "length": 263, "provenance": "stackexchange_0000F.jsonl.gz:903979", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664174" }
18cf36bd4856baf6e2c706221fb1c9da5e325f19
Stackoverflow Stackexchange Q: Vue.js label for an input element inside loop How would you set up the input id and the label for on repeated input elements so they are unique, using Vue.js v2. <section class="section" v-for="(section, i) in sections"> <div class="fields"> <fieldset> <input type="checkbox" id="" name="example-a" v-model="section.ex-a"> <label for="">Example A</label> </fieldset> <fieldset> <label for="">Example B</label> <input type="text" id="" name="example-b" v-model="section.ex-b"> </fieldset> <fieldset> <label for="">Example C</label> <input type="text" id="" name="example-c" v-model="section.ex-c"> </fieldset> </div> </section> I want to be able to click on the label element and have it select the input field. A: You can use :id="" and :for="". You would need to add a js string interpolation to create a unique id from the section and index information. For example: <div class="fields"> <fieldset> <input type="checkbox" :id="'section'+i+'example-a'" name="example-a" v-model="section.ex-a"> <label :for="'section'+i+'example-a'">Example A</label> </fieldset> <fieldset> <label for="'section'+i+'example-b'">Example B</label> <input type="text" :id="'section'+i+'example-b'" name="example-b" v-model="section.ex-b"> </fieldset> <fieldset> <label :for="'section'+i+'example-c'">Example C</label> <input type="text" :id="'section'+i+'example-c'" name="example-c" v-model="section.ex-c"> </fieldset> </div> For example, for the first fieldset the binding :id="'section'+i+'example-a'" will render id="section-0-example-a" as its interpolating 'section' + the index of the array + 'example-a'
Q: Vue.js label for an input element inside loop How would you set up the input id and the label for on repeated input elements so they are unique, using Vue.js v2. <section class="section" v-for="(section, i) in sections"> <div class="fields"> <fieldset> <input type="checkbox" id="" name="example-a" v-model="section.ex-a"> <label for="">Example A</label> </fieldset> <fieldset> <label for="">Example B</label> <input type="text" id="" name="example-b" v-model="section.ex-b"> </fieldset> <fieldset> <label for="">Example C</label> <input type="text" id="" name="example-c" v-model="section.ex-c"> </fieldset> </div> </section> I want to be able to click on the label element and have it select the input field. A: You can use :id="" and :for="". You would need to add a js string interpolation to create a unique id from the section and index information. For example: <div class="fields"> <fieldset> <input type="checkbox" :id="'section'+i+'example-a'" name="example-a" v-model="section.ex-a"> <label :for="'section'+i+'example-a'">Example A</label> </fieldset> <fieldset> <label for="'section'+i+'example-b'">Example B</label> <input type="text" :id="'section'+i+'example-b'" name="example-b" v-model="section.ex-b"> </fieldset> <fieldset> <label :for="'section'+i+'example-c'">Example C</label> <input type="text" :id="'section'+i+'example-c'" name="example-c" v-model="section.ex-c"> </fieldset> </div> For example, for the first fieldset the binding :id="'section'+i+'example-a'" will render id="section-0-example-a" as its interpolating 'section' + the index of the array + 'example-a'
stackoverflow
{ "language": "en", "length": 176, "provenance": "stackexchange_0000F.jsonl.gz:903994", "question_score": "20", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664208" }
30ff709c3dca9e43c1ddae44dd025e692d64f7d7
Stackoverflow Stackexchange Q: IO.puts vs IO.inspect It seems to me that IO.puts and IO.inspect are both used to print to the console. What is the difference between them? A: Reading through the Elixir docs, it looks like IO.puts/2 is simply going to write and append a newline. IO.inspect/2 will do the same thing, but it also returns the first value unchanged (so it's chainable), enables pretty printing/decoration and other formatting options. * *https://hexdocs.pm/elixir/IO.html#inspect/2 *https://hexdocs.pm/elixir/IO.html#print/2 Friendly reminder that hexdocs can be really awesome. I was able to easily find the answer to your question and learn the differences myself. I highly encourage you to read through modules you normally use to discover other functions you might not know about that you could be benefitting from.
Q: IO.puts vs IO.inspect It seems to me that IO.puts and IO.inspect are both used to print to the console. What is the difference between them? A: Reading through the Elixir docs, it looks like IO.puts/2 is simply going to write and append a newline. IO.inspect/2 will do the same thing, but it also returns the first value unchanged (so it's chainable), enables pretty printing/decoration and other formatting options. * *https://hexdocs.pm/elixir/IO.html#inspect/2 *https://hexdocs.pm/elixir/IO.html#print/2 Friendly reminder that hexdocs can be really awesome. I was able to easily find the answer to your question and learn the differences myself. I highly encourage you to read through modules you normally use to discover other functions you might not know about that you could be benefitting from. A: Adding to the previous answer, IO.inspect can print an arbitrary elixir term, with an optional keyword list containing a label: and values for initializing an Inspect.Opts struct: @spec inspect(item, Keyword.t) :: item when item: var IO.puts requires the argument to be either a string, or a struct that implements the String.Chars protocol: @spec puts(device, chardata | String.Chars.t) :: :ok
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:904001", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664230" }
8f76a22883f5b234b41f78c8265e3e9efc19f61a
Stackoverflow Stackexchange Q: python dictionary: How to get all keys with specific values Is it possible to get all keys in a dictionary with values above a threshold? A dictionary could look like: mydict = {(0,1,2): "16", (2,3,4): "19"} The threshold could be 17 for example. A: Of course it is possible. We can simply write: [k for k,v in mydict.items() if float(v) >= 17] Or in the case you work with python-2.7, you - like @NoticeMeSenpai says - better use: [k for k,v in mydict.iteritems() if float(v) >= 17] This is a list comprehension. We iterate through the key-value pairs in the mydict dictionary. Next we convert the value v into a float(v) and check if that float is greater than or equal to 17. If that is the case, we add the key k to the list. For your given mydict, this generates: >>> [k for k,v in mydict.items() if float(v) >= 17] [(2, 3, 4)] So a list containing the single key that satisfied the condition here: (2,3,4).
Q: python dictionary: How to get all keys with specific values Is it possible to get all keys in a dictionary with values above a threshold? A dictionary could look like: mydict = {(0,1,2): "16", (2,3,4): "19"} The threshold could be 17 for example. A: Of course it is possible. We can simply write: [k for k,v in mydict.items() if float(v) >= 17] Or in the case you work with python-2.7, you - like @NoticeMeSenpai says - better use: [k for k,v in mydict.iteritems() if float(v) >= 17] This is a list comprehension. We iterate through the key-value pairs in the mydict dictionary. Next we convert the value v into a float(v) and check if that float is greater than or equal to 17. If that is the case, we add the key k to the list. For your given mydict, this generates: >>> [k for k,v in mydict.items() if float(v) >= 17] [(2, 3, 4)] So a list containing the single key that satisfied the condition here: (2,3,4). A: One can use filter() function here. list(filter(lambda k: float(mydict[k]) >= 17, mydict)) Another even more convoluted way is to create boolean selectors and compress similar to how boolean indexing works in pandas/numpy. # using built-in methods from itertools import compress, repeat import operator list(compress(mydict, map(operator.ge, map(float, mydict.values()), repeat(17)))) # or using a lambda list(compress(mydict, map(lambda x: float(x) >= 17, mydict.values()))) Speaking of pandas/numpy, if you need to filter keys by values repeatedly, pandas Series or numpy array is a useful data type to store the data in, so that this kind of filtering can be done vectorially in a more efficient way. Using pandas Series: import pandas as pd my_srs = pd.Series(mydict).astype(int) my_srs.index[my_srs >= 17].tolist() Using numpy arrays (will have to create two arrays, one for the keys and another for the values and use the values array to filter the keys array): import numpy as np keys = np.array(list(mydict.keys()), dtype=object) values = np.array(list(mydict.values()), dtype=float) keys[values >= 17].tolist() Using numpy structured array: import numpy as np arr = np.array(list(mydict.items()), dtype=[('keys', object), ('values', int)]) arr['keys'][arr['values'] >= 17]
stackoverflow
{ "language": "en", "length": 346, "provenance": "stackexchange_0000F.jsonl.gz:904008", "question_score": "25", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664247" }
1cbdcb453eec0f12c16db5303662f1457a4d3534
Stackoverflow Stackexchange Q: Calculate hmac value with base64 encode using sha256 python I'm trying to transform a php code into python language. the php function calculates the hmac value using sha256 and base64 encoding. My Php function: <?php define('SHOPIFY_APP_SECRET', 'some_key'); function verify_webhook($data) { $calculated_hmac = base64_encode(hash_hmac('sha256', $data, SHOPIFY_APP_SECRET, true)); echo $calculated_hmac; } $data = "some_data"; $verified = verify_webhook($data); ?> My Python function: import base64 import hmac import binascii from hashlib import sha256 API_SECRET_KEY = "some_key" data = "some_data" def verify_webhook(): dig = hmac.new( API_SECRET_KEY, msg=data, digestmod=sha256 ).digest() calculated_hmac = base64.b64encode(bytes(binascii.hexlify(dig))) print(calculated_hmac) verify_webhook() I got different outputs even I have the same key and data. I still don't know what I'm missing here. please help! Python output: YWM3NjlhMDZjMmViMzdmM2E3YjhiZGY4NjhkNTZhOGZhMDgzZDM4MGM1OTkyZTM4YjA5MDNkMDEwNGEwMzJjMA== Php output: N7JyAyKocoDx/Opx36nGqAuUKdyGH+ROX+J5AJgQ+/g= A: I was able to match your php output using Python 3: >>> dig = hmac.new( bytes(API_SECRET_KEY,'ascii'), msg=bytes(data, 'ascii'), digestmod=sha256 ) >>> dig.digest() b'7\xb2r\x03"\xa8r\x80\xf1\xfc\xeaq\xdf\xa9\xc6\xa8\x0b\x94)\xdc\x86\x1f\xe4N_\xe2y\x00\x98\x10\xfb\xf8' >>> base64.b64encode(dig.digest()) b'N7JyAyKocoDx/Opx36nGqAuUKdyGH+ROX+J5AJgQ+/g='
Q: Calculate hmac value with base64 encode using sha256 python I'm trying to transform a php code into python language. the php function calculates the hmac value using sha256 and base64 encoding. My Php function: <?php define('SHOPIFY_APP_SECRET', 'some_key'); function verify_webhook($data) { $calculated_hmac = base64_encode(hash_hmac('sha256', $data, SHOPIFY_APP_SECRET, true)); echo $calculated_hmac; } $data = "some_data"; $verified = verify_webhook($data); ?> My Python function: import base64 import hmac import binascii from hashlib import sha256 API_SECRET_KEY = "some_key" data = "some_data" def verify_webhook(): dig = hmac.new( API_SECRET_KEY, msg=data, digestmod=sha256 ).digest() calculated_hmac = base64.b64encode(bytes(binascii.hexlify(dig))) print(calculated_hmac) verify_webhook() I got different outputs even I have the same key and data. I still don't know what I'm missing here. please help! Python output: YWM3NjlhMDZjMmViMzdmM2E3YjhiZGY4NjhkNTZhOGZhMDgzZDM4MGM1OTkyZTM4YjA5MDNkMDEwNGEwMzJjMA== Php output: N7JyAyKocoDx/Opx36nGqAuUKdyGH+ROX+J5AJgQ+/g= A: I was able to match your php output using Python 3: >>> dig = hmac.new( bytes(API_SECRET_KEY,'ascii'), msg=bytes(data, 'ascii'), digestmod=sha256 ) >>> dig.digest() b'7\xb2r\x03"\xa8r\x80\xf1\xfc\xeaq\xdf\xa9\xc6\xa8\x0b\x94)\xdc\x86\x1f\xe4N_\xe2y\x00\x98\x10\xfb\xf8' >>> base64.b64encode(dig.digest()) b'N7JyAyKocoDx/Opx36nGqAuUKdyGH+ROX+J5AJgQ+/g='
stackoverflow
{ "language": "en", "length": 145, "provenance": "stackexchange_0000F.jsonl.gz:904013", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664267" }
61a152a29525d2e4106725757b8c99710fbaef13
Stackoverflow Stackexchange Q: What are the constraints for tensorflow scope names? I'm running a tensorflow model and getting the following error: ValueError: 'Cement (component 1)(kg in a m^3 mixture)' is not a valid scope name. I get that tensorflow probably doesn't like special chars and spaces in its scope names, but I'm trying to find an actual doc on what chars are allowed. Does anyone know where I could find this? A: From the TF source: NOTE: This constructor validates the given name. Valid scope names match one of the following regular expressions: [A-Za-z0-9.][A-Za-z0-9_.\\-/]* (for scopes at the root) [A-Za-z0-9_.\\-/]* (for other scopes)
Q: What are the constraints for tensorflow scope names? I'm running a tensorflow model and getting the following error: ValueError: 'Cement (component 1)(kg in a m^3 mixture)' is not a valid scope name. I get that tensorflow probably doesn't like special chars and spaces in its scope names, but I'm trying to find an actual doc on what chars are allowed. Does anyone know where I could find this? A: From the TF source: NOTE: This constructor validates the given name. Valid scope names match one of the following regular expressions: [A-Za-z0-9.][A-Za-z0-9_.\\-/]* (for scopes at the root) [A-Za-z0-9_.\\-/]* (for other scopes) A: do not give space between the name example here name = 'name of model' here you have given space that is why this model gives this error if you put name = 'name_of_model' it will not give you this error
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:904022", "question_score": "26", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664285" }
7dd3245ec00573e92115ec1f5564ec3e3082bbb3
Stackoverflow Stackexchange Q: SDL_KEYDOWN triggering twice I am following lazy foo's tutorial, however I realized every time I press press s or p, SDL_KEYDOWNtriggers twice. How can this be fixed? Here is the code snippet: while(SDL_PollEvent(&e) != 0) { if(e.type == SDL_QUIT) { quit = true; } else if(e.type == SDL_KEYDOWN) { if(e.key.keysym.sym == SDLK_s) { if(timer.isStarted()) { timer.stop(); printf("stop\n"); } else { timer.start(); printf("start\n"); } } else if(e.key.keysym.sym == SDLK_p) { if(timer.isPaused()) { timer.unpause(); printf("unpause\n"); } else { timer.pause(); printf("pause\n"); } } } } Pressing s once: start stop A: TL;DR: Check if e.key.repeat equals to 0 before handling the events. SDL generates fake repeated keypresses if you hold a key long enough. This is used mostly for text input. The original key press has .repeat == 0, and fake presses have .repeat == 1. For convenience reasons probably (I'd argue that it's rather inconvenient), since SDL 2.0.5 the actual key press generates two events instead of one. One has .repeat set to 0, and other (new) one has it set to 1.
Q: SDL_KEYDOWN triggering twice I am following lazy foo's tutorial, however I realized every time I press press s or p, SDL_KEYDOWNtriggers twice. How can this be fixed? Here is the code snippet: while(SDL_PollEvent(&e) != 0) { if(e.type == SDL_QUIT) { quit = true; } else if(e.type == SDL_KEYDOWN) { if(e.key.keysym.sym == SDLK_s) { if(timer.isStarted()) { timer.stop(); printf("stop\n"); } else { timer.start(); printf("start\n"); } } else if(e.key.keysym.sym == SDLK_p) { if(timer.isPaused()) { timer.unpause(); printf("unpause\n"); } else { timer.pause(); printf("pause\n"); } } } } Pressing s once: start stop A: TL;DR: Check if e.key.repeat equals to 0 before handling the events. SDL generates fake repeated keypresses if you hold a key long enough. This is used mostly for text input. The original key press has .repeat == 0, and fake presses have .repeat == 1. For convenience reasons probably (I'd argue that it's rather inconvenient), since SDL 2.0.5 the actual key press generates two events instead of one. One has .repeat set to 0, and other (new) one has it set to 1.
stackoverflow
{ "language": "en", "length": 172, "provenance": "stackexchange_0000F.jsonl.gz:904038", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664331" }
aee27ed9e66666e1961a5c4bd9c0600b8785b2c2
Stackoverflow Stackexchange Q: How to click on span element with python selenium Im trying to click on this for whole day with python selenium with no luck, tried several selectors, xpath..nothing seems to be work for me. This is the element I try to click on: <span style="vertical-align: middle;">No</span> Here is my obviously non function code driver.find_element_by_link_text("No") A: Search by link text can help you only if your span is a child of anchor tag, e.g. <a><span style="vertical-align: middle;">No</span></a>. As you're trying to click it, I believe it's really inside an anchor, but if not I'd suggest you to use XPath with predicate that returns True only if exact text content matched: //span[text()="No"] Note that //span[contains(text(), "No")] is quite unreliable solution as it will return span elements with text * *"November rain" *"Yes. No." *"I think Chuck Norris can help you" etc... If you get NoSuchElementException you might need to wait for element to appear in DOM: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait as wait wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='No']"))).click()
Q: How to click on span element with python selenium Im trying to click on this for whole day with python selenium with no luck, tried several selectors, xpath..nothing seems to be work for me. This is the element I try to click on: <span style="vertical-align: middle;">No</span> Here is my obviously non function code driver.find_element_by_link_text("No") A: Search by link text can help you only if your span is a child of anchor tag, e.g. <a><span style="vertical-align: middle;">No</span></a>. As you're trying to click it, I believe it's really inside an anchor, but if not I'd suggest you to use XPath with predicate that returns True only if exact text content matched: //span[text()="No"] Note that //span[contains(text(), "No")] is quite unreliable solution as it will return span elements with text * *"November rain" *"Yes. No." *"I think Chuck Norris can help you" etc... If you get NoSuchElementException you might need to wait for element to appear in DOM: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait as wait wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='No']"))).click() A: I was doing something in my project too for Spotify. This is the function I wrote to select genders which are in span html tags. Libraries Required from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import random Defining Variables gender_male = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Male']"))) gender_female = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Female']"))) non_binary = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Non-binary']"))) other = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Other']"))) pnts = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Prefer not to say']"))) Using Random gender_guess = random.randint(1, 5) if gender_guess == 1: gender_male.click() elif gender_guess == 2: gender_female.click() elif gender_guess == 3: non_binary.click() elif gender_guess == 4: other.click() elif gender_guess == 5: pnts.click() Full Code from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC gender_male = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Male']"))) gender_female = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Female']"))) non_binary = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Non-binary']"))) other = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Other']"))) pnts = wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Prefer not to say']"))) gender_guess = random.randint(1, 5) if gender_guess == 1: gender_male.click() elif gender_guess == 2: gender_female.click() elif gender_guess == 3: non_binary.click() elif gender_guess == 4: other.click() elif gender_guess == 5: pnts.click() Hopefully this helped.
stackoverflow
{ "language": "en", "length": 353, "provenance": "stackexchange_0000F.jsonl.gz:904065", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664434" }
815470a08b97b61fd040a852f6e86c4464a212e8
Stackoverflow Stackexchange Q: "Atomic increment" with CloudKit I want to implement a counter using CloudKit. Let's say I have a field called count of type Int(64). How can I go about implementing this counter so that multiple users can increment it at the same time? If multiple users increment this counter at the same time, my CKModifyRecordsOperation might fail because of the conflict. I could take this failure and recursively try to save my record, but this doesn't work at scale. In 2011, Parse launched a simple solution called atomic increment. You could write code like this and not worry about multiple users creating conflicting values: [gameScore incrementKey:@"score" byAmount:[NSNumber numberWithInt:10]. (That post here) How can I do this with CloudKit? A: I don't believe CloudKit has similar atomic increment functionality built in. But a similar effect can be achieved by setting savePolicy on the CKModifyRecordsOperation to ifServerRecordUnchanged and checking for a serverRecordChanged error (docs). There is an existing answer here to a slightly different question: Increment field value in a CKRecord variable without fetching?
Q: "Atomic increment" with CloudKit I want to implement a counter using CloudKit. Let's say I have a field called count of type Int(64). How can I go about implementing this counter so that multiple users can increment it at the same time? If multiple users increment this counter at the same time, my CKModifyRecordsOperation might fail because of the conflict. I could take this failure and recursively try to save my record, but this doesn't work at scale. In 2011, Parse launched a simple solution called atomic increment. You could write code like this and not worry about multiple users creating conflicting values: [gameScore incrementKey:@"score" byAmount:[NSNumber numberWithInt:10]. (That post here) How can I do this with CloudKit? A: I don't believe CloudKit has similar atomic increment functionality built in. But a similar effect can be achieved by setting savePolicy on the CKModifyRecordsOperation to ifServerRecordUnchanged and checking for a serverRecordChanged error (docs). There is an existing answer here to a slightly different question: Increment field value in a CKRecord variable without fetching?
stackoverflow
{ "language": "en", "length": 172, "provenance": "stackexchange_0000F.jsonl.gz:904140", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664664" }
e0eeb8d42ca177e05be9adaa8f03b83b4ca35055
Stackoverflow Stackexchange Q: What's the difference between extern fn and extern "C" fn in Rust? I've tried reading various github issues trying to track down what the difference is and just ended up confused. #[no_mangle] pub extern fn foo() { ... } vs. #[no_mangle] pub extern "C" fn foo() { ... } A: There is no difference because, as the reference says: By default external blocks assume that the library they are calling uses the standard C ABI on the specific platform. extern "C" -- This is the same as extern fn foo(); whatever the default your C compiler supports. An issue was created to always require explicitly stating extern "C" but the RFC has been refused. There is an issue in fmt-rfcs about "should we format extern "C" fn as that or extern fn?".
Q: What's the difference between extern fn and extern "C" fn in Rust? I've tried reading various github issues trying to track down what the difference is and just ended up confused. #[no_mangle] pub extern fn foo() { ... } vs. #[no_mangle] pub extern "C" fn foo() { ... } A: There is no difference because, as the reference says: By default external blocks assume that the library they are calling uses the standard C ABI on the specific platform. extern "C" -- This is the same as extern fn foo(); whatever the default your C compiler supports. An issue was created to always require explicitly stating extern "C" but the RFC has been refused. There is an issue in fmt-rfcs about "should we format extern "C" fn as that or extern fn?".
stackoverflow
{ "language": "en", "length": 133, "provenance": "stackexchange_0000F.jsonl.gz:904148", "question_score": "20", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664703" }
2be55ea8af54d33c4a7b74f9ccffd44a42f26a12
Stackoverflow Stackexchange Q: Export R environment to YAML (including package list) in order to recreate the environment somewhere else I am trying to export my R environment (including the list of active packages) as a YAML file in order to recreate the same R environment in a container (or a different machine). I know there are other ways and formats, but I need a YAML file to encapsulate the environment. Anaconda makes it easy in Python: conda env export > environment.yml Can't seem to find a way to do it in R. The closest representation that I found is sessionInfo(). Can anyone help me with this task?
Q: Export R environment to YAML (including package list) in order to recreate the environment somewhere else I am trying to export my R environment (including the list of active packages) as a YAML file in order to recreate the same R environment in a container (or a different machine). I know there are other ways and formats, but I need a YAML file to encapsulate the environment. Anaconda makes it easy in Python: conda env export > environment.yml Can't seem to find a way to do it in R. The closest representation that I found is sessionInfo(). Can anyone help me with this task?
stackoverflow
{ "language": "en", "length": 105, "provenance": "stackexchange_0000F.jsonl.gz:904150", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664710" }
5ac518bfee6c1ff94fb67bae7029350938215908
Stackoverflow Stackexchange Q: Are macOS and iOS targets supposed to share the same entitlement file? I have a project that has a target for iOS and macOS. When I was adding the iCloud capability to the iOS project and I ran it, I received an error that my entitlements file contained invalid or not permitted entitlements. When I went to the build settings I noticed that my iOS target was using the same entitlement file as the macOS target. Are both targets supposed to use the same entitlement file or should they each have their own? A: No, different targets should, in principle, have different entitlements. I had the same problem once, and unfortunately had to use different filenames for each target's entitlements file, or else Xcode would get them all mixed up. You can set the entitlements file in each target's Build Settings.
Q: Are macOS and iOS targets supposed to share the same entitlement file? I have a project that has a target for iOS and macOS. When I was adding the iCloud capability to the iOS project and I ran it, I received an error that my entitlements file contained invalid or not permitted entitlements. When I went to the build settings I noticed that my iOS target was using the same entitlement file as the macOS target. Are both targets supposed to use the same entitlement file or should they each have their own? A: No, different targets should, in principle, have different entitlements. I had the same problem once, and unfortunately had to use different filenames for each target's entitlements file, or else Xcode would get them all mixed up. You can set the entitlements file in each target's Build Settings.
stackoverflow
{ "language": "en", "length": 142, "provenance": "stackexchange_0000F.jsonl.gz:904204", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664889" }
b0e80ce23b3228ab2bf38c45d8b6757523f6121a
Stackoverflow Stackexchange Q: How do you connect to multiple databases using knex.js? There is a process that takes data from one database and replicates it to another. They are on different db platforms. It is intended that knex.js be the middleware. This works under 0.10.0 var first = require("knex")(...); var second = require("knex").initialize(...); but complains that initialize is deprecated. Can someone give an example of how to do this in the current version of knex.js? A: Why don't you use same syntax as for first? I guess that .initialize is just outdated(deprecated) version of just function call. var first = require("knex")(firstConfig); var second = require("knex")(secondConfig); first.select('*').from('users'); second.select('*').from('table'); And you have 2 different builders (each with different config).
Q: How do you connect to multiple databases using knex.js? There is a process that takes data from one database and replicates it to another. They are on different db platforms. It is intended that knex.js be the middleware. This works under 0.10.0 var first = require("knex")(...); var second = require("knex").initialize(...); but complains that initialize is deprecated. Can someone give an example of how to do this in the current version of knex.js? A: Why don't you use same syntax as for first? I guess that .initialize is just outdated(deprecated) version of just function call. var first = require("knex")(firstConfig); var second = require("knex")(secondConfig); first.select('*').from('users'); second.select('*').from('table'); And you have 2 different builders (each with different config).
stackoverflow
{ "language": "en", "length": 115, "provenance": "stackexchange_0000F.jsonl.gz:904209", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664905" }
41b0be1b70bc624b0d78c84fe426b9cab6d48824
Stackoverflow Stackexchange Q: How can I use a wildcard in uBlock Origin? How can I use a wildcard in uBlock Origin? I've tried to figure out how to do it, but I'm a little bit confused. I just want to simplify all of these rules into one rule: www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(2) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(3) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(4) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(5) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(6) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(7) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(9) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(10) Is it possible to give a range of numbers, or a list of specific numbers, or simply an asterisk? Thanks! A: You may be able to express the desired block with an arithmetic formula. For example, to block all elements except the very first one, use nth-of-type(n+2). Apparently, n starts from 0, so the blocking will skip the first element, but block everything afterwards. I use this to block articles automatically loaded by the god-awful sites, that employ the "endless stream" approach to reader-engagement...
Q: How can I use a wildcard in uBlock Origin? How can I use a wildcard in uBlock Origin? I've tried to figure out how to do it, but I'm a little bit confused. I just want to simplify all of these rules into one rule: www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(2) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(3) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(4) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(5) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(6) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(7) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(9) www.dailymail.co.uk###js-article-text > div:nth-of-type(2) > div:nth-of-type(10) Is it possible to give a range of numbers, or a list of specific numbers, or simply an asterisk? Thanks! A: You may be able to express the desired block with an arithmetic formula. For example, to block all elements except the very first one, use nth-of-type(n+2). Apparently, n starts from 0, so the blocking will skip the first element, but block everything afterwards. I use this to block articles automatically loaded by the god-awful sites, that employ the "endless stream" approach to reader-engagement... A: You can use 'odd' and 'even' as placeholders: www.dailymail.co.uk###js-article-text > div:nth-of-type(even) > div:nth-of-type(even) www.dailymail.co.uk###js-article-text > div:nth-of-type(even) > div:nth-of-type(odd) See https://www.w3schools.com/cssref/sel_nth-of-type.asp A: This will delete from all sites: ###js-article-text > div:nth-of-type.* This will delete from only this site www.dailymail.co.uk###js-article-text > div:nth-of-type NOTE: in both cases delete the first line starting with ! That line will only do instants, meaning next time you log in it will ignore your rule on any page of that site except that page Deleting line will make rule apply for entire site.
stackoverflow
{ "language": "en", "length": 257, "provenance": "stackexchange_0000F.jsonl.gz:904210", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44664907" }
ba59450c1b7e8f1441f564e464f5147403261748
Stackoverflow Stackexchange Q: Abandoned question: Why does 'npm install' remove my packages? The command is npm install --save file-saver and it returns this: npm WARN The package enzyme is included as both a dev and production dependency. npm WARN The package gulp-util is included as both a dev and production dependency. npm WARN The package react-addons-test-utils is included as both a dev and production dependency. [email protected] added 1 package and removed 15 packages in 6.536s I know two of the packages removed are react-google-recaptcha and react-async-script. Also, I'm not using npm's public registry.
Q: Abandoned question: Why does 'npm install' remove my packages? The command is npm install --save file-saver and it returns this: npm WARN The package enzyme is included as both a dev and production dependency. npm WARN The package gulp-util is included as both a dev and production dependency. npm WARN The package react-addons-test-utils is included as both a dev and production dependency. [email protected] added 1 package and removed 15 packages in 6.536s I know two of the packages removed are react-google-recaptcha and react-async-script. Also, I'm not using npm's public registry.
stackoverflow
{ "language": "en", "length": 91, "provenance": "stackexchange_0000F.jsonl.gz:904247", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665038" }
c7c3b0c429a7b458045a986cd118881d514dd951
Stackoverflow Stackexchange Q: CLion only shows type of result in debugger, not actual value So I have this problem in a lot of places including watches, but it's especially annoying for evaulate expression. Basically, CLion successfully evaulates the expression, figures out that it gives back a result, shows the type of the result, but doesn't actually show me the value. Is there some magic command I'm missing to actually see the value? I can see if I switch to lldb instead of gdb, but lldb has it's own set of problems, including expression evaluation not working at all in most contexts. A: This happens when there is some error evaluating the expression. CLion doesn't indicate there is an error in gdb mode other than the red squiggle (in lldb mode, it does show some errors, sometimes). Correcting the error made the value show up next to the type of the result
Q: CLion only shows type of result in debugger, not actual value So I have this problem in a lot of places including watches, but it's especially annoying for evaulate expression. Basically, CLion successfully evaulates the expression, figures out that it gives back a result, shows the type of the result, but doesn't actually show me the value. Is there some magic command I'm missing to actually see the value? I can see if I switch to lldb instead of gdb, but lldb has it's own set of problems, including expression evaluation not working at all in most contexts. A: This happens when there is some error evaluating the expression. CLion doesn't indicate there is an error in gdb mode other than the red squiggle (in lldb mode, it does show some errors, sometimes). Correcting the error made the value show up next to the type of the result
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:904256", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665058" }
17277d28e8b1b4bcab5f86aba77a0e6c871d906a
Stackoverflow Stackexchange Q: Which server Django is using? After we installed the Django, we use the command: python manage.py runserver we can run a server, but I don't know the server is which server, and I searched the django directory, find the server is not in the directory: aircraftdeMacBook-Pro:Django-1.11.2-py2.7.egg ldl$ cd django/ aircraftdeMacBook-Pro:django ldl$ ls __init__.py bin dispatch shortcuts.pyc utils __init__.pyc conf forms template views __main__.py contrib http templatetags __main__.pyc core middleware test apps db shortcuts.py urls So, I have two questions: * *The server is which web-server, and how can I find its location? *If we finish the application, if we use the web-server as the python-web's web-server(means why not apache or nginx)? *The port default is 8000, how to change to the 80? A: 1) Django provides a default wsgi server as @sach20 mentioned. 2) The django server should be used for development. I personally use nginx and gunicorn to run my server. You can find a tutorial on how to set on up here: Tutorial 3) You can run: python manage.py runserver 0.0.0.0:80 You can substitute 80 with any port you want to use.
Q: Which server Django is using? After we installed the Django, we use the command: python manage.py runserver we can run a server, but I don't know the server is which server, and I searched the django directory, find the server is not in the directory: aircraftdeMacBook-Pro:Django-1.11.2-py2.7.egg ldl$ cd django/ aircraftdeMacBook-Pro:django ldl$ ls __init__.py bin dispatch shortcuts.pyc utils __init__.pyc conf forms template views __main__.py contrib http templatetags __main__.pyc core middleware test apps db shortcuts.py urls So, I have two questions: * *The server is which web-server, and how can I find its location? *If we finish the application, if we use the web-server as the python-web's web-server(means why not apache or nginx)? *The port default is 8000, how to change to the 80? A: 1) Django provides a default wsgi server as @sach20 mentioned. 2) The django server should be used for development. I personally use nginx and gunicorn to run my server. You can find a tutorial on how to set on up here: Tutorial 3) You can run: python manage.py runserver 0.0.0.0:80 You can substitute 80 with any port you want to use. A: Django runserver is a local dev server, should not be used in production... APACHE AND NGINX are different things. Django provides a simple WSGI server as a dev server. Also id guess you have not looked inside the django docs because what you are looking for is right here Examples of using different ports and addresses¶ Port 8000 on IP address 127.0.0.1: django-admin runserver Port 8000 on IP address 1.2.3.4: django-admin runserver 1.2.3.4:8000 Port 7000 on IP address 127.0.0.1: django-admin runserver 7000 A: Django provides a default wsgi development server
stackoverflow
{ "language": "en", "length": 276, "provenance": "stackexchange_0000F.jsonl.gz:904284", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665138" }
e6c8f834f969772385774495bad148f954afecc6
Stackoverflow Stackexchange Q: Xamarin - Type not found in xmlns clr-namespace I am making a Xamarin Forms app, the solution is called RESTTest, my shared project is called RestApp. In my shared project I have a folder called ViewModels, which contains a class called MainViewModel.cs I have a page called MainPage.xaml which has a code-behind called MainPage.xaml.cs. In my XAML I am trying to include my Viewmodels folder like this: <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:RestApp" x:Class="RestApp.MainPage" xmlns:ViewModels="clr-namespace:RestApp.ViewModels;assembly=RestApp"> But when I add binding to my page like this: <ContentPage.BindingContext> <ViewModels:MainViewModel /> </ContentPage.BindingContext> I am getting an unhandled exception: Type ViewModels:MainViewModel not found in xmlns clr-namespace:RestApp.ViewModels;assembly=RestApp What am I missing? A: Removing the ";assembly=RestApp" in the namespace, and setting the linker behaviour to "Link SDK Assemblies Only" worked for me and solved the problem!
Q: Xamarin - Type not found in xmlns clr-namespace I am making a Xamarin Forms app, the solution is called RESTTest, my shared project is called RestApp. In my shared project I have a folder called ViewModels, which contains a class called MainViewModel.cs I have a page called MainPage.xaml which has a code-behind called MainPage.xaml.cs. In my XAML I am trying to include my Viewmodels folder like this: <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:RestApp" x:Class="RestApp.MainPage" xmlns:ViewModels="clr-namespace:RestApp.ViewModels;assembly=RestApp"> But when I add binding to my page like this: <ContentPage.BindingContext> <ViewModels:MainViewModel /> </ContentPage.BindingContext> I am getting an unhandled exception: Type ViewModels:MainViewModel not found in xmlns clr-namespace:RestApp.ViewModels;assembly=RestApp What am I missing? A: Removing the ";assembly=RestApp" in the namespace, and setting the linker behaviour to "Link SDK Assemblies Only" worked for me and solved the problem! A: This usually happens when you have Linker optimizations that trim unused code. Note that deserialization into a type may not be detectable by the linker as a type use. In the properties of your project find the "Linker Behavior" option under "iOS Build" or "Android Build", and set it to either "Link SDK assemblies only" or "Don’t Link". You'll need to clean+rebuild your whole solution for the change to take effect. A: <ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:cvt="clr-namespace:XamarinTest.UI.Resources.Converts;assembly=XamarinTest.UI"> <cvt:DoubleToImageConverter x:Key="CVT_DoubleToImage"/> <cvt:MediaTypeToImageConverter x:Key="CVT_MediaTypeToImage"/> </ResourceDictionary> In my app, I add the assembly=XamarinTest.UI solved the problem. I think the dev team may removed the assembly=xxxx section in Xamarin Forms 5.0.
stackoverflow
{ "language": "en", "length": 235, "provenance": "stackexchange_0000F.jsonl.gz:904289", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665152" }
7012b4325aebd206988ee4f3b46eb4c6f2eef8cc
Stackoverflow Stackexchange Q: How copy entire directory from one folder two another using laravel 5 May be it's so easy but I couldn't find any proper answer in google or here!! I did use \File::copyDirectory('public/' . $token . '/cover/', $folderName . '/cover/'); but there's no different!! This is where I found above solution. Do you know how can I copy entire directory from one folder to another using laravel 5.4? Thanks in Advance A: We can do it in laravel 5.8 using file facade as followings: use Illuminate\Support\Facades\File; File::copyDirectory(__DIR__.'/form-directory', resource_path('to-directory')); Hope, it'll be helpful.
Q: How copy entire directory from one folder two another using laravel 5 May be it's so easy but I couldn't find any proper answer in google or here!! I did use \File::copyDirectory('public/' . $token . '/cover/', $folderName . '/cover/'); but there's no different!! This is where I found above solution. Do you know how can I copy entire directory from one folder to another using laravel 5.4? Thanks in Advance A: We can do it in laravel 5.8 using file facade as followings: use Illuminate\Support\Facades\File; File::copyDirectory(__DIR__.'/form-directory', resource_path('to-directory')); Hope, it'll be helpful. A: More than one year later :) Use path helpers functions https://laravel.com/docs/5.6/helpers \File::copyDirectory( public_path . 'to/the/app', resource_path('to/the/app')); A: Just do this: /* Move test images from public folder to storage folder */ $source = "source/path"; $destination = "public/files"; File::copyDirectory(base_path($source), base_path($destination)); A: I used Storage facades and worked well config/filesystems.php 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => public_path(), ], ... ] Copy all files from public/seed_images/ to public/images/ app/Http/Controllers/HomeController.php use Illuminate\Support\Facades\Storage; $fromFiles = Storage::allFiles('seed_images'); for ($i=0; $i < count($fromFiles) ; $i++) { $toFile = str_replace("seed_images","images",$fromFiles[$i]); Storage::copy( $fromFiles[$i], $toFile ); } A: Try using the mix.copy() method. mix.copy('public/' . $token . '/cover/', $folderName . '/cover/'); Read more at: https://laravel.com/docs/5.4/mix#copying-files-and-directories
stackoverflow
{ "language": "en", "length": 203, "provenance": "stackexchange_0000F.jsonl.gz:904310", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665234" }
291a55574c3ec08001e7ddbee5252f03a3efc8e7
Stackoverflow Stackexchange Q: Propagating ng-invalid class update to child elements I have build custom form control which works well. However when i hook it up with inbuilt angular validators I am facing issues. I am expecting that when validation fails angular should set all the elements from the root of the custom component to last child as invalid. However I am facing this issue below The parent control shows ng-invalid but has the class ng-untouched. Whereas the input shows ng-touched and ng-valid. What I need is the input element to have ng-invalid set on validation failure. My Angular 2 form binding are as below html <phone-control [formControl]="form.controls['phone']" type="number"></phone-control> ts phone: [null, Validators.compose([Validators.required,Validators.minLength(10),Validators.maxLength(10)])], Can some help me understand what I am missing here.
Q: Propagating ng-invalid class update to child elements I have build custom form control which works well. However when i hook it up with inbuilt angular validators I am facing issues. I am expecting that when validation fails angular should set all the elements from the root of the custom component to last child as invalid. However I am facing this issue below The parent control shows ng-invalid but has the class ng-untouched. Whereas the input shows ng-touched and ng-valid. What I need is the input element to have ng-invalid set on validation failure. My Angular 2 form binding are as below html <phone-control [formControl]="form.controls['phone']" type="number"></phone-control> ts phone: [null, Validators.compose([Validators.required,Validators.minLength(10),Validators.maxLength(10)])], Can some help me understand what I am missing here.
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:904336", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665328" }
13b4f3cab3e0fd1815c06808b94c2452d272e280
Stackoverflow Stackexchange Q: Conditional statement in blogger template is not working In my blogger template add a conditional statement. But it is not working. It is always display 'Not equal' Home url: http://abc.blogspot.in Page url: http://abc.blogspot.in/p/my-page-url.html For testing purpose i had pasted the below code after '<body>' tag. <b:if cond='data:blog.url == data:blog.homepageUrl + &quot;p/my-page-url.html&quot;'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if> I had printed the value of <data:blog.url/> and <data:blog.homepageUrl/>p/my-page-url.html and it is same. updates: <b:if cond='data:blog.url == &quot;http://abc.blogspot.in/p/my-page-url.html&quot;'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if> //Not equal <b:if cond='data:blog.url == &quot;http://abc.blogspot.com/p/my-page-url.html&quot;'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if> //Equal Thank You A: Replace the above code with this <b:if cond='data:blog.pageId == "PAGE_ID"'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if> To find the PAGE_ID go to Pages, now click edit to open the page in Blogger post editor. In the address bar you may find something like this "pageID=6284317258827606063" now copy the page id and replace with the PAGE_ID above.
Q: Conditional statement in blogger template is not working In my blogger template add a conditional statement. But it is not working. It is always display 'Not equal' Home url: http://abc.blogspot.in Page url: http://abc.blogspot.in/p/my-page-url.html For testing purpose i had pasted the below code after '<body>' tag. <b:if cond='data:blog.url == data:blog.homepageUrl + &quot;p/my-page-url.html&quot;'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if> I had printed the value of <data:blog.url/> and <data:blog.homepageUrl/>p/my-page-url.html and it is same. updates: <b:if cond='data:blog.url == &quot;http://abc.blogspot.in/p/my-page-url.html&quot;'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if> //Not equal <b:if cond='data:blog.url == &quot;http://abc.blogspot.com/p/my-page-url.html&quot;'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if> //Equal Thank You A: Replace the above code with this <b:if cond='data:blog.pageId == "PAGE_ID"'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if> To find the PAGE_ID go to Pages, now click edit to open the page in Blogger post editor. In the address bar you may find something like this "pageID=6284317258827606063" now copy the page id and replace with the PAGE_ID above. A: Replace the '+' with 'path' without '. A: Patternpy answer is correct. You can use this to achieve what you want. <b:if cond='data:blog.url.canonical== data:blog.homepageUrl.canonical path "my-page-url.html"'> <h1>Equal</h1> <b:else/> <h1>Not equal</h1> </b:if>
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:904380", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665455" }
deb57badb3d335f524fdc73b4adb3f51a89669f5
Stackoverflow Stackexchange Q: Undertow XNIO I/O thread consistently eat CPU I observed my application (based on undertow) constantly eat CPU percentage after running a while: In the end I found if I suspend one of the XNIO I/O thread the CPU percentage will be released. The stack frame after suspended the I/O thread: The CPU consumption after suspended and resumed that thread: Any idea what triggered this issue? Updates The suspended place of normal I/O thread: The suspended place of error I/O thread: Update 2 - More findings There are dead loop found in the logic: * *WorkerThread call select: *Thread interupted: *Selected key is null and it breaks out the loop: *It repeats the infinit loop again: *And back to the select() call:
Q: Undertow XNIO I/O thread consistently eat CPU I observed my application (based on undertow) constantly eat CPU percentage after running a while: In the end I found if I suspend one of the XNIO I/O thread the CPU percentage will be released. The stack frame after suspended the I/O thread: The CPU consumption after suspended and resumed that thread: Any idea what triggered this issue? Updates The suspended place of normal I/O thread: The suspended place of error I/O thread: Update 2 - More findings There are dead loop found in the logic: * *WorkerThread call select: *Thread interupted: *Selected key is null and it breaks out the loop: *It repeats the infinit loop again: *And back to the select() call:
stackoverflow
{ "language": "en", "length": 122, "provenance": "stackexchange_0000F.jsonl.gz:904409", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665552" }
f5efeac2c57cfd0862cecef340b709cdcb4a0813
Stackoverflow Stackexchange Q: Difference between the two types for writing into file I am going through Java's NIO class from Java 8. Path dataPath = FileSystems.getDefault().getPath("SomeFile"); Files.write(dataPath,"\n Hello".getBytes("UTF-8"), StandardOpenOption.APPEND); and Path dataPath = FileSystems.getDefault().getPath("SomeFile"); BufferedWriter locFile = Files.newBufferedWriter(dataPath); locFile.write("\n Hello"); Is it just that we are writing in terms of Bytes with Files.write() and Using a BufferedWriter for directly writing the text ?
Q: Difference between the two types for writing into file I am going through Java's NIO class from Java 8. Path dataPath = FileSystems.getDefault().getPath("SomeFile"); Files.write(dataPath,"\n Hello".getBytes("UTF-8"), StandardOpenOption.APPEND); and Path dataPath = FileSystems.getDefault().getPath("SomeFile"); BufferedWriter locFile = Files.newBufferedWriter(dataPath); locFile.write("\n Hello"); Is it just that we are writing in terms of Bytes with Files.write() and Using a BufferedWriter for directly writing the text ?
stackoverflow
{ "language": "en", "length": 61, "provenance": "stackexchange_0000F.jsonl.gz:904413", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665573" }
cd3435027cf76de85e545e321eea449aea93cea9
Stackoverflow Stackexchange Q: Does the "editorWhitespace.foreground" workbench.colorCustomizations setting in VSCode actually work? I'm using version 1.13 of VSCode on the Mac. I'd like to override the theme colour for whitespace. Following the docs: editorWhitespace.foreground: Color of whitespace characters in the editor. https://github.com/Microsoft/vscode-docs/blob/master/docs/getstarted/theme-color-reference.md I have put this in the settings: "workbench.colorCustomizations": { "editorWhitespace.foreground": "#333", "editorIndentGuide.background": "#333" } The "editorIndentGuide.background" has an effect, but "editorWhitespace.foreground" doesn't. Am I doing something wrong? UPDATE: To clarify, when the whitespace is visible the spaces are indicated with white dots. I'm expecting to be able to change the colour of the dots to, say, #333 with the "editorWhitespace.foreground" setting. A: Yes, it does for me on Windows 10. I assume you have "Toggle Render Whitespace" under View menu on? What color is your editor background, perhaps it is too close to #333 to appear obvious.
Q: Does the "editorWhitespace.foreground" workbench.colorCustomizations setting in VSCode actually work? I'm using version 1.13 of VSCode on the Mac. I'd like to override the theme colour for whitespace. Following the docs: editorWhitespace.foreground: Color of whitespace characters in the editor. https://github.com/Microsoft/vscode-docs/blob/master/docs/getstarted/theme-color-reference.md I have put this in the settings: "workbench.colorCustomizations": { "editorWhitespace.foreground": "#333", "editorIndentGuide.background": "#333" } The "editorIndentGuide.background" has an effect, but "editorWhitespace.foreground" doesn't. Am I doing something wrong? UPDATE: To clarify, when the whitespace is visible the spaces are indicated with white dots. I'm expecting to be able to change the colour of the dots to, say, #333 with the "editorWhitespace.foreground" setting. A: Yes, it does for me on Windows 10. I assume you have "Toggle Render Whitespace" under View menu on? What color is your editor background, perhaps it is too close to #333 to appear obvious. A: I had an issue with this when specifically using the Default High Contrast theme. This has been fixed with the August 2017 release.
stackoverflow
{ "language": "en", "length": 161, "provenance": "stackexchange_0000F.jsonl.gz:904419", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665595" }
fcbcacfcb9374c004a53e5b9bc5e29bb67a7fdd4
Stackoverflow Stackexchange Q: Generate object from Typescript interface I realize this is essentially the opposite intent of Typescript, but I would like to be able to programmatically generate an object FROM a typescript interface. Basically, I want something like this: interface Foo { bar: string } const generateObjFromInterface = (Foo) => // { bar: 'string'} I -do not- mind how contrived the implementation is if it IS possible! If it is categorically impossible that would also be helpful information! Thanks in advance! A: It is possible. As typescript 2.4 is around the corner we can use custom transformers for typescript during compilation and get the list of all properties that are there and as a result create object with such properties. Here is an example, but please note - as I have said this require to use typescript 2.4+ that is not yet in stable release
Q: Generate object from Typescript interface I realize this is essentially the opposite intent of Typescript, but I would like to be able to programmatically generate an object FROM a typescript interface. Basically, I want something like this: interface Foo { bar: string } const generateObjFromInterface = (Foo) => // { bar: 'string'} I -do not- mind how contrived the implementation is if it IS possible! If it is categorically impossible that would also be helpful information! Thanks in advance! A: It is possible. As typescript 2.4 is around the corner we can use custom transformers for typescript during compilation and get the list of all properties that are there and as a result create object with such properties. Here is an example, but please note - as I have said this require to use typescript 2.4+ that is not yet in stable release A: Since TypeScript's interfaces are not present in the JavaScript output, runtime reflection over an interface is impossible. Given this TypeScript: interface Foo { bar: string } This is the resultant JavaScript: Since there is no JavaScript, what you want to do is categorically impossible is very contrived. Edit: Come to think of it, you could find, read, and parse the *.ts source file at runtime. A: I also was searching for something that could do it and I didn't find anything. So I build this lib https://www.npmjs.com/package/class-validator-mocker, which can generate random data for classes attributes annotated with class-validator's decorators. Worked pretty well for my purposes. A: I did it by using intermock (Google) Here is a demo page
stackoverflow
{ "language": "en", "length": 263, "provenance": "stackexchange_0000F.jsonl.gz:904438", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665650" }
9264a117825b5a401f920ac959403fec1e1b924a
Stackoverflow Stackexchange Q: Creating a framework that uses XCTest I am developing several iOS Apps that require testing. I have created some helper methods that extend the functionality of the classes in XCTest. However because they are separate apps, I end up duplicating code. If this were a Non-test situation, I would create a framework called Common.framework and put all my class extension in there. I would like to create a framework called "XCTest_extensions.framework" so that I can add the class extensions I have made for XCTest classes. My plan is to make XCTest_extensions into a framework that only a UnitTest bundle would import. However, if I create a framework and add XCTest to "Linked frameworks and libraries" it doesn't work! It says "Framework not found XCTest" Is it possible to create an a dynamic framework that imports XCTest? A: You have to add additional Framework Search Path in the Build Settings: $(PLATFORM_DIR)/Developer/Library/Frameworks
Q: Creating a framework that uses XCTest I am developing several iOS Apps that require testing. I have created some helper methods that extend the functionality of the classes in XCTest. However because they are separate apps, I end up duplicating code. If this were a Non-test situation, I would create a framework called Common.framework and put all my class extension in there. I would like to create a framework called "XCTest_extensions.framework" so that I can add the class extensions I have made for XCTest classes. My plan is to make XCTest_extensions into a framework that only a UnitTest bundle would import. However, if I create a framework and add XCTest to "Linked frameworks and libraries" it doesn't work! It says "Framework not found XCTest" Is it possible to create an a dynamic framework that imports XCTest? A: You have to add additional Framework Search Path in the Build Settings: $(PLATFORM_DIR)/Developer/Library/Frameworks
stackoverflow
{ "language": "en", "length": 151, "provenance": "stackexchange_0000F.jsonl.gz:904442", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665656" }
3e0af487927022e7caf20b272085684739295676
Stackoverflow Stackexchange Q: Check if a video on YouTube is available from the URL using JavaScript How can I check if a YouTube video is available or unavailable for any reason from the URL or video id by using JavaScript in an html website for example: this link goes to a video that is available https://www.youtube.com/watch?v=3aY1Z15vTw0 this link goes to a video that is not available https://www.youtube.com/watch?v=FMbz0444444 I want to make it so it does something different depending on whether the video from the link is available or not if youtube link is available: do something else: do something else A: You can use list and check on uploadStatus. Possible statuses are: * *deleted *failed *processed *rejected *uploaded
Q: Check if a video on YouTube is available from the URL using JavaScript How can I check if a YouTube video is available or unavailable for any reason from the URL or video id by using JavaScript in an html website for example: this link goes to a video that is available https://www.youtube.com/watch?v=3aY1Z15vTw0 this link goes to a video that is not available https://www.youtube.com/watch?v=FMbz0444444 I want to make it so it does something different depending on whether the video from the link is available or not if youtube link is available: do something else: do something else A: You can use list and check on uploadStatus. Possible statuses are: * *deleted *failed *processed *rejected *uploaded
stackoverflow
{ "language": "en", "length": 116, "provenance": "stackexchange_0000F.jsonl.gz:904444", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665661" }
ba7ac006df1741e2357d6088091d05bb8897f041
Stackoverflow Stackexchange Q: How do I crop an image in Flutter? Let's say I have a rectangular, portrait image: I'd like to crop it, such that it's rendered like this: How can I do this in Flutter? (I don't need to resize the image.) (Image from https://flic.kr/p/nwXTDb) A: I would probably use a BoxDecoration with a DecorationImage. You can use the alignment and fit properties to determine how your image is cropped. You can use an AspectRatio widget if you don't want to hard code a height on the Container. import 'package:flutter/material.dart'; void main() { runApp(new MaterialApp( home: new MyHomePage(), )); } class MyHomePage extends StatelessWidget { Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Image Crop Example"), ), body: new Center( child: new AspectRatio( aspectRatio: 487 / 451, child: new Container( decoration: new BoxDecoration( image: new DecorationImage( fit: BoxFit.fitWidth, alignment: FractionalOffset.topCenter, image: new NetworkImage('https://i.stack.imgur.com/lkd0a.png'), ) ), ), ), ), ); } }
Q: How do I crop an image in Flutter? Let's say I have a rectangular, portrait image: I'd like to crop it, such that it's rendered like this: How can I do this in Flutter? (I don't need to resize the image.) (Image from https://flic.kr/p/nwXTDb) A: I would probably use a BoxDecoration with a DecorationImage. You can use the alignment and fit properties to determine how your image is cropped. You can use an AspectRatio widget if you don't want to hard code a height on the Container. import 'package:flutter/material.dart'; void main() { runApp(new MaterialApp( home: new MyHomePage(), )); } class MyHomePage extends StatelessWidget { Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Image Crop Example"), ), body: new Center( child: new AspectRatio( aspectRatio: 487 / 451, child: new Container( decoration: new BoxDecoration( image: new DecorationImage( fit: BoxFit.fitWidth, alignment: FractionalOffset.topCenter, image: new NetworkImage('https://i.stack.imgur.com/lkd0a.png'), ) ), ), ), ), ); } } A: Worked for me using just these 2 properties: CachedNetworkImage( fit: BoxFit.cover,// OR BoxFit.fitWidth alignment: FractionalOffset.topCenter, .... ) A: There is a new package called ImageCropper. I would recommend everyone to use this instead as it has many features and makes everything easier. It allows you to crop the image to any or specified aspect ratio you want and can even compress the image. Here is the link to the package: https://pub.dev/packages/image_cropper A: import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:image_cropper/image_cropper.dart'; class MyPage extends StatefulWidget { @override _MyPageState createState() => _MyPageState(); } class _MyPageState extends State<MyPage> { /// Variables File imageFile; /// Widget @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color(0XFF307777), title: Text("Image Cropper"), ), body: Container( child: imageFile == null ? Container( alignment: Alignment.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( color: Color(0XFF307777), onPressed: () { _getFromGallery(); }, child: Text( "PICK FROM GALLERY", style: TextStyle(color: Colors.white), ), ), ], ), ) : Container( child: Image.file( imageFile, fit: BoxFit.cover, ), ))); } /// Get from gallery _getFromGallery() async { PickedFile pickedFile = await ImagePicker().getImage( source: ImageSource.gallery, maxWidth: 1800, maxHeight: 1800, ); _cropImage(pickedFile.path); } /// Crop Image _cropImage(filePath) async { File croppedImage = await ImageCropper.cropImage( sourcePath: filePath, maxWidth: 1080, maxHeight: 1080, ); if (croppedImage != null) { imageFile = croppedImage; setState(() {}); } } } A: You can also directly use the Image class with BoxFit and do something like: new Image.asset( stringToImageLocation, fit: BoxFit.cover, ) A: Provide a fit factor to your Image widget and then wrap it in AspectRatio. AspectRatio( aspectRatio: 1.5, child: Image.asset( 'your_image_asset', fit: BoxFit.cover, ), ) A: Take a look to brendan-duncan/image, it's platform-independent library to manipulate images in Dart. You can use the function: Image copyCrop(Image src, int x, int y, int w, int h); A: Here I crop file to square. I use image library. import 'dart:io'; import 'package:image/image.dart' as img; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; class CropperService { static const _side = 1800; Future<File> cropImageFile(File file, [int? side]) async { final image = await img.decodeImageFile(file.path); if (image == null) throw Exception('Unable to decode image'); final croppedImage = img.copyResizeCropSquare(image, size: _side); final croppedFile = await _convertImageToFile(croppedImage, file.path); return croppedFile; } Future<File> _convertImageToFile(img.Image image, String path) async { final newPath = await _croppedFilePath(path); final jpegBytes = img.encodeJpg(image); final convertedFile = await File(newPath).writeAsBytes(jpegBytes); await File(path).delete(); return convertedFile; } Future<String> _croppedFilePath(String path) async { final tempDir = await getTemporaryDirectory(); return join( tempDir.path, '${basenameWithoutExtension(path)}_compressed.jpg', ); } }
stackoverflow
{ "language": "en", "length": 556, "provenance": "stackexchange_0000F.jsonl.gz:904468", "question_score": "40", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665720" }
b18e702b5e35565a1124e127a95d9854dc5fcf63
Stackoverflow Stackexchange Q: How to include test category in visual studio test results How do I make sure the test categories I used in my unit tests are included in the test results. So that I could use the category to filter my tests or generate a html using trx2html grouped by the category. [Trait("Category", "1")] public class MyFeature1Tests [Trait("Category", "2")] public class MyFeature2Tests I could see the tests grouped by the category in the visual studio test explorer. But it is not possible in the test results (.trx) file?
Q: How to include test category in visual studio test results How do I make sure the test categories I used in my unit tests are included in the test results. So that I could use the category to filter my tests or generate a html using trx2html grouped by the category. [Trait("Category", "1")] public class MyFeature1Tests [Trait("Category", "2")] public class MyFeature2Tests I could see the tests grouped by the category in the visual studio test explorer. But it is not possible in the test results (.trx) file?
stackoverflow
{ "language": "en", "length": 88, "provenance": "stackexchange_0000F.jsonl.gz:904474", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665748" }
1ba176c0e0c40b23e712fd338ebcfce3165700a6
Stackoverflow Stackexchange Q: Closing python requests connection import requests requests.get(path_url, timeout=100) In the above usage of python requests library, does the connection close automatically once requests.get is done running? If not, how can I make for certain that connection is closed A: Yes, there is a call to a session.close behind the get code. If using a proper IDE like PyCharm for example, you can follow the get code to see what is happening. Inside get there is a call to request: return request('get', url, params=params, **kwargs) Within the definition of that request method, the call to session.close is made. By following the link here to the requests repo, there is a call being made for the session control: # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs)
Q: Closing python requests connection import requests requests.get(path_url, timeout=100) In the above usage of python requests library, does the connection close automatically once requests.get is done running? If not, how can I make for certain that connection is closed A: Yes, there is a call to a session.close behind the get code. If using a proper IDE like PyCharm for example, you can follow the get code to see what is happening. Inside get there is a call to request: return request('get', url, params=params, **kwargs) Within the definition of that request method, the call to session.close is made. By following the link here to the requests repo, there is a call being made for the session control: # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs)
stackoverflow
{ "language": "en", "length": 162, "provenance": "stackexchange_0000F.jsonl.gz:904482", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665767" }
a09976f8e02dd25c2dc8cfdc710ae8e7a6068d65
Stackoverflow Stackexchange Q: libart.so crash on Android 5.1 There are lots of native crashes in my app, only in 5.0 or 5.1 android system, the crash trace are bellow: SIGBUS(BUS_ADRERR): #00 pc 0022dece /system/lib/libart.so (art::StackVisitor::WalkStack(bool) +209) #01 pc 00237915 /system/lib/libart.so (_jobject* art::Thread::CreateInternalStackTrace<false>(art::ScopedObjectAccessAlreadyRunnable const&) const +56) #02 pc 002081b3 /system/lib/libart.so (art::Throwable_nativeFillInStackTrace(_JNIEnv*, _jclass*) +18) #03 pc 00000c1d /data/dalvik-cache/arm/system@[email protected] Does anyone else have met this problem before ? what is /data/dalvik-cache/arm/system@[email protected] ? Any help on how to proceed would be appreciated ! Thanks
Q: libart.so crash on Android 5.1 There are lots of native crashes in my app, only in 5.0 or 5.1 android system, the crash trace are bellow: SIGBUS(BUS_ADRERR): #00 pc 0022dece /system/lib/libart.so (art::StackVisitor::WalkStack(bool) +209) #01 pc 00237915 /system/lib/libart.so (_jobject* art::Thread::CreateInternalStackTrace<false>(art::ScopedObjectAccessAlreadyRunnable const&) const +56) #02 pc 002081b3 /system/lib/libart.so (art::Throwable_nativeFillInStackTrace(_JNIEnv*, _jclass*) +18) #03 pc 00000c1d /data/dalvik-cache/arm/system@[email protected] Does anyone else have met this problem before ? what is /data/dalvik-cache/arm/system@[email protected] ? Any help on how to proceed would be appreciated ! Thanks
stackoverflow
{ "language": "en", "length": 78, "provenance": "stackexchange_0000F.jsonl.gz:904485", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665775" }
13eae7823a8ed819b64c74c7434e1d4879009afa
Stackoverflow Stackexchange Q: MYSQL - Compare 2 Arrays I would like to update my MYSQL query conditions to also include the equivalent of "AND all of the numbers in array 1 are present in array 2". Array1: (1,14,7) Array2: (1,23,45,14,6) So, this example would fail because "7" is not present. If I use "IN" it would require that they match in the same order? or can you compare using that? Can I do this as part of the MYSQL Query or do I need to get the results first and then loop through them throwing out some that don't match?? Any help greatly appreciated :-) A: Order does not matter. you can use this condition WHERE SomeColumn IN (1,14,7) AND SomeColumn IN (1,23,45,14,6) This is will give you the intersection between both sets, which are 1 & 14 only
Q: MYSQL - Compare 2 Arrays I would like to update my MYSQL query conditions to also include the equivalent of "AND all of the numbers in array 1 are present in array 2". Array1: (1,14,7) Array2: (1,23,45,14,6) So, this example would fail because "7" is not present. If I use "IN" it would require that they match in the same order? or can you compare using that? Can I do this as part of the MYSQL Query or do I need to get the results first and then loop through them throwing out some that don't match?? Any help greatly appreciated :-) A: Order does not matter. you can use this condition WHERE SomeColumn IN (1,14,7) AND SomeColumn IN (1,23,45,14,6) This is will give you the intersection between both sets, which are 1 & 14 only
stackoverflow
{ "language": "en", "length": 137, "provenance": "stackexchange_0000F.jsonl.gz:904521", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665917" }
2d8e48bf58518728ee1d4e6f53fbe20a053731bc
Stackoverflow Stackexchange Q: How do I determine the width and height of an image in Flutter? Assume I have declared my image in my pubspec.yaml like this: assets: - assets/kitten.jpg And my Flutter code is this: void main() { runApp( new Center( child: new Image.asset('assets/kitten.jpg'), ), ); } Now that I have a new Image.asset(), how do I determine the width and height of that image? For example, I just want to print out the image's width and height. (It looks like dart:ui's Image class has width and height, but not sure how to go from widget's Image to dart:ui's Image.) Thanks! A: If you don't want to use FutureBuilder or then, you can also use await like this: Don't forget to import the Image. But as there are two Image classes, import it like this and use with ui.Image import 'dart:ui' as ui Then you can fetch the dimensions of the image as follows. final Image image = Image(image: AssetImage('assets/images/someimage.png')); Completer<ui.Image> completer = new Completer<ui.Image>(); image.image .resolve(new ImageConfiguration()) .addListener(new ImageStreamListener((ImageInfo image, bool _) { completer.complete(image.image); })); ui.Image info = await completer.future; int width = info.width; int height = info.height;
Q: How do I determine the width and height of an image in Flutter? Assume I have declared my image in my pubspec.yaml like this: assets: - assets/kitten.jpg And my Flutter code is this: void main() { runApp( new Center( child: new Image.asset('assets/kitten.jpg'), ), ); } Now that I have a new Image.asset(), how do I determine the width and height of that image? For example, I just want to print out the image's width and height. (It looks like dart:ui's Image class has width and height, but not sure how to go from widget's Image to dart:ui's Image.) Thanks! A: If you don't want to use FutureBuilder or then, you can also use await like this: Don't forget to import the Image. But as there are two Image classes, import it like this and use with ui.Image import 'dart:ui' as ui Then you can fetch the dimensions of the image as follows. final Image image = Image(image: AssetImage('assets/images/someimage.png')); Completer<ui.Image> completer = new Completer<ui.Image>(); image.image .resolve(new ImageConfiguration()) .addListener(new ImageStreamListener((ImageInfo image, bool _) { completer.complete(image.image); })); ui.Image info = await completer.future; int width = info.width; int height = info.height; A: UPDATED SOLUTION: With the new version of flutter old solution is obsolete. Now the addListener needs an ImageStreamListener. Widget build(BuildContext context) { Image image = new Image.network('https://i.stack.imgur.com/lkd0a.png'); Completer<ui.Image> completer = new Completer<ui.Image>(); image.image .resolve(new ImageConfiguration()) .addListener(ImageStreamListener((ImageInfo info, bool _) { completer.complete(info.image)); }) ... ... ORIGINAL VERSION: If you already have an Image widget, you can read the ImageStream out of it by calling resolve on its ImageProvider. import 'dart:ui' as ui; import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { runApp(new MaterialApp( home: new MyHomePage(), )); } class MyHomePage extends StatelessWidget { Widget build(BuildContext context) { Image image = new Image.network('https://i.stack.imgur.com/lkd0a.png'); Completer<ui.Image> completer = new Completer<ui.Image>(); image.image .resolve(new ImageConfiguration()) .addListener((ImageInfo info, bool _) => completer.complete(info.image)); return new Scaffold( appBar: new AppBar( title: new Text("Image Dimensions Example"), ), body: new ListView( children: [ new FutureBuilder<ui.Image>( future: completer.future, builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) { if (snapshot.hasData) { return new Text( '${snapshot.data.width}x${snapshot.data.height}', style: Theme.of(context).textTheme.display3, ); } else { return new Text('Loading...'); } }, ), image, ], ), ); } } A: A way for who only want decode image bounds: final buffer = await ui.ImmutableBuffer.fromUint8List(bytes); final descriptor = await ui.ImageDescriptor.encoded(buffer); final imageWidth = descriptor.width; final imageHeight = descriptor.height; print("imageWidth: $imageWidth, imageHeight: $imageHeight"); descriptor.dipose(); buffer.dipose(); A: A simple way how to check image dimensions that is loaded from assets. var img = await rootBundle.load("Your image path"); var decodedImage = await decodeImageFromList(img.buffer.asUint8List()); int imgWidth = decodedImage.width; int imgHeight = decodedImage.height; A: Here's a handy helper function, based on other solutions helper function Future<ImageInfo> getImageInfo(Image img) async { final c = new Completer<ImageInfo>(); img.image .resolve(new ImageConfiguration()) .addListener(new ImageStreamListener((ImageInfo i, bool _) { c.complete(i); })); return c.future; } usage Image image = Image.network("https://example.com/pic.png"); ImageInfo info = await getImageInfo(image); A: Create a method, like: Future<Size> _calculateImageDimension() { Completer<Size> completer = Completer(); Image image = Image.network("https://i.stack.imgur.com/lkd0a.png"); image.image.resolve(ImageConfiguration()).addListener( ImageStreamListener( (ImageInfo image, bool synchronousCall) { var myImage = image.image; Size size = Size(myImage.width.toDouble(), myImage.height.toDouble()); completer.complete(size); }, ), ); return completer.future; } And use it like: _calculateImageDimension().then((size) => print("size = ${size}")); // 487.0,696.0 A: You can resolve the ImageProvider to get an ImageStream, then use addListener to be notified when the image is ready. import 'dart:ui' as ui; import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { runApp(new MaterialApp( home: new MyHomePage(), )); } class MyHomePage extends StatelessWidget { Future<ui.Image> _getImage() { Completer<ui.Image> completer = new Completer<ui.Image>(); new NetworkImage('https://i.stack.imgur.com/lkd0a.png') .resolve(new ImageConfiguration()) .addListener((ImageInfo info, bool _) => completer.complete(info.image)); return completer.future; } Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("Image Dimensions Example"), ), body: new Center( child: new FutureBuilder<ui.Image>( future: _getImage(), builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) { if (snapshot.hasData) { ui.Image image = snapshot.data; return new Text( '${image.width}x${image.height}', style: Theme.of(context).textTheme.display4); } else { return new Text('Loading...'); } }, ), ), ); } } A: The other answers seem overly complicated if you just want the width and height of an image in an async function. You can get the image resolution using flutter lib directly like this: import 'dart:io'; File image = new File('image.png'); // Or any other way to get a File instance. var decodedImage = await decodeImageFromList(image.readAsBytesSync()); print(decodedImage.width); print(decodedImage.height); A: With new version of flutter old solution not working example: image.image .resolve(new ImageConfiguration()) .addListener((ImageInfo info, bool _) => completer.complete(info.image)); Below the Working version: _image.image .resolve(new ImageConfiguration()) .addListener(new ImageStreamListener((ImageInfo image, bool _) { completer.complete(image.image); })); A: Easy way to get asset images size. Future<Size> _loadAssetImageSize(String asset) async{ ByteData data = await rootBundle.load(asset); ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List()); ui.FrameInfo fi = await codec.getNextFrame(); return Size(fi.image.width.toDouble(), fi.image.height.toDouble()); } A: Does any of the solution works for Flutter web? I am unable to find any solution, if i try to use image_size_getter package its throws "Error: Unsupported operation: _Namespace". A: All the answers on this page currently only get the raw image size: that is the pixel height and width of the original image. Not the size of the image on the Flutter app. I needed that to resize bounding boxes as the page was resized. I need the current image size, and also know when it changes so I can resize the bounding box. My solution involves: * *GlobalKey and addPostFrameCallback to get the image size *Some logic to render when the image size changes At the top of my build method: final _imageKey = GlobalKey(); Size imageSize = Size.zero; @override Widget build(BuildContext context) { MediaQuery.of(context); // Trigger rebuild when window is resized. This updates the bounding box sizes. final image = Image.asset(exampleImagePath, key: _imageKey); // Yes, we call this every time the widget rebuilds, so we update our understanding of the image size. WidgetsBinding.instance.addPostFrameCallback(_updateImageSize); My _updateImageSize void _updateImageSize(Duration _) { final size = _imageKey.currentContext?.size; if (size == null) return; if (imageSize != size) { imageSize = size; // When the window is resized using keyboard shortcuts (e.g. Rectangle.app), // The widget won't rebuild AFTER this callback. Therefore, the new // image size is not used to update the bounding box drawing. // So we call setState setState(() {}); } }
stackoverflow
{ "language": "en", "length": 1010, "provenance": "stackexchange_0000F.jsonl.gz:904539", "question_score": "55", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44665955" }
828889c8ebeef56870a480e830d1ca0b8761a3e7
Stackoverflow Stackexchange Q: Notepad++ Retain code Fold on Paste I have a folded code block in Notepad++ [+] /begin{code} I want to copy and paste this code block. However, when I do so, it is expanded out, like this: /begin{code} ... /end{code} when I really want to retain the folded code and have it appear like this when I paste: [+] /begin{code} Is there any way to do this in Notepad++, or any other editor that supports this feature?
Q: Notepad++ Retain code Fold on Paste I have a folded code block in Notepad++ [+] /begin{code} I want to copy and paste this code block. However, when I do so, it is expanded out, like this: /begin{code} ... /end{code} when I really want to retain the folded code and have it appear like this when I paste: [+] /begin{code} Is there any way to do this in Notepad++, or any other editor that supports this feature?
stackoverflow
{ "language": "en", "length": 77, "provenance": "stackexchange_0000F.jsonl.gz:904584", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666079" }
86d6a5f64ac7b5d6f0bcdf5ff2c9e4af8208f935
Stackoverflow Stackexchange Q: WP API Get Post Tags Trying to get post tags with wordpress API - api call is /wp-json/wp/v2/posts ourHTMLString += '<i class="fa fa-tags">"' + postsData[i].tags + '"</i>'; It is returning these values "tags": [ 766, 19, 578 ], I need the tag name and href to this, not sure how to get this. I have tried postsData[i].wp:term[i].tag.name - cannot find a solution. Any help? thanks A: I think you need to do another request to get this and use include to list only theses tags. eg: /wp-json/wp/v2/tags?include=766,19,578 https://developer.wordpress.org/rest-api/reference/tags/
Q: WP API Get Post Tags Trying to get post tags with wordpress API - api call is /wp-json/wp/v2/posts ourHTMLString += '<i class="fa fa-tags">"' + postsData[i].tags + '"</i>'; It is returning these values "tags": [ 766, 19, 578 ], I need the tag name and href to this, not sure how to get this. I have tried postsData[i].wp:term[i].tag.name - cannot find a solution. Any help? thanks A: I think you need to do another request to get this and use include to list only theses tags. eg: /wp-json/wp/v2/tags?include=766,19,578 https://developer.wordpress.org/rest-api/reference/tags/ A: Send a request to the Wordpress site with the tag's id: http://demo.wp-api.org/wp-json/wp/v2/tags/TagID REF : https://developer.wordpress.org/rest-api/reference/tags/#definition Definition GET /wp/v2/tags/ Example Request $ curl http://demo.wp-api.org/wp-json/wp/v2/tags/ A: If we need tags in same API call we can add a custom field in our response. we can add following code in theme's function.php file add_action('rest_api_init', 'bs_rest_api_hooks'); function bs_rest_api_hooks() { register_rest_field( 'post', 'mtags', array( 'get_callback' => 'm_get_tags', ) ); } function m_get_tags($object, $field_name, $request) { $tags = get_the_tags($object["id"]); return $tags; }
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:904627", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666200" }
4aec07c463acf893d6b4813420412d245a3208dc
Stackoverflow Stackexchange Q: Vector of pairs in python I need to store start and end indexes of certain substrings. I need to do this in python. What is the python equivalent for c++ vector of pairs? A: I would suggest storing it in a dictionary (Hashmap) input = ['str1', 'str2', 'str3'] stored_as = {'str1': {'start': 1, 'end': 2}, 'str2': {'start': 0, 'end': 2}, 'str3': {'start': 1, 'end': 1}} This gives you a better representation. If you are tight on space, then you can store it as either of the following: stored_as = [(1,2), (0,2), (1,1)] or stored_as = [[1,2], [0,2], [1,1]]
Q: Vector of pairs in python I need to store start and end indexes of certain substrings. I need to do this in python. What is the python equivalent for c++ vector of pairs? A: I would suggest storing it in a dictionary (Hashmap) input = ['str1', 'str2', 'str3'] stored_as = {'str1': {'start': 1, 'end': 2}, 'str2': {'start': 0, 'end': 2}, 'str3': {'start': 1, 'end': 1}} This gives you a better representation. If you are tight on space, then you can store it as either of the following: stored_as = [(1,2), (0,2), (1,1)] or stored_as = [[1,2], [0,2], [1,1]] A: If you use slice objects, you can use them to select the substrings directly: In [924]: al = [slice(0,3), slice(2,5), slice(5,10)] In [925]: astr = 'this is a long enough string' In [926]: [astr[s] for s in al] Out[926]: ['thi', 'is ', 'is a '] Or with a list of tuples: In [927]: at = [(0,3), (2,5), (5,10)] In [928]: [astr[s[0]:s[1]] for s in at] Out[928]: ['thi', 'is ', 'is a '] They could even be named tuples. or a list of lists. We can even hide that slice iteration with an itemgetter: In [933]: import operator In [934]: f=operator.itemgetter(*al) In [935]: f Out[935]: operator.itemgetter(slice(0, 3, None), slice(2, 5, None), slice(5, 10, None)) In [936]: f(astr) Out[936]: ('thi', 'is ', 'is a ') This list of slices could also contain scalar indexes: In [945]: al = [0, slice(5,7), slice(10,14), -1] In [946]: operator.itemgetter(*al)(astr) Out[946]: ('t', 'is', 'long', 'g')
stackoverflow
{ "language": "en", "length": 248, "provenance": "stackexchange_0000F.jsonl.gz:904635", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666232" }
f1a5ca73e12e1e1a284bdbe69d6dd03ffa9476ff
Stackoverflow Stackexchange Q: Round off to 0.5 SQL I'm new in SQL. How do I round off if: 1.01 -- 1.24 -> 1 1.25 -- 1.49 -> 1.5 1.51 -- 1.74 -> 1.5 1.75 -- 1.99 -> 2 Thanks for your help, much appreciated. A: You can just do: select floor(val * 2 + 0.5) / 2
Q: Round off to 0.5 SQL I'm new in SQL. How do I round off if: 1.01 -- 1.24 -> 1 1.25 -- 1.49 -> 1.5 1.51 -- 1.74 -> 1.5 1.75 -- 1.99 -> 2 Thanks for your help, much appreciated. A: You can just do: select floor(val * 2 + 0.5) / 2
stackoverflow
{ "language": "en", "length": 55, "provenance": "stackexchange_0000F.jsonl.gz:904636", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666237" }
8329bfae61a6cf96a3e93ec415926e45a754c292
Stackoverflow Stackexchange Q: JIRA: Filter all issues that has subtasks of a particular component I want to filter out all issues that has subtasks but of a particular component. The following works but it returns all stories with subtasks. project = ABCDEF123 AND issuetype in (Story) and issueFunction in hasSubtasks() I have tried this but it doesn't work, returning nothing project = ABCDEF123 AND issuetype in (Story) and issueFunction in subtasksOf("component = xyz1234") So I want JIRA to return all stories with subtasks and the component of that subtask is xyz1234. I do not want to use any plugins.Hope you can help. A: I suppose you are using Adaptivist ScriptRunner plugin for JIRA. Documentation says, that subquery returns parents of the subtasks. It looks like you have to swap the query for the subtasks and parents: issuefunction in subtasksOf(project = ABCDEF123 AND issuetype in (Story)) and "component = xyz1234"
Q: JIRA: Filter all issues that has subtasks of a particular component I want to filter out all issues that has subtasks but of a particular component. The following works but it returns all stories with subtasks. project = ABCDEF123 AND issuetype in (Story) and issueFunction in hasSubtasks() I have tried this but it doesn't work, returning nothing project = ABCDEF123 AND issuetype in (Story) and issueFunction in subtasksOf("component = xyz1234") So I want JIRA to return all stories with subtasks and the component of that subtask is xyz1234. I do not want to use any plugins.Hope you can help. A: I suppose you are using Adaptivist ScriptRunner plugin for JIRA. Documentation says, that subquery returns parents of the subtasks. It looks like you have to swap the query for the subtasks and parents: issuefunction in subtasksOf(project = ABCDEF123 AND issuetype in (Story)) and "component = xyz1234" A: I've worked it out project = ABCDDEF123 AND issuetype in (Story) AND issueFunction in linkedIssuesOf("component in (xyz1234)")
stackoverflow
{ "language": "en", "length": 165, "provenance": "stackexchange_0000F.jsonl.gz:904642", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666252" }
c884092179267fd8367fff53ddaa2bddfdb9565b
Stackoverflow Stackexchange Q: PopoverPresentationController coming as nil Created a SingleViewApplication in that I have placed a button. Now clicking on button I need to display a tableView as popover. The TableViewController is created in xib. The issue is tableViewController.popoverPresentationController always comes as nil see below code let filterVC = TableViewController(nibName: "TableViewController", bundle: nil) var filterDistanceViewController = UINavigationController(rootViewController: filterVC) filterDistanceViewController.preferredContentSize = CGSize(width: 300, height: 200) let popoverPresentationViewController = filterDistanceViewController.popoverPresentationController popoverPresentationViewController?.permittedArrowDirections = .any if let pop = filterDistanceViewController.popoverPresentationController { pop.delegate = self } in above code filterDistanceViewController.popoverPresentationController is always coming as nil Any hint in right direction will be highly appreciated. A: You are not presenting anything, so you need to present the popoverPresentationViewController on the current viewcontroller, for example: @IBAction func importantButtonPressed(_ sender: UIButton) { let tableViewController = UITableViewController() tableViewController.modalPresentationStyle = .popover present(tableViewController, animated: true, completion: nil) if let pop = tableViewController.popoverPresentationController { pop.delegate = self } }
Q: PopoverPresentationController coming as nil Created a SingleViewApplication in that I have placed a button. Now clicking on button I need to display a tableView as popover. The TableViewController is created in xib. The issue is tableViewController.popoverPresentationController always comes as nil see below code let filterVC = TableViewController(nibName: "TableViewController", bundle: nil) var filterDistanceViewController = UINavigationController(rootViewController: filterVC) filterDistanceViewController.preferredContentSize = CGSize(width: 300, height: 200) let popoverPresentationViewController = filterDistanceViewController.popoverPresentationController popoverPresentationViewController?.permittedArrowDirections = .any if let pop = filterDistanceViewController.popoverPresentationController { pop.delegate = self } in above code filterDistanceViewController.popoverPresentationController is always coming as nil Any hint in right direction will be highly appreciated. A: You are not presenting anything, so you need to present the popoverPresentationViewController on the current viewcontroller, for example: @IBAction func importantButtonPressed(_ sender: UIButton) { let tableViewController = UITableViewController() tableViewController.modalPresentationStyle = .popover present(tableViewController, animated: true, completion: nil) if let pop = tableViewController.popoverPresentationController { pop.delegate = self } } A: You may do like below. @IBAction func popoverBtnPressed(_ sender: Any) { let vc2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController2") vc2.modalPresentationStyle = .popover vc2.popoverPresentationController?.delegate = self vc2.popoverPresentationController?.barButtonItem = popoverBtn vc2.popoverPresentationController?.sourceRect = .zero present(vc2, animated: true, completion: nil) } A: Until you've set a modalPresentationStyle on your VC, the popoverPresentationController property will be nil. Ensure that you set the modalPresentationStyle before accessing.
stackoverflow
{ "language": "en", "length": 206, "provenance": "stackexchange_0000F.jsonl.gz:904647", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666281" }
b2a29504fe3d1492396b3a077d925274781992e7
Stackoverflow Stackexchange Q: Converting ERDs in visio 2016 to SQL Script to create tables As the title describes, is there a way to convert ERDs in visio 2016 to SQL Script to create tables? I'm using the crow's foot database notation diagram. I've tried viso forward engineer but it cannot install on my Win10 x64 machine.
Q: Converting ERDs in visio 2016 to SQL Script to create tables As the title describes, is there a way to convert ERDs in visio 2016 to SQL Script to create tables? I'm using the crow's foot database notation diagram. I've tried viso forward engineer but it cannot install on my Win10 x64 machine.
stackoverflow
{ "language": "en", "length": 54, "provenance": "stackexchange_0000F.jsonl.gz:904667", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666354" }
04caf36bbf0176975b088763d52864f85e9163d5
Stackoverflow Stackexchange Q: Max pool layer vs Convolution with stride performance In most of the architectures, conv layers are being followed by a pooling layer (max / avg etc.). As those pooling layers are just selecting the output of previous layer (i.e. conv), can we just use convolution with stride 2 and expect the similar accuracy results with reduced process need? A: Yes that can be done. Its explained in the paper 'Striving for simplicity: The all convolutional net' https://arxiv.org/pdf/1412.6806.pdf. Quote from the paper: 'We find that max-pooling can simply be replaced by a convolutional layer with increased stride without loss in accuracy on several image recognition benchmarks'
Q: Max pool layer vs Convolution with stride performance In most of the architectures, conv layers are being followed by a pooling layer (max / avg etc.). As those pooling layers are just selecting the output of previous layer (i.e. conv), can we just use convolution with stride 2 and expect the similar accuracy results with reduced process need? A: Yes that can be done. Its explained in the paper 'Striving for simplicity: The all convolutional net' https://arxiv.org/pdf/1412.6806.pdf. Quote from the paper: 'We find that max-pooling can simply be replaced by a convolutional layer with increased stride without loss in accuracy on several image recognition benchmarks'
stackoverflow
{ "language": "en", "length": 106, "provenance": "stackexchange_0000F.jsonl.gz:904678", "question_score": "36", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666390" }
ee67b0ecd50665fc0d6af5ae7c5fa91825232250
Stackoverflow Stackexchange Q: Multiply numbers and return the number with a decimal I don't know if i am asking my question right, but i want to know if its possible for me to multiply two numbers, and place a decimal depending on the length of the number? I am currently doing something like this def multiply(input1, input1): num = (input1 * input1) if len(str(num)) == 4 and str(num).isdigit(): print(num) return num multiply(225, 10) Instead of returning something like 2250, i will like to return something like 2.25k. Is there an inbuilt function in python to achieve this? Thank you. Now i am currently doing something like this from __future__ import division def multiply(string1, string2): num = (string1 * string2) if len(str(num)) == 4 and str(num).isdigit(): num = format(num/1000, '.2f') print(num + "k") elif len(str(num)) == 5 and str(num).isdigit(): num = format(num/1000, '.1f') print(num + "k") return num multiply(225, 10) How efficient is this? A: If you want a simple example of how this can be done, take a look, def m(a, b): num = float(a * b) if num / 1000 > 1: return str(num/1000) + "k" else: return num >>> m(225, 10) '2.25k'
Q: Multiply numbers and return the number with a decimal I don't know if i am asking my question right, but i want to know if its possible for me to multiply two numbers, and place a decimal depending on the length of the number? I am currently doing something like this def multiply(input1, input1): num = (input1 * input1) if len(str(num)) == 4 and str(num).isdigit(): print(num) return num multiply(225, 10) Instead of returning something like 2250, i will like to return something like 2.25k. Is there an inbuilt function in python to achieve this? Thank you. Now i am currently doing something like this from __future__ import division def multiply(string1, string2): num = (string1 * string2) if len(str(num)) == 4 and str(num).isdigit(): num = format(num/1000, '.2f') print(num + "k") elif len(str(num)) == 5 and str(num).isdigit(): num = format(num/1000, '.1f') print(num + "k") return num multiply(225, 10) How efficient is this? A: If you want a simple example of how this can be done, take a look, def m(a, b): num = float(a * b) if num / 1000 > 1: return str(num/1000) + "k" else: return num >>> m(225, 10) '2.25k'
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:904729", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666512" }
d16c26c1f5e9e3a44f145a337b0c8bd1c001937d
Stackoverflow Stackexchange Q: Semantic UI Sidebar pushes elements outside of screen width I'm not sure if I'm doing something wrong or if this is the intended result but the I'm using semantic ui's sidebar and it pushes everything past the max screen width. Am I missing something here? <div class="ui bottom attached segment pushable"> <div class="ui left vertical menu visible thin attached inverted sidebar"> <a class="item"> Item 1 </a> <a class="item"> Item 2 </a> <a class="item"> Item 3 </a> </div> <div class="pusher"> <div id="search-bar"> <div class="ui fluid action input"> <input placeholder="Search.."> <div class="ui green button"> Search </div> </div> </div> <h3 class="ui block header"> Item </h3> </div> </div> https://jsfiddle.net/kour6d1x/ A: If you don't want the content "pushed" for the Semantic UI sidebars you should use the .overlay class on it - relevant demos Like the class name suggests, it will overlay the sidebar rather than pushing the content along with it. Add overlay class to the <div class="ui left vertical menu visible thin attached inverted sidebar"> element. JSfiddle
Q: Semantic UI Sidebar pushes elements outside of screen width I'm not sure if I'm doing something wrong or if this is the intended result but the I'm using semantic ui's sidebar and it pushes everything past the max screen width. Am I missing something here? <div class="ui bottom attached segment pushable"> <div class="ui left vertical menu visible thin attached inverted sidebar"> <a class="item"> Item 1 </a> <a class="item"> Item 2 </a> <a class="item"> Item 3 </a> </div> <div class="pusher"> <div id="search-bar"> <div class="ui fluid action input"> <input placeholder="Search.."> <div class="ui green button"> Search </div> </div> </div> <h3 class="ui block header"> Item </h3> </div> </div> https://jsfiddle.net/kour6d1x/ A: If you don't want the content "pushed" for the Semantic UI sidebars you should use the .overlay class on it - relevant demos Like the class name suggests, it will overlay the sidebar rather than pushing the content along with it. Add overlay class to the <div class="ui left vertical menu visible thin attached inverted sidebar"> element. JSfiddle A: I have used below css to reduce thr width of pusher when sidebar is open. In below code 58px is the width of sidebar .sidebar.visible + .pusher{ margin-right: 58px; } A: Custom CSS subtracting the width of the sidebar would do the trick: .sidebar.visible + .pusher { width: calc(100% - 260px); }
stackoverflow
{ "language": "en", "length": 218, "provenance": "stackexchange_0000F.jsonl.gz:904731", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666515" }
90e5a8998cf18bde95d41051607a3d908a85225b
Stackoverflow Stackexchange Q: Using redisson how to check if a given key is present in redis I have a set of keys and i want to check if any of those are present in my redis db. How can i do so using redisson library ? A: RedissonKeys.countExists(String... name) can help you to determine if the key exists, without knowing the type of it beforehand. I think this what you need.
Q: Using redisson how to check if a given key is present in redis I have a set of keys and i want to check if any of those are present in my redis db. How can i do so using redisson library ? A: RedissonKeys.countExists(String... name) can help you to determine if the key exists, without knowing the type of it beforehand. I think this what you need. A: You can use isExists function to check whether the key is present in redis or not. Here is the ref link: Redis-commands-mapping-with-redisson
stackoverflow
{ "language": "en", "length": 92, "provenance": "stackexchange_0000F.jsonl.gz:904777", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666694" }
0af53de617f2e9e602a0e08d6b53b3ffc1d0e441
Stackoverflow Stackexchange Q: How to split an image dataset into train and test sets? I'm working on 256_ObjectCategories dataset from Caltech. They have organised all the images in 256 categories in different folders. I'm using ImageDataGenerator from Keras to load the dataset but I'm not able to split it into training and testing using the same. How can I do this in a terminal without moving images or changing directories? Any help is appreciated. Thank you. :) A: This doesn´t seem to be possible out of the box with ImageDataGenerator right now. See this thread: https://github.com/fchollet/keras/issues/5862 User AloshkaD suggests as a workaround that you create an index list with glob: rasterList = glob.glob(os.path.join(path_of_your_image_directory, '*.jpg')), split that programmatically and feed the validation part of that list into the validation_data parameter of fit_generator().
Q: How to split an image dataset into train and test sets? I'm working on 256_ObjectCategories dataset from Caltech. They have organised all the images in 256 categories in different folders. I'm using ImageDataGenerator from Keras to load the dataset but I'm not able to split it into training and testing using the same. How can I do this in a terminal without moving images or changing directories? Any help is appreciated. Thank you. :) A: This doesn´t seem to be possible out of the box with ImageDataGenerator right now. See this thread: https://github.com/fchollet/keras/issues/5862 User AloshkaD suggests as a workaround that you create an index list with glob: rasterList = glob.glob(os.path.join(path_of_your_image_directory, '*.jpg')), split that programmatically and feed the validation part of that list into the validation_data parameter of fit_generator().
stackoverflow
{ "language": "en", "length": 129, "provenance": "stackexchange_0000F.jsonl.gz:904780", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666703" }
8af3600c01fbe57b1c8b683085a9d49520c710ed
Stackoverflow Stackexchange Q: Disable throwing exceptions for E_USER_WARNING Laravel is returning a 500 when I do: trigger_error("Some message", E_USER_WARNING); I need it to not error out, but I do want it to run through \App\Exceptions\Handler::report which logs the warning to Sentry. How do I disable turning warnings and errors into exceptions with Laravel 5.2? A: You could edit laravel's error handler to only report warnings in HandleExceptions.php public function handleError($level, $message, $file = '', $line = 0, $context = []) { $exception = new ErrorException($message, 0, $level, $file, $line); if (E_USER_WARNING & $level) { $this->getExceptionHandler()->report($exception); } elseif (error_reporting() & $level) { throw $exception; } } User Warning: Modifying vendor code is usually a bad idea. You can avoid modifying vendor code by extending the HandleExceptions class and registering your new class in Kernel.php MyHandleExceptions extends HandleExceptions { public function handleError($level, $message, $file = '', $line = 0, $context = []) { if (E_USER_WARNING & $level) { $this->getExceptionHandler()->report(new ErrorException($message, 0, $level, $file, $line)); } else { return parent::handleError($level, $message, $file, $line, $context); } } }
Q: Disable throwing exceptions for E_USER_WARNING Laravel is returning a 500 when I do: trigger_error("Some message", E_USER_WARNING); I need it to not error out, but I do want it to run through \App\Exceptions\Handler::report which logs the warning to Sentry. How do I disable turning warnings and errors into exceptions with Laravel 5.2? A: You could edit laravel's error handler to only report warnings in HandleExceptions.php public function handleError($level, $message, $file = '', $line = 0, $context = []) { $exception = new ErrorException($message, 0, $level, $file, $line); if (E_USER_WARNING & $level) { $this->getExceptionHandler()->report($exception); } elseif (error_reporting() & $level) { throw $exception; } } User Warning: Modifying vendor code is usually a bad idea. You can avoid modifying vendor code by extending the HandleExceptions class and registering your new class in Kernel.php MyHandleExceptions extends HandleExceptions { public function handleError($level, $message, $file = '', $line = 0, $context = []) { if (E_USER_WARNING & $level) { $this->getExceptionHandler()->report(new ErrorException($message, 0, $level, $file, $line)); } else { return parent::handleError($level, $message, $file, $line, $context); } } } A: Since you can't display the normal content of the page when you are inside the ErrorHandler, you have to throw another error message: Route::get('error', function() { $client = new Raven_Client(env("SENTRY_DSN")); $client->captureMessage("Some Warning", ['log'], [ 'level' => 'warning' ]); }); This will create a custom warning entry for sentry without throwing a real error in php that would stop your normal code. you could also wrap it in a function function trigger_sentry_warning($message) { $client = new Raven_Client(env("SENTRY_DSN")); $client->captureMessage($message, ['log'], [ 'level' => 'warning' ]); } A: I think it should be handled by php. did you try error_reporting()? set_error_handler more information: Out of the box, Laravel supports writing log information to single files, daily files, the syslog, and the errorlog. To configure which storage mechanism Laravel uses, you should modify the log option in your config/app.php configuration file. For example, if you wish to use daily log files instead of a single file, you should set the log value in your app configuration file to daily laravel error and logging
stackoverflow
{ "language": "en", "length": 342, "provenance": "stackexchange_0000F.jsonl.gz:904819", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666834" }
a751221d654c73e1fc691dd7917f201f4a3fb845
Stackoverflow Stackexchange Q: How to efficiently combine two columns into one column/ combine strings? I have two columns(A and Date) like below, and need to combine them into one column like column C. This dataset has more than 900,000 rows. Then I met with two main problems. * *The data type of column "Date" is timestamp, when I combine them with string type will cause error: TypeError: unsupported operand type(s) for +: 'Timestamp' and 'str'. *The code is way too time-costing. I wrote a for loop to do the combination as below: for i in range(0,911462): df['Combine'][i]=df['Date'][i]+df['A'][i] I guess it is because using for-loop is doing the combination row by row, thus every single combination cost a lot of time on system IO. Is there any method to do this job more efficiently? A: You have to explicitly case the Timestamp to a string e.g. with strftime: In [11]: df = pd.DataFrame([[pd.Timestamp("2017-01-01"), 'a'], [pd.Timestamp("2017-01-02"), 'b']], columns=["A", "B"]) In [12]: df["A"].dt.strftime("%Y-%m-%d") + df["B"] Out[12]: 0 2017-01-01a 1 2017-01-02b dtype: object
Q: How to efficiently combine two columns into one column/ combine strings? I have two columns(A and Date) like below, and need to combine them into one column like column C. This dataset has more than 900,000 rows. Then I met with two main problems. * *The data type of column "Date" is timestamp, when I combine them with string type will cause error: TypeError: unsupported operand type(s) for +: 'Timestamp' and 'str'. *The code is way too time-costing. I wrote a for loop to do the combination as below: for i in range(0,911462): df['Combine'][i]=df['Date'][i]+df['A'][i] I guess it is because using for-loop is doing the combination row by row, thus every single combination cost a lot of time on system IO. Is there any method to do this job more efficiently? A: You have to explicitly case the Timestamp to a string e.g. with strftime: In [11]: df = pd.DataFrame([[pd.Timestamp("2017-01-01"), 'a'], [pd.Timestamp("2017-01-02"), 'b']], columns=["A", "B"]) In [12]: df["A"].dt.strftime("%Y-%m-%d") + df["B"] Out[12]: 0 2017-01-01a 1 2017-01-02b dtype: object A: Try with astype, it can cast object like Timestamp to string: import pandas as pd df = pd.DataFrame({'A':['XX','YY','ZZ','AA'], 'Date':[pd.Timestamp("2016-01-01"),pd.Timestamp('2016-01-15'),pd.Timestamp('2016-12-01'),pd.Timestamp('2016-07-12')]}) df['Combine'] = df['Date'].astype(str) + '_'+df['A'] df df will be: A Date Combine 0 XX 2016-01-01 2016-01-01_XX 1 YY 2016-01-15 2016-01-15_YY 2 ZZ 2016-12-01 2016-12-01_ZZ 3 AA 2016-07-12 2016-07-12_AA A: Setup df = pd.DataFrame(dict( A='XX YY ZZ AA'.split(), Date=pd.date_range('2017-03-31', periods=4) )) Option 1 apply with a lambda based on format and dictionary unpacking. This is a slow, but cool way to do it. df.assign(C=df.apply(lambda x: '{Date:%Y-%m-%d}_{A}'.format(**x), 1)) A Date C 0 XX 2017-03-31 2017-03-31_XX 1 YY 2017-04-01 2017-04-01_YY 2 ZZ 2017-04-02 2017-04-02_ZZ 3 AA 2017-04-03 2017-04-03_AA Option 2 numpy.core.defchararray.add Very fast way to do it using 'datetime64[D]' to round to the day. chr_add = np.core.defchararray.add d = df.Date.values.astype('datetime64[D]').astype(str) a = df.A.values.astype(str) df.assign(C=chr_add(chr_add(d, '_'), a)) A Date C 0 XX 2017-03-31 2017-03-31_XX 1 YY 2017-04-01 2017-04-01_YY 2 ZZ 2017-04-02 2017-04-02_ZZ 3 AA 2017-04-03 2017-04-03_AA Option 3 Rip-off of @AndyHayden's answer with a small twist. I'll add my underscore '_' in the strftime... Mainly, this is what I'll use in timeit. df.assign(C=df.Date.dt.strftime('%Y-%m-%d_') + df.A) A Date C 0 XX 2017-03-31 2017-03-31_XX 1 YY 2017-04-01 2017-04-01_YY 2 ZZ 2017-04-02 2017-04-02_ZZ 3 AA 2017-04-03 2017-04-03_AA Timing %%timeit chr_add = np.core.defchararray.add d = df.Date.values.astype('datetime64[D]').astype(str) a = df.A.values.astype(str) chr_add(chr_add(d, '_'), a) %timeit df.assign(C=df.apply(lambda x: '{Date:%Y-%m-%d}_{A}'.format(**x), 1)) %timeit df.assign(C=df.Date.dt.strftime('%Y-%m-%d_') + df.A) small data 10000 loops, best of 3: 53.2 µs per loop 1000 loops, best of 3: 1.14 ms per loop 1000 loops, best of 3: 831 µs per loop large data df = pd.concat([df] * 10000, ignore_index=True) 10 loops, best of 3: 80.3 ms per loop 1 loop, best of 3: 4.58 s per loop 1 loop, best of 3: 233 ms per loop A: About 1., you can print the timestamp as a string About 2. If you are planning to run this on a regular basis, you should consider to use map/reduce. MrJob is a tool written in python that allows you to run locally you map/reduce jobs, splitting them into multiple jobs that run in parallel. Check the examples, your script should be very simple. Important note: this works only if your are not worry about the rows order and is useful only if you have more than one core available. Best.
stackoverflow
{ "language": "en", "length": 545, "provenance": "stackexchange_0000F.jsonl.gz:904867", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44666974" }
dfedfcaf7d6990447f37365a9beb4117562b7215
Stackoverflow Stackexchange Q: Sum the “previous row” value with existing row value in a SELECT statement I want to sum the previous value with the existing value in that row. Here's my code: SELECT co.partner_id, to_char(co.date, 'DD') AS day, to_char(co.date, 'MM') AS month, to_char(co.date, 'YYYY') AS year, sum(col.qty * p.price) AS priceday FROM order_detail col JOIN ORDER co ON co.id = col.order_id JOIN product p ON p.id = col.product_id GROUP BY co.partner_id, to_char(co.date, 'MM'), to_char(co.date, 'YYYY'), to_char(co.date, 'DD') that code become like this: the table sould be like this : Thank You. A: Here is an example of what you need (I hope): test=# with nums(n) as ( select z from generate_series(1, 10) as _(z) ) select n, sum(n) over (order by n) from nums; n | sum ----+----- 1 | 1 2 | 3 3 | 6 4 | 10 5 | 15 6 | 21 7 | 28 8 | 36 9 | 45 10 | 55 (10 rows) It is so called "window functions", see documentation here: https://www.postgresql.org/docs/current/static/tutorial-window.html
Q: Sum the “previous row” value with existing row value in a SELECT statement I want to sum the previous value with the existing value in that row. Here's my code: SELECT co.partner_id, to_char(co.date, 'DD') AS day, to_char(co.date, 'MM') AS month, to_char(co.date, 'YYYY') AS year, sum(col.qty * p.price) AS priceday FROM order_detail col JOIN ORDER co ON co.id = col.order_id JOIN product p ON p.id = col.product_id GROUP BY co.partner_id, to_char(co.date, 'MM'), to_char(co.date, 'YYYY'), to_char(co.date, 'DD') that code become like this: the table sould be like this : Thank You. A: Here is an example of what you need (I hope): test=# with nums(n) as ( select z from generate_series(1, 10) as _(z) ) select n, sum(n) over (order by n) from nums; n | sum ----+----- 1 | 1 2 | 3 3 | 6 4 | 10 5 | 15 6 | 21 7 | 28 8 | 36 9 | 45 10 | 55 (10 rows) It is so called "window functions", see documentation here: https://www.postgresql.org/docs/current/static/tutorial-window.html A: You can use Window Functions with Frame clause. If you want to SUM with the previous row then you will do: SELECT o.partner_id, o.date, SUM(SUM(p.price * od.qty)) OVER (PARTITION BY o.partner_id ORDER BY o.partner_id, o.date ROWS 1 PRECEDING) AS priceday FROM test.order AS o INNER JOIN test.order_detail AS od ON o.id = od.order_id INNER JOIN test.product AS p ON od.product_id = p.id GROUP BY o.partner_id, o.date; Notice the ROWS 1 PRECEDING. If you want to SUM with all the previous rows (running total) then you will do: SELECT o.partner_id, o.date, SUM(SUM(p.price * od.qty)) OVER (PARTITION BY o.partner_id ORDER BY o.partner_id, o.date ROWS UNBOUNDED PRECEDING) AS priceday FROM test.order AS o INNER JOIN test.order_detail AS od ON o.id = od.order_id INNER JOIN test.product AS p ON od.product_id = p.id GROUP BY o.partner_id, o.date; Notice the ROWS UNBOUNDED PRECEDING. Explanation SUM(SUM(p.price * od.qty)) OVER (PARTITION BY o.partner_id ORDER BY o.partner_id, o.date ROWS 1 PRECEDING) AS priceday is the main actor: * *SUM(p.price * od.qty) - computes the price per day *SUM(SUM(...)) OVER (...) - sums multiple prices on multiple days *PARTITION BY o.partner_id - required in order to keep the SUM within the boundaries of the partner_id *ORDER BY o.partner_id, o.date - required to order the rows within the partition by date *ROWS 1 PRECEDING - in order to include the previous row in the SUM along with the current row Complete example (for easier testing) CREATE SCHEMA test; CREATE TABLE test.order ( id SERIAL PRIMARY KEY, partner_id int, date date ); CREATE TABLE test.product ( id SERIAL PRIMARY KEY, price DECIMAL ); CREATE TABLE test.order_detail ( id SERIAL PRIMARY KEY, order_id int REFERENCES test.order (id), product_id int REFERENCES test.product (id), qty int ); INSERT INTO test.order (partner_id, date) VALUES (531, '2017-06-20'), (531, '2017-06-21'), (531, '2017-06-22'), (532, '2017-06-20'), (532, '2017-06-20'), (532, '2017-06-22'), (532, '2017-06-23'); INSERT INTO test.product (price) VALUES (1000.0); INSERT INTO test.order_detail (order_id, product_id, qty) VALUES (1, 1, 300), (2, 1, 230), (3, 1, 130), (4, 1, 300), (5, 1, 230), (6, 1, 130), (7, 1, 100); -- sum with the previous row SELECT o.partner_id, o.date, SUM(SUM(p.price * od.qty)) OVER (PARTITION BY o.partner_id ORDER BY o.partner_id, o.date ROWS 1 PRECEDING) AS priceday FROM test.order AS o INNER JOIN test.order_detail AS od ON o.id = od.order_id INNER JOIN test.product AS p ON od.product_id = p.id GROUP BY o.partner_id, o.date; -- sum with all the previous rows SELECT o.partner_id, o.date, SUM(SUM(p.price * od.qty)) OVER (PARTITION BY o.partner_id ORDER BY o.partner_id, o.date ROWS UNBOUNDED PRECEDING) AS priceday FROM test.order AS o INNER JOIN test.order_detail AS od ON o.id = od.order_id INNER JOIN test.product AS p ON od.product_id = p.id GROUP BY o.partner_id, o.date; DROP SCHEMA test CASCADE;
stackoverflow
{ "language": "en", "length": 613, "provenance": "stackexchange_0000F.jsonl.gz:904876", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667009" }
e43ba490fadca85d4f77feafbe4b239d8bb8027d
Stackoverflow Stackexchange Q: Haskell pattern matching not allowed in Elm? Following this Elm tutorial and I assumed that the function update : Msg -> Model -> Model is defined in the tutorial as update msg model = case msg of Increment -> model + 1 Deccrement -> model - 1 Reset -> 0 I thought I would define it the same way but with syntax I prefer: update Increment model = model + 1 update Decrement model = model - 1 update Reset model = 0 But this doesn't compile, does Elm not support this syntax or did I make a mistake? A: One of the goals of Elm is to use a consistent style; removing redundant syntax is a conclusion of this. For that reason, you will not find any where clause and function definitions with multiple variants are not permitted either.
Q: Haskell pattern matching not allowed in Elm? Following this Elm tutorial and I assumed that the function update : Msg -> Model -> Model is defined in the tutorial as update msg model = case msg of Increment -> model + 1 Deccrement -> model - 1 Reset -> 0 I thought I would define it the same way but with syntax I prefer: update Increment model = model + 1 update Decrement model = model - 1 update Reset model = 0 But this doesn't compile, does Elm not support this syntax or did I make a mistake? A: One of the goals of Elm is to use a consistent style; removing redundant syntax is a conclusion of this. For that reason, you will not find any where clause and function definitions with multiple variants are not permitted either.
stackoverflow
{ "language": "en", "length": 141, "provenance": "stackexchange_0000F.jsonl.gz:904882", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667027" }
05ac87983f618aaa09a4ab4d07f05ebbf62ea680
Stackoverflow Stackexchange Q: Python ipywidgets checkbox events I am using ipywidgets.widgets.Checkbox. Is there any way to handle the checkbox events? Please do help. I am a beginner. edit: How to create a list of checkboxes? A: Building on Jacques' answer: If using Jupyter Lab, rather than a standard Jupyter Notebook, you must also create an output widget and tell the callback function to write to it using a decorator. So the given example becomes: import ipywidgets as widgets box = widgets.Checkbox(False, description='checker') out = widgets.Output() @out.capture() def changed(b): print(b) box.observe(changed) display(box) display(out) These steps are documented here, but it is obvious that they are required when using Jupyter Lab.
Q: Python ipywidgets checkbox events I am using ipywidgets.widgets.Checkbox. Is there any way to handle the checkbox events? Please do help. I am a beginner. edit: How to create a list of checkboxes? A: Building on Jacques' answer: If using Jupyter Lab, rather than a standard Jupyter Notebook, you must also create an output widget and tell the callback function to write to it using a decorator. So the given example becomes: import ipywidgets as widgets box = widgets.Checkbox(False, description='checker') out = widgets.Output() @out.capture() def changed(b): print(b) box.observe(changed) display(box) display(out) These steps are documented here, but it is obvious that they are required when using Jupyter Lab. A: There aren't any direct events but you can use the observe event. That will likely create more events than you want so you may want to filter them down to one. from IPython.display import display from ipywidgets import Checkbox box = Checkbox(False, description='checker') display(box) def changed(b): print(b) box.observe(changed) To create a "list" of widgets you can use container widgets. From the link: from ipywidgets import Button, HBox, VBox words = ['correct', 'horse', 'battery', 'staple'] items = [Button(description=w) for w in words] left_box = VBox([items[0], items[1]]) right_box = VBox([items[2], items[3]]) HBox([left_box, right_box])
stackoverflow
{ "language": "en", "length": 199, "provenance": "stackexchange_0000F.jsonl.gz:904895", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667052" }
d1cfcc5416192b2b35f6624256d45fab2870049c
Stackoverflow Stackexchange Q: How do I only pass one parameter to a function when it expects two? fun multipleParams(id: Int = 1 , name: String) { ... } I created the above method in the class. The following method call is a working correctly with: multipleParams(1,"Rose") Is it possible to use it in a way, such that sometimes I pass only name and sometimes both? multipleParams(1,"Rose") multipleParams("Rose") A: You're almost there -- you just need to utilize named arguments since you've already have them named: multipleParams(name = "Rose") This will use the default value of 1 for id as it is not passed and use "Rose" for name. You can't simply use positional arguments here because you're not supplying the first argument, so use the names you've given.
Q: How do I only pass one parameter to a function when it expects two? fun multipleParams(id: Int = 1 , name: String) { ... } I created the above method in the class. The following method call is a working correctly with: multipleParams(1,"Rose") Is it possible to use it in a way, such that sometimes I pass only name and sometimes both? multipleParams(1,"Rose") multipleParams("Rose") A: You're almost there -- you just need to utilize named arguments since you've already have them named: multipleParams(name = "Rose") This will use the default value of 1 for id as it is not passed and use "Rose" for name. You can't simply use positional arguments here because you're not supplying the first argument, so use the names you've given. A: I want to add on to the answer of @Andrew Li. You can just change the order of arguments to achieve that. fun multipleParams(name: String, id: Int = 1) { ... } Now you can call function following way: multipleParams("Rose", 1) multipleParams("Rose") Note: Preferably default arguments should be at the end of function parameters. Then you need not use named arguments. A: I want to add on to the @chandil03's answer. "default arguments should be at the end of function parameters" ,but except the Function types parameter, if you want to using Lambda Expression, for example: fun multipleParams(name: String, id: Int = 1, block: () -> Unit) { ... } multipleParams("Rose") {}; multipleParams("Rose", 1) {};
stackoverflow
{ "language": "en", "length": 242, "provenance": "stackexchange_0000F.jsonl.gz:904930", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667183" }
8eb6ffaaba1967eeb9e752697775cf5463a59e3c
Stackoverflow Stackexchange Q: How to solve "Missing Marketing Icon. iOS Apps must include a 1024x1024px" I am uploading app in iTunes from Xcode 9.0...This error is showing on the last step. How to solve this? 1024x1024px icon is present in my icons list A: Tap little grey circle arrow next to App Icons Source to go to the icon drag/drop screen. Then go to the bottom and drag your new 1024 icon in the 1024 slot Hint: Your [email protected] icon is the same thing as this requirement and you already have it because you already use it in the App Store through iTunes Connect
Q: How to solve "Missing Marketing Icon. iOS Apps must include a 1024x1024px" I am uploading app in iTunes from Xcode 9.0...This error is showing on the last step. How to solve this? 1024x1024px icon is present in my icons list A: Tap little grey circle arrow next to App Icons Source to go to the icon drag/drop screen. Then go to the bottom and drag your new 1024 icon in the 1024 slot Hint: Your [email protected] icon is the same thing as this requirement and you already have it because you already use it in the App Store through iTunes Connect A: Now onwards we need to add a new icon in our project with the size 1024X1024. Please see below-attached image. This issue was stared from WWDC 2017. Note: - Do not upload or use the beta version (mac os or Xcode) for app upload. As per Apple recommendation. I already got mail from Apple about this. A: For the XCode 9: we need to drag a new icon with size 1024pt new available icon item named "App Store iOS 1024pt" under AppIcon image set. Make sure to use icon in PNG format without alpha/transparency. Thanks to @Hammoud for sharing transparency experience ! After doing this stuff, this warning should be gone and you should be able to see something like this. Happy Coding ! A: Since XCode 12 you will have to explicitly activate "Mac" in your Assets as a Device for macCatalyst apps: After you have done that, you will see some new frames inside the main windows where you can add AppIcons for Mac. You have to add your 1024x1024 logo to the new frame "Mac 512pt 1024x1024px". The other Mac-AppIcons can be left empty. A: I was stuck at this problem for about 2 hours. I had a icon present in my icon list but it keeps on failing. The problem was that the PNG had alpha channel enabled. Open up photoshop and save your image without alhpa/transparency. Solution found at: https://forums.developer.apple.com/thread/86829 A: i have the same problem, there is my check steps: * *i check all the image of AppIcon ,the other images are ok, but there is a error: ERROR ITMS-90704: "Missing App Icon. An app icon measuring 1024 by 1024 pixels in PNG format must be included in the Asset Catalog of apps built for iOS, iPadOS, or watchOS. Without this icon, apps cannot be submitted for review. For details, see https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/." *i check the pixel alpha and transparent, those is all ok ,but the same is all the same :( *i create a new asset catalog, and move the AppIcon dir to the new dir:Media.Xcassets. it works! if u have tried all the above method and have nothing effective, u can try mine, have a good luck! A: First, follow @Sukeshj 's solution. If @Sukeshj 's solution doesn't work and you are using CocoaPods for project management, that may be the key point. My environment: XCode 9.1 CocoaPods 1.2.1 Find {porject}/Pods/Target Support Files/Pods-{porjectname}/Pods-{porjectname}-resources.sh in Xcode, and change the last piece of code like this: before change: printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output- format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} -- compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi after change: printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output- format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} -- compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app- icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info- plist "${BUILD_DIR}/assetcatalog_generated_info.plist" fi Try to archive your project and upload it again, hope it helps. A: Its mandatory to add app icon of size 1024*1024 in image asset for Xcode 9 or later. Other wise it will give following error after uploading build to app store. So please make sure to add app icon in image asset before uploading app. Dear developer, We have discovered one or more issues with your recent delivery for "CarPal". Your delivery was successful, but you may wish to correct the following issues in your next delivery: Missing Marketing Icon - iOS Apps must include a 1024x1024px Marketing Icon in PNG format. Apps that do not include the Marketing Icon cannot be submitted for App Review or Beta App Review. After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect. A: If you are using Cordova Framework then: * *Create an icon file with height=1024px and width=1024px. You can name the file as icon-1024.png *Put that icon in folder res/icon/ios/ *Write the following code in your config.xml file. <platform name="ios"> <icon height="1024" src="res/icon/ios/icon-1024.png" width="1024" /> </platform> *Open terminal/command-prompt, then cd to your project's root directory and run the following command: cordova prepare ios --verbose *This will copy the icon-1024.png file to its proper location (platforms/ios/YourProjectName/Images.xcassets/AppIcon.appiconset/)
stackoverflow
{ "language": "en", "length": 787, "provenance": "stackexchange_0000F.jsonl.gz:904993", "question_score": "67", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667434" }
7bc1b8f8c4aff9f58edf8fbe39e387101db20722
Stackoverflow Stackexchange Q: How to setup Magento2 with MAMP PRO and nginx? Does anybody suceeded on setup Magento2 and MAMP's nginx? I'm using MAMP PRO 4.1.1 and didn't realize how MAMP works with the rewrites and rules we config for each site, or if there's a way to debug and see the final used nginx config. I would appreciate if anybody shares the config for Magento2 on this screen. Thank you. A: I just ran into this issue and for me it was that my hosts had both "Apache" and "Nginx" selected. What was weird is that I was unable to change it, so I had to create a new host with just NGINX selected and it worked. You may also need to setup NGINX "try_files" under the NGINX tab like so: $uri $uri/ /index.php?$args Also This link provided some more helpful info.
Q: How to setup Magento2 with MAMP PRO and nginx? Does anybody suceeded on setup Magento2 and MAMP's nginx? I'm using MAMP PRO 4.1.1 and didn't realize how MAMP works with the rewrites and rules we config for each site, or if there's a way to debug and see the final used nginx config. I would appreciate if anybody shares the config for Magento2 on this screen. Thank you. A: I just ran into this issue and for me it was that my hosts had both "Apache" and "Nginx" selected. What was weird is that I was unable to change it, so I had to create a new host with just NGINX selected and it worked. You may also need to setup NGINX "try_files" under the NGINX tab like so: $uri $uri/ /index.php?$args Also This link provided some more helpful info. A: It's been 2 years since I posted the question, and some of the answers here helped to figure out how to configure Nginx + Magento 2 + Mamp Pro. Here is my final configuration that worked with Magento 2.3.0 with SSL on local. Under the Nginx tab, I've added: * *Directory index: index.php *try files: $uri $uri/ /index.php?$args *Custom: empty *Additional parameters for directive: https://pastebin.com/pQ5KKCQ7 * *Note on line 27 I've added the current magento folder Under nginx config: Under Ports: Final Result: Final thoughts I don't know which of these configurations are really necessary, and which one are (maybe) incorrect. However, my M2 is now working very well on MAMP PRO 5.3. Next step is to make mamp support HTTP/2 and make Magento 2 even faster on local. A huge thank you for those who replied earlier. Your answers helped me to solve some parts of the puzzle. I'm glad to be sharing the whole solution with you now. If it doesn't work for you, keel an eye on MAMP Nginx log. It may bring some useful information about what's wrong. A: You have to turn off "Use Nginx as a Reverse Proxy for Apache", otherwise, you need to turn on your Apache to work with nginx. Screenshot
stackoverflow
{ "language": "en", "length": 351, "provenance": "stackexchange_0000F.jsonl.gz:905000", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667452" }
8c17714e9cfb0ced8c4b72d967129259915df455
Stackoverflow Stackexchange Q: Get CheckBox default Drawable in versions I want to omit the default padding of Android CheckBox. So , that customized CheckBox as below. But it will work only versions >= Android M. How can I get default drawable of CheckBox in versions < Android M @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int w=40; int h=40; setMeasuredDimension(w,h); //super.onMeasure(w, h); } @Override protected void onDraw(Canvas canvas) { Drawable drawable= null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { drawable = getButtonDrawable(); } drawable.setBounds(-15,-15,55,55); drawable.draw(canvas); //super.onDraw(canvas); } A: Try this method, Drawable drawable = CompoundButtonCompat.getButtonDrawable(this); You can refer the documentation here and let me know in case of any issue.
Q: Get CheckBox default Drawable in versions I want to omit the default padding of Android CheckBox. So , that customized CheckBox as below. But it will work only versions >= Android M. How can I get default drawable of CheckBox in versions < Android M @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int w=40; int h=40; setMeasuredDimension(w,h); //super.onMeasure(w, h); } @Override protected void onDraw(Canvas canvas) { Drawable drawable= null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { drawable = getButtonDrawable(); } drawable.setBounds(-15,-15,55,55); drawable.draw(canvas); //super.onDraw(canvas); } A: Try this method, Drawable drawable = CompoundButtonCompat.getButtonDrawable(this); You can refer the documentation here and let me know in case of any issue.
stackoverflow
{ "language": "en", "length": 107, "provenance": "stackexchange_0000F.jsonl.gz:905002", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667455" }
e3aa935bd83156ed0538194b71e93b82888ec857
Stackoverflow Stackexchange Q: Python: How to extend or append multiple elements in list comprehension format? I'd like to get a nice neat list comprehension for this code or something similar! extra_indices = [] for i in range(len(indices)): index = indices[i] extra_indices.extend([index, index + 1, index +2]) Thanks! Edit* The indices are a list of integers. A list of indexes of another array. For example if indices is [1, 52, 150] then the goal (here, this is the second time I've wanted two separate actions on continuously indexed outputs in a list comprehension) Then extra_indices would be [1, 2, 3, 52, 53, 54, 150, 151, 152] A: You can use two loops in list comp - extra_indices = [index+i for index in indices for i in range(3)]
Q: Python: How to extend or append multiple elements in list comprehension format? I'd like to get a nice neat list comprehension for this code or something similar! extra_indices = [] for i in range(len(indices)): index = indices[i] extra_indices.extend([index, index + 1, index +2]) Thanks! Edit* The indices are a list of integers. A list of indexes of another array. For example if indices is [1, 52, 150] then the goal (here, this is the second time I've wanted two separate actions on continuously indexed outputs in a list comprehension) Then extra_indices would be [1, 2, 3, 52, 53, 54, 150, 151, 152] A: You can use two loops in list comp - extra_indices = [index+i for index in indices for i in range(3)] A: code below should do the equivalant of your code, assuming indices is a list of integer from itertools import chain extra_indices = list(chain(*([x,x+1,x+2] for x in indices))) >>> indices = range(3) >>> list(chain(*([x,x+1,x+2] for x in indices))) >>> [0, 1, 2, 1, 2, 3, 2, 3, 4]
stackoverflow
{ "language": "en", "length": 172, "provenance": "stackexchange_0000F.jsonl.gz:905026", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667519" }
5b998319636d998bb048bd0fc45f259abe78bc48
Stackoverflow Stackexchange Q: How to get commented intellisense in VS Code Does anyone know how to get comments from above your created functions to show up in intellisense in visual studio code? im wanting it for use with C++ and on linux. Im not sure exactly how to describe this so ive included a picture below, hopefully that helps. A: It accepts notation to codedoc or doxyGen, well, compatible with DoxyGen and similar tools, e.g.: /// - C# (and I think, C++ of recent versions) ''' - VisualBasic
Q: How to get commented intellisense in VS Code Does anyone know how to get comments from above your created functions to show up in intellisense in visual studio code? im wanting it for use with C++ and on linux. Im not sure exactly how to describe this so ive included a picture below, hopefully that helps. A: It accepts notation to codedoc or doxyGen, well, compatible with DoxyGen and similar tools, e.g.: /// - C# (and I think, C++ of recent versions) ''' - VisualBasic
stackoverflow
{ "language": "en", "length": 86, "provenance": "stackexchange_0000F.jsonl.gz:905032", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667532" }
71334d5db8aedcf8c15279cf6f94d67584f3eb22
Stackoverflow Stackexchange Q: Use of ReflectionTestUtils.setField() in Junit testing I am new in JUnittesting so i have a question. Can anyone please tell me why we use ReflectionTestUtils.setField() in our Junit testing with example. A: One more Use Case: We externalised many properties Such as: URL's , endpoint and many other properties in application properties like below: kf.get.profile.endpoint=/profile kf.get.clients.endpoint=clients and then use it in application like below: @Value("${kf.get.clients.endpoint}") private String getClientEndpoint and whenever when we write unit test , we get NullPointerException because Spring cannot inject @value similarly as @Autowired does. ( at least at the moment , I dont know alternative. ) so to avoid that we can use ReflectionTestUtils to inject externalised properties. like below: ReflectionTestUtils.setField(targetObject,"getClientEndpoint","lorem");
Q: Use of ReflectionTestUtils.setField() in Junit testing I am new in JUnittesting so i have a question. Can anyone please tell me why we use ReflectionTestUtils.setField() in our Junit testing with example. A: One more Use Case: We externalised many properties Such as: URL's , endpoint and many other properties in application properties like below: kf.get.profile.endpoint=/profile kf.get.clients.endpoint=clients and then use it in application like below: @Value("${kf.get.clients.endpoint}") private String getClientEndpoint and whenever when we write unit test , we get NullPointerException because Spring cannot inject @value similarly as @Autowired does. ( at least at the moment , I dont know alternative. ) so to avoid that we can use ReflectionTestUtils to inject externalised properties. like below: ReflectionTestUtils.setField(targetObject,"getClientEndpoint","lorem"); A: As mentioned in the comment, the java docs explain the usage well. But I want to give you also a simple example. Let's say you have an Entity class with private or protected field access and no provided setter method. @Entity public class MyEntity { @Id private Long id; public Long getId(Long id){ this.id = id; } } In your test class, you cannot set an id of your entity because of the missing setter method. Using ReflectionTestUtils.setField you are able to do that for testing purpose: ReflectionTestUtils.setField(myEntity, "id", 1); The Parameters are described: public static void setField(Object targetObject, String name, Object value) Set the field with the given name on the provided targetObject to the supplied value. This method delegates to setField(Object, String, Object, Class), supplying null for the type argument. Parameters: targetObject - the target object on which to set the field; never null name - the name of the field to set; never null value - the value to set But give it a try and read the docs. A: it's very useful when we want to write unit test, such as: class A{ int getValue(); } class B{ A a; int caculate(){ ... int v = a.getValue(); .... } } class ServiceTest{ @Test public void caculateTest(){ B serviceB = new B(); A serviceA = Mockito.mock(A.class); Mockito.when(serviceA.getValue()).thenReturn(5); ReflectionTestUtils.setField(serviceB, "a", serviceA); } } A: Thank you for above discussions, the below part can also contribute in writing the unit tests by reading the properties from application-test.properties. import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.util.ReflectionTestUtils; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @TestPropertySource("classpath:application-test.properties") public class FileRetrivalServiceTest { @Value ("${fs.local.quarantine.directory}") private String localQuarantineDirectory; @Value ("${fs.local.quarantine.wrong.directory}") private String localQuarantineWrongDirectory; @Value ("${fs.local.quarantine.tmp.directory}") private String localQuarantineTmpDirectory; @Value ("${fs.local.keys.file}") private String localKeyFile; private FileRetrivalService fileRetrivalService; @Before public void setUp() throws Exception { fileRetrivalService = new FileRetrivalServiceImpl(); ReflectionTestUtils.setField(fileRetrivalService, "keyFile", localKeyFile); } @Test public void shouldRetrieveListOfFilesInQuarantineDirectory() { // given ReflectionTestUtils.setField(fileRetrivalService, "quarantineDirectory", localQuarantineDirectory); // when List<IcrFileModel> quarantineFiles = fileRetrivalService.retrieveListOfFilesInQuarantineDirectory(); // then assertNotNull(quarantineFiles); assertEquals(quarantineFiles.size(), 4); } } A: ReflectionTestUtils.setField is used is various contexts. But the most common scenario is when you have a class and inside that, there are attributes with private access, and you want to test this class. So a possible solution can be using ReflectionTestUtils like in the example below: public class BBVAFileProviderTest { @Mock private BBVAFileProvider bbvaFileProvider; @Before public void setup() throws Exception { bbvaFileProvider = new BBVAFileProvider(payoutFileService, bbvaFileAdapter, bbvaCryptographyService, amazonS3Client, providerRequestService, payoutConfirmationService); ReflectionTestUtils.setField(this.bbvaFileProvider, "bbvaClient", this.bbvaClient); } // ... } In this example can you see, that ReflectionTestUtils.setField is used to set the value to the private field because it doesn't have a setter method.
stackoverflow
{ "language": "en", "length": 557, "provenance": "stackexchange_0000F.jsonl.gz:905040", "question_score": "22", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667573" }
a6817778de693b9adbad99f647d83717c95c2b48
Stackoverflow Stackexchange Q: UIResponder touch points vs UIGestureRecognizer touch points I wanted to know what the differences between the points available from UIResponder methods from UITouch object and points available from UIGestureRecognizer object. I'm sure we will not get all the points on the device when a finger is moved. Is it the same number of points say for a pan is available for both the API or if any API gives more points? Which is better to track all the touched points?
Q: UIResponder touch points vs UIGestureRecognizer touch points I wanted to know what the differences between the points available from UIResponder methods from UITouch object and points available from UIGestureRecognizer object. I'm sure we will not get all the points on the device when a finger is moved. Is it the same number of points say for a pan is available for both the API or if any API gives more points? Which is better to track all the touched points?
stackoverflow
{ "language": "en", "length": 81, "provenance": "stackexchange_0000F.jsonl.gz:905042", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667576" }
3ddc4649d39bf1d803a941d3c3c4bd926f68d49f
Stackoverflow Stackexchange Q: MySQL AVG wrong result with ELSE 0 I am doing average on a column based on values of two other columns. Table structure is like this | rid | rate | status |.... | 1 | 1500 | 1 |.... | 1 | 1500 | 1 |.... | 1 | 1500 | 1 |.... | 1 | 1500 | 1 |.... | 2 | 1500 | 1 |.... When I do this way it gives me correct result 1500, But it returns NULL for no CASE match, I need AVG to return 0 if no rows match the CASE condition. AVG(CASE WHEN `rid` = `status` THEN `rate` END) DIV 1 AS `avg` I tried this way but its giving me wrong result as 1200 AVG(CASE WHEN `rid` = `status` THEN `rate` ELSE 0 END) DIV 1 AS `avg` Why I am getting wrong result? Please see and suggest any possible way to do this. Thanks A: Try this IFNULL(AVG(CASE WHEN `rid` = `status` THEN `rate` END) DIV 1,0) AS `avg` Note : MySQL IFNULL takes two arguments, if first arguments is not null then it returns first arguments, otherwise it return second arguments
Q: MySQL AVG wrong result with ELSE 0 I am doing average on a column based on values of two other columns. Table structure is like this | rid | rate | status |.... | 1 | 1500 | 1 |.... | 1 | 1500 | 1 |.... | 1 | 1500 | 1 |.... | 1 | 1500 | 1 |.... | 2 | 1500 | 1 |.... When I do this way it gives me correct result 1500, But it returns NULL for no CASE match, I need AVG to return 0 if no rows match the CASE condition. AVG(CASE WHEN `rid` = `status` THEN `rate` END) DIV 1 AS `avg` I tried this way but its giving me wrong result as 1200 AVG(CASE WHEN `rid` = `status` THEN `rate` ELSE 0 END) DIV 1 AS `avg` Why I am getting wrong result? Please see and suggest any possible way to do this. Thanks A: Try this IFNULL(AVG(CASE WHEN `rid` = `status` THEN `rate` END) DIV 1,0) AS `avg` Note : MySQL IFNULL takes two arguments, if first arguments is not null then it returns first arguments, otherwise it return second arguments A: SELECT AVG(RATE) FROM TABLENAME GROUP BY rid,status Try above query. Hope this will help you. A: You are getting 1200 because that last row where the case would return 0 would still count as a row , Hence (1500*4 + 0)/5 = 1200 . A: The reason is based as case when filter the rows from the table In the first select AVG(CASE WHEN `rid` = `status` THEN `rate` END) DIV 1 AS `avg` the condition in case when is executed fo only 4 rows do the fact that you have not else condition the query is filter only for the matching rid = status In the second AVG(CASE WHEN `rid` = `status` THEN `rate` ELSE 0 END) DIV 1 AS `avg` the else clause implies the use also of the last row (rid = 2) so you have 5 rows with 4 valid content for avg A: Apply COALESCE on your result: COALESCE(AVG(CASE WHEN `rid` = `status` THEN `rate` END), 0) DIV 1 AS `avg`
stackoverflow
{ "language": "en", "length": 361, "provenance": "stackexchange_0000F.jsonl.gz:905044", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667587" }
803650f759bcd88c6756a03d1ab018ad4911ab2a
Stackoverflow Stackexchange Q: How to write select query with subquery using laravel Eloquent Querybuilder? I had got the result from the query. My Simple SQL is: SELECT o2.driver_id, total_delieveries, DATE_FORMAT(o1.created_at ,'%Y-%m-%d') AS created_at FROM ( SELECT driver_id, created_at, COUNT(driver_id) AS total_delieveries FROM orders WHERE is_paid = 0 AND order_status = 5 AND created_at BETWEEN "'.$first_Day.'" AND "'.$last_Day.'" GROUP BY DATE_FORMAT(created_at ,'%Y-%m-%d'),driver_id ) o1 INNER JOIN orders o2 ON o1.driver_id = o2.driver_id GROUP BY o1.created_at In Laravel source, I wrote the query: $responseData = DB::select(DB::raw('select t.driver_id,total_delieveries,DATE_FORMAT(q1.created_at,\'%Y-%m-%d\') as created_at from ( SELECT driver_id, created_at, COUNT( driver_id ) AS total_delieveries FROM orders WHERE is_paid=0 AND order_status = 5 AND created_at BETWEEN "'.$first_Day.'" AND "'.$last_Day.'" GROUP BY DATE_FORMAT(created_at,\'%Y-%m-%d\'),driver_id) q1 INNER JOIN orders t ON q1.driver_id = t.driver_id GROUP BY q1.created_at')); I got the result what I wanted but I want to write it in a better way. Please tell me the correct and proper method to write this query. A: Also show this answer and for your variant: $subQuery = \DB::table('orders')->selectRaw('driver_id, created_at, COUNT(driver_id) AS total_delieveries') ->where('is_paid', 0) ->where('order_status', '5') ->whereBetween('created_at', [$first_Day, $last_Day]) ->groupBy(\DB::raw('DATE_FORMAT(created_at ,"%Y-%m-%d"),driver_id')); $q = \DB::table(\DB::raw('('.$subQuery->toSql().') as o1')) ->selectRaw('o2.driver_id,total_delieveries,DATE_FORMAT(o1.created_at ,"%Y-%m-%d") AS created_at') ->join('orders as o2', 'o1.driver_id', '=', 'o2.driver_id') ->groupBy('o1.created_at') ->mergeBindings($subQuery) ->get();
Q: How to write select query with subquery using laravel Eloquent Querybuilder? I had got the result from the query. My Simple SQL is: SELECT o2.driver_id, total_delieveries, DATE_FORMAT(o1.created_at ,'%Y-%m-%d') AS created_at FROM ( SELECT driver_id, created_at, COUNT(driver_id) AS total_delieveries FROM orders WHERE is_paid = 0 AND order_status = 5 AND created_at BETWEEN "'.$first_Day.'" AND "'.$last_Day.'" GROUP BY DATE_FORMAT(created_at ,'%Y-%m-%d'),driver_id ) o1 INNER JOIN orders o2 ON o1.driver_id = o2.driver_id GROUP BY o1.created_at In Laravel source, I wrote the query: $responseData = DB::select(DB::raw('select t.driver_id,total_delieveries,DATE_FORMAT(q1.created_at,\'%Y-%m-%d\') as created_at from ( SELECT driver_id, created_at, COUNT( driver_id ) AS total_delieveries FROM orders WHERE is_paid=0 AND order_status = 5 AND created_at BETWEEN "'.$first_Day.'" AND "'.$last_Day.'" GROUP BY DATE_FORMAT(created_at,\'%Y-%m-%d\'),driver_id) q1 INNER JOIN orders t ON q1.driver_id = t.driver_id GROUP BY q1.created_at')); I got the result what I wanted but I want to write it in a better way. Please tell me the correct and proper method to write this query. A: Also show this answer and for your variant: $subQuery = \DB::table('orders')->selectRaw('driver_id, created_at, COUNT(driver_id) AS total_delieveries') ->where('is_paid', 0) ->where('order_status', '5') ->whereBetween('created_at', [$first_Day, $last_Day]) ->groupBy(\DB::raw('DATE_FORMAT(created_at ,"%Y-%m-%d"),driver_id')); $q = \DB::table(\DB::raw('('.$subQuery->toSql().') as o1')) ->selectRaw('o2.driver_id,total_delieveries,DATE_FORMAT(o1.created_at ,"%Y-%m-%d") AS created_at') ->join('orders as o2', 'o1.driver_id', '=', 'o2.driver_id') ->groupBy('o1.created_at') ->mergeBindings($subQuery) ->get();
stackoverflow
{ "language": "en", "length": 196, "provenance": "stackexchange_0000F.jsonl.gz:905066", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667668" }
974ad41be1c4f7c63f2c04da7d9a3990fe3ecf86
Stackoverflow Stackexchange Q: Vue.js Syntax Highlight in Visual Studio I'm using Visual Studio 2015 I have install Vue.js Pack. But IDE doesn't support highlight Vue.js syntax . What else plugin can I install in VS 2015? A: I am using Vetur and VueVSCode Snippets. Pretty good so far.
Q: Vue.js Syntax Highlight in Visual Studio I'm using Visual Studio 2015 I have install Vue.js Pack. But IDE doesn't support highlight Vue.js syntax . What else plugin can I install in VS 2015? A: I am using Vetur and VueVSCode Snippets. Pretty good so far.
stackoverflow
{ "language": "en", "length": 46, "provenance": "stackexchange_0000F.jsonl.gz:905119", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667815" }
20bdbf4182e80e40f03f8c8aa3718e768e82d859
Stackoverflow Stackexchange Q: Amazon EC2 blue box next to "Disabled" Blue box problem. There is a blue box right next to the label disabled on my Amazon dashboard for EC2 services. The blue box has no tooltip. What is it for? Is it a friend or foe? How did it get there? Do I need it? Will it always stay blue? Can I change its color? Why is it square? How come other don't have a blue box? I don't want a blue box. How do I get rid of it? A: The box is a color key for the graphs on the Monitoring tab. If you select mutiple instances, you can view the metrics for multiple instances on the same charts, and the color key tells you which line is which instance.
Q: Amazon EC2 blue box next to "Disabled" Blue box problem. There is a blue box right next to the label disabled on my Amazon dashboard for EC2 services. The blue box has no tooltip. What is it for? Is it a friend or foe? How did it get there? Do I need it? Will it always stay blue? Can I change its color? Why is it square? How come other don't have a blue box? I don't want a blue box. How do I get rid of it? A: The box is a color key for the graphs on the Monitoring tab. If you select mutiple instances, you can view the metrics for multiple instances on the same charts, and the color key tells you which line is which instance.
stackoverflow
{ "language": "en", "length": 131, "provenance": "stackexchange_0000F.jsonl.gz:905137", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667860" }
db9bc855d1e34906f65fca4c6ade6c98441eb424
Stackoverflow Stackexchange Q: How to show SnackBar in BottomSheetDialogFragment? I search alot but couldn't find any solution and Snackbar is not working within fragment class doesn't help. I pass rootView of fragment and also try passing a view from getActivity but none of them works! @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.content_dialog_bottom_sheet, container, false); Snackbar.make(MyActivity.myTextview, "Hello", Snackbar.LENGTH_INDEFINITE).show(); Snackbar.make(rootView, "Hello", Snackbar.LENGTH_INDEFINITE).show(); return rootView; } and my content_dialog_bottom_sheet : <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/bottomSheetLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/background" app:behavior_hideable="true" app:behavior_peekHeight="180dp" app:layout_behavior="@string/bottom_sheet_behavior"> //some views </RelativeLayout> A: Solution is fairly simple. You need to: * *Wrap your dialog layout with CoordinatorLayout (and if you want to show snackbar just next to some specific view, wrap it instead) *Use CoordinatorLayout id as view while showing snackbar.
Q: How to show SnackBar in BottomSheetDialogFragment? I search alot but couldn't find any solution and Snackbar is not working within fragment class doesn't help. I pass rootView of fragment and also try passing a view from getActivity but none of them works! @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.content_dialog_bottom_sheet, container, false); Snackbar.make(MyActivity.myTextview, "Hello", Snackbar.LENGTH_INDEFINITE).show(); Snackbar.make(rootView, "Hello", Snackbar.LENGTH_INDEFINITE).show(); return rootView; } and my content_dialog_bottom_sheet : <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/bottomSheetLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/background" app:behavior_hideable="true" app:behavior_peekHeight="180dp" app:layout_behavior="@string/bottom_sheet_behavior"> //some views </RelativeLayout> A: Solution is fairly simple. You need to: * *Wrap your dialog layout with CoordinatorLayout (and if you want to show snackbar just next to some specific view, wrap it instead) *Use CoordinatorLayout id as view while showing snackbar. A: Snackbar.make( getDialog().getWindow().getDecorView(), "your-string", Snackbar.LENGTH_SHORT ).show(); Add this peace of code to your onCreateView A: Show snackbar after a delay: new Handler().postDelayed(new Runnable() { @Override public void run() { Snackbar.make(rootView, "Hello", Snackbar.LENGTH_INDEFINITE).show(); } },200); A: using @Wimukthi Rajapaksha answer: Snackbar.make( getDialog().getWindow().getDecorView(), "your-string", Snackbar.LENGTH_SHORT ).show(); you can use the following code line to show it above a certain view, make sure to show the snack bar after setting anchor view not before. snackBar.anchorView = -Your view- A: If you are extending your Bottomsheet class to BottomSheetDialogFragment(), you can use dialog's decorView as a view. Sample Code Snippet for reference : Snackbar.make( dialog?.window?.decorView, "Press login button to continue", Snackbar.LENGTH_LONG ) .setAction("Login") { v: View? -> val intent = Intent(context, DestinationActivityAfterLogin::class.java) startActivity(intent) }.show() ==== If you are using BottomSheetDialog for showing the bottomsheet, there one can use rootView to pop-up snackbar. Sample code for reference : Snackbar.make( bsBinding.root.rootView, // bsBinding is view binding object "Press login button to continue", Snackbar.LENGTH_LONG ) .setAction("Login") { v: View? -> val intent = Intent(context, DestinationActivityAfterLogin::class.java) startActivity(intent) }.show() Hope this would be useful while showing snackbar with bottom sheet dialogs. Happy coding.
stackoverflow
{ "language": "en", "length": 307, "provenance": "stackexchange_0000F.jsonl.gz:905154", "question_score": "24", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44667916" }
170295ae7e9a0c13882740cad9a0a3052e09d99b
Stackoverflow Stackexchange Q: High memory consumption of ASP.NET Core MVC vs previous ASP.NET MVC We were curious how our new ASP.NET Core MVC web application might perform against our current ASP.NET MVC application. While throughput may be good (nothing we were concerned about in our previous application), the following made us question our effort: Higher startup time (not serious but notable) 3-5 times more memory consumption Now the latter made us really worry because this is a huge difference. Nowhere on the internet could I find comments on this. The opposite is true: on most announcements it was stated that ASP.NET Core would require less memory then the previous version. So we checked the default ASP.NET Core MVC template (maybe we made a serious mistake somewhere). But even the default ASP.NET Core MVC template took about 100 MB memory. Compared to about 20 MB memory of the previous ASP.NET MVC template, this is an increase by factor 5. So maybe someone can answer these questions: Why is this? Are there any solutions to mitigate this problem? Will there be a solution for this in near future? Why can’t I find anyone complaining about this?
Q: High memory consumption of ASP.NET Core MVC vs previous ASP.NET MVC We were curious how our new ASP.NET Core MVC web application might perform against our current ASP.NET MVC application. While throughput may be good (nothing we were concerned about in our previous application), the following made us question our effort: Higher startup time (not serious but notable) 3-5 times more memory consumption Now the latter made us really worry because this is a huge difference. Nowhere on the internet could I find comments on this. The opposite is true: on most announcements it was stated that ASP.NET Core would require less memory then the previous version. So we checked the default ASP.NET Core MVC template (maybe we made a serious mistake somewhere). But even the default ASP.NET Core MVC template took about 100 MB memory. Compared to about 20 MB memory of the previous ASP.NET MVC template, this is an increase by factor 5. So maybe someone can answer these questions: Why is this? Are there any solutions to mitigate this problem? Will there be a solution for this in near future? Why can’t I find anyone complaining about this?
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:905174", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44668014" }
51ac110bf63b8deebc8d7d7d95ac65421b2f4a03
Stackoverflow Stackexchange Q: Start text from new line I have two string. and I want to display the second string from new line. But I have to use only one variable in html. let msg = "hello"+\n+"how r u"; I have to concat two string but start the second string from new line. A: Since you have not described your problem completely, one possible and simple way is to use split function. <p>{{msg.split('\n')[0]}}</p> <p>{{msg.split('\n')[1]}}</p>
Q: Start text from new line I have two string. and I want to display the second string from new line. But I have to use only one variable in html. let msg = "hello"+\n+"how r u"; I have to concat two string but start the second string from new line. A: Since you have not described your problem completely, one possible and simple way is to use split function. <p>{{msg.split('\n')[0]}}</p> <p>{{msg.split('\n')[1]}}</p> A: Import DomSanitizationService. import {DomSanitizationService} from '@angular/platform-browser'; in constructor of class do this constructor(sanitizer: DomSanitizationService) { this.msg = "Hello" + "<br/>" + "How are you?"; this.msg = this.sanitizer.bypassSecurityTrustHtml(this.msg); } Use msg in the template as shown below <p [innerHTML]="msg"></p>
stackoverflow
{ "language": "en", "length": 111, "provenance": "stackexchange_0000F.jsonl.gz:905186", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44668041" }
5759b228b0766e98ceec60c7816eb04fb0d49da4
Stackoverflow Stackexchange Q: Set UIImageView AspectRatio constraint programmatically in swift 3 I have an UIImageView in storyboard which AspectRatio is 1:1, that I want to change to 2:1 programmatically in ViewController in some cases. I create reference of that constraint in ViewController but unable to set the constraint. A: You can change constraint programmatically in swift 3 let aspectRatioConstraint = NSLayoutConstraint(item: self.YourImageObj,attribute: .height,relatedBy: .equal,toItem: self.YourImageObj,attribute: .width,multiplier: (2.0 / 1.0),constant: 0) self.YourImageObj.addConstraint(aspectRatioConstraint)
Q: Set UIImageView AspectRatio constraint programmatically in swift 3 I have an UIImageView in storyboard which AspectRatio is 1:1, that I want to change to 2:1 programmatically in ViewController in some cases. I create reference of that constraint in ViewController but unable to set the constraint. A: You can change constraint programmatically in swift 3 let aspectRatioConstraint = NSLayoutConstraint(item: self.YourImageObj,attribute: .height,relatedBy: .equal,toItem: self.YourImageObj,attribute: .width,multiplier: (2.0 / 1.0),constant: 0) self.YourImageObj.addConstraint(aspectRatioConstraint) A: As it's stated in Apple's guide, there're three ways to set constraints programmatically: * *You can use layout anchors *You can use the NSLayoutConstraint class *You can use the Visual Format Language The most convenient and fluent way to set constraints is using Layout Anchors. It's just one line of code to change aspect ratio for your ImageView imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1.0/2.0).isActive = true To avoid "[LayoutConstraints] Unable to simultaneously satisfy constraints." you should add reference to your ImageView's height constraint then deactivate it: heightConstraint.isActive = false A: Set the multiplier of the constraint to 0.5 or 2 depending on your constraint condition, It'll become 2:1
stackoverflow
{ "language": "en", "length": 176, "provenance": "stackexchange_0000F.jsonl.gz:905209", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44668106" }
aa81bbae344f6068ec5ee75e3d0e7c6f52f8bc83
Stackoverflow Stackexchange Q: Why does list iterator point in between the elements returned by next() and previous() methods I was going through JavaDocs and I found out that ListIterator in Java works slightly in a different manner from what we expect. I thought that after we have used next() or previous() methods the cursor points to the corresponding element (i.e. current element). But the documentation states that it points in between the elements that will be returned when we use next() or previous(): A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). Also I have read somewhere that Java does this to prevent loops in the linked lists. But I am not able to get a grasp of this.
Q: Why does list iterator point in between the elements returned by next() and previous() methods I was going through JavaDocs and I found out that ListIterator in Java works slightly in a different manner from what we expect. I thought that after we have used next() or previous() methods the cursor points to the corresponding element (i.e. current element). But the documentation states that it points in between the elements that will be returned when we use next() or previous(): A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). Also I have read somewhere that Java does this to prevent loops in the linked lists. But I am not able to get a grasp of this.
stackoverflow
{ "language": "en", "length": 143, "provenance": "stackexchange_0000F.jsonl.gz:905216", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44668130" }
f9534d8a68e665d7b70bf038ee1df2de87c555e4
Stackoverflow Stackexchange Q: Python Selenium: Unable to scroll inside iframe Hi, I am able to switch between tabs, access all elements. I am unable to scroll in this iframe. Please help. Code I am using is as follows. iframe = self.browser.find_elements_by_tag_name('iframe')[0] self.browser.switch_to_frame(iframe) # Iterating through tabs for tab_name in soup.find_all('md-dummy-tab'): return_dict[tab_name.text] = [] tab_names.append(tab_name.text) # clicking on tabs one by one self.force_click('xpath=/html/body/div/md-content/md-tabs/md-tabs-wrapper/md-tabs-canvas/md-pagination-wrapper/md-tab-item[%s]/span' % tab) tab += 1 time.sleep(2) # Scrolling try: self.browser.execute_async_script("frame.scrollTo(0, 10000);") except: pass time.sleep(2) A: You can use this code to scroll-down in frame. frame.contentWindow.scrollTo(0, 300); For more info you can see this link :- scroll an iframe from parent page
Q: Python Selenium: Unable to scroll inside iframe Hi, I am able to switch between tabs, access all elements. I am unable to scroll in this iframe. Please help. Code I am using is as follows. iframe = self.browser.find_elements_by_tag_name('iframe')[0] self.browser.switch_to_frame(iframe) # Iterating through tabs for tab_name in soup.find_all('md-dummy-tab'): return_dict[tab_name.text] = [] tab_names.append(tab_name.text) # clicking on tabs one by one self.force_click('xpath=/html/body/div/md-content/md-tabs/md-tabs-wrapper/md-tabs-canvas/md-pagination-wrapper/md-tab-item[%s]/span' % tab) tab += 1 time.sleep(2) # Scrolling try: self.browser.execute_async_script("frame.scrollTo(0, 10000);") except: pass time.sleep(2) A: You can use this code to scroll-down in frame. frame.contentWindow.scrollTo(0, 300); For more info you can see this link :- scroll an iframe from parent page A: I found the following commands to help. First, assuming one has already switched to an iframe where the element is accessible, store the location of that element. Then switch back to the default content and scroll in the window. Then, search again for the iframe, switch to that iframe, and reload any other dynamical variables in Selenium needed to continue. length = prods[p].location["y"] self.driver.switch_to.default_content() self.driver.execute_script("window.scrollTo(0,"+str(length) + ");") iframe = self.driver.find_elements_by_xpath('.//iframe[contains(@id,"frame")]') self.driver.switch_to_frame(iframe[0]) prods = self.driver.find_elements_by_xpath('.//div[@class="products"]') prods[p].click() A: Try location_once_scrolled_into_view: # assume `driver` is an instance of `WebDriver` element = driver.find_element(By.CSS_SELECTOR, 'some_element') # `location_once_scrolled_into_view` is a property that behaves like function element.location_once_scrolled_into_view A Python function wrapper: # it's not necessary to switch into the iframe where your element is located before calling this function. def scroll_into_view(driver, element=None, css_selector=None): if (not element) and (not css_selector): return if css_selector and (not element): element = driver.find_element_by_css_selector(css_selector) driver.execute_script('arguments[0].scrollIntoView({block: "center"})', element) more about javascript function scrollIntoView
stackoverflow
{ "language": "en", "length": 251, "provenance": "stackexchange_0000F.jsonl.gz:905228", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44668169" }
549d6d082a1f2c13752973269378f29e886ec695
Stackoverflow Stackexchange Q: Different tabBar icons in react navigation for selected and unselected state? I am setting up a tabbar using react navigation in react native. I am unable to setup multiple tabbar icons for selected/unselected state. Any reference or doc would help ? A: tabBarIcon callback provides you the focused variable for the same. static navigationOptions = { tabBarLabel: 'Home', tabBarIcon: ({ focused }) => { const image = focused ? require('../active.png') : require('../inactive.png') return ( <Image source={image} style={styles.tabIcon} /> ) } }
Q: Different tabBar icons in react navigation for selected and unselected state? I am setting up a tabbar using react navigation in react native. I am unable to setup multiple tabbar icons for selected/unselected state. Any reference or doc would help ? A: tabBarIcon callback provides you the focused variable for the same. static navigationOptions = { tabBarLabel: 'Home', tabBarIcon: ({ focused }) => { const image = focused ? require('../active.png') : require('../inactive.png') return ( <Image source={image} style={styles.tabIcon} /> ) } } A: You can change the icon based on the activeTintColor / inactiveTintColor static navigationOptions = { tabBarLabel: 'Notifications', tabBarIcon: ({ tintColor }) => (tintColor == '#e91e63' ? <Image source={require('./activeIcon.png')} style={[styles.icon, {tintColor: tintColor}]} /> : <Image source={require('./inactiveIcon.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), tabBarOptions: { activeTintColor: '#e91e63', } }; You can do something like this even if you don't use the tint color.
stackoverflow
{ "language": "en", "length": 143, "provenance": "stackexchange_0000F.jsonl.gz:905263", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44668280" }
753f445a84492fc76c3eaf9e1bc8b89fadf20508
Stackoverflow Stackexchange Q: I got message for error_log file "The stream or file ".../laravel.log" could not be opened: failed to open stream: Permission denied" Tue Jun 20 13:17:41.195156 2017] [:error] [pid 14454] [client 203.131.216.144:60475] PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'The stream or file "/var/www/html/app/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied' in /var/www/html/app/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107\nStack trace:\n#0 /var/www/html/app/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\StreamHandler->write(Array)\n#1 /var/www/html/app/vendor/monolog/monolog/src/Monolog/Logger.php(336): Monolog\Handler\AbstractProcessingHandler->handle(Array)\n#2 /var/www/html/app/vendor/monolog/monolog/src/Monolog/Logger.php(615): Monolog\Logger->addRecord(400, Object(Symfony\Component\Debug\Exception\FatalErrorException), Array)\n#3 /var/www/html/app/vendor/laravel/framework/src/Illuminate/Log/Writer.php(202): Monolog\Logger->error(Object(Symfony\Component\Debug\Exception\FatalErrorException), Array)\n#4 /var/www/html/app/vendor/laravel/framework/src/Illuminate/Log/Writer.php(113): Illuminate\Log\Writer->writeLog('er in /var/www/html/app/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 107, referer: http://203.131.209.179/app/login A: Directory Permissions After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. https://laravel.com/docs/5.4/installation#installing-laravel So, for example, in Linux you can do this by executing chmod command: chmod -R 755 storage bootstrap/cache
Q: I got message for error_log file "The stream or file ".../laravel.log" could not be opened: failed to open stream: Permission denied" Tue Jun 20 13:17:41.195156 2017] [:error] [pid 14454] [client 203.131.216.144:60475] PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'The stream or file "/var/www/html/app/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied' in /var/www/html/app/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107\nStack trace:\n#0 /var/www/html/app/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php(37): Monolog\Handler\StreamHandler->write(Array)\n#1 /var/www/html/app/vendor/monolog/monolog/src/Monolog/Logger.php(336): Monolog\Handler\AbstractProcessingHandler->handle(Array)\n#2 /var/www/html/app/vendor/monolog/monolog/src/Monolog/Logger.php(615): Monolog\Logger->addRecord(400, Object(Symfony\Component\Debug\Exception\FatalErrorException), Array)\n#3 /var/www/html/app/vendor/laravel/framework/src/Illuminate/Log/Writer.php(202): Monolog\Logger->error(Object(Symfony\Component\Debug\Exception\FatalErrorException), Array)\n#4 /var/www/html/app/vendor/laravel/framework/src/Illuminate/Log/Writer.php(113): Illuminate\Log\Writer->writeLog('er in /var/www/html/app/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php on line 107, referer: http://203.131.209.179/app/login A: Directory Permissions After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. https://laravel.com/docs/5.4/installation#installing-laravel So, for example, in Linux you can do this by executing chmod command: chmod -R 755 storage bootstrap/cache A: In your project directory run this command: chmod -R 777 storage bootstrap/cache A: Quick fix: Remove bootstrap/cache/config.php file. A: Use this command for giving the right permissions to the storage folder that involves logs/laravel.logs sudo chmod -R 775 storage If you are using windows the 775 means : owner group other rwx rwx r_x
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:905276", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44668311" }