repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
teodorpatras/SrollViewPlay
ScrollViewPlay/ScrollViewPlay/InfiniteScrollView.swift
1
6306
// // InfiniteScrollView.swift // ScrollViewPlay // // Created by Teodor Patras on 02/07/15. // Copyright (c) 2015 Teodor Patras. All rights reserved. // import UIKit class InfiniteScrollView: UIScrollView { let containerView : UIView let imageNames = ["rocket1", "rocket4", "rocket2", "rocket3"] var imageViews = [UIImageView]() var visibleImageViews = [UIImageView]() required init(coder aDecoder: NSCoder) { containerView = UIView() super.init(coder: aDecoder) self.contentSize = CGSizeMake(5000, UIScreen.mainScreen().bounds.height - 128) containerView.frame = CGRectMake(0, 0, self.contentSize.width, self.contentSize.height * 0.7) self.addSubview(self.containerView) var actualSize : CGFloat = 0 var imageView : UIImageView for name in imageNames { imageView = UIImageView(image: UIImage(named: name)) actualSize += CGRectGetWidth(imageView.frame) imageViews.append(imageView) } /* this should only work if all the images place side by side would not fit within the width of the scroll view */ if actualSize <= CGRectGetWidth(self.bounds) { self.scrollEnabled = false self.bounces = false } } // MARK:- Layout - func recenterIfNecessary () { let centerOffsetX = (self.contentSize.width - self.bounds.size.width) / 2 let distanceFromCenter = fabs(self.contentOffset.x - centerOffsetX) if distanceFromCenter > self.contentSize.width / 4 { // move all the views by the same amount so they appear still for imageView in self.visibleImageViews { var center = self.containerView.convertPoint(imageView.center, toView: self) center.x += centerOffsetX - self.contentOffset.x imageView.center = self.convertPoint(center, toView: self.containerView) } self.contentOffset = CGPointMake(centerOffsetX, self.contentOffset.y) } } override func layoutSubviews() { super.layoutSubviews() self.recenterIfNecessary() // tile content in visible bounds let visibleBounds = self.convertRect(self.bounds, toView: self.containerView) let minVisX = CGRectGetMinX(visibleBounds) let maxVisX = CGRectGetMaxX(visibleBounds) self.tileFromMinX(minVisX, toMaxX: maxVisX) } // MARK:- UIImageViews Tiling - func placeImageViewOnRight(imageView : UIImageView, rightEdge : CGFloat) -> CGFloat { var frame = imageView.frame frame.origin.x = rightEdge frame.origin.y = CGRectGetHeight(self.containerView.bounds) - frame.size.height imageView.frame = frame self.containerView.addSubview(imageView) self.visibleImageViews.append(imageView) return CGRectGetMaxX(frame) } func placeImageViewOnLeft(imageView : UIImageView, leftEdge : CGFloat) -> CGFloat { var frame = imageView.frame frame.origin.x = leftEdge - CGRectGetWidth(frame) frame.origin.y = CGRectGetHeight(self.containerView.bounds) - frame.size.height imageView.frame = frame self.containerView.addSubview(imageView) self.visibleImageViews.insert(imageView, atIndex: 0) return CGRectGetMinX(frame) } func tileFromMinX(minVisX : CGFloat, toMaxX maxX: CGFloat) { // place the first image if visibleImageViews.count == 0 { var imageView = imageViews.removeAtIndex(0) self.placeImageViewOnRight(imageView, rightEdge: minVisX) } // place missing images on the right edge var shouldPlaceSomeMore = true var newXOrigin = CGRectGetMaxX(self.visibleImageViews.last!.frame) while shouldPlaceSomeMore { shouldPlaceSomeMore = false if newXOrigin < maxX { if let iv = imageViews.last { newXOrigin = self.placeImageViewOnRight(iv, rightEdge: newXOrigin) imageViews.removeLast() shouldPlaceSomeMore = newXOrigin < maxX } } } // place missing images on the left edge shouldPlaceSomeMore = true newXOrigin = CGRectGetMinX(self.visibleImageViews.first!.frame) while shouldPlaceSomeMore { shouldPlaceSomeMore = false if newXOrigin > minVisX { if let iv = imageViews.first { newXOrigin = self.placeImageViewOnLeft(iv, leftEdge: newXOrigin) imageViews.removeAtIndex(0) shouldPlaceSomeMore = newXOrigin > minVisX } } } // remove images that have fallen over the right edge var shouldRemove = true while shouldRemove { shouldRemove = false if let iv = visibleImageViews.last { if CGRectGetMinX(iv.frame) > maxX { imageViews.append(iv) iv.removeFromSuperview() shouldRemove = true visibleImageViews.removeLast() } } } // remove images that have fallen over the left edge shouldRemove = true while shouldRemove { shouldRemove = false if let iv = visibleImageViews.first { if CGRectGetMaxX(iv.frame) < minVisX { imageViews.insert(iv, atIndex: 0) iv.removeFromSuperview() shouldRemove = true visibleImageViews.removeAtIndex(0) } } } } }
mit
7060bdd8d4256a44519cd6e157990862
29.911765
101
0.5536
5.473958
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/UnixScript.swift
1
8429
// // UnixScript.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2017-10-28. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2022 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import AppKit.NSDocument final class UnixScript: Script { // MARK: Script Properties let url: URL let name: String // MARK: Private Properties private lazy var content: String? = try? String(contentsOf: self.url) // MARK: - // MARK: Lifecycle init(url: URL, name: String) throws { self.url = url self.name = name } // MARK: Private Enum private enum OutputType: String, ScriptToken { case replaceSelection = "ReplaceSelection" case replaceAllText = "ReplaceAllText" case insertAfterSelection = "InsertAfterSelection" case appendToAllText = "AppendToAllText" case newDocument = "NewDocument" case pasteBoard = "Pasteboard" static var token = "CotEditorXOutput" } private enum InputType: String, ScriptToken { case selection = "Selection" case allText = "AllText" static var token = "CotEditorXInput" } // MARK: Script Methods /// Execute the script. /// /// - Throws: `ScriptError` by the script,`ScriptFileError`, or any errors on script loading. func run() async throws { // check script file guard self.url.isReachable else { throw ScriptFileError(kind: .existance, url: self.url) } guard try self.url.resourceValues(forKeys: [.isExecutableKey]).isExecutable ?? false else { throw ScriptFileError(kind: .permission, url: self.url) } guard let script = self.content, !script.isEmpty else { throw ScriptFileError(kind: .read, url: self.url) } // fetch target document weak var document = await NSDocumentController.shared.currentDocument as? NSDocument & Editable // read input let input: String? if let inputType = InputType(scanning: script) { input = try await self.readInput(type: inputType, editor: document) } else { input = nil } // get output type let outputType = OutputType(scanning: script) // prepare file path as argument if available let arguments: [String] = await [document?.fileURL?.path].compactMap { $0 } // create task let task = try NSUserUnixTask(url: self.url) let inPipe = Pipe() let outPipe = Pipe() let errPipe = Pipe() task.standardInput = inPipe.fileHandleForReading task.standardOutput = outPipe.fileHandleForWriting task.standardError = errPipe.fileHandleForWriting // set input data if available if let data = input?.data(using: .utf8) { inPipe.fileHandleForWriting.writeabilityHandler = { (handle) in // write input data chunk by chunk // -> to avoid freeze by a huge input data, whose length is more than 65,536 (2^16). for chunk in data.components(length: 65_536) { handle.write(chunk) } // inPipe must avoid releasing before `writeabilityHandler` is invocated inPipe.fileHandleForWriting.writeabilityHandler = nil } } // read output asynchronously for safe with huge output var outputData = Data() if outputType != nil { outPipe.fileHandleForReading.readabilityHandler = { (handle) in outputData.append(handle.availableData) } } // execute do { try await task.execute(withArguments: arguments) } catch where (error as? POSIXError)?.code == .ENOTBLK { // on user cancellation return } catch { throw error } outPipe.fileHandleForReading.readabilityHandler = nil // apply output if let outputType = outputType, let output = String(data: outputData, encoding: .utf8) { do { try await self.applyOutput(output, type: outputType, editor: document) } catch { await Console.shared.show(message: error.localizedDescription, title: name) } } // obtain standard error let errorData = errPipe.fileHandleForReading.readDataToEndOfFile() if let errorString = String(data: errorData, encoding: .utf8), !errorString.isEmpty { throw ScriptError.standardError(errorString) } } // MARK: Private Methods /// Read the document content. /// /// - Parameters: /// - type: The type of input target. /// - editor: The editor to read the input. /// - Returns: The read string. /// - Throws: `ScriptError` @MainActor private func readInput(type: InputType, editor: Editable?) throws -> String { guard let editor = editor else { throw ScriptError.noInputTarget } switch type { case .selection: return editor.selectedString case .allText: return editor.string } } /// Apply script output to the desired target. /// /// - Parameters: /// - output: The output string. /// - type: The type of output target. /// - editor: The editor to write the output. /// - Throws: `ScriptError` @MainActor private func applyOutput(_ output: String, type: OutputType, editor: Editable?) throws { switch type { case .replaceSelection: guard let editor = editor else { throw ScriptError.noOutputTarget } editor.insert(string: output, at: .replaceSelection) case .replaceAllText: guard let editor = editor else { throw ScriptError.noOutputTarget } editor.insert(string: output, at: .replaceAll) case .insertAfterSelection: guard let editor = editor else { throw ScriptError.noOutputTarget } editor.insert(string: output, at: .afterSelection) case .appendToAllText: guard let editor = editor else { throw ScriptError.noOutputTarget } editor.insert(string: output, at: .afterAll) case .newDocument: let document = try NSDocumentController.shared.openUntitledDocumentAndDisplay(true) as! any Editable document.insert(string: output, at: .replaceAll) document.selectedRange = NSRange(0..<0) case .pasteBoard: NSPasteboard.general.clearContents() NSPasteboard.general.setString(output, forType: .string) } } } // MARK: - ScriptToken private protocol ScriptToken { static var token: String { get } } private extension ScriptToken where Self: RawRepresentable, Self.RawValue == String { /// read type from script init?(scanning script: String) { let pattern = "%%%\\{" + Self.token + "=" + "(.+)" + "\\}%%%" let regex = try! NSRegularExpression(pattern: pattern) guard let result = regex.firstMatch(in: script, range: script.nsRange) else { return nil } let type = (script as NSString).substring(with: result.range(at: 1)) self.init(rawValue: type) } }
apache-2.0
292a0a14856b26a49c3c1ff66a142429
31.287356
116
0.57565
4.890888
false
false
false
false
maxadamski/SwiftyHTTP
SwiftyHTTP/HTTPConnection/HTTPConnection.swift
2
5878
// // ARIHTTPConnection.swift // SwiftyHTTP // // Created by Helge Hess on 6/5/14. // Copyright (c) 2014 Always Right Institute. All rights reserved. // import Darwin public class HTTPConnection { public let socket : ActiveSocketIPv4 let debugOn = false let parser : HTTPParser public init(_ socket: ActiveSocketIPv4) { self.socket = socket parser = HTTPParser() /* next: configuration, all ivars are setup */ // init sequence issue, connection can't be passed as an unowned? requestQueue.connection = self responseQueue.connection = self parser.onRequest { [unowned self] rq in self.requestQueue.emit (rq) if rq.closeConnection { self.close() } } parser.onResponse { [unowned self] res in self.responseQueue.emit(res) if res.closeConnection { self.close() } } self.socket.isNonBlocking = true self.socket.onRead { [unowned self] in self.handleIncomingData($0, expectedLength: $1) } // look for data already in the queue. // FIXME: This is failing sometimes with 0 bytes. While it's OK to return // 0 bytes, it should fail with an EWOULDBLOCK self.handleIncomingData(self.socket, expectedLength: 1) if debugOn { debugPrint("HC: did init \(self)") } } /* callbacks */ public func onRequest(cb: ((HTTPRequest, HTTPConnection) -> Void)?) -> Self { requestQueue.on = cb return self } public func onResponse(cb: ((HTTPResponse, HTTPConnection) -> Void)?) -> Self { responseQueue.on = cb return self } // FIXME: how to fix init order (cannot pass in 'self') var requestQueue = HTTPEventQueue<HTTPRequest>() var responseQueue = HTTPEventQueue<HTTPResponse>() /* don't want to queue such func onHeaders(cb: ((HTTPMessage, HTTPConnection) -> Bool)?) -> Self { parser.onHeaders(cb ? { cb!($0, self) } : nil) return self } func onBodyData(cb: ((HTTPMessage, HTTPConnection, CString, UInt) -> Bool)?) -> Self { parser.onBodyData(cb ? { cb!($0, self, $1, $2) } : nil) return self } */ public func onClose(cb: ((FileDescriptor) -> Void)?) -> Self { // FIXME: what if the socket was closed already? Need to check for isValid? socket.onClose(cb) return self } public var isValid : Bool { return self.socket.isValid } /* close the connection */ func close(reason: String?) -> Self { if debugOn { debugPrint("HC: closing \(self)") } socket.close() // this is calling master.unregister ... socket.onRead(nil) parser.resetEventHandlers() return self } public func close() { // cannot assign default-arg to reason, makes it a kw arg close(nil) } /* handle incoming data */ func handleIncomingData<T>(socket: ActiveSocket<T>, expectedLength: Int) { // For some reason this is called on a closed socket (in the SwiftyClient). // Not quite sure why, presumably the read-closure is hanging in some queue // on a different thread. // Technically it shouldn't happen as we reset the read closure in the // socket close()? Go figure! ;-) repeat { let (count, block, errno) = socket.read() if debugOn { debugPrint("HC: read \(count) \(errno)") } if count < 0 && errno == EWOULDBLOCK { break } if count < 0 { close("Some socket error \(count): \(errno) ...") return } /* feed HTTP parser */ let rc = parser.write(block, count) if rc != .OK { close("Got parser error: \(rc)") return } // if parser.bodyIsFinal { // I don't really know what this is :-) if count == 0 { close("EOF") return } } while true } } extension HTTPConnection { /* send HTTP messages */ func fixupHeaders(m: HTTPMessage) { if let bodyBuffer = m.bodyAsByteArray { m["Content-Length"] = String(bodyBuffer.count) } } func sendHeaders(m: HTTPMessage) -> Self { // this sends things as UTF-8 which is only right in the very lastest // HTTP revision (before HTTP headers have been Latin1) var s = "" for (key, value) in m.headers { s += "\(key): \(value)\r\n" } s += "\r\n" socket.write(s) // debugPrint("Headers:\r\n \(s)") return self } func sendBody(r: HTTPMessage) { let bodyBuffer = r.bodyAsByteArray if let bb = bodyBuffer { socket.asyncWrite(bb); } } public func sendRequest(rq: HTTPRequest, cb: (()->Void)? = nil) -> Self { // FIXME: it's inefficient to do that many writes fixupHeaders(rq) let requestLine = "\(rq.method.method) \(rq.url) " + "HTTP/\(rq.version.major).\(rq.version.minor)\r\n" if debugOn { debugPrint("HC: sending request \(rq) \(self)") } socket.write(requestLine) sendHeaders(rq) sendBody(rq) if let lcb = cb { lcb() } if debugOn { debugPrint("HC: did enqueue request \(rq) \(self)") } return self } public func sendResponse(res: HTTPResponse, cb: (()->Void)? = nil) -> Self { // FIXME: it's inefficient to do that many writes fixupHeaders(res) let statusLine = "HTTP/\(res.version.major).\(res.version.minor)" + " \(res.status.status) \(res.status.statusText)\r\n" if debugOn { debugPrint("HC: sending response \(res) \(self)") } socket.write(statusLine) sendHeaders(res) sendBody(res) if let lcb = cb { lcb() } if debugOn { debugPrint("HC: did enqueue response \(res) \(self)") } return self } } extension HTTPConnection : CustomStringConvertible { public var description : String { return "<HTTPConnection \(socket)>" } }
mit
67dc7356a732b82b5f0c48ea82c8f131
24.780702
81
0.598843
3.998639
false
false
false
false
dipen30/Qmote
KodiRemote/Pods/UPnAtom/Source/HTTP Client Session Managers and Serializers/SOAPSerialization.swift
1
5590
// // SOAPSerialization.swift // ControlPointDemo // // SOAPSerialization.swift // // Copyright (c) 2015 David Robles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import AFNetworking import Ono open class SOAPRequestSerializer: AFHTTPRequestSerializer { open class Parameters { let soapAction: String let serviceURN: String let arguments: NSDictionary? public init(soapAction: String, serviceURN: String, arguments: NSDictionary?) { self.soapAction = soapAction self.serviceURN = serviceURN self.arguments = arguments } } override open func request(bySerializingRequest request: URLRequest, withParameters parameters: Any?, error: NSErrorPointer) -> URLRequest? { guard let requestParameters = parameters as? Parameters else { return nil } let mutableRequest: NSMutableURLRequest = (request as NSURLRequest).mutableCopy() as! NSMutableURLRequest for (field, value) in self.httpRequestHeaders { if let field = field as? String, let value = value as? String , request.value(forHTTPHeaderField: field) == nil { mutableRequest.setValue(value, forHTTPHeaderField: field) } } if mutableRequest.value(forHTTPHeaderField: "Content-Type") == nil { let charSet = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue)) mutableRequest.setValue("text/xml; charset=\"\(charSet)\"", forHTTPHeaderField: "Content-Type") } mutableRequest.setValue("\"\(requestParameters.serviceURN)#\(requestParameters.soapAction)\"", forHTTPHeaderField: "SOAPACTION") var body = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" body += "<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" body += "<s:Body>" body += "<u:\(requestParameters.soapAction) xmlns:u=\"\(requestParameters.serviceURN)\">" if let arguments = requestParameters.arguments { for (key, value) in arguments { body += "<\(key)>\(value)</\(key)>" } } body += "</u:\(requestParameters.soapAction)>" body += "</s:Body></s:Envelope>" LogVerbose("SOAP request body: \(body)") mutableRequest.setValue("\(body.utf8.count)", forHTTPHeaderField: "Content-Length") mutableRequest.httpBody = body.data(using: String.Encoding.utf8, allowLossyConversion: false) return mutableRequest as URLRequest } } open class SOAPResponseSerializer: AFXMLParserResponseSerializer { open func responseObject(for response: URLResponse?, data: Data?, error: NSErrorPointer) -> AnyObject? { do { try validate(response as! HTTPURLResponse, data: data) } catch { return nil } let xmlParser = SOAPResponseParser() guard let data = data else { return nil } switch xmlParser.parse(soapResponseData: data) { case .success(let value): return value as AnyObject? case .failure(let error): return nil } } } class SOAPResponseParser: AbstractDOMXMLParser { fileprivate var _responseParameters = [String: String]() override func parse(document: ONOXMLDocument) -> EmptyResult { var result: EmptyResult = .success document.enumerateElements(withXPath: "/s:Envelope/s:Body/*/*", using: { (element: ONOXMLElement?, index: UInt, stop: UnsafeMutablePointer<ObjCBool>?) -> Void in if let elementTag = element?.tag, let elementValue = element?.stringValue() , elementTag.characters.count > 0 && elementValue.characters.count > 0 && elementValue != "NOT_IMPLEMENTED" { self._responseParameters[elementTag] = elementValue } result = .success }) LogVerbose("SOAP response values: \(prettyPrint(_responseParameters))") return result } func parse(soapResponseData: Data) -> Result<[String: String]> { switch super.parse(data: soapResponseData) { case .success: return .success(_responseParameters) case .failure(let error): return .failure(error) } } }
apache-2.0
15537dce2c85923195cd05f7f07f2c1d
40.716418
169
0.646691
4.991071
false
false
false
false
noahprince22/StrollSafe_iOS
Stroll SafeTests/View Controllers/PinpadViewControllSpec.swift
1
8967
// // PinpadViewControllSpec.swift // Stroll Safe // // Created by Noah Prince on 7/26/15. // Copyright © 2015 Stroll Safe. All rights reserved. // import Foundation import Quick import Nimble @testable import Stroll_Safe class PinpadViewControllerSpec: QuickSpec { override func spec() { describe ("the view") { class Delegate: PinpadViewDelegate { func passEntered(controller: PinpadViewController, pass: String) { // do nothing } } var viewController: Stroll_Safe.PinpadViewController! beforeEach { let storyboard = UIStoryboard(name: "Main", bundle: nil) viewController = storyboard.instantiateViewControllerWithIdentifier( "Pinpad") as! Stroll_Safe.PinpadViewController viewController.beginAppearanceTransition(true, animated: false) viewController.endAppearanceTransition() viewController.delegate = Delegate() } func expectClear() { // All should still be unfilled expect(viewController.first.hidden).to(beTrue()) expect(viewController.second.hidden).to(beTrue()) expect(viewController.third.hidden).to(beTrue()) expect(viewController.fourth.hidden).to(beTrue()) } it ("starts out cleared") { expectClear(); } // The following three should cover all number presses describe ("number buttons") { it ("fills placeholders for numbers") { expect(viewController.first.hidden).to(beTrue()) viewController.buttonOne(self) expect(viewController.first.hidden).to(beFalse()) expect(viewController.second.hidden).to(beTrue()) viewController.buttonTwo(self) expect(viewController.second.hidden).to(beFalse()) expect(viewController.third.hidden).to(beTrue()) viewController.buttonThree(self) expect(viewController.third.hidden).to(beFalse()) expect(viewController.fourth.hidden).to(beTrue()) viewController.buttonFour(self) expect(viewController.fourth.hidden).to(beFalse()) } it ("does not enter more numbers when over four are type") { viewController.buttonFive(self) viewController.buttonSix(self) viewController.buttonSeven(self) viewController.buttonEight(self) viewController.buttonNine(self) viewController.buttonZero(self) // All should still be filled expect(viewController.first.hidden).to(beFalse()) expect(viewController.second.hidden).to(beFalse()) expect(viewController.third.hidden).to(beFalse()) expect(viewController.fourth.hidden).to(beFalse()) } } describe ("the back button") { it("unfills the first placeholder") { viewController.buttonFive(self) viewController.buttonBack(self) expect(viewController.first.hidden).to(beTrue()) } it ("unfills the second placeholder") { viewController.buttonSix(self) viewController.buttonSeven(self) viewController.buttonBack(self) expect(viewController.second.hidden).to(beTrue()) } it ("unfills the third placeholder") { viewController.buttonSeven(self) viewController.buttonEight(self) viewController.buttonEight(self) viewController.buttonBack(self) expect(viewController.third.hidden).to(beTrue()) } it ("unfills the fourth placeholder") { viewController.buttonSeven(self) viewController.buttonEight(self) viewController.buttonEight(self) viewController.buttonOne(self) viewController.buttonBack(self) expect(viewController.fourth.hidden).to(beTrue()) } it ("can unfil multiple placeholders") { viewController.buttonSeven(self) viewController.buttonEight(self) viewController.buttonEight(self) viewController.buttonOne(self) viewController.buttonBack(self) expect(viewController.fourth.hidden).to(beTrue()) viewController.buttonBack(self) expect(viewController.third.hidden).to(beTrue()) viewController.buttonBack(self) expect(viewController.second.hidden).to(beTrue()) viewController.buttonBack(self) expect(viewController.first.hidden).to(beTrue()) } it ("continues in the correct position after a back") { viewController.buttonOne(self) viewController.buttonTwo(self) viewController.buttonThree(self) viewController.buttonBack(self) viewController.buttonOne(self) expect(viewController.first.hidden).to(beFalse()) expect(viewController.second.hidden).to(beFalse()) expect(viewController.third.hidden).to(beFalse()) expect(viewController.fourth.hidden).to(beTrue()) } it ("does not do anything when it backspaces nothing") { viewController.buttonBack(self) expectClear() } } describe ("the clear button") { it ("does nothing when nothing has been entered") { viewController.buttonClear(self) expectClear() } it ("clears when only partially full") { viewController.buttonSix(self) viewController.buttonSeven(self) viewController.buttonClear(self) expectClear(); } it ("clears when all are full") { viewController.buttonSeven(self) viewController.buttonEight(self) viewController.buttonEight(self) viewController.buttonOne(self) viewController.buttonClear(self) expectClear(); } it ("allows typing after a clear") { viewController.buttonOne(self) viewController.buttonClear(self) viewController.buttonTwo(self) expect(viewController.first.hidden).to(beFalse()) } } it ("runs my function on completion with the correct pass") { class thing: PinpadViewDelegate { var functionCalled = false var mainPass = "1234" func passEntered(controller: PinpadViewController, pass: String) { expect(pass).to(equal("1234")) controller.clear() functionCalled = true } } let del = thing() viewController.delegate = del viewController.buttonOne(self) viewController.buttonTwo(self) viewController.buttonThree(self) viewController.buttonFour(self) expect(del.functionCalled).to(beTrue()) expectClear(); } } } }
apache-2.0
a36a73e2a155d72f1d4a67222c55f268
39.391892
86
0.477805
6.492397
false
false
false
false
eljeff/AudioKit
Sources/AudioKit/Nodes/Generators/Physical Models/Clarinet.swift
1
2355
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation import CAudioKit #if !os(tvOS) /// STK Clarinet /// public class Clarinet: Node, AudioUnitContainer, Tappable, Toggleable { /// Unique four-letter identifier "clar" public static let ComponentDescription = AudioComponentDescription(instrument: "clar") /// Internal type of audio unit for this node public typealias AudioUnitType = InternalAU /// Internal audio unit public private(set) var internalAU: AudioUnitType? /// INternal audio unti for clarinet public class InternalAU: AudioUnitBase { /// Create the clarinet DSP /// - Returns: DSP Reference public override func createDSP() -> DSPRef { return akCreateDSP("ClarinetDSP") } /// Trigger a clarinet note /// - Parameters: /// - note: MIDI Note Number /// - velocity: MIDI Velocity public func trigger(note: MIDINoteNumber, velocity: MIDIVelocity) { if let midiBlock = scheduleMIDIEventBlock { let event = MIDIEvent(noteOn: note, velocity: velocity, channel: 0) event.data.withUnsafeBufferPointer { ptr in guard let ptr = ptr.baseAddress else { return } midiBlock(AUEventSampleTimeImmediate, 0, event.data.count, ptr) } } } } // MARK: - Initialization /// Initialize the STK Clarinet model /// /// - Parameters: /// - note: MIDI note number /// - velocity: Amplitude or volume expressed as a MIDI Velocity 0-127 /// public init() { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType } } /// Trigger the sound with a set of parameters /// /// - Parameters: /// - note: MIDI note number /// - velocity: Amplitude or volume expressed as a MIDI Velocity 0-127 /// public func trigger(note: MIDINoteNumber, velocity: MIDIVelocity = 127) { internalAU?.start() internalAU?.trigger(note: note, velocity: velocity) } } #endif
mit
aceb710cca3efa95cb11fcf2cfedbcc2
29.192308
100
0.621231
4.926778
false
false
false
false
jhong70/JKHImageZoomTransition
Example/TransitionPlayer/TransitionPlayer/JKHCorgiTableViewController.swift
1
3233
// // JKHCorgiTableViewController.swift // TransitionPlayer // // Created by Joon Hong on 8/4/16. // Copyright © 2016 JoonKiHong. All rights reserved. // import UIKit class JKHCorgiTableViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var corgiImages = [UIImage]() var selectedCorgiCell: JKHCorgiTableViewCell? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. for i in 1...7 { if let image = UIImage(named: "corgi-\(i)") { corgiImages.append(image) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let selectedRow = tableView.indexPathForSelectedRow { tableView.deselectRow(at: selectedRow, animated: animated) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let vc = segue.destination as! JKHCorgiDetailViewController vc.image = selectedCorgiCell?.corgiImageView.image vc.customTransition = true } } // MARK: - UITableViewDelegate/Datasource extension JKHCorgiTableViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return corgiImages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "JKHCorgiTableViewCell") as! JKHCorgiTableViewCell cell.corgiImageView.image = corgiImages[indexPath.row] cell.corgiTitleLabel.text = "Corgi number #\(indexPath.row)" return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedCorgiCell = tableView.cellForRow(at: indexPath) as? JKHCorgiTableViewCell performSegue(withIdentifier: "CorgiDetailSegue", sender: self) } } // MARK: - JKHImageZoomTransitionAnimating extension JKHCorgiTableViewController: JKHImageZoomTransitionProtocol { func transitionFromImageView() -> UIImageView { let imageView = selectedCorgiCell!.corgiImageView imageView?.isHidden = true return imageView! } func transitionToImageView() -> UIImageView { let imageView = selectedCorgiCell!.corgiImageView imageView?.isHidden = true return imageView! } func transitionDidFinish(_ completed: Bool, finalImage: UIImage) { if completed { guard let cell = selectedCorgiCell else { return } let imageView = cell.corgiImageView imageView?.isHidden = false } } }
mit
25746893bae499eac753ec4ddf22e0fc
26.159664
115
0.629332
5.255285
false
false
false
false
WangCrystal/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Dialogs/Cells/DialogCell.swift
4
6208
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit; class DialogCell: UITableViewCell { let avatarView = AvatarView(frameSize: 48, type: .Rounded) let titleView: UILabel = UILabel() let messageView: UILabel = UILabel() let dateView: UILabel = UILabel() let statusView: UIImageView = UIImageView() let separatorView = TableViewSeparator(color: MainAppTheme.list.separatorColor) let unreadView: UILabel = UILabel() let unreadViewBg: UIImageView = UIImageView() var bindedFile: jlong? = nil; var avatarCallback: CocoaDownloadCallback? = nil; init(reuseIdentifier:String) { super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier) backgroundColor = MainAppTheme.list.bgColor titleView.font = UIFont(name: "Roboto-Medium", size: 19); titleView.textColor = MainAppTheme.list.dialogTitle messageView.font = UIFont(name: "HelveticaNeue", size: 16); messageView.textColor = MainAppTheme.list.dialogText dateView.font = UIFont(name: "HelveticaNeue", size: 14); dateView.textColor = MainAppTheme.list.dialogDate dateView.textAlignment = NSTextAlignment.Right; statusView.contentMode = UIViewContentMode.Center; unreadView.font = UIFont(name: "HelveticaNeue", size: 14); unreadView.textColor = MainAppTheme.list.unreadText unreadView.textAlignment = .Center unreadViewBg.image = Imaging.imageWithColor(MainAppTheme.list.unreadBg, size: CGSizeMake(18, 18)) .roundImage(18).resizableImageWithCapInsets(UIEdgeInsetsMake(9, 9, 9, 9)) self.contentView.addSubview(avatarView) self.contentView.addSubview(titleView) self.contentView.addSubview(messageView) self.contentView.addSubview(dateView) self.contentView.addSubview(statusView) self.contentView.addSubview(separatorView) self.contentView.addSubview(unreadViewBg) self.contentView.addSubview(unreadView) let selectedView = UIView() selectedView.backgroundColor = MainAppTheme.list.bgSelectedColor selectedBackgroundView = selectedView } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bindDialog(dialog: ACDialog, isLast:Bool) { self.avatarView.bind(dialog.getDialogTitle(), id: dialog.getPeer().getPeerId(), avatar: dialog.getDialogAvatar()); self.titleView.text = dialog.getDialogTitle(); self.messageView.text = Actor.getFormatter().formatDialogText(dialog) if (dialog.getDate() > 0) { self.dateView.text = Actor.getFormatter().formatShortDate(dialog.getDate()); self.dateView.hidden = false; } else { self.dateView.hidden = true; } if (dialog.getUnreadCount() != 0) { self.unreadView.text = "\(dialog.getUnreadCount())" self.unreadView.hidden = false self.unreadViewBg.hidden = false } else { self.unreadView.hidden = true self.unreadViewBg.hidden = true } let messageState = UInt(dialog.getStatus().ordinal()); if (messageState == ACMessageState.PENDING.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogSending self.statusView.image = Resources.iconClock; self.statusView.hidden = false; } else if (messageState == ACMessageState.READ.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogRead self.statusView.image = Resources.iconCheck2; self.statusView.hidden = false; } else if (messageState == ACMessageState.RECEIVED.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogReceived self.statusView.image = Resources.iconCheck2; self.statusView.hidden = false; } else if (messageState == ACMessageState.SENT.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogSent self.statusView.image = Resources.iconCheck1; self.statusView.hidden = false; } else if (messageState == ACMessageState.ERROR.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogError self.statusView.image = Resources.iconError; self.statusView.hidden = false; } else { self.statusView.hidden = true; } self.separatorView.hidden = isLast; setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews(); // We expect height == 76; let width = self.contentView.frame.width; let leftPadding = CGFloat(76); let padding = CGFloat(14); avatarView.frame = CGRectMake(padding, padding, 48, 48); titleView.frame = CGRectMake(leftPadding, 18, width - leftPadding - /*paddingRight*/(padding + 50), 18); var messagePadding:CGFloat = 0; if (!self.statusView.hidden) { messagePadding = 22; statusView.frame = CGRectMake(leftPadding, 44, 20, 18); } var unreadPadding = CGFloat(0) if (!self.unreadView.hidden) { unreadView.frame = CGRectMake(0, 0, 1000, 1000) unreadView.sizeToFit() let unreadW = max(unreadView.frame.width + 8, 18) unreadView.frame = CGRectMake(width - padding - unreadW, 44, unreadW, 18) unreadViewBg.frame = unreadView.frame unreadPadding = unreadW } messageView.frame = CGRectMake(leftPadding+messagePadding, 44, width - leftPadding - /*paddingRight*/padding - messagePadding - unreadPadding, 18); dateView.frame = CGRectMake(width - /*width*/60 - /*paddingRight*/padding , 18, 60, 18); separatorView.frame = CGRectMake(leftPadding, 75.5, width, 0.5); } }
mit
7e04c4096a20b855072cd7dbe8d611be
39.581699
155
0.632571
4.804954
false
false
false
false
Quick/Nimble
Sources/Nimble/Matchers/RaisesException.swift
15
7284
// This matcher requires the Objective-C, and being built by Xcode rather than the Swift Package Manager #if canImport(Darwin) && !SWIFT_PACKAGE import class Foundation.NSObject import class Foundation.NSDictionary import class Foundation.NSException /// A Nimble matcher that succeeds when the actual expression raises an /// exception with the specified name, reason, and/or userInfo. /// /// Alternatively, you can pass a closure to do any arbitrary custom matching /// to the raised exception. The closure only gets called when an exception /// is raised. /// /// nil arguments indicates that the matcher should not attempt to match against /// that parameter. public func raiseException<Out>( named: NSExceptionName? = nil, reason: String? = nil, userInfo: NSDictionary? = nil, closure: ((NSException) -> Void)? = nil ) -> Predicate<Out> { return raiseException(named: named?.rawValue, reason: reason, userInfo: userInfo, closure: closure) } /// A Nimble matcher that succeeds when the actual expression raises an /// exception with the specified name, reason, and/or userInfo. /// /// Alternatively, you can pass a closure to do any arbitrary custom matching /// to the raised exception. The closure only gets called when an exception /// is raised. /// /// nil arguments indicates that the matcher should not attempt to match against /// that parameter. public func raiseException<Out>( named: String?, reason: String? = nil, userInfo: NSDictionary? = nil, closure: ((NSException) -> Void)? = nil ) -> Predicate<Out> { return Predicate { actualExpression in var exception: NSException? let capture = NMBExceptionCapture(handler: ({ e in exception = e }), finally: nil) do { try capture.tryBlockThrows { _ = try actualExpression.evaluate() } } catch { return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>")) } let message = messageForException( exception: exception, named: named, reason: reason, userInfo: userInfo, closure: closure ) let matches = exceptionMatchesNonNilFieldsOrClosure( exception, named: named, reason: reason, userInfo: userInfo, closure: closure ) return PredicateResult(bool: matches, message: message) } } internal func messageForException( exception: NSException?, named: String?, reason: String?, userInfo: NSDictionary?, closure: ((NSException) -> Void)? ) -> ExpectationMessage { var rawMessage: String = "raise exception" if let named = named { rawMessage += " with name <\(named)>" } if let reason = reason { rawMessage += " with reason <\(reason)>" } if let userInfo = userInfo { rawMessage += " with userInfo <\(userInfo)>" } if closure != nil { rawMessage += " that satisfies block" } if named == nil && reason == nil && userInfo == nil && closure == nil { rawMessage = "raise any exception" } let actual: String if let exception = exception { // swiftlint:disable:next line_length actual = "\(String(describing: type(of: exception))) { name=\(exception.name), reason='\(stringify(exception.reason))', userInfo=\(stringify(exception.userInfo)) }" } else { actual = "no exception" } return .expectedCustomValueTo(rawMessage, actual: actual) } internal func exceptionMatchesNonNilFieldsOrClosure( _ exception: NSException?, named: String?, reason: String?, userInfo: NSDictionary?, closure: ((NSException) -> Void)?) -> Bool { var matches = false if let exception = exception { matches = true if let named = named, exception.name.rawValue != named { matches = false } if reason != nil && exception.reason != reason { matches = false } if let userInfo = userInfo, let exceptionUserInfo = exception.userInfo, (exceptionUserInfo as NSDictionary) != userInfo { matches = false } if let closure = closure { let assertions = gatherFailingExpectations { closure(exception) } let messages = assertions.map { $0.message } if messages.count > 0 { matches = false } } } return matches } public class NMBObjCRaiseExceptionPredicate: NMBPredicate { private let _name: String? private let _reason: String? private let _userInfo: NSDictionary? private let _block: ((NSException) -> Void)? fileprivate init(name: String?, reason: String?, userInfo: NSDictionary?, block: ((NSException) -> Void)?) { _name = name _reason = reason _userInfo = userInfo _block = block let predicate: Predicate<NSObject> = raiseException( named: name, reason: reason, userInfo: userInfo, closure: block ) let predicateBlock: PredicateBlock = { actualExpression in return try predicate.satisfies(actualExpression).toObjectiveC() } super.init(predicate: predicateBlock) } @objc public var named: (_ name: String) -> NMBObjCRaiseExceptionPredicate { let (reason, userInfo, block) = (_reason, _userInfo, _block) return { name in return NMBObjCRaiseExceptionPredicate( name: name, reason: reason, userInfo: userInfo, block: block ) } } @objc public var reason: (_ reason: String?) -> NMBObjCRaiseExceptionPredicate { let (name, userInfo, block) = (_name, _userInfo, _block) return { reason in return NMBObjCRaiseExceptionPredicate( name: name, reason: reason, userInfo: userInfo, block: block ) } } @objc public var userInfo: (_ userInfo: NSDictionary?) -> NMBObjCRaiseExceptionPredicate { let (name, reason, block) = (_name, _reason, _block) return { userInfo in return NMBObjCRaiseExceptionPredicate( name: name, reason: reason, userInfo: userInfo, block: block ) } } @objc public var satisfyingBlock: (_ block: ((NSException) -> Void)?) -> NMBObjCRaiseExceptionPredicate { let (name, reason, userInfo) = (_name, _reason, _userInfo) return { block in return NMBObjCRaiseExceptionPredicate( name: name, reason: reason, userInfo: userInfo, block: block ) } } } extension NMBPredicate { @objc public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionPredicate { return NMBObjCRaiseExceptionPredicate(name: nil, reason: nil, userInfo: nil, block: nil) } } #endif
apache-2.0
f6e42c271cdc2c437533795f8ce7f81f
31.810811
172
0.592532
5.023448
false
false
false
false
peferron/algo
EPI/Heaps/Implement a stack API using a heap/swift/heap.swift
2
1832
class Heap<T> { let higherPriority: (T, T) -> Bool private var array = [T]() var count: Int { return array.count } init(higherPriority: @escaping (T, T) -> Bool) { self.higherPriority = higherPriority } private func parentIndex(_ i: Int) -> Int? { return i > 0 ? (i - 1) / 2 : nil } private func swap(_ i: Int, _ j: Int) { (array[i], array[j]) = (array[j], array[i]) } private func bubbleUp(_ i: Int) { if let pi = parentIndex(i), higherPriority(array[i], array[pi]) { swap(i, pi) bubbleUp(pi) } } func insert(_ element: T) { array.append(element) bubbleUp(array.count - 1) } private func leftChildIndex(_ i: Int) -> Int? { let lci = i * 2 + 1 return lci < array.count ? lci : nil } private func rightChildIndex(_ i: Int) -> Int? { let rci = i * 2 + 2 return rci < array.count ? rci : nil } private func bubbleDown(_ i: Int) { if let lci = leftChildIndex(i) { let priorityChildIndex: Int if let rci = rightChildIndex(i), higherPriority(array[rci], array[lci]) { priorityChildIndex = rci } else { priorityChildIndex = lci } if higherPriority(array[priorityChildIndex], array[i]) { swap(priorityChildIndex, i) bubbleDown(priorityChildIndex) } } } func removeHighestPriority() -> T? { switch array.count { case 0: return nil case 1: return array.removeLast() default: let first = array[0] array[0] = array.removeLast() bubbleDown(0) return first } } }
mit
f29e1322d85f4c3efb205b6bf9ff2466
24.444444
85
0.501092
3.91453
false
false
false
false
IvanVorobei/Sparrow
sparrow/modules/rate-app/types/dialog/banner-with-indicator/views/SPRateAppBannerWithIndicatorAlertView.swift
2
2836
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPRateAppBannerWithIndicatorAlertView: UIView { let label = UILabel() let button: SPRateAppBannerWithIndicatorTwiceButton init(title: String, buttonTitle: String, firstColor: UIColor, secondColor: UIColor) { self.button = SPRateAppBannerWithIndicatorTwiceButton.init(title: buttonTitle, normalColor: firstColor, selectedColor: secondColor) super.init(frame: CGRect.zero) self.label.textColor = firstColor self.label.font = UIFont.fonts.AvenirNext(type: .Bold, size: 16) self.label.text = title self.label.adjustsFontSizeToFitWidth = true self.label.minimumScaleFactor = 0.5 self.label.numberOfLines = 0 self.addSubview(self.label) self.addSubview(button) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.label.setEqualsFrameFromBounds(self, withWidthFactor: 0.4, maxWidth: nil, withHeightFactor: 0.6, maxHeight: nil, withCentering: false) self.label.frame.origin.y = (self.frame.height - self.label.frame.height) / 2 let space = (self.frame.height - self.label.frame.height) * 0.8 self.label.frame.origin.x = space let buttonWidth: CGFloat = self.frame.width - self.label.frame.bottomXPosition - space * 1.5 self.button.frame = CGRect.init(x: self.label.frame.bottomXPosition + space / 2, y: 0, width: buttonWidth, height: self.frame.height * 0.465) self.button.center.y = self.frame.height / 2 } }
mit
af0366cad5107777c02d3af92905b848
45.47541
149
0.706878
4.308511
false
false
false
false
benlangmuir/swift
benchmark/single-source/CharacterLiteralsSmall.swift
10
2114
//===--- CharacterLiteralsSmall.swift -------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test tests the performance of Characters initialized from literals that // fit within the small (63 bits or fewer) representation and can be // represented as a packed integer. import TestsUtils public let benchmarks = BenchmarkInfo( name: "CharacterLiteralsSmall", runFunction: run_CharacterLiteralsSmall, tags: [.validation, .api, .String]) @inline(never) func makeCharacter_UTF8Length1() -> Character { return "a" } @inline(never) func makeCharacter_UTF8Length2() -> Character { return "\u{00a9}" } @inline(never) func makeCharacter_UTF8Length3() -> Character { return "a\u{0300}" } @inline(never) func makeCharacter_UTF8Length4() -> Character { return "\u{00a9}\u{0300}" } @inline(never) func makeCharacter_UTF8Length5() -> Character { return "a\u{0300}\u{0301}" } @inline(never) func makeCharacter_UTF8Length6() -> Character { return "\u{00a9}\u{0300}\u{0301}" } @inline(never) func makeCharacter_UTF8Length7() -> Character { return "a\u{0300}\u{0301}\u{0302}" } @inline(never) func makeCharacter_UTF8Length8() -> Character { return "\u{00a9}\u{0300}\u{0301}\u{0302}" } @inline(never) func makeLiterals() { blackHole(makeCharacter_UTF8Length1()) blackHole(makeCharacter_UTF8Length2()) blackHole(makeCharacter_UTF8Length3()) blackHole(makeCharacter_UTF8Length4()) blackHole(makeCharacter_UTF8Length5()) blackHole(makeCharacter_UTF8Length6()) blackHole(makeCharacter_UTF8Length7()) blackHole(makeCharacter_UTF8Length8()) } public func run_CharacterLiteralsSmall(_ n: Int) { for _ in 0...10000 * n { makeLiterals() } }
apache-2.0
797a7ae3f6dbbc1117fe60eb59566ca4
25.425
80
0.681646
3.638554
false
false
false
false
j-chao/venture
source/venture/FlightDetailsVC.swift
1
2116
// // FlightDetailsVC.swift // venture // // Created by Justin Chao on 4/18/17. // Copyright © 2017 Group1. All rights reserved. // import UIKit class FlightDetailsVC: UIViewController { var departureTimeDate:Date! var arrivalTimeDate:Date! var departureTimeStr:String! var arrivalTimeStr:String! var duration:String! var saleTotal:String! var flightNumber:String! var tripDate:String! var eventDate:Date! var destArrival:String! @IBOutlet weak var destArrivalLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var flightLabel: UILabel! @IBOutlet weak var airlineLabel: UILabel! @IBOutlet weak var departureLabel: UILabel! @IBOutlet weak var arrivalLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var costLabel: UILabel! override func viewDidLoad() { self.setBackground() super.viewDidLoad() self.departureTimeStr = stringTimefromDate(date: departureTimeDate) self.arrivalTimeStr = stringTimefromDate(date: arrivalTimeDate) self.destArrivalLabel.text = self.destArrival self.dateLabel.text = stringLongFromDate(date: eventDate) self.flightLabel.text = self.flightNumber self.departureLabel.text = self.departureTimeStr self.arrivalLabel.text = self.arrivalTimeStr self.durationLabel.text = self.duration self.costLabel.text = self.saleTotal } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toEventFromFlight"{ if let destinationVC = segue.destination as? AddEventVC { destinationVC.fromFlight = true destinationVC.fromFoodorPlace = false destinationVC.eventDate = self.eventDate destinationVC.eventDescStr = self.destArrival destinationVC.eventLocStr = self.destArrival.substring(to: 4) destinationVC.flightTime = self.departureTimeDate } } } }
mit
f6b8e58a5c9965c3becc3406b03df4c9
31.045455
77
0.666194
4.607843
false
false
false
false
nakau1/NerobluCore
NerobluCore/NBNotification.swift
1
4845
// ============================================================================= // NerobluCore // Copyright (C) NeroBlu. All rights reserved. // ============================================================================= import UIKit // MARK: - App拡張 - public extension App { /// 通知処理 public class Notify { /// 通知の監視を開始する /// - parameter observer: 監視するオブジェクト /// - parameter selectorName: 通知受信時に動作するセレクタ /// - parameter name: 通知文字列 /// - parameter object: 監視対象のオブジェクト public class func add(observer: AnyObject, _ selectorName: String, _ name: String, _ object: AnyObject? = nil) { NSNotificationCenter.defaultCenter().addObserver(observer, selector: Selector(selectorName), name: name, object: object) } /// 通知の監視を終了する /// - parameter observer: 監視解除するオブジェクト /// - parameter name: 通知文字列 /// - parameter object: 監視対象のオブジェクト public class func remove(observer: AnyObject, _ name: String, _ object: AnyObject? = nil) { NSNotificationCenter.defaultCenter().removeObserver(observer, name: name, object: object) } /// 渡したNSNotificationオブジェクトに紐づく通知監視を終了する /// - parameter observer: 監視するオブジェクト /// - parameter notification: NSNotificationオブジェクト public class func remove(observer: NSObject, _ notification: NSNotification) { NSNotificationCenter.defaultCenter().removeObserver(observer, notification: notification) } /// 通知を行う /// - parameter name: 通知文字列 /// - parameter object: 通知をするオブジェクト /// - parameter userInfo: 通知に含める情報 public class func post(name: String, _ object: AnyObject? = nil, _ userInfo: [NSObject : AnyObject]? = nil) { NSNotificationCenter.defaultCenter().postNotificationName(name, object: object, userInfo: userInfo) } } } // MARK: - NSNotificationCenterの拡張 - public extension NSNotificationCenter { /// 通知の監視開始/終了の設定を一括で行う /// - parameter selectorAndNotificationNames: 通知時に実行するセレクタ名と通知文字列をセットにした辞書 /// - parameter observer: 監視するオブジェクト /// - parameter start: 監視の開始または終了 public func observeNotifications(selectorAndNotificationNames: [String : String], observer: AnyObject, start: Bool) { for e in selectorAndNotificationNames { let name = e.1 if start { let selector = Selector(e.0) self.addObserver(observer, selector: selector, name: name, object: nil) } else { self.removeObserver(observer, name: name, object: nil) } } } /// 渡したNSNotificationオブジェクトに紐づく通知監視を解除する /// - parameter observer: 監視するオブジェクト /// - parameter notification: NSNotificationオブジェクト public func removeObserver(observer: NSObject, notification: NSNotification) { self.removeObserver(observer, name: notification.name, object: notification.object) } } // MARK: - NBViewController拡張 - public extension NBViewController { /// 監視する通知とそのセレクタの設定を返却する /// /// 例えば下記のように実装するとキーボードイベントがハンドルできます /// /// func keyboardWillChangeFrame(n: NSNotification) { /// // 何か処理 /// } /// /// override func observingNotifications() -> [String : String] { /// var ret = super.observingNotifications() /// ret["keyboardWillChangeFrame:"] = UIKeyboardWillChangeFrameNotification /// return ret /// } /// /// - returns: 通知時に実行するセレクタ名と通知文字列をセットにした辞書 public func observingNotifications() -> [String : String] { return [:] } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().observeNotifications(self.observingNotifications(), observer:self, start: true) } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().observeNotifications(self.observingNotifications(), observer:self, start: false) } }
apache-2.0
e3f4bdd65a0a5539df440f7c63e041de
38.009434
132
0.615719
4.584257
false
false
false
false
michelleran/FicFeed
iOS/FicFeed/FeedController.swift
1
3594
// // FeedController.swift // FicFeed // // Created by Michelle Ran on 7/24/16. // Copyright © 2016 Michelle Ran LLC. All rights reserved. // import UIKit import MWFeedParser import Firebase import FirebaseMessaging class FeedController: UITableViewController, MWFeedParserDelegate { @IBOutlet var button: UIBarButtonItem! @IBAction func pressed(sender: UIBarButtonItem) { if sender.title == "Track" { Cloud.subscribeTo(feedId) sender.title = "Untrack" } else { Cloud.unsubscribeFrom(feedId) sender.title = "Track" } } var url: NSURL? var parser: MWFeedParser! var feedId: Int = 0 var feedTitle: String = "Feed" var fics: [[String: String]] = [] var refresh: UIRefreshControl! override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 150.0 navigationItem.title = feedTitle if let u = url { parser = MWFeedParser(feedURL: u) parser.delegate = self parser.parse() refresh = UIRefreshControl() refresh.addTarget(self, action: #selector(FeedController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged) refreshControl = refresh } else { Popup.pop("Error", message: "Couldn't load feed.", sender: self) } } override func viewWillAppear(animated: Bool) { Cloud.getSubscribedTags { (subscribed: [Int]) in if subscribed.contains(self.feedId) { self.button.title = "Untrack" } else { self.button.title = "Track" } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refresh(refreshControl: UIRefreshControl) { fics.removeAll() parser.parse() // a very clunky refresh method for rn refreshControl.endRefreshing() } func feedParser(parser: MWFeedParser!, didParseFeedItem item: MWFeedItem!) { var info = Extrekt.extractInfo(item.summary) info["author"] = item.author info["title"] = Extrekt.charHelper(item.title) info["link"] = item.link fics.append(info) } func feedParserDidFinish(parser: MWFeedParser!) { tableView.reloadData() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fics.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: FicCell = tableView.dequeueReusableCellWithIdentifier("FicCell", forIndexPath: indexPath) as! FicCell let fic = fics[indexPath.row] cell.title.text = fic["title"] cell.author.text = "by " + fic["author"]! cell.warnings.text = fic["warnings"] cell.relationships.text = fic["ships"] cell.summary.text = fic["summary"] cell.rating.text = fic ["rating"] return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let ficController = segue.destinationViewController as? FicController { let selected = fics[tableView.indexPathForSelectedRow!.row] ficController.ficTitle = selected["title"]! ficController.link = NSURL(string: selected["link"]!)! } } }
mit
5e17f672db44e142b452acf7bcb95330
31.963303
130
0.623713
4.709043
false
false
false
false
GraphStory/neo4j-ios
Sources/Theo/Model/Path.swift
2
2591
import Foundation import Bolt import PackStream public typealias Segment = Relationship public class Path: ResponseItem { public var segments: [Segment] = [] internal var nodes: [Node] internal var unboundRelationships: [UnboundRelationship] internal var sequence: [Int] init?(data: PackProtocol) { if let s = data as? Structure, s.signature == 80, s.items.count >= 3, let nodeStructs = (s.items[0] as? List)?.items, let unboundRelationshipsStructures = (s.items[1] as? List)?.items, let sequenceValues = (s.items[2] as? List)?.items { let nodes = nodeStructs.flatMap { Node(data: $0) } let unboundRelationships = unboundRelationshipsStructures.flatMap { UnboundRelationship(data: $0) } let sequence = sequenceValues.flatMap { $0.intValue() }.flatMap { Int($0) } self.nodes = nodes self.unboundRelationships = unboundRelationships self.sequence = sequence assert(sequence.count % 2 == 0) // S must always consist of an even number of integers, or be empty generateSegments(fromNodeSequenceIndex: nil) self.nodes = [] self.unboundRelationships = [] self.sequence = [] } else { return nil } } func generateSegments(fromNodeSequenceIndex: Int?) { let fromNodeIndex: Int if let fromNodeSequenceIndex = fromNodeSequenceIndex { fromNodeIndex = sequence[fromNodeSequenceIndex] } else { fromNodeIndex = 0 } let toNodeIndex = sequence[fromNodeIndex + 2] let fromNode = nodes[fromNodeIndex] let toNode = nodes[toNodeIndex] let unboundRelationshipIndex = sequence[fromNodeIndex + 1] assert(unboundRelationshipIndex != 0) // S has a range encompassed by (..,-1] and [1,..) let unboundRelationship = unboundRelationships[abs(unboundRelationshipIndex) - 1] let direction: RelationshipDirection = unboundRelationshipIndex > 0 ? .to : .from let segment = Relationship( fromNode: fromNode, toNode: toNode, type: unboundRelationship.type, direction: direction, properties: unboundRelationship.properties) segments.append(segment) let fromNodeSequenceIndex = fromNodeSequenceIndex ?? -1 if sequence.count >= fromNodeSequenceIndex + 4 { generateSegments(fromNodeSequenceIndex: fromNodeSequenceIndex + 2) } } }
mit
a7baf908e5fdbfecf8c1f4b35e4d8a76
34.013514
111
0.625241
4.676895
false
false
false
false
OscarSwanros/swift
test/SILGen/scalar_to_tuple_args.swift
2
4422
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {} func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {} func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {} func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {} func tupleWithDefaults(x x: (Int, Int), y: Int = 0, z: Int = 0) {} func variadicFirst(_ x: Int...) {} func variadicSecond(_ x: Int, _ y: Int...) {} var x = 0 // CHECK: [[X_ADDR:%.*]] = global_addr @_T020scalar_to_tuple_args1xSivp : $*Int // CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args17inoutWithDefaultsySiz_Si1ySi1ztF // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int // CHECK: apply [[INOUT_WITH_DEFAULTS]]([[WRITE]], [[DEFAULT_Y]], [[DEFAULT_Z]]) inoutWithDefaults(&x) // CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args27inoutWithCallerSideDefaultsySiz_Si1ytF // CHECK: [[LINE_VAL:%.*]] = integer_literal // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int // CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[WRITE]], [[LINE]]) inoutWithCallerSideDefaults(&x) // CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A12WithDefaultsySi_Si1ySi1ztF // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]]) scalarWithDefaults(x) // CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A22WithCallerSideDefaultsySi_Si1ytF // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] // CHECK: [[LINE_VAL:%.*]] = integer_literal // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]] // CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]]) scalarWithCallerSideDefaults(x) // CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0C12WithDefaultsySi_Sit1x_Si1ySi1ztF // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X1:%.*]] = load [trivial] [[READ]] // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X2:%.*]] = load [trivial] [[READ]] // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]]) tupleWithDefaults(x: (x,x)) // CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @_T020scalar_to_tuple_args13variadicFirstySid_tF // CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [[BORROWED_ALLOC_ARRAY:%.*]] = begin_borrow [[ALLOC_ARRAY]] // CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_ALLOC_ARRAY]] {{.*}}, 0 // CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]] // CHECK: [[MEMORY:%.*]] = tuple_extract [[BORROWED_ALLOC_ARRAY]] {{.*}}, 1 // CHECK: end_borrow [[BORROWED_ALLOC_ARRAY]] from [[ALLOC_ARRAY]] // CHECK: destroy_value [[ALLOC_ARRAY]] // CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]] // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: store [[X]] to [trivial] [[ADDR]] // CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]]) variadicFirst(x) // CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_T020scalar_to_tuple_args14variadicSecondySi_SidtF // CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [[BORROWED_ALLOC_ARRAY:%.*]] = begin_borrow [[ALLOC_ARRAY]] // CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_ALLOC_ARRAY]] {{.*}}, 0 // CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]] // CHECK: end_borrow [[BORROWED_ALLOC_ARRAY]] from [[ALLOC_ARRAY]] // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]]) variadicSecond(x)
apache-2.0
36595fc3c13fec0b59eaa471a46b4a12
54.949367
126
0.604072
3.184438
false
false
false
false
getconnect/connect-swift
Pod/Classes/Timeframe.swift
1
2712
// // Timeframe.swift // ConnectSwift // // Created by Chad Edrupt on 2/12/2015. // Copyright © 2015 Connect. All rights reserved. // import Foundation public enum Timeframe { case ThisMinute case LastMinute case ThisHour case LastHour case Today case Yesterday case ThisWeek case LastWeek case ThisMonth case LastMonth case ThisQuarter case LastQuarter case ThisYear case LastYear case Custom(NSDate?, NSDate?) case Current(RelativeTimeframe) case Previous(RelativeTimeframe) public var jsonObject: AnyObject { switch self { case .ThisMinute: return "this_minute" case .LastMinute: return "last_minute" case .ThisHour: return "this_hour" case .LastHour: return "last_hour" case .Today: return "today" case .Yesterday: return "yesterday" case .ThisWeek: return "this_week" case .LastWeek: return "last_week" case .ThisMonth: return "this_month" case .LastMonth: return "last_month" case .ThisQuarter: return "this_quarter" case .LastQuarter: return "last_quarter" case .ThisYear: return "this_year" case .LastYear: return "last_year" case .Custom(let start, let end): return [ "start": start?.iso8601String ?? "", "end": end?.iso8601String ?? "" ] case .Current(let relative): return ["current": relative.jsonObject] case .Previous(let relative): return ["previous": relative.jsonObject] } } } extension Timeframe: Equatable { } public func ==(lhs: Timeframe, rhs: Timeframe) -> Bool { switch (lhs, rhs) { case (.Today, .Today): return true case (.Yesterday, .Yesterday): return true case (.ThisWeek, .ThisWeek): return true case (.LastWeek, .LastWeek): return true case (.ThisMonth, .ThisMonth): return true case (.LastMonth, .LastMonth): return true case (.ThisYear, .ThisYear): return true case (.LastYear, .LastYear): return true case (let .Custom(firstStart, firstEnd), let .Custom(secondStart, secondEnd)): return firstStart == secondStart && firstEnd == secondEnd case (let .Current(lhsValue), let .Current(rhsValue)): return lhsValue == rhsValue case (let .Previous(lhsValue), let .Previous(rhsValue)): return lhsValue == rhsValue default: return false } }
mit
eef3aa14179139335829b42db8ba05c3
25.320388
82
0.571745
4.473597
false
false
false
false
grandiere/box
box/Model/GridVisor/Render/Algo/MGridVisorRenderAlgo.swift
1
5598
import Foundation import CoreLocation import MetalKit class MGridVisorRenderAlgo:MetalRenderableProtocol { var userHeading:Float var moveVertical:Float weak var render:MGridVisorRender! private weak var textureLoader:MTKTextureLoader! private weak var device:MTLDevice! private(set) var items:[String:MGridAlgoItem] private let textures:MGridVisorRenderTextures private let vertexes:MGridVisorRenderVertexes private let kMaxTarget:Float = 85 init( device:MTLDevice, textureLoader:MTKTextureLoader) { self.device = device self.textureLoader = textureLoader moveVertical = 0 userHeading = 0 items = [:] textures = MGridVisorRenderTextures(textureLoader:textureLoader) vertexes = MGridVisorRenderVertexes(device:device) NotificationCenter.default.addObserver( self, selector:#selector(notifiedDestroyAlgo(sender:)), name:Notification.destroyAlgoRendered, object:nil) } deinit { NotificationCenter.default.removeObserver(self) } //MARK: notified @objc func notifiedDestroyAlgo(sender notification:Notification) { guard let algoItem:MGridAlgoItem = notification.object as? MGridAlgoItem else { return } items.removeValue(forKey:algoItem.firebaseId) } //MARK: private private func positionFor(item:MGridAlgoItem) -> MGridVisorRenderAlgoItem { let position:MetalPosition = render.controller.orientation.itemPosition( userHeading:userHeading, moveVertical:moveVertical, itemHeading:item.multipliedHeading) let positioned:MGridVisorRenderAlgoItem = MGridVisorRenderAlgoItem( device:device, model:item, position:position) return positioned } private func renderStandby( manager:MetalRenderManager, item:MGridVisorRenderAlgoItem, rotation:MTLBuffer) { guard let texture:MTLTexture = item.model.textureStandby(textures:textures) else { return } manager.renderSimple( vertex:vertexes.vertexStandby, position:item.positionBuffer, rotation:rotation, texture:texture) } private func renderTargeted( manager:MetalRenderManager, item:MGridVisorRenderAlgoItem, rotation:MTLBuffer) { if render.controller.targeting !== item.model { textures.restart() } guard let texture:MTLTexture = item.model.textureTargeted(textures:textures) else { return } manager.renderSimple( vertex:vertexes.vertexTargeted, position:item.positionBuffer, rotation:rotation, texture:texture) render.controller.targeting = item.model } //MARK: public func renderAlgoList(nearItems:[MGridAlgoItem]) { var items:[String:MGridAlgoItem] = [:] for nearItem:MGridAlgoItem in nearItems { nearItem.multipliedHeading = MGridVisorOrientation.normalHeading( rawHeading:nearItem.heading) items[nearItem.firebaseId] = nearItem } self.items = items } //MARK: renderable Protocol func render(manager:MetalRenderManager) { guard let rotation:MTLBuffer = render.rotationBuffer else { return } var targeted:MGridVisorRenderAlgoItem? let items:[MGridAlgoItem] = Array(self.items.values) for item:MGridAlgoItem in items { let positioned:MGridVisorRenderAlgoItem = positionFor(item:item) if let currentTargeted:MGridVisorRenderAlgoItem = targeted { if positioned.deltaHorizontal < currentTargeted.deltaHorizontal { renderStandby( manager:manager, item:currentTargeted, rotation:rotation) targeted = positioned } else { renderStandby( manager:manager, item:positioned, rotation:rotation) } } else { targeted = positioned } } if let currentTargeted:MGridVisorRenderAlgoItem = targeted { if currentTargeted.deltaHorizontal < kMaxTarget && currentTargeted.deltaVertical < kMaxTarget { renderTargeted( manager:manager, item:currentTargeted, rotation:rotation) } else { renderStandby( manager:manager, item:currentTargeted, rotation:rotation) render.controller.targeting = nil } } else { render.controller.targeting = nil } } }
mit
07a90758b1cd30dacd26a8338f3fa83e
26.043478
105
0.540729
5.807054
false
false
false
false
jkolb/midnightbacon
MidnightBacon/Modules/Common/Services/UIColor+RGBA.swift
1
1705
// // UIColor+RGBA.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit extension UIColor { public convenience init(_ red: UInt8, _ green: UInt8, _ blue: UInt8) { let r = CGFloat(red) / 255.0 let g = CGFloat(green) / 255.0 let b = CGFloat(blue) / 255.0 self.init(red: r, green: g, blue: b, alpha: 1.0) } public convenience init(_ rgb: UInt32) { let r = UInt8((rgb & 0x00FF0000) >> 16) let g = UInt8((rgb & 0x0000FF00) >> 08) let b = UInt8((rgb & 0x000000FF) >> 00) self.init(r, g, b) } }
mit
3db517e566cc29e70514992af7bd486b
39.595238
80
0.690323
3.928571
false
false
false
false
juliobertolacini/ReduxPaperSwift
ReduxPaperScissors/Pods/ReSwift/ReSwift/CoreTypes/Action.swift
13
4479
// // Action.swift // ReSwift // // Created by Benjamin Encz on 12/14/15. // Copyright © 2015 Benjamin Encz. All rights reserved. // import Foundation /** This is ReSwift's built in action type, it is the only built in type that conforms to the `Action` protocol. `StandardAction` can be serialized and can therefore be used with developer tools that restore state between app launches. The downside of `StandardAction` is that it carries its payload as an untyped dictionary which does not play well with Swift's type system. It is recommended that you define your own types that conform to `Action` - if you want to be able to serialize your custom action types, you can implement `StandardActionConvertible` which will make it possible to generate a `StandardAction` from your typed action - the best of both worlds! */ public struct StandardAction: Action { /// A String that identifies the type of this `StandardAction` public let type: String /// An untyped, JSON-compatible payload public let payload: [String: AnyObject]? /// Indicates whether this action will be deserialized as a typed action or as a standard action public let isTypedAction: Bool /** Initializes this `StandardAction` with a type, a payload and information about whether this is a typed action or not. - parameter type: String representation of the Action type - parameter payload: Payload convertable to JSON - parameter isTypedAction: Is Action a subclassed type */ public init(type: String, payload: [String: AnyObject]? = nil, isTypedAction: Bool = false) { self.type = type self.payload = payload self.isTypedAction = isTypedAction } } // MARK: Coding Extension private let typeKey = "type" private let payloadKey = "payload" private let isTypedActionKey = "isTypedAction" let reSwiftNull = "ReSwift_Null" extension StandardAction: Coding { public init?(dictionary: [String: AnyObject]) { guard let type = dictionary[typeKey] as? String, let isTypedAction = dictionary[isTypedActionKey] as? Bool else { return nil } self.type = type self.payload = dictionary[payloadKey] as? [String: AnyObject] self.isTypedAction = isTypedAction } public var dictionaryRepresentation: [String: AnyObject] { let payload: AnyObject = self.payload as AnyObject? ?? reSwiftNull as AnyObject return [typeKey: type as NSString, payloadKey: payload, isTypedActionKey: isTypedAction as NSNumber] } } /// Implement this protocol on your custom `Action` type if you want to make the action /// serializable. /// - Note: We are working on a tool to automatically generate the implementation of this protocol /// for your custom action types. public protocol StandardActionConvertible: Action { /** Within this initializer you need to use the payload from the `StandardAction` to configure the state of your custom action type. Example: ``` init(_ standardAction: StandardAction) { self.twitterUser = decode(standardAction.payload!["twitterUser"]!) } ``` - Note: If you, as most developers, only use action serialization/deserialization during development, you can feel free to use the unsafe `!` operator. */ init (_ standardAction: StandardAction) /** Use the information from your custom action to generate a `StandardAction`. The `type` of the StandardAction should typically match the type name of your custom action type. You also need to set `isTypedAction` to `true`. Use the information from your action's properties to configure the payload of the `StandardAction`. Example: ``` func toStandardAction() -> StandardAction { let payload = ["twitterUser": encode(self.twitterUser)] return StandardAction(type: SearchTwitterScene.SetSelectedTwitterUser.type, payload: payload, isTypedAction: true) } ``` */ func toStandardAction() -> StandardAction } /// All actions that want to be able to be dispatched to a store need to conform to this protocol /// Currently it is just a marker protocol with no requirements. public protocol Action { } /// Initial Action that is dispatched as soon as the store is created. /// Reducers respond to this action by configuring their intial state. public struct ReSwiftInit: Action {}
mit
ec78c4ef3e8066abbc962d6b40292bcf
36.316667
100
0.706565
4.621259
false
false
false
false
Gofake1/Color-Picker
Color Picker/ColorPickerViewController.swift
1
3762
// // ColorPickerViewController.swift // Color Picker // // Created by David Wu on 5/4/17. // Copyright © 2017 Gofake1. All rights reserved. // import Cocoa class ColorPickerViewController: NSViewController { @IBOutlet weak var brightnessSlider: NSSlider! @IBOutlet weak var colorLabel: NSTextField! @IBOutlet weak var colorWheelView: ColorWheelView! @IBOutlet weak var colorDragView: ColorDragView! override func awakeFromNib() { ColorController.shared.colorPicker = self colorWheelView.delegate = self } /// - postcondition: Mutates `ColorController.brightness`, redraws views @IBAction func setBrightness(_ sender: NSSlider) { ColorController.shared.brightness = CGFloat((sender.maxValue-sender.doubleValue) / sender.maxValue) updateColorWheel(redrawCrosshair: false) updateLabel() } /// - postcondition: Mutates `colorController.selectedColor`, redraws views @IBAction func setColor(_ sender: NSTextField) { let color = NSColor(hexString: sender.stringValue) ColorController.shared.setColor(color) view.window?.makeFirstResponder(view) } func updateColorWheel(redrawCrosshair: Bool = true) { colorWheelView.setColor(ColorController.shared.selectedColor, redrawCrosshair) } func updateLabel() { colorLabel.backgroundColor = ColorController.shared.selectedColor colorLabel.stringValue = "#"+ColorController.shared.selectedColor.rgbHexString if ColorController.shared.selectedColor.scaledBrightness < 0.5 { colorLabel.textColor = NSColor.white } else { colorLabel.textColor = NSColor.black } } func updateSlider() { guard let sliderCell = brightnessSlider.cell as? GradientSliderCell else { fatalError() } sliderCell.colorA = ColorController.shared.masterColor brightnessSlider.drawCell(sliderCell) brightnessSlider.doubleValue = brightnessSlider.maxValue - (Double(ColorController.shared.brightness) * brightnessSlider.maxValue) } } extension ColorPickerViewController: ColorWheelViewDelegate { /// - postcondition: Mutates `ColorController.masterColor` func colorDidChange(_ newColor: NSColor) { ColorController.shared.masterColor = newColor updateLabel() updateSlider() } } extension ColorPickerViewController: NSControlTextEditingDelegate { private func validateControlString(_ string: String) -> Bool { // String must be 6 characters and only contain numbers and letters 'a' through 'f', // or 7 characters if the first character is '#' switch string.count { case 6: guard string.containsOnlyHexCharacters else { return false } return true case 7: guard string.hasPrefix("#") else { return false } var trimmed = string; trimmed.remove(at: trimmed.startIndex) guard trimmed.containsOnlyHexCharacters else { return false } return true default: return false } } func control(_ control: NSControl, isValidObject obj: Any?) -> Bool { if control == colorLabel { guard let string = obj as? String else { return false } return validateControlString(string) } return false } } extension String { var containsOnlyHexCharacters: Bool { return !contains { switch $0 { case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "a", "b", "c", "d", "e", "f": return false default: return true } } } }
mit
dc3b0a40bbb603cd6a2d5279c3781081
33.504587
111
0.643446
4.772843
false
false
false
false
nifty-swift/Nifty
Sources/ind2sub.swift
2
2475
/*************************************************************************************************** * ind2sub.swift * * This file provides functionality for converting indices to subscripts. * * Author: Philip Erickson * Creation Date: 1 May 2016 * Contributors: * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. * * Copyright 2016 Philip Erickson **************************************************************************************************/ /// Convert monodimensional index into multidimensional subscripts. /// /// Note: Row-major order is used. In row-major order, the last dimension is contiguous. In 2-D /// matrix, this corresponds to walking through the columns in a row before moving to the next row. /// In a 3-D matrix, the index walks through the layers for a particular row/column pair, then /// through the columns in a row, then finally moves to the next row. /// /// - Parameters: /// - size: size of data structure to subscript /// - index: index into flattened data structure /// - Returns: list of subscripts corresponding to index, or empty list if index is out of bounds func ind2sub(size: [Int], index: Int) -> [Int] { precondition(!size.isEmpty, "Size must not be empty") if index < 0 || index > size.reduce(1, *)-1 { return [] } var curIndex = index var subs = [Int](repeating: 0, count: size.count) // compute the steps in linear index needed to increment each dimension subscript var steps = [Int](repeating: 0, count: size.count) steps[size.count-1] = 1 for i in stride(from: size.count-2, through: 0, by: -1) { steps[i] = steps[i+1] * size[i+1] } // count the number of subscript increments, beginning with slowest moving dimension for dim in 0..<size.count { subs[dim] = curIndex/steps[dim] curIndex = curIndex - (subs[dim]*steps[dim]) } return subs }
apache-2.0
aa027c19cb106aa89addcc2e61f6cef4
38.935484
101
0.616162
4.216354
false
false
false
false
flodolo/firefox-ios
Client/Frontend/Theme/LightTheme.swift
1
3082
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import UIKit struct LightTheme: Theme { var type: ThemeType = .light var colors: ThemeColourPalette = LightColourPalette() } private struct LightColourPalette: ThemeColourPalette { // MARK: - Layers var layer1: UIColor = FXColors.LightGrey10 var layer2: UIColor = FXColors.White var layer3: UIColor = FXColors.LightGrey20 var layer4: UIColor = FXColors.LightGrey30.withAlphaComponent(0.6) var layer5: UIColor = FXColors.White var layer6: UIColor = FXColors.White var layer5Hover: UIColor = FXColors.LightGrey20 var layerScrim: UIColor = FXColors.DarkGrey30.withAlphaComponent(0.95) var layerGradient: Gradient = Gradient(start: FXColors.Violet70, end: FXColors.Violet40) var layerAccentNonOpaque: UIColor = FXColors.Blue50.withAlphaComponent(0.1) var layerAccentPrivate: UIColor = FXColors.Purple60 var layerAccentPrivateNonOpaque: UIColor = FXColors.Purple60.withAlphaComponent(0.1) var layerLightGrey30: UIColor = FXColors.LightGrey30 // MARK: - Actions var actionPrimary: UIColor = FXColors.Blue50 var actionPrimaryHover: UIColor = FXColors.Blue60 var actionSecondary: UIColor = FXColors.LightGrey30 var actionSecondaryHover: UIColor = FXColors.LightGrey40 var formSurfaceOff: UIColor = FXColors.LightGrey30 var formKnob: UIColor = FXColors.White var indicatorActive: UIColor = FXColors.LightGrey50 var indicatorInactive: UIColor = FXColors.LightGrey30 // MARK: - Text var textPrimary: UIColor = FXColors.DarkGrey90 var textSecondary: UIColor = FXColors.DarkGrey05 var textDisabled: UIColor = FXColors.DarkGrey90.withAlphaComponent(0.4) var textWarning: UIColor = FXColors.Red70 var textAccent: UIColor = FXColors.Blue50 var textOnColor: UIColor = FXColors.LightGrey05 var textInverted: UIColor = FXColors.LightGrey05 // MARK: - Icons var iconPrimary: UIColor = FXColors.DarkGrey90 var iconSecondary: UIColor = FXColors.DarkGrey05 var iconDisabled: UIColor = FXColors.DarkGrey90.withAlphaComponent(0.4) var iconAction: UIColor = FXColors.Blue50 var iconOnColor: UIColor = FXColors.LightGrey05 var iconWarning: UIColor = FXColors.Red70 var iconSpinner: UIColor = FXColors.LightGrey80 var iconAccentViolet: UIColor = FXColors.Violet60 var iconAccentBlue: UIColor = FXColors.Blue60 var iconAccentPink: UIColor = FXColors.Pink60 var iconAccentGreen: UIColor = FXColors.Green60 var iconAccentYellow: UIColor = FXColors.Yellow60 // MARK: - Border var borderPrimary: UIColor = FXColors.LightGrey30 var borderAccent: UIColor = FXColors.Blue50 var borderAccentNonOpaque: UIColor = FXColors.Blue50.withAlphaComponent(0.1) var borderAccentPrivate: UIColor = FXColors.Purple60 // MARK: - Shadow var shadowDefault: UIColor = FXColors.DarkGrey40.withAlphaComponent(0.16) }
mpl-2.0
255ecbf9bf82284ef509ebb2ded158fb
43.666667
92
0.753407
3.987063
false
false
false
false
yuxiuyu/TrendBet
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Charts/CombinedChartView.swift
4
7267
// // CombinedChartView.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area. open class CombinedChartView: BarLineChartViewBase, CombinedChartDataProvider { /// the fill-formatter used for determining the position of the fill-line internal var _fillFormatter: IFillFormatter! /// enum that allows to specify the order in which the different data objects for the combined-chart are drawn @objc(CombinedChartDrawOrder) public enum DrawOrder: Int { case bar case bubble case line case candle case scatter } open override func initialize() { super.initialize() self.highlighter = CombinedHighlighter(chart: self, barDataProvider: self) // Old default behaviour self.highlightFullBarEnabled = true _fillFormatter = DefaultFillFormatter() renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } open override var data: ChartData? { get { return super.data } set { super.data = newValue self.highlighter = CombinedHighlighter(chart: self, barDataProvider: self) (renderer as? CombinedChartRenderer)?.createRenderers() renderer?.initBuffers() } } @objc open var fillFormatter: IFillFormatter { get { return _fillFormatter } set { _fillFormatter = newValue if _fillFormatter == nil { _fillFormatter = DefaultFillFormatter() } } } /// - returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the CombinedChart. open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } guard let h = self.highlighter?.getHighlight(x: pt.x, y: pt.y) else { return nil } if !isHighlightFullBarEnabled { return h } // For isHighlightFullBarEnabled, remove stackIndex return Highlight( x: h.x, y: h.y, xPx: h.xPx, yPx: h.yPx, dataIndex: h.dataIndex, dataSetIndex: h.dataSetIndex, stackIndex: -1, axis: h.axis) } // MARK: - CombinedChartDataProvider open var combinedData: CombinedChartData? { get { return _data as? CombinedChartData } } // MARK: - LineChartDataProvider open var lineData: LineChartData? { get { return combinedData?.lineData } } // MARK: - BarChartDataProvider open var barData: BarChartData? { get { return combinedData?.barData } } // MARK: - ScatterChartDataProvider open var scatterData: ScatterChartData? { get { return combinedData?.scatterData } } // MARK: - CandleChartDataProvider open var candleData: CandleChartData? { get { return combinedData?.candleData } } // MARK: - BubbleChartDataProvider open var bubbleData: BubbleChartData? { get { return combinedData?.bubbleData } } // MARK: - Accessors /// if set to true, all values are drawn above their bars, instead of below their top @objc open var drawValueAboveBarEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled } set { (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled = newValue } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value @objc open var drawBarShadowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled } set { (renderer as! CombinedChartRenderer!).drawBarShadowEnabled = newValue } } /// - returns: `true` if drawing values above bars is enabled, `false` ifnot open var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled } /// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot open var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. @objc open var drawOrder: [Int] { get { return (renderer as! CombinedChartRenderer!).drawOrder.map { $0.rawValue } } set { (renderer as! CombinedChartRenderer!).drawOrder = newValue.map { DrawOrder(rawValue: $0)! } } } /// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values @objc open var highlightFullBarEnabled: Bool = false /// - returns: `true` the highlight is be full-bar oriented, `false` ifsingle-value open var isHighlightFullBarEnabled: Bool { return highlightFullBarEnabled } // MARK: - ChartViewBase /// draws all MarkerViews on the highlighted positions override func drawMarkers(context: CGContext) { guard let marker = marker, isDrawMarkersEnabled && valuesToHighlight() else { return } for i in 0 ..< _indicesToHighlight.count { let highlight = _indicesToHighlight[i] guard let set = combinedData?.getDataSetByHighlight(highlight), let e = _data?.entryForHighlight(highlight) else { continue } let entryIndex = set.entryIndex(entry: e) if entryIndex > Int(Double(set.entryCount) * _animator.phaseX) { continue } let pos = getMarkerPosition(highlight: highlight) // check bounds if !_viewPortHandler.isInBounds(x: pos.x, y: pos.y) { continue } // callbacks to update the content marker.refreshContent(entry: e, highlight: highlight) // draw the marker marker.draw(context: context, point: pos) } } }
apache-2.0
650c5e77db74dd4240d133e25595d247
28.54065
149
0.582496
5.30438
false
false
false
false
ravirani/algorithms
Sorting/MergeSort.swift
1
1362
// // MergeSort.swift // // Recursively split the passed in array until there is only one value left. // Sort and merge at each step rebuilding the array. // import Foundation func combine(_ arr1: [Int], _ arr2: [Int]) -> [Int] { var sortedArray = [Int]() var leftIndex = 0, rightIndex = 0 while leftIndex < arr1.count || rightIndex < arr2.count { if leftIndex < arr1.count && rightIndex < arr2.count { if arr1[leftIndex] < arr2[rightIndex] { sortedArray.append(arr1[leftIndex]) leftIndex += 1 } else { sortedArray.append(arr2[rightIndex]) rightIndex += 1 } } else if leftIndex < arr1.count { sortedArray.append(arr1[leftIndex]) leftIndex += 1 } else if rightIndex < arr2.count { sortedArray.append(arr2[rightIndex]) rightIndex += 1 } } return sortedArray } func mergeSort(_ inputArray: [Int]) -> [Int] { guard inputArray.count > 1 else { return inputArray } let middleIndex: Int = Int(inputArray.count / 2) let leftHalf = mergeSort(Array(inputArray[0..<middleIndex])) let rightHalf = mergeSort(Array(inputArray[middleIndex..<inputArray.count])) return combine(leftHalf, rightHalf) } assert(mergeSort([2, 10, 3, 200, 110]) == [2, 3, 10, 110, 200]) assert(mergeSort([10, -1, 3, 9, 2, 27, 8, 26]) == [-1, 2, 3, 8, 9, 10, 26, 27])
mit
3da16c24b878203910a2e94d87ce3fd2
27.978723
79
0.631424
3.510309
false
false
false
false
briancroom/BackgroundFetchLogger
BackgroundFetchLogger/LogStats.swift
1
801
import Foundation struct LogStats { let backgroundFetchCount: NSInteger let averageBackgroundFetchInterval: NSTimeInterval? let minBackgroundFetchInterval: NSTimeInterval? let maxBackgroundFetchInterval: NSTimeInterval? } func logStatsFromLog(log: Logger.Log) -> LogStats { let backgroundFetchTimestamps = log.filter { $0.eventName == AppDelegate.LogEvents.BackgroundFetch }.map { $0.timestamp.timeIntervalSinceReferenceDate } let intervals = deltas(backgroundFetchTimestamps) let count = backgroundFetchTimestamps.count return LogStats( backgroundFetchCount: backgroundFetchTimestamps.count, averageBackgroundFetchInterval: intervals.avg(), minBackgroundFetchInterval: intervals.min(), maxBackgroundFetchInterval: intervals.max()) }
mit
9792d7703c542f48e8f7666f003aa7bb
39.05
156
0.776529
5.375839
false
false
false
false
djq993452611/YiYuDaoJia_Swift
YiYuDaoJia/YiYuDaoJia/Classes/Home/ViewModel/HomeViewModel.swift
1
3373
// // HomeViewModel.swift // YiYuDaoJia // // Created by 蓝海天网Djq on 2017/4/25. // Copyright © 2017年 蓝海天网Djq. All rights reserved. // import UIKit import SwiftyJSON // 每个ViewModel类都还要引入一次SwiftyJSON才可以使用 class HomeViewModel: BaseViewModel { } extension HomeViewModel { func requestData(_ finishCallback : @escaping ()->() ){ let parameters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()] NetworkTools.requestData(.POST, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: parameters) { (result) in // 使用 JSON 直接解析字段“data”里面的数据,并且直接获取可选值array,dictionary let json = JSON.init(result) if let dataArray = json["data"].array{ // DLog(log: "dataArray= \(dataArray)") // 取出数据,并把JSON数据类型转换成普通的字典数据类型 let dict = dataArray[0].dictionaryObject // BaseModel.printProperty(dict: dict!) //快速打印model的属性名称,创建model使用 // 使用MJExtension进行model和字典直接的相互转换 let home = HomeModel.mj_object(withKeyValues: dict!) let homeDic = home?.mj_keyValues() DLog(log: "homeDic=\(String(describing: homeDic))") DLog(log: "gameName = \(String(describing: home?.game_name))") finishCallback() } // DLog(log: "json=\(json)") } } // 请求无线轮播的数据 func requestCycleData(_ finishCallback : @escaping () -> ()) { NetworkTools.requestData(.GET, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in let json = JSON.init(result) //取出room的模型数据打印 if let dataRoom = json["data"][0]["room"].dictionaryObject{ BaseModel.printProperty(dict: dataRoom) // DLog(log: "dataRoom=\(dataRoom)") } if let dataArray = json["data"].arrayObject{ //使用工具CommonUtil测试本地数据持久化 let dict = dataArray.first // BaseModel.printProperty(dict: dict!) //DLog(log: "dict=\(String(describing: dict))") CommonUtil.saveDictionary("dictSave", withDic: dict as! [AnyHashable : Any]) let dicGet = CommonUtil.getDictionary("dictSave") DLog(log: "dicGet=\(String(describing: dicGet))") //DLog(log: "pic_url=\(String(describing: dicGet?["pic_url"]))") //单例写法,先转换在写入 let user = UserModel.mj_object(withKeyValues: dict) UserModel.saveUserModel(user: user) let userShare = UserModel.mj_object(withKeyValues: dict) UserModel.setInstance(user: userShare!) // DLog(log: userShare) finishCallback() } } } }
mit
92488b8f5fc06d9ea682e56cb77dcd23
31.851064
139
0.519754
4.436782
false
false
false
false
nicolastinkl/swift
ListerAProductivityAppBuiltinSwift/ListerKit/ListCoordinator.swift
1
6653
/* Copyright (C) 2014 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The ListCoordinator handles file operations and tracking based on the users storage choice (local vs. cloud). */ import UIKit class ListCoordinator: NSObject { // MARK: Types struct Notifications { struct StorageDidChange { static let name = "storageChoiceDidChangeNotification" } } struct SingleInstance { static let sharedListCoordinator: ListCoordinator = { let listCoordinator = ListCoordinator() NSNotificationCenter.defaultCenter().addObserver(listCoordinator, selector: "updateDocumentStorageContainerURL", name: AppConfiguration.Notifications.StorageOptionDidChange.name, object: nil) return listCoordinator }() } // MARK: Class Properties class var sharedListCoordinator: ListCoordinator { return SingleInstance.sharedListCoordinator } // MARK: Properties var documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL var todayDocumentURL: NSURL { return documentsDirectory.URLByAppendingPathComponent(AppConfiguration.localizedTodayDocumentNameAndExtension) } // MARK: Document Management func copyInitialDocuments() { let defaultListURLs = NSBundle.mainBundle().URLsForResourcesWithExtension(AppConfiguration.listerFileExtension, subdirectory: "") as NSURL[] for url in defaultListURLs { copyFileToDocumentsDirectory(url) } } func updateDocumentStorageContainerURL() { let oldDocumentsDirectory = documentsDirectory let fileManager = NSFileManager.defaultManager() if AppConfiguration.sharedConfiguration.storageOption != .Cloud { documentsDirectory = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL NSNotificationCenter.defaultCenter().postNotificationName(Notifications.StorageDidChange.name, object: self) } else { let defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(defaultQueue) { // The call to URLForUbiquityContainerIdentifier should be on a background queue. let cloudDirectory = fileManager.URLForUbiquityContainerIdentifier(nil) dispatch_async(dispatch_get_main_queue()) { self.documentsDirectory = cloudDirectory.URLByAppendingPathComponent("Documents") let localDocuments = fileManager.contentsOfDirectoryAtURL(oldDocumentsDirectory, includingPropertiesForKeys: nil, options: .SkipsPackageDescendants, error: nil) as NSURL[]? if let localDocuments = localDocuments { for url in localDocuments { if url.pathExtension == AppConfiguration.listerFileExtension { self.makeItemUbiquitousAtURL(url) } } } NSNotificationCenter.defaultCenter().postNotificationName(Notifications.StorageDidChange.name, object: self) } } } } func makeItemUbiquitousAtURL(sourceURL: NSURL) { let destinationFileName = sourceURL.lastPathComponent let destinationURL = documentsDirectory.URLByAppendingPathComponent(destinationFileName) // Upload the file to iCloud on a background queue. var defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(defaultQueue) { let fileManager = NSFileManager() let success = fileManager.setUbiquitous(true, itemAtURL: sourceURL, destinationURL: destinationURL, error: nil) // If the move wasn't successful, try removing the item locally since the document may already exist in the cloud. if !success { fileManager.removeItemAtURL(sourceURL, error: nil) } } } // MARK: Convenience func copyFileToDocumentsDirectory(fromURL: NSURL) { let toURL = documentsDirectory.URLByAppendingPathComponent(fromURL.lastPathComponent) let coordinator = NSFileCoordinator() coordinator.coordinateWritingItemAtURL(fromURL, options: .ForMoving, writingItemAtURL: toURL, options: .ForReplacing, error: nil) { sourceURL, destinationURL in let fileManager = NSFileManager() var moveError: NSError? let success = fileManager.copyItemAtURL(sourceURL, toURL: destinationURL, error: &moveError) if success { fileManager.setAttributes([ NSFileExtensionHidden: true ], ofItemAtPath: destinationURL.path, error: nil) NSLog("Moved file: \(sourceURL.absoluteString) to: \(destinationURL.absoluteString).") } else { // In your app, handle this gracefully. NSLog("Couldn't move file: \(sourceURL.absoluteString) to: \(destinationURL.absoluteString). Error: \(moveError.description).") abort() } } } func deleteFileAtURL(fileURL: NSURL) { let fileCoordinator = NSFileCoordinator() var error: NSError? fileCoordinator.coordinateWritingItemAtURL(fileURL, options: .ForDeleting, error: &error) { writingURL in let fileManager = NSFileManager() fileManager.removeItemAtURL(writingURL, error: &error) } if error { // In your app, handle this gracefully. NSLog("Couldn't delete file at URL \(fileURL.absoluteString). Error: \(error.description).") abort() } } // MARK: Document Name Helper Methods func documentURLForName(name: String) -> NSURL { return documentsDirectory.URLByAppendingPathComponent(name).URLByAppendingPathExtension(AppConfiguration.listerFileExtension) } func isValidDocumentName(name: String) -> Bool { if name.isEmpty { return false } let proposedDocumentPath = documentURLForName(name).path return !NSFileManager.defaultManager().fileExistsAtPath(proposedDocumentPath) } }
mit
5198549cd1322f640b0f515a666791d1
39.066265
203
0.640204
6.090659
false
false
false
false
bizz84/MVCarouselCollectionView
MVCarouselCollectionViewDemo/Carousel/MVEmbeddedCarouselViewController.swift
1
4771
// MVEmbeddedCarouselViewController.swift // // Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import MVCarouselCollectionView class MVEmbeddedCarouselViewController: UIViewController, MVCarouselCollectionViewDelegate, MVFullScreenCarouselViewControllerDelegate { var imagePaths : [String] = [] var imageLoader: ((imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ())? @IBOutlet var collectionView : MVCarouselCollectionView! @IBOutlet var pageControl : MVCarouselPageControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.translatesAutoresizingMaskIntoConstraints = false self.pageControl.numberOfPages = imagePaths.count // Configure collection view self.collectionView.selectDelegate = self self.collectionView.imagePaths = imagePaths self.collectionView.commonImageLoader = self.imageLoader self.collectionView.maximumZoom = 2.0 self.collectionView.reloadData() } func addAsChildViewController(parentViewController : UIViewController, attachToView parentView: UIView) { parentViewController.addChildViewController(self) self.didMoveToParentViewController(parentViewController) parentView.addSubview(self.view) self.autoLayout(parentView) } func autoLayout(parentView: UIView) { self.matchLayoutAttribute(.Left, parentView:parentView) self.matchLayoutAttribute(.Right, parentView:parentView) self.matchLayoutAttribute(.Bottom, parentView:parentView) self.matchLayoutAttribute(.Top, parentView:parentView) } func matchLayoutAttribute(attribute : NSLayoutAttribute, parentView: UIView) { parentView.addConstraint( NSLayoutConstraint(item:self.view, attribute:attribute, relatedBy:NSLayoutRelation.Equal, toItem:parentView, attribute:attribute, multiplier:1.0, constant:0)) } // MARK: MVCarouselCollectionViewDelegate func carousel(carousel: MVCarouselCollectionView, didSelectCellAtIndexPath indexPath: NSIndexPath) { // Send indexPath.row as index to use self.performSegueWithIdentifier("FullScreenSegue", sender:indexPath); } func carousel(carousel: MVCarouselCollectionView, didScrollToCellAtIndex cellIndex : NSInteger) { self.pageControl.currentPage = cellIndex } // MARK: IBActions @IBAction func pageControlEventChanged(sender: UIPageControl) { self.collectionView.setCurrentPageIndex(sender.currentPage, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "FullScreenSegue" { let nc = segue.destinationViewController as? UINavigationController let vc = nc?.viewControllers[0] as? MVFullScreenCarouselViewController if let vc = vc { vc.imageLoader = self.imageLoader vc.imagePaths = self.imagePaths vc.delegate = self vc.title = self.parentViewController?.navigationItem.title if let indexPath = sender as? NSIndexPath { vc.initialViewIndex = indexPath.row } } } } // MARK: FullScreenViewControllerDelegate func willCloseWithSelectedIndexPath(indexPath: NSIndexPath) { self.collectionView.resetZoom() self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition:UICollectionViewScrollPosition.CenteredHorizontally, animated:false) } }
mit
f4bfe9b7b411da6df7cbb373248cb7dd
40.486957
166
0.719975
5.403171
false
false
false
false
ben-ng/swift
test/SILGen/closures.swift
1
35124
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s import Swift var zero = 0 // <rdar://problem/15921334> // CHECK-LABEL: sil hidden @_TF8closures46return_local_generic_function_without_captures{{.*}} : $@convention(thin) <A, R> () -> @owned @callee_owned (@in A) -> @out R { func return_local_generic_function_without_captures<A, R>() -> (A) -> R { func f(_: A) -> R { Builtin.int_trap() } // CHECK: [[FN:%.*]] = function_ref @_TFF8closures46return_local_generic_function_without_captures{{.*}} : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1 // CHECK: [[FN_WITH_GENERIC_PARAMS:%.*]] = partial_apply [[FN]]<A, R>() : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1 // CHECK: return [[FN_WITH_GENERIC_PARAMS]] : $@callee_owned (@in A) -> @out R return f } func return_local_generic_function_with_captures<A, R>(_ a: A) -> (A) -> R { func f(_: A) -> R { _ = a } return f } // CHECK-LABEL: sil hidden @_TF8closures17read_only_captureFSiSi : $@convention(thin) (Int) -> Int { func read_only_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // SEMANTIC ARC TODO: This is incorrect. We need to do the project_box on the copy. // CHECK: [[PROJECT:%.*]] = project_box [[XBOX]] // CHECK: store [[X]] to [trivial] [[PROJECT]] func cap() -> Int { return x } return cap() // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // SEMANTIC ARC TODO: See above. This needs to happen on the copy_valued box. // CHECK: mark_function_escape [[PROJECT]] // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures17read_only_capture.*]] : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // CHECK: [[RET:%[0-9]+]] = apply [[CAP]]([[XBOX_COPY]]) // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: } // end sil function '_TF8closures17read_only_captureFSiSi' // CHECK: sil shared @[[CAP_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : $<τ_0_0> { var τ_0_0 } <Int>): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[X:%[0-9]+]] = load [trivial] [[XADDR]] // CHECK: destroy_value [[XBOX]] // CHECK: return [[X]] // } // end sil function '[[CAP_NAME]]' // SEMANTIC ARC TODO: This is a place where we have again project_box too early. // CHECK-LABEL: sil hidden @_TF8closures16write_to_captureFSiSi : $@convention(thin) (Int) -> Int { func write_to_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: store [[X]] to [trivial] [[XBOX_PB]] // CHECK: [[X2BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // CHECK: [[X2BOX_PB:%.*]] = project_box [[X2BOX]] // CHECK: copy_addr [[XBOX_PB]] to [initialization] [[X2BOX_PB]] // CHECK: [[X2BOX_COPY:%.*]] = copy_value [[X2BOX]] // SEMANTIC ARC TODO: This next mark_function_escape should be on a projection from X2BOX_COPY. // CHECK: mark_function_escape [[X2BOX_PB]] var x2 = x func scribble() { x2 = zero } scribble() // CHECK: [[SCRIB:%[0-9]+]] = function_ref @[[SCRIB_NAME:_TFF8closures16write_to_capture.*]] : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> () // CHECK: apply [[SCRIB]]([[X2BOX_COPY]]) // SEMANTIC ARC TODO: This should load from X2BOX_COPY project. There is an // issue here where after a copy_value, we need to reassign a projection in // some way. // CHECK: [[RET:%[0-9]+]] = load [trivial] [[X2BOX_PB]] // CHECK: destroy_value [[X2BOX]] // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] return x2 } // CHECK: } // end sil function '_TF8closures16write_to_captureFSiSi' // CHECK: sil shared @[[SCRIB_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : $<τ_0_0> { var τ_0_0 } <Int>): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: copy_addr {{%[0-9]+}} to [[XADDR]] // CHECK: destroy_value [[XBOX]] // CHECK: return // CHECK: } // end sil function '[[SCRIB_NAME]]' // CHECK-LABEL: sil hidden @_TF8closures21multiple_closure_refs func multiple_closure_refs(_ x: Int) -> (() -> Int, () -> Int) { var x = x func cap() -> Int { return x } return (cap, cap) // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures21multiple_closure_refs.*]] : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // CHECK: [[CAP_CLOSURE_1:%[0-9]+]] = partial_apply [[CAP]] // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures21multiple_closure_refs.*]] : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // CHECK: [[CAP_CLOSURE_2:%[0-9]+]] = partial_apply [[CAP]] // CHECK: [[RET:%[0-9]+]] = tuple ([[CAP_CLOSURE_1]] : {{.*}}, [[CAP_CLOSURE_2]] : {{.*}}) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_TF8closures18capture_local_funcFSiFT_FT_Si : $@convention(thin) (Int) -> @owned @callee_owned () -> @owned @callee_owned () -> Int { func capture_local_func(_ x: Int) -> () -> () -> Int { // CHECK: bb0([[ARG:%.*]] : $Int): var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: store [[ARG]] to [trivial] [[XBOX_PB]] func aleph() -> Int { return x } func beth() -> () -> Int { return aleph } // CHECK: [[BETH_REF:%.*]] = function_ref @[[BETH_NAME:_TFF8closures18capture_local_funcFSiFT_FT_SiL_4bethfT_FT_Si]] : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> @owned @callee_owned () -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // SEMANTIC ARC TODO: This is incorrect. This should be a project_box from XBOX_COPY. // CHECK: mark_function_escape [[XBOX_PB]] // CHECK: [[BETH_CLOSURE:%[0-9]+]] = partial_apply [[BETH_REF]]([[XBOX_COPY]]) return beth // CHECK: destroy_value [[XBOX]] // CHECK: return [[BETH_CLOSURE]] } // CHECK: } // end sil function '_TF8closures18capture_local_funcFSiFT_FT_Si' // CHECK: sil shared @[[ALEPH_NAME:_TFF8closures18capture_local_funcFSiFT_FT_SiL_5alephfT_Si]] : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int { // CHECK: bb0([[XBOX:%[0-9]+]] : $<τ_0_0> { var τ_0_0 } <Int>): // CHECK: sil shared @[[BETH_NAME]] : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> @owned @callee_owned () -> Int { // CHECK: bb0([[XBOX:%[0-9]+]] : $<τ_0_0> { var τ_0_0 } <Int>): // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: [[ALEPH_REF:%[0-9]+]] = function_ref @[[ALEPH_NAME]] : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // SEMANTIC ARC TODO: This should be on a PB from XBOX_COPY. // CHECK: mark_function_escape [[XBOX_PB]] // CHECK: [[ALEPH_CLOSURE:%[0-9]+]] = partial_apply [[ALEPH_REF]]([[XBOX_COPY]]) // CHECK: destroy_value [[XBOX]] // CHECK: return [[ALEPH_CLOSURE]] // CHECK: } // end sil function '[[BETH_NAME]]' // CHECK-LABEL: sil hidden @_TF8closures22anon_read_only_capture func anon_read_only_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // CHECK: [[PB:%.*]] = project_box [[XBOX]] return ({ x })() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures22anon_read_only_capture.*]] : $@convention(thin) (@inout_aliasable Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]]) // -- cleanup // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil shared @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : $*Int): // CHECK: [[X:%[0-9]+]] = load [trivial] [[XADDR]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_TF8closures21small_closure_capture func small_closure_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // CHECK: [[PB:%.*]] = project_box [[XBOX]] return { x }() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures21small_closure_capture.*]] : $@convention(thin) (@inout_aliasable Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]]) // -- cleanup // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil shared @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : $*Int): // CHECK: [[X:%[0-9]+]] = load [trivial] [[XADDR]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_TF8closures35small_closure_capture_with_argument func small_closure_capture_with_argument(_ x: Int) -> (_ y: Int) -> Int { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> return { x + $0 } // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures35small_closure_capture_with_argument.*]] : $@convention(thin) (Int, @owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // CHECK: [[ANON_CLOSURE_APP:%[0-9]+]] = partial_apply [[ANON]]([[XBOX_COPY]]) // -- return // CHECK: destroy_value [[XBOX]] // CHECK: return [[ANON_CLOSURE_APP]] } // CHECK: sil shared @[[CLOSURE_NAME]] : $@convention(thin) (Int, @owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // CHECK: bb0([[DOLLAR0:%[0-9]+]] : $Int, [[XBOX:%[0-9]+]] : $<τ_0_0> { var τ_0_0 } <Int>): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[PLUS:%[0-9]+]] = function_ref @_TFsoi1pFTSiSi_Si{{.*}} // CHECK: [[LHS:%[0-9]+]] = load [trivial] [[XADDR]] // CHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]]) // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_TF8closures24small_closure_no_capture func small_closure_no_capture() -> (_ y: Int) -> Int { // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures24small_closure_no_captureFT_FSiSiU_FSiSi]] : $@convention(thin) (Int) -> Int // CHECK: [[ANON_THICK:%[0-9]+]] = thin_to_thick_function [[ANON]] : ${{.*}} to $@callee_owned (Int) -> Int // CHECK: return [[ANON_THICK]] return { $0 } } // CHECK: sil shared @[[CLOSURE_NAME]] : $@convention(thin) (Int) -> Int // CHECK: bb0([[YARG:%[0-9]+]] : $Int): // CHECK-LABEL: sil hidden @_TF8closures17uncaptured_locals{{.*}} : func uncaptured_locals(_ x: Int) -> (Int, Int) { var x = x // -- locals without captures are stack-allocated // CHECK: bb0([[XARG:%[0-9]+]] : $Int): // CHECK: [[XADDR:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> // CHECK: [[PB:%.*]] = project_box [[XADDR]] // CHECK: store [[XARG]] to [trivial] [[PB]] var y = zero // CHECK: [[YADDR:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <Int> return (x, y) } class SomeClass { var x : Int = zero init() { x = { self.x }() // Closing over self. } } // Closures within destructors <rdar://problem/15883734> class SomeGenericClass<T> { deinit { var i: Int = zero // CHECK: [[C1REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU_FT_Si : $@convention(thin) (@inout_aliasable Int) -> Int // CHECK: apply [[C1REF]]([[IBOX:%[0-9]+]]) : $@convention(thin) (@inout_aliasable Int) -> Int var x = { i + zero } () // CHECK: [[C2REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU0_FT_Si : $@convention(thin) () -> Int // CHECK: apply [[C2REF]]() : $@convention(thin) () -> Int var y = { zero } () // CHECK: [[C3REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU1_FT_T_ : $@convention(thin) <τ_0_0> () -> () // CHECK: apply [[C3REF]]<T>() : $@convention(thin) <τ_0_0> () -> () var z = { _ = T.self } () } // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU_FT_Si : $@convention(thin) (@inout_aliasable Int) -> Int // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU0_FT_Si : $@convention(thin) () -> Int // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU1_FT_T_ : $@convention(thin) <T> () -> () } // This is basically testing that the constraint system ranking // function conversions as worse than others, and therefore performs // the conversion within closures when possible. class SomeSpecificClass : SomeClass {} func takesSomeClassGenerator(_ fn : () -> SomeClass) {} func generateWithConstant(_ x : SomeSpecificClass) { takesSomeClassGenerator({ x }) } // CHECK-LABEL: sil shared @_TFF8closures20generateWithConstantFCS_17SomeSpecificClassT_U_FT_CS_9SomeClass : $@convention(thin) (@owned SomeSpecificClass) -> @owned SomeClass { // CHECK: bb0([[T0:%.*]] : $SomeSpecificClass): // CHECK: debug_value [[T0]] : $SomeSpecificClass, let, name "x", argno 1 // CHECK: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK: [[T0_COPY_CASTED:%.*]] = upcast [[T0_COPY]] : $SomeSpecificClass to $SomeClass // CHECK: destroy_value [[T0]] // CHECK: return [[T0_COPY_CASTED]] // CHECK: } // end sil function '_TFF8closures20generateWithConstantFCS_17SomeSpecificClassT_U_FT_CS_9SomeClass' // Check the annoying case of capturing 'self' in a derived class 'init' // method. We allocate a mutable box to deal with 'self' potentially being // rebound by super.init, but 'self' is formally immutable and so is captured // by value. <rdar://problem/15599464> class Base {} class SelfCapturedInInit : Base { var foo : () -> SelfCapturedInInit // CHECK-LABEL: sil hidden @_TFC8closures18SelfCapturedInInitc{{.*}} : $@convention(method) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit { // CHECK: [[VAL:%.*]] = load_borrow {{%.*}} : $*SelfCapturedInInit // CHECK: [[VAL:%.*]] = load_borrow {{%.*}} : $*SelfCapturedInInit // CHECK: [[VAL:%.*]] = load [copy] {{%.*}} : $*SelfCapturedInInit // CHECK: partial_apply {{%.*}}([[VAL]]) : $@convention(thin) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit override init() { super.init() foo = { self } } } func takeClosure(_ fn: () -> Int) -> Int { return fn() } class TestCaptureList { var x = zero func testUnowned() { let aLet = self takeClosure { aLet.x } takeClosure { [unowned aLet] in aLet.x } takeClosure { [weak aLet] in aLet!.x } var aVar = self takeClosure { aVar.x } takeClosure { [unowned aVar] in aVar.x } takeClosure { [weak aVar] in aVar!.x } takeClosure { self.x } takeClosure { [unowned self] in self.x } takeClosure { [weak self] in self!.x } takeClosure { [unowned newVal = TestCaptureList()] in newVal.x } takeClosure { [weak newVal = TestCaptureList()] in newVal!.x } } } class ClassWithIntProperty { final var x = 42 } func closeOverLetLValue() { let a : ClassWithIntProperty a = ClassWithIntProperty() takeClosure { a.x } } // The let property needs to be captured into a temporary stack slot so that it // is loadable even though we capture the value. // CHECK-LABEL: sil shared @_TFF8closures18closeOverLetLValueFT_T_U_FT_Si : $@convention(thin) (@owned ClassWithIntProperty) -> Int { // CHECK: bb0([[ARG:%.*]] : $ClassWithIntProperty): // CHECK: [[TMP_CLASS_ADDR:%.*]] = alloc_stack $ClassWithIntProperty, let, name "a", argno 1 // CHECK: store [[ARG]] to [init] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: [[LOADED_CLASS:%.*]] = load [copy] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: [[INT_IN_CLASS_ADDR:%.*]] = ref_element_addr [[LOADED_CLASS]] : $ClassWithIntProperty, #ClassWithIntProperty.x // CHECK: [[INT_IN_CLASS:%.*]] = load [trivial] [[INT_IN_CLASS_ADDR]] : $*Int // CHECK: destroy_value [[LOADED_CLASS]] // CHECK: destroy_addr [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: dealloc_stack %1 : $*ClassWithIntProperty // CHECK: return [[INT_IN_CLASS]] // CHECK: } // end sil function '_TFF8closures18closeOverLetLValueFT_T_U_FT_Si' // Use an external function so inout deshadowing cannot see its body. @_silgen_name("takesNoEscapeClosure") func takesNoEscapeClosure(fn : () -> Int) struct StructWithMutatingMethod { var x = 42 mutating func mutatingMethod() { // This should not capture the refcount of the self shadow. takesNoEscapeClosure { x = 42; return x } } } // Check that the address of self is passed in, but not the refcount pointer. // CHECK-LABEL: sil hidden @_TFV8closures24StructWithMutatingMethod14mutatingMethod // CHECK: bb0(%0 : $*StructWithMutatingMethod): // CHECK: [[CLOSURE:%[0-9]+]] = function_ref @_TFFV8closures24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int // CHECK: partial_apply [[CLOSURE]](%0) : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int // Check that the closure body only takes the pointer. // CHECK-LABEL: sil shared @_TFFV8closures24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int { // CHECK: bb0(%0 : $*StructWithMutatingMethod): class SuperBase { func boom() {} } class SuperSub : SuperBase { override func boom() {} // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1afT_T_ : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1a.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: apply [[INNER]]([[SELF_COPY]]) // CHECK: } // end sil function '_TFC8closures8SuperSub1afT_T_' func a() { // CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[ARG]]) // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' func a1() { self.boom() super.boom() } a1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1bfT_T_ : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1b.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: = apply [[INNER]]([[SELF_COPY]]) // CHECK: } // end sil function '_TFC8closures8SuperSub1bfT_T_' func b() { // CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_TFFFC8closures8SuperSub1b.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: = apply [[INNER]]([[ARG_COPY]]) // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' func b1() { // CHECK: sil shared @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> () // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' func b2() { self.boom() super.boom() } b2() } b1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1cfT_T_ : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1c.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]]) // CHECK: [[PA_COPY:%.*]] = copy_value [[PA]] // CHECK: apply [[PA_COPY]]() // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '_TFC8closures8SuperSub1cfT_T_' func c() { // CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> () // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' let c1 = { () -> Void in self.boom() super.boom() } c1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1dfT_T_ : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1d.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]]) // CHECK: [[PA_COPY:%.*]] = copy_value [[PA]] // CHECK: apply [[PA_COPY]]() // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '_TFC8closures8SuperSub1dfT_T_' func d() { // CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_TFFFC8closures8SuperSub1d.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: = apply [[INNER]]([[ARG_COPY]]) // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' let d1 = { () -> Void in // CHECK: sil shared @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' func d2() { super.boom() } d2() } d1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1efT_T_ : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME1:_TFFC8closures8SuperSub1e.*]] : $@convention(thin) // CHECK: = apply [[INNER]]([[SELF_COPY]]) // CHECK: } // end sil function '_TFC8closures8SuperSub1efT_T_' func e() { // CHECK: sil shared @[[INNER_FUNC_NAME1]] : $@convention(thin) // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME2:_TFFFC8closures8SuperSub1e.*]] : $@convention(thin) // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]]) // CHECK: [[PA_COPY:%.*]] = copy_value [[PA]] // CHECK: apply [[PA_COPY]]() : $@callee_owned () -> () // CHECK: destroy_value [[PA]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_NAME1]]' func e1() { // CHECK: sil shared @[[INNER_FUNC_NAME2]] : $@convention(thin) // ChECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPERCAST:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPERCAST]]) // CHECK: destroy_value [[ARG_COPY_SUPERCAST]] // CHECK: destroy_value [[ARG]] // CHECK: return // CHECK: } // end sil function '[[INNER_FUNC_NAME2]]' let e2 = { super.boom() } e2() } e1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1ffT_T_ : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1fFT_T_U_FT_T_]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]]) // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '_TFC8closures8SuperSub1ffT_T_' func f() { // CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[TRY_APPLY_AUTOCLOSURE:%.*]] = function_ref @_TFsoi2qqurFzTGSqx_KzT_x_x : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error) // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_TFFFC8closures8SuperSub1fFT_T_U_FT_T_u_KzT_T_]] : $@convention(thin) (@owned SuperSub) -> @error Error // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]]) // CHECK: [[REABSTRACT_PA:%.*]] = partial_apply {{.*}}([[PA]]) // CHECK: try_apply [[TRY_APPLY_AUTOCLOSURE]]<()>({{.*}}, {{.*}}, [[REABSTRACT_PA]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]] // CHECK: [[NORMAL_BB]]{{.*}} // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' let f1 = { // CHECK: sil shared [transparent] @[[INNER_FUNC_2]] // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' nil ?? super.boom() } } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1gfT_T_ : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1g.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: = apply [[INNER]]([[SELF_COPY]]) // CHECK: } // end sil function '_TFC8closures8SuperSub1gfT_T_' func g() { // CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[TRY_APPLY_FUNC:%.*]] = function_ref @_TFsoi2qqurFzTGSqx_KzT_x_x : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error) // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_TFFFC8closures8SuperSub1g.*]] : $@convention(thin) (@owned SuperSub) -> @error Error // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]]) // CHECK: [[REABSTRACT_PA:%.*]] = partial_apply {{%.*}}([[PA]]) : $@convention(thin) (@owned @callee_owned () -> @error Error) -> (@out (), @error Error) // CHECK: try_apply [[TRY_APPLY_FUNC]]<()>({{.*}}, {{.*}}, [[REABSTRACT_PA]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]] // CHECK: [[NORMAL_BB]]{{.*}} // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' func g1() { // CHECK: sil shared [transparent] @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> @error Error { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' nil ?? super.boom() } g1() } } // CHECK-LABEL: sil hidden @_TFC8closures24UnownedSelfNestedCapture13nestedCapture{{.*}} : $@convention(method) (@guaranteed UnownedSelfNestedCapture) -> () // -- We enter with an assumed strong +1. // CHECK: bb0([[SELF:%.*]] : $UnownedSelfNestedCapture): // CHECK: [[OUTER_SELF_CAPTURE:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <@sil_unowned UnownedSelfNestedCapture> // CHECK: [[PB:%.*]] = project_box [[OUTER_SELF_CAPTURE]] // -- strong +2 // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UNOWNED_SELF:%.*]] = ref_to_unowned [[SELF_COPY]] : // -- TODO: A lot of fussy r/r traffic and owned/unowned conversions here. // -- strong +2, unowned +1 // CHECK: unowned_retain [[UNOWNED_SELF]] // CHECK: store [[UNOWNED_SELF]] to [init] [[PB]] // SEMANTIC ARC TODO: This destroy_value should probably be /after/ the load from PB on the next line. // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[UNOWNED_SELF:%.*]] = load [take] [[PB]] // -- strong +2, unowned +1 // CHECK: strong_retain_unowned [[UNOWNED_SELF]] // CHECK: [[SELF:%.*]] = unowned_to_ref [[UNOWNED_SELF]] // CHECK: [[UNOWNED_SELF2:%.*]] = ref_to_unowned [[SELF]] // -- strong +2, unowned +2 // CHECK: unowned_retain [[UNOWNED_SELF2]] // -- strong +1, unowned +2 // CHECK: destroy_value [[SELF]] // -- closure takes unowned ownership // CHECK: [[OUTER_CLOSURE:%.*]] = partial_apply {{%.*}}([[UNOWNED_SELF2]]) // -- call consumes closure // -- strong +1, unowned +1 // CHECK: [[INNER_CLOSURE:%.*]] = apply [[OUTER_CLOSURE]] // CHECK: [[CONSUMED_RESULT:%.*]] = apply [[INNER_CLOSURE]]() // CHECK: destroy_value [[CONSUMED_RESULT]] // -- destroy_values unowned self in box // -- strong +1, unowned +0 // CHECK: destroy_value [[OUTER_SELF_CAPTURE]] // -- strong +0, unowned +0 // CHECK: } // end sil function '_TFC8closures24UnownedSelfNestedCapture13nestedCapture{{.*}}' // -- outer closure // -- strong +0, unowned +1 // CHECK: sil shared @[[OUTER_CLOSURE_FUN:_TFFC8closures24UnownedSelfNestedCapture13nestedCaptureFT_T_U_FT_FT_S0_]] : $@convention(thin) (@owned @sil_unowned UnownedSelfNestedCapture) -> @owned @callee_owned () -> @owned UnownedSelfNestedCapture { // CHECK: bb0([[CAPTURED_SELF:%.*]] : $@sil_unowned UnownedSelfNestedCapture): // -- strong +0, unowned +2 // CHECK: [[CAPTURED_SELF_COPY:%.*]] = copy_value [[CAPTURED_SELF]] : // -- closure takes ownership of unowned ref // CHECK: [[INNER_CLOSURE:%.*]] = partial_apply {{%.*}}([[CAPTURED_SELF_COPY]]) // -- strong +0, unowned +1 (claimed by closure) // CHECK: destroy_value [[CAPTURED_SELF]] // CHECK: return [[INNER_CLOSURE]] // CHECK: } // end sil function '[[OUTER_CLOSURE_FUN]]' // -- inner closure // -- strong +0, unowned +1 // CHECK: sil shared @[[INNER_CLOSURE_FUN:_TFFFC8closures24UnownedSelfNestedCapture13nestedCapture.*]] : $@convention(thin) (@owned @sil_unowned UnownedSelfNestedCapture) -> @owned UnownedSelfNestedCapture { // CHECK: bb0([[CAPTURED_SELF:%.*]] : $@sil_unowned UnownedSelfNestedCapture): // -- strong +1, unowned +1 // CHECK: strong_retain_unowned [[CAPTURED_SELF:%.*]] : // CHECK: [[SELF:%.*]] = unowned_to_ref [[CAPTURED_SELF]] // -- strong +1, unowned +0 (claimed by return) // CHECK: destroy_value [[CAPTURED_SELF]] // CHECK: return [[SELF]] // CHECK: } // end sil function '[[INNER_CLOSURE_FUN]]' class UnownedSelfNestedCapture { func nestedCapture() { {[unowned self] in { self } }()() } } // Check that capturing 'self' via a 'super' call also captures the generic // signature if the base class is concrete and the derived class is generic class ConcreteBase { func swim() {} } // CHECK-LABEL: sil shared @_TFFC8closures14GenericDerived4swimFT_T_U_FT_T_ : $@convention(thin) <Ocean> (@owned GenericDerived<Ocean>) -> () // CHECK: bb0([[ARG:%.*]] : $GenericDerived<Ocean>): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $GenericDerived<Ocean> to $ConcreteBase // CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures12ConcreteBase4swimfT_T_ // CHECK: apply [[METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed ConcreteBase) -> () // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_TFFC8closures14GenericDerived4swimFT_T_U_FT_T_' class GenericDerived<Ocean> : ConcreteBase { override func swim() { withFlotationAid { super.swim() } } func withFlotationAid(_ fn: () -> ()) {} } // Don't crash on this func r25993258_helper(_ fn: (inout Int, Int) -> ()) {} func r25993258() { r25993258_helper { _ in () } }
apache-2.0
68cf54f898d244a89cdb425c1c48cf7a
47.610264
276
0.585055
3.298325
false
false
false
false
folio3/SocialNetwork
FacebookDemo/FacebookDemo/FacebookClasses/Parser/FBProfileParser.swift
1
3761
// // SDFBProfileParser.swift // ShreddDemand // // Created by Kabir on 15/10/2015. // Copyright (c) 2014–2016 Folio3 Pvt Ltd (http://www.folio3.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation class FBProfileParser: BaseParser { /** Parse objet - Parameter object: That needs to paresed - Parameter parseType: Use enum in sepecfic class to class for a particular parse methods. Default value is Zero - Parameter completion: call back. - Throws: nil - Returns: nil */ override func parse(parseType: Int, object: AnyObject?, completion: ParserCompletionCallback!) { guard let response = self.getJson(object) else { return completion(result: nil, error: nil) } completion(result: self.parseUserProfile(response), error: nil) } func parseUserProfile(response: JSON) -> FacebookUserProfile { let birthday = response["profile"]["birthday"].stringValue let email = response["profile"]["email"].stringValue let gender = response["profile"]["gender"].stringValue let name = response["profile"]["name"].stringValue let firstName = response["profile"]["first_name"].stringValue let lastName = response["profile"]["last_name"].stringValue let userId = response["profile"]["id"].numberValue let uri = response["profile"]["picture"]["data"]["url"].stringValue let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy" let date = dateFormatter.dateFromString(birthday) let profile = FacebookUserProfile() profile.firstName = firstName profile.lastName = lastName profile.name = name profile.birthday = date profile.gender = gender profile.userId = userId profile.email = email profile.socialNetworkAvatarUri = uri // let socialNetwork = self.parseSocialNetwork(response) // socialNetwork.addUserProfile(profile) // profile.addSocialNetwork(socialNetwork) return profile } // override func parseSocialNetwork(response: JSON) -> SocialNetwork { // // let appId = response["app_id"].stringValue // let identifier = SDBalConstants.SocialNetwork.Facebook.hashValue // let name = SDBalConstants.SocialNetwork.Facebook.rawValue // // let network = SocialNetwork.MR_findFirstOrCreateByAttribute("identifier", withValue: identifier, inContext: context) // network.appId = appId // network.identifier = identifier // network.name = name // // return network // } }
mit
77ed071c040126b94f70a1f1bf4904d3
38.166667
126
0.675446
4.623616
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/ReadingListsController.swift
1
32850
import Foundation // Sync keys let WMFReadingListSyncStateKey = "WMFReadingListsSyncState" private let WMFReadingListSyncRemotelyEnabledKey = "WMFReadingListSyncRemotelyEnabled" let WMFReadingListUpdateKey = "WMFReadingListUpdateKey" // Default list key private let WMFReadingListDefaultListEnabledKey = "WMFReadingListDefaultListEnabled" // Batch size keys let WMFReadingListBatchSizePerRequestLimit = 500 let WMFReadingListCoreDataBatchSize = 500 // Reading lists config keys let WMFReadingListsConfigMaxEntriesPerList = "WMFReadingListsConfigMaxEntriesPerList" let WMFReadingListsConfigMaxListsPerUser = "WMFReadingListsConfigMaxListsPerUser" struct ReadingListSyncState: OptionSet { let rawValue: Int64 static let needsRemoteEnable = ReadingListSyncState(rawValue: 1 << 0) static let needsSync = ReadingListSyncState(rawValue: 1 << 1) static let needsUpdate = ReadingListSyncState(rawValue: 1 << 2) static let needsRemoteDisable = ReadingListSyncState(rawValue: 1 << 3) static let needsLocalReset = ReadingListSyncState(rawValue: 1 << 4) // mark all as unsynced, remove remote IDs static let needsLocalArticleClear = ReadingListSyncState(rawValue: 1 << 5) // remove all saved articles static let needsLocalListClear = ReadingListSyncState(rawValue: 1 << 6) // remove all lists static let needsRandomLists = ReadingListSyncState(rawValue: 1 << 7) // for debugging, populate random lists static let needsRandomEntries = ReadingListSyncState(rawValue: 1 << 8) // for debugging, populate with random entries static let needsEnable: ReadingListSyncState = [.needsRemoteEnable, .needsSync] static let needsLocalClear: ReadingListSyncState = [.needsLocalArticleClear, .needsLocalListClear] static let needsClearAndEnable: ReadingListSyncState = [.needsLocalClear, .needsRemoteEnable, .needsSync] static let needsDisable: ReadingListSyncState = [.needsRemoteDisable, .needsLocalReset] } public enum ReadingListError: Error, Equatable { case listExistsWithTheSameName case unableToCreateList case generic case unableToDeleteList case unableToUpdateList case unableToAddEntry case unableToRemoveEntry case entryLimitReached(name: String, count: Int, limit: Int) case listWithProvidedNameNotFound(name: String) case listLimitReached(limit: Int) case listEntryLimitsReached(name: String, count: Int, listLimit: Int, entryLimit: Int) public var localizedDescription: String { switch self { case .generic: return WMFLocalizedString("reading-list-generic-error", value: "An unexpected error occurred while updating your reading lists.", comment: "An unexpected error occurred while updating your reading lists.") case .listExistsWithTheSameName: return WMFLocalizedString("reading-list-exists-with-same-name", value: "Reading list name already in use", comment: "Informs the user that a reading list exists with the same name.") case .listWithProvidedNameNotFound(let name): let format = WMFLocalizedString("reading-list-with-provided-name-not-found", value: "A reading list with the name “%1$@” was not found. Please make sure you have the correct name.", comment: "Informs the user that a reading list with the name they provided was not found. %1$@ will be replaced with the name of the reading list which could not be found") return String.localizedStringWithFormat(format, name) case .unableToCreateList: return WMFLocalizedString("reading-list-unable-to-create", value: "An unexpected error occurred while creating your reading list. Please try again later.", comment: "Informs the user that an error occurred while creating their reading list.") case .unableToDeleteList: return WMFLocalizedString("reading-list-unable-to-delete", value: "An unexpected error occurred while deleting your reading list. Please try again later.", comment: "Informs the user that an error occurred while deleting their reading list.") case .unableToUpdateList: return WMFLocalizedString("reading-list-unable-to-update", value: "An unexpected error occurred while updating your reading list. Please try again later.", comment: "Informs the user that an error occurred while updating their reading list.") case .unableToAddEntry: return WMFLocalizedString("reading-list-unable-to-add-entry", value: "An unexpected error occurred while adding an entry to your reading list. Please try again later.", comment: "Informs the user that an error occurred while adding an entry to their reading list.") case .entryLimitReached(let name, let count, let limit): return String.localizedStringWithFormat(CommonStrings.readingListsEntryLimitReachedFormat, count, limit, name) case .unableToRemoveEntry: return WMFLocalizedString("reading-list-unable-to-remove-entry", value: "An unexpected error occurred while removing an entry from your reading list. Please try again later.", comment: "Informs the user that an error occurred while removing an entry from their reading list.") case .listLimitReached(let limit): return String.localizedStringWithFormat(CommonStrings.readingListsListLimitReachedFormat, limit) case .listEntryLimitsReached(let name, let count, let listLimit, let entryLimit): let entryLimitReached = String.localizedStringWithFormat(CommonStrings.readingListsEntryLimitReachedFormat, count, entryLimit, name) let listLimitReached = String.localizedStringWithFormat(CommonStrings.readingListsListLimitReachedFormat, listLimit) return "\(entryLimitReached)\n\n\(listLimitReached)" } } public static func ==(lhs: ReadingListError, rhs: ReadingListError) -> Bool { return lhs.localizedDescription == rhs.localizedDescription //shrug } } public typealias ReadingListsController = WMFReadingListsController @objc public class WMFReadingListsController: NSObject { @objc public static let readingListsServerDidConfirmSyncWasEnabledForAccountNotification = NSNotification.Name("WMFReadingListsServerDidConfirmSyncWasEnabledForAccount") @objc public static let readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncEnabledKey = NSNotification.Name("wasSyncEnabledForAccount") @objc public static let readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncEnabledOnDeviceKey = NSNotification.Name("wasSyncEnabledOnDevice") @objc public static let readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncDisabledOnDeviceKey = NSNotification.Name("wasSyncDisabledOnDevice") @objc public static let syncDidStartNotification = NSNotification.Name(rawValue: "WMFSyncDidStartNotification") @objc public static let readingListsWereSplitNotification = NSNotification.Name("WMFReadingListsWereSplit") @objc public static let readingListsWereSplitNotificationEntryLimitKey = NSNotification.Name("WMFReadingListsWereSplitNotificationEntryLimitKey") @objc public static let syncDidFinishNotification = NSNotification.Name(rawValue: "WMFSyncFinishedNotification") @objc public static let syncDidFinishErrorKey = NSNotification.Name(rawValue: "error") @objc public static let syncDidFinishSyncedReadingListsCountKey = NSNotification.Name(rawValue: "syncedReadingLists") @objc public static let syncDidFinishSyncedReadingListEntriesCountKey = NSNotification.Name(rawValue: "syncedReadingListEntries") internal weak var dataStore: MWKDataStore! internal let apiController = ReadingListsAPIController() public weak var authenticationDelegate: AuthenticationDelegate? private let operationQueue = OperationQueue() private var updateTimer: Timer? private var observedOperations: [Operation: NSKeyValueObservation] = [:] private var isSyncing = false { didSet { guard oldValue != isSyncing, isSyncing else { return } DispatchQueue.main.async { NotificationCenter.default.post(name: ReadingListsController.syncDidStartNotification, object: nil) } } } @objc init(dataStore: MWKDataStore) { self.dataStore = dataStore super.init() operationQueue.maxConcurrentOperationCount = 1 } private func addOperation(_ operation: ReadingListsOperation) { observedOperations[operation] = operation.observe(\.state, changeHandler: { (operation, change) in if operation.isFinished { self.observedOperations.removeValue(forKey: operation)?.invalidate() DispatchQueue.main.async { var userInfo: [Notification.Name: Any] = [:] if let error = operation.error { userInfo[ReadingListsController.syncDidFinishErrorKey] = error } if let syncOperation = operation as? ReadingListsSyncOperation { userInfo[ReadingListsController.syncDidFinishSyncedReadingListsCountKey] = syncOperation.syncedReadingListsCount userInfo[ReadingListsController.syncDidFinishSyncedReadingListEntriesCountKey] = syncOperation.syncedReadingListEntriesCount } NotificationCenter.default.post(name: ReadingListsController.syncDidFinishNotification, object: nil, userInfo: userInfo) self.isSyncing = false } } else if operation.isExecuting { self.isSyncing = true } }) operationQueue.addOperation(operation) } // User-facing actions. Everything is performed on the main context public func createReadingList(named name: String, description: String? = nil, with articles: [WMFArticle] = []) throws -> ReadingList { assert(Thread.isMainThread) let moc = dataStore.viewContext let list = try createReadingList(named: name, description: description, with: articles, in: moc) if moc.hasChanges { try moc.save() } let listLimit = moc.wmf_readingListsConfigMaxListsPerUser let readingListsCount = try moc.allReadingListsCount() guard readingListsCount + 1 <= listLimit else { throw ReadingListError.listLimitReached(limit: listLimit) } try throwLimitErrorIfNecessary(for: nil, articles: [], in: moc) sync() return list } private func throwLimitErrorIfNecessary(for readingList: ReadingList?, articles: [WMFArticle], in moc: NSManagedObjectContext) throws { let listLimit = moc.wmf_readingListsConfigMaxListsPerUser let entryLimit = moc.wmf_readingListsConfigMaxEntriesPerList.intValue let readingListsCount = try moc.allReadingListsCount() let countOfEntries = Int(readingList?.countOfEntries ?? 0) let willExceedListLimit = readingListsCount + 1 > listLimit let didExceedListLimit = readingListsCount > listLimit let willExceedEntryLimit = countOfEntries + articles.count > entryLimit if let name = readingList?.name { if didExceedListLimit && willExceedEntryLimit { throw ReadingListError.listEntryLimitsReached(name: name, count: articles.count, listLimit: listLimit, entryLimit: entryLimit) } else if willExceedEntryLimit { throw ReadingListError.entryLimitReached(name: name, count: articles.count, limit: entryLimit) } } else if willExceedListLimit { throw ReadingListError.listLimitReached(limit: listLimit) } } public func createReadingList(named name: String, description: String? = nil, with articles: [WMFArticle] = [], in moc: NSManagedObjectContext) throws -> ReadingList { let listExistsWithTheSameName = try listExists(with: name, in: moc) guard !listExistsWithTheSameName else { throw ReadingListError.listExistsWithTheSameName } guard let list = moc.wmf_create(entityNamed: "ReadingList", withKeysAndValues: ["canonicalName": name, "readingListDescription": description]) as? ReadingList else { throw ReadingListError.unableToCreateList } list.createdDate = NSDate() list.updatedDate = list.createdDate list.isUpdatedLocally = true try add(articles: articles, to: list, in: moc) return list } func listExists(with name: String, in moc: NSManagedObjectContext) throws -> Bool { let name = name.precomposedStringWithCanonicalMapping let existingOrDefaultListRequest: NSFetchRequest<ReadingList> = ReadingList.fetchRequest() existingOrDefaultListRequest.predicate = NSPredicate(format: "canonicalName MATCHES %@ or isDefault == YES", name) existingOrDefaultListRequest.fetchLimit = 2 let lists = try moc.fetch(existingOrDefaultListRequest) return lists.first(where: { $0.name == name }) != nil } public func updateReadingList(_ readingList: ReadingList, with newName: String?, newDescription: String?) { assert(Thread.isMainThread) guard !readingList.isDefault else { assertionFailure("Default reading list cannot be updated") return } let moc = dataStore.viewContext if let newName = newName, !newName.isEmpty { readingList.name = newName } readingList.readingListDescription = newDescription readingList.isUpdatedLocally = true if moc.hasChanges { do { try moc.save() } catch let error { DDLogError("Error updating name or description for reading list: \(error)") } } sync() } /// Marks that reading lists were deleted locally and updates associated objects. Doesn't delete them from the NSManagedObjectContext - that should happen only with confirmation from the server that they were deleted. /// /// - Parameters: /// - readingLists: the reading lists to delete func markLocalDeletion(for readingLists: [ReadingList]) throws { for readingList in readingLists { readingList.isDeletedLocally = true readingList.isUpdatedLocally = true try markLocalDeletion(for: Array(readingList.entries ?? [])) } } /// Marks that reading list entries were deleted locally and updates associated objects. Doesn't delete them from the NSManagedObjectContext - that should happen only with confirmation from the server that they were deleted. /// /// - Parameters: /// - readingListEntriess: the reading lists to delete internal func markLocalDeletion(for readingListEntries: [ReadingListEntry]) throws { guard readingListEntries.count > 0 else { return } var lists: Set<ReadingList> = [] for entry in readingListEntries { entry.isDeletedLocally = true entry.isUpdatedLocally = true guard let list = entry.list else { continue } lists.insert(list) } for list in lists { try list.updateArticlesAndEntries() } } public func delete(readingLists: [ReadingList]) throws { assert(Thread.isMainThread) let moc = dataStore.viewContext try markLocalDeletion(for: readingLists) if moc.hasChanges { try moc.save() } sync() } internal func add(articles: [WMFArticle], to readingList: ReadingList, in moc: NSManagedObjectContext) throws { guard articles.count > 0 else { return } var existingKeys = Set(readingList.articleKeys) for article in articles { guard let key = article.key, !existingKeys.contains(key) else { continue } guard let entry = moc.wmf_create(entityNamed: "ReadingListEntry", withValue: key, forKey: "articleKey") as? ReadingListEntry else { return } existingKeys.insert(key) entry.createdDate = NSDate() entry.updatedDate = entry.createdDate entry.isUpdatedLocally = true entry.displayTitle = article.displayTitle entry.list = readingList } try readingList.updateArticlesAndEntries() } public func add(articles: [WMFArticle], to readingList: ReadingList) throws { assert(Thread.isMainThread) let moc = dataStore.viewContext try throwLimitErrorIfNecessary(for: readingList, articles: articles, in: moc) try add(articles: articles, to: readingList, in: moc) if moc.hasChanges { try moc.save() } sync() } var syncState: ReadingListSyncState { get { assert(Thread.isMainThread) let rawValue = dataStore.viewContext.wmf_numberValue(forKey: WMFReadingListSyncStateKey)?.int64Value ?? 0 return ReadingListSyncState(rawValue: rawValue) } set { assert(Thread.isMainThread) let moc = dataStore.viewContext moc.wmf_setValue(NSNumber(value: newValue.rawValue), forKey: WMFReadingListSyncStateKey) do { try moc.save() } catch let error { DDLogError("Error saving after sync state update: \(error)") } } } public func debugSync(createLists: Bool, listCount: Int64, addEntries: Bool, entryCount: Int64, deleteLists: Bool, deleteEntries: Bool, doFullSync: Bool, completion: @escaping () -> Void) { dataStore.viewContext.wmf_setValue(NSNumber(value: listCount), forKey: "WMFCountOfListsToCreate") dataStore.viewContext.wmf_setValue(NSNumber(value: entryCount), forKey: "WMFCountOfEntriesToCreate") let oldValue = syncState var newValue = oldValue if createLists { newValue.insert(.needsRandomLists) } else { newValue.remove(.needsRandomLists) } if addEntries { newValue.insert(.needsRandomEntries) } else { newValue.remove(.needsRandomEntries) } if deleteLists { newValue.insert(.needsLocalListClear) } else { newValue.remove(.needsLocalListClear) } if deleteEntries { newValue.insert(.needsLocalArticleClear) } else { newValue.remove(.needsLocalArticleClear) } cancelSync { self.syncState = newValue if doFullSync { self.fullSync(completion) } else { self.backgroundUpdate(completion) } } } // is sync enabled for this user @objc public var isSyncEnabled: Bool { assert(Thread.isMainThread) let state = syncState return state.contains(.needsSync) || state.contains(.needsUpdate) } // is sync available or is it shut down server-side @objc public var isSyncRemotelyEnabled: Bool { get { assert(Thread.isMainThread) let moc = dataStore.viewContext return moc.wmf_isSyncRemotelyEnabled } set { assert(Thread.isMainThread) let moc = dataStore.viewContext moc.wmf_isSyncRemotelyEnabled = newValue } } // should the default list be shown to the user @objc public var isDefaultListEnabled: Bool { get { assert(Thread.isMainThread) let moc = dataStore.viewContext return moc.wmf_numberValue(forKey: WMFReadingListDefaultListEnabledKey)?.boolValue ?? false } set { assert(Thread.isMainThread) let moc = dataStore.viewContext moc.wmf_setValue(NSNumber(value: newValue), forKey: WMFReadingListDefaultListEnabledKey) do { try moc.save() } catch let error { DDLogError("Error saving after sync state update: \(error)") } } } func postReadingListsServerDidConfirmSyncWasEnabledForAccountNotification(_ wasSyncEnabledForAccount: Bool) { // we want to know if sync was ever enabled on this device let wasSyncEnabledOnDevice = apiController.lastRequestType == .setup let wasSyncDisabledOnDevice = apiController.lastRequestType == .teardown DispatchQueue.main.async { NotificationCenter.default.post(name: ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountNotification, object: nil, userInfo: [ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncEnabledKey: NSNumber(value: wasSyncEnabledForAccount), ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncEnabledOnDeviceKey: NSNumber(value: wasSyncEnabledOnDevice), ReadingListsController.readingListsServerDidConfirmSyncWasEnabledForAccountWasSyncDisabledOnDeviceKey: NSNumber(value: wasSyncDisabledOnDevice)]) } } @objc public func setSyncEnabled(_ isSyncEnabled: Bool, shouldDeleteLocalLists: Bool, shouldDeleteRemoteLists: Bool) { let oldSyncState = self.syncState var newSyncState = oldSyncState if shouldDeleteLocalLists { newSyncState.insert(.needsLocalClear) } else { newSyncState.insert(.needsLocalReset) } if isSyncEnabled { newSyncState.insert(.needsRemoteEnable) newSyncState.insert(.needsSync) newSyncState.remove(.needsUpdate) newSyncState.remove(.needsRemoteDisable) } else { if shouldDeleteRemoteLists { newSyncState.insert(.needsRemoteDisable) } newSyncState.remove(.needsSync) newSyncState.remove(.needsUpdate) newSyncState.remove(.needsRemoteEnable) } guard newSyncState != oldSyncState else { return } self.syncState = newSyncState sync() } @objc public func start() { guard updateTimer == nil else { return } assert(Thread.isMainThread) updateTimer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(sync), userInfo: nil, repeats: true) sync() } private func cancelSync(_ completion: @escaping () -> Void) { operationQueue.cancelAllOperations() apiController.cancelPendingTasks() operationQueue.addOperation { DispatchQueue.main.async(execute: completion) } } @objc public func stop(_ completion: @escaping () -> Void) { assert(Thread.isMainThread) updateTimer?.invalidate() updateTimer = nil cancelSync(completion) } @objc public func backgroundUpdate(_ completion: @escaping () -> Void) { #if TEST #else let sync = ReadingListsSyncOperation(readingListsController: self) addOperation(sync) operationQueue.addOperation { DispatchQueue.main.async(execute: completion) } #endif } @objc public func fullSync(_ completion: @escaping () -> Void) { #if TEST #else var newValue = self.syncState if newValue.contains(.needsUpdate) { newValue.remove(.needsUpdate) newValue.insert(.needsSync) self.syncState = newValue } let sync = ReadingListsSyncOperation(readingListsController: self) addOperation(sync) operationQueue.addOperation { DispatchQueue.main.async(execute: completion) } #endif } @objc private func _sync() { let sync = ReadingListsSyncOperation(readingListsController: self) addOperation(sync) } @objc private func _syncIfNotSyncing() { guard operationQueue.operationCount == 0 else { return } _sync() } @objc public func sync() { #if TEST #else assert(Thread.isMainThread) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(_syncIfNotSyncing), object: nil) perform(#selector(_syncIfNotSyncing), with: nil, afterDelay: 0.5) #endif } public func remove(articles: [WMFArticle], readingList: ReadingList) throws { assert(Thread.isMainThread) let moc = dataStore.viewContext let articleKeys = articles.compactMap { $0.key } let entriesRequest: NSFetchRequest<ReadingListEntry> = ReadingListEntry.fetchRequest() entriesRequest.predicate = NSPredicate(format: "list == %@ && articleKey IN %@", readingList, articleKeys) let entriesToDelete = try moc.fetch(entriesRequest) try remove(entries: entriesToDelete) } public func remove(entries: [ReadingListEntry]) throws { assert(Thread.isMainThread) let moc = dataStore.viewContext try markLocalDeletion(for: entries) if moc.hasChanges { try moc.save() } sync() } @objc public func save(_ article: WMFArticle) { assert(Thread.isMainThread) do { let moc = dataStore.viewContext try article.addToDefaultReadingList() if moc.hasChanges { try moc.save() } sync() } catch let error { DDLogError("Error adding article to default list: \(error)") } } @objc public func addArticleToDefaultReadingList(_ article: WMFArticle) throws { try article.addToDefaultReadingList() } @objc(unsaveArticle:inManagedObjectContext:) public func unsaveArticle(_ article: WMFArticle, in moc: NSManagedObjectContext) { unsave([article], in: moc) } @objc(unsaveArticles:inManagedObjectContext:) public func unsave(_ articles: [WMFArticle], in moc: NSManagedObjectContext) { do { let keys = articles.compactMap { $0.key } let entryFetchRequest: NSFetchRequest<ReadingListEntry> = ReadingListEntry.fetchRequest() entryFetchRequest.predicate = NSPredicate(format: "articleKey IN %@", keys) let entries = try moc.fetch(entryFetchRequest) try markLocalDeletion(for: entries) } catch let error { DDLogError("Error removing article from default list: \(error)") } } @objc public func removeArticlesWithURLsFromDefaultReadingList(_ articleURLs: [URL]) { assert(Thread.isMainThread) do { let moc = dataStore.viewContext for url in articleURLs { guard let article = dataStore.fetchArticle(with: url) else { continue } unsave([article], in: moc) } if moc.hasChanges { try moc.save() } sync() } catch let error { DDLogError("Error removing all articles from default list: \(error)") } } } public extension WMFArticle { func fetchReadingListEntries() throws -> [ReadingListEntry] { guard let moc = managedObjectContext, let key = key else { return [] } let entryFetchRequest: NSFetchRequest<ReadingListEntry> = ReadingListEntry.fetchRequest() entryFetchRequest.predicate = NSPredicate(format: "articleKey == %@", key) return try moc.fetch(entryFetchRequest) } func fetchDefaultListEntry() throws -> ReadingListEntry? { let readingListEntries = try fetchReadingListEntries() return readingListEntries.first(where: { (entry) -> Bool in return (entry.list?.isDefault ?? false) && !entry.isDeletedLocally }) } } extension WMFArticle { func addToDefaultReadingList() throws { guard let moc = self.managedObjectContext else { return } guard try fetchDefaultListEntry() == nil else { return } guard let defaultReadingList = moc.wmf_fetchDefaultReadingList() else { return } guard let defaultListEntry = NSEntityDescription.insertNewObject(forEntityName: "ReadingListEntry", into: moc) as? ReadingListEntry else { return } defaultListEntry.createdDate = NSDate() defaultListEntry.updatedDate = defaultListEntry.createdDate defaultListEntry.articleKey = self.key defaultListEntry.list = defaultReadingList defaultListEntry.displayTitle = displayTitle defaultListEntry.isUpdatedLocally = true try defaultReadingList.updateArticlesAndEntries() } func readingListsDidChange() { let readingLists = self.readingLists ?? [] if readingLists.count == 0 && savedDate != nil { savedDate = nil } else if readingLists.count > 0 && savedDate == nil { savedDate = Date() } } @objc public var isInDefaultList: Bool { guard let readingLists = self.readingLists else { return false } return readingLists.filter { $0.isDefault }.count > 0 } @objc public var isOnlyInDefaultList: Bool { return (readingLists ?? []).count == 1 && isInDefaultList } @objc public var readingListsCount: Int { return (readingLists ?? []).count } @objc public var userCreatedReadingLists: [ReadingList] { return (readingLists ?? []).filter { !$0.isDefault } } @objc public var userCreatedReadingListsCount: Int { return userCreatedReadingLists.count } } public extension NSManagedObjectContext { // use with caution, fetching is expensive @objc func wmf_fetchDefaultReadingList() -> ReadingList? { var defaultList = wmf_fetch(objectForEntityName: "ReadingList", withValue: NSNumber(value: true), forKey: "isDefault") as? ReadingList if defaultList == nil { // failsafe defaultList = wmf_fetch(objectForEntityName: "ReadingList", withValue: ReadingList.defaultListCanonicalName, forKey: "canonicalName") as? ReadingList defaultList?.isDefault = true } return defaultList } // is sync available or is it shut down server-side @objc public var wmf_isSyncRemotelyEnabled: Bool { get { return wmf_numberValue(forKey: WMFReadingListSyncRemotelyEnabledKey)?.boolValue ?? true } set { guard newValue != wmf_isSyncRemotelyEnabled else { return } wmf_setValue(NSNumber(value: newValue), forKey: WMFReadingListSyncRemotelyEnabledKey) do { try save() } catch let error { DDLogError("Error saving after sync state update: \(error)") } } } // MARK: - Reading lists config @objc public var wmf_readingListsConfigMaxEntriesPerList: NSNumber { get { return wmf_numberValue(forKey: WMFReadingListsConfigMaxEntriesPerList) ?? 5000 } set { wmf_setValue(newValue, forKey: WMFReadingListsConfigMaxEntriesPerList) do { try save() } catch let error { DDLogError("Error saving new value for WMFReadingListsConfigMaxEntriesPerList: \(error)") } } } @objc public var wmf_readingListsConfigMaxListsPerUser: Int { get { return wmf_numberValue(forKey: WMFReadingListsConfigMaxListsPerUser)?.intValue ?? 100 } set { wmf_setValue(NSNumber(value: newValue), forKey: WMFReadingListsConfigMaxListsPerUser) do { try save() } catch let error { DDLogError("Error saving new value for WMFReadingListsConfigMaxListsPerUser: \(error)") } } } func allReadingListsCount() throws -> Int { assert(Thread.isMainThread) let request: NSFetchRequest<ReadingList> = ReadingList.fetchRequest() request.predicate = NSPredicate(format: "isDeletedLocally == NO") return try self.count(for: request) } }
mit
154c816901d80d0b4f623c6dff63d827
42.332454
588
0.657553
5.266314
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Business/WalletJournal/CorpWalletJournal.swift
2
2272
// // CorpWalletJournal.swift // Neocom // // Created by Artem Shimanski on 7/2/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import EVEAPI import Alamofire import Combine struct CorpWalletJournal: View { @Environment(\.managedObjectContext) private var managedObjectContext @EnvironmentObject private var sharedState: SharedState @ObservedObject var journal: Lazy<DataLoader<ESI.WalletJournal, AFError>, Account> = Lazy() private func getJournal(characterID: Int64, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> AnyPublisher<ESI.WalletJournal, AFError> { sharedState.esi.characters.characterID(Int(characterID)).wallet().journal().get(cachePolicy: cachePolicy) .map{$0.value} .receive(on: RunLoop.main) .eraseToAnyPublisher() } var body: some View { let result = sharedState.account.map { account in self.journal.get(account, initial: DataLoader(self.getJournal(characterID: account.characterID))) } let list = List { if result?.result?.value != nil { WalletJournalContent(journal: result!.result!.value!) } } .listStyle(GroupedListStyle()) .overlay(result == nil ? Text(RuntimeError.noAccount).padding() : nil) .overlay((result?.result?.error).map{Text($0)}) .overlay(result?.result?.value?.isEmpty == true ? Text(RuntimeError.noResult).padding() : nil) return Group { if result != nil { list.onRefresh(isRefreshing: Binding(result!, keyPath: \.isLoading)) { guard let account = self.sharedState.account else {return} result?.update(self.getJournal(characterID: account.characterID, cachePolicy: .reloadIgnoringLocalCacheData)) } } else { list } } .navigationBarTitle(Text("Wallet Journal")) } } #if DEBUG struct CorpWalletJournal_Previews: PreviewProvider { static var previews: some View { NavigationView { CorpWalletJournal() } .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
dafa63d39ab8b4508aaf070fc7cd30f6
32.397059
156
0.628358
4.904968
false
false
false
false
VadimPavlov/Swifty
Sources/Swifty/Common/Foundation/String.swift
1
1434
// // String.swift // Created by Vadim Pavlov on 26.07.16. #if canImport(UIKit) import UIKit public typealias Color = UIColor public typealias Font = UIFont #endif #if canImport(AppKit) import AppKit public typealias Color = NSColor public typealias Font = NSFont #endif public extension String { func foregroundColorString(color: Color) -> NSAttributedString { return NSAttributedString(string: self, attributes: [.foregroundColor : color]) } func asHTML(font: Font? = nil, color: Color? = nil) -> NSAttributedString? { guard let data = self.data(using: .utf8) else { return nil } let type = NSAttributedString.DocumentType.html let encoding = String.Encoding.utf8.rawValue let html = try? NSAttributedString(data: data, options: [.documentType: type, .characterEncoding: encoding], documentAttributes: nil) guard let htmlString = html else { return nil } let result = NSMutableAttributedString(attributedString: htmlString) let range = NSRange(location: 0, length: result.length) if let font = font { result.addAttribute(.font, value: font, range: range) } if let color = color { result.addAttribute(.foregroundColor, value: color, range: range) } return result } }
mit
5a50a0676f8f064c2cb350e6537e09e7
31.590909
105
0.624128
4.78
false
false
false
false
GuiBayma/PasswordVault
PasswordVault/Scenes/Item Detail/ItemDetailViewController.swift
1
1045
// // ItemDetailViewController.swift // PasswordVault // // Created by Guilherme Bayma on 8/1/17. // Copyright © 2017 Bayma. All rights reserved. // import UIKit class ItemDetailViewController: UIViewController { // MARK: - Variables fileprivate let itemDetailView = ItemDetailView() var item: Item? // MARK: - Initializing required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func loadView() { self.view = itemDetailView } // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() setUpLabels() } // MARK: - Set up labels func setUpLabels() { itemDetailView.nameLabel.text = item?.name itemDetailView.userLabel.text = item?.userName itemDetailView.passwordLabel.text = item?.password } }
mit
998deea5a61cef9a6719e837afac23e2
20.75
82
0.654215
4.578947
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Core/Util/AssetManager+LivePhotoURL.swift
1
16087
// // AssetManager+LivePhotoURL.swift // HXPHPicker // // Created by Slience on 2021/1/8. // import UIKit import Photos public extension AssetManager { // MARK: 获取LivePhoto里的图片Data和视频地址 static func requestLivePhoto( content asset: PHAsset, imageDataHandler: @escaping (Data?) -> Void, videoHandler: @escaping (URL?) -> Void, completionHandler: @escaping (LivePhotoError?) -> Void ) { if #available(iOS 9.1, *) { requestLivePhoto( for: asset, targetSize: PHImageManagerMaximumSize ) { (ID) in } progressHandler: { (progress, error, stop, info) in } resultHandler: { (livePhoto, info, downloadSuccess) in if livePhoto == nil { completionHandler( .allError( PhotoError.error( type: .imageEmpty, message: "livePhoto为nil,获取失败" ), PhotoError.error( type: .videoEmpty, message: "livePhoto为nil,获取失败" ) ) ) return } let assetResources: [PHAssetResource] = PHAssetResource.assetResources(for: livePhoto!) if assetResources.isEmpty { completionHandler( .allError( PhotoError.error( type: .imageEmpty, message: "assetResources为nil,获取失败" ), PhotoError.error( type: .videoEmpty, message: "assetResources为nil,获取失败" ) ) ) return } let options = PHAssetResourceRequestOptions.init() options.isNetworkAccessAllowed = true var imageCompletion = false var imageError: Error? var videoCompletion = false var videoError: Error? var imageData: Data? let videoURL = PhotoTools.getVideoTmpURL() let callback = {(imageError: Error?, videoError: Error?) in if imageError != nil && videoError != nil { completionHandler(.allError(imageError, videoError)) }else if imageError != nil { completionHandler(.imageError(imageError)) }else if videoError != nil { completionHandler(.videoError(videoError)) }else { completionHandler(nil) } } var hasAdjustmentData = false for assetResource in assetResources where assetResource.type == .adjustmentData { hasAdjustmentData = true break } for assetResource in assetResources { var photoType: PHAssetResourceType = .photo var videoType: PHAssetResourceType = .pairedVideo if hasAdjustmentData { photoType = .fullSizePhoto videoType = .fullSizePairedVideo } if assetResource.type == photoType { PHAssetResourceManager.default().requestData(for: assetResource, options: options) { (data) in imageData = data DispatchQueue.main.async { imageDataHandler(imageData) } } completionHandler: { (error) in imageError = error DispatchQueue.main.async { if videoCompletion { callback(imageError, videoError) } imageCompletion = true } } }else if assetResource.type == videoType { PHAssetResourceManager.default().writeData( for: assetResource, toFile: videoURL, options: options ) { (error) in DispatchQueue.main.async { if error == nil { videoHandler(videoURL) } videoCompletion = true videoError = error if imageCompletion { callback(imageError, videoError) } } } } } } } else { // Fallback on earlier versions completionHandler( .allError( PhotoError.error( type: .imageEmpty, message: "系统版本低于9.1" ), PhotoError.error( type: .videoEmpty, message: "系统版本低于9.1" ) ) ) } } /// 获取LivePhoto里的视频地址 /// - Parameters: /// - forAsset: 对应的 PHAsset 对象 /// - fileURL: 指定视频地址 /// - completionHandler: 获取完成 static func requestLivePhoto( videoURL forAsset: PHAsset, toFile fileURL: URL, completionHandler: @escaping (URL?, LivePhotoError?) -> Void ) { if #available(iOS 9.1, *) { requestLivePhoto( for: forAsset, targetSize: PHImageManagerMaximumSize ) { (ID) in } progressHandler: { (progress, error, stop, info) in } resultHandler: { (livePhoto, info, downloadSuccess) in if livePhoto == nil { completionHandler( nil, .allError( PhotoError.error( type: .imageEmpty, message: "livePhoto为nil,获取失败"), PhotoError.error( type: .videoEmpty, message: "livePhoto为nil,获取失败" ) ) ) return } let assetResources: [PHAssetResource] = PHAssetResource.assetResources(for: livePhoto!) if assetResources.isEmpty { completionHandler( nil, .allError( PhotoError.error( type: .imageEmpty, message: "assetResources为nil,获取失败" ), PhotoError.error( type: .videoEmpty, message: "assetResources为nil,获取失败" ) ) ) return } if !PhotoTools.removeFile(fileURL: fileURL) { completionHandler( nil, .allError( PhotoError.error( type: .imageEmpty, message: "指定的地址已存在" ), PhotoError.error( type: .videoEmpty, message: "指定的地址已存在" ) ) ) return } let videoURL = fileURL let options = PHAssetResourceRequestOptions.init() options.isNetworkAccessAllowed = true var hasAdjustmentData = false for assetResource in assetResources where assetResource.type == .adjustmentData { hasAdjustmentData = true break } for assetResource in assetResources { var videoType: PHAssetResourceType = .pairedVideo if hasAdjustmentData { videoType = .fullSizePairedVideo } if assetResource.type == videoType { PHAssetResourceManager.default().writeData( for: assetResource, toFile: videoURL, options: options ) { (error) in DispatchQueue.main.async { if error == nil { completionHandler(videoURL, nil) }else { completionHandler(nil, .videoError(error)) } } } } } } } else { // Fallback on earlier versions completionHandler( nil, .allError( PhotoError.error( type: .imageEmpty, message: "系统版本低于9.1" ), PhotoError.error( type: .videoEmpty, message: "系统版本低于9.1" ) ) ) } } // MARK: 获取LivePhoto里的图片地址和视频地址 static func requestLivePhoto( contentURL asset: PHAsset, imageURLHandler: @escaping (URL?) -> Void, videoHandler: @escaping (URL?) -> Void, completionHandler: @escaping (LivePhotoError?) -> Void ) { if #available(iOS 9.1, *) { requestLivePhoto(for: asset, targetSize: PHImageManagerMaximumSize) { (ID) in } progressHandler: { (progress, error, stop, info) in } resultHandler: { (livePhoto, info, downloadSuccess) in if livePhoto == nil { completionHandler( .allError( PhotoError.error( type: .imageEmpty, message: "livePhoto为nil,获取失败" ), PhotoError.error( type: .videoEmpty, message: "livePhoto为nil,获取失败" ) ) ) return } let assetResources: [PHAssetResource] = PHAssetResource.assetResources(for: livePhoto!) if assetResources.isEmpty { completionHandler( .allError( PhotoError.error( type: .imageEmpty, message: "assetResources为nil,获取失败" ), PhotoError.error( type: .videoEmpty, message: "assetResources为nil,获取失败" ) ) ) return } let options = PHAssetResourceRequestOptions.init() options.isNetworkAccessAllowed = true var imageCompletion = false var imageError: Error? var videoCompletion = false var videoError: Error? let imageURL = PhotoTools.getImageTmpURL() let videoURL = PhotoTools.getVideoTmpURL() let callback = {(imageError: Error?, videoError: Error?) in if imageError != nil && videoError != nil { completionHandler(.allError(imageError, videoError)) }else if imageError != nil { completionHandler(.imageError(imageError)) }else if videoError != nil { completionHandler(.videoError(videoError)) }else { completionHandler(nil) } } var hasAdjustmentData = false for assetResource in assetResources where assetResource.type == .adjustmentData { hasAdjustmentData = true break } for assetResource in assetResources { var photoType: PHAssetResourceType = .photo var videoType: PHAssetResourceType = .pairedVideo if hasAdjustmentData { photoType = .fullSizePhoto videoType = .fullSizePairedVideo } if assetResource.type == photoType { PHAssetResourceManager.default().writeData( for: assetResource, toFile: imageURL, options: options ) { (error) in DispatchQueue.main.async { if error == nil { imageURLHandler(imageURL) } imageCompletion = true imageError = error if videoCompletion { callback(imageError, videoError) } } } }else if assetResource.type == videoType { PHAssetResourceManager.default().writeData( for: assetResource, toFile: videoURL, options: options ) { (error) in DispatchQueue.main.async { if error == nil { videoHandler(videoURL) } videoCompletion = true videoError = error if imageCompletion { callback(imageError, videoError) } } } } } } } else { // Fallback on earlier versions completionHandler( .allError( PhotoError.error( type: .imageEmpty, message: "系统版本低于9.1"), PhotoError.error( type: .videoEmpty, message: "系统版本低于9.1" ) ) ) } } }
mit
ae40d6f55b3ee22048772a84f9e5c22b
40.325459
118
0.383804
6.893608
false
false
false
false
OpenCraft/OCHuds
OCHuds/Classes/SpinnerHUD.swift
1
2708
// // SpinnerHUD.swift // OCHud // // Created by Henrique Morbin on 06/08/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit open class SpinnerHUD: BaseHUD { internal override class func customHud(withViewController viewController: UIViewController) -> HudView? { return SpinnerView(withViewController: viewController) } } // TODO: Change to OCExtensions internal var topMostViewController: UIViewController? { var topMost = UIApplication.shared.keyWindow?.rootViewController while let presented = topMost?.presentedViewController { topMost = presented } return topMost } // TODO: Change to OCExtensions internal extension UIView { func centerSuperview(withSize size: CGSize, verticalMargin: CGFloat = 0, horizontalMargin: CGFloat = 0) { if let superview = self.superview { let subview = self subview.translatesAutoresizingMaskIntoConstraints = false superview.addConstraint(NSLayoutConstraint(item: subview, attribute: .centerX, relatedBy: .equal, toItem: superview, attribute: .centerX, multiplier: 1, constant: verticalMargin)) superview.addConstraint(NSLayoutConstraint(item: subview, attribute: .centerY, relatedBy: .equal, toItem: superview, attribute: .centerY, multiplier: 1, constant: horizontalMargin)) subview.addConstraint(NSLayoutConstraint(item: subview, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size.width)) subview.addConstraint(NSLayoutConstraint(item: subview, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size.height)) } } func baseSuperview(withSize size: CGSize) { if let superview = self.superview { let subview = self subview.translatesAutoresizingMaskIntoConstraints = false superview.addConstraint(NSLayoutConstraint(item: subview, attribute: .centerX, relatedBy: .equal, toItem: superview, attribute: .centerX, multiplier: 1, constant: 0)) superview.addConstraint(NSLayoutConstraint(item: subview, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom, multiplier: 1, constant: -10)) subview.addConstraint(NSLayoutConstraint(item: subview, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size.width)) subview.addConstraint(NSLayoutConstraint(item: subview, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size.height)) } } }
mit
8f2b7db0293de7acafb6f0fb1c20c3d8
51.057692
193
0.712597
4.912886
false
false
false
false
dn-m/Collections
Collections/Zip3Sequence.swift
1
12342
// // Zip3Sequence.swift // Collections // // Created by James Bean on 2/13/17. // // // Apache License // Version 2.0, January 2004 // http://www.apache.org/licenses/ // // TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION // // 1. Definitions. // // "License" shall mean the terms and conditions for use, reproduction, // and distribution as defined by Sections 1 through 9 of this document. // // "Licensor" shall mean the copyright owner or entity authorized by // the copyright owner that is granting the License. // // "Legal Entity" shall mean the union of the acting entity and all // other entities that control, are controlled by, or are under common // control with that entity. For the purposes of this definition, // "control" means (i) the power, direct or indirect, to cause the // direction or management of such entity, whether by contract or // otherwise, or (ii) ownership of fifty percent (50%) or more of the // outstanding shares, or (iii) beneficial ownership of such entity. // // "You" (or "Your") shall mean an individual or Legal Entity // exercising permissions granted by this License. // // "Source" form shall mean the preferred form for making modifications, // including but not limited to software source code, documentation // source, and configuration files. // // "Object" form shall mean any form resulting from mechanical // transformation or translation of a Source form, including but // not limited to compiled object code, generated documentation, // and conversions to other media types. // // "Work" shall mean the work of authorship, whether in Source or // Object form, made available under the License, as indicated by a // copyright notice that is included in or attached to the work // (an example is provided in the Appendix below). // // "Derivative Works" shall mean any work, whether in Source or Object // form, that is based on (or derived from) the Work and for which the // editorial revisions, annotations, elaborations, or other modifications // represent, as a whole, an original work of authorship. For the purposes // of this License, Derivative Works shall not include works that remain // separable from, or merely link (or bind by name) to the interfaces of, // the Work and Derivative Works thereof. // // "Contribution" shall mean any work of authorship, including // the original version of the Work and any modifications or additions // to that Work or Derivative Works thereof, that is intentionally // submitted to Licensor for inclusion in the Work by the copyright owner // or by an individual or Legal Entity authorized to submit on behalf of // the copyright owner. For the purposes of this definition, "submitted" // means any form of electronic, verbal, or written communication sent // to the Licensor or its representatives, including but not limited to // communication on electronic mailing lists, source code control systems, // and issue tracking systems that are managed by, or on behalf of, the // Licensor for the purpose of discussing and improving the Work, but // excluding communication that is conspicuously marked or otherwise // designated in writing by the copyright owner as "Not a Contribution." // // "Contributor" shall mean Licensor and any individual or Legal Entity // on behalf of whom a Contribution has been received by Licensor and // subsequently incorporated within the Work. // // 2. Grant of Copyright License. Subject to the terms and conditions of // this License, each Contributor hereby grants to You a perpetual, // worldwide, non-exclusive, no-charge, royalty-free, irrevocable // copyright license to reproduce, prepare Derivative Works of, // publicly display, publicly perform, sublicense, and distribute the // Work and such Derivative Works in Source or Object form. // // 3. Grant of Patent License. Subject to the terms and conditions of // this License, each Contributor hereby grants to You a perpetual, // worldwide, non-exclusive, no-charge, royalty-free, irrevocable // (except as stated in this section) patent license to make, have made, // use, offer to sell, sell, import, and otherwise transfer the Work, // where such license applies only to those patent claims licensable // by such Contributor that are necessarily infringed by their // Contribution(s) alone or by combination of their Contribution(s) // with the Work to which such Contribution(s) was submitted. If You // institute patent litigation against any entity (including a // cross-claim or counterclaim in a lawsuit) alleging that the Work // or a Contribution incorporated within the Work constitutes direct // or contributory patent infringement, then any patent licenses // granted to You under this License for that Work shall terminate // as of the date such litigation is filed. // // 4. Redistribution. You may reproduce and distribute copies of the // Work or Derivative Works thereof in any medium, with or without // modifications, and in Source or Object form, provided that You // meet the following conditions: // // (a) You must give any other recipients of the Work or // Derivative Works a copy of this License; and // // (b) You must cause any modified files to carry prominent notices // stating that You changed the files; and // // (c) You must retain, in the Source form of any Derivative Works // that You distribute, all copyright, patent, trademark, and // attribution notices from the Source form of the Work, // excluding those notices that do not pertain to any part of // the Derivative Works; and // // (d) If the Work includes a "NOTICE" text file as part of its // distribution, then any Derivative Works that You distribute must // include a readable copy of the attribution notices contained // within such NOTICE file, excluding those notices that do not // pertain to any part of the Derivative Works, in at least one // of the following places: within a NOTICE text file distributed // as part of the Derivative Works; within the Source form or // documentation, if provided along with the Derivative Works; or, // within a display generated by the Derivative Works, if and // wherever such third-party notices normally appear. The contents // of the NOTICE file are for informational purposes only and // do not modify the License. You may add Your own attribution // notices within Derivative Works that You distribute, alongside // or as an addendum to the NOTICE text from the Work, provided // that such additional attribution notices cannot be construed // as modifying the License. // // You may add Your own copyright statement to Your modifications and // may provide additional or different license terms and conditions // for use, reproduction, or distribution of Your modifications, or // for any such Derivative Works as a whole, provided Your use, // reproduction, and distribution of the Work otherwise complies with // the conditions stated in this License. // // 5. Submission of Contributions. Unless You explicitly state otherwise, // any Contribution intentionally submitted for inclusion in the Work // by You to the Licensor shall be under the terms and conditions of // this License, without any additional terms or conditions. // Notwithstanding the above, nothing herein shall supersede or modify // the terms of any separate license agreement you may have executed // with Licensor regarding such Contributions. // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor, // except as required for reasonable and customary use in describing the // origin of the Work and reproducing the content of the NOTICE file. // // 7. Disclaimer of Warranty. Unless required by applicable law or // agreed to in writing, Licensor provides the Work (and each // Contributor provides its Contributions) on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied, including, without limitation, any warranties or conditions // of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A // PARTICULAR PURPOSE. You are solely responsible for determining the // appropriateness of using or redistributing the Work and assume any // risks associated with Your exercise of permissions under this License. // // 8. Limitation of Liability. In no event and under no legal theory, // whether in tort (including negligence), contract, or otherwise, // unless required by applicable law (such as deliberate and grossly // negligent acts) or agreed to in writing, shall any Contributor be // liable to You for damages, including any direct, indirect, special, // incidental, or consequential damages of any character arising as a // result of this License or out of the use or inability to use the // Work (including but not limited to damages for loss of goodwill, // work stoppage, computer failure or malfunction, or any and all // other commercial damages or losses), even if such Contributor // has been advised of the possibility of such damages. // // 9. Accepting Warranty or Additional Liability. While redistributing // the Work or Derivative Works thereof, You may choose to offer, // and charge a fee for, acceptance of support, warranty, indemnity, // or other liability obligations and/or rights consistent with this // License. However, in accepting such obligations, You may act only // on Your own behalf and on Your sole responsibility, not on behalf // of any other Contributor, and only if You agree to indemnify, // defend, and hold each Contributor harmless for any liability // incurred by, or claims asserted against, such Contributor by reason // of your accepting any such warranty or additional liability. // // END OF TERMS AND CONDITIONS /// Lazy `Sequence` zipping three `Sequence` values together. /// /// - note: This should be deprecated when `Variadic Generics` are implemented in Swift. As /// outlined in the [Generics Manifesto] /// (http://thread.gmane.org/gmane.comp.lang.swift.evolution/8484) /// /// - author: https://github.com/amomchilov/ZipNsequence/blob/master/Zip3Sequence.swift /// /// Modified by James Bean. /// public func zip <A: Sequence, B: Sequence, C: Sequence>(_ a: A, _ b: B, _ c: C) -> Zip3Sequence<A,B,C> { return Zip3Sequence(a,b,c) } public struct Zip3Sequence <A: Sequence, B: Sequence, C: Sequence>: Sequence { /// A type whose instances can produce the elements of this sequence, in order. public typealias Iterator = Zip3Iterator<A.Iterator, B.Iterator, C.Iterator> private let a: A private let b: B private let c: C /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public init(_ a: A, _ b: B, _ c: C) { (self.a, self.b, self.c) = (a, b, c) } /// Returns an iterator over the elements of this sequence. public func makeIterator() -> Iterator { return Iterator( a.makeIterator(), b.makeIterator(), c.makeIterator()) } } public struct Zip3Iterator <A: IteratorProtocol, B: IteratorProtocol, C: IteratorProtocol> : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (A.Element, B.Element, C.Element) private var a: A private var b: B private var c: C /// Creates an instance around a pair of underlying iterators. internal init(_ a: A, _ b: B, _ c: C) { (self.a, self.b, self.c) = (a, b, c) } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { guard let a = a.next(), let b = b.next(), let c = c.next() else { return nil } return (a, b, c) } }
mit
1500850e4db957b9873a9104c8250721
46.837209
91
0.711554
4.215164
false
false
false
false
PseudoSudoLP/Bane
Carthage/Checkouts/Moya/Demo/Demo/ViewController.swift
1
3913
// // ViewController.swift // Demo // // Created by Ash Furrow on 2014-11-16. // Copyright (c) 2014 Ash Furrow. All rights reserved. // import UIKit class ViewController: UITableViewController { var repos = NSArray() override func viewDidLoad() { super.viewDidLoad() downloadRepositories("ashfurrow") } // MARK: - API Stuff func downloadRepositories(username: String) { GitHubProvider.request(.UserRepositories(username), completion: { (data, status, resonse, error) -> () in var success = error == nil if let data = data { let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) if let json = json as? NSArray { // Presumably, you'd parse the JSON into a model object. This is just a demo, so we'll keep it as-is. self.repos = json } else { success = false } self.tableView.reloadData() } else { success = false } if !success { let alertController = UIAlertController(title: "GitHub Fetch", message: error?.description, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in alertController.dismissViewControllerAnimated(true, completion: nil) }) alertController.addAction(ok) self.presentViewController(alertController, animated: true, completion: nil) } }) } func downloadZen() { GitHubProvider.request(.Zen, completion: { (data, status, response, error) -> () in var message = "Couldn't access API" if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String ?? message } let alertController = UIAlertController(title: "Zen", message: message, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in alertController.dismissViewControllerAnimated(true, completion: nil) }) alertController.addAction(ok) self.presentViewController(alertController, animated: true, completion: nil) }) } // MARK: - User Interaction @IBAction func searchWasPressed(sender: UIBarButtonItem) { var usernameTextField: UITextField? let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in if let usernameTextField = usernameTextField { self.downloadRepositories(usernameTextField.text) } }) let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in } promptController.addAction(ok) promptController.addTextFieldWithConfigurationHandler { (textField) -> Void in usernameTextField = textField } presentViewController(promptController, animated: true, completion: nil) } @IBAction func zenWasPressed(sender: UIBarButtonItem) { downloadZen() } // MARK: - Table View override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repos.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let object = repos[indexPath.row] as! NSDictionary (cell.textLabel as UILabel!).text = object["name"] as? String return cell } }
mit
9decc2eec9370c34d506f0c8e148d186
36.625
131
0.611807
5.155468
false
false
false
false
Draveness/RbSwift
RbSwiftTests/Sequence/Sequence+EnumerationSpec.swift
1
2287
// // Sequence+EnumerationSpec.swift // RbSwift // // Created by Draveness on 23/03/2017. // Copyright © 2017 draveness. All rights reserved. // import Quick import Nimble import RbSwift class SequenceEnumerationSpec: BaseSpec { override func spec() { describe(".each(closure:)") { it("is an alias to forEach(body:)") { var result: [Int] = [] [1, 2, 3].each { result.append($0) } expect(result).to(equal([1, 2, 3])) } } describe(".eachWithIndex(closure:)") { it("is an alias to forEach(body:) with index") { var indexes: [Int] = [] var result: [Int] = [] [10, 20, 30].eachWithIndex { indexes.append($0) result.append($1) } expect(indexes).to(equal([0, 1, 2])) expect(result).to(equal([10, 20, 30])) } } describe(".mapWithIndex(closure:)") { it("is an alias to forEach(body:) with index") { var indexes: [Int] = [] let result = [10, 20, 30].mapWithIndex { (index, value) -> Int in indexes.append(index) return 1000 } expect(indexes).to(equal([0, 1, 2])) expect(result).to(equal([1000, 1000, 1000])) } } describe(".reverseEach(closure:)") { it("is an alias to forEach(body:)") { var result: [Int] = [] [1, 2, 3].reverseEach { result.append($0) } expect(result).to(equal([3, 2, 1])) } } describe(".withIndex") { it("returns an enumerated seqeuence") { var indexes: [Int] = [] var result: [Int] = [] for (index, element) in [10, 20, 30].withIndex { indexes.append(index) result.append(element) } expect(indexes).to(equal([0, 1, 2])) expect(result).to(equal([10, 20, 30])) } } } }
mit
126d7783e9d3ceac5aa3ad7a61fa022b
30.315068
81
0.421697
4.430233
false
false
false
false
suragch/Chimee-iOS
Chimee/MainViewController.swift
1
13093
import UIKit import SQLite // protocol used for sending data back protocol MenuDelegate: class { // editing func copyText() func pasteText() func clearText() // message func insertMessage(_ text: String) } class MainViewController: UIViewController, KeyboardDelegate, UIGestureRecognizerDelegate, UIPopoverPresentationControllerDelegate, MenuDelegate { var docController: UIDocumentInteractionController! let minimumInputWindowSize = CGSize(width: 80, height: 150) let inputWindowSizeIncrement: CGFloat = 50 let spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) // MARK:- Outlets @IBOutlet weak var inputWindow: UIMongolTextView! @IBOutlet weak var topContainerView: UIView! @IBOutlet weak var keyboardContainer: KeyboardController! @IBOutlet weak var inputWindowHeightConstraint: NSLayoutConstraint! @IBOutlet weak var inputWindowWidthConstraint: NSLayoutConstraint! // MARK:- Actions @IBAction func shareButtonTapped(_ sender: UIBarButtonItem) { // start spinner spinner.frame = self.view.frame // center it spinner.startAnimating() let message = inputWindow.text let image = imageFromTextView(inputWindow) // Create a URL let imageURL = URL(fileURLWithPath: NSTemporaryDirectory() + "MiniiChimee.png") // create image on a background thread, then share it let qualityOfServiceClass = DispatchQoS.QoSClass.background let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass) backgroundQueue.async(execute: { // save image to URL try? UIImagePNGRepresentation(image)?.write(to: imageURL, options: [.atomic]) // update suggestion bar with those words DispatchQueue.main.async(execute: { () -> Void in // share the image self.clearText() self.clearKeyboard() self.docController.url = imageURL self.docController.presentOptionsMenu(from: sender, animated: true) self.spinner.stopAnimating() }) }) // save message to database history table saveMessageToHistory(message) } @IBAction func logoButtonTapped(_ sender: UIBarButtonItem) { // FIXME: This method is never called } // MARK:- Overrides override func viewDidLoad() { super.viewDidLoad() // setup spinner spinner.backgroundColor = UIColor(white: 0, alpha: 0.2) // make bg darker for greater contrast self.view.addSubview(spinner) // inputWindow: get rid of space at beginning of textview self.automaticallyAdjustsScrollViewInsets = false // Get any saved draft if let savedText = UserDefaults.standard.string(forKey: UserDefaultsKey.lastMessage) { DispatchQueue.main.async { self.insertMessage(savedText) } } NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) docController = UIDocumentInteractionController() // setup keyboard keyboardContainer.delegate = self inputWindow.underlyingTextView.inputView = UIView() // dummy view to prevent keyboard from showing inputWindow.underlyingTextView.becomeFirstResponder() // create message tables if they don't exist let dataStore = SQLiteDataStore.sharedInstance do { try dataStore.createMessageTables() } catch _ {} } override func viewWillAppear(_ animated: Bool) { inputWindow.underlyingTextView.becomeFirstResponder() } // MARK: - KeyboardDelegate protocol func keyWasTapped(_ character: String) { inputWindow.insertMongolText(character) increaseInputWindowSizeIfNeeded() } func keyBackspace() { inputWindow.deleteBackward() decreaseInputWindowSizeIfNeeded() } func charBeforeCursor() -> String? { return inputWindow.unicodeCharBeforeCursor() } func oneMongolWordBeforeCursor() -> String? { return inputWindow.oneMongolWordBeforeCursor() } func twoMongolWordsBeforeCursor() -> (String?, String?) { return inputWindow.twoMongolWordsBeforeCursor() } func replaceCurrentWordWith(_ replacementWord: String) { inputWindow.replaceWordAtCursorWith(replacementWord) } func keyNewKeyboardChosen(_ type: KeyboardType) { // Do nothing // Keyboard Controller already handles keyboard switches } // MARK: - Other fileprivate func increaseInputWindowSizeIfNeeded() { if inputWindow.frame.size == topContainerView.frame.size { return } // width if inputWindow.contentSize.width > inputWindow.frame.width && inputWindow.frame.width < topContainerView.frame.size.width { if inputWindow.contentSize.width > topContainerView.frame.size.width { inputWindowWidthConstraint.constant = topContainerView.frame.size.width } else { self.inputWindowWidthConstraint.constant = self.inputWindow.contentSize.width } } // height if inputWindow.contentSize.width > inputWindow.contentSize.height { if inputWindow.frame.height < topContainerView.frame.height { if inputWindow.frame.height + inputWindowSizeIncrement < topContainerView.frame.height { // increase height by increment unit inputWindowHeightConstraint.constant = inputWindow.frame.height + inputWindowSizeIncrement } else { inputWindowHeightConstraint.constant = topContainerView.frame.height } } } } fileprivate func decreaseInputWindowSizeIfNeeded() { if inputWindow.frame.size == minimumInputWindowSize { return } // width if inputWindow.contentSize.width < inputWindow.frame.width && inputWindow.frame.width > minimumInputWindowSize.width { //inputWindow.scrollEnabled = false if inputWindow.contentSize.width < minimumInputWindowSize.width { inputWindowWidthConstraint.constant = minimumInputWindowSize.width } else { inputWindowWidthConstraint.constant = inputWindow.contentSize.width } } // height if (2 * inputWindow.contentSize.width) <= inputWindow.contentSize.height && inputWindow.contentSize.width < topContainerView.frame.width { // got too high, make it shorter if minimumInputWindowSize.height < inputWindow.contentSize.height - inputWindowSizeIncrement { inputWindowHeightConstraint.constant = inputWindow.contentSize.height - inputWindowSizeIncrement } else { // Bump down to min height inputWindowHeightConstraint.constant = minimumInputWindowSize.height } } } func imageFromTextView(_ textView: UIMongolTextView) -> UIImage { // make a copy of the text view with the same size and text attributes let textViewCopy = UIMongolTextView(frame: textView.frame) textViewCopy.attributedText = textView.attributedText // resize if contentView is larger than the frame if textView.contentSize.width > textView.frame.width { textViewCopy.frame = CGRect(origin: CGPoint.zero, size: textView.contentSize) } // draw the text view to an image UIGraphicsBeginImageContextWithOptions(textViewCopy.bounds.size, false, UIScreen.main.scale) textViewCopy.drawHierarchy(in: textViewCopy.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "copyMenuSegue" { let popoverViewController = segue.destination as! CopyMenuViewController popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover popoverViewController.popoverPresentationController!.delegate = self popoverViewController.delegate = self } else if segue.identifier == "favoriteSegue" { let favoriteViewController = segue.destination as! FavoriteViewController favoriteViewController.currentMessage = inputWindow.text favoriteViewController.delegate = self } } func willResignActive() { // save the current text let defaults = UserDefaults.standard defaults.set(inputWindow.text, forKey: UserDefaultsKey.lastMessage) } func showUnicodeNotification() { let title = "ᠳᠤᠰ ᠪᠢᠴᠢᠯᠭᠡ ᠬᠠᠭᠤᠯᠠᠭᠳᠠᠪᠠ" let message = "ᠳᠤᠰ ᠪᠢᠴᠢᠯᠭᠡ ᠶᠢᠨ ᠶᠦᠨᠢᠺᠤᠳ᠋ ᠲᠡᠺᠧᠰᠲ ᠢ ᠭᠠᠷ ᠤᠳᠠᠰᠤᠨ ᠰᠢᠰᠲ᠋ᠧᠮ ᠦᠨ ᠨᠠᠭᠠᠬᠤ ᠰᠠᠮᠪᠠᠷ᠎ᠠ ᠳᠤ ᠬᠠᠭᠤᠯᠠᠭᠳᠠᠪᠠ᠃ ᠳᠠ ᠡᠭᠦᠨ ᠢ ᠪᠤᠰᠤᠳ APP ᠳᠤ ᠨᠠᠭᠠᠵᠤ ᠬᠡᠷᠡᠭᠯᠡᠵᠤ ᠪᠤᠯᠤᠨ᠎ᠠ᠃ ᠭᠡᠪᠡᠴᠦ ᠮᠤᠩᠭᠤᠯ ᠬᠡᠯᠡᠨ ᠦ ᠶᠦᠨᠢᠺᠤᠳ᠋ ᠤᠨ ᠪᠠᠷᠢᠮᠵᠢᠶ᠎ᠠ ᠨᠢᠭᠡᠳᠦᠭᠡᠳᠦᠢ ᠳᠤᠯᠠ ᠵᠠᠷᠢᠮ ᠰᠤᠹᠲ ᠪᠤᠷᠤᠭᠤ ᠦᠰᠦᠭ ᠢᠶᠡᠷ ᠢᠯᠡᠷᠡᠬᠦ ᠮᠠᠭᠠᠳ᠃" showAlert(withTitle: title, message: message, numberOfButtons: 1, topButtonText: "ᠮᠡᠳᠡᠯ᠎ᠡ", topButtonAction: nil, bottomButtonText: nil, bottomButtonAction: nil, alertWidth: 300) } func clearKeyboard() { self.keyboardContainer.clearKeyboard() } // MARK: - Database func saveMessageToHistory(_ message: String) { // do in background guard message.characters.count > 0 else { return } // do on background thread let qualityOfServiceClass = DispatchQoS.QoSClass.background let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass) backgroundQueue.async(execute: { do { _ = try HistoryDataHelper.insertMessage(message) //self.messages = try FavoriteDataHelper.findAll() } catch _ { print("message update failed") } }) } // MARK: - UIPopoverPresentationControllerDelegate method func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { // Force popover style return UIModalPresentationStyle.none } // MARK: - Menu Delegate func copyText() { // check for empty input window guard inputWindow.text.characters.count > 0 else { //TODO:? show a notification that window is empty return } // copy (selected) text if let selectedText = inputWindow.selectedText() { // add unicode text to the pasteboard UIPasteboard.general.string = selectedText } else { // copy everything // add unicode text to the pasteboard UIPasteboard.general.string = inputWindow.text } // tell user about problems with Unicode text // TODO: don't tell them every time forever showUnicodeNotification() } func pasteText() { if let myString = UIPasteboard.general.string { inputWindow.insertMongolText(myString) } } func clearText() { inputWindow.text = "" inputWindowWidthConstraint.constant = minimumInputWindowSize.width inputWindowHeightConstraint.constant = minimumInputWindowSize.height } func insertMessage(_ text: String) { inputWindow.insertMongolText(text) increaseInputWindowSizeIfNeeded() } }
mit
b51e5207cb7a3a7eff794f298f92c761
32.472149
265
0.615421
4.455862
false
false
false
false
robconrad/fledger-common
FledgerCommon/services/models/parse/ParseServiceImpl.swift
1
4889
// // ParseService.swift // fledger-ios // // Created by Robert Conrad on 5/10/15. // Copyright (c) 2015 Robert Conrad. All rights reserved. // import Foundation import SQLite #if os(iOS) import Parse #elseif os(OSX) import ParseOSX #endif class ParseServiceImpl: ParseService { func select(filters: ParseFilters?) -> [ParseModel] { var query = DatabaseSvc().parse if let f = filters { query = f.toQuery(query, limit: true) } var elements: [ParseModel] = [] for row in DatabaseSvc().db.prepare(query) { elements.append(ParseModel(row: row)) } return elements } func withModelId(id: Int64, _ modelType: ModelType) -> ParseModel? { return DatabaseSvc().db.pluck(DatabaseSvc().parse.filter(Fields.model == modelType.rawValue && Fields.modelId == id)).map { ParseModel(row: $0) } } func withParseId(id: String, _ modelType: ModelType) -> ParseModel? { return DatabaseSvc().db.pluck(DatabaseSvc().parse.filter(Fields.model == modelType.rawValue && Fields.parseId == id)).map { ParseModel(row: $0) } } func markSynced(id: Int64, _ modelType: ModelType, _ pf: PFObject) -> Bool { do { if let parseId = pf.objectId { let query = DatabaseSvc().parse.filter(Fields.model == modelType.rawValue && Fields.modelId == id) let rows = try DatabaseSvc().db.run(query.update([ Fields.synced <- true, Fields.parseId <- parseId, Fields.updatedAt <- NSDateTime(pf.updatedAt!) ])) if rows != 1 { throw NSError(domain: "", code: 1, userInfo: nil) } } } catch { return false } return true } func save(convertible: PFObjectConvertible) -> PFObject? { if let pf = convertible.toPFObject() { pf.ACL = PFACL(user: PFUser.currentUser()!) do { try pf.save() } catch { print("Save of PFObject for \(convertible) failed") return nil } print("Save of PFObject for \(convertible) returned \(pf.objectId)") return pf } return nil } // TODO: revisit this sync logic, it needs some love func remote(modelType: ModelType, updatedOnly: Bool) -> [PFObject]? { let lastSyncedRow = DatabaseSvc().db.pluck(DatabaseSvc().parse.filter(Fields.model == modelType.rawValue).order(Fields.updatedAt.desc)) var bufferRows = [String]() let query = PFQuery(className: modelType.rawValue) if let lastRow = lastSyncedRow { let lastDateFactory = NSDate.dateByAddingTimeInterval(lastRow.get(Fields.updatedAt)?.date ?? NSDate(timeIntervalSince1970: 0)) let updatedAtLeast = lastDateFactory(-60) for row in DatabaseSvc().db.prepare(DatabaseSvc().parse.filter(Fields.model == modelType.rawValue && Fields.updatedAt >= NSDateTime(updatedAtLeast))) { if let id = row.get(Fields.parseId) { bufferRows.append(id) } } // query for records within one minute of the last updated record that are not themselves the last updated record query.whereKey("updatedAt", greaterThanOrEqualTo: updatedAtLeast) query.whereKey("objectId", notContainedIn: [lastRow.get(Fields.parseId) ?? ""]) } do { let result = try query.findObjects() print("Remote query for PFObjects of \(modelType) lastSyncedRow (\(lastSyncedRow.flatMap { $0.get(Fields.updatedAt)?.date }), \(lastSyncedRow?.get(Fields.parseId))) returned \(result.count ?? 0) rows") //for parseId in bufferRows { //result!.find { $0.parseId == parseId } //} return result } catch { // oh god why } return [] } func isLoggedIn() -> Bool { return PFUser.currentUser() != nil } func login(email: String, _ password: String, _ onComplete: Bool -> Void) { PFUser.logInWithUsernameInBackground(email, password: password) { (user: PFUser?, error: NSError?) -> Void in onComplete(user != nil) } } func logout() { PFUser.logOut() } func signup(email: String, _ password: String, _ onComplete: Bool -> Void) { let user = PFUser() user.username = email user.password = password user.email = email user.signUpInBackgroundWithBlock({ (succeeded: Bool, error: NSError?) -> Void in onComplete(succeeded) }) } }
mit
962c701f68a925508f0569413b5cb88e
34.427536
213
0.561669
4.582006
false
false
false
false
JARMourato/JMProjectEuler
JMProjectEuler/Problems/1-10/7.swift
1
1373
// // 7.swift // JMProjectEuler // // Created by iOS on 26/12/15. // Copyright © 2015 JARM. All rights reserved. // import Darwin /* PROBLEM - 7 : 10001st Prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? */ extension EulerProblem { private func isPrime(n : Int) -> Bool { guard n != 1 else { return false } guard n > 4 else { return true } guard n % 2 != 0 else { return false } guard n > 9 else { return true } guard n % 3 != 0 else { return false } var j = 5 while j <= Int(floor(sqrt(Double(n)))) { if n % j == 0 { return false } if n % (j+2) == 0 { return false } j+=6 } return true } public mutating func solutionAlgorithmForProblem7(nPrime : Int) { if nPrime < 2 { result = 1; return } var primeNumberCandidate = 1 var count = 1 while count <= nPrime { if isPrime(primeNumberCandidate) { count+=1 } if count <= nPrime { primeNumberCandidate+=2 } } result = primeNumberCandidate } public mutating func the10001stPrimeNumber(){ solutionAlgorithmForProblem7(10001) } }
mit
c3cd5cccf4dfb2c2d2718f8c3089037a
23.517857
100
0.530612
3.931232
false
false
false
false
XeresRazor/SwiftNES
SwiftNES/util/Image/Geometry.swift
1
4569
// // Geometry.swift // SwiftNES // // Created by Articulate on 6/2/15. // Copyright (c) 2015 DigitalWorlds. All rights reserved. // import Swift struct Point { var X, Y: Int init() { self.X = 0 self.Y = 0 } init(_ x: Int, _ y: Int) { self.X = x self.Y = y } func Add(q: Point) -> Point { return Point(self.X + q.X, self.Y + q.Y) } func Sub(q: Point) -> Point { return Point(self.X - q.X, self.Y - q.Y) } func Mul(k: Int) -> Point { return Point(self.X * k, self.Y * k) } func Div(k: Int) -> Point { return Point(self.X / k, self.Y / k) } func In(r: Rectangle) -> Bool { return r.Min.X <= self.X && self.X < r.Max.X && r.Min.Y <= self.Y && self.Y < r.Max.Y } func Mod(r: Rectangle) -> Point { let w = r.Dx(), h = r.Dy() var p = self.Sub(r.Min) p.X = p.X % w if p.X < 0 { p.X += w } p.Y = p.Y % h if p.Y < 0 { p.Y += h } return p.Add(r.Min) } func Eq(q: Point) -> Bool { return self.X == q.X && self.Y == q.Y } } let ZP = Point(0, 0) struct Rectangle { var Min, Max: Point init(_ min: Point, _ max: Point) { self.Min = min self.Max = max } init(var _ x0: Int, var _ y0: Int, var _ x1: Int, var _ y1: Int) { if x0 > x1 { (x0, x1) = (x1, x0) } if y0 > y1 { (y0, y1) = (y1, y0) } self.init(Point(x0, y0), Point(x1, y1)) } func Dx() -> Int { return self.Max.X - self.Min.X } func Dy() -> Int { return self.Max.Y - self.Min.Y } func Size() -> Point { return Point(self.Max.X - self.Min.X, self.Max.Y - self.Min.Y) } func Add(p: Point) -> Rectangle { return Rectangle(self.Min.X + p.X, self.Min.Y + p.Y, self.Max.X + p.X, self.Max.Y + p.Y) } func Sub(p: Point) -> Rectangle { return Rectangle(self.Min.X - p.X, self.Min.Y - p.Y, self.Max.X - p.X, self.Max.Y - p.Y) } func Inset(n: Int) -> Rectangle { var r = self if r.Dx() < 2 * n { r.Min.X = (r.Min.X + r.Max.X) / 2 r.Max.X = r.Min.X } else { r.Min.X += n r.Max.X -= n } if r.Dy() < 2 * n { r.Min.Y = (r.Min.Y + r.Max.Y) / 2 r.Max.Y = r.Min.Y } else { r.Min.Y += n r.Max.Y -= n } return r } func Intersect(s: Rectangle) -> Rectangle { var r = self if r.Min.X < s.Min.X { r.Min.X = s.Min.X } if r.Min.Y < s.Min.Y { r.Min.Y = s.Min.Y } if r.Max.X > s.Max.X { r.Max.X = s.Max.X } if r.Max.Y > s.Max.Y { r.Max.Y = s.Max.Y } if r.Min.X > r.Max.X || r.Min.Y > r.Max.Y { return ZR } return r } func Union(s: Rectangle) -> Rectangle { var r = self if r.Min.X > s.Min.X { r.Min.X = s.Min.X } if r.Min.Y > s.Min.Y { r.Min.Y = s.Min.Y } if r.Max.X < s.Max.X { r.Max.X = s.Max.X } if r.Max.Y < s.Max.Y { r.Max.Y = s.Max.Y } return r } func Empty() -> Bool { return self.Min.X >= self.Max.X || self.Min.Y >= self.Max.Y } func Eq(s: Rectangle) -> Bool { return self.Min.X == s.Min.X && self.Min.Y == s.Min.Y && self.Max.X == s.Max.X && self.Max.Y == s.Max.Y } func Overlaps(s: Rectangle) -> Bool { let r = self return r.Min.X < s.Max.X && s.Min.X < r.Max.X && r.Min.Y < s.Max.Y && s.Min.Y < r.Max.Y } func In(s: Rectangle) -> Bool { let r = self if r.Empty() { return true } // Note that r.Max is an exclusive bound for r, so that r.In(s) // does not require that r.Max.In(s). return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X && s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y } func Canon() -> Rectangle { var r = self if r.Max.X < r.Min.X { (r.Min.X, r.Max.X) = (r.Max.X, r.Min.X) } if r.Max.Y < r.Min.Y { (r.Min.Y, r.Max.Y) = (r.Max.Y, r.Min.Y) } return r } } let ZR = Rectangle(Point(0, 0), Point(0, 0))
mit
c1f7a5174c141794b6116f66f6b2554c
22.430769
111
0.412125
2.799632
false
false
false
false
ivygulch/IVGRouter
IVGRouter/source/presenters/SlidingWrappingRouteSegmentAnimator.swift
1
2568
// // SlidingWrappingRouteSegmentAnimator.swift // IVGRouter // // Created by Douglas Sjoquist on 4/8/16. // Copyright © 2016 Ivy Gulch LLC. All rights reserved. // import UIKit public struct SlidingWrappingRouteSegmentAnimatorSettings { public static let DefaultSlideFactor: CGFloat = 0.8 public static let DefaultAnimationDuration: TimeInterval = 0.3 } open class SlidingWrappingRouteSegmentAnimator: WrappingRouteSegmentAnimator { open let animationDuration: TimeInterval open let slideFactor: CGFloat public init(animationDuration: TimeInterval = SlidingWrappingRouteSegmentAnimatorSettings.DefaultAnimationDuration, slideFactor: CGFloat = SlidingWrappingRouteSegmentAnimatorSettings.DefaultSlideFactor) { self.animationDuration = animationDuration self.slideFactor = slideFactor } open lazy var prepareForViewWrappingAnimation: ((UIViewController,UIViewController) -> ViewAnimationInfoType) = { [weak self] (child,wrapper) -> ViewAnimationInfoType in var frame = child.view.frame let slideFactor = self?.slideFactor ?? SlidingWrappingRouteSegmentAnimatorSettings.DefaultSlideFactor frame.origin.x = frame.size.width * slideFactor return ["frame": NSValue(cgRect: frame)] } open lazy var animateViewWrapping: ((UIViewController,UIViewController,ViewAnimationInfoType) -> ViewAnimationInfoType) = { (child,wrapper,viewAnimationInfo) in if let frame = viewAnimationInfo["frame"] as? NSValue { child.view.frame = frame.cgRectValue } return viewAnimationInfo } open lazy var completeViewWrappingAnimation: ((UIViewController,UIViewController,ViewAnimationInfoType) -> Void) = { _,_,_ in // nothing to do by default } open lazy var prepareForViewUnwrappingAnimation: ((UIViewController,UIViewController) -> ViewAnimationInfoType) = { [weak self] (child,wrapper) -> ViewAnimationInfoType in var frame = child.view.frame frame.origin.x = 0 return ["frame": NSValue(cgRect: frame)] } open lazy var animateViewUnwrapping: ((UIViewController,UIViewController,ViewAnimationInfoType) -> ViewAnimationInfoType) = { (child,wrapper,viewAnimationInfo) in if let frame = viewAnimationInfo["frame"] as? NSValue { child.view.frame = frame.cgRectValue } return viewAnimationInfo } // nothing to do by default open lazy var completeViewUnwrappingAnimation: ((UIViewController,UIViewController,ViewAnimationInfoType) -> Void) = { _,_,_ in } }
mit
f3fa3d5819c870d7ca1374f130c69735
41.783333
208
0.733541
4.974806
false
false
false
false
inket/stts
Scripts/generate_google_services.swift
1
6401
#!/usr/bin/swift import Foundation enum GooglePlatform: CaseIterable { case cloudPlatform case firebase var url: URL { switch self { case .cloudPlatform: // swiftlint:disable:next force_unwrapping return URL(string: "https://status.cloud.google.com")! case .firebase: // swiftlint:disable:next force_unwrapping return URL(string: "https://status.firebase.google.com")! } } func outputPath(root: String) -> String { switch self { case .cloudPlatform: return "\(root)/stts/Services/Generated/GoogleCloudPlatformServices.swift" case .firebase: return "\(root)/stts/Services/Generated/FirebaseServices.swift" } } } protocol Service { var serviceName: String { get } var className: String { get } var output: String { get } } extension Service { var className: String { var sanitizedName = serviceName sanitizedName = sanitizedName.replacingOccurrences(of: " & ", with: "And") sanitizedName = sanitizedName.replacingOccurrences(of: "/", with: "") sanitizedName = sanitizedName.replacingOccurrences(of: ":", with: "") sanitizedName = sanitizedName.replacingOccurrences(of: "-", with: "") sanitizedName = sanitizedName.replacingOccurrences(of: "(", with: "") sanitizedName = sanitizedName.replacingOccurrences(of: ")", with: "") return sanitizedName.components(separatedBy: " ") .map { $0.capitalized(firstLetterOnly: true) } .joined(separator: "") } } struct GCPService: Service { let serviceName: String let dashboardName: String init(dashboardName: String) { self.dashboardName = dashboardName if !dashboardName.hasPrefix("Google") { serviceName = "Google \(dashboardName)" } else { serviceName = dashboardName } } var output: String { return """ class \(className): GoogleCloudPlatform, SubService { let name = "\(serviceName)" let dashboardName = "\(dashboardName)" } """ } } struct FirebaseService: Service { let serviceName: String init(dashboardName: String) { if !dashboardName.hasPrefix("Firebase") { serviceName = "Firebase \(dashboardName)" } else { serviceName = dashboardName } } var output: String { return """ class \(className): FirebaseService, SubService { let name = "\(serviceName)" } """ } } extension String { subscript(_ range: NSRange) -> String { // Why we still have to do this shit in 2019 I don't know let start = self.index(self.startIndex, offsetBy: range.lowerBound) let end = self.index(self.startIndex, offsetBy: range.upperBound) let subString = self[start..<end] return String(subString) } func capitalized(firstLetterOnly: Bool) -> String { return firstLetterOnly ? (prefix(1).capitalized + dropFirst()) : self } } func envVariable(forKey key: String) -> String { guard let variable = ProcessInfo.processInfo.environment[key] else { print("error: Environment variable '\(key)' not set") exit(1) } return variable } func discoverServices(for platform: GooglePlatform) -> [Service] { var result = [Service]() var dataResult: Data? let semaphore = DispatchSemaphore(value: 0) URLSession.shared.dataTask(with: platform.url) { data, _, _ in dataResult = data semaphore.signal() }.resume() _ = semaphore.wait(timeout: .now() + .seconds(10)) guard let data = dataResult, var body = String(data: data, encoding: .utf8) else { print(""" warning: Build script generate_google_services could not retrieve list of Google Cloud Platform/Firebase services """) exit(0) } body = body.replacingOccurrences(of: "\n", with: "") let regex: NSRegularExpression switch platform { case .cloudPlatform: // swiftlint:disable:next force_try regex = try! NSRegularExpression( pattern: "__product\">[\\s\\n]*(.+?)[\\s\\n]*<.*?\\/th>", options: [.caseInsensitive, .dotMatchesLineSeparators] ) case .firebase: // swiftlint:disable:next force_try regex = try! NSRegularExpression( pattern: "class=\"product-name\">[\\s\\n]*(.+?)[\\s\\n]*<.*?\\/tr>", options: [.caseInsensitive, .dotMatchesLineSeparators] ) } let range = NSRange(location: 0, length: body.count) regex.enumerateMatches(in: body, options: [], range: range) { textCheckingResult, _, _ in guard let textCheckingResult = textCheckingResult, textCheckingResult.numberOfRanges == 2 else { return } switch platform { case .cloudPlatform: break case .firebase: let matchSubstring = body[textCheckingResult.range(at: 0)] // Some entries are just links to Firebase and don't have any status data. Skip those. guard matchSubstring.contains("class=\"product-day") else { return } } let serviceName = body[textCheckingResult.range(at: 1)] switch platform { case .cloudPlatform: result.append(GCPService(dashboardName: serviceName)) case .firebase: result.append(FirebaseService(dashboardName: serviceName)) } } return result } func main() { let srcRoot = envVariable(forKey: "SRCROOT") GooglePlatform.allCases.forEach { platform in let services = discoverServices(for: platform) let header = """ // This file is generated by generate_google_services.swift and should not be modified manually. // swiftlint:disable superfluous_disable_command type_name import Foundation """ let content = services.map { $0.output }.joined(separator: "\n\n") let footer = "" let output = [header, content, footer].joined(separator: "\n") // swiftlint:disable:next force_try try! output.write(toFile: platform.outputPath(root: srcRoot), atomically: true, encoding: .utf8) } print("Finished generating Google services.") } main()
mit
638a02f7bcbc110218c813d5d1d5b438
29.193396
113
0.611155
4.572143
false
false
false
false
jpvasquez/Eureka
Source/Rows/SegmentedRow.swift
5
8915
// SegmentedRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit // MARK: SegmentedCell open class SegmentedCell<T: Equatable> : Cell<T>, CellType { @IBOutlet public weak var segmentedControl: UISegmentedControl! @IBOutlet public weak var titleLabel: UILabel? private var dynamicConstraints = [NSLayoutConstraint]() fileprivate var observingTitleText = false private var awakeFromNibCalled = false required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let segmentedControl = UISegmentedControl() segmentedControl.translatesAutoresizingMaskIntoConstraints = false segmentedControl.setContentHuggingPriority(UILayoutPriority(rawValue: 250), for: .horizontal) self.segmentedControl = segmentedControl self.titleLabel = self.textLabel self.titleLabel?.translatesAutoresizingMaskIntoConstraints = false self.titleLabel?.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) self.titleLabel?.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil) { [weak self] _ in guard let me = self else { return } guard me.observingTitleText else { return } me.titleLabel?.removeObserver(me, forKeyPath: "text") me.observingTitleText = false } NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [weak self] _ in guard let me = self else { return } guard !me.observingTitleText else { return } me.titleLabel?.addObserver(me, forKeyPath: "text", options: [.new, .old], context: nil) me.observingTitleText = true } NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { [weak self] _ in self?.titleLabel = self?.textLabel self?.setNeedsUpdateConstraints() } contentView.addSubview(titleLabel!) contentView.addSubview(segmentedControl) titleLabel?.addObserver(self, forKeyPath: "text", options: [.old, .new], context: nil) observingTitleText = true imageView?.addObserver(self, forKeyPath: "image", options: [.old, .new], context: nil) contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func awakeFromNib() { super.awakeFromNib() awakeFromNibCalled = true } deinit { segmentedControl.removeTarget(self, action: nil, for: .allEvents) if !awakeFromNibCalled { if observingTitleText { titleLabel?.removeObserver(self, forKeyPath: "text") } imageView?.removeObserver(self, forKeyPath: "image") NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil) } } open override func setup() { super.setup() selectionStyle = .none segmentedControl.addTarget(self, action: #selector(SegmentedCell.valueChanged), for: .valueChanged) } open override func update() { super.update() detailTextLabel?.text = nil updateSegmentedControl() segmentedControl.selectedSegmentIndex = selectedIndex() ?? UISegmentedControl.noSegment segmentedControl.isEnabled = !row.isDisabled } @objc func valueChanged() { row.value = (row as! SegmentedRow<T>).options?[segmentedControl.selectedSegmentIndex] } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let obj = object as AnyObject? if let changeType = change, let _ = keyPath, ((obj === titleLabel && keyPath == "text") || (obj === imageView && keyPath == "image")) && (changeType[NSKeyValueChangeKey.kindKey] as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue, !awakeFromNibCalled { setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } func updateSegmentedControl() { segmentedControl.removeAllSegments() (row as! SegmentedRow<T>).options?.reversed().forEach { if let image = $0 as? UIImage { segmentedControl.insertSegment(with: image, at: 0, animated: false) } else { segmentedControl.insertSegment(withTitle: row.displayValueFor?($0) ?? "", at: 0, animated: false) } } } open override func updateConstraints() { guard !awakeFromNibCalled else { super.updateConstraints() return } contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views: [String: AnyObject] = ["segmentedControl": segmentedControl] var hasImageView = false var hasTitleLabel = false if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView hasImageView = true } if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["titleLabel"] = titleLabel hasTitleLabel = true dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)) } dynamicConstraints.append(NSLayoutConstraint(item: segmentedControl!, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: 0.3, constant: 0.0)) if hasImageView && hasTitleLabel { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[titleLabel]-[segmentedControl]-|", options: [], metrics: nil, views: views) } else if hasImageView && !hasTitleLabel { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-[segmentedControl]-|", options: [], metrics: nil, views: views) } else if !hasImageView && hasTitleLabel { dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views) } else { dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views) } contentView.addConstraints(dynamicConstraints) super.updateConstraints() } func selectedIndex() -> Int? { guard let value = row.value else { return nil } return (row as! SegmentedRow<T>).options?.firstIndex(of: value) } } // MARK: SegmentedRow /// An options row where the user can select an option from an UISegmentedControl public final class SegmentedRow<T: Equatable>: OptionsRow<SegmentedCell<T>>, RowType { required public init(tag: String?) { super.init(tag: tag) } }
mit
02fb07fdcc838fb6a198aa44778f9cd6
44.953608
201
0.686708
5.259587
false
false
false
false
xrage/elasticsearch-swift
elasticsearch/transport.swift
1
5418
// // transport.swift // elasticsearch-swift // // Created by Dharmendra Verma on 07/08/16. // // import Foundation enum RequestMethod: String{ case GET = "GET" case POST = "POST" case PUT = "PUT" case HEAD = "HEAD" case PATCH = "PATCH" case DELETE = "DELETE" } struct Transport { var connectionPoolClass:ConnectionPool.Type! = ConnectionPool.self var connectionClass:HttpConnection.Type! = HttpConnection.self var selectorClass:SelectorClass = SelectorClass.roundRobinSelector var connectionPool:ConnectionPool? var hosts: [String] = [] var deadTimeout: Int = 5 var apiClient = ApiClient() var toggleGet: Bool = false mutating func setConnections() { do { self.connectionPool = try self.connectionPoolClass.init(deadTimeout: self.deadTimeout, selectorClass: self.selectorClass) } catch TransportError.improperlyConfigured{ print("improperly configured hosts") } catch{ print("Some Unknown Error occurred") } if self.connectionPool == nil{ NSException(name:NSExceptionName(rawValue: "connectionPool"), reason:"Error occurred", userInfo:nil).raise() } for host in self.hosts{ addConnection(host: host) } } internal func addConnection(host: String) -> Void { let cc = connectionClass.init(url: host) self.connectionPool?.markLive(cc) } internal func markDeadConnection(connection: HttpConnection) -> Void { self.connectionPool?.markDead(connection) } internal func getConnection() -> HttpConnection{ let con: HttpConnection? do { try con = self.connectionPool?.get_connection()} catch { con = nil NSException(name:NSExceptionName(rawValue: "ConnectionError"), reason:"No Live Connection Found", userInfo:nil).raise()} return con! } internal func performGet(path: String, params: Dictionary<String, Any>? = nil, body: Dictionary<String, Any>?, afterGet: @escaping (Int, Any?) -> ()){ let method:RequestMethod.RawValue if self.toggleGet{ method = RequestMethod.POST.rawValue }else{ method = RequestMethod.GET.rawValue } let request = prepareRequest(method: method, path: path, params: params, body: body) self.apiClient.get(request: request, responseCallback: {status, resp in afterGet(status, resp) }) } internal func performPost(path: String, params: Dictionary<String, Any>? = nil, body: Dictionary<String, Any>?, afterPost: @escaping (Int, Any?) -> ()){ let request = prepareRequest(method: RequestMethod.POST.rawValue, path: path, params: params, body: body) self.apiClient.get(request: request, responseCallback: {status, resp in afterPost(status, resp) }) } internal func performPatch(path: String, params: Dictionary<String, Any>? = nil, body: Dictionary<String, Any>?,afterPatch: @escaping (Int, Any?) -> ()){ let request = prepareRequest(method: RequestMethod.PATCH.rawValue, path: path, params: params, body: body) self.apiClient.patch(request: request, responseCallback: {status, resp in afterPatch(status, resp) }) } internal func performHead(path: String, params: Dictionary<String, Any>? = nil, body: Dictionary<String, Any>?, afterHead: @escaping (Int, Any?) -> ()){ let request = prepareRequest(method: RequestMethod.HEAD.rawValue, path: path, params: params, body: body) self.apiClient.head(request: request, responseCallback: {status, resp in afterHead(status, resp) }) } internal func performPut(path: String, params: Dictionary<String, Any>? = nil, body: Dictionary<String, Any>?, afterPut: @escaping (Int, Any?) -> ()){ let request = prepareRequest(method: RequestMethod.PUT.rawValue, path: path, params: params, body: body) self.apiClient.put(request: request, responseCallback: {status, resp in afterPut(status, resp) }) } internal func performDelete(path: String, params: Dictionary<String, Any>? = nil, body: Dictionary<String, Any>?, afterDelete: @escaping (Int, Any?) -> ()){ let request = prepareRequest(method: RequestMethod.DELETE.rawValue, path: path, params: params, body: body) self.apiClient.delete(request: request, responseCallback: {status, resp in afterDelete(status, resp) }) } private func prepareRequest(method: RequestMethod.RawValue, path: String, params: Dictionary<String, Any>?, body: Dictionary<String, Any>?)-> URLRequest{ let connection = self.getConnection() connection.path = self.preparePath(path: path, params: params) return self.apiClient.clientURLRequest(connection: connection, method:method, body: body) } private func preparePath(path: String, params: Dictionary<String, Any>?) -> String{ var qString:String = "" if (params != nil) && !(params?.isEmpty)!{ var query:[String] = [] for (key, value) in params!{ query.append("\(key)=\(value)") } qString = query.joined(separator: "&") } return "\(path)?\(qString)" } }
mit
b0c3420ef7fa53ec6d6685f17e74f8a9
37.978417
160
0.634182
4.348315
false
false
false
false
labi3285/QXConsMaker
QXConsMaker/LayoutChangeVc.swift
1
1339
// // LayoutChangeVc.swift // QXAutoLayoutDemo // // Created by Richard.q.x on 16/5/9. // Copyright © 2016年 labi3285_lab. All rights reserved. // import UIKit class LayoutChangeVc: UIViewController { var widthSlider: UISlider? var widthCons: NSLayoutConstraint? let scale: CGFloat = 1 override func viewDidLoad() { view.backgroundColor = UIColor.white let SuperV = view! widthSlider = { let one = UISlider() one.minimumValue = 10 one.maximumValue = 200 view.addSubview(one) one.addTarget(self, action: #selector(widthSliderValueChange(_:)), for: .valueChanged) return one }() let sharp = NewSharp(title: "", inView: SuperV) widthSlider!.CENTER_X.EQUAL(SuperV).MAKE(scale) widthSlider!.CENTER_Y.EQUAL(SuperV).MAKE(scale) widthSlider!.WIDTH.EQUAL(200).MAKE(scale) sharp.CENTER_X.EQUAL(SuperV).MAKE(scale) sharp.TOP.EQUAL(SuperV).OFFSET(100).MAKE() widthCons = sharp.WIDTH.EQUAL(10).MAKE(scale) sharp.HEIGHT.EQUAL(100).MAKE(scale) } @objc func widthSliderValueChange(_ sender: UISlider) { widthCons?.constant = CGFloat(sender.value) * scale } }
apache-2.0
911b9810e3a7c071e1f36d01142e65a9
25.72
98
0.58982
4.149068
false
false
false
false
shu223/ARKit-Sampler
ARKit-Sampler/Samples/ARMetal/MetalImageView/MetalImageView.swift
1
10157
// // MetalImageView.swift // // Created by Shuichi Tsutsumi on 2016/12/11. // Copyright © 2016 Shuichi Tsutsumi. All rights reserved. // import MetalKit import MetalPerformanceShaders class MetalImageView: MTKView, MTKViewDelegate { private var commandQueue: MTLCommandQueue! internal var textureLoader: MTKTextureLoader! var texture: MTLTexture? { didSet { if let texture = texture { let pixelFormat = texture.pixelFormat colorPixelFormat = pixelFormat != MTLPixelFormat.invalid ? pixelFormat : MTLPixelFormat.rgba8Unorm DispatchQueue.main.async(execute: { let contentMode = self.contentMode self.transform(contentMode: contentMode) self.setNeedsDisplay() }) } } } private var lanczos: MPSImageLanczosScale! var transformedTexture: MTLTexture? // TODO: only get for external private let vertexData: [Float] = [ -1, -1, 0, 1, 1, -1, 0, 1, -1, 1, 0, 1, 1, 1, 0, 1 ] private lazy var vertexBuffer: MTLBuffer? = { let size = vertexData.count * MemoryLayout<Float>.size return makeBuffer(bytes: vertexData, length: size) }() private let textureCoordinateData: [Float] = [ 0, 1, 1, 1, 0, 0, 1, 0 ] private lazy var texCoordBuffer: MTLBuffer? = { let size = textureCoordinateData.count * MemoryLayout<Float>.size return makeBuffer(bytes: textureCoordinateData, length: size) }() // additional textures to pass to the fragment shader var additionalTextures: [MTLTexture] = [] // additional buffers to pass to the fragment shader var additionalBuffers: [MTLBuffer] = [] private var renderDescriptor: MTLRenderPipelineDescriptor? private var renderPipeline: MTLRenderPipelineState? // ========================================================================= // MARK: - Initialization init(frame frameRect: CGRect) { guard let device = MTLCreateSystemDefaultDevice() else {fatalError()} super.init(frame: frameRect, device: device) commonInit() } required init(coder: NSCoder) { super.init(coder: coder) guard let device = MTLCreateSystemDefaultDevice() else {fatalError()} self.device = device commonInit() } private func commonInit() { guard let device = device else {fatalError()} commandQueue = device.makeCommandQueue() textureLoader = MTKTextureLoader(device: device) lanczos = MPSImageLanczosScale(device: device) framebufferOnly = false enableSetNeedsDisplay = true isPaused = true delegate = self } // ========================================================================= // MARK: - Private private func transform(contentMode: UIView.ContentMode) { guard let device = device else {fatalError()} guard let drawable = currentDrawable, let texture = texture else {return} guard texture.width != drawable.texture.width || texture.height != drawable.texture.height else { transformedTexture = texture return } var transform: MPSScaleTransform = contentMode.scaleTransform( from: texture, to: drawable.texture) // make dest texture transformedTexture = device.makeTexture(pixelFormat: texture.pixelFormat, width: drawable.texture.width, height: drawable.texture.height) guard let transformedTexture = transformedTexture else {fatalError()} // resize guard let commandBuffer = commandQueue.makeCommandBuffer() else {fatalError()} withUnsafePointer(to: &transform) { (transformPtr: UnsafePointer<MPSScaleTransform>) in lanczos.scaleTransform = transformPtr lanczos.encode(commandBuffer: commandBuffer, sourceTexture: texture, destinationTexture: transformedTexture) } commandBuffer.commit() commandBuffer.waitUntilCompleted() } func makeBuffer(bytes: UnsafeRawPointer, length: Int) -> MTLBuffer { guard let device = device else {fatalError()} return device.makeBuffer(bytes: bytes, length: length, options: [])! } func registerShaders(library: MTLLibrary, vertexFunctionName: String, fragmentFunctionName: String) { renderDescriptor = MTLRenderPipelineDescriptor() guard let descriptor = renderDescriptor else {return} descriptor.vertexFunction = library.makeFunction(name: vertexFunctionName) descriptor.fragmentFunction = library.makeFunction(name: fragmentFunctionName) } private func makePipelineIfNeeded() { guard let texture = texture else {return} guard let descriptor = renderDescriptor else {return} guard let device = device else {fatalError()} descriptor.colorAttachments[0].pixelFormat = texture.pixelFormat renderPipeline = try? device.makeRenderPipelineState(descriptor: descriptor) } private func encodeShaders(commandBuffer: MTLCommandBuffer) { guard let renderPipeline = renderPipeline else {fatalError()} guard let renderPassDescriptor = currentRenderPassDescriptor else {return} renderPassDescriptor.colorAttachments[0].storeAction = .store guard let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else {return} renderEncoder.setRenderPipelineState(renderPipeline) renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0) renderEncoder.setVertexBuffer(texCoordBuffer, offset: 0, index: 1) renderEncoder.setFragmentTexture(texture, index: 0) var textureIndex = 1 for additionalTex in additionalTextures { renderEncoder.setFragmentTexture(additionalTex, index: textureIndex) textureIndex += 1 } var bufferIndex = 0 for additionalBuf in additionalBuffers { renderEncoder.setFragmentBuffer(additionalBuf, offset: 0, index: bufferIndex) bufferIndex += 1 } renderEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) renderEncoder.endEncoding() } // ========================================================================= // MARK: - MTKViewDelegate func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { print("\(self.classForCoder)/" + #function) } func draw(in view: MTKView) { guard let drawable = view.currentDrawable else {return} guard let transformedTexture = transformedTexture else {return} guard let commandBuffer = commandQueue.makeCommandBuffer() else {fatalError()} makePipelineIfNeeded() if renderPipeline != nil { encodeShaders(commandBuffer: commandBuffer) } else { // just copy to drawable guard let blitEncoder = commandBuffer.makeBlitCommandEncoder() else {fatalError()} blitEncoder.copy(from: transformedTexture, sourceSlice: 0, sourceLevel: 0, sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0), sourceSize: MTLSizeMake(transformedTexture.width, transformedTexture.height, transformedTexture.depth), to: drawable.texture, destinationSlice: 0, destinationLevel: 0, destinationOrigin: MTLOrigin(x: 0, y: 0, z: 0)) blitEncoder.endEncoding() } commandBuffer.present(drawable) commandBuffer.commit() commandBuffer.waitUntilCompleted() } } extension MTLDevice { func makeTexture(pixelFormat: MTLPixelFormat, width: Int, height: Int) -> MTLTexture { let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: width, height: height, mipmapped: true) textureDescriptor.usage = .shaderWrite return makeTexture(descriptor: textureDescriptor)! } } extension UIView.ContentMode { func scaleTransform(from inTexture: MTLTexture, to outTexture: MTLTexture) -> MPSScaleTransform { var scaleX: Double var scaleY: Double switch self { case .scaleToFill: scaleX = Double(outTexture.width) / Double(inTexture.width) scaleY = Double(outTexture.height) / Double(inTexture.height) case .scaleAspectFill: scaleX = Double(outTexture.width) / Double(inTexture.width) scaleY = Double(outTexture.height) / Double(inTexture.height) if scaleX > scaleY { scaleY = scaleX } else { scaleX = scaleY } case .scaleAspectFit: scaleX = Double(outTexture.width) / Double(inTexture.width) scaleY = Double(outTexture.height) / Double(inTexture.height) if scaleX > scaleY { scaleX = scaleY } else { scaleY = scaleX } default: scaleX = 1 scaleY = 1 } let translateX: Double let translateY: Double switch self { case .center, .scaleAspectFill, .scaleToFill: translateX = (Double(outTexture.width) - Double(inTexture.width) * scaleX) / 2 translateY = (Double(outTexture.height) - Double(inTexture.height) * scaleY) / 2 case .scaleAspectFit: translateX = 0 translateY = 0 default: fatalError("I'm sorry, this contentMode is not supported for now. Welcome your pull request!") } return MPSScaleTransform(scaleX: scaleX, scaleY: scaleY, translateX: translateX, translateY: translateY) } }
mit
3a3d09fe7b1ced0eb51b4d925b25bd9d
38.984252
145
0.614021
5.387798
false
false
false
false
milseman/swift
test/IRGen/objc_class_export.swift
12
5841
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop // CHECK: %swift.refcounted = type // CHECK: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }> // CHECK: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }> // CHECK: [[INT:%TSi]] = type <{ i64 }> // CHECK: [[DOUBLE:%TSd]] = type <{ double }> // CHECK: [[NSRECT:%TSC6NSRectV]] = type <{ %TSC7NSPointV, %TSC6NSSizeV }> // CHECK: [[NSPOINT:%TSC7NSPointV]] = type <{ %TSd, %TSd }> // CHECK: [[NSSIZE:%TSC6NSSizeV]] = type <{ %TSd, %TSd }> // CHECK: [[OBJC:%objc_object]] = type opaque // CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class { // CHECK: %objc_class* @"OBJC_METACLASS_$_SwiftObject", // CHECK: %objc_class* @"OBJC_METACLASS_$_SwiftObject", // CHECK: %swift.opaque* @_objc_empty_cache, // CHECK: %swift.opaque* null, // CHECK: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64) // CHECK: } // CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00" // CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK: i32 129, // CHECK: i32 40, // CHECK: i32 40, // CHECK: i32 0, // CHECK: i8* null, // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK: @_CLASS_METHODS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: i8* null, // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK: i32 128, // CHECK: i32 16, // CHECK: i32 24, // CHECK: i32 0, // CHECK: i8* null, // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: @_IVARS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: _PROPERTIES__TtC17objc_class_export3Foo // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_T017objc_class_export3FooCMf = internal global <{{.*i64}} }> <{ // CHECK: void ([[FOO]]*)* @_T017objc_class_export3FooCfD, // CHECK: i8** @_T0BOWV, // CHECK: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64), // CHECK: %objc_class* @"OBJC_CLASS_$_SwiftObject", // CHECK: %swift.opaque* @_objc_empty_cache, // CHECK: %swift.opaque* null, // CHECK: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 1), // CHECK: [[FOO]]* (%swift.type*)* @_T017objc_class_export3FooC6createACyFZ, // CHECK: void (double, double, double, double, [[FOO]]*)* @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tF // CHECK: }>, section "__DATA,__objc_data, regular" // -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of // Foo. // CHECK: @_T017objc_class_export3FooCN = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @_T017objc_class_export3FooCMf, i32 0, i32 2) to %swift.type*) // CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @_T017objc_class_export3FooCN import gizmo class Hoozit {} struct BigStructWithNativeObjects { var x, y, w : Double var h : Hoozit } @objc class Foo { @objc var x = 0 @objc class func create() -> Foo { return Foo() } @objc func drawInRect(dirty dirty: NSRect) { } // CHECK: define internal void @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tFTo([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]* // CHECK: call swiftcc void @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) // CHECK: } @objc func bounds() -> NSRect { return NSRect(origin: NSPoint(x: 0, y: 0), size: NSSize(width: 0, height: 0)) } // CHECK: define internal void @_T017objc_class_export3FooC6boundsSC6NSRectVyFTo([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @_T017objc_class_export3FooC6boundsSC6NSRectVyF([[FOO]]* swiftself [[CAST]]) @objc func convertRectToBacking(r r: NSRect) -> NSRect { return r } // CHECK: define internal void @_T017objc_class_export3FooC20convertRectToBackingSC6NSRectVAF1r_tFTo([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @_T017objc_class_export3FooC20convertRectToBackingSC6NSRectVAF1r_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) func doStuffToSwiftSlice(f f: [Int]) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @_T017objc_class_export3FooC19doStuffToSwiftSliceySaySiG1f_tcAAFTo func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStructfS_FT1fV17objc_class_export27BigStructWithNativeObjects_T_ init() { } }
apache-2.0
53a704965ade520d27ac449b518e9568
48.923077
218
0.643554
3.128548
false
false
false
false
larryhou/swift
MotionTracker/MotionTracker/ViewController.swift
1
10113
// // ViewController.swift // MotionTracker // // Created by larryhou on 13/8/2015. // Copyright © 2015 larryhou. All rights reserved. // import UIKit import CoreMotion extension Double { var radian: Double { return self * M_PI / 180 } var angle: Double { return self * 180 / M_PI } } extension Int { var double: Double { return Double(self) } } class MotionValue { var value: Double let name: String, format: String init(name: String, value: Double, format: String) { self.name = name self.value = value self.format = format } } struct UpdateState { var timestamp: NSTimeInterval var recordCount = 0, sum = 0.0, average = 0.0 var count = 0, fps = 0 init(timestamp: NSTimeInterval) { self.timestamp = timestamp } } enum TableSection: Int { case Gyroscrope, OptGyroscope case Magnetometer, OptMagnetometer case Accelerometer case UserAccelerometer case Gravity case AttitudeEuler case AttitudeQuaternion static var count: Int { return TableSection.AttitudeQuaternion.rawValue + 1 } } class NavigationController: UINavigationController { override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return [UIInterfaceOrientationMask.Portrait, UIInterfaceOrientationMask.PortraitUpsideDown] } } class ViewController: UITableViewController { private var motionManager: CMMotionManager! private var model: [Int: [MotionValue]]! private var state: UpdateState! private var timestamp: NSTimeInterval = 0 override func viewDidLoad() { super.viewDidLoad() model = [:] state = UpdateState(timestamp: 0) motionManager = CMMotionManager() print(motionManager.gyroAvailable) print(motionManager.magnetometerAvailable) print(motionManager.deviceMotionAvailable) print(motionManager.accelerometerAvailable) startGyroUpdate() startMagnetometerUpdate() startAccelerometerUpdate() startDeviceMotionUpdate() NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector: "scheduledTimerUpdate:", userInfo: nil, repeats: true) } func scheduledTimerUpdate(timer: NSTimer) { if timer.fireDate.timeIntervalSinceReferenceDate - state.timestamp >= 1.0 { state.timestamp = timer.fireDate.timeIntervalSinceReferenceDate state.fps = state.count state.count = 0 state.sum += state.fps.double state.average = state.sum / (++state.recordCount).double print(String(format: "fps:%d, average:%.2f", state.fps, state.average)) } if timer.fireDate.timeIntervalSinceReferenceDate - timestamp > 1.0 / 10 { timestamp = timer.fireDate.timeIntervalSinceReferenceDate tableView.reloadData() } } func startGyroUpdate() { motionManager.gyroUpdateInterval = 1/50 motionManager.startGyroUpdatesToQueue(NSOperationQueue.mainQueue()) { (data: CMGyroData?, error: NSError?) -> Void in if error == nil { // self.state.count++ self.updateGyroscope(data!.rotationRate, section: TableSection.Gyroscrope.rawValue) } } } func updateGyroscope(rate: CMRotationRate, section: Int) { let format = "%18.14f°/s" if model[section] == nil { var list = [MotionValue]() list.append(MotionValue(name: "X", value: rate.x.angle, format: format)) list.append(MotionValue(name: "Y", value: rate.y.angle, format: format)) list.append(MotionValue(name: "Z", value: rate.z.angle, format: format)) model.updateValue(list, forKey: section) } else { let list = model[section]! list[0].value = rate.x list[1].value = rate.y list[2].value = rate.z } } func startMagnetometerUpdate() { motionManager.startMagnetometerUpdatesToQueue(NSOperationQueue.mainQueue()) { (data: CMMagnetometerData?, error: NSError?) -> Void in if error == nil { // self.state.count++ self.updateMagnetometer(data!.magneticField, section: TableSection.Magnetometer.rawValue) } } } func updateMagnetometer(field: CMMagneticField, section: Int) { let format = "%18.12fμT" if model[section] == nil { var list = [MotionValue]() list.append(MotionValue(name: "X", value: field.x, format: format)) list.append(MotionValue(name: "Y", value: field.y, format: format)) list.append(MotionValue(name: "Z", value: field.z, format: format)) model.updateValue(list, forKey: section) } else { let list = model[section]! list[0].value = field.x list[1].value = field.y list[2].value = field.z } } func startAccelerometerUpdate() { motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) { (data: CMAccelerometerData?, error: NSError?) -> Void in if error == nil { self.state.count++ self.updateAcceleration(data!.acceleration, section: TableSection.Accelerometer.rawValue) } } } func updateAcceleration(acceleration: CMAcceleration, section: Int) { let format = "%10.6f × 9.81m/s²" if model[section] == nil { var list = [MotionValue]() list.append(MotionValue(name: "X", value: acceleration.x, format: format)) list.append(MotionValue(name: "Y", value: acceleration.y, format: format)) list.append(MotionValue(name: "Z", value: acceleration.z, format: format)) model.updateValue(list, forKey: section) } else { let list = model[section]! list[0].value = acceleration.x list[1].value = acceleration.y list[2].value = acceleration.z } } func startDeviceMotionUpdate() { motionManager.startDeviceMotionUpdatesUsingReferenceFrame(CMAttitudeReferenceFrame.XTrueNorthZVertical, toQueue: NSOperationQueue.mainQueue()) { (data: CMDeviceMotion?, error: NSError?) -> Void in if error == nil { // self.state.count++ self.updateGyroscope(data!.rotationRate, section: TableSection.OptGyroscope.rawValue) self.updateMagnetometer(data!.magneticField.field, section: TableSection.OptMagnetometer.rawValue) self.updateAcceleration(data!.userAcceleration, section: TableSection.UserAccelerometer.rawValue) self.updateAcceleration(data!.gravity, section: TableSection.Gravity.rawValue) let attitude: CMAttitude = data!.attitude let quaternion = self.convertQuaternionToEuler(attitude.quaternion) self.updateAttitude(quaternion, section: TableSection.AttitudeQuaternion.rawValue) self.updateAttitude((attitude.pitch, attitude.roll, attitude.yaw), section: TableSection.AttitudeEuler.rawValue) } } } func updateAttitude(attitude:(pitch: Double, roll: Double, yaw: Double), section: Int) { let format = "%18.13f°" if model[section] == nil { var list = [MotionValue]() list.append(MotionValue(name: "Pitch", value: attitude.pitch.angle, format: format)) list.append(MotionValue(name: "Roll", value: attitude.roll.angle, format: format)) list.append(MotionValue(name: "Yaw", value: attitude.yaw.angle, format: format)) model.updateValue(list, forKey: section) } else { let list = model[section]! list[0].value = attitude.pitch.angle list[1].value = attitude.roll.angle list[2].value = attitude.yaw.angle } } func convertQuaternionToEuler(quat: CMQuaternion) -> (pitch: Double, roll: Double, yaw: Double) { let x = atan2(2 * (quat.w * quat.x + quat.y * quat.z), 1 - 2 * (quat.x * quat.x + quat.y * quat.y)) let y = asin(2 * (quat.w * quat.y - quat.z * quat.x)) let z = atan2(2 * (quat.w * quat.z + quat.x * quat.y), 1 - 2 * (quat.y * quat.y + quat.z * quat.z)) return (x, y, z) } // MARK: table view override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return TableSection.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return model[section] == nil ? 0 : model[section]!.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let data = model[indexPath.section]![indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("MotionValueCell")! cell.textLabel?.text = data.name + ":" cell.detailTextLabel?.text = String(format: data.format, data.value) return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case TableSection.Gyroscrope.rawValue:return "Gyroscope" case TableSection.OptGyroscope.rawValue:return "Gyroscope Without Bias" case TableSection.Magnetometer.rawValue:return "Magnetometer" case TableSection.OptMagnetometer.rawValue:return "Magnetometer Without Bias" case TableSection.Accelerometer.rawValue:return "Acceleration" case TableSection.UserAccelerometer.rawValue:return "User Acceleration" case TableSection.AttitudeEuler.rawValue:return "Attitude Euler Angles" case TableSection.AttitudeQuaternion.rawValue:return "Attitude Quaternion Angles" case TableSection.Gravity.rawValue:return "Gravity" default:return "Unknown" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
2935218b24c700be0678ad7487ae0d9f
37.429658
204
0.638369
4.546559
false
false
false
false
MUECKE446/ActionLoggerPackage
Examples/ActionLoggerExample_1/ActionLoggerExample_1/MyMutableAttributedString.swift
1
14972
// // MyMutableAttributedString.swift // ActionLoggerExample_1 // // Created by Christian Muth on 02.01.16. // Copyright © 2016 Christian Muth. All rights reserved. // import Cocoa class MyMutableAttributedString: NSMutableAttributedString { fileprivate var _contents: NSMutableAttributedString override var string: String { get { return self._contents.string } } override init() { self._contents = NSMutableAttributedString() super.init() } override init(attributedString attrStr: NSAttributedString?) { if let _ = attrStr { self._contents = (attrStr!.mutableCopy() as! NSMutableAttributedString) } else { self._contents = NSMutableAttributedString() } super.init() } override init(string str: String) { self._contents = NSMutableAttributedString.init(string: str) super.init() } required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { // Local variable inserted by Swift 4.2 migrator. _ = convertFromNSPasteboardPasteboardType(type) fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [NSAttributedString.Key : Any] { let tmp = self._contents.attributes(at: location, effectiveRange: range) let tmp1 = convertFromNSAttributedStringKeyDictionary(tmp) return (tmp1) } override func replaceCharacters(in range: NSRange, with attrString: NSAttributedString) { self._contents.replaceCharacters(in: range, with: attrString) } override func setAttributes(_ attrs: [NSAttributedString.Key : Any]?, range: NSRange) { // Local variable inserted by Swift 4.2 migrator. let attrs = convertFromOptionalNSAttributedStringKeyDictionary(attrs) self._contents.setAttributes(convertToOptionalNSAttributedStringKeyDictionary(attrs), range: range) } override func fixAttachmentAttribute(in range: NSRange) { self._contents.fixAttributes(in: range) XcodeColors() } fileprivate func XcodeColors() { _ = string as NSString let editedRange = NSRange.init(location: 0, length: self._contents.length) //var attrs = NSMutableDictionary(capacity: 2) let attrs = NSMutableDictionary(objects: [NSColor.clear,NSColor.clear], forKeys: [convertFromNSAttributedStringKey(NSAttributedString.Key.backgroundColor) as NSCopying,convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor) as NSCopying]) attrs.removeObject(forKey: convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor)) attrs.removeObject(forKey: convertFromNSAttributedStringKey(NSAttributedString.Key.backgroundColor)) // Attribute fürs unsichtbar machen let clearAttrs = NSDictionary(objects: [NSFont.systemFont(ofSize: 0.001),NSColor.clear], forKeys: [convertFromNSAttributedStringKey(NSAttributedString.Key.font) as NSCopying,convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor) as NSCopying]) // finde alle ESCAPEs let matchesEscapeSequencesPattern = escapeSequencePattern.matches(in: string, options: .reportProgress, range: editedRange) setColorsInComponents(matchesEscapeSequencesPattern, colorAttributes: attrs, string: string) // finde zunächst alle Sequenzen für die Vordergrund Farbe let matchesColorPrefixForegroundPattern = xcodeColorPrefixForegroundPattern.matches(in: string, options: .reportProgress, range: editedRange) for result in matchesColorPrefixForegroundPattern { // der Bereich dieser Sequenz wird unsichtbar gemacht self.addAttributes(convertToNSAttributedStringKeyDictionary(clearAttrs as! [String : AnyObject]), range: result.range) } // finde zunächst alle Sequenzen für die Hintergrundfarbe let matchesColorPrefixBackgroundPattern = xcodeColorPrefixBackgroundPattern.matches(in: string, options: .reportProgress, range: editedRange) for result in matchesColorPrefixBackgroundPattern { // der Bereich dieser Sequenz wird unsichtbar gemacht self.addAttributes(convertToNSAttributedStringKeyDictionary(clearAttrs as! [String : AnyObject]), range: result.range) } let matchesResetForegroundPattern = xcodeColorResetForegroundPattern.matches(in: string, options: .reportProgress, range: editedRange) for result in matchesResetForegroundPattern { // der Bereich dieser Sequenz wird unsichtbar gemacht self.addAttributes(convertToNSAttributedStringKeyDictionary(clearAttrs as! [String : AnyObject]), range: result.range) } let matchesResetBackgroundPattern = xcodeColorResetBackgroundPattern.matches(in: string, options: .reportProgress, range: editedRange) for result in matchesResetBackgroundPattern { // der Bereich dieser Sequenz wird unsichtbar gemacht self.addAttributes(convertToNSAttributedStringKeyDictionary(clearAttrs as! [String : AnyObject]), range: result.range) } let matchesResetForeAndBackgroundPattern = xcodeColorResetForeAndBackgroundPattern.matches(in: string, options: .reportProgress, range: editedRange) for result in matchesResetForeAndBackgroundPattern { // der Bereich dieser Sequenz wird unsichtbar gemacht self.addAttributes(convertToNSAttributedStringKeyDictionary(clearAttrs as! [String : AnyObject]), range: result.range) } // hier müßte ich alle Esc Sequenzen zusammenhaben } func setColorsInComponents(_ xs: [NSTextCheckingResult], colorAttributes: NSMutableDictionary, string: String) { var resultArr: [NSRange] = [] let text = string as NSString let length = text.length for i in 0 ... xs.count-1 { let range_n_1 = xs[i].range if i < xs.count-1 { let range_n = xs[i+1].range let result = NSRange.init(location: range_n_1.location, length: range_n.location - range_n_1.location) resultArr.append(result) } else { let result = NSRange.init(location: range_n_1.location, length: length - range_n_1.location) resultArr.append(result) } } // nun ist der gesamte string in components aufgeteilt // stelle nun fest, um was es sich im einzelnen handelt for r in resultArr { let tmpStr = text.substring(with: r) as NSString var reset = false var reset_fg = false var reset_bg = false switch tmpStr.length { case 3: reset = tmpStr == "\u{1b}[;" case 5: reset_fg = tmpStr == "\u{1b}[fg;" reset_bg = tmpStr == "\u{1b}[bg;" default: break } if reset || reset_fg || reset_bg { if reset { // beide Attribute werden gelöscht colorAttributes.removeObject(forKey: convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor)) colorAttributes.removeObject(forKey: convertFromNSAttributedStringKey(NSAttributedString.Key.backgroundColor)) } else { if reset_fg { colorAttributes.removeObject(forKey: convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor)) } else { colorAttributes.removeObject(forKey: convertFromNSAttributedStringKey(NSAttributedString.Key.backgroundColor)) } } } else { // nun kann es sich nur noch um einen neuen Wert für Vorder- oder Hintergrungfarbe handeln // finde Sequenz für die Vordergrundfarbe let matchesColorPrefixForegroundPattern = xcodeColorPrefixForegroundPattern.matches(in: tmpStr as String, options: .reportProgress, range: NSRange.init(location: 0, length: tmpStr.length)) // finde Sequenz für die Hintergrundfarbe let matchesColorPrefixBackgroundPattern = xcodeColorPrefixBackgroundPattern.matches(in: tmpStr as String, options: .reportProgress, range: NSRange.init(location: 0, length: tmpStr.length)) if !matchesColorPrefixForegroundPattern.isEmpty { // das ist die Sequenz: \\x1b\\[fg[0-9][0-9]{0,2},[0-9][0-9]{0,2},[0-9][0-9]{0,2}; let string1 = tmpStr.substring(with: matchesColorPrefixForegroundPattern[0].range) colorAttributes.setObject(getColor(components: string1), forKey: convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor) as NSCopying) } else { assert(!matchesColorPrefixBackgroundPattern.isEmpty) // das ist die Sequenz: \\x1b\\[bg[0-9][0-9]{0,2},[0-9][0-9]{0,2},[0-9][0-9]{0,2}; let string1 = tmpStr.substring(with: matchesColorPrefixBackgroundPattern[0].range) colorAttributes.setObject(getColor(components: string1), forKey: convertFromNSAttributedStringKey(NSAttributedString.Key.backgroundColor) as NSCopying) } } // nun kann die Komponente mit den Farben versehen werden self.addAttributes(convertToNSAttributedStringKeyDictionary(colorAttributes as NSDictionary as! [String : AnyObject]), range: r) } } fileprivate func getColor(components componentString: String) -> NSColor { // before swift 4.2 //let searchString = componentString.substring(from: componentString.index(componentString.startIndex, offsetBy: 4)) let searchString = String(componentString[componentString.index(componentString.startIndex, offsetBy: 4)...]) let text1 = searchString as NSString let matchesColorsPattern = xcodeColorsPattern.matches(in: searchString, options: .reportProgress, range: NSMakeRange(0, searchString.count)) // es müssen 3 Farbkomponenten gefunden werden assert(matchesColorsPattern.count == 3) let str_r = text1.substring(with: matchesColorsPattern[0].range) let str_g = text1.substring(with: matchesColorsPattern[1].range) let str_b = text1.substring(with: matchesColorsPattern[2].range) // wandle die Strings in Ints let r = CGFloat.init(Int(str_r)!) let g = CGFloat.init(Int(str_g)!) let b = CGFloat.init(Int(str_b)!) let color = NSColor(calibratedRed: (r/255.0), green: (g/255.0), blue: (b/255.0), alpha: 1.0) return color } fileprivate var pattern: NSRegularExpression { // The second capture is either a file extension (default) or a function name (SwiftyBeaver format). // Callers should check for the presence of the third capture to detect if it is SwiftyBeaver or not. // // (If this gets any more complicated there will need to be a formal way to walk through multiple // patterns and check if each one matches.) return try! NSRegularExpression(pattern: "([\\w\\+]+)\\.(\\w+)(\\(\\))?:(\\d+)", options: .caseInsensitive) } fileprivate var escapeSequencePattern: NSRegularExpression { return try! NSRegularExpression(pattern: "\\x1b\\[", options: .caseInsensitive) } fileprivate var xcodeColorPrefixPattern: NSRegularExpression { return try! NSRegularExpression(pattern: "\\x1b\\[fg[0-9][0-9]{0,2},[0-9][0-9]{0,2},[0-9][0-9]{0,2};\\x1b\\[bg[0-9][0-9]{0,2},[0-9][0-9]{0,2},[0-9][0-9]{0,2};", options: .caseInsensitive) } fileprivate var xcodeColorPrefixForegroundPattern: NSRegularExpression { return try! NSRegularExpression(pattern: "\\x1b\\[fg[0-9][0-9]{0,2},[0-9][0-9]{0,2},[0-9][0-9]{0,2};", options: .caseInsensitive) } fileprivate var xcodeColorPrefixBackgroundPattern: NSRegularExpression { return try! NSRegularExpression(pattern: "\\x1b\\[bg[0-9][0-9]{0,2},[0-9][0-9]{0,2},[0-9][0-9]{0,2};", options: .caseInsensitive) } fileprivate var xcodeColorsPattern: NSRegularExpression { return try! NSRegularExpression(pattern: "([0-9][0-9]{0,2})", options: .caseInsensitive) } fileprivate var xcodeColorResetForegroundPattern: NSRegularExpression { return try! NSRegularExpression(pattern: "\\x1b\\[fg;", options: .caseInsensitive) } fileprivate var xcodeColorResetBackgroundPattern: NSRegularExpression { return try! NSRegularExpression(pattern: "\\x1b\\[bg;", options: .caseInsensitive) } fileprivate var xcodeColorResetForeAndBackgroundPattern: NSRegularExpression { return try! NSRegularExpression(pattern: "\\x1b\\[;", options: .caseInsensitive) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSPasteboardPasteboardType(_ input: NSPasteboard.PasteboardType) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromOptionalNSAttributedStringKeyDictionary(_ input: [NSAttributedString.Key: Any]?) -> [String: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKeyDictionary(_ input: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToNSAttributedStringKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.Key: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
mit
24291b199885c2f77d48d09dbeab11af
48.207237
269
0.672639
4.647095
false
false
false
false
THINKGlobalSchool/SpotConnect
ShareAction/AlbumListViewController.swift
1
5322
// // AlbumListViewController.swift // SpotConnect // // Created by Jeff Tilson on 2015-09-30. // Copyright © 2015 Jeff Tilson. All rights reserved. // import UIKit import SwiftyJSON // MARK: - Protocols protocol AlbumListViewControllerDelegate { func albumInputCompleted(titleString: String, guidString: String) } class AlbumListViewController: UITableViewController { // MARK: - Class structures struct TableViewValues { static let identifier = "albumCell" } // MARK: - Class constants/vars var delegate: AlbumListViewControllerDelegate? var spotApi: SpotApi! var albums = [[String: String]]() // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: TableViewValues.identifier) // Load a list of albums spotApi.makeGetRequest(SpotMethods.albumsList, parameters: nil) { (response) in var wasError = false var title = "" var message = "" // Check for errors if (response.result.isFailure) { if let uError = response.result.error { title = uError.localizedDescription if let reason = uError.localizedFailureReason { message = reason } else { message = title title = "Error" } wasError = true } } else { var json = JSON(response.result.value!) // Check for an API error if (json["status"] != 0) { title = "Error" message = json["message"].stringValue wasError = true } else { for result in json["result"].arrayValue { let title = result["title"].stringValue let guid = result["guid"].stringValue let album = ["title": title, "guid": guid] self.albums.append(album) } self.tableView.reloadData() dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } } if (wasError) { let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { action in // Pop back to the share view controller self.navigationController?.popViewControllerAnimated(true) })) self.presentViewController(alertController, animated: true, completion: nil) } } // Uncomment the following line to preserve selection between presentations self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITableViewController override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.albums.count } override init(style: UITableViewStyle) { super.init(style: style) title = "Select Album" } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier(TableViewValues.identifier, forIndexPath: indexPath) let albumInfo = self.albums[indexPath.row] cell.textLabel!.text = albumInfo["title"] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let delegate = self.delegate { let selectedAlbum = self.albums[indexPath.row] delegate.albumInputCompleted(selectedAlbum["title"]!, guidString: selectedAlbum["guid"]!) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
e41470a8222e98cb6b53af284a49bb93
33.329032
133
0.56869
5.860132
false
false
false
false
arvedviehweger/swift
test/SILOptimizer/definite_init_protocol_init.swift
13
5273
// RUN: %target-swift-frontend -emit-sil %s | %FileCheck %s // Ensure that convenience initializers on concrete types can // delegate to factory initializers defined in protocol // extensions. protocol TriviallyConstructible { init(lower: Int) } extension TriviallyConstructible { init(middle: Int) { self.init(lower: middle) } init?(failingMiddle: Int) { self.init(lower: failingMiddle) } init(throwingMiddle: Int) throws { try self.init(lower: throwingMiddle) } } class TrivialClass : TriviallyConstructible { required init(lower: Int) {} // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B012TrivialClassCACSi5upper_tcfc // CHECK: bb0(%0 : $Int, [[OLD_SELF:%.*]] : $TrivialClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $TrivialClass // CHECK-NEXT: debug_value // CHECK-NEXT: store [[OLD_SELF]] to [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick TrivialClass.Type, %1 // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $TrivialClass // CHECK-NEXT: apply [[FN]]<TrivialClass>([[RESULT]], %0, [[METATYPE]]) // CHECK-NEXT: [[NEW_SELF:%.*]] = load [[RESULT]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick TrivialClass.Type, %1 // CHECK-NEXT: dealloc_partial_ref %1 : $TrivialClass, [[METATYPE]] : $@thick TrivialClass.Type // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] convenience init(upper: Int) { self.init(middle: upper) } convenience init?(failingUpper: Int) { self.init(failingMiddle: failingUpper) } convenience init(throwingUpper: Int) throws { try self.init(throwingMiddle: throwingUpper) } } struct TrivialStruct : TriviallyConstructible { let x: Int init(lower: Int) { self.x = lower } // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B013TrivialStructVACSi5upper_tcfC // CHECK: bb0(%0 : $Int, %1 : $@thin TrivialStruct.Type): // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialStruct // CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $TrivialStruct // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialStruct.Type // CHECK-NEXT: apply [[FN]]<TrivialStruct>([[SELF_BOX]], %0, [[METATYPE]]) // CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[NEW_SELF]] init(upper: Int) { self.init(middle: upper) } init?(failingUpper: Int) { self.init(failingMiddle: failingUpper) } init(throwingUpper: Int) throws { try self.init(throwingMiddle: throwingUpper) } } struct AddressOnlyStruct : TriviallyConstructible { let x: Any init(lower: Int) { self.x = lower } // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B017AddressOnlyStructVACSi5upper_tcfC // CHECK: bb0(%0 : $*AddressOnlyStruct, %1 : $Int, %2 : $@thin AddressOnlyStruct.Type): // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $AddressOnlyStruct // CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $AddressOnlyStruct // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick AddressOnlyStruct.Type // CHECK-NEXT: apply [[FN]]<AddressOnlyStruct>([[SELF_BOX]], %1, [[METATYPE]]) // CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [initialization] [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: copy_addr [take] [[SELF]] to [initialization] %0 // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] init(upper: Int) { self.init(middle: upper) } init?(failingUpper: Int) { self.init(failingMiddle: failingUpper) } init(throwingUpper: Int) throws { try self.init(throwingMiddle: throwingUpper) } } enum TrivialEnum : TriviallyConstructible { case NotSoTrivial init(lower: Int) { self = .NotSoTrivial } // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B011TrivialEnumOACSi5upper_tcfC // CHECK: bb0(%0 : $Int, %1 : $@thin TrivialEnum.Type): // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialEnum // CHECK: [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $TrivialEnum // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialEnum.Type // CHECK-NEXT: apply [[FN]]<TrivialEnum>([[SELF_BOX]], %0, [[METATYPE]]) // CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[NEW_SELF]] init(upper: Int) { self.init(middle: upper) } init?(failingUpper: Int) { self.init(failingMiddle: failingUpper) } init(throwingUpper: Int) throws { try self.init(throwingMiddle: throwingUpper) } }
apache-2.0
440db3d8c730402e4c489bb9de021765
34.389262
119
0.666224
3.47365
false
false
false
false
AllenOoo/SliderMenu-CollectionView
MyDemosInSwift/SliderMenuView.swift
1
6712
// // SliderMenuView.swift // MyDemosInSwift // // Created by allen on 16/8/26. // Copyright © 2016年 allen.wu. All rights reserved. // import UIKit protocol SliderMenuViewDelegate { func didSelectedAtIndex(index: NSInteger , animated: Bool) } class SliderMenuView: YZView, YZButtonDelegate { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var titles: [String] = []; var delegate : SliderMenuViewDelegate! var index : NSInteger = 0 { didSet { initIndex = index if !YZButtons.isEmpty { YZButtons[index]?.scaleFloat = YZButtonScaleMaxFloat self.delegate.didSelectedAtIndex(index, animated: isAnimated) selectTitleGotoCenter(index) } isAnimated = true } } override var backgroundColor: UIColor? { didSet { mainScrolleView.backgroundColor = backgroundColor } } private var isAnimated: Bool = false private var initIndex : NSInteger = 0; private var titleWidths : [NSNumber] = [] private var YZButtons : [YZButton?] = [] private var mainScrolleView: UIScrollView! private var buttonsTotalLength: CGFloat = 0 override init(frame: CGRect) { super.init(frame: frame) mainScrolleView = UIScrollView.init(frame: CGRectMake(0, 0, frame.width, frame.height)) mainScrolleView.showsVerticalScrollIndicator = false mainScrolleView.showsHorizontalScrollIndicator = false mainScrolleView.backgroundColor = UIColor.init(red: 255/255.0, green: 66/255.0, blue: 93/255, alpha: 1) self.addSubview(mainScrolleView) } override func drawRect(rect: CGRect) { drawMainViews() } /// 构建画面 func drawMainViews() { // titleWidths = getTitleWidths(titles) if YZButtons.isEmpty { for index in 0..<titles.count { let button = YZButton.initWithType(CGRectMake(getButtonMinX(index), 0, CGFloat.init(titleWidths[index]), self.frame.height), type: .scale) button?.setTitle(titles[index], forState: .Normal) button?.delegate = self button?.tag = YZButtonTagStart+index YZButtons.append(button) mainScrolleView.addSubview(button!) } mainScrolleView.contentSize = CGSizeMake(buttonsTotalLength, self.frame.height) } isAnimated = false index = initIndex } /// 根据title宽度返回item宽度 func getTitleWidths(titles: [String]) -> [NSNumber] { var titleWidthArray: [NSNumber] = []; var widths : [NSNumber] = []; for title in titles { let titleWidth = NSNumber(double: (title.width() + 50)) titleWidthArray.append(titleWidth) } buttonsTotalLength = getTotalLength(titleWidthArray) if buttonsTotalLength <= self.frame.width { buttonsTotalLength = self.frame.width let width = self.frame.width/CGFloat.init(titles.count) for _ in 0..<titles.count{ widths.append(width) } titleWidthArray = widths } return titleWidthArray } /// 获得items的总长度 func getTotalLength(buttonWidths: [NSNumber]) -> CGFloat { var totalLength: CGFloat = 0; for width in buttonWidths { let butttonWith = CGFloat.init(width) totalLength += butttonWith } return totalLength <= self.frame.width ? self.frame.width : totalLength } /// 根据title不同宽度获取item该显示的最小x坐标 func getButtonMinX(index: NSInteger) -> CGFloat { var minX: CGFloat = 0; for itemIndex in 0..<index { minX += CGFloat.init(titleWidths[itemIndex]) } return minX } /// 将item置中心位置 func selectTitleGotoCenter(index: NSInteger) { if !YZButtons.isEmpty { let indexButton = YZButtons[index]! let judageLength = (self.frame.width + indexButton.frame.width)/2 if buttonsTotalLength > self.frame.width { if indexButton.frame.maxX <= judageLength{ mainScrolleView.setContentOffset(CGPointZero, animated: true) } else if indexButton.frame.minX >= buttonsTotalLength - judageLength { mainScrolleView.setContentOffset(CGPointMake(buttonsTotalLength-self.frame.width, 0) , animated: true) } else { // 可滑动 mainScrolleView.setContentOffset(CGPointMake(indexButton.frame.midX-self.frame.width/2, 0), animated: true) } } } } /// 给对应的item进行缩放 func itemScaledByDistance(distance: Double) { let scaleFloat = (fabs(distance)/Double(self.frame.width))*YZButtonScaleMaxFloat let currentItem = YZButtons[index] let nextItem : YZButton? if distance > 0 { // 左 if index <= 0 { nextItem = YZButton.init(frame: CGRectZero) } else { nextItem = YZButtons[index-1] } } else { if index >= YZButtons.count-1 { nextItem = YZButton.init(frame: CGRectZero) } else { nextItem = YZButtons[index+1] } } nextItem?.scaleFloat = 1 + scaleFloat currentItem?.scaleFloat = YZButtonScaleMaxFloat - scaleFloat } /// 设定最终状态,除需要高亮的外全部返回初始状态 func sliderMenuWillScrollToIndex(targetIndex: NSInteger) { let lastItem : YZButton? let nextItem : YZButton? if targetIndex == 0 { nextItem = YZButtons[targetIndex + 1] lastItem = YZButton.init(frame: CGRectZero) } else if targetIndex >= YZButtons.count - 1 { nextItem = YZButton.init(frame: CGRectZero) lastItem = YZButtons[targetIndex - 1] } else { nextItem = YZButtons[targetIndex + 1] lastItem = YZButtons[targetIndex - 1] } /// 返回初始状态 lastItem?.scaleFloat = YZButtonScaleMinFloat nextItem?.scaleFloat = YZButtonScaleMinFloat index = targetIndex; } // MARK: YZButtonDelegate func didSelectedAtButton(button: YZButton?) { if button?.tag != YZButtonTagStart+index { YZButtons[index]?.scaleFloat = YZButtonScaleMinFloat; } index = (button?.tag)! - YZButtonTagStart; } }
apache-2.0
49698dce56c4fdae056752d1b26cf8c8
31.909548
154
0.596122
4.605485
false
false
false
false
davidbutz/ChristmasFamDuels
iOS/Boat Aware/DeviceCapability.swift
1
1791
// // DeviceCapability.swift // Boat Aware // // Created by Adam Douglass on 2/8/16. // Copyright © 2016 Thrive Engineering. All rights reserved. // import UIKit class DeviceCapability { class func allDeviceCapabilities() -> [DeviceCapability] { var photos = [DeviceCapability]() if let URL = NSBundle.mainBundle().URLForResource("DeviceCapabilities", withExtension: "plist") { if let photosFromPlist = NSArray(contentsOfURL: URL) { for dictionary in photosFromPlist { let photo = DeviceCapability(dictionary: dictionary as! NSDictionary) photos.append(photo) } } } return photos } var name: String var value: String? var image: UIImage? var status: String? init(name: String, value: String?, image: UIImage?, status: String?) { self.name = name self.value = value self.image = image self.status = status } convenience init(dictionary: NSDictionary) { let name = dictionary["Name"] as? String let value = dictionary["Value"] as? String let photo = dictionary["Photo"] as? String var image : UIImage? if photo != nil { image = UIImage(named: photo!)?.decompressedImage } let status = dictionary["Status"] as? String self.init(name: name!, value: value, image: image, status: status) } func heightForComment(font: UIFont, width: CGFloat) -> CGFloat { let rect = NSString(string: name).boundingRectWithSize(CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(rect.height) } }
mit
b250ad4494ff3d3b7fe7c2eaa61172db
32.148148
200
0.615084
4.601542
false
false
false
false
practicalswift/swift
test/SILGen/synthesized_conformance_enum.swift
4
5045
// RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 | %FileCheck -check-prefix CHECK -check-prefix CHECK-FRAGILE %s // RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 -enable-resilience | %FileCheck -check-prefix CHECK -check-prefix CHECK-RESILIENT %s enum Enum<T> { case a(T), b(T) } // CHECK-LABEL: enum Enum<T> { // CHECK: case a(T), b(T) // CHECK: } enum NoValues { case a, b } // CHECK-LABEL: enum NoValues { // CHECK: case a, b // CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: NoValues, _ b: NoValues) -> Bool // CHECK-RESILIENT: static func == (a: NoValues, b: NoValues) -> Bool // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension Enum : Equatable where T : Equatable { // CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Enum<T>, _ b: Enum<T>) -> Bool // CHECK-RESILIENT: static func == (a: Enum<T>, b: Enum<T>) -> Bool // CHECK: } // CHECK-LABEL: extension Enum : Hashable where T : Hashable { // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension NoValues : CaseIterable { // CHECK: typealias AllCases = [NoValues] // CHECK: static var allCases: [NoValues] { get } // CHECK: } extension Enum: Equatable where T: Equatable {} // CHECK-FRAGILE-LABEL: // static Enum<A>.__derived_enum_equals(_:_:) // CHECK-FRAGILE-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASQRzlE010__derived_C7_equalsySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool { // CHECK-RESILIENT-LABEL: // static Enum<A>.== infix(_:_:) // CHECK-RESILIENT-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASQRzlE2eeoiySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool { extension Enum: Hashable where T: Hashable {} // CHECK-LABEL: // Enum<A>.hashValue.getter // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASHRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Enum<T>) -> Int { // CHECK-LABEL: // Enum<A>.hash(into:) // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASHRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Enum<T>) -> () { extension NoValues: CaseIterable {} // CHECK-LABEL: // static NoValues.allCases.getter // CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum8NoValuesO8allCasesSayACGvgZ : $@convention(method) (@thin NoValues.Type) -> @owned Array<NoValues> { // Witness tables for Enum // CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum { // CHECK-NEXT: method #Equatable."=="!1: <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$s28synthesized_conformance_enum4EnumOyxGSQAASQRzlSQ2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Enum<A> // CHECK-NEXT: conditional_conformance (T: Equatable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Enum<T>: Hashable module synthesized_conformance_enum { // CHECK-DAG: base_protocol Equatable: <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum // CHECK-DAG: method #Hashable.hashValue!getter.1: <Self where Self : Hashable> (Self) -> () -> Int : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Enum<A> // CHECK-DAG: method #Hashable.hash!1: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Enum<A> // CHECK-DAG: method #Hashable._rawHashValue!1: <Self where Self : Hashable> (Self) -> (Int) -> Int : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH13_rawHashValue4seedS2i_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Enum<A> // CHECK-DAG: conditional_conformance (T: Hashable): dependent // CHECK: } // Witness tables for NoValues // CHECK-LABEL: sil_witness_table hidden NoValues: CaseIterable module synthesized_conformance_enum { // CHECK-NEXT: associated_type_protocol (AllCases: Collection): [NoValues]: specialize <NoValues> (<Element> Array<Element>: Collection module Swift) // CHECK-NEXT: associated_type AllCases: Array<NoValues> // CHECK-NEXT: method #CaseIterable.allCases!getter.1: <Self where Self : CaseIterable> (Self.Type) -> () -> Self.AllCases : @$s28synthesized_conformance_enum8NoValuesOs12CaseIterableAAsADP8allCases03AllI0QzvgZTW // protocol witness for static CaseIterable.allCases.getter in conformance NoValues // CHECK-NEXT: }
apache-2.0
f20463878f06a54913a6dafe99e34706
63.679487
298
0.716353
3.401888
false
false
false
false
huonw/swift
stdlib/public/SDK/Dispatch/Dispatch.swift
4
5636
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Dispatch import _SwiftDispatchOverlayShims /// dispatch_assert @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public enum DispatchPredicate { case onQueue(DispatchQueue) case onQueueAsBarrier(DispatchQueue) case notOnQueue(DispatchQueue) } @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public func _dispatchPreconditionTest(_ condition: DispatchPredicate) -> Bool { switch condition { case .onQueue(let q): __dispatch_assert_queue(q) case .onQueueAsBarrier(let q): __dispatch_assert_queue_barrier(q) case .notOnQueue(let q): __dispatch_assert_queue_not(q) } return true } @_transparent @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public func dispatchPrecondition(condition: @autoclosure () -> DispatchPredicate) { // precondition is able to determine release-vs-debug asserts where the overlay // cannot, so formulating this into a call that we can call with precondition() precondition(_dispatchPreconditionTest(condition()), "dispatchPrecondition failure") } /// qos_class_t public struct DispatchQoS : Equatable { public let qosClass: QoSClass public let relativePriority: Int @available(macOS 10.10, iOS 8.0, *) public static let background = DispatchQoS(qosClass: .background, relativePriority: 0) @available(macOS 10.10, iOS 8.0, *) public static let utility = DispatchQoS(qosClass: .utility, relativePriority: 0) @available(macOS 10.10, iOS 8.0, *) public static let `default` = DispatchQoS(qosClass: .default, relativePriority: 0) @available(macOS 10.10, iOS 8.0, *) public static let userInitiated = DispatchQoS(qosClass: .userInitiated, relativePriority: 0) @available(macOS 10.10, iOS 8.0, *) public static let userInteractive = DispatchQoS(qosClass: .userInteractive, relativePriority: 0) public static let unspecified = DispatchQoS(qosClass: .unspecified, relativePriority: 0) public enum QoSClass { @available(macOS 10.10, iOS 8.0, *) case background @available(macOS 10.10, iOS 8.0, *) case utility @available(macOS 10.10, iOS 8.0, *) case `default` @available(macOS 10.10, iOS 8.0, *) case userInitiated @available(macOS 10.10, iOS 8.0, *) case userInteractive case unspecified @available(macOS 10.10, iOS 8.0, *) public init?(rawValue: qos_class_t) { switch rawValue { case QOS_CLASS_BACKGROUND: self = .background case QOS_CLASS_UTILITY: self = .utility case QOS_CLASS_DEFAULT: self = .default case QOS_CLASS_USER_INITIATED: self = .userInitiated case QOS_CLASS_USER_INTERACTIVE: self = .userInteractive case QOS_CLASS_UNSPECIFIED: self = .unspecified default: return nil } } @available(macOS 10.10, iOS 8.0, *) public var rawValue: qos_class_t { switch self { case .background: return QOS_CLASS_BACKGROUND case .utility: return QOS_CLASS_UTILITY case .default: return QOS_CLASS_DEFAULT case .userInitiated: return QOS_CLASS_USER_INITIATED case .userInteractive: return QOS_CLASS_USER_INTERACTIVE case .unspecified: return QOS_CLASS_UNSPECIFIED } } } public init(qosClass: QoSClass, relativePriority: Int) { self.qosClass = qosClass self.relativePriority = relativePriority } public static func ==(a: DispatchQoS, b: DispatchQoS) -> Bool { return a.qosClass == b.qosClass && a.relativePriority == b.relativePriority } } /// @_frozen public enum DispatchTimeoutResult { case success case timedOut } /// dispatch_group public extension DispatchGroup { public func notify(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], queue: DispatchQueue, execute work: @escaping @convention(block) () -> Void) { if #available(macOS 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: work) _swift_dispatch_group_notify(self, queue, item._block) } else { _swift_dispatch_group_notify(self, queue, work) } } @available(macOS 10.10, iOS 8.0, *) public func notify(queue: DispatchQueue, work: DispatchWorkItem) { _swift_dispatch_group_notify(self, queue, work._block) } public func wait() { _ = __dispatch_group_wait(self, DispatchTime.distantFuture.rawValue) } public func wait(timeout: DispatchTime) -> DispatchTimeoutResult { return __dispatch_group_wait(self, timeout.rawValue) == 0 ? .success : .timedOut } public func wait(wallTimeout timeout: DispatchWallTime) -> DispatchTimeoutResult { return __dispatch_group_wait(self, timeout.rawValue) == 0 ? .success : .timedOut } } /// dispatch_semaphore public extension DispatchSemaphore { @discardableResult public func signal() -> Int { return __dispatch_semaphore_signal(self) } public func wait() { _ = __dispatch_semaphore_wait(self, DispatchTime.distantFuture.rawValue) } public func wait(timeout: DispatchTime) -> DispatchTimeoutResult { return __dispatch_semaphore_wait(self, timeout.rawValue) == 0 ? .success : .timedOut } public func wait(wallTimeout: DispatchWallTime) -> DispatchTimeoutResult { return __dispatch_semaphore_wait(self, wallTimeout.rawValue) == 0 ? .success : .timedOut } }
apache-2.0
38e3eec7e0062dcb22ef6b38575cefdf
30.311111
166
0.706352
3.65974
false
false
false
false
yanif/circator
MetabolicCompass/CommonUI/UITooltips.swift
1
2967
// // UITooltips.swift // MetabolicCompass // // Created by Yanif Ahmad on 7/17/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import Foundation import EasyTipView public class UITooltips : NSObject { public static let sharedInstance = UITooltips() public override init() { var preferences = EasyTipView.Preferences() preferences.drawing.foregroundColor = .whiteColor() preferences.drawing.backgroundColor = .blueColor() preferences.drawing.arrowPosition = .Top EasyTipView.globalPreferences = preferences } public func showTip(forView view: UIView, withinSuperview superview: UIView? = nil, text: String, delegate: EasyTipViewDelegate? = nil) { EasyTipView.show(forView: view, withinSuperview: superview, text: text, delegate: delegate) } public func tipBelow() -> EasyTipView.Preferences { var preferences = EasyTipView.Preferences() preferences.drawing.foregroundColor = .whiteColor() preferences.drawing.backgroundColor = .blueColor() preferences.drawing.arrowPosition = .Top preferences.positioning.maxWidth = ScreenManager.sharedInstance.tooltipMaxWidth() return preferences } public func tipAbove() -> EasyTipView.Preferences { var preferences = EasyTipView.Preferences() preferences.drawing.foregroundColor = .whiteColor() preferences.drawing.backgroundColor = .blueColor() preferences.drawing.arrowPosition = .Bottom preferences.positioning.maxWidth = ScreenManager.sharedInstance.tooltipMaxWidth() return preferences } } public class TapTip : NSObject, EasyTipViewDelegate { public var visible: Bool = false public var tipView: EasyTipView! = nil public var forView: UIView public var withinView: UIView? = nil public var tapRecognizer: UITapGestureRecognizer! = nil public init(forView view: UIView, withinView: UIView? = nil, text: String, width: CGFloat? = nil, numTaps: Int = 2, numTouches: Int = 1, asTop: Bool = false) { self.forView = view self.withinView = withinView super.init() var preferences = asTop ? UITooltips.sharedInstance.tipAbove() : UITooltips.sharedInstance.tipBelow() if let w = width { preferences.positioning.maxWidth = min(w, ScreenManager.sharedInstance.tooltipMaxWidth()) } tipView = EasyTipView(text: text, preferences: preferences, delegate: self) tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showTip)) tapRecognizer.numberOfTapsRequired = numTaps tapRecognizer.numberOfTouchesRequired = numTouches } public func showTip() { if !visible { visible = true tipView.show(forView: forView, withinSuperview: withinView) } } public func easyTipViewDidDismiss(tipView: EasyTipView) { visible = false } }
apache-2.0
6ddc0c49ba680e6a7d4ccac8c8f22da6
37.025641
163
0.692515
4.968174
false
false
false
false
keyOfVv/Cusp
CuspDemo/Classes/Scan+Connect+ReadRSSI/SCRTableViewController.swift
1
1947
// // SCRTableViewController.swift // Cusp // // Created by Ke Yang on 27/02/2017. // Copyright © 2017 com.keyofvv. All rights reserved. // import UIKit import Cusp class SCRTableViewController: UITableViewController { var ad: Advertisement? { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() title = "Connect/Disconnect & Subscription" tableView.register(UINib(nibName: "ScanTableViewCell", bundle: nil), forCellReuseIdentifier: ScanTableViewCellReuseID) CuspCentral.default.scanForUUIDString(["1803"], completion: { (ads) in self.ad = ads.first }, abruption: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.ad == nil ? 0 : 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ScanTableViewCellReuseID, for: indexPath) as! ScanTableViewCell cell.advertisement = self.ad return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let peripheral = self.ad?.peripheral else { return } switch peripheral.state { case .disconnected: CuspCentral.default.connect(peripheral, success: { (_) in peripheral.readRSSI(success: { (resp) in dog(resp?.RSSI) }, failure: nil) }, failure: nil, abruption: nil) case .connected: CuspCentral.default.disconnect(peripheral, completion: { dog("diconnected") }) case .unknown: dog("unknown state") case .connecting: dog("connecting") } } }
mit
d732a2dad735869f5f8a284ec7b0c078
28.938462
130
0.715313
3.96334
false
false
false
false
novi/proconapp
ProconApp/ProconApp WatchKit Extension/ResultInterfaceController.swift
1
2179
// // ResultInterfaceController.swift // ProconApp // // Created by hanamiju on 2015/08/13. // Copyright (c) 2015年 Procon. All rights reserved. // import WatchKit import Foundation import ProconBase class ResultInterfaceController: InterfaceController { @IBOutlet weak var titleLabel: WKInterfaceLabel! @IBOutlet weak var timeLabel: WKInterfaceLabel! @IBOutlet weak var schoolTable: WKInterfaceTable! var gameResult: GameResult? override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) gameResult = (context as! GameResultObject).result } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() fetchContents() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func fetchContents() { self.reloadContents() } override func reloadContents() { if let gr = self.gameResult { titleLabel.setText(gr.title) timeLabel.setText(gr.startedAt.relativeDateString) let ranks = gr.resultsByRank schoolTable.setNumberOfRows(ranks.count, withRowType: .ResultSchool) for i in 0..<ranks.count { let cell = schoolTable.rowControllerAtIndex(i) as! SchoolTableCell cell.result = ranks[i] } } } } class SchoolTableCell: NSObject { @IBOutlet weak var schoolLabel: WKInterfaceLabel! @IBOutlet weak var rankLabel: WKInterfaceLabel! @IBOutlet weak var scoreLabel: WKInterfaceLabel! @IBOutlet weak var unitLabel: WKInterfaceLabel! var result: GameResult.Result? { didSet { if let result = self.result { schoolLabel.setText(result.player.shortName) rankLabel.setText("\(result.rank)位") scoreLabel.setText(result.scoresShortString) unitLabel.setText(result.scoreUnit) } } } }
bsd-3-clause
95c8f7154bbe3f59fb4d49190e1afe44
28
90
0.638161
4.954442
false
false
false
false
kylebshr/zerostore-ios
ZeroStore/PasswordManager.swift
1
1916
// // PasswordManager.swift // ZeroStore // // Created by Kyle Bashour on 9/3/15. // Copyright (c) 2015 Kyle Bashour. All rights reserved. // import Foundation import NAChloride class PasswordManager { // MARK: Properties static let sharedInstance = PasswordManager() // MARK: Lifecycle init() { // Call this because the extension can be used before the app is launched PasswordManager.setInitialDefaultLength() } func generatePassword(masterPassword: String, userID: String, length: Int, completion: (String -> ())?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let salt = ("zerostore-salt" + userID as NSString).dataUsingEncoding(NSUTF8StringEncoding)! let password = (masterPassword as NSString).dataUsingEncoding(NSUTF8StringEncoding)! let data = try! NAScrypt.scrypt(password, salt: salt, n: 16384, r: 8, p: 1, length: 64) let digest = userID.hmac(CryptoAlgorithm.SHA256, key: data) let range = Range<String.Index>(start: digest.startIndex, end: digest.startIndex.advancedBy(length )) // DEBUG // print("password used: \(masterPassword)") // print("userID user: \(userID)") // print("password generated: \(digest.substringWithRange(range))") completion?(digest.substringWithRange(range)) } } // Set the password length in the defaults if there isn't one set class func setInitialDefaultLength() { guard let defaults = NSUserDefaults(suiteName: Constants.Defaults.suiteName) where !defaults.boolForKey(Constants.Defaults.opened) else { return } defaults.setBool(true, forKey: Constants.Defaults.opened) defaults.setInteger(24, forKey: Constants.Defaults.length) defaults.synchronize() } }
mit
548f5ac5430eac610ddfe4354146c54d
30.409836
113
0.652923
4.518868
false
false
false
false
SwiftKitz/Storez
Sources/Storez/Stores/Cache/CacheConvertible+Swift.swift
1
1644
// // CacheConvertible+Swift.swift // Storez // // Created by Mazyad Alabduljaleel on 12/9/15. // Copyright © 2015 mazy. All rights reserved. // import Foundation /** Adding support to Swift types */ extension Int: CacheConvertible { public typealias CacheType = AnyObject public static func decode(cacheValue value: CacheType) -> Int? { return value as? Int } public var encodeForCache: CacheType? { return self as AnyObject } } extension Double: CacheConvertible { public typealias CacheType = AnyObject public static func decode(cacheValue value: CacheType) -> Double? { return value as? Double } public var encodeForCache: CacheType? { return self as AnyObject } } extension Bool: CacheConvertible { public typealias CacheType = AnyObject public static func decode(cacheValue value: CacheType) -> Bool? { return value as? Bool } public var encodeForCache: CacheType? { return self as AnyObject } } extension Float: CacheConvertible { public typealias CacheType = AnyObject public static func decode(cacheValue value: CacheType) -> Float? { return value as? Float } public var encodeForCache: CacheType? { return self as AnyObject } } extension String: CacheConvertible { public typealias CacheType = AnyObject public static func decode(cacheValue value: CacheType) -> String? { return value as? String } public var encodeForCache: CacheType? { return self as AnyObject } }
mit
a6bed9c7df113f585316b3a40046b7a2
20.337662
71
0.647596
4.73487
false
false
false
false
seungprk/PenguinJump
Archive/PenguinJumpDavidTest/PenguinJump/GameScene.swift
1
2729
// // GameScene.swift // PenguinJump // // Created by Seung Park on 5/7/16. // Copyright (c) 2016 DeAnza. All rights reserved. // import SpriteKit class GameScene: SKScene { let player = SKSpriteNode(imageNamed:"Spaceship") let myLabel = SKLabelNode(fontNamed:"Chalkduster") override func didMoveToView(view: SKView) { /* Setup your scene here */ backgroundColor = SKColor.blackColor() player.position = CGPoint(x: size.width * 0.5, y: size.height * 0.1 ); player.xScale = 0.1 player.yScale = 0.1 player.zPosition = 100.0 myLabel.text = "Start!"; myLabel.fontSize = 45; myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); self.addChild(player) self.addChild(myLabel) runAction(SKAction.repeatActionForever(SKAction.sequence([ SKAction.runBlock(addPlatform), SKAction.waitForDuration(1.0) ]) )) print("trying") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ for touch in touches { let location = touch.locationInNode(self) let sprite = SKSpriteNode(imageNamed:"Spaceship") sprite.xScale = 0.5 sprite.yScale = 0.5 sprite.position = location let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1) sprite.runAction(SKAction.repeatActionForever(action)) self.addChild(sprite) } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } func addPlatform() { let platform = SKSpriteNode(imageNamed: "Spaceship") let actualX = random(min: platform.size.width, max: size.width - platform.size.width) platform.position = CGPoint(x: actualX, y: size.height + platform.size.height/2) addChild(platform) let actualDuration = 3.0//random(min: CGFloat(2.0), max: CGFloat(4.0)) let actionMove = SKAction.moveTo(CGPoint(x: actualX, y: -platform.size.height/2), duration: NSTimeInterval(actualDuration)) let actionMoveDone = SKAction.removeFromParent() platform.runAction(SKAction.sequence([actionMove, actionMoveDone])) } func random() -> CGFloat { return CGFloat(Float(arc4random()) / 0xFFFFFFFF) } func random(min min: CGFloat, max: CGFloat) -> CGFloat { return random() * (max - min) + min } }
bsd-2-clause
07f63174261e252e3df76eb8fbf4c99a
30.011364
131
0.589227
4.578859
false
false
false
false
stripe/stripe-ios
Stripe/STPEphemeralKey.swift
1
3233
// // STPEphemeralKey.swift // StripeiOS // // Created by Ben Guo on 5/4/17. // Copyright © 2017 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripePayments class STPEphemeralKey: NSObject, STPAPIResponseDecodable { private(set) var stripeID: String private(set) var created: Date private(set) var livemode = false private(set) var secret: String private(set) var expires: Date private(set) var customerID: String? private(set) var issuingCardID: String? /// You cannot directly instantiate an `STPEphemeralKey`. You should instead use /// `decodedObjectFromAPIResponse:` to create a key from a JSON response. required init( stripeID: String, created: Date, secret: String, expires: Date ) { self.stripeID = stripeID self.created = created self.secret = secret self.expires = expires super.init() } private(set) var allResponseFields: [AnyHashable: Any] = [:] class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? { guard let response = response else { return nil } let dict = response.stp_dictionaryByRemovingNulls() // required fields guard let stripeId = dict.stp_string(forKey: "id"), let created = dict.stp_date(forKey: "created"), let secret = dict.stp_string(forKey: "secret"), let expires = dict.stp_date(forKey: "expires"), let associatedObjects = dict.stp_array(forKey: "associated_objects"), dict["livemode"] != nil else { return nil } var customerID: String? var issuingCardID: String? for obj in associatedObjects { if let obj = obj as? [AnyHashable: Any] { let type = obj.stp_string(forKey: "type") if type == "customer" { customerID = obj.stp_string(forKey: "id") } if type == "issuing.card" { issuingCardID = obj.stp_string(forKey: "id") } } } if customerID == nil && issuingCardID == nil { return nil } let key = self.init(stripeID: stripeId, created: created, secret: secret, expires: expires) key.customerID = customerID key.issuingCardID = issuingCardID key.stripeID = stripeId key.livemode = dict.stp_bool(forKey: "livemode", or: true) key.created = created key.secret = secret key.expires = expires key.allResponseFields = response return key } override var hash: Int { return stripeID.hash } override func isEqual(_ object: Any?) -> Bool { if self === (object as? STPEphemeralKey) { return true } if object == nil || !(object is STPEphemeralKey) { return false } if let object = object as? STPEphemeralKey { return isEqual(to: object) } return false } func isEqual(to other: STPEphemeralKey) -> Bool { return stripeID == other.stripeID } }
mit
ae34af89589a4edff24d98cacd50f12e
30.076923
99
0.575804
4.303595
false
false
false
false
nab0y4enko/PrettyExtensionsKit
Sources/UIKit/UIAlertController+PrettyExtensionsKit.swift
1
1106
// // UIAlertController+PrettyExtensionsKit.swift // PrettyExtensionsKit // // Created by Oleksii Naboichenko on 1/3/17. // Copyright © 2017 Oleksii Naboichenko. All rights reserved. // import UIKit public extension UIAlertController { // MARK: - Private Properties static var defaultAlertTitle: String { let bundleName = Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String return bundleName ?? "Ooops!" } // MARK: - Initializers convenience init(alertTitle title: String? = defaultAlertTitle, error: Error?) { self.init(title: title, message: error?.localizedDescription, preferredStyle: .alert) } convenience init(alertTitle title: String? = defaultAlertTitle, message: String?) { self.init(title: title, message: message, preferredStyle: .alert) } // MARK: - Public Instance Methods func addAcceptAction(withTitle title: String = "OK") { let acceptAction = UIAlertAction( title: title, style: .default ) addAction(acceptAction) } }
mit
d08aeb4a7b891c1dcbcf6d8fa9f525d6
28.864865
93
0.659729
4.547325
false
false
false
false
EstefaniaGilVaquero/ciceIOS
App_VolksWagenFinal-/App_VolksWagenFinal-/VWCatalogoPruebasModel.swift
1
829
// // VWCatalogoPruebasModel.swift // App_VolksWagenFinal_CICE // // Created by Formador on 6/10/16. // Copyright © 2016 icologic. All rights reserved. // import UIKit class VWCatalogoPruebasModel: NSObject { var idCatalogo : Int? var NombreModelo : String? var Cilindrada : Float? var KW : Float? var HP : Float? var Combustible : String? var Imagen : String? init(pIdCatalogo : Int, pNombreModelo : String, pCilindrada : Float, pKW : Float, pHP : Float, pCombustible : String, pImagen : String) { self.idCatalogo = pIdCatalogo self.NombreModelo = pNombreModelo self.Cilindrada = pCilindrada self.KW = pKW self.HP = pHP self.Combustible = pCombustible self.Imagen = pImagen super.init() } }
apache-2.0
f87af7ee24bcbd4a044c038d933f1770
22.657143
141
0.624396
3.124528
false
false
false
false
peiei/PJPhototLibrary
JPhotoLibrary/Class/UIKitExtension.swift
1
2797
// // UIKitExtension.swift // JPhotoLibrary // // Created by AidenLance on 2017/3/6. // Copyright © 2017年 AidenLance. All rights reserved. // import Foundation import UIKit import Photos //MARK: calling and callback public extension UIViewController { public func showPJPhotoAlbum() { PJPhotoAlbum.authorizedAction(parentVC: self) } } extension UIImage { /// cropRect 移动坐标并裁剪图片 默认nil target 裁剪的大小 func cropImage(cropRect:CGRect? = nil, targetSize: CGSize) -> UIImage? { UIGraphicsBeginImageContextWithOptions(targetSize, false, UIScreen.main.scale) if cropRect != nil { guard let newCGImage = self.cgImage?.cropping(to: cropRect!) else { return nil } let newImage = UIImage.init(cgImage: newCGImage) newImage.draw(in: CGRect.init(origin: CGPoint.zero, size: targetSize)) } else { self.draw(in: CGRect.init(origin: CGPoint.zero, size: targetSize)) } defer { UIGraphicsEndImageContext() } return UIGraphicsGetImageFromCurrentImageContext() } func calculateSize() -> CGSize { switch self.imageOrientation { case .up: return CGSize.init(width: ConstantValue.screenWidth, height: self.size.height*ConstantValue.screenWidth/self.size.width) default: return CGSize.zero } } } extension UIImageView { } extension UIColor { class var btTitleSelectColor: UIColor { return UIColor.init(red: 58/255, green: 187/255, blue: 4/255, alpha: 1) } class var btTitleDisableColor: UIColor { return UIColor.init(red: 180/255, green: 227/255, blue: 185/255, alpha: 1) } class var navViewBackgroundColor: UIColor { return UIColor.init(white: 0.1, alpha: 0.7) } } func imageResize(image: UIImage, size: CGSize) -> UIImage? { let pixelHeight = image.size.height let pixelWidth = image.size.width let newImage: UIImage? if pixelHeight > pixelWidth { newImage = image.cropImage(cropRect: CGRect.init(x: 0, y: (pixelHeight - pixelWidth)/2, width: pixelWidth, height: pixelWidth), targetSize: size) }else { newImage = image.cropImage(cropRect: CGRect.init(x: (pixelWidth - pixelHeight)/2, y: 0, width: pixelHeight, height: pixelHeight), targetSize: size) } return newImage } ///MARK: origin button icon and title separately class OriginBt : UIButton { override func titleRect(forContentRect contentRect: CGRect) -> CGRect { return CGRect.init(x: 20, y: 2, width: 35, height: 40) } override func imageRect(forContentRect contentRect: CGRect) -> CGRect { return CGRect.init(x: 5, y: 14, width: 15, height: 15) } }
mit
dfb06af8043eed259dca25b187552ded
30.033708
155
0.655684
4.104012
false
false
false
false
petester42/SwiftCharts
Examples/Examples/Examples/CandleStickInteractiveExample.swift
4
15260
// // CandleStickInteractiveExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit class CandleStickInteractiveExample: UIViewController { private var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) var readFormatter = NSDateFormatter() readFormatter.dateFormat = "dd.MM.yyyy" var displayFormatter = NSDateFormatter() displayFormatter.dateFormat = "MMM dd" let date = {(str: String) -> NSDate in return readFormatter.dateFromString(str)! } let calendar = NSCalendar.currentCalendar() let dateWithComponents = {(day: Int, month: Int, year: Int) -> NSDate in let components = NSDateComponents() components.day = day components.month = month components.year = year return calendar.dateFromComponents(components)! } func filler(date: NSDate) -> ChartAxisValueDate { let filler = ChartAxisValueDate(date: date, formatter: displayFormatter) filler.hidden = true return filler } let chartPoints = [ ChartPointCandleStick(date: date("01.10.2015"), formatter: displayFormatter, high: 40, low: 37, open: 39.5, close: 39), ChartPointCandleStick(date: date("02.10.2015"), formatter: displayFormatter, high: 39.8, low: 38, open: 39.5, close: 38.4), ChartPointCandleStick(date: date("03.10.2015"), formatter: displayFormatter, high: 43, low: 39, open: 41.5, close: 42.5), ChartPointCandleStick(date: date("04.10.2015"), formatter: displayFormatter, high: 48, low: 42, open: 44.6, close: 44.5), ChartPointCandleStick(date: date("05.10.2015"), formatter: displayFormatter, high: 45, low: 41.6, open: 43, close: 44), ChartPointCandleStick(date: date("06.10.2015"), formatter: displayFormatter, high: 46, low: 42.6, open: 44, close: 46), ChartPointCandleStick(date: date("07.10.2015"), formatter: displayFormatter, high: 47.5, low: 41, open: 42, close: 45.5), ChartPointCandleStick(date: date("08.10.2015"), formatter: displayFormatter, high: 50, low: 46, open: 46, close: 49), ChartPointCandleStick(date: date("09.10.2015"), formatter: displayFormatter, high: 45, low: 41, open: 44, close: 43.5), ChartPointCandleStick(date: date("11.10.2015"), formatter: displayFormatter, high: 47, low: 35, open: 45, close: 39), ChartPointCandleStick(date: date("12.10.2015"), formatter: displayFormatter, high: 45, low: 33, open: 44, close: 40), ChartPointCandleStick(date: date("13.10.2015"), formatter: displayFormatter, high: 43, low: 36, open: 41, close: 38), ChartPointCandleStick(date: date("14.10.2015"), formatter: displayFormatter, high: 42, low: 31, open: 38, close: 39), ChartPointCandleStick(date: date("15.10.2015"), formatter: displayFormatter, high: 39, low: 34, open: 37, close: 36), ChartPointCandleStick(date: date("16.10.2015"), formatter: displayFormatter, high: 35, low: 32, open: 34, close: 33.5), ChartPointCandleStick(date: date("17.10.2015"), formatter: displayFormatter, high: 32, low: 29, open: 31.5, close: 31), ChartPointCandleStick(date: date("18.10.2015"), formatter: displayFormatter, high: 31, low: 29.5, open: 29.5, close: 30), ChartPointCandleStick(date: date("19.10.2015"), formatter: displayFormatter, high: 29, low: 25, open: 25.5, close: 25), ChartPointCandleStick(date: date("20.10.2015"), formatter: displayFormatter, high: 28, low: 24, open: 26.7, close: 27.5), ChartPointCandleStick(date: date("21.10.2015"), formatter: displayFormatter, high: 28.5, low: 25.3, open: 26, close: 27), ChartPointCandleStick(date: date("22.10.2015"), formatter: displayFormatter, high: 30, low: 28, open: 28, close: 30), ChartPointCandleStick(date: date("25.10.2015"), formatter: displayFormatter, high: 31, low: 29, open: 31, close: 31), ChartPointCandleStick(date: date("26.10.2015"), formatter: displayFormatter, high: 31.5, low: 29.2, open: 29.6, close: 29.6), ChartPointCandleStick(date: date("27.10.2015"), formatter: displayFormatter, high: 30, low: 27, open: 29, close: 28.5), ChartPointCandleStick(date: date("28.10.2015"), formatter: displayFormatter, high: 32, low: 30, open: 31, close: 30.6), ChartPointCandleStick(date: date("29.10.2015"), formatter: displayFormatter, high: 35, low: 31, open: 31, close: 33) ] func generateDateAxisValues(month: Int, year: Int) -> [ChartAxisValueDate] { let date = dateWithComponents(1, month, year) let calendar = NSCalendar.currentCalendar() let monthDays = calendar.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date) return Array(monthDays.toRange()!).map {day in let date = dateWithComponents(day, month, year) let axisValue = ChartAxisValueDate(date: date, formatter: displayFormatter, labelSettings: labelSettings) axisValue.hidden = !(day % 5 == 0) return axisValue } } let xValues = generateDateAxisValues(10, 2015) let yValues = Array(stride(from: 20, through: 55, by: 5)).map {ChartAxisValueFloat($0, labelSettings: labelSettings)} let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let defaultChartFrame = ExamplesDefaults.chartFrame(self.view.bounds) let infoViewHeight: CGFloat = 50 let chartFrame = CGRectMake(defaultChartFrame.origin.x, defaultChartFrame.origin.y + infoViewHeight, defaultChartFrame.width, defaultChartFrame.height - infoViewHeight) let coordsSpace = ChartCoordsSpaceRightBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let viewGenerator = {(chartPointModel: ChartPointLayerModel<ChartPointCandleStick>, layer: ChartPointsViewsLayer<ChartPointCandleStick, ChartCandleStickView>, chart: Chart) -> ChartCandleStickView? in let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc) let x = screenLoc.x let width = 10 let highScreenY = screenLoc.y let lowScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.low)).y let openScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.open)).y let closeScreenY = layer.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.close)).y let (rectTop, rectBottom, fillColor) = closeScreenY < openScreenY ? (closeScreenY, openScreenY, UIColor.whiteColor()) : (openScreenY, closeScreenY, UIColor.blackColor()) let v = ChartCandleStickView(lineX: screenLoc.x, width: Env.iPad ? 10 : 5, top: highScreenY, bottom: lowScreenY, innerRectTop: rectTop, innerRectBottom: rectBottom, fillColor: fillColor, strokeWidth: Env.iPad ? 1 : 0.5) v.userInteractionEnabled = false return v } let candleStickLayer = ChartPointsCandleStickViewsLayer<ChartPointCandleStick, ChartCandleStickView>(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: viewGenerator) let infoView = InfoWithIntroView(frame: CGRectMake(10, 70, self.view.frame.size.width, infoViewHeight)) self.view.addSubview(infoView) let trackerLayer = ChartPointsTrackerLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, locChangedFunc: {[weak candleStickLayer, weak infoView] screenLoc in candleStickLayer?.highlightChartpointView(screenLoc: screenLoc) if let chartPoint = candleStickLayer?.chartPointsForScreenLocX(screenLoc.x).first { infoView?.showChartPoint(chartPoint) } else { infoView?.clear() } }, lineColor: UIColor.redColor(), lineWidth: Env.iPad ? 1 : 0.6) let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, onlyVisibleX: true) let dividersSettings = ChartDividersLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth, start: Env.iPad ? 7 : 3, end: 0, onlyVisibleValues: true) let dividersLayer = ChartDividersLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: dividersSettings) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, dividersLayer, candleStickLayer, trackerLayer ] ) self.view.addSubview(chart.view) self.chart = chart } } private class InfoView: UIView { let statusView: UIView let dateLabel: UILabel let lowTextLabel: UILabel let highTextLabel: UILabel let openTextLabel: UILabel let closeTextLabel: UILabel let lowLabel: UILabel let highLabel: UILabel let openLabel: UILabel let closeLabel: UILabel override init(frame: CGRect) { let itemHeight: CGFloat = 40 let y = (frame.height - itemHeight) / CGFloat(2) self.statusView = UIView(frame: CGRectMake(0, y, itemHeight, itemHeight)) self.statusView.layer.borderColor = UIColor.blackColor().CGColor self.statusView.layer.borderWidth = 1 self.statusView.layer.cornerRadius = Env.iPad ? 13 : 8 let font = ExamplesDefaults.labelFont self.dateLabel = UILabel() self.dateLabel.font = font self.lowTextLabel = UILabel() self.lowTextLabel.text = "Low:" self.lowTextLabel.font = font self.lowLabel = UILabel() self.lowLabel.font = font self.highTextLabel = UILabel() self.highTextLabel.text = "High:" self.highTextLabel.font = font self.highLabel = UILabel() self.highLabel.font = font self.openTextLabel = UILabel() self.openTextLabel.text = "Open:" self.openTextLabel.font = font self.openLabel = UILabel() self.openLabel.font = font self.closeTextLabel = UILabel() self.closeTextLabel.text = "Close:" self.closeTextLabel.font = font self.closeLabel = UILabel() self.closeLabel.font = font super.init(frame: frame) self.addSubview(self.statusView) self.addSubview(self.dateLabel) self.addSubview(self.lowTextLabel) self.addSubview(self.lowLabel) self.addSubview(self.highTextLabel) self.addSubview(self.highLabel) self.addSubview(self.openTextLabel) self.addSubview(self.openLabel) self.addSubview(self.closeTextLabel) self.addSubview(self.closeLabel) } private override func didMoveToSuperview() { let views = [self.statusView, self.dateLabel, self.highTextLabel, self.highLabel, self.lowTextLabel, self.lowLabel, self.openTextLabel, self.openLabel, self.closeTextLabel, self.closeLabel] for v in views { v.setTranslatesAutoresizingMaskIntoConstraints(false) } let namedViews = Array(enumerate(views)).map{index, view in ("v\(index)", view) } let viewsDict = namedViews.reduce(Dictionary<String, UIView>()) {(var u, tuple) in u[tuple.0] = tuple.1 return u } let circleDiameter: CGFloat = Env.iPad ? 26 : 15 let labelsSpace: CGFloat = Env.iPad ? 10 : 5 let hConstraintStr = namedViews[1..<namedViews.count].reduce("H:|[v0(\(circleDiameter))]") {str, tuple in "\(str)-(\(labelsSpace))-[\(tuple.0)]" } let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraintsWithVisualFormat("V:|-(18)-[\($0.0)(\(circleDiameter))]", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: viewsDict)} self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(hConstraintStr, options: NSLayoutFormatOptions.allZeros, metrics: nil, views: viewsDict) + vConstraits) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func showChartPoint(chartPoint: ChartPointCandleStick) { let color = chartPoint.open > chartPoint.close ? UIColor.blackColor() : UIColor.whiteColor() self.statusView.backgroundColor = color self.dateLabel.text = chartPoint.x.labels.first?.text ?? "" self.lowLabel.text = "\(chartPoint.low)" self.highLabel.text = "\(chartPoint.high)" self.openLabel.text = "\(chartPoint.open)" self.closeLabel.text = "\(chartPoint.close)" } func clear() { self.statusView.backgroundColor = UIColor.clearColor() } } private class InfoWithIntroView: UIView { var introView: UIView! var infoView: InfoView! override init(frame: CGRect) { super.init(frame: frame) } private override func didMoveToSuperview() { let label = UILabel(frame: CGRectMake(0, self.bounds.origin.y, self.bounds.width, self.bounds.height)) label.text = "Drag the line to see chartpoint data" label.font = ExamplesDefaults.labelFont label.backgroundColor = UIColor.whiteColor() self.introView = label self.infoView = InfoView(frame: self.bounds) self.addSubview(self.infoView) self.addSubview(self.introView) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func animateIntroAlpha(alpha: CGFloat) { UIView.animateWithDuration(0.1, animations: { self.introView.alpha = alpha }) } func showChartPoint(chartPoint: ChartPointCandleStick) { self.animateIntroAlpha(0) self.infoView.showChartPoint(chartPoint) } func clear() { self.animateIntroAlpha(1) self.infoView.clear() } }
apache-2.0
a987b73a4800f7b13d770dbdfd5cc499
47.294304
231
0.642726
4.506793
false
false
false
false
tbkka/swift-protobuf
Sources/SwiftProtobuf/Message+JSONAdditions.swift
3
5648
// Sources/SwiftProtobuf/Message+JSONAdditions.swift - JSON format primitive types // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Extensions to `Message` to support JSON encoding/decoding. /// // ----------------------------------------------------------------------------- import Foundation /// JSON encoding and decoding methods for messages. extension Message { /// Returns a string containing the JSON serialization of the message. /// /// Unlike binary encoding, presence of required fields is not enforced when /// serializing to JSON. /// /// - Returns: A string containing the JSON serialization of the message. /// - Parameters: /// - options: The JSONEncodingOptions to use. /// - Throws: `JSONEncodingError` if encoding fails. public func jsonString( options: JSONEncodingOptions = JSONEncodingOptions() ) throws -> String { if let m = self as? _CustomJSONCodable { return try m.encodedJSONString(options: options) } let data = try jsonUTF8Data(options: options) return String(data: data, encoding: String.Encoding.utf8)! } /// Returns a Data containing the UTF-8 JSON serialization of the message. /// /// Unlike binary encoding, presence of required fields is not enforced when /// serializing to JSON. /// /// - Returns: A Data containing the JSON serialization of the message. /// - Parameters: /// - options: The JSONEncodingOptions to use. /// - Throws: `JSONEncodingError` if encoding fails. public func jsonUTF8Data( options: JSONEncodingOptions = JSONEncodingOptions() ) throws -> Data { if let m = self as? _CustomJSONCodable { let string = try m.encodedJSONString(options: options) let data = string.data(using: String.Encoding.utf8)! // Cannot fail! return data } var visitor = try JSONEncodingVisitor(type: Self.self, options: options) visitor.startObject(message: self) try traverse(visitor: &visitor) visitor.endObject() return visitor.dataResult } /// Creates a new message by decoding the given string containing a /// serialized message in JSON format. /// /// - Parameter jsonString: The JSON-formatted string to decode. /// - Parameter options: The JSONDecodingOptions to use. /// - Throws: `JSONDecodingError` if decoding fails. public init( jsonString: String, options: JSONDecodingOptions = JSONDecodingOptions() ) throws { try self.init(jsonString: jsonString, extensions: nil, options: options) } /// Creates a new message by decoding the given string containing a /// serialized message in JSON format. /// /// - Parameter jsonString: The JSON-formatted string to decode. /// - Parameter extensions: An ExtensionMap for looking up extensions by name /// - Parameter options: The JSONDecodingOptions to use. /// - Throws: `JSONDecodingError` if decoding fails. public init( jsonString: String, extensions: ExtensionMap? = nil, options: JSONDecodingOptions = JSONDecodingOptions() ) throws { if jsonString.isEmpty { throw JSONDecodingError.truncated } if let data = jsonString.data(using: String.Encoding.utf8) { try self.init(jsonUTF8Data: data, extensions: extensions, options: options) } else { throw JSONDecodingError.truncated } } /// Creates a new message by decoding the given `Data` containing a /// serialized message in JSON format, interpreting the data as UTF-8 encoded /// text. /// /// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented /// as UTF-8 encoded text. /// - Parameter options: The JSONDecodingOptions to use. /// - Throws: `JSONDecodingError` if decoding fails. public init( jsonUTF8Data: Data, options: JSONDecodingOptions = JSONDecodingOptions() ) throws { try self.init(jsonUTF8Data: jsonUTF8Data, extensions: nil, options: options) } /// Creates a new message by decoding the given `Data` containing a /// serialized message in JSON format, interpreting the data as UTF-8 encoded /// text. /// /// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented /// as UTF-8 encoded text. /// - Parameter extensions: The extension map to use with this decode /// - Parameter options: The JSONDecodingOptions to use. /// - Throws: `JSONDecodingError` if decoding fails. public init( jsonUTF8Data: Data, extensions: ExtensionMap? = nil, options: JSONDecodingOptions = JSONDecodingOptions() ) throws { self.init() try jsonUTF8Data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in // Empty input is valid for binary, but not for JSON. guard body.count > 0 else { throw JSONDecodingError.truncated } var decoder = JSONDecoder(source: body, options: options, messageType: Self.self, extensions: extensions) if decoder.scanner.skipOptionalNull() { if let customCodable = Self.self as? _CustomJSONCodable.Type, let message = try customCodable.decodedFromJSONNull() { self = message as! Self } else { throw JSONDecodingError.illegalNull } } else { try decoder.decodeFullObject(message: &self) } if !decoder.scanner.complete { throw JSONDecodingError.trailingGarbage } } } }
apache-2.0
92837fbc202fa2458a5cd7b141a9c802
36.653333
82
0.670857
4.746218
false
false
false
false
sumitjain7/AppleTouchId
Example/appleTouchId/ViewController.swift
1
2528
// // ViewController.swift // appleTouchId // // Created by SumitJain on 08/28/2017. // Copyright (c) 2017 SumitJain. All rights reserved. // import UIKit import appleTouchId import LocalAuthentication class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func authenticate(_ sender: Any) { AppleAuthenticator.sharedInstance.authenticateWithSuccess({ [unowned self](Void) in self.presentAlertControllerWithMessage("Successfully Authenticated!") }) { (errorCode) in var authErrorString : NSString switch (errorCode) { case LAError.systemCancel.rawValue: authErrorString = "System canceled auth request due to app coming to foreground or background."; break; case LAError.authenticationFailed.rawValue: authErrorString = "User failed after a few attempts."; break; case LAError.userCancel.rawValue: authErrorString = "User cancelled."; break; case LAError.userFallback.rawValue: authErrorString = "Fallback auth method should be implemented here."; break; case LAError.touchIDNotEnrolled.rawValue: authErrorString = "No Touch ID fingers enrolled."; break; case LAError.touchIDNotAvailable.rawValue: authErrorString = "Touch ID not available on your device."; break; case LAError.passcodeNotSet.rawValue: authErrorString = "Need a passcode set to use Touch ID."; break; default: authErrorString = "Check your Touch ID Settings."; break; } self.presentAlertControllerWithMessage(authErrorString) } } func presentAlertControllerWithMessage(_ message : NSString) { let alertController = UIAlertController(title:"Touch ID", message:message as String, preferredStyle:.alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } }
mit
3a5aac3233add220331280cd0ac6efd9
36.176471
115
0.620649
5.580574
false
false
false
false
melling/ios_topics
GameClock/GameClock/AppDelegate.swift
1
4596
// // AppDelegate.swift // GameClock // // Created by Michael Mellinger on 11/24/17. // Copyright © 2017 h4labs. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "GameClock") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
cc0-1.0
dfc723893858bed0fd3d6ff7a0d2574a
48.408602
285
0.685963
5.831218
false
false
false
false
zisko/swift
benchmark/utils/TestsUtils.swift
1
6926
//===--- TestsUtils.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if os(Linux) import Glibc #else import Darwin #endif public enum BenchmarkCategory : String { // Validation "micro" benchmarks test a specific operation or critical path that // we know is important to measure. case validation // subsystems to validate and their subcategories. case api, Array, String, Dictionary, Codable, Set case sdk case runtime, refcount, metadata // Other general areas of compiled code validation. case abstraction, safetychecks, exceptions, bridging, concurrency // Algorithms are "micro" that test some well-known algorithm in isolation: // sorting, searching, hashing, fibonaci, crypto, etc. case algorithm // Miniapplications are contrived to mimic some subset of application behavior // in a way that can be easily measured. They are larger than micro-benchmarks, // combining multiple APIs, data structures, or algorithms. This includes small // standardized benchmarks, pieces of real applications that have been extracted // into a benchmark, important functionality like JSON parsing, etc. case miniapplication // Regression benchmarks is a catch-all for less important "micro" // benchmarks. This could be a random piece of code that was attached to a bug // report. We want to make sure the optimizer as a whole continues to handle // this case, but don't know how applicable it is to general Swift performance // relative to the other micro-benchmarks. In particular, these aren't weighted // as highly as "validation" benchmarks and likely won't be the subject of // future investigation unless they significantly regress. case regression // Most benchmarks are assumed to be "stable" and will be regularly tracked at // each commit. A handful may be marked unstable if continually tracking them is // counterproductive. case unstable // CPU benchmarks represent instrinsic Swift performance. They are useful for // measuring a fully baked Swift implementation across different platforms and // hardware. The benchmark should also be reasonably applicable to real Swift // code--it should exercise a known performance critical area. Typically these // will be drawn from the validation benchmarks once the language and standard // library implementation of the benchmark meets a reasonable efficiency // baseline. A benchmark should only be tagged "cpubench" after a full // performance investigation of the benchmark has been completed to determine // that it is a good representation of future Swift performance. Benchmarks // should not be tagged if they make use of an API that we plan on // reimplementing or call into code paths that have known opportunities for // significant optimization. case cpubench // Explicit skip marker case skip } public struct BenchmarkInfo { /// The name of the benchmark that should be displayed by the harness. public var name: String /// A function that invokes the specific benchmark routine. public var runFunction: (Int) -> () /// A set of category tags that describe this benchmark. This is used by the /// harness to allow for easy slicing of the set of benchmarks along tag /// boundaries, e.x.: run all string benchmarks or ref count benchmarks, etc. public var tags: [BenchmarkCategory] /// An optional function that if non-null is run before benchmark samples /// are timed. public var setUpFunction: (() -> ())? /// An optional function that if non-null is run immediately after a sample is /// taken. public var tearDownFunction: (() -> ())? public init(name: String, runFunction: @escaping (Int) -> (), tags: [BenchmarkCategory], setUpFunction: (() -> ())? = nil, tearDownFunction: (() -> ())? = nil) { self.name = name self.runFunction = runFunction self.tags = tags self.setUpFunction = setUpFunction self.tearDownFunction = tearDownFunction } } extension BenchmarkInfo : Comparable { public static func < (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name < rhs.name } public static func == (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name == rhs.name } } extension BenchmarkInfo : Hashable { public var hashValue: Int { return name.hashValue } } // Linear function shift register. // // This is just to drive benchmarks. I don't make any claim about its // strength. According to Wikipedia, it has the maximal period for a // 32-bit register. struct LFSR { // Set the register to some seed that I pulled out of a hat. var lfsr : UInt32 = 0xb78978e7 mutating func shift() { lfsr = (lfsr >> 1) ^ (UInt32(bitPattern: -Int32((lfsr & 1))) & 0xD0000001) } mutating func randInt() -> Int64 { var result : UInt32 = 0 for _ in 0..<32 { result = (result << 1) | (lfsr & 1) shift() } return Int64(bitPattern: UInt64(result)) } } var lfsrRandomGenerator = LFSR() // Start the generator from the beginning public func SRand() { lfsrRandomGenerator = LFSR() } public func Random() -> Int64 { return lfsrRandomGenerator.randInt() } @inline(__always) public func CheckResults( _ resultsMatch: Bool, file: StaticString = #file, function: StaticString = #function, line: Int = #line ) { guard _fastPath(resultsMatch) else { print("Incorrect result in \(function), \(file):\(line)") abort() } } public func False() -> Bool { return false } /// This is a dummy protocol to test the speed of our protocol dispatch. public protocol SomeProtocol { func getValue() -> Int } struct MyStruct : SomeProtocol { init() {} func getValue() -> Int { return 1 } } public func someProtocolFactory() -> SomeProtocol { return MyStruct() } // Just consume the argument. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func blackHole<T>(_ x: T) { } // Return the passed argument without letting the optimizer know that. @inline(never) public func identity<T>(_ x: T) -> T { return x } // Return the passed argument without letting the optimizer know that. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func getInt(_ x: Int) -> Int { return x } // The same for String. @inline(never) public func getString(_ s: String) -> String { return s }
apache-2.0
73e1f08ad93c356a7adb6b86cc003b86
34.336735
90
0.698094
4.462629
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0191.xcplaygroundpage/Contents.swift
1
6460
/*: # Eliminate `IndexDistance` from `Collection` * Proposal: [SE-0191](0191-eliminate-indexdistance.md) * Authors: [Ben Cohen](https://github.com/airspeedswift) * Review Manager: [Doug Gregor](https://github.com/DougGregor) * Status: **Implemented (Swift 4.1)** * Implementation: [apple/swift#12641](https://github.com/apple/swift/pull/12641) * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2017-December/000415.html) ## Introduction Eliminate the associated type `IndexDistance` from `Collection`, and modify all uses to the concrete type `Int` instead. ## Motivation `Collection` allows for the distance between two indices to be any `SignedInteger` type via the `IndexDistance` associated type. While in practice the distance between indices is almost always an `Int`, generic algorithms on `Collection` need to either constrain `IndexDistance == Int` or write their algorithm to be generic over any `SignedInteger`. Swift 4.0 introduced the ability to constrain associated types with `where` clauses ([SE-142](https://github.com/apple/swift-evolution/blob/master/proposals/0142-associated-types-constraints.md)) and will soon allow protocol constraints to be recursive ([SE-157](https://github.com/apple/swift-evolution/blob/master/proposals/0157-recursive-protocol-constraints.md)). With these features, writing generic algorithms against `Collection` is finally a realistic tool for intermediate Swift programmers. You no longer need to know to constrain `SubSequence.Element == Element` or `SubSequence: Collection`, missing constraints that previously led to inexplicable error messages. At this point, the presence of `IndexDistance` is of of the biggest hurdles that new users trying to write generic algorithms face. If you want to write code that will compile against any distance type, you need to constantly juggle with explicit type annotations (i.e. you need to write `let i: IndexDistance = 0` instead of just `let i = 0`), and perform `numericCast` to convert from one distance type to another. But these `numericCasts` are hard to use correctly. Given two collections with different index distances, it's very hard to reason about whether your `numericCast` is casting from the smaller to larger type correctly. This turns any problem of writing a generic collection algorithm into both a collection _and_ numeric problem. And chances are you are going to need to interoperate with a method that takes or provides a concrete `Int` anyway (like `Array.reserveCapacity` inside `Collection.map`). Much of the generic code in the standard library would trap if ever presented with a collection with a distance greater than `Int.max`. Additionally, this generalization makes specialization less likely and increases compile-time work. For these reasons, it's common to see algorithms constrained to `IndexDistance == Int`. In fact, the inconvenience of having to deal with generic index distances probably encourages more algorithms to be constrained to `Index == Int`, such as [this code](https://github.com/airspeedswift/swift-package-manager/blob/472c647dcad3adf4344a06ef7ba91d2d4abddc94/Sources/Basic/OutputByteStream.swift#L119) in the Swift Package Manager. Converting this function to work with any index type would be straightforward. Converting it to work with any index distance as well would be much trickier. The general advice from [The Swift Programming Language](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309) when writing Swift code is to encourage users to stick to using `Int` unless they have a special reason not to: > Unless you need to work with a specific size of integer, always use `Int` for integer values in your code. [...] `Int` is preferred, even when the values to be stored are known to be nonnegative. A consistent use of Int for integer values aids code interoperability, avoids the need to convert between different number types, and matches integer type inference[.] There are two main use cases for keeping `IndexDistance` as an associated type rather than concretizing it to be `Int`: tiny collections that might benefit from tiny distances, and huge collections that need to address greater than `Int.max` elements. For example, it may seem wasteful to force a type that presents the bits in a `UInt` as a collection to need to use a whole `Int` for its distance type. Or you may want to create a gigantic collection, such as one backed by a memory mapped file, with a size great than `Int.max`. The most likely scenario for this is on 32-bit processors where a collection would be constrained to 2 billion elements. These use cases are very niche, and do not seem to justify the considerable impedance to generic programming that `IndexDistance` causes. Therefore, this proposal recommends removing the associated type and replacing all references to it with `Int`. ## Proposed solution Scrap the `IndexDistance` associated type. Switch all references to it in the standard library to the concrete `Int` type: ```swift protocol Collection { var count: Int { get } func index(_ i: Index, offsetBy n: Int) -> Index func index(_ i: Index, offsetBy n: Int, limitedBy limit: Index) -> Index? func distance(from start: Index, to end: Index) -> Int } // and in numerous extensions in the standard library ``` The one instance where a concrete type uses an `IndexDistance` other than `Int` in the standard library is `AnyCollection`, which uses `Int64`. This would be changed to `Int`. ## Source compatibility This can be split into 2 parts: Algorithms that currently constrain `IndexDistance` to `Int` in their `where` clause, and algorithms that use `IndexDistance` within the body of a method, can be catered for by a deprecated typealias for `IndexDistance` inside an extension on `Collection`. This is the common case. Collections that truly take advantage of the ability to define non-`Int` distances would be source-broken, with no practical way of making this compatible in a 4.0 mode. It's worth noting that there are no such types in the Swift source compatibility suite. ## Effect on ABI stability This removes an associated type and changes function signatures, so must be done before declaring ABI stability ## Alternatives considered None other than status quo. ---------- [Previous](@previous) | [Next](@next) */
mit
b5cfbe1e0c2dfd4f6e7d1cacb024496f
67.723404
280
0.786223
4.266843
false
false
false
false
AlvinL33/TownHunt
TownHunt-1.9/TownHunt/PinPackCreatorInitViewController.swift
1
4059
// // MapPackCreatorInitViewController.swift // TownHunt // // Created by Alvin Lee on 23/02/2017. // Copyright © 2017 LeeTech. All rights reserved. // import UIKit class PinPackCreatorInitViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, ModalTransitionListener { @IBOutlet weak var menuOpenNavBarButton: UIBarButtonItem! @IBOutlet weak var packPicker: UIPickerView! @IBOutlet weak var selectButton: UIButton! private var pickerData: [String] = [String]() private var userPackDictName = "" private var selectedPickerData: String = "" private var userID = "" override func viewDidLoad() { super.viewDidLoad() ModalTransitionMediator.instance.setListener(listener: self) menuOpenNavBarButton.target = self.revealViewController() menuOpenNavBarButton.action = #selector(SWRevealViewController.revealToggle(_:)) UIGraphicsBeginImageContext(self.view.frame.size) UIImage(named: "createPackBackground")?.draw(in: self.view.bounds) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() self.view.backgroundColor = UIColor(patternImage: image) self.packPicker.delegate = self self.packPicker.dataSource = self setUpPicker() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func setUpPicker(){ let defaults = UserDefaults.standard userID = defaults.string(forKey: "UserID")! userPackDictName = "UserID-\(userID)-LocalPacks" if let dictOfPacksOnPhone = defaults.dictionary(forKey: userPackDictName) { self.pickerData = Array(dictOfPacksOnPhone.keys).sorted(by: <) self.selectedPickerData = pickerData[0] } else { self.pickerData = ["No Packs Found"] self.selectButton.isHidden = true } } // Number of columns of data func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } // Numbers of rows of data func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.pickerData.count } // The picker data to return for a certain row and column func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.pickerData[row] } // func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let textString = self.pickerData[row] return NSAttributedString(string: textString, attributes: [NSFontAttributeName:UIFont(name: "Futura" , size: 17.0)!, NSForegroundColorAttributeName: UIColor.white]) } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.selectedPickerData = pickerData[row] } func modalViewDismissed(){ self.navigationController?.dismiss(animated: true, completion: nil) self.packPicker.reloadAllComponents() self.setUpPicker() } @IBAction func selectButtonTapped(_ sender: Any) { } // Preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "PackSelectorToPackEditor"{ let navigationController = segue.destination as! UINavigationController let nextViewController = navigationController.topViewController as! PinPackEditorViewController print("Preparing to leave view, key is \(self.selectedPickerData)") nextViewController.selectedPackKey = self.selectedPickerData nextViewController.userPackDictName = self.userPackDictName nextViewController.userID = self.userID } } }
apache-2.0
88ce29289fabb89d32e19010ae7a6b33
36.229358
133
0.678413
5.29765
false
false
false
false
Nosrac/Dictater
Dictater/AppDelegate.swift
1
1217
// // AppDelegate.swift // Dictate Assist // // Created by Kyle Carson on 9/1/15. // Copyright © 2015 Kyle Carson. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { NSApp.servicesProvider = DictaterService() if !Dictater.hasBeenUsed { self.openHowToUseWindow() } let args = ProcessInfo.processInfo.arguments var skip = false for arg in args[ 1 ..< args.count ] { if skip { skip = false continue } if arg.hasPrefix("-") { skip = true continue } Speech.sharedSpeech.speak( text: arg ) break } } func applicationWillTerminate(aNotification: NSNotification) { Speech.sharedSpeech.pause() } var howToUseController : NSWindowController? func openHowToUseWindow() { if let sb = NSApplication.shared.windows.first?.windowController?.storyboard, let controller = sb.instantiateController(withIdentifier: "howToUse") as? NSWindowController { controller.showWindow(self) self.howToUseController = controller controller.window?.becomeKey() controller.window?.becomeMain() } } }
mit
4a1122eac0960a945dbcb2d13ab39937
18.612903
95
0.699836
3.764706
false
false
false
false
classmere/app
Classmere/Classmere/Service/DummyProvider.swift
1
1268
import Foundation enum DummyProviderError: Error { case fileDoesNotExist case jsonParsing } struct DummyProvider: Provider { fileprivate let decoder = JSONDecoder() init() { decoder.dateDecodingStrategy = .iso8601 } private func decode<T: Decodable>(_ type: T.Type, from: Data) -> Result<T> { do { let result = try self.decoder.decode(type, from: from) return .success(result) } catch { return .failure(error) } } internal func get<T: Decodable>(url: URL, responseType: T.Type, completion: @escaping Completion<T>) { let fileString = url.absoluteString .replacingOccurrences(of: API.baseURL.absoluteString, with: "") .dropFirst() .replacingOccurrences(of: "/", with: "-") guard let filePath = Bundle.main.path(forResource: fileString, ofType: "json") else { return completion(.failure(DummyProviderError.fileDoesNotExist)) } let fileURL = URL(fileURLWithPath: filePath) guard let json = try? Data(contentsOf: fileURL) else { return completion(.failure(DummyProviderError.jsonParsing)) } completion(self.decode(responseType, from: json)) } }
gpl-3.0
92d7c2033ab1097ea7b560c1db4134ac
30.7
106
0.625394
4.644689
false
false
false
false
smud/Smud
Sources/Smud/Controllers/DB+Accounts.swift
1
2990
// // DB+Accounts.swift // // This source file is part of the SMUD open source project // // Copyright (c) 2016 SMUD project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SMUD project authors // import Foundation import ConfigFile public extension DB { func loadAccounts() throws { var accountCount = 0 try enumerateFiles(atPath: smud.accountsDirectory) { filename, stop in print(" \(filename)") let directory = URL(fileURLWithPath: smud.accountsDirectory, isDirectory: true) let fullName = directory.appendingPathComponent(filename, isDirectory: false).relativePath let configFile = try ConfigFile(fromFile: fullName) let account = try Account(from: configFile, smud: smud) guard account.filename == filename else { throw DBError(kind: .inconsistentAccountFilename(actual: filename, generated: account.filename)) } addToIndexes(account: account) nextAccountId = max(account.accountId + 1, nextAccountId) accountCount += 1 } print(" \(accountCount) account(s), next id: \(nextAccountId)") } func saveAccounts(completion: (_ count: Int) throws->()) throws { var count = 0 if !modifiedAccounts.isEmpty { let directory = URL(fileURLWithPath: smud.accountsDirectory, isDirectory: true) try FileManager.default.createDirectory(atPath: directory.relativePath, withIntermediateDirectories: true, attributes: nil) for account in modifiedAccounts { let configFile = ConfigFile() account.save(to: configFile) let fullName = directory.appendingPathComponent(account.filename, isDirectory: false).relativePath try configFile.save(toFile: fullName, atomically: true) count += 1 } modifiedAccounts.removeAll(keepingCapacity: true) } try completion(count) } public func createAccountId() -> Int64 { defer { nextAccountId += 1 } return nextAccountId } public func account(id: Int64) -> Account? { return accountsById[id] } public func account(email: String) -> Account? { return accountsByLowercasedEmail[email.lowercased()] } public func addToIndexes(account: Account) { accountsById[account.accountId] = account accountsByLowercasedEmail[account.email.lowercased()] = account } private func removeFromIndexes(account: Account) { accountsById.removeValue(forKey: account.accountId) accountsByLowercasedEmail.removeValue(forKey: account.email.lowercased()) } }
apache-2.0
7ea7e459b21b66a675457bdad8568403
34.595238
135
0.622074
5.155172
false
true
false
false
ouch1985/IQuery
IQuery/utils/URLCache.swift
1
3789
// // URLCache.swift // IQuery // // Created by ouchuanyu on 15/12/12. // Copyright © 2015年 ouchuanyu.com. All rights reserved. // import Foundation // URL缓存工具. 单例 class URLCache{ let H5_BOUNDLE : String = "h5.bundle://" // 单例 class var sharedURLCache : URLCache{ struct Static { static let sharedInstance : URLCache = URLCache() } return Static.sharedInstance } // 获取URL资源,返回本地文件的路径。如果URL没有缓存过,则先缓存 func get(urlStr : String, callback : (err : String?, path : String?) -> ()){ if(urlStr.hasPrefix(H5_BOUNDLE)){ var filePath = NSBundle.mainBundle().pathForResource("h5", ofType: "bundle") filePath?.appendContentsOf("/") filePath?.appendContentsOf(urlStr.substringFromIndex(urlStr.startIndex.advancedBy(12))) callback(err: nil, path : filePath); return ; } if let nsUrl = NSURL(string: urlStr) { if let filePath : String = FileUtil.sharedInstance.url2path(nsUrl, urlStr: urlStr) { // 已经下载过了 if NSFileManager.defaultManager().fileExistsAtPath(filePath) { NSLog("已经下载过了[%@] ", filePath) callback(err: nil, path : filePath) } else { // 创建文件夹 FileUtil.sharedInstance.mkdirsByFilePath(filePath, isFile: true) // 请求并保存文件 let request = NSMutableURLRequest(URL: nsUrl) request.HTTPMethod = "GET" let session = NSURLSession.sharedSession() session.dataTaskWithRequest(request, completionHandler: { (data:NSData?,response:NSURLResponse?,error:NSError?)-> Void in let httpResp = response as? NSHTTPURLResponse dispatch_async(dispatch_get_main_queue(), { if error == nil && httpResp?.statusCode == 200{ NSLog("下载完成.[%@]", filePath) data!.writeToFile(filePath, atomically: true) callback(err: nil, path: filePath) } else { var errStr = "下载失败." if error != nil { errStr.appendContentsOf("err:") errStr.appendContentsOf((error?.description)!) } if httpResp?.statusCode != nil { errStr.appendContentsOf("code:") errStr.appendContentsOf(String(httpResp!.statusCode)) } NSLog("下载下载失败.[%@]", errStr) callback(err: errStr, path: nil) } }) } ).resume() } return ; } } // 不是下载过,也不去下载. URL有问题吧 callback(err: "URL error.", path : nil) NSLog("err url %@.", urlStr) } }
mit
0172c6133e49de92b04abf5c924b1938
37.827957
99
0.413573
6.046901
false
false
false
false
fakerabbit/LucasBot
LucasBot/AppDelegate.swift
1
2652
// // AppDelegate.swift // LucasBot // // Created by Mirko Justiniano on 1/8/17. // Copyright © 2017 LB. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Create window. window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.darkGray let vc = SplashVC() let nav:NavController = NavController(rootViewController: vc) window?.rootViewController = nav if !window!.isKeyWindow { window!.makeKeyAndVisible() } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. DataMgr.sharedInstance.saveContext() } }
gpl-3.0
8a584dc42b5e5264d793aa7793a4e85b
43.183333
285
0.725009
5.701075
false
false
false
false
zixun/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/CocoaChina/Search/CCSearchViewController.swift
1
2501
// // CCAboutViewController.swift // CocoaChinaPlus // // Created by zixun on 15/10/3. // Copyright © 2015年 zixun. All rights reserved. // import UIKit import RxSwift import RxCocoa import Alamofire class CCSearchViewController: CCArticleTableViewController { //搜索条 fileprivate var searchfiled:UISearchBar! //取消按钮 fileprivate var cancelButton:UIButton! //RxSwift资源回收包 fileprivate let disposeBag = DisposeBag() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(navigatorURL URL: URL?, query: Dictionary<String, String>) { super.init(navigatorURL: URL, query: query) } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge() self.cancelButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) self.cancelButton.setImage(R.image.nav_cancel(), for: UIControlState()) self.navigationItem.rightBarButtonItemFixedSpace(item: UIBarButtonItem(customView: cancelButton)) self.searchfiled = UISearchBar() self.searchfiled.placeholder = "关键字必需大于2个字符哦" self.navigationItem.titleView = self.searchfiled self.subscribes() } fileprivate func subscribes() { //取消按钮点击Observable self.cancelButton.rx.tap.bindNext { [unowned self] _ in self.dismiss(animated: true, completion: nil) }.addDisposableTo(self.disposeBag) //tableView滚动偏移量Observable self.tableView.rx.contentOffset.bindNext {[unowned self] (p:CGPoint) in if self.searchfiled.isFirstResponder { _ = self.searchfiled.resignFirstResponder() } }.addDisposableTo(self.disposeBag) //搜索框搜索按钮点击Observable self.searchfiled.rx.searchButtonClicked.map({ [unowned self] _ -> PublishSubject<[CCArticleModel]> in self.tableView.clean() return CCHTMLModelHandler.sharedHandler.handleSearchPage(self.searchfiled.text!, loadNextPageTrigger: self.loadNextPageTrigger) }).switchLatest().bindNext({ [unowned self] (models:Array<CCArticleModel>) in self.tableView.append(models) self.tableView.infiniteScrollingView.stopAnimating() }).addDisposableTo(self.disposeBag) } }
mit
0c1ff11c3e401bd79de88a4203a71382
32.971831
139
0.662521
4.710938
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Runtime/Instruction.swift
1
28649
// // Instruction.swift // LispKit // // Created by Matthias Zenger on 12/04/2016. // Copyright © 2016 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import NumberKit /// /// Enumeration `Instruction` defines the bytecode instruction set supported by the LispKit /// compiler and virtual machine. /// public enum Instruction: CustomStringConvertible { // Stack ------------------------------------------------------------------------------------ /// **`pop`**: Drops the top element from stack. case pop /// **`dup`**: Duplicates the top element on the stack. case dup /// **`swap`**: Swaps the top two elements on the stack. case swap /// **`alloc` _n_**: Pushes `n` undefined values onto the stack. case alloc(Int) /// **`allocBelow` _n_**: Pushes `n` undefined values below the top of the stack. case allocBelow(Int) /// **`reset` _o_,_n_**: Replaces `n` values on the stack with the undefined value starting /// from frame pointer offset `o`. case reset(Int, Int) // Constants -------------------------------------------------------------------------------- /// **`push_undef`**: Pushes the _undefined value_ onto the stack. case pushUndef /// **`push_void`**: Pushes the _void value_ onto the stack. case pushVoid /// **`push_eof`**: Pushes the _EOF value_ onto the stack. case pushEof /// **`push_null`**: Pushes value _null_ (empty list) onto the stack. case pushNull /// **`push_true`**: Pushes value `#true` onto the stack. case pushTrue /// **`push_false`**: Pushes value `#false` onto the stack. case pushFalse /// **`push_fixnum` _n_**: Pushes the fixnum _n_ onto the stack. case pushFixnum(Int64) /// **`push_bignum` _bn_**: Pushes the bignum _bn_ onto the stack. case pushBignum(BigInt) /// **`push_rat` _r_**: Pushes the rational number _r_ onto the stack. case pushRat(Rational<Int64>) /// **`push_bigrat` _br_**: Pushes the given bigrat number _br_ onto the stack. case pushBigrat(Rational<BigInt>) /// **`push_flonum` _x_**: Pushes the flonum _x_ onto the stack. case pushFlonum(Double) /// **`push_complex` _cx_**: Pushes the complex number _cx_ onto the stack. case pushComplex(Complex<Double>) /// **`push_char` _ch_**: Pushes the character _ch_ onto the stack. case pushChar(UniChar) /// **`push_constant` _c_**: Pushes the constant from the constant pool at index _c_ onto /// the stack. case pushConstant(Int) /// **`push_procedure` _c_**: Pushes the procedure from the constant pool at index _c_ onto /// the stack. (there is currently no difference to `push_constant`) case pushProcedure(Int) // Multi values /// **`pack` _n_**: Pops _n_ values from the stack and packages them up in a multi-value /// expression. case pack(Int) /// **`flatpack` _n_**: Pops _n_ values from the stack and packages them up in a multi-value /// expression. As opposed to `pack`, this guarantees that there are no nested multi-value /// expressions. case flatpack(Int) /// **`unpack` _n_**: Retrieves _n_ values from a multi-value expression and stores them on /// the stack. If the boolean flag is true, all values beyond _n_ are pushed onto the stack /// as a list. case unpack(Int, Bool) // Functions -------------------------------------------------------------------------------- /// **`make_closure` _i_,_n_,_f_**: Creates a new closure from a name, capture list and a code /// fragment. The capture list is created from the top _n_ elements on the stack. _f_ is /// an index into the list of code fragments of the currently executed code. _i_ is a /// reference into the constant pool referring to the name of the closure (-1 indicates that /// the closure is anonymous, -2 indicates that the closure is a continuation). case makeClosure(Int, Int, Int) /// **`make_tagged_closure` _i_,_n_,_f_**: Creates a new tagged closure from a name, capture /// list and a code fragment. The capture list is created from the top _n_ elements on the /// stack. _f_ is an index into the list of code fragments of the currently executed code. /// _i_ is a reference into the constant pool referring to the name of the closure (-1 /// indicates that the closure is anonymous, -2 indicates that the closure is a continuation). case makeTaggedClosure(Int, Int, Int) /// **`make_frame`**: Pushes a new stack frame onto the stack. case makeFrame /// **`inject_frame` _i_**: Creates a new stack frame on the stack below the top value. case injectFrame /// **`call` _n_**: Calls a procedure with _n_ arguments. case call(Int) /// **`tail_call` _n_**: Calls a procedure with _n_ arguments. This instruction is used /// for tail calls and does not require a new frame to be pushed. case tailCall(Int) /// **`apply` _n_**: This instruction expects on the stack a function, _n - 1_ individual /// arguments and an additional list of arguments. apply pushes the elements of the list /// onto the stack as well and then applies the function to all arguments on the stack. /// The instruction puts the result of the function application onto the stack. case apply(Int) /// **`return`**: Returns from the currently executed procedure. case `return` /// **`assert_arg_count` _n_**: Checks that there are exactly _n_ arguments on the stack. case assertArgCount(Int) /// **`assert_min_arg_count` _n_**: Checks that there are at least _n_ arguments on the /// stack. case assertMinArgCount(Int) /// **`no_matching_arg_count`**: Fails with an error signaling the lack of a matching case /// (in a `case-lambda`). case noMatchingArgCount /// **`collect_rest` _n_**: Collects the arguments exceeding _n_ into a list. case collectRest(Int) /// **`compile`**: Compiles the expression on top of the stack creating a thunk (a /// procedure without arguments) which is left on top of the stack. case compile // Macros ----------------------------------------------------------------------------------- /// **`make_syntax`**: Pops a syntax transformer function off the stack, creates a special /// form from it and pushes it onto the stack. case makeSyntax(Int) // Promises and streams --------------------------------------------------------------------- /// **`make_promise`**: Creates a new promise on the stack whose value will be computed /// by executing the closure on top of the stack. case makePromise /// **`make_stream`**: Creates a new stream on the stack whose value will be computed /// by executing the closure on top of the stack. case makeStream /// **`force`**: Forces the value of the promise or stream on top of the stack. If the /// promise or stream has been evaluated already, push the value onto the stack and skip /// the next instruction (which is typically a `store_in_promise` instruction). case force /// **`store_in_promise`**: Stores the value on top of the stack in the promise or stream /// to which the second top-most entry on the stack The promise gets removed from the stack. case storeInPromise // Variables -------------------------------------------------------------------------------- /// **`make_local_variable` _o_**: Creates a new variable, pops an expression from the /// stack and assignes the variable this expression as its initial value. The variable /// is then stored at the location specified by the frame pointer offset _o_. case makeLocalVariable(Int) /// **`make_variable_argument` _o_**: Creates a new variable and assignes the variable the /// expression at the location specified by the frame pointer offset _o_. The variable is /// then stored at the location specified by the frame pointer offset _o_, i.e. this /// instruction swaps a value on the stack with a variable with the same value. case makeVariableArgument(Int) // Bindings --------------------------------------------------------------------------------- /// **`push_global` _c_**: _c_ is an index into the constant pool referring to a symbol. /// `push_global` pushes the value to which this symbol is bound in the global environment /// onto the stack. case pushGlobal(Int) /// **`set_global` _c_**: _c_ is an index into the constant pool referring to a symbol. /// `set_global` binds the symbol in the global environment to the value on top of the /// stack. `set_global` fails if the symbol has not previously been bound in the global /// environment. case setGlobal(Int) /// **`define_global` _c_**: _c_ is an index into the constant pool referring to a symbol. /// `define_global` binds the symbol in the global environment to the value on top of the /// stack. As opposed to `set_global`, the symbol does not have to be bound previously. case defineGlobal(Int) /// **`push_captured` _d_**: _d_ is an index into the capture list. `push_captured` pushes /// the value _d_ refers to onto the stack. case pushCaptured(Int) /// **`push_captured_value` _d_**: _d_ is an index into the capture list referring to /// a variable. `push_captured_value` pushes the value of the variable to which _d_ /// refers to onto the stack. case pushCapturedValue(Int) /// **`set_captured_value` _d_**: _d_ is an index into the capture list referring to /// a variable. `set_captured_value` stores the value on top of the stack in the variable /// to which _d_ refers to. case setCapturedValue(Int) /// **`push_local` _o_**: is an offset relative to the frame pointer. `push_local` pushes /// the value in this location onto the stack. case pushLocal(Int) /// **`push_local_value` _o_**: _o_ is an offset relative to the frame pointer referring /// to a variable. `push_local_value` pushes the value of this variable onto the stack. case pushLocalValue(Int) /// **`set_local` _o_**: _o_ is an offset relative to the frame pointer. `set_local` /// stores the value on top of the stack in this stack location overwriting the previous /// value. case setLocal(Int) /// **`set_local_value` _o_**: _o_ is an offset relative to the frame pointer referring /// to a variable. `set_local_value` stores the value on top of the stack in this variable. case setLocalValue(Int) // Control flow ----------------------------------------------------------------------------- /// **`branch` _i_**: _i_ is an offset relative to the current instruction pointer. /// `branch` jumps to the instruction to which _i_ refers to. case branch(Int) /// **`branch_if` _i_**: _i_ is an offset relative to the current instruction pointer. /// `branch_if` jumps to the instruction to which _i_ refers to if the value on the stack /// is not `#false`. case branchIf(Int) /// **`branch_if_not` _i_**: _i_ is an offset relative to the current instruction /// pointer. `branch_if_not` jumps to the instruction to which _i_ refers to if the value /// on the stack is `#false`. case branchIfNot(Int) /// **`keep_or_branch_if_not` _i_**: _i_ is an offset relative to the current instruction /// pointer. `keep_or_branch_if_not` jumps to the instruction to which _i_ refers to if /// the value on the stack is `#false`. If the value is not `#false`, the value will remain /// on the stack. case keepOrBranchIfNot(Int) /// **`branch_if_arg_mismatch` _n_,_i_**: _i_ is an offset relative to the current instruction /// pointer. `branch_if_arg_mismatch` jumps to the instruction to which _i_ refers to if /// there are not exactly _n_ arguments on the stack. case branchIfArgMismatch(Int, Int) /// **`branch_if_min_arg_mismatch` _n_,_i_**: _i_ is an offset relative to the current /// instruction pointer. `branch_if_min_arg_mismatch` jumps to the instruction to which _i_ /// refers to if there are not at least _n_ arguments on the stack. case branchIfMinArgMismatch(Int, Int) /// **`or` _i_**: _i_ is an offset relative to the current instruction pointer. `or` /// jumps to the instruction to which _i_ refers to if the value on the stack is not /// `#false`. As opposed to `branch_if`, the value on top of the stack will remain there. /// Only if the value on top of the stack is `#false`, `or` will pop this value off the /// stack. case or(Int) /// **`and` _i_**: _i_ is an offset relative to the current instruction pointer. `or` /// jumps to the instruction to which _i_ refers to if the value on the stack is `#false`. /// As opposed to `branch_if_not`, the value on top of the stack will remain there. Only /// if the value on top of the stack is not `#false`, `and` will pop this value off the /// stack. case and(Int) // Equivalences ----------------------------------------------------------------------------- /// **`eq`**: Compares the top two values on the stack via `eq?` and pushes the result /// onto the stack. case eq /// **`eqv`**: Compares the top two values on the stack via `eqv?` and pushes the result /// onto the stack. case eqv /// **`equal`**: Compares the top two values on the stack via `equal?` and pushes the /// result onto the stack. case equal // Frequently used primitives -------------------------------------------------------------- /// **`is_pair`**: Pushes `#false` onto the stack if the current value on top of /// the stack is not a pair. case isPair /// **`is_null`**: Pushes `#false` onto the stack if the current value on top of /// the stack is not null. case isNull /// **`is_undef`**: Pushes `#false` onto the stack if the current value on top of /// the stack is not undefined. case isUndef /// **`list` _n_**: Pops the top _n_ values off the stack and constructs a list out of /// them on top of the stack. case list(Int) /// **`cons`**: Pops the head and the tail of a new pair off the stack and pushes a /// new pair with this head and tail onto the stack. case cons /// **`decons`**: Pops a pair off the stack and pushes first its tail and then its head /// onto the stack. case decons /// **`decons_keyword`**: Pops a list off the stack, pushing the first two elements as well as the /// tail of the second pair onto the stack case deconsKeyword /// **`car`**: Pops a pair off the stack and pushes its head onto the stack. case car /// **`cdr`**: Pops a pair off the stack and pushes its tail onto the stack. case cdr /// **`vector` _n_**: Pops the top _n_ values off the stack and constructs a vector /// out of them on top of the stack. case vector(Int) /// **`list_to_vector`**: Converts a list to a vector. case listToVector /// **`vector_append` _n_**: Pops the top _n_ vectors off the stack and constructs a /// new vector by concatenating the individual vectors. case vectorAppend(Int) /// **`is_vector`**: Pushes `#false` onto the stack if the current value on top of /// the stack is not a vector. case isVector /// **`not`**: Logical negation of the value on top of the stack. case not // Math ------------------------------------------------------------------------------------- /// **`fx_plus`**: Computes the sum of two fixnum values on the stack. case fxPlus /// **`fx_minus`**: Computes the difference of two fixnum values on the stack. case fxMinus /// **`fx_mult`**: Multiplies two fixnum values on the stack. case fxMult /// **`fx_div`**: Divides a fixnum value by another fixnum value on the stack. case fxDiv /// **`fx_inc`**: Adds one to another fixnum value on the stack. case fxInc /// **`fx_dec`**: Substracts one from another fixnum value on the stack. case fxDec /// **`fx_is_zero`**: Puts true on the stack if the fixnum value on the stack is zero. case fxIsZero /// **`fx_eq` _n_**: Compares _n_ fixnum values on top of the stack for equality. case fxEq(Int) /// **`fx_lt` _n_**: Compares _n_ fixnum values on top of the stack for "less than". case fxLt(Int) /// **`fx_gt` _n_**: Compares _n_ fixnum values on top of the stack for "greater than". case fxGt(Int) /// **`fx_lt_eq` _n_**: Compares _n_ fixnum values on top of the stack for "less than or equal". case fxLtEq(Int) /// **`fx_gt_eq` _n_**: Compares _n_ fixnum values on top of the stack for "greater than /// or equal". case fxGtEq(Int) /// **`fx_assert`**: Raises an exception if the value on the stack is not a fixed point /// number. This instruction does not change the stack. case fxAssert /// **`fl_plus`**: Computes the sum of two flonum values on the stack. case flPlus /// **`fl_minus`**: Computes the difference of two flonum values on the stack. case flMinus /// **`fl_mult`**: Multiplies two flonum values on the stack. case flMult /// **`fl_div`**: Divides a flonum value by another flonum value on the stack. case flDiv /// **`fl_neg`**: Negates the flonum value on the stack. case flNeg /// **`fl_eq` _n_**: Compares _n_ flonum values on top of the stack for equality. case flEq(Int) /// **`fl_lt` _n_**: Compares _n_ flonum values on top of the stack for "less than". case flLt(Int) /// **`fl_gt` _n_**: Compares _n_ flonum values on top of the stack for "greater than". case flGt(Int) /// **`fl_lt_eq` _n_**: Compares _n_ flonum values on top of the stack for "less than /// of equal". case flLtEq(Int) /// **`fl_gt_eq` _n_**: Compares _n_ flonum values on top of the stack for "greater than /// or equal". case flGtEq(Int) /// **`fl_assert`**: Raises an exception if the value on the stack is not a floating point /// number. This instruction does not change the stack. case flAssert // Miscellaneous ---------------------------------------------------------------------------- /// **`make_thread` _s_**: Creates a new thread from the thunk on top of the stack /// and returns it. If _s_ is set to true, the thread is started right away. case makeThread(Bool) /// **`fail_if_not_null`**: Raises a "list not empty" error if the top element on the /// stack is not an empty list. case failIfNotNull /// **`raise_error` _err_,_n_**: Raises the given evaluation error _err_ using the top _n_ /// elements on top of the stack as irritants. case raiseError(Int, Int) /// **`push_current_time`**: Pushes the current time as a flonum onto the stack. The time /// is expressed as seconds since January 1, 1970 at 00:00. case pushCurrentTime /// **`display`**: Displays the value on top of the stack on the console. case display /// **`newline`**: Displays a newline character on the console. case newline /// **`noop`**: Empty instruction; proceeds to the next instruction. case noOp // ------------------------------------------------------------------------------------------ /// Provides supplemental information about this instruction in a given code context. public func comment(for code: Code, at ip: Int) -> String? { switch self { case .pushGlobal(_): return nil case .setGlobal(_): return nil case .defineGlobal(_): return nil case .pushCaptured(_): return nil case .pushCapturedValue(_): return nil case .setCapturedValue(_): return nil case .pushLocal(_): return nil case .pushLocalValue(_): return nil case .setLocal(_): return nil case .setLocalValue(_): return nil case .pushConstant(let index): return code.constants[index].description case .pushProcedure(let index): return code.constants[index].description case .makeClosure(let i, _, _): return i >= 0 ? code.constants[i].description : (i == -2 ? "continuation" : nil) case .makeTaggedClosure(let i, _, _): return i >= 0 ? code.constants[i].description : (i == -2 ? "continuation" : nil) case .makeSyntax(let i): return i >= 0 ? code.constants[i].description : nil case .makeVariableArgument(_): return nil case .pushChar(let char): var res = "'" res.append(Character(unicodeScalar(char))) res.append(Character("'")) return res case .call(_): return nil case .tailCall(_): return nil case .branch(let offset): return "jump to \(ip + offset - 1)" case .branchIf(let offset): return "jump to \(ip + offset - 1)" case .branchIfNot(let offset): return "jump to \(ip + offset - 1)" case .keepOrBranchIfNot(let offset): return "jump to \(ip + offset - 1)" case .branchIfArgMismatch(_, let offset): return "jump to \(ip + offset - 1)" case .branchIfMinArgMismatch(_, let offset): return "jump to \(ip + offset - 1)" case .and(let offset): return "pop or jump to \(ip + offset - 1) if false" case .or(let offset): return "pop or jump to \(ip + offset - 1) if true" default: return nil } } /// Returns a textual description of this instruction. public var description: String { switch self { case .noOp: return "noop" case .pop: return "pop" case .dup: return "dup" case .pushGlobal(let loc): return "push_global \(loc)" case .setGlobal(let loc): return "set_global \(loc)" case .defineGlobal(let loc): return "define_global \(loc)" case .pushCaptured(let index): return "push_captured \(index)" case .pushCapturedValue(let index): return "push_captured_value \(index)" case .setCapturedValue(let index): return "set_captured_value \(index)" case .pushLocal(let index): return "push_local \(index)" case .makeLocalVariable(let index): return "make_local_variable \(index)" case .pushLocalValue(let index): return "push_local_value \(index)" case .setLocal(let index): return "set_local \(index)" case .setLocalValue(let index): return "set_local_value \(index)" case .pushConstant(let index): return "push_constant \(index)" case .pushProcedure(let index): return "push_procedure \(index)" case .makeVariableArgument(let index): return "make_variable_argument \(index)" case .pushUndef: return "push_undef" case .pushVoid: return "push_void" case .pushEof: return "push_eof" case .pushNull: return "push_null" case .pushTrue: return "push_true" case .pushFalse: return "push_false" case .pushFixnum(let num): return "push_fixnum \(num)" case .pushBignum(let num): return "push_bignum \(num)" case .pushRat(let num): return "push_rat \(num)" case .pushBigrat(let num): return "push_bigrat \(num)" case .pushFlonum(let num): return "push_flonum \(num)" case .pushComplex(let num): return "push_complex \(num)" case .pushChar(let char): return "push_char \(char)" case .pack(let n): return "pack \(n)" case .flatpack(let n): return "flatpack \(n)" case .unpack(let n, let all): return "unpack \(n), \(all ? "given" : "all")" case .makeClosure(let i, let n, let index): return "make_closure \(i), \(n), \(index)" case .makeTaggedClosure(let i, let n, let index): return "make_tagged_closure \(i), \(n), \(index)" case .makePromise: return "make_promise" case .makeStream: return "make_stream" case .makeSyntax(let i): return "make_syntax \(i)" case .compile: return "compile" case .apply(let n): return "apply \(n)" case .makeFrame: return "make_frame" case .injectFrame: return "inject_frame" case .call(let n): return "call \(n)" case .tailCall(let n): return "tail_call \(n)" case .assertArgCount(let n): return "assert_arg_count \(n)" case .assertMinArgCount(let n): return "assert_min_arg_count \(n)" case .noMatchingArgCount: return "no_matching_arg_count" case .collectRest(let n): return "collect_rest \(n)" case .alloc(let n): return "alloc \(n)" case .allocBelow(let n): return "alloc_below \(n)" case .reset(let index, let n): return "reset \(index), \(n)" case .`return`: return "return" case .branch(let offset): return "branch \(offset)" case .branchIf(let offset): return "branch_if \(offset)" case .branchIfNot(let offset): return "branch_if_not \(offset)" case .keepOrBranchIfNot(let offset): return "keep_or_branch_if_not \(offset)" case .branchIfArgMismatch(let n, let offset): return "branch_if_arg_mismatch \(n), \(offset)" case .branchIfMinArgMismatch(let n, let offset): return "branch_if_min_arg_mismatch \(n), \(offset)" case .and(let offset): return "and \(offset)" case .or(let offset): return "or \(offset)" case .force: return "force" case .storeInPromise: return "store_in_promise" case .swap: return "swap" case .makeThread(let s): return "make_thread \(s ? "start" : "new")" case .failIfNotNull: return "fail_if_not_null" case .raiseError(let err, let n): return "raise_error \(err), \(n)" case .pushCurrentTime: return "push_current_time" case .display: return "display" case .newline: return "newline" case .eq: return "eq" case .eqv: return "eqv" case .equal: return "equal" case .isPair: return "is_pair" case .isNull: return "is_null" case .isUndef: return "is_undef" case .cons: return "cons" case .decons: return "decons" case .deconsKeyword: return "decons_keyword" case .car: return "car" case .cdr: return "cdr" case .list(let n): return "list \(n)" case .vector(let n): return "vector \(n)" case .listToVector: return "list_to_vector" case .vectorAppend(let n): return "vector_append \(n)" case .isVector: return "is_vector" case .not: return "not" case .fxPlus: return "fx_plus" case .fxMinus: return "fx_minus" case .fxMult: return "fx_mult" case .fxDiv: return "fx_div" case .fxInc: return "fx_inc" case .fxDec: return "fx_dec" case .fxIsZero: return "fx_is_zero" case .fxEq(let n): return "fx_eq \(n)" case .fxLt(let n): return "fx_lt \(n)" case .fxGt(let n): return "fx_gt \(n)" case .fxLtEq(let n): return "fx_lt_eq \(n)" case .fxGtEq(let n): return "fx_gt_eq \(n)" case .fxAssert: return "fx_assert" case .flPlus: return "fl_plus" case .flMinus: return "fl_minus" case .flMult: return "fl_mult" case .flDiv: return "fl_div" case .flNeg: return "fl_neg" case .flEq(let n): return "fl_eq \(n)" case .flLt(let n): return "fl_lt \(n)" case .flGt(let n): return "fl_gt \(n)" case .flLtEq(let n): return "fl_lt_eq \(n)" case .flGtEq(let n): return "fl_gt_eq \(n)" case .flAssert: return "fl_assert" } } } /// A sequence of instructions, represented as an array. public typealias Instructions = ContiguousArray<Instruction>
apache-2.0
25c5f96c09bb6f5f39c2490effd2f78b
35.35533
100
0.601368
3.896097
false
false
false
false
PjGeeroms/IOSRecipeDB
Pods/ReactiveKit/Sources/Observer.swift
5
3781
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Represents a type that receives events. public typealias Observer<Element, Error: Swift.Error> = (Event<Element, Error>) -> Void /// Represents a type that receives events. public protocol ObserverProtocol { /// Type of elements being received. associatedtype Element /// Type of error that can be received. associatedtype Error: Swift.Error /// Send the event to the observer. func on(_ event: Event<Element, Error>) } /// Represents a type that receives events. Observer is just a convenience /// wrapper around a closure observer `Observer<Element, Error>`. public struct AnyObserver<Element, Error: Swift.Error>: ObserverProtocol { private let observer: Observer<Element, Error> /// Creates an observer that wraps a closure observer. public init(observer: @escaping Observer<Element, Error>) { self.observer = observer } /// Calles wrapped closure with the given element. public func on(_ event: Event<Element, Error>) { observer(event) } } /// Observer that ensures events are sent atomically. public class AtomicObserver<Element, Error: Swift.Error>: ObserverProtocol { private let observer: Observer<Element, Error> private let disposable: Disposable private let lock = NSRecursiveLock(name: "com.reactivekit.signal.atomicobserver") private var terminated = false /// Creates an observer that wraps given closure. public init(disposable: Disposable, observer: @escaping Observer<Element, Error>) { self.disposable = disposable self.observer = observer } /// Calles wrapped closure with the given element. public func on(_ event: Event<Element, Error>) { lock.lock(); defer { lock.unlock() } guard !disposable.isDisposed && !terminated else { return } if event.isTerminal { terminated = true observer(event) disposable.dispose() } else { observer(event) } } } // MARK: - Extensions public extension ObserverProtocol { /// Convenience method to send `.next` event. public func next(_ element: Element) { on(.next(element)) } /// Convenience method to send `.failed` event. public func failed(_ error: Error) { on(.failed(error)) } /// Convenience method to send `.completed` event. public func completed() { on(.completed) } /// Convenience method to send `.next` event followed by a `.completed` event. public func completed(with element: Element) { next(element) completed() } /// Converts the receiver to the Observer closure. public func toObserver() -> Observer<Element, Error> { return on } }
mit
f6d16823aa5089fbdf27522bf9384a94
31.316239
88
0.715155
4.376157
false
false
false
false
ray3132138/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendNewCell.swift
1
3783
// // CBRecommendNewCell.swift // TestKitchen // // Created by qianfeng on 16/8/19. // Copyright © 2016年 ray. All rights reserved. // import UIKit class CBRecommendNewCell: UITableViewCell { //显示数据 var model:CBRecommendWidgetListModel?{ didSet{ showData() } } func showData(){ //按照三列来遍历: for i in 0..<3{ //图片 //0 4 8 if model?.widget_data?.count>i*4{ let imageModel = model?.widget_data![i*4] if imageModel?.type == "image"{ let url = NSURL(string: (imageModel?.content)!) let dImage = UIImage(named: "sdefaultImage") //获取图片视图 let subView = contentView.viewWithTag(200+i) if subView?.isKindOfClass(UIImageView.self) == true{ let imageView = subView as! UIImageView imageView.kf_setImageWithURL(url, placeholderImage: dImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } } //视频 // 1 5 9 //标题文字 // 2 6 10 if model?.widget_data?.count>(i*4+2){ let titleModel = model?.widget_data![i*4+2] if titleModel?.type == "text"{ //获取标题的label let subView = contentView.viewWithTag(400+i) if subView?.isKindOfClass(UILabel.self) == true{ let titleLabel = subView as! UILabel titleLabel.text = titleModel?.content } } } //描述文字 if model?.widget_data?.count > (i*4+3){ let descModel = model?.widget_data![i*4+3] if descModel?.type == "text"{ let subView = contentView.viewWithTag(500+i) if subView?.isKindOfClass(UILabel.self) == true{ let descLabel = subView as! UILabel descLabel.text = descModel?.content } } } } } class func createNewCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath,withListModel model: CBRecommendWidgetListModel)->CBRecommendNewCell{ let cellId = "recommendNewCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBRecommendNewCell if cell == nil{ cell = NSBundle.mainBundle().loadNibNamed("CBRecommendNewCell", owner: nil, options: nil).last as? CBRecommendNewCell } cell?.model = model return cell! } //点击进详情 @IBAction func clickBtn(sender: UIButton) { } //播放视频 @IBAction func playAction(sender: UIButton) { } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
7896f9a144a86ded42f8c3bb207a3e9b
24.832168
160
0.446941
5.808176
false
false
false
false
DannyvanSwieten/SwiftSignals
SwiftEngine/SwiftEngine/MetalViewController.swift
1
1249
// // MetalViewController.swift // SwiftEngine // // Created by Danny van Swieten on 1/25/16. // Copyright © 2016 Danny van Swieten. All rights reserved. // import MetalKit import AppKit class MetalViewController: NSViewController, MTKViewDelegate { func drawInMTKView(view: MTKView) { GameEngine.instance.render() } func mtkView(view: MTKView, drawableSizeWillChange size: CGSize) { } override func viewDidLoad() { super.viewDidLoad() let view = self.view as! MetalView view.delegate = self GameEngine.instance.setupGraphics(view) GameEngine.instance.physics.start() } override func keyDown(theEvent: NSEvent) { let controller = GameEngine.instance.controller if theEvent.characters! != ""{ controller.keyPressed.addObject(theEvent.characters!) } switch(theEvent.keyCode) { case 56: controller.keyPressed.addObject("shift") default: return } } override func keyUp(theEvent: NSEvent) { let controller = GameEngine.instance.controller controller.keyPressed.removeObject(theEvent.characters!) } }
gpl-3.0
313b1d43a177a5850cf0b9142c0027fc
24.489796
70
0.627404
4.674157
false
false
false
false
zmian/xcore.swift
Sources/Xcore/SwiftUI/Components/Clients/PasteboardClient.swift
1
2037
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import UIKit /// Provides functionality for copying a string to pasteboard. /// /// **Usage** /// /// ```swift /// struct ViewModel { /// @Dependency(\.pasteboard) var pasteboard /// /// func copy() { /// pasteboard.copy("hello") /// } /// } /// ``` public struct PasteboardClient: Hashable, Identifiable { public let id: String /// Copy the specified string to pasteboard. public let copy: (String) -> Void public init(id: String = #function, copy: @escaping (String) -> Void) { self.id = id self.copy = copy } public static func ==(lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id } public func hash(into hasher: inout Hasher) { hasher.combine(id) } } // MARK: - Variants extension PasteboardClient { /// Returns live variant of `PasteboardClient`. public static var live: Self { .init { string in UIPasteboard.general.string = string } } /// Returns noop variant of `PasteboardClient`. public static var noop: Self { .init { _ in } } #if DEBUG /// Returns failing variant of `PasteboardClient`. public static var failing: Self { .init { _ in internal_XCTFail("\(Self.self).copy is unimplemented") } } #endif } // MARK: - Dependency extension DependencyValues { private struct PasteboardClientKey: DependencyKey { static let defaultValue: PasteboardClient = .live } /// Provides functionality for copying a string to pasteboard. public var pasteboard: PasteboardClient { get { self[PasteboardClientKey.self] } set { self[PasteboardClientKey.self] = newValue } } /// Provides functionality for copying a string to pasteboard. @discardableResult public static func pasteboard(_ value: PasteboardClient) -> Self.Type { set(\.pasteboard, value) return Self.self } }
mit
daa62c6902f9887fec753f8c8f4b5e51
22.674419
75
0.612967
4.331915
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/SelectSizeRowItem.swift
1
18421
// // SelectSizeRowItem.swift // Telegram // // Created by keepcoder on 15/12/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit class SelectSizeRowItem: GeneralRowItem { fileprivate let titles:[String]? fileprivate let sizes: [Int32] fileprivate var current: Int32 fileprivate let initialCurrent: Int32 fileprivate let selectAction:(Int)->Void fileprivate let hasMarkers: Bool fileprivate let dottedIndexes: [Int] init(_ initialSize: NSSize, stableId: AnyHashable, current: Int32, sizes: [Int32], hasMarkers: Bool, titles:[String]? = nil, dottedIndexes:[Int] = [], viewType: GeneralViewType = .legacy, selectAction: @escaping(Int)->Void) { self.sizes = sizes self.titles = titles self.dottedIndexes = dottedIndexes self.initialCurrent = current self.hasMarkers = hasMarkers self.current = current self.selectAction = selectAction super.init(initialSize, height: titles != nil ? 70 : 40, stableId: stableId, viewType: viewType, inset: NSEdgeInsets(left: 30, right: 30)) } override func viewClass() -> AnyClass { return SelectSizeRowView.self } } private class SelectSizeRowView : TableRowView, ViewDisplayDelegate { private var availableRects:[NSRect] = [] private let containerView = GeneralRowContainerView(frame: NSZeroRect) required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.addSubview(containerView) containerView.displayDelegate = self containerView.userInteractionEnabled = false containerView.isEventLess = true layerContentsRedrawPolicy = .onSetNeedsDisplay } override func mouseDragged(with event: NSEvent) { guard let item = item as? SelectSizeRowItem, !item.sizes.isEmpty else { super.mouseDragged(with: event) return } if item.sizes.count == availableRects.count { let point = containerView.convert(event.locationInWindow, from: nil) for i in 0 ..< availableRects.count { if NSPointInRect(point, availableRects[i]), item.current != i { item.current = item.sizes[i] containerView.needsDisplay = true } } } } override func mouseUp(with event: NSEvent) { guard let item = item as? SelectSizeRowItem, !item.sizes.isEmpty else { super.mouseUp(with: event) return } if item.sizes.count == availableRects.count { let point = containerView.convert(event.locationInWindow, from: nil) for i in 0 ..< availableRects.count { if NSPointInRect(point, availableRects[i]), item.sizes.firstIndex(of: item.current) != i { item.selectAction(i) return } } if item.initialCurrent != item.current { item.selectAction(item.sizes.firstIndex(of: item.current)!) } } } func _focus(_ size: NSSize) -> NSRect { var focus = self.containerView.focus(size) if let item = item as? SelectSizeRowItem { switch item.viewType { case .legacy: if item.titles != nil { focus.origin.y += 20 } case let .modern(_, insets): if item.titles != nil { focus.origin.y += (24 - insets.bottom) } } } return focus } override func draw(_ layer: CALayer, in ctx: CGContext) { super.draw(layer, in: ctx) guard let item = item as? SelectSizeRowItem, !item.sizes.isEmpty, containerView.layer == layer else {return} switch item.viewType { case .legacy: let minFontSize = CGFloat(item.sizes.first!) let maxFontSize = CGFloat(item.sizes.last!) let minNode = TextNode.layoutText(.initialize(string: "A", color: theme.colors.text, font: .normal(min(minFontSize, 11))), backdorColor, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left) let maxNode = TextNode.layoutText(.initialize(string: "A", color: theme.colors.text, font: .normal(min(maxFontSize, 15))), backdorColor, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left) let minF = _focus(item.hasMarkers ? minNode.0.size : NSZeroSize) let maxF = _focus(item.hasMarkers ? maxNode.0.size : NSZeroSize) if item.hasMarkers { minNode.1.draw(NSMakeRect(item.inset.left, minF.minY, minF.width, minF.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor) maxNode.1.draw(NSMakeRect(containerView.frame.width - item.inset.right - maxF.width, maxF.minY, maxF.width, maxF.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor) } let count = CGFloat(item.sizes.count) let insetBetweenFont: CGFloat = item.hasMarkers ? 20 : 0 let width: CGFloat = containerView.frame.width - (item.inset.left + minF.width) - (item.inset.right + maxF.width) - insetBetweenFont * 2 let per = floorToScreenPixels(backingScaleFactor, width / (count - 1)) ctx.setFillColor(theme.colors.accent.cgColor) let lineSize = NSMakeSize(width, 2) let lc = _focus(lineSize) let minX = item.inset.left + minF.width + insetBetweenFont let interactionRect = NSMakeRect(minX, lc.minY, lc.width, lc.height) ctx.fill(interactionRect) let current: CGFloat = CGFloat(item.sizes.firstIndex(of: item.current) ?? 0) let selectSize = NSMakeSize(20, 20) let selectPoint = NSMakePoint(minX + floorToScreenPixels(backingScaleFactor, interactionRect.width / CGFloat(item.sizes.count - 1)) * current - selectSize.width / 2, _focus(selectSize).minY) ctx.setFillColor(theme.colors.grayText.cgColor) let unMinX = selectPoint.x + selectSize.width / 2 ctx.fill(NSMakeRect(unMinX, lc.minY, lc.maxX - unMinX, lc.height)) for i in 0 ..< item.sizes.count { let perSize = NSMakeSize(10, 10) let perF = _focus(perSize) let point = NSMakePoint(minX + per * CGFloat(i) - (i > 0 ? perSize.width / 2 : 0), perF.minY) ctx.setFillColor(theme.colors.background.cgColor) ctx.fill(NSMakeRect(point.x, point.y, perSize.width, perSize.height)) ctx.setFillColor(item.sizes[i] <= item.current ? theme.colors.accent.cgColor : theme.colors.grayText.cgColor) ctx.fillEllipse(in: NSMakeRect(point.x + perSize.width/2 - 2, point.y + 3, 4, 4)) if let titles = item.titles, titles.count == item.sizes.count { let title = titles[i] let titleNode = TextNode.layoutText(.initialize(string: title, color: theme.colors.text, font: .normal(.short)), backdorColor, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left) titleNode.1.draw(NSMakeRect(min(max(point.x - titleNode.0.size.width / 2 + 3, minX), frame.width - titleNode.0.size.width - minX), point.y - 15 - titleNode.0.size.height, titleNode.0.size.width, titleNode.0.size.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor) } } if let titles = item.titles, titles.count == 1, let title = titles.first { let perSize = NSMakeSize(10, 10) let perF = _focus(perSize) let titleNode = TextNode.layoutText(.initialize(string: title, color: theme.colors.text, font: .normal(.short)), backdorColor, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left) titleNode.1.draw(NSMakeRect(_focus(titleNode.0.size).minX, perF.minY - 15 - titleNode.0.size.height, titleNode.0.size.width, titleNode.0.size.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor) } ctx.setFillColor(theme.colors.border.cgColor) ctx.fillEllipse(in: NSMakeRect(selectPoint.x, selectPoint.y, selectSize.width, selectSize.height)) ctx.setFillColor(.white) ctx.fillEllipse(in: NSMakeRect(selectPoint.x + 1, selectPoint.y + 1, selectSize.width - 2, selectSize.height - 2)) resetCursorRects() availableRects.removeAll() for i in 0 ..< item.sizes.count { let perF = _focus(selectSize) let point = NSMakePoint(interactionRect.minX + floorToScreenPixels(backingScaleFactor, interactionRect.width / (count - 1)) * CGFloat(i) - selectSize.width / 2, perF.minY) let rect = NSMakeRect(point.x, point.y, selectSize.width, selectSize.height) addCursorRect(rect, cursor: NSCursor.pointingHand) availableRects.append(rect) } case let .modern(_, insets): let minFontSize = CGFloat(item.sizes.first!) let maxFontSize = CGFloat(item.sizes.last!) let minNode = TextNode.layoutText(.initialize(string: "A", color: theme.colors.text, font: .normal(min(minFontSize, 11))), backdorColor, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left) let maxNode = TextNode.layoutText(.initialize(string: "A", color: theme.colors.text, font: .normal(min(maxFontSize, 15))), backdorColor, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left) let minF = _focus(item.hasMarkers ? minNode.0.size : NSZeroSize) let maxF = _focus(item.hasMarkers ? maxNode.0.size : NSZeroSize) if item.hasMarkers { minNode.1.draw(NSMakeRect(insets.left, minF.minY, minF.width, minF.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor) maxNode.1.draw(NSMakeRect(containerView.frame.width - insets.right - maxF.width, maxF.minY, maxF.width, maxF.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor) } let count = CGFloat(item.sizes.count) let insetBetweenFont: CGFloat = item.hasMarkers ? 20 : 0 let width: CGFloat = containerView.frame.width - (insets.left + minF.width) - (insets.right + maxF.width) - insetBetweenFont * 2 let per = floorToScreenPixels(backingScaleFactor, width / (count - 1)) ctx.setFillColor(theme.colors.accent.cgColor) let lineSize = NSMakeSize(width, 2) let lc = _focus(lineSize) let minX = insets.left + minF.width + insetBetweenFont let interactionRect = NSMakeRect(minX, lc.minY, lc.width, lc.height) ctx.fill(interactionRect) let current: CGFloat = CGFloat(item.sizes.firstIndex(of: item.current) ?? 0) let selectSize = NSMakeSize(20, 20) let selectPoint = NSMakePoint(minX + floorToScreenPixels(backingScaleFactor, interactionRect.width / CGFloat(item.sizes.count - 1)) * current - selectSize.width / 2, _focus(selectSize).minY) ctx.setFillColor(theme.colors.grayText.cgColor) let unMinX = selectPoint.x + selectSize.width / 2 ctx.fill(NSMakeRect(unMinX, lc.minY, lc.maxX - unMinX, lc.height)) for i in 0 ..< item.sizes.count { let perSize = NSMakeSize(10, 10) let perF = _focus(perSize) let point = NSMakePoint(minX + per * CGFloat(i) - (i > 0 ? perSize.width / 2 : 0), perF.minY) ctx.setFillColor(theme.colors.background.cgColor) ctx.fill(NSMakeRect(point.x, point.y, perSize.width, perSize.height)) ctx.setFillColor(i <= (item.sizes.firstIndex(of: item.current) ?? 0) ? theme.colors.accent.cgColor : theme.colors.grayText.cgColor) ctx.fillEllipse(in: NSMakeRect(point.x + perSize.width/2 - 2, point.y + 3, 4, 4)) if item.dottedIndexes.contains(i), i > 0 { let prevPoint = NSMakePoint(minX + per * CGFloat(i - 1) + (i == 1 ? perSize.width : perSize.width / 2), lc.minY) let rect = NSMakeRect(prevPoint.x, lc.minY, point.x - prevPoint.x, lc.height) ctx.clear(rect) let w: CGFloat = 16 let count = Int(floor(rect.width / w)) let total = CGFloat(count) * w let inset: CGFloat = ceil((rect.width - total) / 2) for j in 0 ..< count { let rect = NSMakeRect(rect.minX + CGFloat(j) * w, rect.minY, w, rect.height) ctx.saveGState() ctx.setFillColor(i <= (item.sizes.firstIndex(of: item.current) ?? 0) ? theme.colors.accent.cgColor : theme.colors.grayText.cgColor) ctx.fill(NSMakeRect(rect.minX + inset + 2, rect.minY, w - 4, rect.height)) ctx.restoreGState() } } if let titles = item.titles, titles.count == item.sizes.count { let title = titles[i] let titleNode = TextNode.layoutText(.initialize(string: title, color: theme.colors.grayText, font: .normal(.short)), backdorColor, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left) var rect = NSMakeRect(min(max(point.x - titleNode.0.size.width / 2 + 3, minX), frame.width - titleNode.0.size.width - minX), point.y - 15 - titleNode.0.size.height, titleNode.0.size.width, titleNode.0.size.height) if i == titles.count - 1 { rect.origin.x = min(rect.minX, (point.x + 5) - titleNode.0.size.width) } titleNode.1.draw(rect, in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor) } } if let titles = item.titles, titles.count == 1, let title = titles.first { let titleNode = TextNode.layoutText(.initialize(string: title, color: theme.colors.grayText, font: .normal(.short)), backdorColor, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left) titleNode.1.draw(NSMakeRect(_focus(titleNode.0.size).minX, insets.top , titleNode.0.size.width, titleNode.0.size.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor) } ctx.setFillColor(theme.colors.border.cgColor) ctx.fillEllipse(in: NSMakeRect(selectPoint.x, selectPoint.y, selectSize.width, selectSize.height)) ctx.setFillColor(.white) ctx.fillEllipse(in: NSMakeRect(selectPoint.x + 1, selectPoint.y + 1, selectSize.width - 2, selectSize.height - 2)) resetCursorRects() availableRects.removeAll() for i in 0 ..< item.sizes.count { let perF = _focus(selectSize) let point = NSMakePoint(interactionRect.minX + floorToScreenPixels(backingScaleFactor, interactionRect.width / (count - 1)) * CGFloat(i) - selectSize.width / 2, perF.minY) let rect = NSMakeRect(point.x, point.y, selectSize.width, selectSize.height) addCursorRect(rect, cursor: NSCursor.pointingHand) availableRects.append(rect) } } layout() } override var backdorColor: NSColor { return theme.colors.background } override func layout() { super.layout() guard let item = item as? SelectSizeRowItem else { return } switch item.viewType { case .legacy: self.containerView.frame = bounds case let .modern(position, _): self.containerView.frame = NSMakeRect(floorToScreenPixels(backingScaleFactor, (frame.width - item.blockWidth) / 2), item.inset.top, item.blockWidth, frame.height - item.inset.bottom - item.inset.top) self.containerView.setCorners(position.corners) } } override var firstResponder: NSResponder? { return self } override func updateColors() { guard let item = item as? SelectSizeRowItem else { return } containerView.backgroundColor = backdorColor self.backgroundColor = item.viewType.rowBackground } override func set(item: TableRowItem, animated: Bool) { super.set(item: item, animated: animated) guard let item = item as? SelectSizeRowItem else { return } switch item.viewType { case .legacy: self.containerView.setCorners([]) case let .modern(position, _): self.containerView.setCorners(position.corners) } needsLayout = true containerView.needsDisplay = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } struct SliderSelectorItem : Equatable { let value: Int32? let localizedText: String? init(value: Int32?, localizedText:String? = nil) { assert(value != nil || localizedText != nil) self.value = value self.localizedText = localizedText } }
gpl-2.0
9e50dcdf6859afeb42262a680f5f91b0
45.751269
323
0.594463
4.437485
false
false
false
false
luismatute/On-The-Map
On The Map/Utilities.swift
1
6102
// // utilities.swift // On The Map // // Created by Luis Matute on 5/26/15. // Copyright (c) 2015 Luis Matute. All rights reserved. // import UIKit class $ { let request : NSMutableURLRequest init(httpMethod: String, endpointURL: String, httpHeaders: Dictionary<String, String>?) { let url = NSURL(string: endpointURL) request = NSMutableURLRequest(URL: url!) request.HTTPMethod = httpMethod if let httpHeadersUnWrapped = httpHeaders { request.allHTTPHeaderFields = httpHeadersUnWrapped } } // MARK: - HTTP class func post(url: String) -> $ { return $(httpMethod: "POST", endpointURL: url, httpHeaders: nil) } class func get(url: String) -> $ { return $(httpMethod: "GET", endpointURL: url, httpHeaders: nil) } class func delete(url: String) -> $ { return $(httpMethod: "DELETE", endpointURL: url, httpHeaders: nil) } func headers(headers: Dictionary<String,String>) -> $ { request.allHTTPHeaderFields = headers return self } func body(httpBody: NSData) -> $ { request.HTTPBody = httpBody return self } func form(dict: Dictionary<String,String>) -> $ { let postData:NSData = prepareForm(dict) request.setValue("application/x-www-form-urlencoded;charset=utf-8", forHTTPHeaderField: "Content-Type") request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length") request.HTTPBody = postData return self } func json(jsonString:String) -> $ { let postData:NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)! request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPBody = postData return self } func cookies() -> $ { var xsrfCookie: NSHTTPCookie? = nil let sharedCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage() for cookie in sharedCookieStorage.cookies as! [NSHTTPCookie] { if cookie.name == "XSRF-TOKEN" { xsrfCookie = cookie } } if let xsrfCookie = xsrfCookie { request.addValue(xsrfCookie.value!, forHTTPHeaderField: "X-XSRF-Token") } return self } func genericValues(dict: [String:String]) -> $ { for (val,head) in dict { self.request.addValue(val, forHTTPHeaderField: head) } return self } // MARK: - Completion Handlers func parseJSONWithCompletion(removeCharsCount: Int, completion: (result: AnyObject!, response: NSURLResponse!, error: NSError!) -> ()) -> () { var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) let task = session.dataTaskWithRequest(self.request) { data, response, downloadError in if let err = downloadError { completion(result: nil, response: response, error: err) } else { var parsingError: NSError? = nil let newData = data.subdataWithRange(NSMakeRange(removeCharsCount, data.length - removeCharsCount)) let parsedResult = NSJSONSerialization.JSONObjectWithData(newData, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) as? [String : AnyObject] if let error = parsingError { completion(result: nil, response: response, error: error) } else { completion(result: parsedResult, response: response, error: nil) } } } task.resume() } func completion(completion: (data: NSData!, response: NSURLResponse!, error: NSError!) -> ()) -> () { var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) session.dataTaskWithRequest(self.request, completionHandler: completion).resume() } // MARK: - Helpers private func prepareForm(dict: Dictionary<String,String>) -> NSData { let frames:NSMutableArray = NSMutableArray() for (key, value) in dict { let encodedString:String = value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())! frames.addObject(("\(key)=\(encodedString)")) } let postData:NSData = frames.componentsJoinedByString("&").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)! return postData } class func uicolorFromHex(rgbValue:UInt32)->UIColor{ let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:1.0) } class func subtituteKeyInMethod(method: String, key: String, value: String) -> String? { if method.rangeOfString("{\(key)}") != nil { return method.stringByReplacingOccurrencesOfString("{\(key)}", withString: value) } else { return nil } } class func escapedParameters(parameters: [String : AnyObject]) -> String { var urlVars = [String]() for (key, value) in parameters { /* Make sure that it is a string value */ let stringValue = "\(value)" /* Escape it */ let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) /* Append it */ urlVars += [key + "=" + "\(escapedValue!)"] } return (!urlVars.isEmpty ? "?" : "") + join("&", urlVars) } }
mit
436239e0a01c1fbf268977cb3ad36f3d
41.381944
175
0.624385
5.030503
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/ServiceHeader.swift
1
3783
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 . Unless required by appli- -cable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Structure representing the data of a http request or response header. @author Aryslan @since v2.0 @version 1.0 */ public class ServiceHeader : KeyValue { /** Default constructor. @since v2.0.6 */ public override init() { super.init() } /** Convenience constructor. @param keyName Name of the key. @param keyData Value of the key. @since v2.0.6 */ public override init(keyName: String, keyData: String) { super.init(keyName: keyName, keyData: keyData) } /** JSON Serialization and deserialization support. */ public struct Serializer { public static func fromJSON(json : String) -> ServiceHeader { let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)! let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary return fromDictionary(dict!) } static func fromDictionary(dict : NSDictionary) -> ServiceHeader { let resultObject : ServiceHeader = ServiceHeader() if let value : AnyObject = dict.objectForKey("keyData") { if "\(value)" as NSString != "<null>" { resultObject.keyData = (value as! String) } } if let value : AnyObject = dict.objectForKey("keyName") { if "\(value)" as NSString != "<null>" { resultObject.keyName = (value as! String) } } return resultObject } public static func toJSON(object: ServiceHeader) -> String { let jsonString : NSMutableString = NSMutableString() // Start Object to JSON jsonString.appendString("{ ") // Fields. object.keyData != nil ? jsonString.appendString("\"keyData\": \"\(JSONUtil.escapeString(object.keyData!))\", ") : jsonString.appendString("\"keyData\": null, ") object.keyName != nil ? jsonString.appendString("\"keyName\": \"\(JSONUtil.escapeString(object.keyName!))\"") : jsonString.appendString("\"keyName\": null") // End Object to JSON jsonString.appendString(" }") return jsonString as String } } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
f460eea0aa384420b1abbe67979fa569
32.166667
172
0.576832
5.088829
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01671-swift-structtype-get.swift
11
1099
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse } struct c enum B { func a<T> Any) -> V, length: AnyObject) { let i<1 { protocol a { return { c: (Any) -> String { extension NSSet { } } typealias f : a { } } } print().c where A, a(T, A = { } struct c in 0.Type struct S<e<h : Int) -> <T.e = 0] { } let start = nil class A = b: b> String } case C(start: b in c = i() { } func ^([c] = T: T } enum S<S { } } b) { typealias e() -> { } func a<T) { return b: B var b(g, length: NSObject { case C(("") import Foundation var b = b()(p typealias b = Swift.Type self..c() public subscript () { typealias d { assert(h>((a!(() -> d typealias d.b { switch x }) } func compose() -> S : C(h: c: c("] } class B<d where B : Any, A<H : T -> (array: P> Any) { protocol B : B
apache-2.0
fc835f2fbfacb7d813caf5f4acaa58f6
18.280702
78
0.623294
2.754386
false
false
false
false
J3D1-WARR10R/WikiRaces
WKRKit/WKRKit/Game/WKRReadyStates.swift
2
815
// // WKRReadyStates.swift // WKRKit // // Created by Andrew Finke on 8/31/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import Foundation public struct WKRReadyStates: Codable { let players: [WKRPlayer] init(players: [WKRPlayer]) { self.players = players } public func isPlayerReady(_ player: WKRPlayer) -> Bool { guard let index = players.firstIndex(of: player) else { return false } return players[index].state == .readyForNextRound } func areAllRacePlayersReady(racePlayers: [WKRPlayer]) -> Bool { let relevantPlayers = players.filter({ racePlayers.contains($0) && $0.state != .quit }) for player in relevantPlayers where player.state != .readyForNextRound { return false } return true } }
mit
a7ab9591ef4d0380dcee277320fa1ba9
27.068966
95
0.644963
3.932367
false
false
false
false
ScoutHarris/WordPress-iOS
WordPressKit/WordPressKit/NotificationSyncServiceRemote.swift
1
6067
import Foundation // MARK: - NotificationSyncServiceRemote // public class NotificationSyncServiceRemote: ServiceRemoteWordPressComREST { // MARK: - Constants // fileprivate let defaultPageSize = 100 // MARK: - Errors // public enum SyncError: Error { case failed } /// Retrieves latest Notifications (OR collection of Notifications, whenever noteIds is present) /// /// - Parameters: /// - pageSize: Number of hashes to retrieve. /// - noteIds: Identifiers of notifications to retrieve. /// - completion: callback to be executed on completion. /// /// public func loadNotes(withPageSize pageSize: Int? = nil, noteIds: [String]? = nil, completion: @escaping ((Error?, [RemoteNotification]?) -> Void)) { let fields = "id,note_hash,type,unread,body,subject,timestamp,meta" loadNotes(withNoteIds: noteIds, fields: fields, pageSize: pageSize) { error, notes in completion(error, notes) } } /// Retrieves the Notification Hashes for the specified pageSize (OR collection of NoteID's, when present) /// /// - Parameters: /// - pageSize: Number of hashes to retrieve. /// - noteIds: Identifiers of notifications to retrieve. /// - completion: callback to be executed on completion. /// /// - Notes: The RemoteNotification Entity will only have it's ID + Hash populated /// public func loadHashes(withPageSize pageSize: Int? = nil, noteIds: [String]? = nil, completion: @escaping ((Error?, [RemoteNotification]?) -> Void)) { let fields = "id,note_hash" loadNotes(withNoteIds: noteIds, fields: fields, pageSize: pageSize) { error, notes in completion(error, notes) } } /// Updates a Notification's Read Status as specified. /// /// - Parameters: /// - notificationID: The NotificationID to Mark as Read. /// - read: The new Read Status to set. /// - completion: Closure to be executed on completion, indicating whether the OP was successful or not. /// public func updateReadStatus(_ notificationID: String, read: Bool, completion: @escaping ((Error?) -> Void)) { let path = "notifications/read" let requestUrl = self.path(forEndpoint: path, with: .version_1_1) // Note: Isn't the API wonderful? let value = read ? 9999 : -9999 let parameters = [ "counts": ["\(notificationID)": value] ] wordPressComRestApi.POST(requestUrl!, parameters: parameters as [String : AnyObject]?, success: { (response, _) in let error = self.errorFromResponse(response) completion(error) }, failure: { (error, _) in completion(error) }) } /// Updates the Last Seen Notification's Timestamp. /// /// - Parameters: /// - timestamp: Timestamp of the last seen notification. /// - completion: Closure to be executed on completion, indicating whether the OP was successful or not. /// public func updateLastSeen(_ timestamp: String, completion: @escaping ((Error?) -> Void)) { let path = "notifications/seen" let requestUrl = self.path(forEndpoint: path, with: .version_1_1) let parameters = [ "time": timestamp ] wordPressComRestApi.POST(requestUrl!, parameters: parameters as [String : AnyObject]?, success: { (response, _) in let error = self.errorFromResponse(response) completion(error) }, failure: { (error, _) in completion(error) }) } } // MARK: - Private Methods // private extension NotificationSyncServiceRemote { /// Attempts to parse the `success` field of a given response. When it's missing, or it's false, /// this method will return SyncError.failed. /// /// - Parameter response: JSON entity , as retrieved from the backend. /// /// - Returns: SyncError.failed whenever the success field is either missing, or set to false. /// func errorFromResponse(_ response: AnyObject) -> Error? { let document = response as? [String: AnyObject] let success = document?["success"] as? Bool guard success != true else { return nil } return SyncError.failed } /// Retrieves the Notification for the specified pageSize (OR collection of NoteID's, when present). /// Note that only the specified fields will be retrieved. /// /// - Parameters: /// - noteIds: Identifier for the notifications that should be loaded. /// - fields: List of comma separated fields, to be loaded. /// - pageSize: Number of notifications to load. /// - completion: Callback to be executed on completion. /// func loadNotes(withNoteIds noteIds: [String]? = nil, fields: String? = nil, pageSize: Int?, completion: @escaping ((Error?, [RemoteNotification]?) -> Void)) { let path = "notifications/" let requestUrl = self.path(forEndpoint: path, with: .version_1_1) var parameters: [String: AnyObject] = [ "number": pageSize as AnyObject? ?? defaultPageSize as AnyObject ] if let notificationIds = noteIds { parameters["ids"] = (notificationIds as NSArray).componentsJoined(by: ",") as AnyObject? } if let fields = fields { parameters["fields"] = fields as AnyObject? } wordPressComRestApi.GET(requestUrl!, parameters: parameters, success: { response, _ in let document = response as? [String: AnyObject] let notes = document?["notes"] as? [[String: AnyObject]] let parsed = notes?.flatMap { RemoteNotification(document: $0) } if let parsed = parsed { completion(nil, parsed) } else { completion(SyncError.failed, nil) } }, failure: { error, _ in completion(error, nil) }) } }
gpl-2.0
ca056e177f7db6673792b4cd9dc2c7a9
34.899408
162
0.61134
4.641928
false
false
false
false
zqqf16/SYM
SYM/UI/DsymStatusBarItem.swift
1
1978
// The MIT License (MIT) // // Copyright (c) 2017 - present zqqf16 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Cocoa import Combine class DsymToolBarButton: NSPopUpButton { private var cancellable: AnyCancellable? var dsymManager: DsymManager? { didSet { cancellable?.cancel() cancellable = dsymManager?.$dsymFiles .receive(on: DispatchQueue.main) .sink { [weak self] dsymFiles in self?.update(withDsymFiles: dsymFiles) } } } private func update(withDsymFiles dsymFiles: [String: DsymFile]) { if let crash = dsymManager?.crash, let uuid = crash.uuid, let dsym = dsymFiles[uuid] { title = dsym.name image = .symbol } else { title = NSLocalizedString("dsym_file_not_found", comment: "") image = .alert } } }
mit
f7d387881251b720e40b43cf526401f6
37.038462
81
0.667846
4.643192
false
false
false
false
citrusbyte/Healthy-Baby
M2XDemo/AppDelegate.swift
1
5079
// // AppDelegate.swift // M2XDemo // // Created by Luis Floreani on 10/28/14. // Copyright (c) 2014 citrusbyte.com. All rights reserved. // import UIKit import Parse import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let migrationKey = "migration" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. Crashlytics.startWithAPIKey("CRASHLYTICS_KEY_TOKEN"); Parse.setApplicationId("PARSE_APP_ID_TOKEN", clientKey: "PARSE_CLIENT_KEY_TOKEN") if application.respondsToSelector("registerUserNotificationSettings:") { let settings = UIUserNotificationSettings(forTypes:.Badge | .Sound | .Alert, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { application.registerForRemoteNotificationTypes(.Badge | .Sound | .Alert) } let font = UIFont(name: "Proxima Nova", size: 17) UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font!] initMigration() return true } func initMigration() { var defaults = NSUserDefaults.standardUserDefaults() let migration = defaults.valueForKey(migrationKey) as? Int if migration < 1 { migration1() } if (migration < 2) { // ... } } // since offline mode semantic changed, we set as false for old users func migration1() { var defaults = NSUserDefaults.standardUserDefaults() let device = DeviceData() device.deleteCache() defaults.setValue(false, forKey: "offline") defaults.setValue(1, forKey: migrationKey) } // @availability(iOS, introduced=3.0) // optional func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) // // @availability(iOS, introduced=3.0) // optional func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) // // @availability(iOS, introduced=3.0) // optional func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) // // @availability(iOS, introduced=4.0) // optional func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let installation = PFInstallation.currentInstallation() installation.setDeviceTokenFromData(deviceToken) installation.saveInBackgroundWithBlock(nil) println("registered for PN") } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { println("Couldn't register: \(error)") } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { println("PN received") PFPush.handlePush(userInfo) } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ce47f19e482733f1169fffc54fb1276a
40.631148
285
0.708604
5.587459
false
false
false
false
darrarski/Messages-iOS
MessagesApp/Services/DemoMessagesService.swift
1
2335
import Foundation class DemoMessagesService { var fetchDelay: TimeInterval = 3 var fetchError: Error? var sendDelay: TimeInterval = 2 var sendError: Error? fileprivate var messages: [Message] = { let bundle = Bundle(for: DemoMessagesService.self) guard let path = bundle.path(forResource: "quotes", ofType: "json") else { fatalError() } guard let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) else { fatalError() } let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) guard let jsonArray = jsonObject as? [[String]] else { fatalError() } return jsonArray.enumerated().map { (index, quote) in let uid = UUID().uuidString let text = quote[0] let author: String? = index % 2 == 0 ? quote[1] : nil return Message(uid: uid, text: text, author: author) } }() } extension DemoMessagesService: MessagesService { func fetchMessages(page: Int, perPage: Int, completion: @escaping (MessagesServiceFetchResult) -> Void) { DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + fetchDelay) { [weak self] in guard let `self` = self else { return } if let error = self.fetchError { completion(.failure(error: error)) return } let startIndex = page * perPage let endIndex = min(startIndex + perPage, self.messages.endIndex) guard perPage > 0, startIndex >= self.messages.startIndex, endIndex > startIndex else { completion(.success(messages: [])) return } completion(.success(messages: Array(self.messages[startIndex..<endIndex]))) } } func sendMessage(_ text: String, completion: @escaping (MessagesServiceSendResult) -> Void) { DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + sendDelay) { [weak self] in guard let `self` = self else { return } if let error = self.sendError { completion(.failure(error: error)) return } let message = Message(uid: UUID().uuidString, text: text, author: nil) completion(.success(message: message)) } } }
mit
a36ad596b63d9f10569d6ec2a2d600a0
39.964912
109
0.601285
4.698189
false
false
false
false
TouchInstinct/LeadKit
TIUIElements/Sources/Helpers/TableViewHeaderTransitioningHandler.swift
1
1087
import UIKit final class TableViewHeaderTransitioningHandler: NSObject, TransitioningHandler { var animator: CollapsibleViewsAnimator? private var startOffset: CGFloat = 0 private var navigationBarOffset: CGFloat = 0 private var isFirstScroll = true private var container: CollapsibleViewsContainer? init(collapsibleViewsContainer: CollapsibleViewsContainer) { self.container = collapsibleViewsContainer } public func scrollViewDidScroll(_ scrollView: UIScrollView) { guard let largeHeaderView = container?.bottomHeaderView else { return } if isFirstScroll { startOffset = max(-(scrollView.contentOffset.y), 0) navigationBarOffset = container?.fixedTopOffet ?? 0 isFirstScroll = false } let offsetY = scrollView.contentOffset.y + startOffset let alpha = min(offsetY / (largeHeaderView.frame.height + navigationBarOffset), 1) animator?.fractionComplete = alpha animator?.currentContentOffset = scrollView.contentOffset } }
apache-2.0
629ed7ed8fd68f02f8dd76a55d4fca57
30.970588
90
0.699172
5.462312
false
false
false
false
muhasturk/smart-citizen-ios
Smart Citizen/Controller/Presenter/DashboardVC.swift
1
7633
/** * Copyright (c) 2016 Mustafa Hastürk * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import Alamofire import SwiftyJSON class DashboardVC: AppVC, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var dashboardTableView: UITableView! var refreshControl: UIRefreshControl! fileprivate var requestBaseURL: String { return AppAPI.serviceDomain + AppAPI.dashboardServiceURL + String(AppReadOnlyUser.roleId) } fileprivate var reportsDict: [String: [Report]] = [:] fileprivate var firstNetworking = true // MARK: - LC override func viewDidLoad() { super.viewDidLoad() self.configureTableView() self.dashboardNetworking() } fileprivate func configureTableView() { refreshControl = UIRefreshControl() refreshControl.tintColor = UIColor.red refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl.addTarget(self, action: #selector(self.dashboardNetworking), for: UIControl.Event.valueChanged) self.dashboardTableView.addSubview(refreshControl) } // MARK: - Table Delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let index = self.reportsDict.index(self.reportsDict.startIndex, offsetBy: section) let key: String = self.reportsDict.keys[index] guard let reports = self.reportsDict[key] else { print("warning there is no '\(key)' key inside dict \(#function)") return 1 } return reports.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let index = self.reportsDict.index(self.reportsDict.startIndex, offsetBy: section) let key = self.reportsDict.keys[index] return key } func numberOfSections(in tableView: UITableView) -> Int { return self.reportsDict.keys.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "dashboardCell", for: indexPath) let sectionIndex = self.reportsDict.index(self.reportsDict.startIndex, offsetBy: (indexPath as NSIndexPath).section) let key = self.reportsDict.keys[sectionIndex] guard let reportsArray = self.reportsDict[key] else { print("warning there is no '\(key)' key inside dict \(#function)") return UITableViewCell() } cell.textLabel?.text = reportsArray[(indexPath as NSIndexPath).row].title return cell } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { let index = self.reportsDict.index(self.reportsDict.startIndex, offsetBy: section) let key = self.reportsDict.keys[index] guard let reports = self.reportsDict[key] else { return nil } let count = reports.count return "\(key) kategorisinde \(count) rapor var." } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: AppSegues.dashboardReportDetail, sender: indexPath) } var selectedReportId: Int? // MARK: Write Model fileprivate func writeDashboardDataToModel(dataJsonFromNetworking data: JSON) { self.reportsDict = [:] for (reportTypeName, reportTypeJSON): (String, JSON) in data { self.reportsDict[reportTypeName] = [] for (_, reportData): (String, JSON) in reportTypeJSON { let r = Report() r.id = reportData["id"].intValue r.title = reportData["title"].stringValue r.description = reportData["description"].stringValue r.count = reportData["count"].intValue r.category = reportData["category"].stringValue r.status = reportData["status"].stringValue r.statusId = reportData["statusId"].intValue self.reportsDict[reportTypeName]?.append(r) } } } func debugReportsDict() { for (h, rd) in self.reportsDict { print("Header: \(h)") for r in rd { super.reflectAttributes(reflectingObject: r) } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == AppSegues.dashboardReportDetail { if let detailVC = segue.destination as? ReportDetailVC { if let indexPath = sender as? IndexPath { let index = self.reportsDict.index(self.reportsDict.startIndex, offsetBy: (indexPath as NSIndexPath).section) let key = self.reportsDict.keys[index] if let reports = self.reportsDict[key] { detailVC.reportId = reports[(indexPath as NSIndexPath).row].id detailVC.report = reports[(indexPath as NSIndexPath).row] } } } } } } // MARK: - Networkng extension DashboardVC { @objc func dashboardNetworking() { if firstNetworking { self.startIndicator() } Alamofire.request(self.requestBaseURL, method: .get, parameters: nil) .responseJSON { response in if self.firstNetworking { self.stopIndicator() self.firstNetworking = false } switch response.result { case .success(let value): print(AppDebugMessages.serviceConnectionDashboardIsOk, self.requestBaseURL, separator: "\n") let json = JSON(value) let serviceCode = json["serviceCode"].intValue if serviceCode == 0 { let data = json["data"] self.dashboardNetworkingSuccessful(data) } else { let exception = json["exception"] self.dashboardNetworkingUnsuccessful(exception) } case .failure(let error): self.createAlertController(title: AppAlertMessages.networkingFailuredTitle, message: AppAlertMessages.networkingFailuredMessage, controllerStyle: .alert, actionStyle: .destructive) debugPrint(error) } } } fileprivate func dashboardNetworkingSuccessful(_ data: JSON) { self.writeDashboardDataToModel(dataJsonFromNetworking: data) self.dashboardTableView.reloadData() if self.refreshControl.isRefreshing { self.refreshControl.endRefreshing() } //self.debugReportsDict() } fileprivate func dashboardNetworkingUnsuccessful(_ exception: JSON) { let c = exception["exceptionCode"].intValue let m = exception["exceptionMessage"].stringValue let (title, message) = self.getHandledExceptionDebug(exceptionCode: c, elseMessage: m) self.createAlertController(title: title, message: message, controllerStyle: .alert, actionStyle: .default) } }
mit
36eae7f55015c7914b9922cd53e1cbac
36.970149
190
0.69641
4.61148
false
false
false
false
macteo/bezier
Bézier.playgroundbook/Contents/Chapters/Bezier.playgroundchapter/Sources/UIBezierPath.swift
2
2959
// // UIBezierPath.swift // ToneCurveEditor // // Created by Simon Gladman on 15/09/2014. // Copyright (c) 2014 Simon Gladman. All rights reserved. // // Based on Objective C code from: https://github.com/jnfisher/ios-curve-interpolation/blob/master/Curve%20Interpolation/UIBezierPath%2BInterpolation.m // From this article: http://spin.atomicobject.com/2014/05/28/ios-interpolating-points/ import Foundation import UIKit public extension UIBezierPath { public func interpolatePointsWithHermite(interpolationPoints : [CGPoint], alpha: CGFloat = 1.0/3.0, closed : Bool = false) -> [CGPoint] { var controlPoints = [CGPoint]() guard !interpolationPoints.isEmpty else { return controlPoints } self.move(to: interpolationPoints[0]) var n = interpolationPoints.count - 1 if closed { n = interpolationPoints.count } for index in 0..<n { var currentPoint = interpolationPoints[index] var nextIndex = (index + 1) % interpolationPoints.count var prevIndex = index == 0 ? interpolationPoints.count - 1 : index - 1 var previousPoint = interpolationPoints[prevIndex] var nextPoint = interpolationPoints[nextIndex] let endPoint = nextPoint var mx : CGFloat var my : CGFloat if closed || index > 0 { mx = (nextPoint.x - previousPoint.x) / 2.0 my = (nextPoint.y - previousPoint.y) / 2.0 } else { mx = (nextPoint.x - currentPoint.x) / 2.0 my = (nextPoint.y - currentPoint.y) / 2.0 } let controlPoint1 = CGPoint(x: currentPoint.x + mx * alpha, y: currentPoint.y + my * alpha) currentPoint = interpolationPoints[nextIndex] nextIndex = (nextIndex + 1) % interpolationPoints.count prevIndex = index previousPoint = interpolationPoints[prevIndex] nextPoint = interpolationPoints[nextIndex] if closed || index < n - 1 { mx = (nextPoint.x - previousPoint.x) / 2.0 my = (nextPoint.y - previousPoint.y) / 2.0 } else { mx = (currentPoint.x - previousPoint.x) / 2.0 my = (currentPoint.y - previousPoint.y) / 2.0 } let controlPoint2 = CGPoint(x: currentPoint.x - mx * alpha, y: currentPoint.y - my * alpha) self.addCurve(to: endPoint, controlPoint1: controlPoint1, controlPoint2: controlPoint2) controlPoints.append(controlPoint1) controlPoints.append(controlPoint2) } if closed { self.close() } return controlPoints } }
mit
bce10b93ea3b83274823f765d631a7b9
34.22619
151
0.553903
4.726837
false
false
false
false