question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
Is there anyway to simulate the [NSString stringWithFormat:@"%p", myVar], from Objective-C, in the new Swift language? For example: let str = "A String" println(" str value \(str) has address: ?")
Note: This is for reference types. Swift 4/5: print(Unmanaged.passUnretained(someVar).toOpaque()) Prints the memory address of someVar. (thanks to @Ying) Swift 3.1: print(Unmanaged<AnyObject>.passUnretained(someVar as AnyObject).toOpaque()) Prints the memory address of someVar.
Swift
24,058,906
254
I can't seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far: UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil) However, it does not seem to do anything. The keyWindow and rootViewController seem to be non-nil values too, so the optional chaining shouldn't be an issue. NOTE: It is a bad idea to do something like this. It breaks the MVC pattern.
presentViewController shows a view controller. It doesn't return a view controller. If you're not using a UINavigationController, you're probably looking for presentedViewController and you'll need to start at the root and iterate down through the presented views. if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // topController should now be your topmost view controller } For Swift 3+: if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // topController should now be your topmost view controller } For iOS 13+ let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first if var topController = keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } // topController should now be your topmost view controller }
Swift
26,667,009
253
How can I extend Swift's Array<T> or T[] type with custom functional utils? Browsing around Swift's API docs shows that Array methods are an extension of the T[], e.g: extension T[] : ArrayType { //... init() var count: Int { get } var capacity: Int { get } var isEmpty: Bool { get } func copy() -> T[] } When copying and pasting the same source and trying any variations like: extension T[] : ArrayType { func foo(){} } extension T[] { func foo(){} } It fails to build with the error: Nominal type T[] can't be extended Using the full type definition fails with Use of undefined type 'T', i.e: extension Array<T> { func foo(){} } And it also fails with Array<T : Any> and Array<String>. Curiously Swift lets me extend an untyped array with: extension Array { func each(fn: (Any) -> ()) { for i in self { fn(i) } } } Which it lets me call with: [1,2,3].each(println) But I can't create a proper generic type extension as the type seems to be lost when it flows through the method, e.g trying to replace Swift's built-in filter with: extension Array { func find<T>(fn: (T) -> Bool) -> T[] { var to = T[]() for x in self { let t = x as T if fn(t) { to += t } } return to } } But the compiler treats it as untyped where it still allows calling the extension with: ["A","B","C"].find { $0 > "A" } And when stepped-thru with a debugger indicates the type is Swift.String but it's a build error to try access it like a String without casting it to String first, i.e: ["A","B","C"].find { ($0 as String).compare("A") > 0 } Does anyone know what's the proper way to create a typed extension method that acts like the built-in extensions?
For extending typed arrays with classes, the below works for me (Swift 2.2). For example, sorting a typed array: class HighScoreEntry { let score:Int } extension Array where Element == HighScoreEntry { func sort() -> [HighScoreEntry] { return sort { $0.score < $1.score } } } Trying to do this with a struct or typealias will give an error: Type 'Element' constrained to a non-protocol type 'HighScoreEntry' Update: To extend typed arrays with non-classes use the following approach: typealias HighScoreEntry = (Int) extension SequenceType where Generator.Element == HighScoreEntry { func sort() -> [HighScoreEntry] { return sort { $0 < $1 } } } In Swift 3 some types have been renamed: extension Sequence where Iterator.Element == HighScoreEntry { // ... }
Swift
24,027,116
253
I have two classes, Shape and Square class Shape { var numberOfSides = 0 var name: String init(name:String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } class Square: Shape { var sideLength: Double init(sideLength:Double, name:String) { super.init(name:name) // Error here self.sideLength = sideLength numberOfSides = 4 } func area () -> Double { return sideLength * sideLength } } With the implementation above I get the error: property 'self.sideLength' not initialized at super.init call super.init(name:name) Why do I have to set self.sideLength before calling super.init?
Quote from The Swift Programming Language, which answers your question: “Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:” Safety check 1 “A designated initializer must ensure that all of the “properties introduced by its class are initialized before it delegates up to a superclass initializer.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11
Swift
24,021,093
253
How to generate a date time stamp, using the format standards for ISO 8601 and RFC 3339? The goal is a string that looks like this: "2015-01-01T00:00:00.000Z" Format: year, month, day, as "XXXX-XX-XX" the letter "T" as a separator hour, minute, seconds, milliseconds, as "XX:XX:XX.XXX". the letter "Z" as a zone designator for zero offset, a.k.a. UTC, GMT, Zulu time. Best case: Swift source code that is simple, short, and straightforward. No need to use any additional framework, subproject, cocoapod, C code, etc. I've searched StackOverflow, Google, Apple, etc. and haven't found a Swift answer to this. The classes that seem most promising are NSDate, NSDateFormatter, NSTimeZone. Related Q&A: How do I get an ISO 8601 date on iOS? Here's the best I've come up with so far: var now = NSDate() var formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) println(formatter.stringFromDate(now))
Swift 5.5 • iOS 15 • Xcode 13 or later extension Date.ISO8601FormatStyle { static let iso8601withFractionalSeconds: Self = .init(includingFractionalSeconds: true) } extension ParseStrategy where Self == Date.ISO8601FormatStyle { static var iso8601withFractionalSeconds: Date.ISO8601FormatStyle { .iso8601withFractionalSeconds } } extension FormatStyle where Self == Date.ISO8601FormatStyle { static var iso8601withFractionalSeconds: Date.ISO8601FormatStyle { .iso8601withFractionalSeconds } } extension Date { init(iso8601withFractionalSeconds parseInput: ParseStrategy.ParseInput) throws { try self.init(parseInput, strategy: .iso8601withFractionalSeconds) } var iso8601withFractionalSeconds: String { formatted(.iso8601withFractionalSeconds) } } extension String { func iso8601withFractionalSeconds() throws -> Date { try .init(iso8601withFractionalSeconds: self) } } extension JSONDecoder.DateDecodingStrategy { static let iso8601withFractionalSeconds = custom { try .init(iso8601withFractionalSeconds: $0.singleValueContainer().decode(String.self)) } } extension JSONEncoder.DateEncodingStrategy { static let iso8601withFractionalSeconds = custom { var container = $1.singleValueContainer() try container.encode($0.iso8601withFractionalSeconds) } } Usage: let date: Date = .now // "19 Nov 2023 at 11:29 PM" date.description(with: .current) // "Sunday, 19 November 2023 at 11:29:40 PM Brasilia Standard Time" let dateString = date.iso8601withFractionalSeconds // "2023-11-20T02:29:40.920Z" if let date = try? dateString.iso8601withFractionalSeconds() { date.description(with: .current) // "Sunday, 19 November 2023 at 11:29:40 PM Brasilia Standard Time" print(date.iso8601withFractionalSeconds) // "2023-11-20T02:29:40.920Z\n" } Swift 4 • iOS 11.2.1 or later extension ISO8601DateFormatter { convenience init(_ formatOptions: Options) { self.init() self.formatOptions = formatOptions } } extension Formatter { static let iso8601withFractionalSeconds = ISO8601DateFormatter([.withInternetDateTime, .withFractionalSeconds]) } extension Date { var iso8601withFractionalSeconds: String { return Formatter.iso8601withFractionalSeconds.string(from: self) } } extension String { var iso8601withFractionalSeconds: Date? { return Formatter.iso8601withFractionalSeconds.date(from: self) } } Usage: Date().description(with: .current) // Tuesday, February 5, 2019 at 10:35:01 PM Brasilia Summer Time" let dateString = Date().iso8601withFractionalSeconds // "2019-02-06T00:35:01.746Z" if let date = dateString.iso8601withFractionalSeconds { date.description(with: .current) // "Tuesday, February 5, 2019 at 10:35:01 PM Brasilia Summer Time" print(date.iso8601withFractionalSeconds) // "2019-02-06T00:35:01.746Z\n" } let dates: [Date] = [.now] let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601withFractionalSeconds let data = try! encoder.encode(dates) print(String(data: data, encoding: .utf8)!) // "["2023-11-20T02:11:29.158Z"]\n" let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601withFractionalSeconds let decodedDates = try! decoder.decode([Date].self, from: data) print(decodedDates) // "[2023-11-20 02:11:29 +0000]\n" iOS 9 • Swift 3 or later extension Formatter { static let iso8601withFractionalSeconds: DateFormatter = { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" return formatter }() } Codable Protocol If you need to encode and decode this format when working with Codable protocol you can create your own custom date encoding/decoding strategies: extension JSONDecoder.DateDecodingStrategy { static let iso8601withFractionalSeconds = custom { let container = try $0.singleValueContainer() let string = try container.decode(String.self) guard let date = Formatter.iso8601withFractionalSeconds.date(from: string) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: " + string) } return date } } and the encoding strategy extension JSONEncoder.DateEncodingStrategy { static let iso8601withFractionalSeconds = custom { var container = $1.singleValueContainer() try container.encode(Formatter.iso8601withFractionalSeconds.string(from: $0)) } } Playground Testing let dates = [Date()] // ["Feb 8, 2019 at 9:48 PM"] encoding let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601withFractionalSeconds let data = try! encoder.encode(dates) print(String(data: data, encoding: .utf8)!) decoding let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601withFractionalSeconds let decodedDates = try! decoder.decode([Date].self, from: data) // ["Feb 8, 2019 at 9:48 PM"]
Swift
28,016,578
252
Is there an Swift equivalent of NSLocalizedString(...)? In Objective-C, we usually use: NSString *string = NSLocalizedString(@"key", @"comment"); How can I achieve the same in Swift? I found a function: func NSLocalizedString( key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, #comment: String) -> String However, it is very long and not convenient at all.
I use the following solution: Create extension: extension String { var localized: String { return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "") } } In Localizable.strings file: "Hi" = "Вітаю"; Example of use: myLabel.text = "Hi".localized For case with comments you can use this solution: Extension: extension String { func localized(withComment:String) -> String { return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment) } } In .strings file: /* with !!! */ "Hi" = "Вітаю!!!"; Using: myLabel.text = "Hi".localized(withComment: "with !!!")
Swift
25,081,757
248
I need to create a String with format which can convert Int, Int64, Double, etc types into String. Using Objective-C, I can do it by: NSString *str = [NSString stringWithFormat:@"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE]; How to do same but in Swift?
I think this could help you: import Foundation let timeNow = time(nil) let aStr = String(format: "%@%x", "timeNow in hex: ", timeNow) print(aStr) Example result: timeNow in hex: 5cdc9c8d
Swift
24,074,479
247
I have a Swift framework that defines a struct: public struct CollectionTO { var index: Order var title: String var description: String } However, I can't seem to use the implicit memberwise initialiser from another project that imports the library. The error is: 'CollectionTO' cannot be initialised because it has no accessible initialisers i.e. the default synthesized memberwise initialiser is not public. var collection1 = CollectionTO(index: 1, title: "New Releases", description: "All the new releases") I'm having to add my own init method like so: public struct CollectionTO { var index: Order var title: String var description: String public init(index: Order, title: String, description: String) { self.index = index; self.title = title; self.description = description; } } ... but is there a way to do this without explicitly defining a public init?
Quoting the manual: "Default Memberwise Initializers for Structure Types The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Otherwise, the initializer has an access level of internal. As with the default initializer above, if you want a public structure type to be initializable with a memberwise initializer when used in another module, you must provide a public memberwise initializer yourself as part of the type’s definition." Excerpt from "The Swift Programming Language", section "Access Control".
Swift
26,224,693
245
I'm trying to pick up a bit of Swift lang and I'm wondering how to convert the following Objective-C into Swift: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; UITouch *touch = [touches anyObject]; if ([touch.view isKindOfClass: UIPickerView.class]) { //your touch was in a uipickerview ... do whatever you have to do } } More specifically I need to know how to use isKindOfClass in the new syntax. override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { ??? if ??? { // your touch was in a uipickerview ... } }
The proper Swift operator is is: if touch.view is UIPickerView { // touch.view is of type UIPickerView } Of course, if you also need to assign the view to a new constant, then the if let ... as? ... syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you should use the is operator.
Swift
24,019,707
245
I am trying to dismiss a ViewController in swift by calling dismissViewController in an IBAction @IBAction func cancel(sender: AnyObject) { self.dismissViewControllerAnimated(false, completion: nil) println("cancel") } @IBAction func done(sender: AnyObject) { self.dismissViewControllerAnimated(false, completion: nil) println("done") } I could see the println message in console output but ViewController never gets dismissed. What could be the problem?
From you image it seems like you presented the ViewController using push The dismissViewControllerAnimated is used to close ViewControllers that presented using modal Swift 2 navigationController.popViewControllerAnimated(true) Swift 4 navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil)
Swift
24,668,818
244
I am having a issue with Xcode where the error "Source Kit Service Terminated" is popping up and all syntax highlighting and code completion is gone in Swift. How can I fix this? Here is an example image:
The answer to mine (Xcode6-Beta7) was simply to delete the Derived Data folder. Preferences > Locations > Derived Data > click the arrow to open in Finder > trash it. There's obviously many reasons why this crash can occur.
Swift
24,006,206
242
In iOS 7 my UIButton titles are animating in and out at the wrong time - late. This problem does not appear on iOS 6. I'm just using: [self setTitle:text forState:UIControlStateNormal]; I would prefer this happens instantly and without a blank frame. This blink is especially distracting and draws attention away from other animations.
Use the performWithoutAnimation: method and then force layout to happen immediately instead of later on. [UIView performWithoutAnimation:^{ [self.myButton setTitle:text forState:UIControlStateNormal]; [self.myButton layoutIfNeeded]; }];
Swift
18,946,490
242
When I use the for loop in Playground, everything worked fine, until I changed the first parameter of for loop to be the highest value. (iterated in descending order) Is this a bug? Did any one else have it? for index in 510..509 { var a = 10 } The counter that displays the number of iterations that will be executions keeps ticking...
Xcode 6 beta 4 added two functions to iterate on ranges with a step other than one: stride(from: to: by:), which is used with exclusive ranges and stride(from: through: by:), which is used with inclusive ranges. To iterate on a range in reverse order, they can be used as below: for index in stride(from: 5, to: 1, by: -1) { print(index) } //prints 5, 4, 3, 2 for index in stride(from: 5, through: 1, by: -1) { print(index) } //prints 5, 4, 3, 2, 1 Note that neither of those is a Range member function. They are global functions that return either a StrideTo or a StrideThrough struct, which are defined differently from the Range struct. A previous version of this answer used the by() member function of the Range struct, which was removed in beta 4. If you want to see how that worked, check the edit history.
Swift
24,508,592
241
How to save a string into the NSUserDefaults?
NSString *valueToSave = @"someValue"; [[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"]; [[NSUserDefaults standardUserDefaults] synchronize]; to get it back later NSString *savedValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"preferenceName"];
Swift
3,074,483
241
enum PostType: Decodable { init(from decoder: Decoder) throws { // What do i put here? } case Image enum CodingKeys: String, CodingKey { case image } } What do i put to complete this? Also, lets say i changed the case to this: case image(value: Int) How do I make this conform to Decodable? Here is my full code (which does not work) let jsonData = """ { "count": 4 } """.data(using: .utf8)! do { let decoder = JSONDecoder() let response = try decoder.decode(PostType.self, from: jsonData) print(response) } catch { print(error) } } } enum PostType: Int, Codable { case count = 4 } Also, how will it handle an enum like this? enum PostType: Decodable { case count(number: Int) }
It's pretty easy, just use String or Int raw values which are implicitly assigned. enum PostType: Int, Codable { case image, blob } image is encoded to 0 and blob to 1 Or enum PostType: String, Codable { case image, blob } image is encoded to "image" and blob to "blob" This is a simple example how to use it: enum PostType : Int, Codable { case count = 4 } struct Post : Codable { var type : PostType } let jsonString = "{\"type\": 4}" let jsonData = Data(jsonString.utf8) do { let decoded = try JSONDecoder().decode(Post.self, from: jsonData) print("decoded:", decoded.type) } catch { print(error) } Update In iOS 13.3+ and macOS 15.1+ it's allowed to en-/decode fragments – single JSON values which are not wrapped in a collection type let jsonString = "4" let jsonData = Data(jsonString.utf8) do { let decoded = try JSONDecoder().decode(PostType.self, from: jsonData) print("decoded:", decoded) // -> decoded: count } catch { print(error) } In Swift 5.5+ it's even possible to en-/decode enums with associated values without any extra code. The values are mapped to a dictionary and a parameter label must be specified for each associated value enum Rotation: Codable { case zAxis(angle: Double, speed: Int) } let jsonString = #"{"zAxis":{"angle":90,"speed":5}}"# let jsonData = Data(jsonString.utf8) do { let decoded = try JSONDecoder().decode(Rotation.self, from: jsonData) print("decoded:", decoded) } catch { print(error) }
Swift
44,580,719
240
How do you create a date object from a date in swift xcode. eg in javascript you would do: var day = new Date('2014-05-20');
Swift has its own Date type. No need to use NSDate. Creating a Date and Time in Swift In Swift, dates and times are stored in a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. This is expressed in the Date structure. The following would give you the current date and time: let currentDateTime = Date() For creating other date-times, you can use one of the following methods. Method 1 If you know the number of seconds before or after the 2001 reference date, you can use that. let someDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM Method 2 Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date. For this you can use DateComponents to specify the components and then Calendar to create the date. The Calendar gives the Date context. Otherwise, how would it know what time zone or calendar to express it in? // Specify date components var dateComponents = DateComponents() dateComponents.year = 1980 dateComponents.month = 7 dateComponents.day = 11 dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time dateComponents.hour = 8 dateComponents.minute = 34 // Create date from components let userCalendar = Calendar(identifier: .gregorian) // since the components above (like year 1980) are for Gregorian let someDateTime = userCalendar.date(from: dateComponents) Other time zone abbreviations can be found here. If you leave that blank, then the default is to use the user's time zone. Method 3 The most succinct way (but not necessarily the best) could be to use DateFormatter. let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd HH:mm" let someDateTime = formatter.date(from: "2016/10/08 22:31") The Unicode technical standards show other formats that DateFormatter supports. Notes See my full answer for how to display the date and time in a readable format. Also read these excellent articles: How to work with dates and times in Swift 3, part 1: Dates, Calendars, and DateComponents How to work with dates and times in Swift 3, part 2: DateFormatter How to work with dates and times in Swift 3, part 3: Date arithmetic
Swift
24,089,999
240
I'm trying to run a HTTP Request in Swift, to POST 2 parameters to a URL. Example: Link: www.thisismylink.com/postName.php Params: id = 13 name = Jack What is the simplest way to do that? I don't even want to read the response. I just want to send that to perform changes on my database through a PHP file.
The key is that you want to: set the httpMethod to POST; optionally, set the Content-Type header, to specify how the request body was encoded, in case server might accept different types of requests; optionally, set the Accept header, to request how the response body should be encoded, in case the server might generate different types of responses; and set the httpBody to be properly encoded for the specific Content-Type; e.g. if application/x-www-form-urlencoded request, we need to percent-encode the body of the request. E.g., in Swift 3 and later you can: let url = URL(string: "https://httpbin.org/post")! var request = URLRequest(url: url) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" let parameters: [String: Any] = [ "id": 13, "name": "Jack & Jill" ] request.httpBody = parameters.percentEncoded() let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, let response = response as? HTTPURLResponse, error == nil else { // check for fundamental networking error print("error", error ?? URLError(.badServerResponse)) return } guard (200 ... 299) ~= response.statusCode else { // check for http errors print("statusCode should be 2xx, but is \(response.statusCode)") print("response = \(response)") return } // do whatever you want with the `data`, e.g.: do { let responseObject = try JSONDecoder().decode(ResponseObject<Foo>.self, from: data) print(responseObject) } catch { print(error) // parsing error if let responseString = String(data: data, encoding: .utf8) { print("responseString = \(responseString)") } else { print("unable to parse response as string") } } } task.resume() Where the following extensions facilitate the percent-encoding request body, converting a Swift Dictionary to a application/x-www-form-urlencoded formatted Data: extension Dictionary { func percentEncoded() -> Data? { map { key, value in let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? "" let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? "" return escapedKey + "=" + escapedValue } .joined(separator: "&") .data(using: .utf8) } } extension CharacterSet { static let urlQueryValueAllowed: CharacterSet = { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowed: CharacterSet = .urlQueryAllowed allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") return allowed }() } And the following Decodable model objects facilitate the parsing of the application/json response using JSONDecoder: // sample Decodable objects for https://httpbin.org struct ResponseObject<T: Decodable>: Decodable { let form: T // often the top level key is `data`, but in the case of https://httpbin.org, it echos the submission under the key `form` } struct Foo: Decodable { let id: String let name: String } This checks for both fundamental networking errors as well as high-level HTTP errors. This also properly percent escapes the parameters of the query. Note, I used a name of Jack & Jill, to illustrate the proper x-www-form-urlencoded result of name=Jack%20%26%20Jill, which is “percent encoded” (i.e. the space is replaced with %20 and the & in the value is replaced with %26). See previous revision of this answer for Swift 2 rendition.
Swift
26,364,914
237
I've got the following function which compiled cleanly previously but generates a warning with Xcode 8. func exitViewController() { navigationController?.popViewController(animated: true) } "Expression of type "UIViewController?" is unused". Why is it saying this and is there a way to remove it? The code executes as expected.
TL;DR popViewController(animated:) returns UIViewController?, and the compiler is giving that warning since you aren't capturing the value. The solution is to assign it to an underscore: _ = navigationController?.popViewController(animated: true) Swift 3 Change Before Swift 3, all methods had a "discardable result" by default. No warning would occur when you did not capture what the method returned. In order to tell the compiler that the result should be captured, you had to add @warn_unused_result before the method declaration. It would be used for methods that have a mutable form (ex. sort and sortInPlace). You would add @warn_unused_result(mutable_variant="mutableMethodHere") to tell the compiler of it. However, with Swift 3, the behavior is flipped. All methods now warn that the return value is not captured. If you want to tell the compiler that the warning isn't necessary, you add @discardableResult before the method declaration. If you don't want to use the return value, you have to explicitly tell the compiler by assigning it to an underscore: _ = someMethodThatReturnsSomething() Motivation for adding this to Swift 3: Prevention of possible bugs (ex. using sort thinking it modifies the collection) Explicit intent of not capturing or needing to capture the result for other collaborators The UIKit API appears to be behind on this, not adding @discardableResult for the perfectly normal (if not more common) use of popViewController(animated:) without capturing the return value. Read More SE-0047 Swift Evolution Proposal Accepted proposal with revisions
Swift
37,843,049
236
I'd like to store an array of weak references in Swift. The array itself should not be a weak reference - its elements should be. I think Cocoa NSPointerArray offers a non-typesafe version of this.
Create a generic wrapper as: class Weak<T: AnyObject> { weak var value : T? init (value: T) { self.value = value } } Add instances of this class to your array. class Stuff {} var weakly : [Weak<Stuff>] = [Weak(value: Stuff()), Weak(value: Stuff())] When defining Weak you can use either struct or class. Also, to help with reaping array contents, you could do something along the lines of: extension Array where Element:Weak<AnyObject> { mutating func reap () { self = self.filter { nil != $0.value } } } The use of AnyObject above should be replaced with T - but I don't think the current Swift language allows an extension defined as such.
Swift
24,127,587
235
override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent; } Using the above code in any ViewController to set the statusBar color to White for a specific viewcontroller doesnt work in iOS8 for me. Any suggestions? Using the UIApplication.sharedApplication method, the color changes after required changes in the Info.plist for the whole app. // Change the colour of status bar from black to white UIApplication.sharedApplication().statusBarStyle = .LightContent How can I just make changes to the status bar color for some required and specific ViewControllers?
After reading all the suggestions, and trying out a few things, I could get this to work for specific viewcontrollers using the following steps : First Step: Open your info.plist and insert a new key named "View controller-based status bar appearance" to NO Second Step (Just an explanation, no need to implement this): Normally we put the following code in the application(_:didFinishLaunchingWithOptions:) method of the AppDelegate, Swift 2 UIApplication.sharedApplication().statusBarStyle = .LightContent Swift 3 UIApplication.shared.statusBarStyle = .lightContent but that affects the statusBarStyle of all the ViewControllers. So, how to get this working for specific ViewControllers - Final Step: Open the viewcontroller file where you want to change the statusBarStyle and put the following code in viewWillAppear(), Swift 2 UIApplication.sharedApplication().statusBarStyle = .LightContent Swift 3 UIApplication.shared.statusBarStyle = .lightContent Also, implement the viewWillDisappear() method for that specific viewController and put the following lines of code, Swift 2 override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default } Swift 3 override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.statusBarStyle = UIStatusBarStyle.default } This step will first change the statusBarStyle for the specific viewcontroller and then change it back to default when the specific viewcontroller disappears. Not implementing the viewWillDisappear() will change the statusBarStyle permanently to the new defined value of UIStatusBarStyle.LightContent
Swift
26,956,728
234
I'm trying to apply a gradient as the background color of a View (main view of a storyboard). The code runs, but nothing changes. I'm using xCode Beta 2 and Swift. Here's the code: class Colors { let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0) let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0) let gl: CAGradientLayer init() { gl = CAGradientLayer() gl.colors = [ colorTop, colorBottom] gl.locations = [ 0.0, 1.0] } } then in the view controller: let colors = Colors() func refresh() { view.backgroundColor = UIColor.clearColor() var backgroundLayer = colors.gl backgroundLayer.frame = view.frame view.layer.insertSublayer(backgroundLayer, atIndex: 0) } } }
Xcode 11 • Swift 5.1 You can design your own Gradient View as follow: @IBDesignable public class Gradient: UIView { @IBInspectable var startColor: UIColor = .black { didSet { updateColors() }} @IBInspectable var endColor: UIColor = .white { didSet { updateColors() }} @IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }} @IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }} @IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }} @IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }} override public class var layerClass: AnyClass { CAGradientLayer.self } var gradientLayer: CAGradientLayer { layer as! CAGradientLayer } func updatePoints() { if horizontalMode { gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5) gradientLayer.endPoint = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5) } else { gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0) gradientLayer.endPoint = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1) } } func updateLocations() { gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber] } func updateColors() { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] } override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updatePoints() updateLocations() updateColors() } }
Swift
24,380,535
234
I want to extract substrings from a string that match a regex pattern. So I'm looking for something like this: func matchesForRegexInText(regex: String!, text: String!) -> [String] { ??? } So this is what I have: func matchesForRegexInText(regex: String!, text: String!) -> [String] { var regex = NSRegularExpression(pattern: regex, options: nil, error: nil) var results = regex.matchesInString(text, options: nil, range: NSMakeRange(0, countElements(text))) as Array<NSTextCheckingResult> /// ??? return ... } The problem is, that matchesInString delivers me an array of NSTextCheckingResult, where NSTextCheckingResult.range is of type NSRange. NSRange is incompatible with Range<String.Index>, so it prevents me of using text.substringWithRange(...) Any idea how to achieve this simple thing in swift without too many lines of code?
Even if the matchesInString() method takes a String as the first argument, it works internally with NSString, and the range parameter must be given using the NSString length and not as the Swift string length. Otherwise it will fail for "extended grapheme clusters" such as "flags". As of Swift 4 (Xcode 9), the Swift standard library provides functions to convert between Range<String.Index> and NSRange. func matches(for regex: String, in text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex) let results = regex.matches(in: text, range: NSRange(text.startIndex..., in: text)) return results.map { String(text[Range($0.range, in: text)!]) } } catch let error { print("invalid regex: \(error.localizedDescription)") return [] } } Example: let string = "🇩🇪€4€9" let matched = matches(for: "[0-9]", in: string) print(matched) // ["4", "9"] Note: The forced unwrap Range($0.range, in: text)! is safe because the NSRange refers to a substring of the given string text. However, if you want to avoid it then use return results.flatMap { Range($0.range, in: text).map { String(text[$0]) } } instead. (Older answer for Swift 3 and earlier:) So you should convert the given Swift string to an NSString and then extract the ranges. The result will be converted to a Swift string array automatically. (The code for Swift 1.2 can be found in the edit history.) Swift 2 (Xcode 7.3.1) : func matchesForRegexInText(regex: String, text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex, options: []) let nsString = text as NSString let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length)) return results.map { nsString.substringWithRange($0.range)} } catch let error as NSError { print("invalid regex: \(error.localizedDescription)") return [] } } Example: let string = "🇩🇪€4€9" let matches = matchesForRegexInText("[0-9]", text: string) print(matches) // ["4", "9"] Swift 3 (Xcode 8) func matches(for regex: String, in text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex) let nsString = text as NSString let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length)) return results.map { nsString.substring(with: $0.range)} } catch let error { print("invalid regex: \(error.localizedDescription)") return [] } } Example: let string = "🇩🇪€4€9" let matched = matches(for: "[0-9]", in: string) print(matched) // ["4", "9"]
Swift
27,880,650
233
I'm using Swift for programing with iOS and I'm using this code to move the UITextField, but it does not work. I call the function keyboardWillShow correctly, but the textfield doesn't move. I'm using autolayout. override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil); } deinit { NSNotificationCenter.defaultCenter().removeObserver(self); } func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { //let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) var frame = self.ChatField.frame frame.origin.y = frame.origin.y - keyboardSize.height + 167 self.chatField.frame = frame println("asdasd") } }
There are a couple of improvements to be made on the existing answers. Firstly the UIKeyboardWillChangeFrameNotification is probably the best notification as it handles changes that aren't just show/hide but changes due to keyboard changes (language, using 3rd party keyboards etc.) and rotations too (but note comment below indicating the keyboard will hide should also be handled to support hardware keyboard connection). Secondly the animation parameters can be pulled from the notification to ensure that animations are properly together. There are probably options to clean up this code a bit more especially if you are comfortable with force unwrapping the dictionary code. class MyViewController: UIViewController { // This constraint ties an element at zero points from the bottom layout guide @IBOutlet var keyboardHeightLayoutConstraint: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc func keyboardNotification(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let endFrameY = endFrame?.origin.y ?? 0 let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw) if endFrameY >= UIScreen.main.bounds.size.height { self.keyboardHeightLayoutConstraint?.constant = 0.0 } else { self.keyboardHeightLayoutConstraint?.constant = endFrame?.size.height ?? 0.0 } UIView.animate( withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: { self.view.layoutIfNeeded() }, completion: nil) } }
Swift
25,693,130
233
Here it says, "Note: the _ means “I don’t care about that value”", but coming from JavaScript, I don't understand what that means. The only way I can get these functions to print was by using the underscores before the parameters: func divmod(_ a: Int, _ b:Int) -> (Int, Int) { return (a / b, a % b) } print(divmod(7, 3)) print(divmod(5, 2)) print(divmod(12,4)) Without the underscores I have to write it like this to avoid any errors: func divmod(a: Int, b:Int) -> (Int, Int) { return (a / b, a % b) } print(divmod(a: 7, b: 3)) print(divmod(a: 5, b: 2)) print(divmod(a: 12,b: 4)) I don't understand this underscore usage. When, how and why do I use these underscores?
There are a few nuances to different use cases, but generally an underscore means "ignore this". When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing. A fuller function declaration looks like this: func myFunc(label name: Int) // call it like myFunc(label: 3) "label" is an argument label, and must be present when you call the function. (And since Swift 3, labels are required for all arguments by default.) "name" is the variable name for that argument that you use inside the function. A shorter form looks like this: func myFunc(name: Int) // call it like myFunc(name: 3) This is a shortcut that lets you use the same word for both external argument label and internal parameter name. It's equivalent to func myFunc(name name: Int). If you want your function to be callable without parameter labels, you use the underscore _ to make the label be nothing/ignored. (In that case you have to provide an internal name if you want to be able to use the parameter.) func myFunc(_ name: Int) // call it like myFunc(3) In an assignment statement, an underscore means "don't assign to anything". You can use this if you want to call a function that returns a result but don't care about the returned value. _ = someFunction() Or, like in the article you linked to, to ignore one element of a returned tuple: let (x, _) = someFunctionThatReturnsXandY() When you write a closure that implements some defined function type, you can use the underscore to ignore certain parameters. PHPhotoLibrary.performChanges( { /* some changes */ }, completionHandler: { success, _ in // don't care about error if success { print("yay") } }) Similarly, when declaring a function that adopts a protocol or overrides a superclass method, you can use _ for parameter names to ignore parameters. Since the protocol/superclass might also define that the parameter has no label, you can even end up with two underscores in a row. class MyView: NSView { override func mouseDown(with _: NSEvent) { // don't care about event, do same thing for every mouse down } override func draw(_ _: NSRect) { // don't care about dirty rect, always redraw the whole view } } Somewhat related to the last two styles: when using a flow control construct that binds a local variable/constant, you can use _ to ignore it. For example, if you want to iterate a sequence without needing access to its members: for _ in 1...20 { // or 0..<20 // do something 20 times } If you're binding tuple cases in a switch statement, the underscore can work as a wildcard, as in this example (shortened from one in The Swift Programming Language): switch somePoint { // somePoint is an (Int, Int) tuple case (0, 0): print("(0, 0) is at the origin") case (_, 0): print("(\(somePoint.0), 0) is on the x-axis") case (0, _): print("(0, \(somePoint.1)) is on the y-axis") default: print("(\(somePoint.0), \(somePoint.1)) isn't on an axis") } One last thing that's not quite related, but which I'll include since (as noted by comments) it seems to lead people here: An underscore in an identifier — e.g. var _foo, func do_the_thing(), struct Stuff_ — means nothing in particular to Swift, but has a few uses among programmers. Underscores within a name are a style choice, but not preferred in the Swift community, which has strong conventions about using UpperCamelCase for types and lowerCamelCase for all other symbols. Prefixing or suffixing a symbol name with underscore is a style convention, historically used to distinguish private/internal-use-only symbols from exported API. However, Swift has access modifiers for that, so this convention generally is seen as non-idiomatic in Swift. A few symbols with double-underscore prefixes (func __foo()) lurk in the depths of Apple's SDKs: These are (Obj)C symbols imported into Swift using the NS_REFINED_FOR_SWIFT attribute. Apple uses that when they want to make a "more Swifty" version of an (Obj)C API — for example, to make a type-agnostic method into a generic method. They need to use the imported API to make the refined Swift version work, so they use the __ to keep it available while hiding it from most tools and documentation.
Swift
39,627,106
231
If I have an enumeration with raw Integer values: enum City: Int { case Melbourne = 1, Chelyabinsk, Bursa } let city = City.Melbourne How can I convert a city value to a string Melbourne? Is this kind of a type name introspection available in the language? Something like (this code will not work): println("Your city is \(city.magicFunction)") > Your city is Melbourne
As of Xcode 7 beta 5 (Swift version 2) you can now print type names and enum cases by default using print(_:), or convert to String using String's init(_:) initializer or string interpolation syntax. So for your example: enum City: Int { case Melbourne = 1, Chelyabinsk, Bursa } let city = City.Melbourne print(city) // prints "Melbourne" let cityName = "\(city)" // or `let cityName = String(city)` // cityName contains "Melbourne" So there is no longer a need to define & maintain a convenience function that switches on each case to return a string literal. In addition, this works automatically for any enum, even if no raw-value type is specified. debugPrint(_:) & String(reflecting:) can be used for a fully-qualified name: debugPrint(city) // prints "App.City.Melbourne" (or similar, depending on the full scope) let cityDebugName = String(reflecting: city) // cityDebugName contains "App.City.Melbourne" Note that you can customise what is printed in each of these scenarios: extension City: CustomStringConvertible { var description: String { return "City \(rawValue)" } } print(city) // prints "City 1" extension City: CustomDebugStringConvertible { var debugDescription: String { return "City (rawValue: \(rawValue))" } } debugPrint(city) // prints "City (rawValue: 1)" (I haven't found a way to call into this "default" value, for example, to print "The city is Melbourne" without resorting back to a switch statement. Using \(self) in the implementation of description/debugDescription causes an infinite recursion.) The comments above String's init(_:) & init(reflecting:) initializers describe exactly what is printed, depending on what the reflected type conforms to: extension String { /// Initialize `self` with the textual representation of `instance`. /// /// * If `T` conforms to `Streamable`, the result is obtained by /// calling `instance.writeTo(s)` on an empty string s. /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the /// result is `instance`'s `description` /// * Otherwise, if `T` conforms to `CustomDebugStringConvertible`, /// the result is `instance`'s `debugDescription` /// * Otherwise, an unspecified result is supplied automatically by /// the Swift standard library. /// /// - SeeAlso: `String.init<T>(reflecting: T)` public init<T>(_ instance: T) /// Initialize `self` with a detailed textual representation of /// `subject`, suitable for debugging. /// /// * If `T` conforms to `CustomDebugStringConvertible`, the result /// is `subject`'s `debugDescription`. /// /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the result /// is `subject`'s `description`. /// /// * Otherwise, if `T` conforms to `Streamable`, the result is /// obtained by calling `subject.writeTo(s)` on an empty string s. /// /// * Otherwise, an unspecified result is supplied automatically by /// the Swift standard library. /// /// - SeeAlso: `String.init<T>(T)` public init<T>(reflecting subject: T) } See the release notes for info about this change.
Swift
24,113,126
231
How can I convert this string "2016-04-14T10:44:00+0000" into an NSDate and keep only the year, month, day, hour? The T in the middle of it really throws off what I am used to when working with dates.
Convert the ISO8601 string to date let isoDate = "2016-04-14T10:44:00+0000" let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let date = dateFormatter.date(from:isoDate)! Get the date components for year, month, day and hour from the date let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day, .hour], from: date) Finally create a new Date object and strip minutes and seconds let finalDate = calendar.date(from:components) Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 10.12: let isoDate = "2016-04-14T10:44:00+0000" let dateFormatter = ISO8601DateFormatter() let date = dateFormatter.date(from:isoDate)!
Swift
36,861,732
230
I'm trying to assign an UIImageView to an action when the user taps it. I know how to create an action for a UIButton, but how could I mimic the same behavior of a UIButton, but using a UIImageView?
You'll need a UITapGestureRecognizer. To set up use this: override func viewDidLoad() { super.viewDidLoad() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:))) imageView.isUserInteractionEnabled = true imageView.addGestureRecognizer(tapGestureRecognizer) } @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) { let tappedImage = tapGestureRecognizer.view as! UIImageView // Your action } (You could also use a UIButton and assign an image to it, without text and than simply connect an IBAction)
Swift
27,880,607
230
I want to test the equality of two Swift enum values. For example: enum SimpleToken { case Name(String) case Number(Int) } let t1 = SimpleToken.Number(123) let t2 = SimpleToken.Number(123) XCTAssert(t1 == t2) However, the compiler won't compile the equality expression: error: could not find an overload for '==' that accepts the supplied arguments XCTAssert(t1 == t2) ^~~~~~~~~~~~~~~~~~~ Do I have do define my own overload of the equality operator? I was hoping the Swift compiler would handle it automatically, much like Scala and Ocaml do.
Swift 4.1+ As @jedwidz has helpfully pointed out, from Swift 4.1 (due to SE-0185, Swift also supports synthesizing Equatable and Hashable for enums with associated values. So if you're on Swift 4.1 or newer, the following will automatically synthesize the necessary methods such that XCTAssert(t1 == t2) works. The key is to add the Equatable protocol to your enum. enum SimpleToken: Equatable { case name(String) case number(Int) } let t1 = SimpleToken.number(123) let t2 = SimpleToken.number(123) Before Swift 4.1 As others have noted, Swift doesn't synthesize the necessary equality operators automatically. Let me propose a cleaner (IMHO) implementation, though: enum SimpleToken: Equatable { case name(String) case number(Int) } public func ==(lhs: SimpleToken, rhs: SimpleToken) -> Bool { switch (lhs, rhs) { case let (.name(a), .name(b)), let (.number(a), .number(b)): return a == b default: return false } } It's far from ideal — there's a lot of repetition — but at least you don't need to do nested switches with if-statements inside.
Swift
24,339,807
230
I have a navigation bar with a title. When I double click the text to rename it, it actually says it's a navigation item, so it might be that. I'm trying to change the text using code, like: declare navigation bar as navagationbar here button stuff { navigationbar.text = "title" } That's not my code obviously, just showing how it would work. So whenever I press the button, I want the title to change.
You change the title by changing the title of the view controller being displayed: viewController.title = "some title" Normally this is done in view did load on the view controller: override func viewDidLoad() { super.viewDidLoad() self.title = "some title" } However, this only works if you have your view controller embedded in a UINavigationController. I highly recommend doing this instead of creating a navigation bar yourself. If you insist on creating a navigation bar yourself, you can change the title by doing: navigationBar.topItem.title = "some title"
Swift
25,167,458
229
How can I get a device's unique ID in Swift? I need an ID to use in the database and as the API-key for my web service in my social app. Something to keep track of this devices daily use and limit its queries to the database.
You can use this (Swift 3): UIDevice.current.identifierForVendor!.uuidString For older versions: UIDevice.currentDevice().identifierForVendor or if you want a string: UIDevice.currentDevice().identifierForVendor!.UUIDString There is no longer a way to uniquely identify a device after the user uninstalled the app(s). The documentation says: The value in this property remains the same while the app (or another app from the same vendor) is installed on the iOS device. The value changes when the user deletes all of that vendor’s apps from the device and subsequently reinstalls one or more of them. You may also want to read this article by Mattt Thompson for more details: http://nshipster.com/uuid-udid-unique-identifier/ Update for Swift 4.1, you will need to use: UIDevice.current.identifierForVendor?.uuidString
Swift
25,925,481
228
I want to convert a Float to an Int in Swift. Basic casting like this does not work because these types are not primitives, unlike floats and ints in Objective-C var float: Float = 2.2 var integer: Int = float as Float But this produces the following error message: 'Float' is not convertible to 'Int' Any idea how to property convert from Float to Int?
You can convert Float to Int in Swift like this: var myIntValue:Int = Int(myFloatValue) println "My value is \(myIntValue)" You can also achieve this result with @paulm's comment: var myIntValue = Int(myFloatValue)
Swift
24,029,917
228
I have an array and I want to iterate through it initialize views based on array value, and want to perform action based on array item index When I iterate through objects ForEach(array, id: \.self) { item in CustomView(item: item) .tapAction { self.doSomething(index) // Can't get index, so this won't work } } So, I've tried another approach ForEach((0..<array.count)) { index in CustomView(item: array[index]) .tapAction { self.doSomething(index) } } But the issue with second approach is, that when I change array, for example, if doSomething does following self.array = [1,2,3] views in ForEach do not change, even if values are changed. I believe, that happens because array.count haven't changed. Is there a solution for this?
Another approach is to use: enumerated() ForEach(Array(array.enumerated()), id: \.offset) { index, element in // ... } Source: https://alejandromp.com/blog/swiftui-enumerated/
Swift
57,244,713
224
I need a way to remove the first character from a string which is a space. I am looking for a method or even an extension for the String type that I can use to cut out a character of a string.
To remove leading and trailing whitespaces: let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) Swift 3 / Swift 4: let trimmedString = string.trimmingCharacters(in: .whitespaces)
Swift
28,570,973
224
I'm looking for a simple method to remove at once all subviews from a superview instead of removing them one by one. //I'm trying something like this, but is not working let theSubviews : Array = container_view.subviews for (view : NSView) in theSubviews { view.removeFromSuperview(container_view) } What I am missing? UPDATE My app has a main container_view. I have to add different other views as subviews to container_view in order to provide a sort of navigation. So, when clicking the button to "open" a particular page, I need to remove allsubviews and add the new one. UPDATE 2 - A working solution (OS X) I guess Apple fixed it. Now it is more easy than ever, just call: for view in containerView.subviews{ view.removeFromSuperview() }
EDIT: (thanks Jeremiah / Rollo) By far the best way to do this in Swift for iOS is: view.subviews.forEach({ $0.removeFromSuperview() }) // this gets things done view.subviews.map({ $0.removeFromSuperview() }) // this returns modified array ^^ These features are fun! let funTimes = ["Awesome","Crazy","WTF"] extension String { func readIt() { print(self) } } funTimes.forEach({ $0.readIt() }) //// END EDIT Just do this: for view in self.view.subviews { view.removeFromSuperview() } Or if you are looking for a specific class for view:CustomViewClass! in self.view.subviews { if view.isKindOfClass(CustomViewClass) { view.doClassThing() } }
Swift
24,312,760
224
With this simple class I am getting the compiler warning Attempting to modify/access x within its own setter/getter and when I use it like this: var p: point = Point() p.x = 12 I get an EXC_BAD_ACCESS. How can I do this without explicit backing ivars? class Point { var x: Int { set { x = newValue * 2 //Error } get { return x / 2 //Error } } // ... }
Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned. Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this: class Point { private var _x: Int = 0 // _x -> backingX var x: Int { set { _x = 2 * newValue } get { return _x / 2 } } } Specifically, in the Swift REPL: 15> var pt = Point() pt: Point = { _x = 0 } 16> pt.x = 10 17> pt $R3: Point = { _x = 20 } 18> pt.x $R4: Int = 10
Swift
24,025,340
224
How can I determine the number of cases in a Swift enum? (I would like to avoid manually enumerating through all the values, or using the old "enum_count trick" if possible.)
As of Swift 4.2 (Xcode 10) you can declare conformance to the CaseIterable protocol, this works for all enumerations without associated values: enum Stuff: CaseIterable { case first case second case third case forth } The number of cases is now simply obtained with print(Stuff.allCases.count) // 4 For more information, see SE-0194 Derived Collection of Enum Cases
Swift
27,094,878
223
I am new to SwiftUI (like most people) and trying to figure out how to remove some whitespace above a List that I embedded in a NavigationView. In this image, you can see that there is some white space above the List. What I want to accomplish is this: I've tried using: .navigationBarHidden(true) but this did not make any noticeable changes. I'm currently setting up my navigiationView like this: NavigationView { FileBrowserView(jsonFromCall: URLRetrieve(URLtoFetch: applicationDelegate.apiURL)) .navigationBarHidden(true) } where FileBrowserView is a view with a List and FileCells defined like this: List { Section(header: Text("Root")) { FileCell(name: "Test", fileType: "JPG",fileDesc: "Test number 1") FileCell(name: "Test 2", fileType: "txt",fileDesc: "Test number 2") FileCell(name: "test3", fileType: "fasta", fileDesc: "") } } I do want to note that the ultimate goal here is that you will be able to click on these cells to navigate deeper into a file tree and thus should display a Back button on the bar on deeper navigation, but I do not want anything at the top as such during my initial view.
For some reason, SwiftUI requires that you also set .navigationBarTitle for .navigationBarHidden to work properly. NavigationView { FileBrowserView(jsonFromCall: URLRetrieve(URLtoFetch: applicationDelegate.apiURL)) .navigationBarTitle("") .navigationBarHidden(true) } Update As @Peacemoon pointed out in the comments, the navigation bar remains hidden as you navigate deeper in the navigation stack, regardless of whether or not you set navigationBarHidden to false in subsequent views. As I said in the comments, this is either a result of poor implementation on Apple's part or just dreadful documentation (who knows, maybe there is a "correct" way to accomplish this). Whatever the case, I came up with a workaround that seems to produce the original poster's desired results. I'm hesitant to recommend it because it seems unnecessarily hacky, but without any straightforward way of hiding and unhiding the navigation bar, this is the best I could do. This example uses three views - View1 has a hidden navigation bar, and View2 and View3 both have visible navigation bars with titles. struct View1: View { @State var isNavigationBarHidden: Bool = true var body: some View { NavigationView { ZStack { Color.red NavigationLink("View 2", destination: View2(isNavigationBarHidden: self.$isNavigationBarHidden)) } .navigationBarTitle("Hidden Title") .navigationBarHidden(self.isNavigationBarHidden) .onAppear { self.isNavigationBarHidden = true } } } } struct View2: View { @Binding var isNavigationBarHidden: Bool var body: some View { ZStack { Color.green NavigationLink("View 3", destination: View3()) } .navigationBarTitle("Visible Title 1") .onAppear { self.isNavigationBarHidden = false } } } struct View3: View { var body: some View { Color.blue .navigationBarTitle("Visible Title 2") } } Setting navigationBarHidden to false on views deeper in the navigation stack doesn't seem to properly override the preference of the view that originally set navigationBarHidden to true, so the only workaround I could come up with was using a binding to change the preference of the original view when a new view is pushed onto the navigation stack. Like I said, this is a hacky solution, but without an official solution from Apple, this is the best that I've been able to come up with.
Swift
57,517,803
222
It's time to admit defeat... In Objective-C, I could use something like: NSString* str = @"abcdefghi"; [str rangeOfString:@"c"].location; // 2 In Swift, I see something similar: var str = "abcdefghi" str.rangeOfString("c").startIndex ...but that just gives me a String.Index, which I can use to subscript back into the original string, but not extract a location from. FWIW, that String.Index has a private ivar called _position that has the correct value in it. I just don't see how it's exposed. I know I could easily add this to String myself. I'm more curious about what I'm missing in this new API.
You are not the only one who couldn't find the solution. String doesn't implement RandomAccessIndexType. Probably because they enable characters with different byte lengths. That's why we have to use string.characters.count (count or countElements in Swift 1.x) to get the number of characters. That also applies to positions. The _position is probably an index into the raw array of bytes and they don't want to expose that. The String.Index is meant to protect us from accessing bytes in the middle of characters. That means that any index you get must be created from String.startIndex or String.endIndex (String.Index implements BidirectionalIndexType). Any other indices can be created using successor or predecessor methods. Now to help us with indices, there is a set of methods (functions in Swift 1.x): Swift 4.x let text = "abc" let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times let lastChar: Character = text[index2] //now we can index! let characterIndex2 = text.index(text.startIndex, offsetBy: 2) let lastChar2 = text[characterIndex2] //will do the same as above let range: Range<String.Index> = text.range(of: "b")! let index: Int = text.distance(from: text.startIndex, to: range.lowerBound) Swift 3.0 let text = "abc" let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times let lastChar: Character = text[index2] //now we can index! let characterIndex2 = text.characters.index(text.characters.startIndex, offsetBy: 2) let lastChar2 = text.characters[characterIndex2] //will do the same as above let range: Range<String.Index> = text.range(of: "b")! let index: Int = text.distance(from: text.startIndex, to: range.lowerBound) Swift 2.x let text = "abc" let index2 = text.startIndex.advancedBy(2) //will call succ 2 times let lastChar: Character = text[index2] //now we can index! let lastChar2 = text.characters[index2] //will do the same as above let range: Range<String.Index> = text.rangeOfString("b")! let index: Int = text.startIndex.distanceTo(range.startIndex) //will call successor/predecessor several times until the indices match Swift 1.x let text = "abc" let index2 = advance(text.startIndex, 2) //will call succ 2 times let lastChar: Character = text[index2] //now we can index! let range = text.rangeOfString("b") let index: Int = distance(text.startIndex, range.startIndex) //will call succ/pred several times Working with String.Index is cumbersome but using a wrapper to index by integers (see https://stackoverflow.com/a/25152652/669586) is dangerous because it hides the inefficiency of real indexing. Note that Swift indexing implementation has the problem that indices/ranges created for one string cannot be reliably used for a different string, for example: Swift 2.x let text: String = "abc" let text2: String = "🎾🏇🏈" let range = text.rangeOfString("b")! //can randomly return a bad substring or throw an exception let substring: String = text2[range] //the correct solution let intIndex: Int = text.startIndex.distanceTo(range.startIndex) let startIndex2 = text2.startIndex.advancedBy(intIndex) let range2 = startIndex2...startIndex2 let substring: String = text2[range2] Swift 1.x let text: String = "abc" let text2: String = "🎾🏇🏈" let range = text.rangeOfString("b") //can randomly return nil or a bad substring let substring: String = text2[range] //the correct solution let intIndex: Int = distance(text.startIndex, range.startIndex) let startIndex2 = advance(text2.startIndex, intIndex) let range2 = startIndex2...startIndex2 let substring: String = text2[range2]
Swift
24,029,163
222
I'm reading the documentation and I am constantly shaking my head at some of the design decisions of the language. But the thing that really got me puzzled is how arrays are handled. I rushed to the playground and tried these out. You can try them too. So the first example: var a = [1, 2, 3] var b = a a[1] = 42 a b Here a and b are both [1, 42, 3], which I can accept. Arrays are referenced - OK! Now see this example: var c = [1, 2, 3] var d = c c.append(42) c d c is [1, 2, 3, 42] BUT d is [1, 2, 3]. That is, d saw the change in the last example but doesn't see it in this one. The documentation says that's because the length changed. Now, how about this one: var e = [1, 2, 3] var f = e e[0..2] = [4, 5] e f e is [4, 5, 3], which is cool. It's nice to have a multi-index replacement, but f STILL doesn't see the change even though the length has not changed. So to sum it up, common references to an array see changes if you change 1 element, but if you change multiple elements or append items, a copy is made. This seems like a very poor design to me. Am I right in thinking this? Is there a reason I don't see why arrays should act like this? EDIT: Arrays have changed and now have value semantics. Much more sane!
Note that array semantics and syntax was changed in Xcode beta 3 version (blog post), so the question no longer applies. The following answer applied to beta 2: It's for performance reasons. Basically, they try to avoid copying arrays as long as they can (and claim "C-like performance"). To quote the language book: For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array. This includes appending, inserting, or removing items, or using a ranged subscript to replace a range of items in the array. I agree that this is a bit confusing, but at least there is a clear and simple description of how it works. That section also includes information on how to make sure an array is uniquely referenced, how to force-copy arrays, and how to check whether two arrays share storage.
Swift
24,081,009
221
Is there a counterpart in Swift to flatten in Scala, Xtend, Groovy, Ruby and co? var aofa = [[1,2,3],[4],[5,6,7,8,9]] aofa.flatten() // shall deliver [1,2,3,4,5,6,7,8,9] of course i could use reduce for that but that kinda sucks var flattened = aofa.reduce(Int[]()){ a,i in var b : Int[] = a b.extend(i) return b }
Swift >= 3.0 reduce: let numbers = [[1,2,3],[4],[5,6,7,8,9]] let reduced = numbers.reduce([], +) flatMap: let numbers = [[1,2,3],[4],[5,6,7,8,9]] let flattened = numbers.flatMap { $0 } joined: let numbers = [[1,2,3],[4],[5,6,7,8,9]] let joined = Array(numbers.joined())
Swift
24,465,281
220
What is the purpose of writing comments in Swift as: // MARK: This is a comment When you can also do: // This is a comment What does the // MARK achieve?
The // MARK: and // MARK: - syntax in Swift functions identically to the #pragma mark and #pragma mark - syntax in Objective-C. When using this syntax (plus // TODO: and // FIXME:), you can get some extra information to show up in the quick jump bar. Consider these few lines of source code: // MARK: A mark comment lives here. func isPrime(_ value: UInt) -> Bool { return true } And for reference, the quick jump bar is at the top in Xcode: It exists mostly to help with quick navigation within the file. Note that the dash (// MARK: -) causes a nice separation line to show up. Consider this MARK comment: // MARK: - A mark comment lives here. The darker gray separator line just above the bolded option in that menu comes from the dash. Additionally, we can achieve this separator line without a comment by simply not having any text after the dash: // MARK: - As mentioned, // TODO: and // FIXME: comments will also appear here. // MARK: - Prime functions func isPrime(_ value: UInt) -> Bool { // TODO: Actually implement the logic for this method return true } func nthPrime(_ value: UInt) -> Int { // FIXME: Returns incorrect values for some arguments return 2 } FIXMEs get a little band-aid icon that help them standout. MARK icon looks like a table of contents TODO icons look more like a checklist Clicking on any line in the quick jump bar takes you directly to that line in the source code.
Swift
35,963,128
219
I am trying to implement a feature in an App that shows an alert when the internet connection is not available. The alert has two actions (OK and Settings), whenever a user clicks on settings, I want to take them to the phone settings programmatically. I am using Swift and Xcode.
Using UIApplication.openSettingsURLString Update for Swift 5.1 override func viewDidAppear(_ animated: Bool) { let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in print("Settings opened: \(success)") // Prints true }) } } alertController.addAction(settingsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } Swift 4.2 override func viewDidAppear(_ animated: Bool) { let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in print("Settings opened: \(success)") // Prints true }) } } alertController.addAction(settingsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) }
Swift
28,152,526
219
Problem: NSAttributedString takes an NSRange while I'm using a Swift String that uses Range let text = "Long paragraph saying something goes here!" let textRange = text.startIndex..<text.endIndex let attributedString = NSMutableAttributedString(string: text) text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange) } }) Produces the following error: error: 'Range' is not convertible to 'NSRange' attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
Swift String ranges and NSString ranges are not "compatible". For example, an emoji like 😄 counts as one Swift character, but as two NSString characters (a so-called UTF-16 surrogate pair). Therefore your suggested solution will produce unexpected results if the string contains such characters. Example: let text = "😄😄😄Long paragraph saying!" let textRange = text.startIndex..<text.endIndex let attributedString = NSMutableAttributedString(string: text) text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in let start = distance(text.startIndex, substringRange.startIndex) let length = distance(substringRange.startIndex, substringRange.endIndex) let range = NSMakeRange(start, length) if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range) } }) println(attributedString) Output: 😄😄😄Long paragra{ }ph say{ NSColor = "NSCalibratedRGBColorSpace 1 0 0 1"; }ing!{ } As you see, "ph say" has been marked with the attribute, not "saying". Since NS(Mutable)AttributedString ultimately requires an NSString and an NSRange, it is actually better to convert the given string to NSString first. Then the substringRange is an NSRange and you don't have to convert the ranges anymore: let text = "😄😄😄Long paragraph saying!" let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) let attributedString = NSMutableAttributedString(string: nsText) nsText.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange) } }) println(attributedString) Output: 😄😄😄Long paragraph { }saying{ NSColor = "NSCalibratedRGBColorSpace 1 0 0 1"; }!{ } Update for Swift 2: let text = "😄😄😄Long paragraph saying!" let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) let attributedString = NSMutableAttributedString(string: text) nsText.enumerateSubstringsInRange(textRange, options: .ByWords, usingBlock: { (substring, substringRange, _, _) in if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange) } }) print(attributedString) Update for Swift 3: let text = "😄😄😄Long paragraph saying!" let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) let attributedString = NSMutableAttributedString(string: text) nsText.enumerateSubstrings(in: textRange, options: .byWords, using: { (substring, substringRange, _, _) in if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.red, range: substringRange) } }) print(attributedString) Update for Swift 4: As of Swift 4 (Xcode 9), the Swift standard library provides method to convert between Range<String.Index> and NSRange. Converting to NSString is no longer necessary: let text = "😄😄😄Long paragraph saying!" let attributedString = NSMutableAttributedString(string: text) text.enumerateSubstrings(in: text.startIndex..<text.endIndex, options: .byWords) { (substring, substringRange, _, _) in if substring == "saying" { attributedString.addAttribute(.foregroundColor, value: NSColor.red, range: NSRange(substringRange, in: text)) } } print(attributedString) Here substringRange is a Range<String.Index>, and that is converted to the corresponding NSRange with NSRange(substringRange, in: text)
Swift
27,040,924
219
I am playing around with Apple's new Swift programming language and have some problems... Currently I'm trying to read a plist file, in Objective-C I would do the following to get the content as a NSDictionary: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"]; NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath]; How do I get a plist as a Dictionary in Swift? I assume I can get the path to the plist with: let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") When this works (If it's correct?): How do I get the content as a Dictionary? Also a more general question: Is it OK to use the default NS* classes? I think so...or am I missing something? As far as I know the default framework NS* classes are still valid and alright to use?
You can still use NSDictionaries in Swift: For Swift 4 var nsDictionary: NSDictionary? if let path = Bundle.main.path(forResource: "Config", ofType: "plist") { nsDictionary = NSDictionary(contentsOfFile: path) } For Swift 3+ if let path = Bundle.main.path(forResource: "Config", ofType: "plist"), let myDict = NSDictionary(contentsOfFile: path){ // Use your myDict here } And older versions of Swift var myDict: NSDictionary? if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") { myDict = NSDictionary(contentsOfFile: path) } if let dict = myDict { // Use your dict here } The NSClasses are still available and perfectly fine to use in Swift. I think they'll probably want to shift focus to swift soon, but currently the swift APIs don't have all the functionality of the core NSClasses.
Swift
24,045,570
219
I'd like to remove the status bar at the top of the screen. This does not work: func application (application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { application.statusBarHidden = true return true } I've also tried: func application (application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) var controller = UIViewController() application.statusBarHidden = true controller.setNeedsStatusBarAppearanceUpdate() var view = UIView(frame: CGRectMake(0, 0, 320, 568)) view.backgroundColor = UIColor.redColor() controller.view = view var label = UILabel(frame: CGRectMake(0, 0, 200, 21)) label.center = CGPointMake(160, 284) label.textAlignment = NSTextAlignment.Center label.text = "Hello World" controller.view.addSubview(label) self.window!.rootViewController = controller self.window!.makeKeyAndVisible() return true }
You really should implement prefersStatusBarHidden on your view controller(s): Swift 3 and later override var prefersStatusBarHidden: Bool { return true }
Swift
24,236,912
217
For a long time, when it comes to the microservice architecture, NATS and Kafka are the first options that come to my mind. But recently I found this gRPC template in dotnet core and that grasped my attention. I read a lot about it and watched a lot of videos but I don't think any of those could address gRPC correctly as they usually contrast between gRPC and message brokers or protocols such as REST which I guess is pretty inappropriate although SOAP would be relevant here. My assumption is that gRPC is a modern version of SOAP with better performance and less implementation hassle due to it protocol buffer. And I think that gRPC can by no means be compared against Kafka or NATS. And also that it cannot replace RESTful service as neither could SOAP. Now, the question, to what extent are my assumptions true? For example, when it comes to selecting a communication bridge between nodes on a cluster, do I have to put gPRC among my options now (NATS, Kafkam Rabbit, etc) or should I consider that when creating a web proxy to bridge external request to my microservices? Finally, how about real-time communication, can gRPC replace websocket/socket.io/signalR completely? What does it replace?
I often see people misplacing these technologies by one crucial aspect: public authentication. For instance, check this graph: This is a benchmark of Inverted Json (https://github.com/lega911/ijson), comparing some tools, such as iJson, RabbitMQ, Nats, 0MQ, etc. Notice that Nats, ZeroMQ and iJson are not meant to be used as public end-points (for instance, Nats have user/password, token and keys, but it is useless in an open environment, such as web browsers, because there is no way to make the key non public). On the other hand, GRPC works just fine with JWT and Oauth2, making it completely safe to public end-points (as safer as any other HTTP endpoint), 'cos those tokens are server-signed (so, even tough they are public, they can't be forged or tempered with) So, what I'm trying to say is: there are techs meant to face public and techs meant to glue together servers and process within servers (which are private connections). GRPC is public, ZeroMQ and iJson are totally private (iJson, for instance, don't have any kind of authentication). Nats works with keys or passwords, so, although is "safer" than iJson and ZeroMQ, it is not meant to be public. When you say REST (I'm assuming HTTP here, because REST is just an architecture), websocket/socket.io/signalR, you are depicting all public interfaces. GRPC will cover you here (it's comparable to REST as request/response and websocket/socket.io/signalR because it supports half and full duplex streaming (similar to sockets)). Nats, iJson, ZeroMQ, on the other hand, are not meant to do that. They are meant to communicate between services. So, basically, REST/websocket/socket.io/signalR = gRPC. Internal communication between services (in the same or in different servers) = NATs, iJSON, ZeroMQ. (notice that I'm not even considering the other technologies in the graph, because they are products, IMO, not simple libraries you can use to achieve an end, such as RabbitMQ, nginx, etc. The other ones I'm not familiar enough to be able to make an opinion (but I'm surprised by the uvloop in that graph)).
gRPC
63,418,503
12
After downloading BloomRPC from the github repo and running brew cask install bloomrpc, when I try to open the BloomRPC application I get "BloomRPC cannot be opened because the developer cannot be verified." I've tried going to Security and Privacy -> Developer Tools -> and enabling BloomRPC under "Allow the apps below to run software locally that does not meet the system's security policy", but I still get the same error message. I'm on macOS Catalina 10.15.5. How do I open the BloomRPC application?
You can try to build BloomRPC from source (as they mentioned in their repo) Or you can simply bypass this error go navigate to SystemPreference -> Security&Privacy. Under General tab, you will see a statement about BloomRPC, click on Open Anyway to suppress the warning and continue to use.
gRPC
63,160,778
12
Is it possible to have a client channel that automatically reconnects? I tried using wait_for_ready(true) on the context, but that doesn't seem to have any effect. I get this crash when I try to use a client channel with a lost connection: E0519 12:56:40.239405883 9379 client_context.cc:119] assertion failed: call_ == nullptr
My problem was attempting to re-use a context. Creating a new context for each attempt fixed the issue.
gRPC
61,889,726
12
I'm trying to work out whether I could use one of the (A/E/N)LBs to load balance gRPC traffic. A simple round robin would suffice in our case. I've read that ALB doesn't fully support HTTP2 and therefore can't be used with gRPC. Specifically lack of support of sending HTTP2 traffic downstream and lack of support for trailer headers was mentioned. Is it still true? Couldn't find any definitive answers with regards to NLBs or "classic" ELBs. Any hints?
As of October 29, 2020, Application Load Balancers now support HTTP/2 and gRPC load balancing. From the announcement: To use the feature on your ALB, choose HTTPS as your listener protocol, gRPC as the protocol version for your target group and register instance or IP as targets for the configured target group. ALB provides rich content based routing features that will let you inspect gRPC calls and route them to the appropriate target group based on the service and method requested. Within a target group, ALB will use gRPC specific health checks to determine availability of targets and provide gRPC specific access logs to monitor your traffic. The support for gRPC and end-to-end HTTP/2 is available for existing and new Application Load Balancers at no extra charge in all AWS Regions. To learn more, please refer to the blog post, demo, and the ALB documentation.
gRPC
60,164,162
12
I have worked with grpc .net client and a grpc server created with java, how can i implement grpc web client on angular 6 with typescript? Also how can i create proto files and it's typing's for typescript? I am following this repo but not able to generate proto files.
After spending sometime i was able to create proto files for typescript by following steps: Download protobuf for windows from this link. After extracting files set the path variable for protoc.exe install npm packages npm install google-protobuf @types/google-protobuf grpc-web-client ts-protoc-gen --save After installing it generate the typescript files by using the command: protoc --plugin="protoc-gen-ts=absolute-path-to-your-project\node_modules\.bin\protoc-gen-ts.cmd" --js_out="import_style=commonjs,binary:${OUT_DIR}" --ts_out="service=true:${OUT_DIR}" your.proto Finally consume it like as mentioned in this repo.
gRPC
51,857,225
12
I'm attempting to add the GRPC dependency to a node elastic beanstalk application and all of my deployments are failing. Once I remove the GRPC dependency from my package.json my deployments work. The error is ERROR: Failed to run npm install. > [email protected] install /tmp/deployment/application/node_modules/grpc > node-pre-gyp install --fallback-to-build --library=static_library node-pre-gyp ERR! Pre-built binaries not installable for [email protected] and [email protected] (node-v57 ABI, glibc) (falling back to source compile with node-gyp) node-pre-gyp ERR! Hit error EACCES: permission denied, mkdir '/tmp/deployment/application/node_modules/grpc/src/node' gyp ERR! configure error gyp ERR! stack Error: EACCES: permission denied I've had this issue on another node app and was able to resolve it by running npm --save-dev eb-fix-npm but it does not work with this app. I also sometimes get an error along the lines of `cannot create symbolic link, file already exists (paraphrased). I have this file set up as well to attempt to fix this. files: "/opt/elasticbeanstalk/hooks/appdeploy/pre/50npm.sh" : mode: "000775" owner: root group: root content: | #!/bin/bash function error_exit { eventHelper.py --msg "$1" --severity ERROR exit $2 } export HOME=/home/ec2-user OUT=$(/opt/elasticbeanstalk/containerfiles/ebnode.py --action npm-install 2>&1) || error_exit "Failed to run npm install. $OUT" $? echo $OUT Thanks for the help
For anyone using bcrypt library in your project. You will get this error if you are trying to deploy your code using Elastic Beanstalk . Just remove bcrypt and start using bycryptjs Banged my head for 2 weeks on this . Also downgrading bcrypt to 3.0.0 won't help you with this.
gRPC
49,951,257
12
Is it possible to only stream to certain clients from a gRPC server? I believe what I'm looking for is something like Pusher, where you have a channel for a client and you can publish messages that can be seen only by a client that has access to that channel. What I'm struggling with is understanding what are the steps we need to take to do something like this. Thinking about web-sockets I believe we can store each client connection, then we can find that connection and send messages. How can we do a similar thing with gRPC?
As per as i understood the question. You want to send the the message to the particular client in gRPC. This is very much possible using Server side streaming or Bi-directional streaming in gRPC. For example: Define a server side streaming or bidi streaming api rpc ListFeatures(Rectangle) returns (stream Feature) {} On Server side: func ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { // Save this stream instance in the server on a map or other suitable data structure // so that you can query for this stream instance later // This will act same like your websocket session } When you want to send something to a specific client then get the stream instance and do err := stream.Send(feature); // Any times as required On the client, it will be waiting for messages like this stream, err := client.ListFeatures(ctx, rect) for { feature, err := stream.Recv() ... // handle message here } Same thing can be done for bidi streaming rpc also. I hope this answers your question
gRPC
49,230,524
12
I want know about good practices with golang and gRPC and protobuf. I am implementing the following gRPC service service MyService { rpc dosomethink(model.MyModel) returns (model.Model) { option (google.api.http) = { post: "/my/path" body: "" }; } } I compiled the protobufs. In fact, the protobuf give us a httpproxy from http to grpc. The code to implement this service: import "google.golang.org/grpc/status" func (Abcd) Dosomethink(c context.Context, sessionRequest *model.MyModel) (*model.Model, error) { return nil, status.New(400,"Default error message for 400") } I want a 400 http error (in the http proxy) with the message "Default error message for 400", the message works, but the http error always is 500. Do you know any post or doc about this?
You need to return empty model.Model object in order for protobufs to be able to properly serialise the message. Try import "google.golang.org/grpc/status" func (Abcd) Dosomethink(c context.Context, sessionRequest *model.MyModel) (*model.Model, error) { return &model.Model{}, status.Error(400,"Default error message for 400") }
gRPC
45,455,144
12
When we want to use distributed TensorFlow, we will create a parameter server using tf.train.Server.join() However, I can't find any way to shut down the server except killing the processing. The TensorFlow documentation for join() is Blocks until the server has shut down. This method currently blocks forever. This is quite bothering to me because I would like to create many servers for computation and shut them down when everything finishes. Is there possible solutions for this. Thanks
You can have parameter server processes die on demand by using session.run(dequeue_op) instead of server.join() and having another process enqueue something onto that queue when you want this process to die. So for k parameter server shards you could create k queues, with unique shared_name property and try to dequeue from that queue. When you want to bring down the servers, you loop over all queues and enqueue a token onto each queue. This would cause session.run to unblock and Python process will run to the end and quit, bringing down the server. Below is a self-contained example with 2 shards taken from: https://gist.github.com/yaroslavvb/82a5b5302449530ca5ff59df520c369e (for multi worker/multi shard example, see https://gist.github.com/yaroslavvb/ea1b1bae0a75c4aae593df7eca72d9ca) import subprocess import tensorflow as tf import time import sys flags = tf.flags flags.DEFINE_string("port1", "12222", "port of worker1") flags.DEFINE_string("port2", "12223", "port of worker2") flags.DEFINE_string("task", "", "internal use") FLAGS = flags.FLAGS # setup local cluster from flags host = "127.0.0.1:" cluster = {"worker": [host+FLAGS.port1, host+FLAGS.port2]} clusterspec = tf.train.ClusterSpec(cluster).as_cluster_def() if __name__=='__main__': if not FLAGS.task: # start servers and run client # launch distributed service def runcmd(cmd): subprocess.Popen(cmd, shell=True, stderr=subprocess.STDOUT) runcmd("python %s --task=0"%(sys.argv[0])) runcmd("python %s --task=1"%(sys.argv[0])) time.sleep(1) # bring down distributed service sess = tf.Session("grpc://"+host+FLAGS.port1) queue0 = tf.FIFOQueue(1, tf.int32, shared_name="queue0") queue1 = tf.FIFOQueue(1, tf.int32, shared_name="queue1") with tf.device("/job:worker/task:0"): add_op0 = tf.add(tf.ones(()), tf.ones(())) with tf.device("/job:worker/task:1"): add_op1 = tf.add(tf.ones(()), tf.ones(())) print("Running computation on server 0") print(sess.run(add_op0)) print("Running computation on server 1") print(sess.run(add_op1)) print("Bringing down server 0") sess.run(queue0.enqueue(1)) print("Bringing down server 1") sess.run(queue1.enqueue(1)) else: # Launch TensorFlow server server = tf.train.Server(clusterspec, config=None, job_name="worker", task_index=int(FLAGS.task)) print("Starting server "+FLAGS.task) sess = tf.Session(server.target) queue = tf.FIFOQueue(1, tf.int32, shared_name="queue"+FLAGS.task) sess.run(queue.dequeue()) print("Terminating server"+FLAGS.task)
gRPC
39,810,356
12
While using Cloud Functions, we've encountered the following error: Timestamp: 2023-10-21 18:50:18.281 EEST Function: v8-specialist ---updateUserByID finish update--- Caused by: Error at WriteBatch.commit (/workspace/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/write-batch.js:433:23) at DocumentReference.update (/workspace/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/reference.js:433:14) at Object.updateUserByID (/workspace/dist/src/DB/db.js:74:14) at createSpecialistOrderListService (/workspace/dist/src/crud/specialist/services/specialistList/createSpecialistOrderListService.js:38:29) at runMicrotasks (<anonymous>) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async getRecommendedSpecialistsListController (/workspace/dist/src/crud/specialist/controllers/getRecommendedSpecialistsListController.js:25:44) at async /workspace/dist/src/framework/express/middlewares/express-handler.js:18:36 Error Details: - Code: `13` - Description: `Received RST_STREAM with code 1` - Metadata: `{ internalRepr: Map(0) {}, options: {} }` - Note: `Exception occurred in retry method that was not classified as transient` This error seems to pop up when we execute the following command in our update function: const writeResult = await admin .firestore() .collection(FirestoreCollections.Users) .doc(userID) .update(fieldsToUpdate); Example of fieldsToUpdate: [ { "boolean": true, "number": 100, "id": "some_id" } ] However, what's puzzling is that this method seems to work flawlessly in our other cloud functions. In certain situations, even if an error is thrown during the update, the data in Firestore might still get updated. The issue persists even when tested locally. Upon creating a new cloud function with the same method, everything operates smoothly.
I had the same problem last week and it seems to be something inside firebase / grpc implementation related to long time delays between firebase calls. Also, firebase library seems to be moving away from RPC but it still keeps it as a default option if you don't set preferRest: true (see docs) For me it works when I call init right before performing an operation or changing firebase config to prefer using rest comunication. Here is my code snipet: function getFbDb() { const mainFirebaseApp = firebaseAdmin.initializeApp({ credential: firebaseAdmin.credential.applicationDefault() }, uuid.v4()); const db = mainFirebaseApp.firestore(); const settings = { preferRest: true, timestampsInSnapshots: true }; db.settings(settings); return { db, firebaseApp: mainFirebaseApp }; } const { db, firebaseApp } = getFbDb(); Use const { db, firebaseApp } = getFbDb(); everytime you have to execute an operation. Another "dirty option" seems to be using a retry approach after the first fail. If this doesn't work for you keep an eye on issue 2345 and see what comes up from there.
gRPC
77,337,076
11
I am trying to make an application using python and gRPC as shown in this article - link I am able to run the app successfully on my terminal but to run with a frontend I need to run it as a flask app, codebase. And I am doing all this in a virtual environment. when I run my flask command FLASK_APP=marketplace.py flask run This is the error I get ImportError: cannot import name 'soft_unicode' from 'markupsafe' (/Users/alex/Desktop/coding/virt/lib/python3.8/site-packages/markupsafe/__init__.py) On researching about this error I found this link - it basically tells us that currently I am using a higher version of MarkUpSafe library than required. So I did pip freeze --local inside the virtualenv and got MarkUpSafe version to be MarkupSafe==2.1.0 I think if I change the version of this library from 2.1.0 to 2.0.1 then the flask app might run. How can I change this library's version from the terminal? PS: If you think changing the version of the library won't help in running the flask app, please let me know what else can I try in this.
If downgrading will solve the issue for you try the following code inside your virtual environment. pip install MarkupSafe==2.0.1
gRPC
71,271,759
11
I'm doing load tests between services implemented in Node.JS, both services on the same machine connected through localhost. There are REST and gRPC client & server files. The main goal is to prove that gRPC is faster than an HTTP call because the use of HTTP/2, the use of protocol buffers that are more efficient than code/decode JSON... But in my tests (sending an integer array) gRPC is so much slower. The code is very simple for boths implementations, I have an auxiliar class to generate objects with sizes (in MB): 0.125, 0.25, 0.5, 1, 2, 5, 20. REST and gRPC server uses this auxiliar class so the object to send is the same. The object send in the payload is like this: { message: "Hello world", array: [] } Where the array is filled with numbers until get the desired size. And my .proto is like this: syntax = "proto3"; service ExampleService { rpc GetExample (Size) returns (Example) {} } message Size { int32 size = 1; } message Example { string message = 1; repeated int32 array = 2; } Also I've running the application measuring only one call, to not create a loop and find the average, and also to not handle measuring time with callbacks. So I'm running the application 10 times and calculating the average. REST server: app.get('/:size',(req,res) => { const size = req.params.size res.status(200).send(objects[size]) }) REST client: const start = performance.now() const response = await axios.get(`http://localhost:8080/${size}`) const end = performance.now() gRPC server: getExample:(call, callback) => { callback(null, objects.objects[call.request.size]) } And gRPC client: const start = performance.now() client.getExample({ size: size }, (error, response) => { const end = performance.now() }) To do more efficently I have tried: Compress data like this: let server = new grpc.Server({ 'grpc.default_compression_level': 3, // (1->Low -- 3->High) }); I know I can use streaming to get data and iterate over the array but I want to prove the "same call" in both methods. And the difference is so big. Other thing I've seen is that times using REST way are more "lineal" the difference between times is small, but using gRPC one call sending 2MB can be 220ms and the next one 500ms. Here is the final comparision, as you can see the difference is considerably big. Data: Size (MB) REST (ms) gRPC (ms) 0,125 37.98976998329162 35.5489800453186 0,25 40.03781998157501 46.077759981155396 0,5 51.35283002853394 59.37109994888306 1 63.4725800037384 166.7616500457128 2 95.76031665007274 394.2442199707031 5 261.9365399837494 804.1371199131012 20 713.1867599964141 5492.330539941788 But I thought... maybe the array field can't be decode in an efficient way, maybe is the integer number which is not heavy for JSON... I don't know, so I'm going to try to send a string, a very huge large string. So my proto file now looks like this: syntax = "proto3"; service ExampleService { rpc GetExample (Size) returns (Example) {} } message Size { int32 size = 1; } message Example { string message = 1; string array = 2; } Now the object send is like this: { message: "Hello world", array: "text to reach the desired MB" } And results are so differents, now gRPC is much more efficient. Data: Size (MB) REST (ms) gRPC (ms) 0,125 30.672580003738403 25.028959941864013 0,25 33.568540048599246 25.366739988327026 0,5 37.19938006401062 27.539460039138795 1 46.4020166794459 28.798949996630352 2 57.50188330809275 35.45066670576731 5 107.39933327833812 48.90079998970032 20 313.4138665994008 136.4138500293096 And the question: So, why sending an integer array is not as efficient as sending an string? Is the way protobuf encode/decode arrays? Is not efficient send repeated values? Is related with the language (JS)?
The reason gRPC -- well, really protobufs -- doesn’t scale well in your example is that every entry of your repeated field results in protobuf needing to decode a separate field, and there is overhead related to that. You can see more details about the encoding of repeated fields in the docs here. You're using proto3, so at least you don't need to specify the [packed=true] option, although that helps somewhat if you're on proto2. The reason switching to a string or bytes field speeds it up so much is that there is only a constant decoding cost for this field which doesn't scale with the amount of data that's encoded in the field (not sure about JS though, which might need to create a copy of the data, but clearly that is still much faster than actually parsing the data). Just make sure your protocol defines what format / endianness the data in the field is :-) Answering your question at a higher level, sending multiple megabytes in a single API call is usually not an amazing idea anyway -- it ties up a thread on both the server and client for a long time which forces you to use multithreading or async code to get reasonable performance. (Admittedly might be less of an issue since you are used to writing async stuff on Node, but there's still only so many CPUs to burn on the server.) Depending on what you're actually trying to do, a common pattern can be to write the data to a file in a shared storage system (S3, etc.) and pass the filename to the other service, which can then download it when it's actually needed.
gRPC
69,889,439
11
I've tried to define a gRPC service where client can subscribe to receive broadcasted messages and they can also send them. syntax = "proto3"; package Messenger; service MessengerService { rpc SubscribeForMessages(User) returns (stream Message) {} rpc SendMessage(Message) returns (Close) {} } message User { string displayName = 1; } message Message { User from = 1; string message = 2; } message Close {} My idea was that when a client requests to subscribe to the messages, the response stream would be added to a collection of response streams, and when a message is sent, the message is sent through all the response streams. However, when my server attempts to write to the response streams, I get an exception System.InvalidOperationException: 'Response stream has already been completed.' Is there any way to tell the server to keep the streams open so that new messages can be sent through them? Or is this not something that gRPC was designed for and a different technology should be used? The end goal service would be allows multiple types of subscriptions (could be to new messages, weather updates, etc...) through different clients written in different languages (C#, Java, etc...). The different languages part is mainly the reason I chose gRPC to try this, although I intend on writing the server in C#. Implementation example using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Messenger; namespace SimpleGrpcTestStream { /* Dependencies Install-Package Google.Protobuf Install-Package Grpc Install-Package Grpc.Tools Install-Package System.Interactive.Async Install-Package System.Linq.Async */ internal static class Program { private static void Main() { var messengerServer = new MessengerServer(); messengerServer.Start(); var channel = Common.GetNewInsecureChannel(); var client = new MessengerService.MessengerServiceClient(channel); var clientUser = Common.GetUser("Client"); var otherUser = Common.GetUser("Other"); var cancelClientSubscription = AddCancellableMessageSubscription(client, clientUser); var cancelOtherSubscription = AddCancellableMessageSubscription(client, otherUser); client.SendMessage(new Message { From = clientUser, Message_ = "Hello" }); client.SendMessage(new Message { From = otherUser, Message_ = "World" }); client.SendMessage(new Message { From = clientUser, Message_ = "Whoop" }); cancelClientSubscription.Cancel(); cancelOtherSubscription.Cancel(); channel.ShutdownAsync().Wait(); messengerServer.ShutDown().Wait(); } private static CancellationTokenSource AddCancellableMessageSubscription( MessengerService.MessengerServiceClient client, User user) { var cancelMessageSubscription = new CancellationTokenSource(); var messages = client.SubscribeForMessages(user); var messageSubscription = messages .ResponseStream .ToAsyncEnumerable() .Finally(() => messages.Dispose()); messageSubscription.ForEachAsync( message => Console.WriteLine($"New Message: {message.Message_}"), cancelMessageSubscription.Token); return cancelMessageSubscription; } } public static class Common { private const int Port = 50051; private const string Host = "localhost"; private static readonly string ChannelAddress = $"{Host}:{Port}"; public static User GetUser(string name) => new User { DisplayName = name }; public static readonly User ServerUser = GetUser("Server"); public static readonly Close EmptyClose = new Close(); public static Channel GetNewInsecureChannel() => new Channel(ChannelAddress, ChannelCredentials.Insecure); public static ServerPort GetNewInsecureServerPort() => new ServerPort(Host, Port, ServerCredentials.Insecure); } public sealed class MessengerServer : MessengerService.MessengerServiceBase { private readonly Server _server; public MessengerServer() { _server = new Server { Ports = { Common.GetNewInsecureServerPort() }, Services = { MessengerService.BindService(this) }, }; } public void Start() { _server.Start(); } public async Task ShutDown() { await _server.ShutdownAsync().ConfigureAwait(false); } private readonly ConcurrentDictionary<User, IServerStreamWriter<Message>> _messageSubscriptions = new ConcurrentDictionary<User, IServerStreamWriter<Message>>(); public override async Task<Close> SendMessage(Message request, ServerCallContext context) { await Task.Run(() => { foreach (var (_, messageStream) in _messageSubscriptions) { messageStream.WriteAsync(request); } }).ConfigureAwait(false); return await Task.FromResult(Common.EmptyClose).ConfigureAwait(false); } public override async Task SubscribeForMessages(User request, IServerStreamWriter<Message> responseStream, ServerCallContext context) { await Task.Run(() => { responseStream.WriteAsync(new Message { From = Common.ServerUser, Message_ = $"{request.DisplayName} is listening for messages!", }); _messageSubscriptions.TryAdd(request, responseStream); }).ConfigureAwait(false); } } public static class AsyncStreamReaderExtensions { public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IAsyncStreamReader<T> asyncStreamReader) { if (asyncStreamReader is null) { throw new ArgumentNullException(nameof(asyncStreamReader)); } return new ToAsyncEnumerableEnumerable<T>(asyncStreamReader); } private sealed class ToAsyncEnumerableEnumerable<T> : IAsyncEnumerable<T> { public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) => new ToAsyncEnumerator<T>(_asyncStreamReader, cancellationToken); private readonly IAsyncStreamReader<T> _asyncStreamReader; public ToAsyncEnumerableEnumerable(IAsyncStreamReader<T> asyncStreamReader) { _asyncStreamReader = asyncStreamReader; } private sealed class ToAsyncEnumerator<TEnumerator> : IAsyncEnumerator<TEnumerator> { public TEnumerator Current => _asyncStreamReader.Current; public async ValueTask<bool> MoveNextAsync() => await _asyncStreamReader.MoveNext(_cancellationToken); public ValueTask DisposeAsync() => default; private readonly IAsyncStreamReader<TEnumerator> _asyncStreamReader; private readonly CancellationToken _cancellationToken; public ToAsyncEnumerator(IAsyncStreamReader<TEnumerator> asyncStreamReader, CancellationToken cancellationToken) { _asyncStreamReader = asyncStreamReader; _cancellationToken = cancellationToken; } } } } }
The problem you're experiencing is due to the fact that MessengerServer.SubscribeForMessages returns immediately. Once that method returns, the stream is closed. You'll need an implementation similar to this to keep the stream alive: public class MessengerService : MessengerServiceBase { private static readonly ConcurrentDictionary<User, IServerStreamWriter<Message>> MessageSubscriptions = new Dictionary<User, IServerStreamWriter<Message>>(); public override async Task SubscribeForMessages(User request, IServerStreamWriter<ReferralAssignment> responseStream, ServerCallContext context) { if (!MessageSubscriptions.TryAdd(request)) { // User is already subscribed return; } // Keep the stream open so we can continue writing new Messages as they are pushed while (!context.CancellationToken.IsCancellationRequested) { // Avoid pegging CPU await Task.Delay(100); } // Cancellation was requested, remove the stream from stream map MessageSubscriptions.TryRemove(request); } } As far as unsubscribing / cancellation goes, there are two possible approaches: The client can hold onto a CancellationToken and call Cancel() when it wants to disconnect The server can hold onto a CancellationToken which you would then store along with the IServerStreamWriter in the MessageSubscriptions dictionary via a Tuple or similar. Then, you could introduce an Unsubscribe method on the server which looks up the CancellationToken by User and calls Cancel on it server-side
gRPC
62,436,956
11
When I try to execute docker build -t exampledockeracc/testapp:v1.0.0 . I receive the following error: failed to dial gRPC: unable to upgrade to h2c, received 500, context canceled When i search for the error people come with the solution to restart docker and waite a while before executing but it does not seem to work. I've read something about an OS mismatch between target OS specified in dockerfile and curretnlly running container OS on you machine. I am using windows. This is my dockerfile: ############# ### build ### ############# # base image FROM node:12.2.0 as build # install chrome for protractor tests RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' RUN apt-get update && apt-get install -yq google-chrome-stable # set working directory WORKDIR /app # add `/app/node_modules/.bin` to $PATH ENV PATH /app/node_modules/.bin:$PATH # install and cache app dependencies COPY ./package.json /app/package.json RUN npm install RUN npm install -g @angular/[email protected] # add app COPY . /app # run tests # RUN ng test --watch=false # RUN ng e2e --port 4202 # generate build RUN ng build --output-path=dist --prod="true" ############ ### prod ### ############ # base image FROM nginx:alpine # copy artifact build from the 'build environment' COPY --from=build /app/dist /usr/share/nginx/html COPY --from=build /app/nginx.conf /etc/nginx/conf.d/default.conf # expose port 80 EXPOSE 80 # run nginx CMD ["nginx", "-g", "daemon off;"] It is used for an Angular application.
This issue is caused because you have not let the Docker enough time to load completely. Please wait for some time and try again. Github Issue Link One other reason is OS mismatch. The node image is Linux-based and you are on windows. I would recommend you, get a Linux server or a VM for building the containers.
gRPC
62,261,552
11
I'm trying to establish a connection to an insecure gRPC server. I'm using gRPC for communication between two processes inside of a Docker container, that's why I don't need any encryption or strong authentication. The server behaves as expected and I can do calls using grpcurl like that: grpcurl -plaintext localhost:42652 SomeService.DoSomething Now I'm trying to call the same RPC method from a .Net Core application: // Registration of the DI service services.AddGrpcClient<DaemonService.DaemonServiceClient>(options => { // Enable support for unencrypted HTTP2 AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); options.Address = new Uri("http://localhost:42652"); // Just a test, doesn't change anything. options.ChannelOptionsActions.Add(channelOptions => channelOptions.Credentials = ChannelCredentials.Insecure); }); // Call var reply = _someServiceClient.DoSomething(new Request()); But the call in the last line results in an exception: fail: Grpc.Net.Client.Internal.GrpcCall[6] Error starting gRPC call. System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The response ended prematurely. at System.Net.Http.HttpConnection.FillAsync() at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Grpc.Net.Client.Internal.GrpcCall`2.SendAsync(HttpRequestMessage request) fail: Grpc.Net.Client.Internal.GrpcCall[3] Call failed with gRPC error status. Status code: 'Cancelled', Message: 'Error starting gRPC call.'. fail: SomeNamespace.Session.Program[0] An error occured. System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The response ended prematurely. at System.Net.Http.HttpConnection.FillAsync() at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Grpc.Net.Client.Internal.GrpcCall`2.SendAsync(HttpRequestMessage request) at Grpc.Net.Client.Internal.GrpcCall`2.GetResponseAsync() at Grpc.Net.Client.Internal.HttpClientCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request) at Grpc.Core.Interceptors.InterceptingCallInvoker.<BlockingUnaryCall>b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext`2 ctx) at Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext`2 context, BlockingUnaryCallContinuation`2 continuation) at Grpc.Core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request) at SomeNamespace.RpcServices.DaemonService.DaemonServiceClient.GetVncContainerEnvironment(EmptyRequest request, CallOptions options) in /src/SomeNamespace.RpcServices/obj/Release/netcoreapp3.0/Vnc-container-daemonGrpc.cs:line 98 at SomeNamespace.RpcServices.DaemonService.DaemonServiceClient.GetVncContainerEnvironment(EmptyRequest request, Metadata headers, Nullable`1 deadline, CancellationToken cancellationToken) in /src/SomeNamespace.RpcServices/obj/Release/netcoreapp3.0/Vnc-container-daemonGrpc.cs:line 94 at SomeNamespace.Rpc.RpcEventListener.StartListening() in /src/SomeNamespace/Rpc/RpcEventListener.cs:line 32 Do you have an idea what I've to do different? I cannot find much documentation about establishing insecure connections like that.
I found the fix on my own: It works when I move the AppContext.SetSwitch above the AddGrpcClient. // Enable support for unencrypted HTTP2 AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); // Registration of the DI service services.AddGrpcClient<DaemonService.DaemonServiceClient>(options => { options.Address = new Uri("http://localhost:42652"); options.ChannelOptionsActions.Add(channelOptions => channelOptions.Credentials = ChannelCredentials.Insecure); });
gRPC
58,052,596
11
I am having issues building the grpc cpp helloworld example with cmake. I built and installed grpc with cmake initially, and then with make directly. I have found this issue raised by someone else in the past, which was closed as resolved. It does not appear to be resolved and I opened a new issue for it, but I feel it will be some time until I get some help, so here I am. The OP of the original issue offers a workaround with his FindGRPC cmake module, but I am not sure how is this suppose to help if gRPCTargets.cmake is still missing. I dropped FindGRPC.cmake inside my cmake modules path, but nothing changes. The error is this: CMake Error at /usr/local/lib/cmake/grpc/gRPCConfig.cmake:8 (include): include could not find load file: /usr/local/lib/cmake/grpc/gRPCTargets.cmake Call Stack (most recent call first): CMakeLists.txt:73 (find_package) -- Using gRPC 1.20.0 -- Configuring incomplete, errors occurred I want to be able to use grpc from my cmake projects without much hassle (using find_package(gRPC CONFIG REQUIRED)) EDIT: When running cmake on grpc I get this error: gRPC_INSTALL will be forced to FALSE because gRPC_ZLIB_PROVIDER is "module" This is printed from zlib.cmake: message(WARNING "gRPC_INSTALL will be forced to FALSE because gRPC_ZLIB_PROVIDER is \"module\"") Apparently all the providers must be "package" as mentioned in grpc's CMakeLists.txt: set(gRPC_INSTALL ${gRPC_INSTALL_default} CACHE BOOL "Generate installation target: gRPC_ZLIB_PROVIDER, gRPC_CARES_PROVIDER, gRPC_SSL_PROVIDER and gRPC_PROTOBUF_PROVIDER must all be \"package\"") I am not sure why zlib is a module here though, or how to make it a package. Do I need to somehow specify to cmake to use the installed zlib instead of the submodule one?
The cause of this problem is explained at https://github.com/grpc/grpc/issues/13841: Because of some limitations of our current CMakeLists.txt, the install targets (see gRPC_INSTALL option) will only be generated if you are building using a pre-installed version of our dependencies (gRPC_CARES_PROVIDER in your case needs to be set to package). The warning you saw "gRPC_INSTALL will be forced to FALSE because gRPC_CARES_PROVIDER" is "module" basically tells you that even though gRPC_INSTALL was set to ON by you, we're setting it back to OFF because your gRPC_CARES_PROVIDER is set to use c-ares from git submodule (which wouldn't work well with the current CMakeLists.txt) - so you shouldn't expect anything to be installed (not even grpc_cpp_plugin. To fix this issue, you should carefully look at the output when invoking cmake. For every gRPC_*_PROVIDER that is reported as "module", you should force it to "package" with -DgRPC_CARES_PROVIDER=package (make sure to install the package as well, then!) Or just force everything with the command-line linked in the issue: cmake -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF -DgRPC_PROTOBUF_PROVIDER=package -DgRPC_ZLIB_PROVIDER=package -DgRPC_CARES_PROVIDER=package -DgRPC_SSL_PROVIDER=package -DCMAKE_BUILD_TYPE=Release ../..
gRPC
57,413,975
11
I am relatively new to GRPC and want to be sure that I am doing connection management correctly with golang. I don't want to have to create a new connection for every call but I also don't want to create bottlenecks as I scale. What I did was to create a single connection in the init function: var userConn *grpc.ClientConn var userServiceName string func init() { userServiceName := os.Getenv("USER_SERVICE_URL") if userServiceName == "" { userServiceName = "localhost" } logging.LogDebug("userClient: Connecting to: "+userServiceName, "") tempConn, err := grpc.Dial(userServiceName, grpc.WithInsecure()) if err != nil { logging.LogEmergency("account_user_client.Init() Could not get the connection. "+err.Error(), "") return } userConn = tempConn } And then for each function I will use that connection to create a Client: c := user.NewUserClient(userConn) // Contact the server and print out its response. ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() r, err := c.GetUserFromTokenID(ctx, &user.GetUserFromTokenRequest{TransactionID: transactionID, OathToken: *oathToken}) //Handle Error and Response is this an acceptable way to handle grpc connections? Any recommendations on better ways? Thank you very much.
Yes, it's fine to have single GRPC client connection per service. Moreover, I don't see any other options here. GRPC does all the heavy lifting under the hood: for example, you don't need to write your own client connection pool (as you would do for a typical RDBMS), because it won't provide better results than a single GRPC connection. However I would suggest you to avoid using global variables and init functions, especially for networking setup. Also you don't need to create GRPC client (c := user.NewUserClient(userConn)) every time you post a request to the GRPC service: this is just an extra work for garbage collector, you can create the only instance of client at the time of application startup. Update Assuming that you're writing server application (because it can be seen from the method you call on the remote GRPC service), you can simply define a type that will contain all the objects that have the same lifetime as the whole application itself. According to the tradition, these types are usually called "server context", though it's a little bit confusing because Go has very important concept of context in its standard library. // this type contains state of the server type serverContext struct { // client to GRPC service userClient user.UserClient // default timeout timeout time.Duration // some other useful objects, like config // or logger (to replace global logging) // (...) } // constructor for server context func newServerContext(endpoint string) (*serverContext, error) { userConn, err := grpc.Dial(endpoint, grpc.WithInsecure()) if err != nil { return nil, err } ctx := &serverContext{ userClient: user.NewUserClient(userConn), timeout: time.Second, } return ctx, nil } type server struct { context *serverContext } func (s *server) Handler(ctx context.Context, request *Request) (*Response, error) { clientCtx, cancel := context.WithTimeout(ctx, time.Second) defer cancel() response, err := c.GetUserFromTokenID( clientCtx, &user.GetUserFromTokenRequest{ TransactionID: transactionID, OathToken: *oathToken, }, ) if err != nil { return nil, err } // ... } func main() { serverCtx, err := newServerContext(os.Getenv("USER_SERVICE_URL")) if err != nil { log.Fatal(err) } s := &server{serverCtx} // listen and serve etc... } Details may change depending on what you're actually working on, but I just wanted to show that it's much more better to encapsulate state of your application in an instance of distinct type instead of infecting global namespace.
gRPC
56,067,076
11
When working with gRPC in C#, asynchronous calls return AsyncUnaryCall<T> (for unary calls - of course, other calls have slightly different return types). However, AsyncUnaryCall<T> does not extend Task<T>. Therefore, common things you would ordinarily do with a Task<T> do not work with AsyncUnaryCall<T>. This includes: specifying the continuation policy (using ConfigureAwait) using helpers like Task.WhenAny and Task.WhenAll The latter is biting me at the moment, since I want to kick off multiple gRPC calls and wait for them all to complete. It seems my only recourse is to write a little helper that awaits for one after the other. Why doesn't AsyncUnaryCall<T> mirror the functionality in Task<T>?
As I said in a comment, whilst it's "Task-like", it actually represents two separate Tasks. If you want to work with the individual Tasks as Tasks, just access the appropriate property (e.g. ResponseHeadersAsync or ResponseAsync). If you have a variable themAll of type List<AsyncUnaryCall<T>> then using WhenAll/WhenAny is easy: await Task.WhenAny(themAll.Select(c=>c.ResponseHeadersAsync)); if you've got useful work you can do when any headers arrive, or await Task.WhenAll(themAll.Select(c=>c.ResponseAsync)); if you can't do anything useful until they're all completed. As two examples. Similarly, you can extract one of these tasks and use it in an await with a ConfigureAwait, if you want to do so.
gRPC
54,684,416
11
If the browser supports http/2, why does grpc-web require envoy proxy? Is it just required for older browsers that do not support http/2?
Answered in https://github.com/grpc/grpc-web/issues/347. For gRPC-Web to work, we need a lot of the underlying transport to be exposed to us but that's not the case currently cross browsers. We cannot leverage the full http2 protocol given the current set of browser APIs.
gRPC
53,051,648
11
The spec for google.protobuf.Empty states: A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. I've been advocating internally to use an empty message wrapper instead, to preserve backwards compatibility. For instance, let's say we have a FooService: service Foo { rpc List(google.protobuf.Empty) returns (ListResponse) {} } message ListResponse { repeated Foo results = 1; } message Foo {...} If in the future we need to add paging to this list request, we'd need to introduce a request wrapper: message ListRequest { int limit = 1; int offset = 2; } and then update the rpc signature: rpc List(ListRequest) returns (ListResponse) {} Is this a backwards-incompatible change, or can the protobuf format handle this gracefully?
The wire format handles this gracefully. However, most code using the gRPC stubs will break as type-safe languages will notice the incompatible types. If you think you may ever need fields, go ahead and make a special message for that case, even if it is empty. If in doubt, do it. If you are confident you will never need any fields (the response message of "delete" is a common example), then using Empty is fine. I mentioned this specific case in my Modifying gRPC Services Over Time talk. Slides and video recording are available.
gRPC
50,993,815
11
I am trying to run the Helloworld example with the client in C# and the server in Python. When I manually start the server and then the client, the client can successfully connect to the server and call the SayHello method. Now, I have configured my IDE (Visual Studio) to start both the client and the server at the same time. The client fails with an RpcException thrown: An unhandled exception of type 'Grpc.Core.RpcException' occurred in mscorlib.dll Additional information: Status(StatusCode=Unavailable, Detail="Connect Failed") at this line: var reply = client.SayHello(new HelloRequest { Name = user }); Question Is there a good way to wait for the connection to be established? Client Code (from grpc/examples) using System; using Grpc.Core; using Helloworld; namespace CSharpClient { class Program { public static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = new Greeter.GreeterClient(channel); String user = "you"; var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + reply.Message); channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
You can use the "WaitForReady" option from the CallOptions (it's off by default) to wait for the server to become available. Using var reply = client.SayHello(new HelloRequest { Name = user }, new CallOptions().WithWaitForReady(true)); will have the desired effect. The option was introduced here: https://github.com/grpc/grpc/pull/8828/files
gRPC
45,547,278
11
I am using Java and Protoc 3.0 compiler and my proto file is mention below. https://github.com/openconfig/public/blob/master/release/models/rpc/openconfig-rpc-api.yang syntax = "proto3"; package Telemetry; // Interface exported by Agent service OpenConfigTelemetry { // Request an inline subscription for data at the specified path. // The device should send telemetry data back on the same // connection as the subscription request. rpc telemetrySubscribe(SubscriptionRequest) returns (stream OpenConfigData) {} // Terminates and removes an exisiting telemetry subscription rpc cancelTelemetrySubscription(CancelSubscriptionRequest) returns (CancelSubscriptionReply) {} // Get the list of current telemetry subscriptions from the // target. This command returns a list of existing subscriptions // not including those that are established via configuration. rpc getTelemetrySubscriptions(GetSubscriptionsRequest) returns (GetSubscriptionsReply) {} // Get Telemetry Agent Operational States rpc getTelemetryOperationalState(GetOperationalStateRequest) returns (GetOperationalStateReply) {} // Return the set of data encodings supported by the device for // telemetry data rpc getDataEncodings(DataEncodingRequest) returns (DataEncodingReply) {} } // Message sent for a telemetry subscription request message SubscriptionRequest { // Data associated with a telemetry subscription SubscriptionInput input = 1; // List of data models paths and filters // which are used in a telemetry operation. repeated Path path_list = 2; // The below configuration is not defined in Openconfig RPC. // It is a proposed extension to configure additional // subscription request features. SubscriptionAdditionalConfig additional_config = 3; } // Data associated with a telemetry subscription message SubscriptionInput { // List of optional collector endpoints to send data for // this subscription. // If no collector destinations are specified, the collector // destination is assumed to be the requester on the rpc channel. repeated Collector collector_list = 1; } // Collector endpoints to send data specified as an ip+port combination. message Collector { // IP address of collector endpoint string address = 1; // Transport protocol port number for the collector destination. uint32 port = 2; } // Data model path message Path { // Data model path of interest // Path specification for elements of OpenConfig data models string path = 1; // Regular expression to be used in filtering state leaves string filter = 2; // If this is set to true, the target device will only send // updates to the collector upon a change in data value bool suppress_unchanged = 3; // Maximum time in ms the target device may go without sending // a message to the collector. If this time expires with // suppress-unchanged set, the target device must send an update // message regardless if the data values have changed. uint32 max_silent_interval = 4; // Time in ms between collection and transmission of the // specified data to the collector platform. The target device // will sample the corresponding data (e.g,. a counter) and // immediately send to the collector destination. // // If sample-frequency is set to 0, then the network device // must emit an update upon every datum change. uint32 sample_frequency = 5; } // Configure subscription request additional features. message SubscriptionAdditionalConfig { // limit the number of records sent in the stream int32 limit_records = 1; // limit the time the stream remains open int32 limit_time_seconds = 2; } // Reply to inline subscription for data at the specified path is done in // two-folds. // 1. Reply data message sent out using out-of-band channel. // 2. Telemetry data send back on the same connection as the // subscription request. // 1. Reply data message sent out using out-of-band channel. message SubscriptionReply { // Response message to a telemetry subscription creation or // get request. SubscriptionResponse response = 1; // List of data models paths and filters // which are used in a telemetry operation. repeated Path path_list = 2; } // Response message to a telemetry subscription creation or get request. message SubscriptionResponse { // Unique id for the subscription on the device. This is // generated by the device and returned in a subscription // request or when listing existing subscriptions uint32 subscription_id = 1; } // 2. Telemetry data send back on the same connection as the // subscription request. message OpenConfigData { // router name:export IP address string system_id = 1; // line card / RE (slot number) uint32 component_id = 2; // PFE (if applicable) uint32 sub_component_id = 3; // Path specification for elements of OpenConfig data models string path = 4; // Sequence number, monotonically increasing for each // system_id, component_id, sub_component_id + path. uint64 sequence_number = 5; // timestamp (milliseconds since epoch) uint64 timestamp = 6; // List of key-value pairs repeated KeyValue kv = 7; } // Simple Key-value, where value could be one of scalar types message KeyValue { // Key string key = 1; // One of possible values oneof value { double double_value = 5; int64 int_value = 6; uint64 uint_value = 7; sint64 sint_value = 8; bool bool_value = 9; string str_value = 10; bytes bytes_value = 11; } } // Message sent for a telemetry subscription cancellation request message CancelSubscriptionRequest { // Subscription identifier as returned by the device when // subscription was requested uint32 subscription_id = 1; } // Reply to telemetry subscription cancellation request message CancelSubscriptionReply { // Return code ReturnCode code = 1; // Return code string string code_str = 2; }; // Result of the operation enum ReturnCode { SUCCESS = 0; NO_SUBSCRIPTION_ENTRY = 1; UNKNOWN_ERROR = 2; } // Message sent for a telemetry get request message GetSubscriptionsRequest { // Subscription identifier as returned by the device when // subscription was requested // --- or --- // 0xFFFFFFFF for all subscription identifiers uint32 subscription_id = 1; } // Reply to telemetry subscription get request message GetSubscriptionsReply { // List of current telemetry subscriptions repeated SubscriptionReply subscription_list = 1; } // Message sent for telemetry agent operational states request message GetOperationalStateRequest { // Per-subscription_id level operational state can be requested. // // Subscription identifier as returned by the device when // subscription was requested // --- or --- // 0xFFFFFFFF for all subscription identifiers including agent-level // operational stats // --- or --- // If subscription_id is not present then sent only agent-level // operational stats uint32 subscription_id = 1; // Control verbosity of the output VerbosityLevel verbosity = 2; } // Verbosity Level enum VerbosityLevel { DETAIL = 0; TERSE = 1; BRIEF = 2; } // Reply to telemetry agent operational states request message GetOperationalStateReply { // List of key-value pairs where // key = operational state definition // value = operational state value repeated KeyValue kv = 1; } // Message sent for a data encoding request message DataEncodingRequest { } // Reply to data encodings supported request message DataEncodingReply { repeated EncodingType encoding_list = 1; } // Encoding Type Supported enum EncodingType { UNDEFINED = 0; XML = 1; JSON_IETF = 2; PROTO3 = 3; } In order to do the service call (rpc TelemetrySubscribe) first i need to read header which have subscription id and then start reading messages. Now, using Java i am able to connect with the service, i did introduce the interceptor but when i print/retrieve header it is null. My code of calling interceptor is below, ClientInterceptor interceptor = new HeaderClientInterceptor(); originChannel = OkHttpChannelBuilder.forAddress(host, port) .usePlaintext(true) .build(); Channel channel = ClientInterceptors.intercept(originChannel, interceptor); telemetryStub = OpenConfigTelemetryGrpc.newStub(channel); This is interceptor code to read meta Data. @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) { @Override public void onHeaders(Metadata headers) { Key<String> CUSTOM_HEADER_KEY = Metadata.Key.of("responseKEY", Metadata.ASCII_STRING_MARSHALLER); System.out.println("Contains Key?? "+headers.containsKey(CUSTOM_HEADER_KEY)); Wondering is there any other way to read meta data or first message which have subscription ID in it? All i need to read first message which have subscription Id, and return the same subscription id to server so that streaming can start I have equivalent Python code using same proto file and it is communicating with server by code mention below for reference only: sub_req = SubscribeRequestMsg("host",port) data_itr = stub.telemetrySubscribe(sub_req, _TIMEOUT_SECONDS) metadata = data_itr.initial_metadata() if metadata[0][0] == "responseKey": metainfo = metadata[0][1] print metainfo subreply = agent_pb2.SubscriptionReply() subreply.SetInParent() google.protobuf.text_format.Merge(metainfo, subreply) if subreply.response.subscription_id: SUB_ID = subreply.response.subscription_id From the python code above i can easily retrieve meta data object, not sure how to retrieve same using Java? After reading metaData all i am getting is: Metadata({content-type=[application/grpc], grpc-encoding=[identity], grpc-accept-encoding=[identity,deflate,gzip]}) But i know there is one more line from meta data to it, which is response { subscription_id: 2 } How can i extract last response from Header which have subscription id in it. I did try many options and i am lost here.
The method you used is for request metadata, not response metadata: public void start(Listener<RespT> responseListener, Metadata headers) { For response metadata, you will need a ClientCall.Listener and wait for the onHeaders callback: public void onHeaders(Metadata headers) I do feel like the usage of metadata you mention seems strange. Metadata is generally for additional error details or cross-cutting features that aren't specific to the RPC method (like auth, tracing, etc.).
gRPC
43,479,217
11
I know there is an example helloworld program in gRPC source. However, being new to this, I don't understand how to write more than one async services in the server. The example here talks about spawning new instances of a class to handle SayHello service calls. How to add new services, for example SayBye, so that I can make calls to it from client? How to make the server identify which service call was made by the client ?
See this thread and the relevant example. The suggestion is to add a bool parameter to CallData (hello_ in this example), instantiate two CallData objects, one with hello_ = true, and one with hello_ = false, and have each one request a different RPC. if (hello_) { service_->RequestSayHello(...); } else { service_->RequestSayBye(...); } For more than two types of calls, you could achieve the same behavior with an enum instead of a bool. A more flexible approach would be to have a different CallData-like class for each RPC. However when you get a tag from cq_->Next(), you know that it is a pointer to an object of one of these classes, but you don't know its exact type. To overcome this, you can have them all inherit from a class with a virtual Proceed() member function, implement it as needed in each subclass, and when you get a tag, cast it as CallData and call Proceed(). class CallData { public: virtual void Proceed() = 0; }; class HelloCallData final : public CallData {...}; class ByeCallData final : public CallData {...}; ... new HelloCallData(...); new ByeCallData(...); cq_->Next(&tag, &ok); static_cast<CallData*>(tag)->Proceed(); ...
gRPC
41,732,884
11
I wonder what is the best practice for protocol buffer regarding source repository (e.g. git) : Do I have to put ONLY the .proto file in the repository and let anyone else who uses the source code to regenerate classes code with protoc compiler ? or is it a best pratice to put both .proto files AND source code generated by protoc compiler ?
You should never check in generated code if you can avoid it. If you check in generated code, you take on multiple risks, such as: You risk losing the knowledge of how to correctly regenerate that code. If it's not automated as part of the build, it's too easy to forget to document, or to have the documentation be wrong. You risk the generated code getting out-of-sync with the schema. For example, someone could make a change to the .proto file but forget to update the generated code. Their changes won't actually "take effect" until someone else later on regenerates the generated code for some other reason -- and then all of the sudden they see side effects they weren't expecting. Your generated code might be for a different version of protocol buffers than what the builder has installed. In this case it won't work correctly, since it's necessary to use the exact same version of the compiler and runtime library. If for some reason you absolutely have to check in generated code, I highly recommend creating an automated test that checks if the checked-in code matches what protoc would generate if run fresh. (For example, the protobuf repository itself contains checked-in copies of generated code for descriptor.proto because this code is needed to compile protoc, creating a circular dependency. But there is a unit test that checks that the checked-in code matches what protoc would generate.)
gRPC
41,186,798
11
Maybe (hopefully) I'm missing something very simple, but I can't seem to figure this out. I have a set of gRPC services that I would like to put behind a nghttpx proxy. For this I need to be able to configure my client with a channel on a non-root url. Eg. channel = grpc.insecure_channel('localhost:50051/myapp') stub = MyAppStub(channel) This wasn't working immediately through the proxy (it just hangs), so I tested with a server on the sub context. server = grpc.server(executor) service_pb2.add_MyAppServicer_to_server( MyAppService(), server) server.add_insecure_port('{}:{}/myapp'.format(hostname, port)) server.start() I get the following E1103 21:00:13.880474000 140735277326336 server_chttp2.c:159] {"created":"@1478203213.880457000","description":"OS Error", "errno":8,"file":"src/core/lib/iomgr/resolve_address_posix.c", "file_line":115,"os_error":"nodename nor servname provided, or not known", "syscall":"getaddrinfo","target_address":"[::]:50051/myapp"} So the question is - is it possible to create gRPC channels on non-root urls?
As confirmed here, this is not possible. I will route traffic via subdomains in nghttpx.
gRPC
40,410,392
11
Given the address of a GRPC service at, say, ipv4:127.0.0.1:25000, are there any standardized queries or tools I can use to discover what GRPC requests the service is capable of receiving? e.g. I'm looking for something like: ./magic-grpc-service-tool 127.0.0.1:25000 > service Greeter { > rpc Greet(HelloMessage) returns (HelloResponse) {} > }
Update: the reflection service is supported across the various languages and grpc CLI is able to consume it. At the moment, no. We will be adding server reflection to the various languages, but the support has to be added to each individually. Once server reflection is supported, the grpc CLI will be enhanced to use it and will be the "standard tool" to use.
gRPC
37,534,274
11
I'm trying to use http2/grpc streaming, but my connection cuts off in 15 seconds. The documentation on the timeout setting says to set the timeout to 0. However when I do this then Envoy throws an error on startup complaining that 0 isn't a valid value for the Duration type. How do I disable the route timeout? Here is my Envoy config .yml admin: access_log_path: "/dev/null" address: socket_address: address: 0.0.0.0 port_value: 8801 static_resources: listeners: - address: socket_address: address: 0.0.0.0 port_value: 11001 filter_chains: - filters: - name: envoy.filters.network.http_connection_manager typed_config: "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager stat_prefix: ingress_http http_filters: - name: envoy.filters.http.router route_config: name: grpc_route virtual_hosts: - name: grpc_service domains: ["*"] routes: - name: grpc_proxy match: prefix: "/" route: timeout: 0 # How do I disable the timeout? auto_host_rewrite: true prefix_rewrite: "/" cluster: grpc clusters: - name: grpc connect_timeout: 0.25s type: STRICT_DNS lb_policy: round_robin http2_protocol_options: {} dns_lookup_family: V4_ONLY load_assignment: cluster_name: grpc endpoints: - lb_endpoints: - endpoint: address: socket_address: address: mygrpcservice port_value: 50061
You almost got it. The only change you need to make is to go from an integer to a duration. So rather than "0", you need to specify "0s" for zero seconds. I verified this by setting timeout: 0s in your config.yaml and everything started up.
gRPC
65,897,760
10
i want return list of Person model to client in grpc.project is asp.net core person.proto code is : syntax = "proto3"; option csharp_namespace = "GrpcService1"; service People { rpc GetPeople (RequestModel) returns (ReplyModel); } message RequestModel { } message ReplyModel { repeated Person person= 1; } message Person { int32 id = 1; string firstName=2; string lastName=3; int32 age=4; } PeopleService.cs code is : using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Grpc.Core; using Microsoft.Extensions.Logging; namespace GrpcService1 { public class PeopleService:People.PeopleBase { private readonly ILogger<GreeterService> _logger; public PeopleService(ILogger<GreeterService> logger) { _logger = logger; } public override async Task<ReplyModel> GetPeople(RequestModel request, ServerCallContext context) { List<Person> people = new List<Person>() { new Person() { Id=1,FirstName="david",LastName="totti",Age=31}, new Person() { Id=2,FirstName="lebron",LastName="maldini",Age=32}, new Person() { Id=3,FirstName="leo",LastName="zidan",Age=33}, new Person() { Id=4,FirstName="bob",LastName="messi",Age=34}, new Person() { Id=5,FirstName="alex",LastName="ronaldo",Age=35}, new Person() { Id=6,FirstName="frank",LastName="fabregas",Age=36} }; ReplyModel replyModel = new ReplyModel(); replyModel.Person = people; //this line is error : Property or indexer 'ReplyModel.Person' cannot be assigned to --it is read only return replyModel; } } } and client project call grpc server : var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new People.PeopleClient(channel); var result= client.GetPeople(new RequestModel(), new Grpc.Core.Metadata()); this work for one model but when want return list of model i can't.how i can send list to client project? thanks for read my problem
change error line (replyModel.Person = people) to this code replyModel.Person.AddRange(people);
gRPC
63,955,514
10
To compile proto files for Python, I could protoc -I=.--python_out=$DST_DIR sommem.proto based on https://developers.google.com/protocol-buffers/docs/pythontutorial or python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. some.proto based on https://grpc.io/docs/languages/python/basics/#generating-client-and-server-code I wonder what's the difference between protoc and python -m grpc_tools.protoc, which one is more recommended for generating python *_pb2.py[i] files? BTW, it looks protoc doesn't support --grpc_python_out.
protoc contains just logic for protocol buffers. That is, it will generate serialization/deserialization code for many languages. It does not, however, generate code for stubs and servers by default. This is left up to separate RPC systems through a system called protoc plugins. Protoc plugins offer a simple interface by which an executable takes a description of a Protocol Buffer on stdin and outputs the corresponding generated code on stdout. Internal to Google, this system is used to generate code for Stubby. Externally, it is used to generate code for gRPC (or any other RPC system that wants to use protocol buffers). Plugins get to register a command line flag for themselves to indicate where protoc should output the generated code. So, in your example above, --python_out indicates where the generated serialization/deserialization code should go, while --grpc_python_out is the flag registered by the gRPC Python code generator, indicating where Python stub and server code should be placed on the filesystem. grpc_tools is a C extension bundling both protoc and the gRPC Python protoc plugin together so that the user doesn't have to deal with downloading protoc, downloading the gRPC Python code generator, and getting the necessary configuration set up to make them work together properly. However, in theory, you should be able to put all these pieces together to make them work just like grpc_tools (though I haven't tried).
gRPC
62,649,353
10
I have a service that transfers messages at a quite high rate. Currently it is served by akka-tcp and it makes 3.5M messages per minute. I decided to give grpc a try. Unfortunately it resulted in much smaller throughput: ~500k messages per minute an even less. Could you please recommend how to optimize it? My setup Hardware: 32 cores, 24Gb heap. grpc version: 1.25.0 Message format and endpoint Message is basically a binary blob. Client streams 100K - 1M and more messages into the same request (asynchronously), server doesn't respond with anything, client uses a no-op observer service MyService { rpc send (stream MyMessage) returns (stream DummyResponse); } message MyMessage { int64 someField = 1; bytes payload = 2; //not huge } message DummyResponse { } Problems: Message rate is low compared to akka implementation. I observe low CPU usage so I suspect that grpc call is actually blocking internally despite it says otherwise. Calling onNext() indeed doesn't return immediately but there is also GC on the table. I tried to spawn more senders to mitigate this issue but didn't get much of improvement. My findings Grpc actually allocates a 8KB byte buffer on each message when serializes it. See the stacktrace: java.lang.Thread.State: BLOCKED (on object monitor) at com.google.common.io.ByteStreams.createBuffer(ByteStreams.java:58) at com.google.common.io.ByteStreams.copy(ByteStreams.java:105) at io.grpc.internal.MessageFramer.writeToOutputStream(MessageFramer.java:274) at io.grpc.internal.MessageFramer.writeKnownLengthUncompressed(MessageFramer.java:230) at io.grpc.internal.MessageFramer.writeUncompressed(MessageFramer.java:168) at io.grpc.internal.MessageFramer.writePayload(MessageFramer.java:141) at io.grpc.internal.AbstractStream.writeMessage(AbstractStream.java:53) at io.grpc.internal.ForwardingClientStream.writeMessage(ForwardingClientStream.java:37) at io.grpc.internal.DelayedStream.writeMessage(DelayedStream.java:252) at io.grpc.internal.ClientCallImpl.sendMessageInternal(ClientCallImpl.java:473) at io.grpc.internal.ClientCallImpl.sendMessage(ClientCallImpl.java:457) at io.grpc.ForwardingClientCall.sendMessage(ForwardingClientCall.java:37) at io.grpc.ForwardingClientCall.sendMessage(ForwardingClientCall.java:37) at io.grpc.stub.ClientCalls$CallToStreamObserverAdapter.onNext(ClientCalls.java:346) Any help with best practices on building high-throughput grpc clients appreciated.
I solved the issue by creating several ManagedChannel instances per destination. Despite articles say that a ManagedChannel can spawn enough connections itself so one instance is enough it's wasn't true in my case. Performance is in parity with akka-tcp implementation.
gRPC
58,764,891
10
I want to use gRPC to expose an interface for bidirectional transfer of large data sets (~100 MB) between two services. Because gRPC imposes a 4 MB message size limit by default, it appears that the preferred way to do this is to manually code streaming of chunks, and re-assemble them at the receiving end [1][2]. However, gRPC also allows increasing the message size limit via grpc.max_receive_message_length and grpc.max_send_message_length, making it possible to directly transmit a message of up to ~2 GB in size, without any manual chunking or streaming. Quick testing indicates that this simpler approach works equally well in terms of performance and throughput, making it seem more desirable for this use case. Assume that the entire data set is needed in memory. Is one of these approaches inherently better than the other? Are there any potential side effects of the simpler non-chunked approach? Can I rely on the MTU-dependent fragmentation at lower layers to be sufficient to avoid network delay and other handicaps? References: Chunking large messages with gRPC Sending files via gRPC
The 4 MB limit is protect clients/servers who haven't thought about message size constraints. gRPC itself is fine with going much higher (100s of MBs), but most applications could be trivially attacked or accidentally go out-of-memory allowing messages of that size. If you're willing to receive a 100 MB message all-at-once, then increasing the limit is fine.
gRPC
58,429,357
10
If I run following these two tests I get the error. 1st test @Rule public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); @Test public void findAll() throws Exception { // Generate a unique in-process server name. String serverName = InProcessServerBuilder.generateName(); // Create a server, add service, start, and register for automatic graceful shutdown. grpcCleanup.register(InProcessServerBuilder .forName(serverName) .directExecutor() .addService(new Data(mockMongoDatabase)) .build() .start()); // Create a client channel and register for automatic graceful shutdown. RoleServiceGrpc.RoleServiceBlockingStub stub = RoleServiceGrpc.newBlockingStub( grpcCleanup.register(InProcessChannelBuilder .forName(serverName) .directExecutor() .build())); RoleOuter.Response response = stub.findAll(Empty.getDefaultInstance()); assertNotNull(response); } 2nd test @Test public void testFindAll() { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8081) .usePlaintext() .build(); RoleServiceGrpc.RoleServiceBlockingStub stub = RoleServiceGrpc.newBlockingStub(channel); RoleOuter.Response response = stub.findAll(Empty.newBuilder().build()); assertNotNull(response); } io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference cleanQueue SEVERE: ~~~ Channel ManagedChannelImpl{logId=1, target=localhost:8081} was not shutdown properly!!! ~~~ Make sure to call shutdown()/shutdownNow() and wait until awaitTermination() returns true. java.lang.RuntimeException: ManagedChannel allocation site at io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference.(ManagedChannelOrphanWrapper.java:94) If I comment out one of them, then no errors, unit tests pass though but the exception is thrown if both are ran together. Edit Based on the suggestion. @Test public void testFindAll() { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8081) .usePlaintext() .build(); RoleServiceGrpc.RoleServiceBlockingStub stub = RoleServiceGrpc.newBlockingStub(channel); RoleOuter.Response response = stub.findAll(Empty.newBuilder().build()); assertNotNull(response); channel.shutdown(); }
Hey I just faced similar issue using Dialogflow V2 Java SDK where I received the error Oct 19, 2019 4:12:23 PM io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference cleanQueue SEVERE: *~*~*~ Channel ManagedChannelImpl{logId=41, target=dialogflow.googleapis.com:443} was not shutdown properly!!! ~*~*~* Make sure to call shutdown()/shutdownNow() and wait until awaitTermination() returns true. Also, Having a huge customer base we started running into out of memory unable to create native thread error. After performing a lot of Debugging operations and Using Visual VM Thread Monitoring I finally figured out that the problem was because of SessionsClient not closing. So I used the attached code block to solve that issue. Post testing that block I was finally able to free up all the used threads and also the error mentioned earlier was resolved. SessionsClient sessionsClient = null; QueryResult queryResult = null; try { SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder(); SessionsSettings sessionsSettings = settingsBuilder .setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build(); sessionsClient = SessionsClient.create(sessionsSettings); SessionName session = SessionName.of(projectId, senderId); com.google.cloud.dialogflow.v2.TextInput.Builder textInput = TextInput.newBuilder().setText(message) .setLanguageCode(languageCode); QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput); queryResult = response.getQueryResult(); } catch (Exception e) { e.printStackTrace(); } finally { sessionsClient.close(); } The shorter values on the graph highlights the use of client.close(). Without that the threads were stuck in Parking State.
gRPC
57,481,760
10
To provide better debugging information for my GRPC server/client setup, I am trying to find an API for grpc.server that allows me to inspect what clients are connected to the server. The most promising question I have found is question, which gives a starting point on how to do this in Java GRPC. However, the Java API doesn't exist in the Python GRPC implementation. So far, I keep track of unique peers using the context.peer() method in a grpc.ServicerContext. If a peer hasn't sent a request in a while (a timeout I set to 2 seconds) I assume the client has disconnected. I've started looking at the python-grpc source code but I haven't made any headway. If anyone knows of a similar API in python I could use, that would be appreciated! Even an internal API would be sufficient for these debugging needs.
There isn't a native API for this, but you have all of the pieces you need. Here's a modified version of the helloworld example from the repo. class PeerSet(object): def __init__(self): self._peers_lock = threading.RLock() self._peers = {} def connect(self, peer): print("Peer {} connecting".format(peer)) with self._peers_lock: if peer not in self._peers: self._peers[peer] = 1 else: self._peers[peer] += 1 def disconnect(self, peer): print("Peer {} disconnecting".format(peer)) with self._peers_lock: if peer not in self._peers: raise RuntimeError("Tried to disconnect peer '{}' but it was never connected.".format(peer)) self._peers[peer] -= 1 if self._peers[peer] == 0: del self._peers[peer] def peers(self): with self._peers_lock: return self._peers.keys() class Greeter(helloworld_pb2_grpc.GreeterServicer): def __init__(self): self._peer_set = PeerSet() def _record_peer(self, context): def _unregister_peer(): self._peer_set.disconnect(context.peer()) context.add_callback(_unregister_peer) self._peer_set.connect(context.peer()) def SayHello(self, request, context): self._record_peer(context) for i in range(10): print("[thread {}] Peers: {}".format(threading.currentThread().ident, self._peer_set.peers())) time.sleep(1) return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) This will get you output like the following: [thread 139905506195200] Peers: [u'ipv6:[::1]:57940', u'ipv6:[::1]:57930', u'ipv6:[::1]:57926', u'ipv6:[::1]:57920', u'ipv6:[::1]:57934'] As Ding commented above, channelz may also be a good fit for you.
gRPC
57,228,886
10
Will gRPC support in Python allow me to implement a server that listens on a Unix domain socket (as opposed to a port)? I am using Python 3.5.3 and grpcio/grpcio-tools 1.18.0. So far, I have not been able to find any relevant example nor direct evidence. The official examples use server.add_insecure_port('[::]:50051'), and its not clear how a socket could fit there.
Apparently add_insecure_port(address) accepts Unix domain sockets in the format unix:///var/run/test.sock after all. More details: https://github.com/grpc/grpc/blob/master/doc/naming.md
gRPC
54,844,882
10
What is the difference between thread safe and thread compatible? What thread compatible mean? What is use cases for thread compatible? UPD: I have found this definition in the grpc documentation of StreamObserver. Also, I have found the link to Characterizing thread safety but its still not clear for me. If a method requires to be in synchronize block, that means that is just threaded unsafe?
Thread safe means that an object can be used by many threads concurrently and still be correct 1 Thread hostile means that the object does something (mutates static state, thread local storage etc.) that prevents it from being thread safe. Thread compatible means not thread safe, but not thread hostile - so to satisfy thread safety, the user must perform synchronization themselves 1 But the definition of correctness varies a little... Java In Theory And In Practice defines this according to the class's specification. Geoff Romer at Google and Wikipedia define this as simply lack of data races. I usually hope this to mean no crashes, deadlocks or other surprises.
gRPC
52,714,494
10
I am building a client/server system in go, using gRPC and protobuf (and with a gRPC gateway to REST). I use metadata in the context on the server side to carry authentication data from the client, and that works perfectly well. Now, I'd like the server to set some metadata keys/values so that the client can get them, alongside with the response. How can I do that? Using SetHeader and SendHeader? Ideally, I'd like every single response from the server to integrate that metadata (can be seen as some kind of UnaryInterceptor, but on the response rather than the request?) Here is the code for the server and for the client.
I finally found my way: https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md So basically, grpc.SetHeader() + grpc.SendHeader() and grpc.SetTrailer() are totally what I was looking for. On the client side, grpc.Header() and grpc.Trailer() functions need to be passed to the RPC call, and their argument is a metadata.MD object to be filled. On the client side, define your receiving metadata: var header, trailer metadata.MD Then, pass it to the SomeRPCCall() unary RPC: response, err := client.SomeRPCCall( context.Background(), proto.MyMessage{}, grpc.Header(&header), grpc.Trailer(&trailer), ) And now, you can check what's in your metadata: for key, value := range header { fmt.Printf("%s => %s", key, value) } for key, value := range trailer { fmt.Printf("%s => %s", key, value) } On the server side, you can: force the data to be sent right after the RPC is received (but before it's processed): grpc.SendHeader(ctx, metadata.New(map[string]string{"my-key": "my-value"})) or set & send the metadata at the end of the RPC process (along with the Status): grpc.SetTrailer(ctx, metadata.New(map[string]string{"my-key": "my-value"}))
gRPC
47,599,509
10
Was wondering if anybody has tried to use jmeter to test gRPC application. I was hoping that I could write a gRPC client class with a non-blocking/asynchronous stub that makes non-blocking calls to the server, Create a Jar of the above client Import the Jar to JMeter Use the Java method in Jmeter BeanShell sampler before investing time in trying the above I wanted to see if any body has tried something similar and if above workaround work? will each thread create a separate TCP connection? We have tried the load test with python client and locust.io but python gRPC is not gevent compatible and even with async call e.g. stub.GetFeature.future, we are hitting a limit on the request per second per process (async call doesn't seem to be async, GIL bottleneck, once TCP stream) SOLUTION: Have a look at https://github.com/whatalokation/whatalokation-grpc-client Readme.md should be self explanatory
if above workaround work? Your solution will work. But if you need it long term, I would recommend, rather than having client class and using BeanShell sampler, implementing custom Java Sampler. It's very practical, since work-wise it will be similar/same as implementing custom client + BeanShell sampler script, but Java sampler is typically more efficient than BeanShell sampler, and maintainability of such solution will be better (you won't have 2 co-dependent components to maintain). A more fancy option is to create your own JMeter Plug-in (the link I provide here is old, and not very accurate, but it's a good starting point). This is quite an investment, but might be worth it eventually if you find that a simpler solution generally works, but has some major limitations, or you need higher level of configurability and control. will each thread create a separate TCP connection? Each thread runs independently, but whether each thread will have its own connection will depend on how you implemented them. In straight forward implementation (where sampler creates and destroys connection), each thread will have a separate TCP connection. But JMeter has properties shared among threads, which, among the rest, can contain objects. So you could share a connection between threads that way. Or you can implement configuration element, which could hold a connection pool, shared by all threads.
gRPC
43,018,472
10
For some background, I am attempting to use grpc auth in order to provide security for some services I am defining. Let's see if I can ask this is a way that makes sense. For my python code, it was pretty easy to implement the server side code. class TestServiceServer(service_pb2.TestServiceServer): def TestHello(self, request, context): ## credential metadata for the incoming request metadata = context.invocation_metadata() ## authenticate the user using the metadata So, as you can tell, I am able to get the metadata from "context" quite easily. What is harder for me is to do the same thing in java. public class TestImpl extends TestServiceGrpc.TestServiceImplBase { @Override public void testHello(TestRequest req, StreamObserver<TestResponse> responseObserver) { // How do I get access to similar request metadata here? // from the parameter positions, it looks like it should be // "responseObserver" but that doesn't seem similar to "context" } } I'll admit my problem comes from a few directions. 1) I am not well versed in Java 2) I heavily used python's "pdb" in order to debug the classes and see what methods are available to me. I don't know of/am not proficient at a similar tool for java. 3) The documentation seems rather sparse at this point. It shows you how to set up an ssl connection on the server side, but I can't find an example of the server taking a look at request metadata, as I have shown in python. Could someone please give me an idea of how to do this, or perhaps show me a useful debugging tool for java in the same vein of python's pdb? EDIT/ANSWER : I needed to first write a definition implementing the interface ServerInterceptor. private class TestInterceptor implements ServerInterceptor { .... Then, before actually binding my service and building my server, I needed to do this. TestImpl service = new TestImpl(); ServerServiceDefinition intercepted = ServerInterceptors.intercept(service, new TestInterceptor()); Now I was able to create the server. server = NettyServerBuilder.forPort(port) // enable tls .useTransportSecurity( new File(serverCert), new File(serverKey) ) .addService( intercepted // had been "new TestImpl()" ) .build(); server.start(); This allowed my ServerInterceptor to actually be called when I fired off a client side request. This link was quite helpful in figuring this out.
Use a ServerInterceptor and then propagate the identity via Context. This allows you to have a central policy for authentication. The interceptor can retrieve the identity from Metadata headers. It should then validate the identity. The validated identity can then be communicated to the application (i.e., testHello) via io.grpc.Context: /** Interceptor that validates user's identity. */ class MyAuthInterceptor implements ServerInterceptor { public static final Context.Key<Object> USER_IDENTITY = Context.key("identity"); // "identity" is just for debugging @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { // You need to implement validateIdentity Object identity = validateIdentity(headers); if (identity == null) { // this is optional, depending on your needs // Assume user not authenticated call.close(Status.UNAUTENTICATED.withDescription("some more info"), new Metadata()); return new ServerCall.Listener() {}; } Context context = Context.current().withValue(USER_IDENTITY, identity); return Contexts.interceptCall(context, call, headers, next); } } public class TestImpl extends TestServiceGrpc.TestServiceImplBase { @Override public void testHello(TestRequest req, StreamObserver<TestResponse> responseObserver) { // Access to identity. Object identity = MyAuthInterceptor.USER_IDENTITY.get(); ... } } // Need to use ServerInterceptors to enable the interceptor Server server = ServerBuilder.forPort(PORT) .addService(ServerInterceptors.intercept(new TestImpl(), new MyAuthInterceptor())) .build() .start();
gRPC
40,112,374
10
Does anyone know how to compile *.proto files for grpc application in maven? This is how I'm compiling protobuf in maven - (old way, using installed protoc compiler, excerpt from pom.xml): <build> <plugins> <!-- protocol buffers runner, requires protoc --> <plugin> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <id>generate-protobuf-sources</id> <phase>generate-sources</phase> <configuration> <tasks> <mkdir dir="target/generated-sources/java" /> <exec executable="protoc"> <arg value="--java_out=target/generated-sources/java" /> <arg value="src/main/protobuf/hello.proto" /> </exec> </tasks> <sourceRoot>target/generated-sources/java</sourceRoot> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> </build> I wonder if something similar is possible for grpc. From what I understand I need to somehow connect protoc-gen-grpc-java plugin with protobuf, but I'm not sure how to do that. UPDATE: For those who interested I created a fully working example of client-server app using maven on github.
I'd highly recommend using protobuf-maven-plugin as described in the grpc-java README. If you really want to do it manually, you can download protoc-gen-grpc-java from Maven Central and add another <arg> for the exec of protoc: --plugin=protoc-gen-grpc-java=path/to/protoc-gen-grpc-java
gRPC
35,934,276
10
As the question says, I compiled grpc from source and also did sudo pip install grpcio, however, the which grpc_python_plugin doesn't return anything. This is a problem because the grpc python example for route_guide requires me to run protoc -I . --python_out=. --grpc_out=. --plugin=protoc-gen-grpc='which grpc_python_plugin' ./route_guide.proto in order to generate the python stubs. Since, which grpc_python_plugin doesn't return anything, I get the following error: : program not found or is not executable --grpc_out: protoc-gen-grpc: Plugin failed with status code 1. If I shorten the command I'm trying to run to:protoc -I . --python_out=. ./route_guide.proto, it generates the route_guide_pb2.py file but without the Servicer and Stub classes, and server and stub methods. Ofc, these methods are necessary if one wants to use grpc for any purpose. Any help would be appreciated.
python -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. my_proto.proto Edited: Apparently, there is open Issue on gRPC github site regarding this problem. Protoc seems to have a compatibility issue with grpc_python_plugin? I solved this problem by installing grpc_tools, then used grpc_tools.protoc instead of protoc. $ pip install grpcio-tools $ pip install googleapis-common-protos Useful python tutorial: https://grpc.io/docs/tutorials/basic/python.html See Protoc Issues [791 and 4961]: https://github.com/google/protobuf/issues/791 https://github.com/grpc/grpc/issues/4961
gRPC
34,713,861
10
I'm writing an opencv program and I found a script on another stackoverflow question: Computer Vision: Masking a human hand When I run the scripted answer, I get the following error: Traceback (most recent call last): File "skinimagecontour.py", line 13, in <module> contours, _ = cv2.findContours(skin_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) ValueError: too many values to unpack The code: import sys import numpy import cv2 im = cv2.imread('Photos/test.jpg') im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2YCR_CB) skin_ycrcb_mint = numpy.array((0, 133, 77)) skin_ycrcb_maxt = numpy.array((255, 173, 127)) skin_ycrcb = cv2.inRange(im_ycrcb, skin_ycrcb_mint, skin_ycrcb_maxt) cv2.imwrite('Photos/output2.jpg', skin_ycrcb) # Second image contours, _ = cv2.findContours(skin_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for i, c in enumerate(contours): area = cv2.contourArea(c) if area > 1000: cv2.drawContours(im, contours, i, (255, 0, 0), 3) cv2.imwrite('Photos/output3.jpg', im) Any help is appreciated!
I got the answer from the OpenCV Stack Exchange site. Answer THE ANSWER: I bet you are using the current OpenCV's master branch: here the return statements have changed, see http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours. Thus, change the corresponding line to read: _, contours, _= cv2.findContours(skin_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) Or: since the current trunk is still not stable and you probably will run in some more problems, you may want to use OpenCV's current stable version 2.4.9.
Contour
25,504,964
88
My simple Python code is this import cv2 img=cv2.imread('Materials/shapes.png') blur=cv2.GaussianBlur(img,(3,3),0) gray=cv2.cvtColor(blur,cv2.COLOR_BGR2GRAY) returns,thresh=cv2.threshold(gray,80,255,cv2.THRESH_BINARY) ret,contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: area=cv2.contourArea(cnt) #contour area if (area>1220): cv2.drawContours(img,[cnt],-1,(0,255,0),2) cv2.imshow('RGB',img) cv2.waitKey(1000) print(len(cnt)) import numpy as np contours=np.array(contours) print(contours) This worked fine. But recently without me even making any changes. This was throwed to me ret,contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) ValueError: not enough values to unpack (expected 3, got 2)
the function cv2.findContours() has been changed to return only the contours and the hierarchy and not ret you should change it to: contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
Contour
54,164,630
66
I would like to get data from a single contour of evenly spaced 2D data (an image-like data). Based on the example found in a similar question: How can I get the (x,y) values of the line that is ploted by a contour plot (matplotlib)? >>> import matplotlib.pyplot as plt >>> x = [1,2,3,4] >>> y = [1,2,3,4] >>> m = [[15,14,13,12],[14,12,10,8],[13,10,7,4],[12,8,4,0]] >>> cs = plt.contour(x,y,m, [9.5]) >>> cs.collections[0].get_paths() The result of this call into cs.collections[0].get_paths() is: [Path([[ 4. 1.625 ] [ 3.25 2. ] [ 3. 2.16666667] [ 2.16666667 3. ] [ 2. 3.25 ] [ 1.625 4. ]], None)] Based on the plots, this result makes sense and appears to be collection of (y,x) pairs for the contour line. Other than manually looping over this return value, extracting the coordinates and assembling arrays for the line, are there better ways to get data back from a matplotlib.path object? Are there pitfalls to be aware of when extracting data from a matplotlib.path? Alternatively, are there alternatives within matplotlib or better yet numpy/scipy to do a similar thing? Ideal thing would be to get a high resolution vector of (x,y) pairs describing the line, which could be used for further analysis, as in general my datasets are not a small or simple as the example above.
For a given path, you can get the points like this: p = cs.collections[0].get_paths()[0] v = p.vertices x = v[:,0] y = v[:,1]
Contour
5,666,056
62
Im trying to get the largest contour of a red book. I've got a little problem with the code because its getting the contours of the smallest objects (blobs) instead of the largest one and I can't seem to figure out why this is happening The code I use: camera = cv2.VideoCapture(0) kernel = np.ones((2,2),np.uint8) while True: #Loading Camera ret, frame = camera.read() blurred = cv2.pyrMeanShiftFiltering(frame, 3, 3) hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) lower_range = np.array([150, 10, 10]) upper_range = np.array([180, 255, 255]) mask = cv2.inRange(hsv, lower_range, upper_range) dilation = cv2.dilate(mask,kernel,iterations = 1) closing = cv2.morphologyEx(dilation, cv2.MORPH_GRADIENT, kernel) closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel) #Getting the edge of morphology edge = cv2.Canny(closing, 175, 175) _, contours,hierarchy = cv2.findContours(edge, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find the index of the largest contour areas = [cv2.contourArea(c) for c in contours] max_index = np.argmax(areas) cnt=contours[max_index] x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow('threshold', frame) cv2.imshow('edge', edge) if cv2.waitKey(1) == 27: break camera.release() cv2.destroyAllWindows() As you can see on this picture Hopefully there is someone who can help
You can start by defining a mask in the range of the red tones of the book you are looking for. Then you can just find the contour with the biggest area and draw the rectangular shape of the book. import numpy as np import cv2 # load the image image = cv2.imread("path_to_your_image.png", 1) # red color boundaries [B, G, R] lower = [1, 0, 20] upper = [60, 40, 220] # create NumPy arrays from the boundaries lower = np.array(lower, dtype="uint8") upper = np.array(upper, dtype="uint8") # find the colors within the specified boundaries and apply # the mask mask = cv2.inRange(image, lower, upper) output = cv2.bitwise_and(image, image, mask=mask) ret,thresh = cv2.threshold(mask, 40, 255, 0) if (cv2.__version__[0] > 3): contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) else: im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) if len(contours) != 0: # draw in blue the contours that were founded cv2.drawContours(output, contours, -1, 255, 3) # find the biggest countour (c) by the area c = max(contours, key = cv2.contourArea) x,y,w,h = cv2.boundingRect(c) # draw the biggest contour (c) in green cv2.rectangle(output,(x,y),(x+w,y+h),(0,255,0),2) # show the images cv2.imshow("Result", np.hstack([image, output])) cv2.waitKey(0) Using your image: If you want the book to rotate you can use rect = cv2.minAreaRect(cnt) as you can find it here. Edit: You should also consider other colour spaces beside the RGB, as the HSV or HLS. Usually, people use the HSV since the H channel stays fairly consistent in shadow or excessive brightness. In other words, you should get better results if you use the HSV colourspace. In specific, in OpenCV the Hue range is [0,179]. In the following figure (made by @Knight), you can find a 2D slice of that cylinder, in V = 255, where the horizontal axis is the H and the vertical axis the S. As you can see from that figure to capture the red you need both to include the lower (e.g., H=0 to H=10) and upper region (e.g., H=170 to H=179) of the Hue values.
Contour
44,588,279
57
I can't seem to find the answer anywhere! I found a discussion here, but trying this I get a TypeError: 'NoneType' object is not iterable: >>> import numpy as np >>> import matplotlib.pyplot as plt >>> x, y = np.meshgrid(np.arange(10),np.arange(10)) >>> z = x + y >>> cs = plt.contourf(x,y,z,levels=[2,3]) >>> cs.collections[0].set_label('test') >>> plt.legend() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2791, in legend ret = gca().legend(*args, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes.py", line 4475, in legend self.legend_ = mlegend.Legend(self, handles, labels, **kwargs) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/legend.py", line 365, in __init__ self._init_legend_box(handles, labels) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/legend.py", line 627, in _init_legend_box handlebox) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/legend_handler.py", line 110, in __call__ handlebox.get_transform()) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/legend_handler.py", line 352, in create_artists width, height, fontsize) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/legend_handler.py", line 307, in get_sizes size_max = max(orig_handle.get_sizes())*legend.markerscale**2 TypeError: 'NoneType' object is not iterable EDIT: I'm looking for something like this:
You could also do it directly with the lines of the contour, without using proxy artists. import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 10.0 * (Z2 - Z1) # Create a simple contour plot with labels using default colors. The # inline argument to clabel will control whether the labels are draw # over the line segments of the contour, removing the lines beneath # the label plt.figure() CS = plt.contour(X, Y, Z) plt.clabel(CS, inline=1, fontsize=10) plt.title('Simplest default with labels') labels = ['line1', 'line2','line3','line4', 'line5', 'line6'] for i in range(len(labels)): CS.collections[i].set_label(labels[i]) plt.legend(loc='upper left') Will produce: However, you might also want to look into annotations for your own need. In my opinion it will give you a more fine grained control on where and what you write on the image, here is the same example with some annotation: ### better with annotation, more flexible plt.figure(2) CS = plt.contour(X, Y, Z) plt.clabel(CS, inline=1, fontsize=10) plt.title('Simplest default with labels') plt.annotate('some text here',(1.4,1.6)) plt.annotate('some text there',(-2,-1.5))
Contour
10,490,302
46
I have gone through pages and pages of contour plots in R (including many hints on stackoverflow) without success. Here is my data to contour, including adding a map of Rwanda (the data consists of 14 values of longitude, latitude and rain as x,y and z): Lon Lat Rain 28.92 -2.47 83.4 29.02 -2.68 144 29.25 -1.67 134.7 29.42 -2.07 174.9 29.55 -1.58 151.5 29.57 -2.48 224.1 29.6 -1.5 254.3 29.72 -2.18 173.9 30.03 -1.95 154.8 30.05 -1.6 152.2 30.13 -1.97 126.2 30.33 -1.3 98.5 30.45 -1.81 145.5 30.5 -2.15 151.3 Here is the code I tried from stackoverflow: datr <- read.table("Apr0130precip.txt",header=TRUE,sep=",") x <- datr$x y <- datr$y z <- datr$z require(akima) fld <- interp(x,y,z) par(mar=c(5,5,1,1)) filled.contour(fld) The interpolation fails.help will be appreciated.
Here are some different possibilites using base R graphics and ggplot. Both simple contours plots, and plots on top of maps are generated. Interpolation library(akima) fld <- with(df, interp(x = Lon, y = Lat, z = Rain)) base R plot using filled.contour filled.contour(x = fld$x, y = fld$y, z = fld$z, color.palette = colorRampPalette(c("white", "blue")), xlab = "Longitude", ylab = "Latitude", main = "Rwandan rainfall", key.title = title(main = "Rain (mm)", cex.main = 1)) Basic ggplot alternative using geom_tile and stat_contour library(ggplot2) library(reshape2) # prepare data in long format df <- melt(fld$z, na.rm = TRUE) names(df) <- c("x", "y", "Rain") df$Lon <- fld$x[df$x] df$Lat <- fld$y[df$y] ggplot(data = df, aes(x = Lon, y = Lat, z = Rain)) + geom_tile(aes(fill = Rain)) + stat_contour() + ggtitle("Rwandan rainfall") + xlab("Longitude") + ylab("Latitude") + scale_fill_continuous(name = "Rain (mm)", low = "white", high = "blue") + theme(plot.title = element_text(size = 25, face = "bold"), legend.title = element_text(size = 15), axis.text = element_text(size = 15), axis.title.x = element_text(size = 20, vjust = -0.5), axis.title.y = element_text(size = 20, vjust = 0.2), legend.text = element_text(size = 10)) ggplot on a Google Map created by ggmap # grab a map. get_map creates a raster object library(ggmap) rwanda1 <- get_map(location = c(lon = 29.75, lat = -2), zoom = 9, maptype = "toner", source = "stamen") # alternative map # rwanda2 <- get_map(location = c(lon = 29.75, lat = -2), # zoom = 9, # maptype = "terrain") # plot the raster map g1 <- ggmap(rwanda1) g1 # plot map and rain data # use coord_map with default mercator projection g1 + geom_tile(data = df, aes(x = Lon, y = Lat, z = Rain, fill = Rain), alpha = 0.8) + stat_contour(data = df, aes(x = Lon, y = Lat, z = Rain)) + ggtitle("Rwandan rainfall") + xlab("Longitude") + ylab("Latitude") + scale_fill_continuous(name = "Rain (mm)", low = "white", high = "blue") + theme(plot.title = element_text(size = 25, face = "bold"), legend.title = element_text(size = 15), axis.text = element_text(size = 15), axis.title.x = element_text(size = 20, vjust = -0.5), axis.title.y = element_text(size = 20, vjust = 0.2), legend.text = element_text(size = 10)) + coord_map() ggplot on a map created from shapefile # Since I don't have your map object, I do like this instead: # get map data from # http://biogeo.ucdavis.edu/data/diva/adm/RWA_adm.zip # unzip files to folder named "rwanda" # read shapefile with rgdal::readOGR # just try the first out of three shapefiles, which seemed to work. # 'dsn' (data source name) is the folder where the shapefile is located # 'layer' is the name of the shapefile without the .shp extension. library(rgdal) rwa <- readOGR(dsn = "rwanda", layer = "RWA_adm0") class(rwa) # [1] "SpatialPolygonsDataFrame" # convert SpatialPolygonsDataFrame object to data.frame rwa2 <- fortify(rwa) class(rwa2) # [1] "data.frame" # plot map and raindata ggplot() + geom_polygon(data = rwa2, aes(x = long, y = lat, group = group), colour = "black", size = 0.5, fill = "white") + geom_tile(data = df, aes(x = Lon, y = Lat, z = Rain, fill = Rain), alpha = 0.8) + stat_contour(data = df, aes(x = Lon, y = Lat, z = Rain)) + ggtitle("Rwandan rainfall") + xlab("Longitude") + ylab("Latitude") + scale_fill_continuous(name = "Rain (mm)", low = "white", high = "blue") + theme_bw() + theme(plot.title = element_text(size = 25, face = "bold"), legend.title = element_text(size = 15), axis.text = element_text(size = 15), axis.title.x = element_text(size = 20, vjust = -0.5), axis.title.y = element_text(size = 20, vjust = 0.2), legend.text = element_text(size = 10)) + coord_map() The interpolation and plotting of your rainfall data could of course be done in a much more sophisticated way, using the nice tools for spatial data in R. Consider my answer a fairly quick and easy start.
Contour
19,339,296
38
When using matplotlib with a contour plot, I'm having trouble getting the colorbar to display as I want. I've read through numerous similar examples, but have still not been able to get what I want. In the image below, I want two things changed. I want the minimum value and maximum values to be display on the color bar (the max should be 2.0 and the min -0.1). These two values should be at the very edge of the colorbar. Also, I want the colorbar to display the value at every color transition. For example. in the plot below, between 2.1 and 1.8, there is another color transition where the value isn't displayed. I think I may need to use norm, but it hasn't worked for me so far. Code: import numpy as np import matplotlib.pyplot as plt xi = np.array([0., 0.5, 1.0]) yi = np.array([0., 0.5, 1.0]) zi = np.array([[0., 1.0, 2.0], [0., 1.0, 2.0], [-0.1, 1.0, 2.0]]) plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k') plt.contourf(xi, yi, zi, 15, cmap=plt.cm.jet) plt.colorbar() plt.show()
If I understand correctly what you want, I think this should do it: import numpy as np import matplotlib.pyplot as plt xi = np.array([0., 0.5, 1.0]) yi = np.array([0., 0.5, 1.0]) zi = np.array([[0., 1.0, 2.0], [0., 1.0, 2.0], [-0.1, 1.0, 2.0]]) v = np.linspace(-.1, 2.0, 15, endpoint=True) plt.contour(xi, yi, zi, v, linewidths=0.5, colors='k') plt.contourf(xi, yi, zi, v, cmap=plt.cm.jet) x = plt.colorbar(ticks=v) print x plt.show()
Contour
5,826,592
37
I need to use cv::FindContours() in a program and I have to know the algorithm behind that. What algorithm does openCV use to find contours? How does it work?
If you read the documentation it is mentioned this function implements the algorithm of: Suzuki, S. and Abe, K., Topological Structural Analysis of Digitized Binary Images by Border Following. CVGIP 30 1, pp 32-46 (1985) OpenCV is open source if you want to see how this is implemented just need to read the code: https://github.com/opencv/opencv/blob/master/modules/imgproc/src/contours.cpp#L1655 The paper is available here.
Contour
10,427,474
34
I am working on Retinal fundus images.The image consists of a circular retina on a black background. With OpenCV, I have managed to get a contour which surrounds the whole circular Retina. What I need is to crop out the circular retina from the black background.
It is unclear in your question whether you want to actually crop out the information that is defined within the contour or mask out the information that isn't relevant to the contour chosen. I'll explore what to do in both situations. Masking out the information Assuming you ran cv2.findContours on your image, you will have received a structure that lists all of the contours available in your image. I'm also assuming that you know the index of the contour that was used to surround the object you want. Assuming this is stored in idx, first use cv2.drawContours to draw a filled version of this contour onto a blank image, then use this image to index into your image to extract out the object. This logic masks out any irrelevant information and only retain what is important - which is defined within the contour you have selected. The code to do this would look something like the following, assuming your image is a grayscale image stored in img: import numpy as np import cv2 img = cv2.imread('...', 0) # Read in your image # contours, _ = cv2.findContours(...) # Your call to find the contours using OpenCV 2.4.x _, contours, _ = cv2.findContours(...) # Your call to find the contours idx = ... # The index of the contour that surrounds your object mask = np.zeros_like(img) # Create mask where white is what we want, black otherwise cv2.drawContours(mask, contours, idx, 255, -1) # Draw filled contour in mask out = np.zeros_like(img) # Extract out the object and place into output image out[mask == 255] = img[mask == 255] # Show the output image cv2.imshow('Output', out) cv2.waitKey(0) cv2.destroyAllWindows() If you actually want to crop... If you want to crop the image, you need to define the minimum spanning bounding box of the area defined by the contour. You can find the top left and lower right corner of the bounding box, then use indexing to crop out what you need. The code will be the same as before, but there will be an additional cropping step: import numpy as np import cv2 img = cv2.imread('...', 0) # Read in your image # contours, _ = cv2.findContours(...) # Your call to find the contours using OpenCV 2.4.x _, contours, _ = cv2.findContours(...) # Your call to find the contours idx = ... # The index of the contour that surrounds your object mask = np.zeros_like(img) # Create mask where white is what we want, black otherwise cv2.drawContours(mask, contours, idx, 255, -1) # Draw filled contour in mask out = np.zeros_like(img) # Extract out the object and place into output image out[mask == 255] = img[mask == 255] # Now crop (y, x) = np.where(mask == 255) (topy, topx) = (np.min(y), np.min(x)) (bottomy, bottomx) = (np.max(y), np.max(x)) out = out[topy:bottomy+1, topx:bottomx+1] # Show the output image cv2.imshow('Output', out) cv2.waitKey(0) cv2.destroyAllWindows() The cropping code works such that when we define the mask to extract out the area defined by the contour, we additionally find the smallest horizontal and vertical coordinates which define the top left corner of the contour. We similarly find the largest horizontal and vertical coordinates that define the bottom left corner of the contour. We then use indexing with these coordinates to crop what we actually need. Note that this performs cropping on the masked image - that is the image that removes everything but the information contained within the largest contour. Note with OpenCV 3.x It should be noted that the above code assumes you are using OpenCV 2.4.x. Take note that in OpenCV 3.x, the definition of cv2.findContours has changed. Specifically, the output is a three element tuple output where the first image is the source image, while the other two parameters are the same as in OpenCV 2.4.x. Therefore, simply change the cv2.findContours statement in the above code to ignore the first output: _, contours, _ = cv2.findContours(...) # Your call to find contours
Contour
28,759,253
33
I have a simple problem in python and matplotlib. I have 3 lists : x, y and rho with rho[i] a density at the point x[i], y[i]. All values of x and y are between -1. and 1. but they are not in a specific order. How to make a contour plot (like with imshow) of the density rho (interpolated at the points x, y). Thank you very much. EDIT : I work with large arrays : x, y and rho have between 10,000 and 1,000,000 elements
You need to interpolate your rho values. There's no one way to do this, and the "best" method depends entirely on the a-priori information you should be incorporating into the interpolation. Before I go into a rant on "black-box" interpolation methods, though, a radial basis function (e.g. a "thin-plate-spline" is a particular type of radial basis function) is often a good choice. If you have millions of points, this implementation will be inefficient, but as a starting point: import numpy as np import matplotlib.pyplot as plt import scipy.interpolate # Generate data: x, y, z = 10 * np.random.random((3,10)) # Set up a regular grid of interpolation points xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100) xi, yi = np.meshgrid(xi, yi) # Interpolate rbf = scipy.interpolate.Rbf(x, y, z, function='linear') zi = rbf(xi, yi) plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower', extent=[x.min(), x.max(), y.min(), y.max()]) plt.scatter(x, y, c=z) plt.colorbar() plt.show()
Contour
9,008,370
33
I want to visualize polygonal curve(s) extracted with cv2.approxPolyDP(). Here's the image I am using: My code attempts to isolate the main island and define and plot the contour approximation and contour hull. I have plotted the contour found in green, the approximation in red: import numpy as np import cv2 # load image and shrink - it's massive img = cv2.imread('../data/UK.png') img = cv2.resize(img, None,fx=0.25, fy=0.25, interpolation = cv2.INTER_CUBIC) # get a blank canvas for drawing contour on and convert img to grayscale canvas = np.zeros(img.shape, np.uint8) img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # filter out small lines between counties kernel = np.ones((5,5),np.float32)/25 img2gray = cv2.filter2D(img2gray,-1,kernel) # threshold the image and extract contours ret,thresh = cv2.threshold(img2gray,250,255,cv2.THRESH_BINARY_INV) im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # find the main island (biggest area) cnt = contours[0] max_area = cv2.contourArea(cnt) for cont in contours: if cv2.contourArea(cont) > max_area: cnt = cont max_area = cv2.contourArea(cont) # define main island contour approx. and hull perimeter = cv2.arcLength(cnt,True) epsilon = 0.01*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) hull = cv2.convexHull(cnt) # cv2.isContourConvex(cnt) cv2.drawContours(canvas, cnt, -1, (0, 255, 0), 3) cv2.drawContours(canvas, approx, -1, (0, 0, 255), 3) ## cv2.drawContours(canvas, hull, -1, (0, 0, 255), 3) # only displays a few points as well. cv2.imshow("Contour", canvas) k = cv2.waitKey(0) if k == 27: # wait for ESC key to exit cv2.destroyAllWindows() Here are the resulting images: The first image plots the contour in green. The second plots the approximation in red - how do I plot this approximation as a continuous closed curve? The documentation isn't terribly clear and neither is the tutorial, but my understanding is that cv2.approxPolyDP() should define a continuous, closed curve, which I should be able to plot with cv2.drawContours(). Is that correct? If so, what am I doing wrong?
The problem is in visualization only: drawContours expects array (list in case of python) of contours, not just one numpy array (which is returned from approxPolyDP). Solution is the following: replacing cv2.drawContours(canvas, approx, -1, (0, 0, 255), 3) to cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 3)
Contour
41,879,315
32
I'm attempting to script a contour polar plot in R from interpolated point data. In other words, I have data in polar coordinates with a magnitude value I would like to plot and show interpolated values. I'd like to mass produce plots similar to the following (produced in OriginPro): My closest attempt in R to this point is basically: ### Convert polar -> cart # ToDo # ### Dummy data x = rnorm(20) y = rnorm(20) z = rnorm(20) ### Interpolate library(akima) tmp = interp(x,y,z) ### Plot interpolation library(fields) image.plot(tmp) ### ToDo ### #Turn off all axis #Plot polar axis ontop Which produces something like: While this is obviously not going to be the final product, is this the best way to go about creating contour polar plots in R? I can't find anything on the topic other than an archive mailing list dicussion from 2008. I guess I'm not fully dedicated to using R for the plots (though that is where I have the data), but I am opposed to manual creation. So, if there is another language with this capability, please suggest it (I did see the Python example). EDIT Regarding the suggestion using ggplot2 - I can't seem to get the geom_tile routine to plot interpolated data in polar_coordinates. I have included code below that illustrates where I'm at. I can plot the original in Cartesian and polar, but I can only get the interpolated data to plot in Cartesian. I can plot the interpolation points in polar using geom_point, but I can't extend that approach to geom_tile. My only guess was that this is related to data order - i.e. geom_tile is expecting sorted/ordered data - I've tried every iteration I can think of sorting the data into ascending/descending azimuth and zenith with no change. ## Libs library(akima) library(ggplot2) ## Sample data in az/el(zenith) tmp = seq(5,355,by=10) geoms <- data.frame(az = tmp, zen = runif(length(tmp)), value = runif(length(tmp))) geoms$az_rad = geoms$az*pi/180 ## These points plot fine ggplot(geoms)+geom_point(aes(az,zen,colour=value))+ coord_polar()+ scale_x_continuous(breaks=c(0,45,90,135,180,225,270,315,360),limits=c(0,360))+ scale_colour_gradient(breaks=seq(0,1,by=.1),low="black",high="white") ## Need to interpolate - most easily done in cartesian x = geoms$zen*sin(geoms$az_rad) y = geoms$zen*cos(geoms$az_rad) df.ptsc = data.frame(x=x,y=y,z=geoms$value) intc = interp(x,y,geoms$value, xo=seq(min(x), max(x), length = 100), yo=seq(min(y), max(y), length = 100),linear=FALSE) df.intc = data.frame(expand.grid(x=intc$x,y=intc$y), z=c(intc$z),value=cut((intc$z),breaks=seq(0,1,.1))) ## This plots fine in cartesian coords ggplot(df.intc)+scale_x_continuous(limits=c(-1.1,1.1))+ scale_y_continuous(limits=c(-1.1,1.1))+ geom_point(data=df.ptsc,aes(x,y,colour=z))+ scale_colour_gradient(breaks=seq(0,1,by=.1),low="white",high="red") ggplot(df.intc)+geom_tile(aes(x,y,fill=z))+ scale_x_continuous(limits=c(-1.1,1.1))+ scale_y_continuous(limits=c(-1.1,1.1))+ geom_point(data=df.ptsc,aes(x,y,colour=z))+ scale_colour_gradient(breaks=seq(0,1,by=.1),low="white",high="red") ## Convert back to polar int_az = atan2(df.intc$x,df.intc$y) int_az = int_az*180/pi int_az = unlist(lapply(int_az,function(x){if(x<0){x+360}else{x}})) int_zen = sqrt(df.intc$x^2+df.intc$y^2) df.intp = data.frame(az=int_az,zen=int_zen,z=df.intc$z,value=df.intc$value) ## Just to check az = atan2(x,y) az = az*180/pi az = unlist(lapply(az,function(x){if(x<0){x+360}else{x}})) zen = sqrt(x^2+y^2) ## The conversion looks correct [[az = geoms$az, zen = geoms$zen]] ## This plots the interpolated locations ggplot(df.intp)+geom_point(aes(az,zen))+coord_polar() ## This doesn't track to geom_tile ggplot(df.intp)+geom_tile(aes(az,zen,fill=value))+coord_polar() Final Results I finally took code from the accepted answer (base graphics) and updated the code. I added a thin plate spline interpolation method, an option to extrapolate or not, data point overlays, and the ability to do continuous colors or segmented colors for the interpolated surface. See the examples below. PolarImageInterpolate <- function( ### Plotting data (in cartesian) - will be converted to polar space. x, y, z, ### Plot component flags contours=TRUE, # Add contours to the plotted surface legend=TRUE, # Plot a surface data legend? axes=TRUE, # Plot axes? points=TRUE, # Plot individual data points extrapolate=FALSE, # Should we extrapolate outside data points? ### Data splitting params for color scale and contours col_breaks_source = 1, # Where to calculate the color brakes from (1=data,2=surface) # If you know the levels, input directly (i.e. c(0,1)) col_levels = 10, # Number of color levels to use - must match length(col) if #col specified separately col = rev(heat.colors(col_levels)), # Colors to plot contour_breaks_source = 1, # 1=z data, 2=calculated surface data # If you know the levels, input directly (i.e. c(0,1)) contour_levels = col_levels+1, # One more contour break than col_levels (must be # specified correctly if done manually ### Plotting params outer.radius = round_any(max(sqrt(x^2+y^2)),5,f=ceiling), circle.rads = pretty(c(0,outer.radius)), #Radius lines spatial_res=1000, #Resolution of fitted surface single_point_overlay=0, #Overlay "key" data point with square #(0 = No, Other = number of pt) ### Fitting parameters interp.type = 1, #1 = linear, 2 = Thin plate spline lambda=0){ #Used only when interp.type = 2 minitics <- seq(-outer.radius, outer.radius, length.out = spatial_res) # interpolate the data if (interp.type ==1 ){ Interp <- akima:::interp(x = x, y = y, z = z, extrap = extrapolate, xo = minitics, yo = minitics, linear = FALSE) Mat <- Interp[[3]] } else if (interp.type == 2){ library(fields) grid.list = list(x=minitics,y=minitics) t = Tps(cbind(x,y),z,lambda=lambda) tmp = predict.surface(t,grid.list,extrap=extrapolate) Mat = tmp$z } else {stop("interp.type value not valid")} # mark cells outside circle as NA markNA <- matrix(minitics, ncol = spatial_res, nrow = spatial_res) Mat[!sqrt(markNA ^ 2 + t(markNA) ^ 2) < outer.radius] <- NA ### Set contour_breaks based on requested source if ((length(contour_breaks_source == 1)) & (contour_breaks_source[1] == 1)){ contour_breaks = seq(min(z,na.rm=TRUE),max(z,na.rm=TRUE), by=(max(z,na.rm=TRUE)-min(z,na.rm=TRUE))/(contour_levels-1)) } else if ((length(contour_breaks_source == 1)) & (contour_breaks_source[1] == 2)){ contour_breaks = seq(min(Mat,na.rm=TRUE),max(Mat,na.rm=TRUE), by=(max(Mat,na.rm=TRUE)-min(Mat,na.rm=TRUE))/(contour_levels-1)) } else if ((length(contour_breaks_source) == 2) & (is.numeric(contour_breaks_source))){ contour_breaks = pretty(contour_breaks_source,n=contour_levels) contour_breaks = seq(contour_breaks_source[1],contour_breaks_source[2], by=(contour_breaks_source[2]-contour_breaks_source[1])/(contour_levels-1)) } else {stop("Invalid selection for \"contour_breaks_source\"")} ### Set color breaks based on requested source if ((length(col_breaks_source) == 1) & (col_breaks_source[1] == 1)) {zlim=c(min(z,na.rm=TRUE),max(z,na.rm=TRUE))} else if ((length(col_breaks_source) == 1) & (col_breaks_source[1] == 2)) {zlim=c(min(Mat,na.rm=TRUE),max(Mat,na.rm=TRUE))} else if ((length(col_breaks_source) == 2) & (is.numeric(col_breaks_source))) {zlim=col_breaks_source} else {stop("Invalid selection for \"col_breaks_source\"")} # begin plot Mat_plot = Mat Mat_plot[which(Mat_plot<zlim[1])]=zlim[1] Mat_plot[which(Mat_plot>zlim[2])]=zlim[2] image(x = minitics, y = minitics, Mat_plot , useRaster = TRUE, asp = 1, axes = FALSE, xlab = "", ylab = "", zlim = zlim, col = col) # add contours if desired if (contours){ CL <- contourLines(x = minitics, y = minitics, Mat, levels = contour_breaks) A <- lapply(CL, function(xy){ lines(xy$x, xy$y, col = gray(.2), lwd = .5) }) } # add interpolated point if desired if (points){ points(x,y,pch=4) } # add overlay point (used for trained image marking) if desired if (single_point_overlay!=0){ points(x[single_point_overlay],y[single_point_overlay],pch=0) } # add radial axes if desired if (axes){ # internals for axis markup RMat <- function(radians){ matrix(c(cos(radians), sin(radians), -sin(radians), cos(radians)), ncol = 2) } circle <- function(x, y, rad = 1, nvert = 500){ rads <- seq(0,2*pi,length.out = nvert) xcoords <- cos(rads) * rad + x ycoords <- sin(rads) * rad + y cbind(xcoords, ycoords) } # draw circles if (missing(circle.rads)){ circle.rads <- pretty(c(0,outer.radius)) } for (i in circle.rads){ lines(circle(0, 0, i), col = "#66666650") } # put on radial spoke axes: axis.rads <- c(0, pi / 6, pi / 3, pi / 2, 2 * pi / 3, 5 * pi / 6) r.labs <- c(90, 60, 30, 0, 330, 300) l.labs <- c(270, 240, 210, 180, 150, 120) for (i in 1:length(axis.rads)){ endpoints <- zapsmall(c(RMat(axis.rads[i]) %*% matrix(c(1, 0, -1, 0) * outer.radius,ncol = 2))) segments(endpoints[1], endpoints[2], endpoints[3], endpoints[4], col = "#66666650") endpoints <- c(RMat(axis.rads[i]) %*% matrix(c(1.1, 0, -1.1, 0) * outer.radius, ncol = 2)) lab1 <- bquote(.(r.labs[i]) * degree) lab2 <- bquote(.(l.labs[i]) * degree) text(endpoints[1], endpoints[2], lab1, xpd = TRUE) text(endpoints[3], endpoints[4], lab2, xpd = TRUE) } axis(2, pos = -1.25 * outer.radius, at = sort(union(circle.rads,-circle.rads)), labels = NA) text( -1.26 * outer.radius, sort(union(circle.rads, -circle.rads)),sort(union(circle.rads, -circle.rads)), xpd = TRUE, pos = 2) } # add legend if desired # this could be sloppy if there are lots of breaks, and that's why it's optional. # another option would be to use fields:::image.plot(), using only the legend. # There's an example for how to do so in its documentation if (legend){ library(fields) image.plot(legend.only=TRUE, smallplot=c(.78,.82,.1,.8), col=col, zlim=zlim) # ylevs <- seq(-outer.radius, outer.radius, length = contour_levels+ 1) # #ylevs <- seq(-outer.radius, outer.radius, length = length(contour_breaks)) # rect(1.2 * outer.radius, ylevs[1:(length(ylevs) - 1)], 1.3 * outer.radius, ylevs[2:length(ylevs)], col = col, border = NA, xpd = TRUE) # rect(1.2 * outer.radius, min(ylevs), 1.3 * outer.radius, max(ylevs), border = "#66666650", xpd = TRUE) # text(1.3 * outer.radius, ylevs[seq(1,length(ylevs),length.out=length(contour_breaks))],round(contour_breaks, 1), pos = 4, xpd = TRUE) } }
[[major edit]] I was finally able to add contour lines to my original attempt, but since the two sides of the original matrix that gets contorted don't actually touch, the lines don't match up between 360 and 0 degree. So I've totally rethought the problem, but leave the original post below because it was still kind of cool to plot a matrix that way. The function I'm posting now takes x,y,z and several optional arguments, and spits back something pretty darn similar to your desired examples, radial axes, legend, contour lines and all: PolarImageInterpolate <- function(x, y, z, outer.radius = 1, breaks, col, nlevels = 20, contours = TRUE, legend = TRUE, axes = TRUE, circle.rads = pretty(c(0,outer.radius))){ minitics <- seq(-outer.radius, outer.radius, length.out = 1000) # interpolate the data Interp <- akima:::interp(x = x, y = y, z = z, extrap = TRUE, xo = minitics, yo = minitics, linear = FALSE) Mat <- Interp[[3]] # mark cells outside circle as NA markNA <- matrix(minitics, ncol = 1000, nrow = 1000) Mat[!sqrt(markNA ^ 2 + t(markNA) ^ 2) < outer.radius] <- NA # sort out colors and breaks: if (!missing(breaks) & !missing(col)){ if (length(breaks) - length(col) != 1){ stop("breaks must be 1 element longer than cols") } } if (missing(breaks) & !missing(col)){ breaks <- seq(min(Mat,na.rm = TRUE), max(Mat, na.rm = TRUE), length = length(col) + 1) nlevels <- length(breaks) - 1 } if (missing(col) & !missing(breaks)){ col <- rev(heat.colors(length(breaks) - 1)) nlevels <- length(breaks) - 1 } if (missing(breaks) & missing(col)){ breaks <- seq(min(Mat,na.rm = TRUE), max(Mat, na.rm = TRUE), length = nlevels + 1) col <- rev(heat.colors(nlevels)) } # if legend desired, it goes on the right and some space is needed if (legend) { par(mai = c(1,1,1.5,1.5)) } # begin plot image(x = minitics, y = minitics, t(Mat), useRaster = TRUE, asp = 1, axes = FALSE, xlab = "", ylab = "", col = col, breaks = breaks) # add contours if desired if (contours){ CL <- contourLines(x = minitics, y = minitics, t(Mat), levels = breaks) A <- lapply(CL, function(xy){ lines(xy$x, xy$y, col = gray(.2), lwd = .5) }) } # add radial axes if desired if (axes){ # internals for axis markup RMat <- function(radians){ matrix(c(cos(radians), sin(radians), -sin(radians), cos(radians)), ncol = 2) } circle <- function(x, y, rad = 1, nvert = 500){ rads <- seq(0,2*pi,length.out = nvert) xcoords <- cos(rads) * rad + x ycoords <- sin(rads) * rad + y cbind(xcoords, ycoords) } # draw circles if (missing(circle.rads)){ circle.rads <- pretty(c(0,outer.radius)) } for (i in circle.rads){ lines(circle(0, 0, i), col = "#66666650") } # put on radial spoke axes: axis.rads <- c(0, pi / 6, pi / 3, pi / 2, 2 * pi / 3, 5 * pi / 6) r.labs <- c(90, 60, 30, 0, 330, 300) l.labs <- c(270, 240, 210, 180, 150, 120) for (i in 1:length(axis.rads)){ endpoints <- zapsmall(c(RMat(axis.rads[i]) %*% matrix(c(1, 0, -1, 0) * outer.radius,ncol = 2))) segments(endpoints[1], endpoints[2], endpoints[3], endpoints[4], col = "#66666650") endpoints <- c(RMat(axis.rads[i]) %*% matrix(c(1.1, 0, -1.1, 0) * outer.radius, ncol = 2)) lab1 <- bquote(.(r.labs[i]) * degree) lab2 <- bquote(.(l.labs[i]) * degree) text(endpoints[1], endpoints[2], lab1, xpd = TRUE) text(endpoints[3], endpoints[4], lab2, xpd = TRUE) } axis(2, pos = -1.2 * outer.radius, at = sort(union(circle.rads,-circle.rads)), labels = NA) text( -1.21 * outer.radius, sort(union(circle.rads, -circle.rads)),sort(union(circle.rads, -circle.rads)), xpd = TRUE, pos = 2) } # add legend if desired # this could be sloppy if there are lots of breaks, and that's why it's optional. # another option would be to use fields:::image.plot(), using only the legend. # There's an example for how to do so in its documentation if (legend){ ylevs <- seq(-outer.radius, outer.radius, length = nlevels + 1) rect(1.2 * outer.radius, ylevs[1:(length(ylevs) - 1)], 1.3 * outer.radius, ylevs[2:length(ylevs)], col = col, border = NA, xpd = TRUE) rect(1.2 * outer.radius, min(ylevs), 1.3 * outer.radius, max(ylevs), border = "#66666650", xpd = TRUE) text(1.3 * outer.radius, ylevs,round(breaks, 1), pos = 4, xpd = TRUE) } } # Example set.seed(10) x <- rnorm(20) y <- rnorm(20) z <- rnorm(20) PolarImageInterpolate(x,y,z, breaks = seq(-2,8,by = 1)) code available here: https://gist.github.com/2893780 [[my original answer follows]] I thought your question would be educational for myself, so I took up the challenge and came up with the following incomplete function. It works similar to image(), wants a matrix as its primary input, and spits back something similar to your example above, minus the contour lines. [[I edited the code June 6th after noticing that it didn't plot in the order I claimed. Fixed. Currently working on contour lines and legend.]] # arguments: # Mat, a matrix of z values as follows: # leftmost edge of first column = 0 degrees, rightmost edge of last column = 360 degrees # columns are distributed in cells equally over the range 0 to 360 degrees, like a grid prior to transform # first row is innermost circle, last row is outermost circle # outer.radius, By default everything scaled to unit circle # ppa: points per cell per arc. If your matrix is little, make it larger for a nice curve # cols: color vector. default = rev(heat.colors(length(breaks)-1)) # breaks: manual breaks for colors. defaults to seq(min(Mat),max(Mat),length=nbreaks) # nbreaks: how many color levels are desired? # axes: should circular and radial axes be drawn? radial axes are drawn at 30 degree intervals only- this could be made more flexible. # circle.rads: at which radii should circles be drawn? defaults to pretty(((0:ncol(Mat)) / ncol(Mat)) * outer.radius) # TODO: add color strip legend. PolarImagePlot <- function(Mat, outer.radius = 1, ppa = 5, cols, breaks, nbreaks = 51, axes = TRUE, circle.rads){ # the image prep Mat <- Mat[, ncol(Mat):1] radii <- ((0:ncol(Mat)) / ncol(Mat)) * outer.radius # 5 points per arc will usually do Npts <- ppa # all the angles for which a vertex is needed radians <- 2 * pi * (0:(nrow(Mat) * Npts)) / (nrow(Mat) * Npts) + pi / 2 # matrix where each row is the arc corresponding to a cell rad.mat <- matrix(radians[-length(radians)], ncol = Npts, byrow = TRUE)[1:nrow(Mat), ] rad.mat <- cbind(rad.mat, rad.mat[c(2:nrow(rad.mat), 1), 1]) # the x and y coords assuming radius of 1 y0 <- sin(rad.mat) x0 <- cos(rad.mat) # dimension markers nc <- ncol(x0) nr <- nrow(x0) nl <- length(radii) # make a copy for each radii, redimension in sick ways x1 <- aperm( x0 %o% radii, c(1, 3, 2)) # the same, but coming back the other direction to close the polygon x2 <- x1[, , nc:1] #now stick together x.array <- abind:::abind(x1[, 1:(nl - 1), ], x2[, 2:nl, ], matrix(NA, ncol = (nl - 1), nrow = nr), along = 3) # final product, xcoords, is a single vector, in order, # where all the x coordinates for a cell are arranged # clockwise. cells are separated by NAs- allows a single call to polygon() xcoords <- aperm(x.array, c(3, 1, 2)) dim(xcoords) <- c(NULL) # repeat for y coordinates y1 <- aperm( y0 %o% radii,c(1, 3, 2)) y2 <- y1[, , nc:1] y.array <- abind:::abind(y1[, 1:(length(radii) - 1), ], y2[, 2:length(radii), ], matrix(NA, ncol = (length(radii) - 1), nrow = nr), along = 3) ycoords <- aperm(y.array, c(3, 1, 2)) dim(ycoords) <- c(NULL) # sort out colors and breaks: if (!missing(breaks) & !missing(cols)){ if (length(breaks) - length(cols) != 1){ stop("breaks must be 1 element longer than cols") } } if (missing(breaks) & !missing(cols)){ breaks <- seq(min(Mat,na.rm = TRUE), max(Mat, na.rm = TRUE), length = length(cols) + 1) } if (missing(cols) & !missing(breaks)){ cols <- rev(heat.colors(length(breaks) - 1)) } if (missing(breaks) & missing(cols)){ breaks <- seq(min(Mat,na.rm = TRUE), max(Mat, na.rm = TRUE), length = nbreaks) cols <- rev(heat.colors(length(breaks) - 1)) } # get a color for each cell. Ugly, but it gets them in the right order cell.cols <- as.character(cut(as.vector(Mat[nrow(Mat):1,ncol(Mat):1]), breaks = breaks, labels = cols)) # start empty plot plot(NULL, type = "n", ylim = c(-1, 1) * outer.radius, xlim = c(-1, 1) * outer.radius, asp = 1, axes = FALSE, xlab = "", ylab = "") # draw polygons with no borders: polygon(xcoords, ycoords, col = cell.cols, border = NA) if (axes){ # a couple internals for axis markup. RMat <- function(radians){ matrix(c(cos(radians), sin(radians), -sin(radians), cos(radians)), ncol = 2) } circle <- function(x, y, rad = 1, nvert = 500){ rads <- seq(0,2*pi,length.out = nvert) xcoords <- cos(rads) * rad + x ycoords <- sin(rads) * rad + y cbind(xcoords, ycoords) } # draw circles if (missing(circle.rads)){ circle.rads <- pretty(radii) } for (i in circle.rads){ lines(circle(0, 0, i), col = "#66666650") } # put on radial spoke axes: axis.rads <- c(0, pi / 6, pi / 3, pi / 2, 2 * pi / 3, 5 * pi / 6) r.labs <- c(90, 60, 30, 0, 330, 300) l.labs <- c(270, 240, 210, 180, 150, 120) for (i in 1:length(axis.rads)){ endpoints <- zapsmall(c(RMat(axis.rads[i]) %*% matrix(c(1, 0, -1, 0) * outer.radius,ncol = 2))) segments(endpoints[1], endpoints[2], endpoints[3], endpoints[4], col = "#66666650") endpoints <- c(RMat(axis.rads[i]) %*% matrix(c(1.1, 0, -1.1, 0) * outer.radius, ncol = 2)) lab1 <- bquote(.(r.labs[i]) * degree) lab2 <- bquote(.(l.labs[i]) * degree) text(endpoints[1], endpoints[2], lab1, xpd = TRUE) text(endpoints[3], endpoints[4], lab2, xpd = TRUE) } axis(2, pos = -1.2 * outer.radius, at = sort(union(circle.rads,-circle.rads))) } invisible(list(breaks = breaks, col = cols)) } I don't know how to interpolate properly over a polar surface, so assuming you can achieve that and get your data into a matrix, then this function will get it plotted for you. Each cell is drawn, as with image(), but the interior ones are teeny tiny. Here's an example: set.seed(1) x <- runif(20, min = 0, max = 360) y <- runif(20, min = 0, max = 40) z <- rnorm(20) Interp <- akima:::interp(x = x, y = y, z = z, extrap = TRUE, xo = seq(0, 360, length.out = 300), yo = seq(0, 40, length.out = 100), linear = FALSE) Mat <- Interp[[3]] PolarImagePlot(Mat) By all means, feel free to modify this and do with it what you will. Code is available on Github here: https://gist.github.com/2877281
Contour
10,856,882
31
I have a pet project to create images of maps, where I draw the roads and other stuff over a contour plot of the terrain elevation. It is intended to plan mountain bike routes (I have made some vectorial drawings by hand, in the past, and they work great for visualization). Currently, I download Digital Elevation Model, in GeoTIFF, from here: http://www.ecologia.ufrgs.br/labgeo/arquivos/downloads/dados/SRTM/geotiff/rs.rar and then create the plot with GDAL and Matplotlib contourf function: from osgeo import gdal import matplotlib import matplotlib.pyplot as plt from pylab import cm import numpy f = 'rs.tif' elev = gdal.Open(f) a = elev.GetRasterBand(1).ReadAsArray() w = elev.RasterXSize h = elev.RasterYSize print w, h altura = (0.35, 0.42) largura = (0.70, 0.82) a = a[int(h*altura[0]):int(h*altura[1]), int(w*largura[0]):int(w*largura[1])] cont = plt.contourf(a, origin='upper', cmap=cm.gist_earth, levels=numpy.arange(0,1000,20)) plt.title('Altitudes - max: %d m; min: %d m' % (numpy.amax(a), numpy.amin(a))) plt.show() Which gives: The problem is that contour lines are "white", and generate some visual pollution, which is undesired since I want to plot roads and rivers later. So, I am trying to modify the way contourf create these lighter lines, either via parameter setting, or via hack (changing source code), similar to the one proposed here: How to format contour lines from Matplotlib Also, if anyone knows how to generate such a map in a more elegant way, using other libraries, I would appreciate the tip very much! Thanks for reading.
I finally found a proper solution to this long-standing problem (currently in Matplotlib 3), which does not require multiple calls to contour or rasterize the figure. Note that the problem illustrated in the question appears only in saved publication-quality figures formats like PDF, not in lower-quality raster files like PNG. My solution was inspired by this answer, related to a similar problem with the colorbar. A similar solution turns out to solve the contour plot as well, as follows: import numpy as np import matplotlib.pyplot as plt np.random.seed(123) x, y = np.random.uniform(size=(100, 2)).T z = np.exp(-x**2 - y**2) levels = np.linspace(0, 1, 100) cnt = plt.tricontourf(x, y, z, levels=levels, cmap="ocean") # This is the fix for the white lines between contour levels cnt.set_edgecolor("face") plt.savefig("test.pdf") Here below is an example of contours before the fix And here below is the same figure after the above fix
Contour
8,263,769
31
In python, If I have a set of data x, y, z I can make a scatter with import matplotlib.pyplot as plt plt.scatter(x,y,c=z) How I can get a plt.contourf(x,y,z) of the scatter ?
You can use tricontourf as suggested in case b. of this other answer: import matplotlib.tri as tri import matplotlib.pyplot as plt plt.tricontour(x, y, z, 15, linewidths=0.5, colors='k') plt.tricontourf(x, y, z, 15) Old reply: Use the following function to convert to the format required by contourf: from numpy import linspace, meshgrid from matplotlib.mlab import griddata def grid(x, y, z, resX=100, resY=100): "Convert 3 column data to matplotlib grid" xi = linspace(min(x), max(x), resX) yi = linspace(min(y), max(y), resY) Z = griddata(x, y, z, xi, yi) X, Y = meshgrid(xi, yi) return X, Y, Z Now you can do: X, Y, Z = grid(x, y, z) plt.contourf(X, Y, Z)
Contour
18,764,814
30
I want to draw x=0 and y=0 axis in my contour plot, using a white color. If that is too cumbersome, I would like to have a white dot denoting where the origin is. My contour plot looks as follows and the code to create it is given below. xvec = linspace(-5.,5.,100) X,Y = meshgrid(xvec, xvec) fig = plt.figure(figsize=(6, 4)) contourf(X, Y, W,100) plt.colorbar()
There are a number of options (E.g. centered spines), but in your case, it's probably simplest to just use axhline and axvline. E.g. import numpy as np import matplotlib.pyplot as plt xvec = np.linspace(-5.,5.,100) x,y = np.meshgrid(xvec, xvec) z = -np.hypot(x, y) plt.contourf(x, y, z, 100) plt.colorbar() plt.axhline(0, color='white') plt.axvline(0, color='white') plt.show()
Contour
9,609,372
30